@push.rocks/qenv 6.1.0 → 6.1.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.
@@ -3,7 +3,7 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@push.rocks/qenv',
6
- version: '6.1.0',
6
+ version: '6.1.2',
7
7
  description: 'A module for easily handling environment variables in Node.js projects with support for .yml and .json configuration.'
8
8
  };
9
9
  //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMDBfY29tbWl0aW5mb19kYXRhLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvMDBfY29tbWl0aW5mb19kYXRhLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOztHQUVHO0FBQ0gsTUFBTSxDQUFDLE1BQU0sVUFBVSxHQUFHO0lBQ3hCLElBQUksRUFBRSxrQkFBa0I7SUFDeEIsT0FBTyxFQUFFLE9BQU87SUFDaEIsV0FBVyxFQUFFLHVIQUF1SDtDQUNySSxDQUFBIn0=
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@push.rocks/qenv",
3
- "version": "6.1.0",
3
+ "version": "6.1.2",
4
4
  "private": false,
5
5
  "description": "A module for easily handling environment variables in Node.js projects with support for .yml and .json configuration.",
6
6
  "main": "dist_ts/index.js",
@@ -26,18 +26,17 @@
26
26
  },
27
27
  "homepage": "https://code.foss.global/push.rocks/qenv",
28
28
  "devDependencies": {
29
- "@git.zone/tsbuild": "^2.2.0",
29
+ "@git.zone/tsbuild": "^2.6.4",
30
30
  "@git.zone/tsrun": "^1.3.3",
31
- "@git.zone/tstest": "^1.0.90",
32
- "@push.rocks/tapbundle": "^5.5.0",
33
- "@types/node": "^22.9.1"
31
+ "@git.zone/tstest": "^2.3.2",
32
+ "@types/node": "^22.13.13"
34
33
  },
35
34
  "dependencies": {
36
35
  "@api.global/typedrequest": "^3.1.10",
37
36
  "@configvault.io/interfaces": "^1.0.17",
38
- "@push.rocks/smartfile": "^11.0.21",
39
- "@push.rocks/smartlog": "^3.0.7",
40
- "@push.rocks/smartpath": "^5.0.18"
37
+ "@push.rocks/smartfile": "^11.2.5",
38
+ "@push.rocks/smartlog": "^3.1.8",
39
+ "@push.rocks/smartpath": "^6.0.0"
41
40
  },
