12factor-env 0.1.0 → 1.0.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/LICENSE CHANGED
@@ -1,6 +1,8 @@
1
1
  The MIT License (MIT)
2
2
 
3
- Copyright (c) 2020 Dan Lynch <pyramation@gmail.com>
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Constructive <developers@constructive.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
4
6
 
5
7
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
8
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,128 +1,233 @@
1
- # 12factor
1
+ # 12factor-env
2
2
 
3
- Secrets meant for usage with docker-based applications.
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
4
6
 
5
- Uses envalid under the hood, but considers secrets for true integration of 12factor apps.
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml">
9
+ <img height="20" src="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/constructive/blob/main/LICENSE">
12
+ <img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/>
13
+ </a>
14
+ <a href="https://www.npmjs.com/package/12factor-env">
15
+ <img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=packages%2F12factor-env%2Fpackage.json"/>
16
+ </a>
17
+ </p>
6
18
 
7
- # default secret path
19
+ > Environment variable validation with secret file support for 12-factor apps
8
20
 
9
- defaults to `/run/secrets/<secret_name>`
21
+ A TypeScript library for validating environment variables with built-in support for Docker/Kubernetes secret files. Built on top of [envalid](https://github.com/af/envalid) with additional features for reading secrets from files.
10
22
 
11
- You must set `process.env.ENV_SECRETS_PATH` to change this, for example,
23
+ ## Installation
12
24
 
13
- ```js
14
- process.env.ENV_SECRETS_PATH='/var/run/your/secrets/folder/';
25
+ ```bash
26
+ npm install 12factor-env
15
27
  ```
16
28
 
17
- or
29
+ ## Usage
18
30
 
19
- ```sh
20
- ENV_SECRETS_PATH='/var/run/your/secrets/folder/' node yourapp.js
21
- ```
22
-
23
- # Recommended Usage
31
+ ```ts
32
+ import { env, str, num, bool, port, email, host } from '12factor-env';
24
33
 
25
- Using `_FILE` convention, include `SECRET_NAME_FILE` as a config var
26
-
27
- ```js
28
- const myEnv = env(
29
- process.env
34
+ const config = env(
35
+ process.env,
30
36
  {
31
- // put all secrets here
32
- SECRET_NAME: str()
37
+ // Required environment variables
38
+ DATABASE_URL: str(),
39
+ API_KEY: str()
33
40
  },
34
41
  {
35
- // all config vars here
36
- PORT: port({ default: 10101 })
42
+ // Optional environment variables with defaults
43
+ PORT: port({ default: 3000 }),
44
+ DEBUG: bool({ default: false }),
45
+ LOG_LEVEL: str({ default: 'info' })
37
46
  }
38
47
  );
48
+
49
+ console.log(config.DATABASE_URL); // Validated string
50
+ console.log(config.PORT); // Validated number
39
51
  ```
40
52
 
41
- If you haven't specified the value, you can enter it inside of a `secret()` call
53
+ ## Secret File Support
42
54
 
55
+ This library supports reading secrets from files, which is useful for Docker secrets and Kubernetes secrets that are mounted as files.
43
56
 
44
- ```js
45
- const myEnv = env(
46
- process.env
47
- {
48
- // put all secrets here
49
- SECRET_NAME: secret('secret.txt') // will look in /run/secrets/secret.txt
50
- },
51
- {
52
- // all config vars here
53
- PORT: port({ default: 10101 })
54
- }
55
- );
57
+ ### Direct Secret Files
58
+
59
+ Secrets can be read from `/run/secrets/` (or a custom path via `ENV_SECRETS_PATH`):
60
+
61
+ ```ts
62
+ import { env, str } from '12factor-env';
63
+
64
+ // If /run/secrets/DATABASE_PASSWORD exists, it will be read automatically
65
+ const config = env(process.env, {
66
+ DATABASE_PASSWORD: str()
67
+ });
56
68
  ```
57
69
 
58
- # Examples
70
+ ### _FILE Suffix Pattern
59
71
 
60
- ## basic usage with envalid
72
+ You can also use the `_FILE` suffix pattern commonly used with Docker:
61
73
 
62
- if you use the `_FILE` standard:
74
+ ```bash
75
+ # Set the path to the secret file
76
+ export DATABASE_PASSWORD_FILE=/run/secrets/db-password
77
+ ```
63
78
 
64
- ```js
65
- const myEnv = cleanEnv(
66
- process.env,
67
- {
68
- PORT: port({ default: 10101 }),
69
- GITHUB_TOKEN: secret(process.env.GITHUB_TOKEN_FILE)
70
- });
79
+ ```ts
80
+ import { env, str } from '12factor-env';
81
+
82
+ // Will read from the file specified in DATABASE_PASSWORD_FILE
83
+ const config = env(process.env, {
84
+ DATABASE_PASSWORD: str()
85
+ });
71
86
  ```
72
87
 
73
- or you can specify the name of the secret file as it is stored
88
+ ### Custom Secrets Path
74
89
 
75
- ```js
76
- const myEnv = cleanEnv(
77
- process.env,
78
- {
79
- PORT: port({ default: 10101 }),
80
- GITHUB_TOKEN: secret('github_token.txt')
81
- });
90
+ Set `ENV_SECRETS_PATH` to change the default secrets directory:
91
+
92
+ ```bash
93
+ export ENV_SECRETS_PATH=/custom/secrets/path
82
94
  ```
83
95
 
84
- Better yet, just ensure that you use the `env` shortcut and it handles it for you
96
+ ## Validators
85
97
 
86
- ```js
87
- const myEnv = env(
88
- {
89
- GITHUB_TOKEN_FILE: process.env.GITHUB_TOKEN_FILE
90
- },
91
- {
92
- GITHUB_TOKEN: str()
93
- },
94
- {
95
- PORT: port({ default: 10101 })
96
- }
97
- );
98
+ All validators from [envalid](https://github.com/af/envalid) are re-exported:
99
+
100
+ | Validator | Description |
101
+ |-----------|-------------|
102
+ | `str()` | String value |
103
+ | `bool()` | Boolean (`true`, `false`, `1`, `0`) |
104
+ | `num()` | Number |
105
+ | `port()` | Port number (1-65535) |
106
+ | `host()` | Hostname or IP address |
107
+ | `url()` | Valid URL |
108
+ | `email()` | Valid email address |
109
+ | `json()` | JSON string (parsed) |
98
110
 
99
- const { GITHUB_TOKEN, PORT } = myEnv;
111
+ ### Validator Options
112
+
113
+ All validators accept options:
114
+
115
+ ```ts
116
+ import { str, num } from '12factor-env';
117
+
118
+ const config = env(process.env, {
119
+ API_KEY: str({ desc: 'API key for external service' }),
120
+ TIMEOUT: num({ default: 5000, desc: 'Request timeout in ms' })
121
+ });
100
122
  ```
101
123
 
124
+ ## API
125
+
126
+ ### `env(inputEnv, secrets, vars)`
102
127
 
103
- ## env shortcut
128
+ Main function to validate environment variables.
104
129
 
105
- Here `env()` expects 2 args, secrets and env vars.
130
+ - `inputEnv` - The environment object (usually `process.env`)
131
+ - `secrets` - Required environment variables
132
+ - `vars` - Optional environment variables
106
133
 
107
- In this example, it will look for `/var/run/secrets/MAILGUN_KEY`, and populate the final env with everything in one object.
134
+ ### `secret(envFile)`
108
135
 
109
- ```js
110
- const myEnv = env(
111
- process.env,
112
- { MAILGUN_KEY: str() },
113
- { PORT: port({ default: 10101 }) }
114
- );
136
+ Create a validator for a secret file:
137
+
138
+ ```ts
139
+ import { env, secret } from '12factor-env';
140
+
141
+ const config = env(process.env, {
142
+ DB_PASSWORD: secret('DATABASE_PASSWORD')
143
+ });
144
+ ```
145
+
146
+ ### `getSecret(name)`
147
+
148
+ Read a secret from a file:
149
+
150
+ ```ts
151
+ import { getSecret } from '12factor-env';
152
+
153
+ const password = getSecret('DATABASE_PASSWORD');
115
154
  ```
116
155
 
117
- ## secret field
156
+ ### `secretPath(name)`
157
+
158
+ Resolve the full path to a secret file:
118
159
 
119
- The `secret` object let's you specify the secret name as it is saved in the `/var/run/secrets` folder.
160
+ ```ts
161
+ import { secretPath } from '12factor-env';
120
162
 
121
- ```js
122
- const myEnv = env(
123
- process.env,
124
- { MAILGUN_KEY: secret('MAILGUN_KEY') },
125
- { PORT: port({ default: 10101 }) }
126
- );
163
+ const path = secretPath('DATABASE_PASSWORD');
164
+ // Returns: /run/secrets/DATABASE_PASSWORD
127
165
  ```
128
166
 
167
+ ## Re-exports from envalid
168
+
169
+ The following are re-exported from envalid for convenience:
170
+
171
+ - `cleanEnv` - Low-level env cleaning function
172
+ - `makeValidator` - Create custom validators
173
+ - `EnvError` - Error class for validation errors
174
+ - `EnvMissingError` - Error class for missing required vars
175
+ - `testOnly` - Helper for test-only defaults
176
+
177
+ ---
178
+
179
+ ## Education and Tutorials
180
+
181
+ 1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
182
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
183
+
184
+ 2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
185
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
186
+
187
+ 3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
188
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
189
+
190
+ 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
191
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
192
+
193
+ 5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
194
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
195
+
196
+ 6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
197
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
198
+
199
+ 7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
200
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
201
+
202
+ ## Related Constructive Tooling
203
+
204
+ ### 📦 Package Management
205
+
206
+ * [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
207
+
208
+ ### 🧪 Testing
209
+
210
+ * [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
211
+ * [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **🌱 PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
212
+ * [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
213
+ * [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
214
+ * [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
215
+
216
+ ### 🧠 Parsing & AST
217
+
218
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
219
+ * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
220
+ * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
221
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
222
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
223
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
224
+
225
+ ## Credits
226
+
227
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
228
+
229
+ ## Disclaimer
230
+
231
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
232
+
233
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/esm/index.d.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { makeValidator, EnvError, EnvMissingError, testOnly, bool, num, str, json, host, port, url, email } from 'envalid';
2
+ import type { ValidatorSpec, CleanedEnv, CleanOptions } from 'envalid';
3
+ /**
4
+ * Wrapper around envalid's cleanEnv that uses a throwing reporter by default
5
+ * This prevents process.exit from being called on validation errors
6
+ */
7
+ declare const cleanEnv: <S extends Record<string, ValidatorSpec<unknown>>>(environment: Record<string, string | undefined>, specs: S, options?: CleanOptions<S>) => CleanedEnv<S>;
8
+ /**
9
+ * Resolve the full path to a secret file
10
+ */
11
+ declare const secretPath: (name: string) => string;
12
+ /**
13
+ * Read a secret from a file
14
+ * @param secret - The secret file name or path
15
+ * @returns The secret value or undefined if not found
16
+ */
17
+ declare const getSecret: (secret: string | undefined) => string | undefined;
18
+ /**
19
+ * Read secrets from files based on the secret props configuration
20
+ * Supports both direct secret files and _FILE suffix pattern
21
+ */
22
+ declare const secretEnv: <T extends Record<string, ValidatorSpec<unknown>>>(inputEnv: Record<string, string | undefined>, secretProps: T) => Record<string, string>;
23
+ /**
24
+ * Create a validator for a secret file
25
+ * @param envFile - The environment variable name for the secret file
26
+ */
27
+ declare const secret: (envFile?: string) => ValidatorSpec<string>;
28
+ type Specs = Record<string, ValidatorSpec<unknown>>;
29
+ /**
30
+ * Validate environment variables with secret file support
31
+ *
32
+ * @param inputEnv - The environment object (usually process.env)
33
+ * @param secrets - Required environment variables (validated with envalid)
34
+ * @param vars - Optional environment variables (validated with envalid)
35
+ * @returns Validated and cleaned environment object
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * const config = env(
40
+ * process.env,
41
+ * {
42
+ * DATABASE_URL: str(),
43
+ * API_KEY: str()
44
+ * },
45
+ * {
46
+ * PORT: port({ default: 3000 }),
47
+ * DEBUG: bool({ default: false })
48
+ * }
49
+ * );
50
+ * ```
51
+ */
52
+ declare const env: <S extends Specs, V extends Specs>(inputEnv: Record<string, string | undefined>, secrets?: S, vars?: V) => CleanedEnv<S & V>;
53
+ export { env, secretEnv, secret, getSecret, secretPath, cleanEnv, makeValidator, EnvError, EnvMissingError, testOnly, bool, num, str, json, host, port, url, email };
54
+ export type { ValidatorSpec, CleanedEnv };
package/esm/index.js ADDED
@@ -0,0 +1,112 @@
1
+ import { cleanEnv as envalidCleanEnv, makeValidator, EnvError, EnvMissingError, testOnly, bool, num, str, json, host, port, url, email } from 'envalid';
2
+ import { readFileSync } from 'fs';
3
+ import { resolve, join } from 'path';
4
+ /**
5
+ * Custom reporter that throws an error instead of calling process.exit
6
+ * This allows errors to be caught and handled properly in tests and applications
7
+ */
8
+ const throwingReporter = ({ errors }) => {
9
+ const errorKeys = Object.keys(errors);
10
+ if (errorKeys.length > 0) {
11
+ const missingVars = errorKeys.map((key) => `${String(key)}: ${errors[key]?.message ?? 'unknown error'}`);
12
+ throw new EnvError(`Missing or invalid environment variables:\n ${missingVars.join('\n ')}`);
13
+ }
14
+ };
15
+ /**
16
+ * Wrapper around envalid's cleanEnv that uses a throwing reporter by default
17
+ * This prevents process.exit from being called on validation errors
18
+ */
19
+ const cleanEnv = (environment, specs, options) => {
20
+ return envalidCleanEnv(environment, specs, {
21
+ reporter: throwingReporter,
22
+ ...options
23
+ });
24
+ };
25
+ /**
26
+ * Default path for secret files (Docker/Kubernetes secrets)
27
+ */
28
+ const ENV_SECRETS_PATH = process.env.ENV_SECRETS_PATH ?? '/run/secrets/';
29
+ /**
30
+ * Resolve the full path to a secret file
31
+ */
32
+ const secretPath = (name) => name.startsWith('/') ? name : resolve(join(ENV_SECRETS_PATH, name));
33
+ /**
34
+ * Read a secret from a file
35
+ * @param secret - The secret file name or path
36
+ * @returns The secret value or undefined if not found
37
+ */
38
+ const getSecret = (secret) => {
39
+ if (!secret)
40
+ return undefined;
41
+ try {
42
+ const value = readFileSync(secretPath(secret), 'utf-8');
43
+ return value.trim();
44
+ }
45
+ catch {
46
+ return undefined;
47
+ }
48
+ };
49
+ /**
50
+ * Read secrets from files based on the secret props configuration
51
+ * Supports both direct secret files and _FILE suffix pattern
52
+ */
53
+ const secretEnv = (inputEnv, secretProps) => {
54
+ return Object.keys(secretProps).reduce((m, k) => {
55
+ // Try to read secret directly from file
56
+ const secret = getSecret(k);
57
+ if (secret) {
58
+ m[k] = secret;
59
+ }
60
+ else {
61
+ // Try _FILE suffix pattern (e.g., DATABASE_PASSWORD_FILE)
62
+ const secretFileKey = `${k}_FILE`;
63
+ if (Object.prototype.hasOwnProperty.call(inputEnv, secretFileKey)) {
64
+ const secretFileValue = getSecret(inputEnv[secretFileKey]);
65
+ if (secretFileValue) {
66
+ m[k] = secretFileValue;
67
+ }
68
+ }
69
+ }
70
+ return m;
71
+ }, {});
72
+ };
73
+ /**
74
+ * Create a validator for a secret file
75
+ * @param envFile - The environment variable name for the secret file
76
+ */
77
+ const secret = (envFile) => str({ default: getSecret(envFile) });
78
+ /**
79
+ * Validate environment variables with secret file support
80
+ *
81
+ * @param inputEnv - The environment object (usually process.env)
82
+ * @param secrets - Required environment variables (validated with envalid)
83
+ * @param vars - Optional environment variables (validated with envalid)
84
+ * @returns Validated and cleaned environment object
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * const config = env(
89
+ * process.env,
90
+ * {
91
+ * DATABASE_URL: str(),
92
+ * API_KEY: str()
93
+ * },
94
+ * {
95
+ * PORT: port({ default: 3000 }),
96
+ * DEBUG: bool({ default: false })
97
+ * }
98
+ * );
99
+ * ```
100
+ */
101
+ const env = (inputEnv, secrets = {}, vars = {}) => {
102
+ // First pass: validate optional vars
103
+ const varEnv = cleanEnv(inputEnv, vars);
104
+ // Read secrets from files
105
+ const _secrets = secretEnv(varEnv, secrets);
106
+ // Second pass: validate secrets with file values merged in
107
+ const mergedEnv = { ...varEnv, ..._secrets };
108
+ return cleanEnv(mergedEnv, secrets);
109
+ };
110
+ export { env, secretEnv, secret, getSecret, secretPath,
111
+ // Re-export from envalid
112
+ cleanEnv, makeValidator, EnvError, EnvMissingError, testOnly, bool, num, str, json, host, port, url, email };
package/index.d.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { makeValidator, EnvError, EnvMissingError, testOnly, bool, num, str, json, host, port, url, email } from 'envalid';
2
+ import type { ValidatorSpec, CleanedEnv, CleanOptions } from 'envalid';
3
+ /**
4
+ * Wrapper around envalid's cleanEnv that uses a throwing reporter by default
5
+ * This prevents process.exit from being called on validation errors
6
+ */
7
+ declare const cleanEnv: <S extends Record<string, ValidatorSpec<unknown>>>(environment: Record<string, string | undefined>, specs: S, options?: CleanOptions<S>) => CleanedEnv<S>;
8
+ /**
9
+ * Resolve the full path to a secret file
10
+ */
11
+ declare const secretPath: (name: string) => string;
12
+ /**
13
+ * Read a secret from a file
14
+ * @param secret - The secret file name or path
15
+ * @returns The secret value or undefined if not found
16
+ */
17
+ declare const getSecret: (secret: string | undefined) => string | undefined;
18
+ /**
19
+ * Read secrets from files based on the secret props configuration
20
+ * Supports both direct secret files and _FILE suffix pattern
21
+ */
22
+ declare const secretEnv: <T extends Record<string, ValidatorSpec<unknown>>>(inputEnv: Record<string, string | undefined>, secretProps: T) => Record<string, string>;
23
+ /**
24
+ * Create a validator for a secret file
25
+ * @param envFile - The environment variable name for the secret file
26
+ */
27
+ declare const secret: (envFile?: string) => ValidatorSpec<string>;
28
+ type Specs = Record<string, ValidatorSpec<unknown>>;
29
+ /**
30
+ * Validate environment variables with secret file support
31
+ *
32
+ * @param inputEnv - The environment object (usually process.env)
33
+ * @param secrets - Required environment variables (validated with envalid)
34
+ * @param vars - Optional environment variables (validated with envalid)
35
+ * @returns Validated and cleaned environment object
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * const config = env(
40
+ * process.env,
41
+ * {
42
+ * DATABASE_URL: str(),
43
+ * API_KEY: str()
44
+ * },
45
+ * {
46
+ * PORT: port({ default: 3000 }),
47
+ * DEBUG: bool({ default: false })
48
+ * }
49
+ * );
50
+ * ```
51
+ */
52
+ declare const env: <S extends Specs, V extends Specs>(inputEnv: Record<string, string | undefined>, secrets?: S, vars?: V) => CleanedEnv<S & V>;
53
+ export { env, secretEnv, secret, getSecret, secretPath, cleanEnv, makeValidator, EnvError, EnvMissingError, testOnly, bool, num, str, json, host, port, url, email };
54
+ export type { ValidatorSpec, CleanedEnv };
package/index.js ADDED
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.email = exports.url = exports.port = exports.host = exports.json = exports.str = exports.num = exports.bool = exports.testOnly = exports.EnvMissingError = exports.EnvError = exports.makeValidator = exports.cleanEnv = exports.secretPath = exports.getSecret = exports.secret = exports.secretEnv = exports.env = void 0;
4
+ const envalid_1 = require("envalid");
5
+ Object.defineProperty(exports, "makeValidator", { enumerable: true, get: function () { return envalid_1.makeValidator; } });
6
+ Object.defineProperty(exports, "EnvError", { enumerable: true, get: function () { return envalid_1.EnvError; } });
7
+ Object.defineProperty(exports, "EnvMissingError", { enumerable: true, get: function () { return envalid_1.EnvMissingError; } });
8
+ Object.defineProperty(exports, "testOnly", { enumerable: true, get: function () { return envalid_1.testOnly; } });
9
+ Object.defineProperty(exports, "bool", { enumerable: true, get: function () { return envalid_1.bool; } });
10
+ Object.defineProperty(exports, "num", { enumerable: true, get: function () { return envalid_1.num; } });
11
+ Object.defineProperty(exports, "str", { enumerable: true, get: function () { return envalid_1.str; } });
12
+ Object.defineProperty(exports, "json", { enumerable: true, get: function () { return envalid_1.json; } });
13
+ Object.defineProperty(exports, "host", { enumerable: true, get: function () { return envalid_1.host; } });
14
+ Object.defineProperty(exports, "port", { enumerable: true, get: function () { return envalid_1.port; } });
15
+ Object.defineProperty(exports, "url", { enumerable: true, get: function () { return envalid_1.url; } });
16
+ Object.defineProperty(exports, "email", { enumerable: true, get: function () { return envalid_1.email; } });
17
+ const fs_1 = require("fs");
18
+ const path_1 = require("path");
19
+ /**
20
+ * Custom reporter that throws an error instead of calling process.exit
21
+ * This allows errors to be caught and handled properly in tests and applications
22
+ */
23
+ const throwingReporter = ({ errors }) => {
24
+ const errorKeys = Object.keys(errors);
25
+ if (errorKeys.length > 0) {
26
+ const missingVars = errorKeys.map((key) => `${String(key)}: ${errors[key]?.message ?? 'unknown error'}`);
27
+ throw new envalid_1.EnvError(`Missing or invalid environment variables:\n ${missingVars.join('\n ')}`);
28
+ }
29
+ };
30
+ /**
31
+ * Wrapper around envalid's cleanEnv that uses a throwing reporter by default
32
+ * This prevents process.exit from being called on validation errors
33
+ */
34
+ const cleanEnv = (environment, specs, options) => {
35
+ return (0, envalid_1.cleanEnv)(environment, specs, {
36
+ reporter: throwingReporter,
37
+ ...options
38
+ });
39
+ };
40
+ exports.cleanEnv = cleanEnv;
41
+ /**
42
+ * Default path for secret files (Docker/Kubernetes secrets)
43
+ */
44
+ const ENV_SECRETS_PATH = process.env.ENV_SECRETS_PATH ?? '/run/secrets/';
45
+ /**
46
+ * Resolve the full path to a secret file
47
+ */
48
+ const secretPath = (name) => name.startsWith('/') ? name : (0, path_1.resolve)((0, path_1.join)(ENV_SECRETS_PATH, name));
49
+ exports.secretPath = secretPath;
50
+ /**
51
+ * Read a secret from a file
52
+ * @param secret - The secret file name or path
53
+ * @returns The secret value or undefined if not found
54
+ */
55
+ const getSecret = (secret) => {
56
+ if (!secret)
57
+ return undefined;
58
+ try {
59
+ const value = (0, fs_1.readFileSync)(secretPath(secret), 'utf-8');
60
+ return value.trim();
61
+ }
62
+ catch {
63
+ return undefined;
64
+ }
65
+ };
66
+ exports.getSecret = getSecret;
67
+ /**
68
+ * Read secrets from files based on the secret props configuration
69
+ * Supports both direct secret files and _FILE suffix pattern
70
+ */
71
+ const secretEnv = (inputEnv, secretProps) => {
72
+ return Object.keys(secretProps).reduce((m, k) => {
73
+ // Try to read secret directly from file
74
+ const secret = getSecret(k);
75
+ if (secret) {
76
+ m[k] = secret;
77
+ }
78
+ else {
79
+ // Try _FILE suffix pattern (e.g., DATABASE_PASSWORD_FILE)
80
+ const secretFileKey = `${k}_FILE`;
81
+ if (Object.prototype.hasOwnProperty.call(inputEnv, secretFileKey)) {
82
+ const secretFileValue = getSecret(inputEnv[secretFileKey]);
83
+ if (secretFileValue) {
84
+ m[k] = secretFileValue;
85
+ }
86
+ }
87
+ }
88
+ return m;
89
+ }, {});
90
+ };
91
+ exports.secretEnv = secretEnv;
92
+ /**
93
+ * Create a validator for a secret file
94
+ * @param envFile - The environment variable name for the secret file
95
+ */
96
+ const secret = (envFile) => (0, envalid_1.str)({ default: getSecret(envFile) });
97
+ exports.secret = secret;
98
+ /**
99
+ * Validate environment variables with secret file support
100
+ *
101
+ * @param inputEnv - The environment object (usually process.env)
102
+ * @param secrets - Required environment variables (validated with envalid)
103
+ * @param vars - Optional environment variables (validated with envalid)
104
+ * @returns Validated and cleaned environment object
105
+ *
106
+ * @example
107
+ * ```ts
108
+ * const config = env(
109
+ * process.env,
110
+ * {
111
+ * DATABASE_URL: str(),
112
+ * API_KEY: str()
113
+ * },
114
+ * {
115
+ * PORT: port({ default: 3000 }),
116
+ * DEBUG: bool({ default: false })
117
+ * }
118
+ * );
119
+ * ```
120
+ */
121
+ const env = (inputEnv, secrets = {}, vars = {}) => {
122
+ // First pass: validate optional vars
123
+ const varEnv = cleanEnv(inputEnv, vars);
124
+ // Read secrets from files
125
+ const _secrets = secretEnv(varEnv, secrets);
126
+ // Second pass: validate secrets with file values merged in
127
+ const mergedEnv = { ...varEnv, ..._secrets };
128
+ return cleanEnv(mergedEnv, secrets);
129
+ };
130
+ exports.env = env;
package/package.json CHANGED
@@ -1,67 +1,50 @@
1
1
  {
2
2
  "name": "12factor-env",
3
- "version": "0.1.0",
4
- "description": "12factor env vars and secrets",
5
- "author": "Dan Lynch <pyramation@gmail.com>",
6
- "homepage": "https://github.com/pyramation/12factor-env#readme",
7
- "license": "SEE LICENSE IN LICENSE",
8
- "main": "main/index.js",
9
- "module": "module/index.js",
10
- "directories": {
11
- "lib": "src",
12
- "test": "__tests__"
13
- },
14
- "files": [
15
- "main",
16
- "module"
17
- ],
18
- "scripts": {
19
- "build:main": "cross-env BABEL_ENV=production babel src --out-dir main --delete-dir-on-start",
20
- "build:module": "cross-env MODULE=true babel src --out-dir module --delete-dir-on-start",
21
- "build": "npm run build:module && npm run build:main",
22
- "prepublish": "npm run build",
23
- "dev": "cross-env NODE_ENV=development babel-node src/index",
24
- "watch": "cross-env NODE_ENV=development babel-watch src/index",
25
- "lint": "eslint src --fix",
26
- "test": "jest",
27
- "test:watch": "jest --watch",
28
- "test:debug": "node --inspect node_modules/.bin/jest --runInBand"
29
- },
3
+ "version": "1.0.0",
4
+ "author": "Constructive <developers@constructive.io>",
5
+ "description": "Environment variable validation with secret file support for 12-factor apps",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/constructive",
10
+ "license": "MIT",
30
11
  "publishConfig": {
31
- "access": "public"
12
+ "access": "public",
13
+ "directory": "dist"
32
14
  },
33
15
  "repository": {
34
16
  "type": "git",
35
- "url": "https://github.com/pyramation/12factor-env"
17
+ "url": "https://github.com/constructive-io/constructive"
36
18
  },
37
- "keywords": [],
38
19
  "bugs": {
39
- "url": "https://github.com/pyramation/12factor-env/issues"
20
+ "url": "https://github.com/constructive-io/constructive/issues"
40
21
  },
41
- "devDependencies": {
42
- "@babel/cli": "7.11.6",
43
- "@babel/core": "7.11.6",
44
- "@babel/node": "^7.10.5",
45
- "@babel/plugin-proposal-class-properties": "7.10.4",
46
- "@babel/plugin-proposal-export-default-from": "7.10.4",
47
- "@babel/plugin-proposal-object-rest-spread": "7.11.0",
48
- "@babel/plugin-transform-runtime": "7.11.5",
49
- "@babel/preset-env": "7.11.5",
50
- "babel-core": "7.0.0-bridge.0",
51
- "babel-eslint": "10.1.0",
52
- "babel-jest": "25.1.0",
53
- "babel-watch": "^7.0.0",
54
- "cross-env": "^7.0.2",
55
- "eslint": "6.8.0",
56
- "eslint-config-prettier": "^6.10.0",
57
- "eslint-plugin-prettier": "^3.1.2",
58
- "jest": "^24.5.0",
59
- "jest-in-case": "^1.0.2",
60
- "prettier": "^2.1.2",
61
- "regenerator-runtime": "^0.13.7"
22
+ "scripts": {
23
+ "clean": "makage clean",
24
+ "prepack": "npm run build",
25
+ "build": "makage build",
26
+ "build:dev": "makage build --dev",
27
+ "lint": "eslint . --fix",
28
+ "test": "jest --passWithNoTests",
29
+ "test:watch": "jest --watch"
62
30
  },
63
31
  "dependencies": {
64
- "@babel/runtime": "^7.11.2",
65
- "envalid": "^6.0.2"
66
- }
32
+ "envalid": "^8.1.1"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^20.12.7",
36
+ "makage": "^0.1.10",
37
+ "ts-node": "^10.9.2"
38
+ },
39
+ "keywords": [
40
+ "environment",
41
+ "env",
42
+ "validation",
43
+ "12factor",
44
+ "secrets",
45
+ "kubernetes",
46
+ "docker",
47
+ "constructive"
48
+ ],
49
+ "gitHead": "390f4dd57fc158554518ec454bf2a4856d550552"
67
50
  }
package/main/index.js DELETED
@@ -1,163 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
- Object.defineProperty(exports, "__esModule", {
6
- value: true
7
- });
8
- Object.defineProperty(exports, "cleanEnv", {
9
- enumerable: true,
10
- get: function get() {
11
- return _envalid.cleanEnv;
12
- }
13
- });
14
- Object.defineProperty(exports, "makeValidator", {
15
- enumerable: true,
16
- get: function get() {
17
- return _envalid.makeValidator;
18
- }
19
- });
20
- Object.defineProperty(exports, "EnvError", {
21
- enumerable: true,
22
- get: function get() {
23
- return _envalid.EnvError;
24
- }
25
- });
26
- Object.defineProperty(exports, "EnvMissingError", {
27
- enumerable: true,
28
- get: function get() {
29
- return _envalid.EnvMissingError;
30
- }
31
- });
32
- Object.defineProperty(exports, "testOnly", {
33
- enumerable: true,
34
- get: function get() {
35
- return _envalid.testOnly;
36
- }
37
- });
38
- Object.defineProperty(exports, "bool", {
39
- enumerable: true,
40
- get: function get() {
41
- return _envalid.bool;
42
- }
43
- });
44
- Object.defineProperty(exports, "num", {
45
- enumerable: true,
46
- get: function get() {
47
- return _envalid.num;
48
- }
49
- });
50
- Object.defineProperty(exports, "str", {
51
- enumerable: true,
52
- get: function get() {
53
- return _envalid.str;
54
- }
55
- });
56
- Object.defineProperty(exports, "json", {
57
- enumerable: true,
58
- get: function get() {
59
- return _envalid.json;
60
- }
61
- });
62
- Object.defineProperty(exports, "host", {
63
- enumerable: true,
64
- get: function get() {
65
- return _envalid.host;
66
- }
67
- });
68
- Object.defineProperty(exports, "port", {
69
- enumerable: true,
70
- get: function get() {
71
- return _envalid.port;
72
- }
73
- });
74
- Object.defineProperty(exports, "url", {
75
- enumerable: true,
76
- get: function get() {
77
- return _envalid.url;
78
- }
79
- });
80
- Object.defineProperty(exports, "email", {
81
- enumerable: true,
82
- get: function get() {
83
- return _envalid.email;
84
- }
85
- });
86
- exports.secret = exports.secretEnv = exports.env = void 0;
87
-
88
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
89
-
90
- var _envalid = require("envalid");
91
-
92
- var _fs = require("fs");
93
-
94
- var _path = require("path");
95
-
96
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
97
-
98
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
99
-
100
- var ENV_SECRETS_PATH = process.env.ENV_SECRETS_PATH ? process.env.ENV_SECRETS_PATH : '/run/secrets/';
101
-
102
- var secretPath = function secretPath(name) {
103
- return name.startsWith('/') ? name : (0, _path.resolve)((0, _path.join)(ENV_SECRETS_PATH, name));
104
- };
105
-
106
- var getSecret = function getSecret(secret) {
107
- if (!secret) return;
108
-
109
- try {
110
- var value = (0, _fs.readFileSync)(secretPath(secret), 'utf-8');
111
- return value;
112
- } catch (e) {
113
- return;
114
- }
115
- };
116
-
117
- var secretEnv = function secretEnv(env, secretProps) {
118
- return Object.keys(secretProps).reduce(function (m, k) {
119
- var secret = getSecret(k);
120
-
121
- if (secret) {
122
- m[k] = secret;
123
- } else {
124
- var secretFileKey = k + '_FILE';
125
-
126
- if (env.hasOwnProperty(secretFileKey)) {
127
- var secretFileValue = getSecret(env[secretFileKey]);
128
-
129
- if (secretFileValue) {
130
- m[k] = secretFileValue;
131
- }
132
- }
133
- }
134
-
135
- return m;
136
- }, {});
137
- };
138
-
139
- exports.secretEnv = secretEnv;
140
-
141
- var secret = function secret(ENV_FILE) {
142
- return (0, _envalid.str)({
143
- "default": getSecret(ENV_FILE)
144
- });
145
- };
146
-
147
- exports.secret = secret;
148
-
149
- var env = function env(inputEnv) {
150
- var secrets = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
151
- var vars = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
152
- var varEnv = (0, _envalid.cleanEnv)(inputEnv, _objectSpread({}, vars), {
153
- dotEnvPath: null
154
- });
155
-
156
- var _secrets = secretEnv(varEnv, secrets);
157
-
158
- return (0, _envalid.cleanEnv)(_objectSpread(_objectSpread({}, varEnv), _secrets), _objectSpread({}, secrets), {
159
- dotEnvPath: null
160
- });
161
- };
162
-
163
- exports.env = env;
package/module/index.js DELETED
@@ -1,65 +0,0 @@
1
- import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
2
-
3
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
4
-
5
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
6
-
7
- import { cleanEnv, makeValidator, EnvError, EnvMissingError, testOnly, bool, num, str, json, host, port, url, email } from 'envalid';
8
- import { readFileSync } from 'fs';
9
- import { resolve, join } from 'path';
10
- const ENV_SECRETS_PATH = process.env.ENV_SECRETS_PATH ? process.env.ENV_SECRETS_PATH : '/run/secrets/';
11
-
12
- const secretPath = name => name.startsWith('/') ? name : resolve(join(ENV_SECRETS_PATH, name));
13
-
14
- const getSecret = secret => {
15
- if (!secret) return;
16
-
17
- try {
18
- const value = readFileSync(secretPath(secret), 'utf-8');
19
- return value;
20
- } catch (e) {
21
- return;
22
- }
23
- };
24
-
25
- const secretEnv = (env, secretProps) => {
26
- return Object.keys(secretProps).reduce((m, k) => {
27
- const secret = getSecret(k);
28
-
29
- if (secret) {
30
- m[k] = secret;
31
- } else {
32
- const secretFileKey = k + '_FILE';
33
-
34
- if (env.hasOwnProperty(secretFileKey)) {
35
- const secretFileValue = getSecret(env[secretFileKey]);
36
-
37
- if (secretFileValue) {
38
- m[k] = secretFileValue;
39
- }
40
- }
41
- }
42
-
43
- return m;
44
- }, {});
45
- };
46
-
47
- const secret = ENV_FILE => str({
48
- default: getSecret(ENV_FILE)
49
- });
50
-
51
- const env = (inputEnv, secrets = {}, vars = {}) => {
52
- const varEnv = cleanEnv(inputEnv, _objectSpread({}, vars), {
53
- dotEnvPath: null
54
- });
55
-
56
- const _secrets = secretEnv(varEnv, secrets);
57
-
58
- return cleanEnv(_objectSpread(_objectSpread({}, varEnv), _secrets), _objectSpread({}, secrets), {
59
- dotEnvPath: null
60
- });
61
- };
62
-
63
- export { env, secretEnv, secret
64
- /* envalid */
65
- , cleanEnv, makeValidator, EnvError, EnvMissingError, testOnly, bool, num, str, json, host, port, url, email };