@vite-hub/env 0.0.0 → 0.0.2

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 CHANGED
@@ -1,3 +1,105 @@
1
1
  # @vite-hub/env
2
2
 
3
- Reserved package name for ViteHub.
3
+ <p>
4
+ <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/badge/ViteHub-vitehub.dev-646cff?style=flat-square"></a>
5
+ <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-3178c6?style=flat-square">
6
+ <img alt="Vite" src="https://img.shields.io/badge/Vite-public%20env-646cff?style=flat-square">
7
+ </p>
8
+
9
+ `@vite-hub/env` declares environment values once, then generates typed public and server env access.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ pnpm add @vite-hub/env
15
+ ```
16
+
17
+ ## Minimal API
18
+
19
+ ```ts
20
+ // vite.config.ts
21
+ import { env, hubEnv } from "@vite-hub/env/vite"
22
+ import { defineConfig } from "vite"
23
+
24
+ export default defineConfig({
25
+ plugins: [hubEnv({ prefix: "VITEHUB_" })],
26
+ env: {
27
+ public: {
28
+ appName: env({ default: "ViteHub App", mode: "build" }),
29
+ },
30
+ server: {
31
+ airtableToken: env({ secret: true }),
32
+ },
33
+ },
34
+ })
35
+ ```
36
+
37
+ ```ts
38
+ // app/env.ts
39
+ import { publicEnv } from "#vitehub/env/public"
40
+
41
+ export const appName = publicEnv.appName
42
+ ```
43
+
44
+ ```ts
45
+ // server/sync.ts
46
+ import { useServerEnv } from "#vitehub/env/server"
47
+
48
+ export async function sync(event: unknown) {
49
+ const { airtableToken } = useServerEnv(event)
50
+
51
+ await fetch("https://api.airtable.com/v0/app/table", {
52
+ headers: { Authorization: `Bearer ${airtableToken.unseal()}` },
53
+ })
54
+ }
55
+ ```
56
+
57
+ ## Structured errors
58
+
59
+ ViteHub-owned Env resolution failures use the shared `ViteHubError` contract with Env-specific codes. Custom source resolvers keep application-owned errors unchanged, so callers can preserve their own error contract without translating it through ViteHub.
60
+
61
+ ```ts
62
+ import { getViteHubErrorShape } from "@vite-hub/runtime"
63
+
64
+ try {
65
+ await resolveVaultEnv()
66
+ }
67
+ catch (error) {
68
+ if (getViteHubErrorShape(error)?.code === "ENV_SOURCE_FAILED") {
69
+ console.error("Env source failed")
70
+ }
71
+ throw error
72
+ }
73
+ ```
74
+
75
+ Each `EnvErrorCode` owns a fixed public message and a bounded details shape. Source details use stable identifiers such as `git:branch`, `package.json`, `env`, or `custom`; raw variable names, package paths, and provider diagnostics stay behind `cause`, which `toJSON()` omits. Cancellation and existing `ViteHubError` instances pass through unchanged. Invalid `env()` calls remain `TypeError`, and `parseSchema()` keeps the schema library's ordinary error boundary.
76
+
77
+ ## Vite Integration
78
+
79
+ Use `hubEnv()` in Vite to resolve public/build env, generate `#vitehub/env/public` and `#vitehub/env/server`, and keep environment declarations close to the app config. Runtime secrets are read from the host environment at request time and are wrapped in `SecretEnv` until explicitly unsealed.
80
+
81
+ `hubEnv()` writes generated env runtime modules to `.vitehub/env/` and generated env types to `.vitehub/types/env.d.ts`. Add `.vitehub/types/**/*.d.ts` to your `tsconfig.json` include list when TypeScript should see app-specific Public Env and Server Env fields.
82
+
83
+ For hosts that do not consume Vite plugin aliases directly, compose the generated modules explicitly:
84
+
85
+ ```ts
86
+ import { createEnvImportAliases, createEnvTypeScriptPaths, hubEnv } from "@vite-hub/env/vite"
87
+
88
+ export default {
89
+ nitro: {
90
+ alias: createEnvImportAliases(),
91
+ },
92
+ typescript: {
93
+ tsConfig: {
94
+ compilerOptions: {
95
+ paths: createEnvTypeScriptPaths({ relativeTo: ".nuxt" }),
96
+ },
97
+ },
98
+ },
99
+ vite: {
100
+ plugins: [hubEnv()],
101
+ },
102
+ }
103
+ ```
104
+
105
+ Learn more at [vitehub.dev](https://vitehub.dev).
@@ -0,0 +1,23 @@
1
+ import { c as EnvSource, d as EnvVariableDeclaration, f as EnvVariableOptions, u as EnvSourceResolver } from "./types-FcnPKias.js";
2
+
3
+ //#region src/core/declarations.d.ts
4
+ interface EnvNamespace {
5
+ (options?: EnvVariableOptions): EnvVariableDeclaration;
6
+ buildTimestamp: () => EnvSource;
7
+ custom: (label: string, resolver: EnvSourceResolver) => EnvSource;
8
+ gitBranch: () => EnvSource;
9
+ gitCommit: (options?: {
10
+ short?: boolean;
11
+ }) => EnvSource;
12
+ gitRef: () => EnvSource;
13
+ gitSha: (options?: {
14
+ short?: boolean;
15
+ }) => EnvSource;
16
+ gitTag: () => EnvSource;
17
+ packageJson: (path: string) => EnvSource;
18
+ source: (name: string | string[]) => EnvSource;
19
+ variable: (options?: EnvVariableOptions) => EnvVariableDeclaration;
20
+ }
21
+ declare const env: EnvNamespace;
22
+ //#endregion
23
+ export { env as t };
@@ -0,0 +1,144 @@
1
+ //#region src/core/declarations.ts
2
+ const defaultStringSchema = {
3
+ __vitehubDefaultRuntimeSchema: getDefaultStringSchemaToken(),
4
+ safeParse(input) {
5
+ return typeof input === "string" ? {
6
+ data: input,
7
+ success: true
8
+ } : {
9
+ error: /* @__PURE__ */ new Error("Expected string"),
10
+ success: false
11
+ };
12
+ }
13
+ };
14
+ const defaultStringSchemaProperty = "__vitehubDefaultRuntimeSchema";
15
+ const defaultStringSchemaToken = defaultStringSchema.__vitehubDefaultRuntimeSchema;
16
+ const defaultStringSchemas = /* @__PURE__ */ new WeakMap();
17
+ const defaultStringSchemaParsers = /* @__PURE__ */ new WeakSet();
18
+ defaultStringSchemaParsers.add(defaultStringSchema.safeParse);
19
+ function source(name) {
20
+ const names = Array.isArray(name) ? name : [name];
21
+ if (!names.length || names.some((value) => typeof value !== "string" || !value.trim())) throw new TypeError("env.source() requires one or more non-empty env variable names.");
22
+ const normalized = names.map((value) => value.trim());
23
+ return {
24
+ kind: "env",
25
+ label: `env:${normalized.join("|")}`,
26
+ name: normalized[0],
27
+ ...normalized.length > 1 ? { names: normalized } : {},
28
+ serializable: true
29
+ };
30
+ }
31
+ function custom(label, resolver) {
32
+ return {
33
+ kind: "custom",
34
+ label,
35
+ resolver,
36
+ serializable: false
37
+ };
38
+ }
39
+ function gitBranch() {
40
+ return {
41
+ kind: "git-branch",
42
+ label: "git:branch",
43
+ serializable: true
44
+ };
45
+ }
46
+ function gitCommit(options = {}) {
47
+ return {
48
+ kind: "git-commit",
49
+ label: "git:commit",
50
+ serializable: true,
51
+ short: options.short
52
+ };
53
+ }
54
+ function gitRef() {
55
+ return {
56
+ kind: "git-ref",
57
+ label: "git:ref",
58
+ serializable: true
59
+ };
60
+ }
61
+ function gitSha(options = {}) {
62
+ return {
63
+ kind: "git-sha",
64
+ label: "git:sha",
65
+ serializable: true,
66
+ short: options.short
67
+ };
68
+ }
69
+ function gitTag() {
70
+ return {
71
+ kind: "git-tag",
72
+ label: "git:tag",
73
+ serializable: true
74
+ };
75
+ }
76
+ function buildTimestamp() {
77
+ return {
78
+ kind: "build-timestamp",
79
+ label: "build:timestamp",
80
+ serializable: true
81
+ };
82
+ }
83
+ function packageJson(path) {
84
+ return {
85
+ kind: "package-json",
86
+ label: `package.json:${path}`,
87
+ path,
88
+ serializable: true
89
+ };
90
+ }
91
+ function variable(options = {}) {
92
+ if (typeof options !== "object" || options === null || Array.isArray(options)) throw new TypeError("env() only accepts a single options object.");
93
+ if (options.optional && typeof options.required !== "undefined") throw new TypeError("env() cannot use both optional and required.");
94
+ const required = options.optional ? false : options.required ?? true;
95
+ const source = typeof options.source === "function" ? custom("custom", options.source) : options.source;
96
+ const schema = options.schema ?? defaultStringSchema;
97
+ const declaration = {
98
+ default: options.default,
99
+ kind: "env-variable",
100
+ mode: options.mode ?? "runtime",
101
+ required,
102
+ schema,
103
+ secret: options.secret ?? false,
104
+ source,
105
+ type: options.type
106
+ };
107
+ if (typeof options.schema === "undefined") {
108
+ defaultStringSchemas.set(declaration, defaultStringSchema);
109
+ Object.defineProperty(declaration, defaultStringSchemaProperty, {
110
+ enumerable: true,
111
+ value: defaultStringSchemaToken
112
+ });
113
+ }
114
+ return declaration;
115
+ }
116
+ const env = Object.assign(variable, {
117
+ buildTimestamp,
118
+ custom,
119
+ gitBranch,
120
+ gitCommit,
121
+ gitRef,
122
+ gitSha,
123
+ gitTag,
124
+ packageJson,
125
+ source,
126
+ variable
127
+ });
128
+ function isDefaultStringEnvVariable(declaration) {
129
+ return defaultStringSchemas.get(declaration) === declaration.schema || declaration[defaultStringSchemaProperty] === defaultStringSchemaToken && typeof declaration.schema === "object" && declaration.schema !== null && declaration.schema[defaultStringSchemaProperty] === defaultStringSchemaToken && hasOnlyDefaultStringSchemaKeys(declaration.schema);
130
+ }
131
+ function getDefaultStringSchemaToken() {
132
+ const tokenKey = Symbol.for("vitehub.env.defaultRuntimeSchemaToken");
133
+ const globalScope = globalThis;
134
+ globalScope[tokenKey] ??= `string:${Math.random().toString(36).slice(2)}`;
135
+ return globalScope[tokenKey];
136
+ }
137
+ function hasOnlyDefaultStringSchemaKeys(schema) {
138
+ if ("~standard" in schema || "parse" in schema) return false;
139
+ const keys = Reflect.ownKeys(schema);
140
+ const safeParse = Object.getOwnPropertyDescriptor(schema, "safeParse");
141
+ return keys.length === 2 && keys.includes(defaultStringSchemaProperty) && keys.includes("safeParse") && typeof safeParse?.value === "function" && defaultStringSchemaParsers.has(safeParse.value);
142
+ }
143
+ //#endregion
144
+ export { env as n, isDefaultStringEnvVariable as r, defaultStringSchema as t };
@@ -0,0 +1,112 @@
1
+ import { ViteHubError } from "@vite-hub/runtime";
2
+ //#region src/core/errors.ts
3
+ const envErrorMessages = {
4
+ ENV_DECLARATION_INVALID: "[vitehub] Env declaration is invalid.",
5
+ ENV_REQUIRED_MISSING: "[vitehub] Required Env value is missing.",
6
+ ENV_RUNTIME_VALUE_INVALID: "[vitehub] Runtime Env value is invalid.",
7
+ ENV_SOURCE_FAILED: "[vitehub] Env source resolution failed."
8
+ };
9
+ const envSourceIdentifierSet = new Set([
10
+ "custom",
11
+ "env",
12
+ "git:branch",
13
+ "git:commit",
14
+ "git:ref",
15
+ "git:sha",
16
+ "git:tag",
17
+ "package.json"
18
+ ]);
19
+ function invalidOptions() {
20
+ throw new TypeError("[vitehub] Invalid Env error options.");
21
+ }
22
+ function own(value, key) {
23
+ if (typeof value !== "object" || value === null || Array.isArray(value)) invalidOptions();
24
+ try {
25
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
26
+ if (descriptor === void 0) return void 0;
27
+ if (!("value" in descriptor)) invalidOptions();
28
+ return descriptor.value;
29
+ } catch {
30
+ invalidOptions();
31
+ }
32
+ }
33
+ function createEnvError(options) {
34
+ const code = own(options, "code");
35
+ if (typeof code !== "string" || !Object.hasOwn(envErrorMessages, code)) invalidOptions();
36
+ const cause = own(options, "cause");
37
+ const details = normalizeDetails(code, own(options, "details"));
38
+ return new ViteHubError(code, envErrorMessages[code], {
39
+ ...cause === void 0 ? {} : { cause },
40
+ ...details === void 0 ? {} : { details }
41
+ });
42
+ }
43
+ function invalidEnvDeclaration(path, diagnostic) {
44
+ return createEnvError({
45
+ cause: new TypeError(diagnostic),
46
+ code: "ENV_DECLARATION_INVALID",
47
+ details: optionalPath(path)
48
+ });
49
+ }
50
+ function missingRequiredEnv(source, diagnostic, path) {
51
+ const pathDetails = optionalPath(path);
52
+ return createEnvError({
53
+ cause: new Error(diagnostic),
54
+ code: "ENV_REQUIRED_MISSING",
55
+ details: {
56
+ ...pathDetails,
57
+ source: publicSourceIdentifier(source)
58
+ }
59
+ });
60
+ }
61
+ function invalidRuntimeEnvValue(source, diagnostic) {
62
+ return createEnvError({
63
+ cause: new TypeError(diagnostic),
64
+ code: "ENV_RUNTIME_VALUE_INVALID",
65
+ details: { source: publicSourceIdentifier(source) }
66
+ });
67
+ }
68
+ function envSourceFailed(source, cause) {
69
+ return createEnvError({
70
+ cause,
71
+ code: "ENV_SOURCE_FAILED",
72
+ details: { source: publicSourceIdentifier(source) }
73
+ });
74
+ }
75
+ function isAbortError(value) {
76
+ if ((typeof value !== "object" || value === null) && typeof value !== "function") return false;
77
+ try {
78
+ return value.name === "AbortError";
79
+ } catch {
80
+ return false;
81
+ }
82
+ }
83
+ function publicSourceIdentifier(source) {
84
+ if (envSourceIdentifierSet.has(source)) return source;
85
+ if (source.startsWith("env:")) return "env";
86
+ if (source.startsWith("package.json:")) return "package.json";
87
+ return "custom";
88
+ }
89
+ function normalizeDetails(code, details) {
90
+ if (details === void 0) return void 0;
91
+ if (typeof details !== "object" || details === null || Array.isArray(details)) invalidOptions();
92
+ const normalized = {};
93
+ if (code === "ENV_DECLARATION_INVALID" || code === "ENV_REQUIRED_MISSING") {
94
+ const path = safePath(own(details, "path"));
95
+ if (path) normalized.path = path;
96
+ }
97
+ if (code !== "ENV_DECLARATION_INVALID") {
98
+ const source = own(details, "source");
99
+ if (envSourceIdentifierSet.has(source)) normalized.source = source;
100
+ }
101
+ return Object.keys(normalized).length ? normalized : void 0;
102
+ }
103
+ function optionalPath(path) {
104
+ const normalized = safePath(path);
105
+ return normalized ? { path: normalized } : {};
106
+ }
107
+ function safePath(path) {
108
+ if (typeof path !== "string" || path.length > 256) return void 0;
109
+ return /^(?:env|runtime)(?:\.[A-Za-z_$][A-Za-z0-9_$-]{0,63}){0,8}$/.test(path) ? path : void 0;
110
+ }
111
+ //#endregion
112
+ export { missingRequiredEnv as a, isAbortError as i, invalidEnvDeclaration as n, invalidRuntimeEnvValue as r, envSourceFailed as t };
@@ -0,0 +1,36 @@
1
+ import { a as EnvMode, c as EnvSource, d as EnvVariableDeclaration, f as EnvVariableOptions, g as ServerEnv, h as PublicEnv, i as EnvIntegrationOptions, l as EnvSourceContext, m as EnvViteUserConfig, n as EnvDiagnosticEntry, o as EnvRuntimeConfigOptions, p as EnvViteConfigOptions, r as EnvDiagnostics, s as EnvRuntimeRegistry, t as EnvConfigOptions, u as EnvSourceResolver } from "./types-FcnPKias.js";
2
+ import { t as env } from "./declarations-BIBfEwer.js";
3
+ import { openWorkflowEnv } from "./presets.js";
4
+ import { StandardSchemaV1, parseSchema } from "./schema.js";
5
+ import { SecretEnv } from "./secret.js";
6
+ import { resolveServerEnv } from "./server.js";
7
+ import { ViteHubError } from "@vite-hub/runtime";
8
+
9
+ //#region src/core/errors.d.ts
10
+ declare const envErrorMessages: {
11
+ readonly ENV_DECLARATION_INVALID: "[vitehub] Env declaration is invalid.";
12
+ readonly ENV_REQUIRED_MISSING: "[vitehub] Required Env value is missing.";
13
+ readonly ENV_RUNTIME_VALUE_INVALID: "[vitehub] Runtime Env value is invalid.";
14
+ readonly ENV_SOURCE_FAILED: "[vitehub] Env source resolution failed.";
15
+ };
16
+ declare const envSourceIdentifiers: readonly ["custom", "env", "git:branch", "git:commit", "git:ref", "git:sha", "git:tag", "package.json"];
17
+ type EnvErrorCode = keyof typeof envErrorMessages;
18
+ type EnvSourceIdentifier = typeof envSourceIdentifiers[number];
19
+ interface EnvErrorDetailsByCode {
20
+ ENV_DECLARATION_INVALID: {
21
+ path?: string;
22
+ };
23
+ ENV_REQUIRED_MISSING: {
24
+ path?: string;
25
+ source?: EnvSourceIdentifier;
26
+ };
27
+ ENV_RUNTIME_VALUE_INVALID: {
28
+ source?: EnvSourceIdentifier;
29
+ };
30
+ ENV_SOURCE_FAILED: {
31
+ source?: EnvSourceIdentifier;
32
+ };
33
+ }
34
+ type EnvErrorDetails<TCode extends EnvErrorCode = EnvErrorCode> = EnvErrorDetailsByCode[TCode];
35
+ //#endregion
36
+ export { type EnvConfigOptions, type EnvDiagnosticEntry, type EnvDiagnostics, type EnvErrorCode, type EnvErrorDetails, type EnvIntegrationOptions, type EnvMode, type EnvRuntimeConfigOptions, type EnvRuntimeRegistry, type EnvSource, type EnvSourceContext, type EnvSourceIdentifier, type EnvSourceResolver, type EnvVariableDeclaration, type EnvVariableOptions, type EnvViteConfigOptions, type EnvViteUserConfig, type PublicEnv, SecretEnv, type ServerEnv, type StandardSchemaV1, env, openWorkflowEnv, parseSchema, resolveServerEnv };
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ import { n as env } from "./declarations-Cy5XamUA.js";
2
+ import { openWorkflowEnv } from "./presets.js";
3
+ import { parseSchema } from "./schema.js";
4
+ import { SecretEnv } from "./secret.js";
5
+ import { t as resolveServerEnv } from "./server-B2Dp8Nc0.js";
6
+ export { SecretEnv, env, openWorkflowEnv, parseSchema, resolveServerEnv };
@@ -0,0 +1,11 @@
1
+ import { o as EnvRuntimeConfigOptions } from "./types-FcnPKias.js";
2
+
3
+ //#region src/presets.d.ts
4
+ interface OpenWorkflowEnvOptions {
5
+ namespaceId?: string;
6
+ schema?: string;
7
+ workerConcurrency?: string;
8
+ }
9
+ declare function openWorkflowEnv(options?: OpenWorkflowEnvOptions): EnvRuntimeConfigOptions;
10
+ //#endregion
11
+ export { OpenWorkflowEnvOptions, openWorkflowEnv };
@@ -0,0 +1,25 @@
1
+ import { n as env } from "./declarations-Cy5XamUA.js";
2
+ //#region src/presets.ts
3
+ function openWorkflowEnv(options = {}) {
4
+ return {
5
+ namespaceId: env({
6
+ default: options.namespaceId || "production",
7
+ source: env.source("OPENWORKFLOW_NAMESPACE_ID")
8
+ }),
9
+ postgresUrl: env({
10
+ optional: true,
11
+ secret: true,
12
+ source: env.source(["OPENWORKFLOW_POSTGRES_URL", "DATABASE_URL"])
13
+ }),
14
+ schema: env({
15
+ default: options.schema || "openworkflow",
16
+ source: env.source("OPENWORKFLOW_SCHEMA")
17
+ }),
18
+ workerConcurrency: env({
19
+ default: options.workerConcurrency || "10",
20
+ source: env.source("OPENWORKFLOW_WORKER_CONCURRENCY")
21
+ })
22
+ };
23
+ }
24
+ //#endregion
25
+ export { openWorkflowEnv };
@@ -0,0 +1,16 @@
1
+ //#region src/schema.d.ts
2
+ interface StandardSchemaResultSuccess<T = unknown> {
3
+ issues?: undefined;
4
+ value: T;
5
+ }
6
+ interface StandardSchemaResultFailure {
7
+ issues: readonly unknown[];
8
+ }
9
+ interface StandardSchemaV1<T = unknown> {
10
+ "~standard": {
11
+ validate: (input: unknown) => StandardSchemaResultSuccess<T> | StandardSchemaResultFailure | Promise<StandardSchemaResultSuccess<T> | StandardSchemaResultFailure>;
12
+ };
13
+ }
14
+ declare function parseSchema(schema: unknown, value: unknown, label: string): unknown;
15
+ //#endregion
16
+ export { StandardSchemaResultFailure, StandardSchemaResultSuccess, StandardSchemaV1, parseSchema };
package/dist/schema.js ADDED
@@ -0,0 +1,37 @@
1
+ //#region src/schema.ts
2
+ function parseSchema(schema, value, label) {
3
+ if (isStandardSchema(schema)) {
4
+ const result = schema["~standard"].validate(value);
5
+ if (isPromiseLike(result)) throw new Error(`[vitehub] ${label} uses an async schema. Env validation currently requires sync schemas.`);
6
+ if ("issues" in result && result.issues && result.issues.length > 0) throw new Error(`[vitehub] Invalid ${label}: ${formatIssues(result.issues)}`);
7
+ if (!("value" in result)) throw new Error(`[vitehub] Invalid ${label}: ${formatIssues(result.issues)}`);
8
+ return result.value;
9
+ }
10
+ if (isZodLike(schema) && typeof schema.safeParse === "function") {
11
+ const result = schema.safeParse(value);
12
+ if (!result.success) throw new Error(`[vitehub] Invalid ${label}: ${formatIssues(result.error)}`);
13
+ return result.data;
14
+ }
15
+ if (isZodLike(schema) && typeof schema.parse === "function") try {
16
+ return schema.parse(value);
17
+ } catch (error) {
18
+ throw new Error(`[vitehub] Invalid ${label}: ${formatIssues(error)}`);
19
+ }
20
+ return value;
21
+ }
22
+ function isPromiseLike(value) {
23
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
24
+ }
25
+ function isStandardSchema(schema) {
26
+ return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"]?.validate === "function";
27
+ }
28
+ function isZodLike(schema) {
29
+ return typeof schema === "object" && schema !== null;
30
+ }
31
+ function formatIssues(issues) {
32
+ if (Array.isArray(issues)) return issues.map((issue) => typeof issue === "string" ? issue : JSON.stringify(issue)).join("; ");
33
+ if (issues instanceof Error) return issues.message;
34
+ return typeof issues === "string" ? issues : JSON.stringify(issues);
35
+ }
36
+ //#endregion
37
+ export { parseSchema };
@@ -0,0 +1,11 @@
1
+ //#region src/secret.d.ts
2
+ declare class SecretEnv<T = string> {
3
+ #private;
4
+ constructor(value: T);
5
+ unseal(): T;
6
+ toString(): string;
7
+ toJSON(): string;
8
+ [Symbol.toPrimitive](): string;
9
+ }
10
+ //#endregion
11
+ export { SecretEnv };
package/dist/secret.js ADDED
@@ -0,0 +1,26 @@
1
+ //#region src/secret.ts
2
+ const redactedSecret = "<redacted>";
3
+ var SecretEnv = class {
4
+ #value;
5
+ constructor(value) {
6
+ this.#value = value;
7
+ Object.freeze(this);
8
+ }
9
+ unseal() {
10
+ return this.#value;
11
+ }
12
+ toString() {
13
+ return redactedSecret;
14
+ }
15
+ toJSON() {
16
+ return redactedSecret;
17
+ }
18
+ [Symbol.toPrimitive]() {
19
+ return redactedSecret;
20
+ }
21
+ };
22
+ Object.defineProperty(SecretEnv.prototype, Symbol.for("nodejs.util.inspect.custom"), { value() {
23
+ return redactedSecret;
24
+ } });
25
+ //#endregion
26
+ export { SecretEnv };
@@ -0,0 +1,59 @@
1
+ import { SecretEnv } from "./secret.js";
2
+ import { a as missingRequiredEnv, r as invalidRuntimeEnvValue } from "./errors-RUmAFDJn.js";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
4
+ const activeEnvStorage = new AsyncLocalStorage();
5
+ function getActiveCloudflareEnv() {
6
+ const scoped = activeEnvStorage.getStore();
7
+ return scoped ? scoped.env : globalThis.__env__;
8
+ }
9
+ function getCloudflareEnv(event) {
10
+ const target = event;
11
+ return target?.env || target?.context?.cloudflare?.env || target?.context?._platform?.cloudflare?.env || target?.req?.runtime?.cloudflare?.env || getActiveCloudflareEnv();
12
+ }
13
+ //#endregion
14
+ //#region src/server.ts
15
+ function isRecord(value) {
16
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17
+ }
18
+ function isRuntimeLiteralEntry(value) {
19
+ return isRecord(value) && value.kind === "literal";
20
+ }
21
+ function isRuntimeEnvEntry(value) {
22
+ return isRecord(value) && isRecord(value.source) && typeof value.source.name === "string" && typeof value.required === "boolean" && typeof value.secret === "boolean";
23
+ }
24
+ function processEnv() {
25
+ return typeof process === "object" && process && process.env ? process.env : {};
26
+ }
27
+ function runtimeEnv(event) {
28
+ return {
29
+ ...processEnv(),
30
+ ...getCloudflareEnv(event)
31
+ };
32
+ }
33
+ function readRuntimeSource(entry, env) {
34
+ for (const name of entry.source.names || [entry.source.name]) if (Object.hasOwn(env, name) && typeof env[name] !== "undefined") return {
35
+ found: true,
36
+ value: env[name]
37
+ };
38
+ return { found: false };
39
+ }
40
+ function resolveRegistryValue(value, env) {
41
+ if (isRuntimeLiteralEntry(value)) return value.value;
42
+ if (isRuntimeEnvEntry(value)) {
43
+ const source = readRuntimeSource(value, env);
44
+ const resolved = source.found ? source.value : value.default;
45
+ if (typeof resolved === "undefined") {
46
+ if (value.required) throw missingRequiredEnv(value.source.label, `Missing Runtime Env from ${value.source.label}.`);
47
+ return;
48
+ }
49
+ if (typeof resolved !== "string") throw invalidRuntimeEnvValue(value.source.label, `Runtime Env from ${value.source.label} must resolve to a string.`);
50
+ return value.secret ? new SecretEnv(resolved) : resolved;
51
+ }
52
+ if (!isRecord(value)) return;
53
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, resolveRegistryValue(child, env)]));
54
+ }
55
+ function resolveServerEnv(registry, event) {
56
+ return resolveRegistryValue(registry, runtimeEnv(event));
57
+ }
58
+ //#endregion
59
+ export { resolveServerEnv as t };
@@ -0,0 +1,6 @@
1
+ import { s as EnvRuntimeRegistry } from "./types-FcnPKias.js";
2
+
3
+ //#region src/server.d.ts
4
+ declare function resolveServerEnv<TServerEnv extends Record<string, unknown> = Record<string, unknown>>(registry: EnvRuntimeRegistry, event?: unknown): TServerEnv;
5
+ //#endregion
6
+ export { resolveServerEnv };
package/dist/server.js ADDED
@@ -0,0 +1,3 @@
1
+ import "./secret.js";
2
+ import { t as resolveServerEnv } from "./server-B2Dp8Nc0.js";
3
+ export { resolveServerEnv };