42
41
  "files": [
43
42
  "ts/**/*",
package/readme.md CHANGED
@@ -1,109 +1,344 @@
1
- # @push.rocks/qenv
2
- easy promised environments
1
+ # @push.rocks/qenv 🔐
2
+ **Smart Environment Variable Management for Node.js**
3
3
 
4
- ## Install
5
- To install `@push.rocks/qenv`, you need to have Node.js installed on your system. Once Node.js is installed, you can add `@push.rocks/qenv` to your project by running the following command in your project's root directory:
4
+ > Never hardcode secrets again. Load environment variables from multiple sources with ease and confidence.
5
+
6
+ ## 🚀 Features
7
+
8
+ ✅ **Multi-source Loading** - Automatically loads from environment variables, config files, and Docker secrets
9
+ ✅ **Type-Safe** - Full TypeScript support with comprehensive type definitions
10
+ ✅ **Flexible Formats** - Supports `.yml`, `.yaml`, and `.json` configuration files
11
+ ✅ **Docker Ready** - Built-in support for Docker secrets and secret.json files
12
+ ✅ **Async & Sync** - Both synchronous and asynchronous variable retrieval
13
+ ✅ **Strict Mode** - Optional strict mode that throws errors for missing variables
14
+ ✅ **Base64 Objects** - Handle complex configuration objects with automatic encoding/decoding
15
+ ✅ **Dynamic Resolution** - Support for async functions as environment variable sources
16
+
17
+ ## 📦 Installation
6
18
 
7
19
  ```bash
20
+ # Using npm
8
21
  npm install @push.rocks/qenv --save
9
- ```
10
22
 
11
- This command will add `@push.rocks/qenv` as a dependency to your project, and you will be ready to use it in your application.
23
+ # Using pnpm (recommended)
24
+ pnpm add @push.rocks/qenv
12
25
 
13
- ## Usage
14
- `@push.rocks/qenv` provides a convenient way to manage and access environment variables in your Node.js projects, especially when dealing with different environments like development, testing, and production. Its primary use is to load environment-specific variables in an easy and organized manner. Below is an extensive guide on how to use this module effectively in various scenarios, ensuring you can handle environment variables efficiently in your projects.
15
-
16
- ### Getting Started
17
- First, ensure you have TypeScript configured in your project. `@push.rocks/qenv` is fully typed, providing excellent IntelliSense support when working in editors that support TypeScript, such as Visual Studio Code.
26
+ # Using yarn
27
+ yarn add @push.rocks/qenv
28
+ ```
18
29
 
19
- #### Importing Qenv
20
- To get started, import the `Qenv` class from `@push.rocks/qenv`:
30
+ ## 🎯 Quick Start
21
31
 
22
32
  ```typescript
23
33
  import { Qenv } from '@push.rocks/qenv';
34
+
35
+ // Create a new Qenv instance
36
+ const qenv = new Qenv('./', './', true);
37
+
38
+ // Access environment variables
39
+ const dbHost = await qenv.getEnvVarOnDemand('DB_HOST');
40
+ const apiKey = await qenv.getEnvVarOnDemand('API_KEY');
41
+
42
+ // Use strict mode to ensure variables exist
43
+ const criticalVar = await qenv.getEnvVarOnDemandStrict('CRITICAL_CONFIG');
44
+ // Throws error if CRITICAL_CONFIG is not set!
24
45
  ```
25
46
 
26
- #### Basic Configuration
27
- `@push.rocks/qenv` works with two main files: `qenv.yml` for specifying required environment variables, and `env.yml` for specifying values for these variables. These files should be placed in your project directory.
47
+ ## 📖 Configuration
48
+
49
+ ### Setting Up Your Environment Files
28
50
 
29
- ##### qenv.yml
30
- This file specifies the environment variables that are required by your application. An example `qenv.yml` might look like this:
51
+ #### 1. Define Required Variables (`qenv.yml`)
52
+
53
+ Create a `qenv.yml` file to specify which environment variables your application needs:
31
54
 
32
55
  ```yaml
33
56
  required:
34
57
  - DB_HOST
35
58
  - DB_USER
36
- - DB_PASS
59
+ - DB_PASSWORD
60
+ - API_KEY
61
+ - LOG_LEVEL
37
62
  ```
38
63
 
39
- ##### env.yml
40
- This file contains the actual values for the environment variables in a development or testing environment. An example `env.yml` could be:
64
+ #### 2. Provide Values (`env.yml` or `env.json`)
65
+
66
+ For local development, create an `env.yml` or `env.json` file:
41
67
 
68
+ **env.yml:**
42
69
  ```yaml
43
70
  DB_HOST: localhost
44
- DB_USER: user
45
- DB_PASS: pass
71
+ DB_USER: developer
72
+ DB_PASSWORD: supersecret123
73
+ API_KEY: dev-key-12345
74
+ LOG_LEVEL: debug
46
75
  ```
47
76
 
48
- #### Instantiating Qenv
49
- Create an instance of `Qenv` by providing paths to the directories containing the `qenv.yml` and `env.yml` files, respectively:
77
+ **env.json:**
78
+ ```json
79
+ {
80
+ "DB_HOST": "localhost",
81
+ "DB_USER": "developer",
82
+ "DB_PASSWORD": "supersecret123",
83
+ "API_KEY": "dev-key-12345",
84
+ "LOG_LEVEL": "debug"
85
+ }
86
+ ```
87
+
88
+ > 💡 **Pro Tip:** Add `env.yml` and `env.json` to your `.gitignore` to keep secrets out of version control!
89
+
90
+ ## 🔥 Advanced Usage
91
+
92
+ ### Loading Priority
93
+
94
+ Qenv loads variables in this order (first found wins):
95
+ 1. **Process environment variables** - Already set in `process.env`
96
+ 2. **Configuration files** - From `env.yml` or `env.json`
97
+ 3. **Docker secrets** - From `/run/secrets/`
98
+ 4. **Docker secret JSON** - From `/run/secrets/secret.json`
99
+
100
+ ### Handling Complex Objects
101
+
102
+ Store and retrieve complex configuration objects:
50
103
 
51
104
  ```typescript
52
- const myQenv = new Qenv('./path/to/dir/with/qenv', './path/to/dir/with/env');
105
+ # In env.yml
106
+ DATABASE_CONFIG:
107
+ database:
108
+ host: localhost
109
+ port: 5432
110
+ options:
111
+ ssl: true
112
+ poolSize: 10
113
+
114
+ // Qenv automatically handles base64 encoding
115
+ const dbConfig = await qenv.getEnvVarOnDemandAsObject('DATABASE_CONFIG');
116
+ console.log(dbConfig.database.options.poolSize); // 10
53
117
  ```
54
118
 
55
- If the `env.yml` file is in the same directory as `qenv.yml`, you can omit the second argument:
119
+ ### Dynamic Environment Variables
120
+
121
+ Load variables from external sources dynamically:
56
122
 
57
123
  ```typescript
58
- const myQenv = new Qenv('./path/to/dir/with/both');
124
+ const qenv = new Qenv();
125
+
126
+ // Define an async function to fetch configuration
127
+ const fetchFromVault = async () => {
128
+ const response = await fetch('https://vault.example.com/api/secret');
129
+ const data = await response.json();
130
+ return data.secret;
131
+ };
132
+
133
+ // Use the function as an environment variable source
134
+ const secret = await qenv.getEnvVarOnDemand(fetchFromVault);
59
135
  ```
60
136
 
61
- #### Accessing Environment Variables
62
- After instantiating `Qenv`, you can access the loaded environment variables directly from `process.env` in Node.js or through the `myQenv` instance for more complex scenarios like asynchronous variable resolution:
137
+ ### Working with Docker
138
+
139
+ Qenv seamlessly integrates with Docker secrets:
140
+
141
+ ```dockerfile
142
+ # docker-compose.yml
143
+ version: '3.7'
144
+ services:
145
+ app:
146
+ image: your-app
147
+ secrets:
148
+ - db_password
149
+ - api_key
150
+
151
+ secrets:
152
+ db_password:
153
+ external: true
154
+ api_key:
155
+ external: true
156
+ ```
157
+
158
+ Your application automatically reads from `/run/secrets/`:
63
159
 
64
160
  ```typescript
65
- // Accessing directly via process.env
66
- console.log(process.env.DB_HOST); // 'localhost' in development environment
161
+ const qenv = new Qenv();
162
+ // Automatically loads from /run/secrets/db_password
163
+ const dbPassword = await qenv.getEnvVarOnDemand('db_password');
164
+ ```
165
+
166
+ ### Handling Missing Variables
167
+
168
+ Control how your application handles missing environment variables:
67
169
 
68
- // Accessing via Qenv instance for more advanced scenarios
69
- (async () => {
70
- const dbHost = await myQenv.getEnvVarOnDemand('DB_HOST');
71
- console.log(dbHost); // 'localhost'
72
- })();
170
+ ```typescript
171
+ // Fail fast (default behavior)
172
+ const qenvStrict = new Qenv('./', './', true);
173
+ // Application exits if required variables are missing
174
+
175
+ // Graceful handling
176
+ const qenvRelaxed = new Qenv('./', './', false);
177
+ // Application continues, you handle missing variables
178
+
179
+ // Check what's missing
180
+ if (qenvRelaxed.missingEnvVars.length > 0) {
181
+ console.warn('Missing variables:', qenvRelaxed.missingEnvVars);
182
+ // Implement fallback logic
183
+ }
73
184
  ```
74
185
 
75
- ### Advanced Usage
76
- #### Handling Missing Variables
77
- By default, `Qenv` will throw an error and exit if any of the required environment variables specified in `qenv.yml` are missing. You can disable this behavior by passing `false` as the third argument to the constructor, which allows your application to handle missing variables gracefully:
186
+ ### Strict Mode for Critical Variables
187
+
188
+ Use the new strict getter when you absolutely need a variable:
78
189
 
79
190
  ```typescript
80
- const myQenv = new Qenv('./path/to/dir/with/qenv', './path/to/dir/with/env', false);
191
+ try {
192
+ // This will throw if TOKEN is not set
193
+ const token = await qenv.getEnvVarOnDemandStrict('TOKEN');
194
+
195
+ // You can also check multiple fallback names
196
+ const db = await qenv.getEnvVarOnDemandStrict(['DATABASE_URL', 'DB_CONNECTION']);
197
+ } catch (error) {
198
+ console.error('Critical configuration missing:', error.message);
199
+ process.exit(1);
200
+ }
81
201
  ```
82
202
 
83
- #### Dynamic Environment Variables
84
- For dynamic or computed environment variables, you can define functions that resolve these variables asynchronously. This is particularly useful for variables that require fetching from an external source:
203
+ ## 🏗️ CI/CD Integration
204
+
205
+ ### GitHub Actions
206
+
207
+ ```yaml
208
+ name: Deploy
209
+ on: [push]
210
+ jobs:
211
+ deploy:
212
+ runs-on: ubuntu-latest
213
+ steps:
214
+ - uses: actions/checkout@v2
215
+ - name: Deploy with secrets
216
+ env:
217
+ API_KEY: ${{ secrets.API_KEY }}
218
+ DB_PASSWORD: ${{ secrets.DB_PASSWORD }}
219
+ run: |
220
+ npm install
221
+ npm run deploy
222
+ ```
223
+
224
+ ### GitLab CI
225
+
226
+ ```yaml
227
+ deploy:
228
+ stage: deploy
229
+ script:
230
+ - npm install
231
+ - npm run deploy
232
+ variables:
233
+ API_KEY: $CI_API_KEY
234
+ DB_PASSWORD: $CI_DB_PASSWORD
235
+ ```
236
+
237
+ ## 🎭 Testing
238
+
239
+ For testing, create a separate `test/assets/env.yml`:
85
240
 
86
241
  ```typescript
87
- // Define a function to fetch a variable
88
- const fetchDbHost = async () => {
89
- // Logic to fetch DB_HOST from an external service
90
- return 'dynamic.host';
91
- };
242
+ import { Qenv } from '@push.rocks/qenv';
243
+
244
+ describe('MyApp', () => {
245
+ let qenv: Qenv;
246
+
247
+ beforeEach(() => {
248
+ qenv = new Qenv('./test/assets', './test/assets', false);
249
+ });
250
+
251
+ it('should load test configuration', async () => {
252
+ const testVar = await qenv.getEnvVarOnDemand('TEST_VAR');
253
+ expect(testVar).toBe('test-value');
254
+ });
255
+ });
256
+ ```
257
+
258
+ ## 🔍 Debugging
259
+
260
+ Enable detailed logging to troubleshoot environment variable loading:
92
261
 
93
- // Use the function with getEnvVarOnDemand
94
- (async () => {
95
- const dbHost = await myQenv.getEnvVarOnDemand(fetchDbHost);
96
- console.log(dbHost); // 'dynamic.host'
97
- })();
262
+ ```typescript
263
+ const qenv = new Qenv();
264
+
265
+ // Check what's loaded
266
+ console.log('Required vars:', qenv.requiredEnvVars);
267
+ console.log('Available vars:', qenv.availableEnvVars);
268
+ console.log('Missing vars:', qenv.missingEnvVars);
269
+
270
+ // Access the logger
271
+ qenv.logger.log('info', 'Custom log message');
98
272
  ```
99
273
 
100
- #### Reading Variables from Docker Secrets or Other Sources
101
- Internally, `@push.rocks/qenv` supports reading from Docker secrets, providing flexibility for applications deployed in Docker environments. The module attempts to read each required variable from the process environment, a provided `env.yml` file, Docker secrets, or any custom source you integrate.
274
+ ## 📊 Real-World Example
275
+
276
+ Here's how you might use qenv in a production Node.js application:
277
+
278
+ ```typescript
279
+ import { Qenv } from '@push.rocks/qenv';
280
+ import { createServer } from './server';
281
+ import { connectDatabase } from './database';
282
+
283
+ async function bootstrap() {
284
+ // Initialize environment
285
+ const qenv = new Qenv();
286
+
287
+ // Load critical configuration
288
+ const config = {
289
+ port: await qenv.getEnvVarOnDemand('PORT') || '3000',
290
+ dbUrl: await qenv.getEnvVarOnDemandStrict('DATABASE_URL'),
291
+ apiKey: await qenv.getEnvVarOnDemandStrict('API_KEY'),
292
+ logLevel: await qenv.getEnvVarOnDemand('LOG_LEVEL') || 'info',
293
+ features: await qenv.getEnvVarOnDemandAsObject('FEATURE_FLAGS')
294
+ };
295
+
296
+ // Connect to database
297
+ await connectDatabase(config.dbUrl);
298
+
299
+ // Start server
300
+ const server = createServer(config);
301
+ server.listen(config.port, () => {
302
+ console.log(`🚀 Server running on port ${config.port}`);
303
+ });
304
+ }
305
+
306
+ bootstrap().catch(error => {
307
+ console.error('Failed to start application:', error);
308
+ process.exit(1);
309
+ });
310
+ ```
311
+
312
+ ## 🤝 API Reference
313
+
314
+ ### Class: `Qenv`
315
+
316
+ #### Constructor
317
+ ```typescript
318
+ new Qenv(
319
+ qenvFileBasePathArg?: string, // Path to qenv.yml (default: process.cwd())
320
+ envFileBasePathArg?: string, // Path to env.yml/json (default: same as qenv)
321
+ failOnMissing?: boolean // Exit on missing vars (default: true)
322
+ )
323
+ ```
324
+
325
+ #### Methods
326
+
327
+ | Method | Description | Returns |
328
+ |--------|-------------|---------|
329
+ | `getEnvVarOnDemand(name)` | Get environment variable value | `Promise<string \| undefined>` |
330
+ | `getEnvVarOnDemandStrict(name)` | Get variable or throw error | `Promise<string>` |
331
+ | `getEnvVarOnDemandSync(name)` | Synchronously get variable | `string \| undefined` |
332
+ | `getEnvVarOnDemandAsObject(name)` | Get variable as decoded object | `Promise<any>` |
102
333
 
103
- ### Conclusion
104
- `@push.rocks/qenv` simplifies handling environment variables across different environments, making your application's configuration more manageable and secure. By separating variable definitions from their values and providing support for dynamic resolution, `@push.rocks/qenv` offers a robust solution for managing configuration in Node.js projects. Whether you're working in a local development environment, CI/CD pipelines, or production, `@push.rocks/qenv` ensures that you have the correct configuration for the task at hand.
334
+ #### Properties
105
335
 
106
- Note: Due to the complexity and depth of `@push.rocks/qenv`, this documentation aims to cover general and advanced usage comprehensively. Please refer to the module's official documentation and typed definitions for further details on specific features or configuration options.
336
+ | Property | Type | Description |
337
+ |----------|------|-------------|
338
+ | `requiredEnvVars` | `string[]` | List of required variable names |
339
+ | `availableEnvVars` | `string[]` | List of found variable names |
340
+ | `missingEnvVars` | `string[]` | List of missing variable names |
341
+ | `keyValueObject` | `object` | All loaded variables as key-value pairs |
107
342
 
108
343
  ## License and Legal Information
109
344
 
@@ -122,4 +357,4 @@ Registered at District court Bremen HRB 35230 HB, Germany
122
357
 
123
358
  For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
124
359
 
125
- By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
360
+ By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@push.rocks/qenv',
6
- version: '6.1.0',
6
+ version: '6.1.2',
7
7
  description: 'A module for easily handling environment variables in Node.js projects with support for .yml and .json configuration.'
8
8
  }