@uniconvex/dotenv 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 ADDED
@@ -0,0 +1,23 @@
1
+ Copyright (c) 2015, Scott Motte
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ * Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
18
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
20
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
21
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
22
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md ADDED
@@ -0,0 +1,615 @@
1
+ # dotenv [![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv)
2
+
3
+ Dotenv is a zero-dependency module that loads environment variables from a `.env` file into [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env). Storing configuration in the environment separate from code is based on [The Twelve-Factor App](https://12factor.net/config) methodology.
4
+
5
+ [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard)
6
+ [![LICENSE](https://img.shields.io/github/license/motdotla/dotenv.svg)](LICENSE)
7
+ [![codecov](https://codecov.io/gh/motdotla/dotenv-expand/graph/badge.svg?token=pawWEyaMfg)](https://codecov.io/gh/motdotla/dotenv-expand)
8
+
9
+ * [🌱 Install](#-install)
10
+ * [🏗️ Usage (.env)](#%EF%B8%8F-usage)
11
+ * [🌴 Multiple Environments 🆕](#-manage-multiple-environments)
12
+ * [🚀 Deploying (encryption) 🆕](#-deploying)
13
+ * [📚 Examples](#-examples)
14
+ * [📖 Docs](#-documentation)
15
+ * [❓ FAQ](#-faq)
16
+ * [⏱️ Changelog](./CHANGELOG.md)
17
+
18
+ ## 🌱 Install
19
+
20
+ ```bash
21
+ npm install dotenv --save
22
+ ```
23
+
24
+ You can also use an npm-compatible package manager like yarn, bun or pnpm:
25
+
26
+ ```bash
27
+ yarn add dotenv
28
+ ```
29
+ ```bash
30
+ bun add dotenv
31
+ ```
32
+ ```bash
33
+ pnpm add dotenv
34
+ ```
35
+
36
+ Create a `.env` file in the root of your project (if using a monorepo structure like `apps/backend/app.js`, put it in the root of the folder where your `app.js` process runs):
37
+
38
+ ```dosini
39
+ S3_BUCKET="YOURS3BUCKET"
40
+ SECRET_KEY="YOURSECRETKEYGOESHERE"
41
+ ```
42
+
43
+ As early as possible in your application, import and configure dotenv:
44
+
45
+ ```javascript
46
+ require('dotenv').config()
47
+ console.log(process.env) // remove this after you've confirmed it is working
48
+ ```
49
+
50
+ .. [or using ES6?](#how-do-i-use-dotenv-with-import)
51
+
52
+ ```javascript
53
+ import 'dotenv/config'
54
+ ```
55
+
56
+ ES6 import if you need to set config options:
57
+
58
+ ```javascript
59
+ import dotenv from 'dotenv'
60
+
61
+ dotenv.config({ path: '/custom/path/to/.env' })
62
+ ```
63
+
64
+ That's it. `process.env` now has the keys and values you defined in your `.env` file:
65
+
66
+ ```javascript
67
+ require('dotenv').config()
68
+ // or import 'dotenv/config' if you're using ES6
69
+
70
+ ...
71
+
72
+ s3.getBucketCors({Bucket: process.env.S3_BUCKET}, function(err, data) {})
73
+ ```
74
+
75
+ ### Multiline values
76
+
77
+ If you need multiline variables, for example private keys, those are now supported (`>= v15.0.0`) with line breaks:
78
+
79
+ ```dosini
80
+ PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
81
+ ...
82
+ Kh9NV...
83
+ ...
84
+ -----END RSA PRIVATE KEY-----"
85
+ ```
86
+
87
+ Alternatively, you can double quote strings and use the `\n` character:
88
+
89
+ ```dosini
90
+ PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n"
91
+ ```
92
+
93
+ ### Comments
94
+
95
+ Comments may be added to your file on their own line or inline:
96
+
97
+ ```dosini
98
+ # This is a comment
99
+ SECRET_KEY=YOURSECRETKEYGOESHERE # comment
100
+ SECRET_HASH="something-with-a-#-hash"
101
+ ```
102
+
103
+ Comments begin where a `#` exists, so if your value contains a `#` please wrap it in quotes. This is a breaking change from `>= v15.0.0` and on.
104
+
105
+ ### Parsing
106
+
107
+ The engine which parses the contents of your file containing environment variables is available to use. It accepts a String or Buffer and will return an Object with the parsed keys and values.
108
+
109
+ ```javascript
110
+ const dotenv = require('dotenv')
111
+ const buf = Buffer.from('BASIC=basic')
112
+ const config = dotenv.parse(buf) // will return an object
113
+ console.log(typeof config, config) // object { BASIC : 'basic' }
114
+ ```
115
+
116
+ ### Preload
117
+
118
+ > Note: Consider using [`dotenvx`](https://github.com/dotenvx/dotenvx) instead of preloading. I am now doing (and recommending) so.
119
+ >
120
+ > It serves the same purpose (you do not need to require and load dotenv), adds better debugging, and works with ANY language, framework, or platform. – [motdotla](https://github.com/motdotla)
121
+
122
+ You can use the `--require` (`-r`) [command line option](https://nodejs.org/api/cli.html#-r---require-module) to preload dotenv. By doing this, you do not need to require and load dotenv in your application code.
123
+
124
+ ```bash
125
+ $ node -r dotenv/config your_script.js
126
+ ```
127
+
128
+ The configuration options below are supported as command line arguments in the format `dotenv_config_<option>=value`
129
+
130
+ ```bash
131
+ $ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env dotenv_config_debug=true
132
+ ```
133
+
134
+ Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.
135
+
136
+ ```bash
137
+ $ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js
138
+ ```
139
+
140
+ ```bash
141
+ $ DOTENV_CONFIG_ENCODING=latin1 DOTENV_CONFIG_DEBUG=true node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env
142
+ ```
143
+
144
+ ### Variable Expansion
145
+
146
+ Use [dotenvx](https://github.com/dotenvx/dotenvx) to use variable expansion.
147
+
148
+ Reference and expand variables already on your machine for use in your .env file.
149
+
150
+ ```ini
151
+ # .env
152
+ USERNAME="username"
153
+ DATABASE_URL="postgres://${USERNAME}@localhost/my_database"
154
+ ```
155
+ ```js
156
+ // index.js
157
+ console.log('DATABASE_URL', process.env.DATABASE_URL)
158
+ ```
159
+ ```sh
160
+ $ dotenvx run --debug -- node index.js
161
+ [dotenvx@0.14.1] injecting env (2) from .env
162
+ DATABASE_URL postgres://username@localhost/my_database
163
+ ```
164
+
165
+ ### Command Substitution
166
+
167
+ Use [dotenvx](https://github.com/dotenvx/dotenvx) to use command substitution.
168
+
169
+ Add the output of a command to one of your variables in your .env file.
170
+
171
+ ```ini
172
+ # .env
173
+ DATABASE_URL="postgres://$(whoami)@localhost/my_database"
174
+ ```
175
+ ```js
176
+ // index.js
177
+ console.log('DATABASE_URL', process.env.DATABASE_URL)
178
+ ```
179
+ ```sh
180
+ $ dotenvx run --debug -- node index.js
181
+ [dotenvx@0.14.1] injecting env (1) from .env
182
+ DATABASE_URL postgres://yourusername@localhost/my_database
183
+ ```
184
+
185
+ ### Syncing
186
+
187
+ You need to keep `.env` files in sync between machines, environments, or team members? Use [dotenvx](https://github.com/dotenvx/dotenvx) to encrypt your `.env` files and safely include them in source control. This still subscribes to the twelve-factor app rules by generating a decryption key separate from code.
188
+
189
+ ### Multiple Environments
190
+
191
+ Use [dotenvx](https://github.com/dotenvx/dotenvx) to generate `.env.ci`, `.env.production` files, and more.
192
+
193
+ ### Deploying
194
+
195
+ You need to deploy your secrets in a cloud-agnostic manner? Use [dotenvx](https://github.com/dotenvx/dotenvx) to generate a private decryption key that is set on your production server.
196
+
197
+ ## 🌴 Manage Multiple Environments
198
+
199
+ Use [dotenvx](https://github.com/dotenvx/dotenvx)
200
+
201
+ Run any environment locally. Create a `.env.ENVIRONMENT` file and use `--env-file` to load it. It's straightforward, yet flexible.
202
+
203
+ ```bash
204
+ $ echo "HELLO=production" > .env.production
205
+ $ echo "console.log('Hello ' + process.env.HELLO)" > index.js
206
+
207
+ $ dotenvx run --env-file=.env.production -- node index.js
208
+ Hello production
209
+ > ^^
210
+ ```
211
+
212
+ or with multiple .env files
213
+
214
+ ```bash
215
+ $ echo "HELLO=local" > .env.local
216
+ $ echo "HELLO=World" > .env
217
+ $ echo "console.log('Hello ' + process.env.HELLO)" > index.js
218
+
219
+ $ dotenvx run --env-file=.env.local --env-file=.env -- node index.js
220
+ Hello local
221
+ ```
222
+
223
+ [more environment examples](https://dotenvx.com/docs/quickstart/environments)
224
+
225
+ ## 🚀 Deploying
226
+
227
+ Use [dotenvx](https://github.com/dotenvx/dotenvx).
228
+
229
+ Add encryption to your `.env` files with a single command. Pass the `--encrypt` flag.
230
+
231
+ ```
232
+ $ dotenvx set HELLO Production --encrypt -f .env.production
233
+ $ echo "console.log('Hello ' + process.env.HELLO)" > index.js
234
+
235
+ $ DOTENV_PRIVATE_KEY_PRODUCTION="<.env.production private key>" dotenvx run -- node index.js
236
+ [dotenvx] injecting env (2) from .env.production
237
+ Hello Production
238
+ ```
239
+
240
+ [learn more](https://github.com/dotenvx/dotenvx?tab=readme-ov-file#encryption)
241
+
242
+ ## 📚 Examples
243
+
244
+ See [examples](https://github.com/dotenv-org/examples) of using dotenv with various frameworks, languages, and configurations.
245
+
246
+ * [nodejs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs)
247
+ * [nodejs (debug on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-debug)
248
+ * [nodejs (override on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-override)
249
+ * [nodejs (processEnv override)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-custom-target)
250
+ * [esm](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm)
251
+ * [esm (preload)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm-preload)
252
+ * [typescript](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript)
253
+ * [typescript parse](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-parse)
254
+ * [typescript config](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-config)
255
+ * [webpack](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack)
256
+ * [webpack (plugin)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack2)
257
+ * [react](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react)
258
+ * [react (typescript)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react-typescript)
259
+ * [express](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-express)
260
+ * [nestjs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nestjs)
261
+ * [fastify](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-fastify)
262
+
263
+ ## 📖 Documentation
264
+
265
+ Dotenv exposes four functions:
266
+
267
+ * `config`
268
+ * `parse`
269
+ * `populate`
270
+
271
+ ### Config
272
+
273
+ `config` will read your `.env` file, parse the contents, assign it to
274
+ [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
275
+ and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed.
276
+
277
+ ```js
278
+ const result = dotenv.config()
279
+
280
+ if (result.error) {
281
+ throw result.error
282
+ }
283
+
284
+ console.log(result.parsed)
285
+ ```
286
+
287
+ You can additionally, pass options to `config`.
288
+
289
+ #### Options
290
+
291
+ ##### path
292
+
293
+ Default: `path.resolve(process.cwd(), '.env')`
294
+
295
+ Specify a custom path if your file containing environment variables is located elsewhere.
296
+
297
+ ```js
298
+ require('dotenv').config({ path: '/custom/path/to/.env' })
299
+ ```
300
+
301
+ By default, `config` will look for a file called .env in the current working directory.
302
+
303
+ Pass in multiple files as an array, and they will be parsed in order and combined with `process.env` (or `option.processEnv`, if set). The first value set for a variable will win, unless the `options.override` flag is set, in which case the last value set will win. If a value already exists in `process.env` and the `options.override` flag is NOT set, no changes will be made to that value.
304
+
305
+ ```js
306
+ require('dotenv').config({ path: ['.env.local', '.env'] })
307
+ ```
308
+
309
+ ##### quiet
310
+
311
+ Default: `false`
312
+
313
+ Suppress runtime logging message.
314
+
315
+ ```js
316
+ // index.js
317
+ require('dotenv').config({ quiet: false }) // change to true to suppress
318
+ console.log(`Hello ${process.env.HELLO}`)
319
+ ```
320
+
321
+ ```ini
322
+ # .env
323
+ .env
324
+ ```
325
+
326
+ ```sh
327
+ $ node index.js
328
+ [dotenv@17.0.0] injecting env (1) from .env
329
+ Hello World
330
+ ```
331
+
332
+ ##### encoding
333
+
334
+ Default: `utf8`
335
+
336
+ Specify the encoding of your file containing environment variables.
337
+
338
+ ```js
339
+ require('dotenv').config({ encoding: 'latin1' })
340
+ ```
341
+
342
+ ##### debug
343
+
344
+ Default: `false`
345
+
346
+ Turn on logging to help debug why certain keys or values are not being set as you expect.
347
+
348
+ ```js
349
+ require('dotenv').config({ debug: process.env.DEBUG })
350
+ ```
351
+
352
+ ##### override
353
+
354
+ Default: `false`
355
+
356
+ Override any environment variables that have already been set on your machine with values from your .env file(s). If multiple files have been provided in `option.path` the override will also be used as each file is combined with the next. Without `override` being set, the first value wins. With `override` set the last value wins.
357
+
358
+ ```js
359
+ require('dotenv').config({ override: true })
360
+ ```
361
+
362
+ ##### processEnv
363
+
364
+ Default: `process.env`
365
+
366
+ Specify an object to write your environment variables to. Defaults to `process.env` environment variables.
367
+
368
+ ```js
369
+ const myObject = {}
370
+ require('dotenv').config({ processEnv: myObject })
371
+
372
+ console.log(myObject) // values from .env
373
+ console.log(process.env) // this was not changed or written to
374
+ ```
375
+
376
+ ### Parse
377
+
378
+ The engine which parses the contents of your file containing environment
379
+ variables is available to use. It accepts a String or Buffer and will return
380
+ an Object with the parsed keys and values.
381
+
382
+ ```js
383
+ const dotenv = require('dotenv')
384
+ const buf = Buffer.from('BASIC=basic')
385
+ const config = dotenv.parse(buf) // will return an object
386
+ console.log(typeof config, config) // object { BASIC : 'basic' }
387
+ ```
388
+
389
+ #### Options
390
+
391
+ ##### debug
392
+
393
+ Default: `false`
394
+
395
+ Turn on logging to help debug why certain keys or values are not being set as you expect.
396
+
397
+ ```js
398
+ const dotenv = require('dotenv')
399
+ const buf = Buffer.from('hello world')
400
+ const opt = { debug: true }
401
+ const config = dotenv.parse(buf, opt)
402
+ // expect a debug message because the buffer is not in KEY=VAL form
403
+ ```
404
+
405
+ ### Populate
406
+
407
+ The engine which populates the contents of your .env file to `process.env` is available for use. It accepts a target, a source, and options. This is useful for power users who want to supply their own objects.
408
+
409
+ For example, customizing the source:
410
+
411
+ ```js
412
+ const dotenv = require('dotenv')
413
+ const parsed = { HELLO: 'world' }
414
+
415
+ dotenv.populate(process.env, parsed)
416
+
417
+ console.log(process.env.HELLO) // world
418
+ ```
419
+
420
+ For example, customizing the source AND target:
421
+
422
+ ```js
423
+ const dotenv = require('dotenv')
424
+ const parsed = { HELLO: 'universe' }
425
+ const target = { HELLO: 'world' } // empty object
426
+
427
+ dotenv.populate(target, parsed, { override: true, debug: true })
428
+
429
+ console.log(target) // { HELLO: 'universe' }
430
+ ```
431
+
432
+ #### options
433
+
434
+ ##### Debug
435
+
436
+ Default: `false`
437
+
438
+ Turn on logging to help debug why certain keys or values are not being populated as you expect.
439
+
440
+ ##### override
441
+
442
+ Default: `false`
443
+
444
+ Override any environment variables that have already been set.
445
+
446
+ ## ❓ FAQ
447
+
448
+ ### Why is the `.env` file not loading my environment variables successfully?
449
+
450
+ Most likely your `.env` file is not in the correct place. [See this stack overflow](https://stackoverflow.com/questions/42335016/dotenv-file-is-not-loading-environment-variables).
451
+
452
+ Turn on debug mode and try again..
453
+
454
+ ```js
455
+ require('dotenv').config({ debug: true })
456
+ ```
457
+
458
+ You will receive a helpful error outputted to your console.
459
+
460
+ ### Should I commit my `.env` file?
461
+
462
+ No. We **strongly** recommend against committing your `.env` file to version
463
+ control. It should only include environment-specific values such as database
464
+ passwords or API keys. Your production database should have a different
465
+ password than your development database.
466
+
467
+ ### Should I have multiple `.env` files?
468
+
469
+ We recommend creating one `.env` file per environment. Use `.env` for local/development, `.env.production` for production and so on. This still follows the twelve factor principles as each is attributed individually to its own environment. Avoid custom set ups that work in inheritance somehow (`.env.production` inherits values form `.env` for example). It is better to duplicate values if necessary across each `.env.environment` file.
470
+
471
+ > In a twelve-factor app, env vars are granular controls, each fully orthogonal to other env vars. They are never grouped together as “environments”, but instead are independently managed for each deploy. This is a model that scales up smoothly as the app naturally expands into more deploys over its lifetime.
472
+ >
473
+ > – [The Twelve-Factor App](http://12factor.net/config)
474
+
475
+ ### What rules does the parsing engine follow?
476
+
477
+ The parsing engine currently supports the following rules:
478
+
479
+ - `BASIC=basic` becomes `{BASIC: 'basic'}`
480
+ - empty lines are skipped
481
+ - lines beginning with `#` are treated as comments
482
+ - `#` marks the beginning of a comment (unless when the value is wrapped in quotes)
483
+ - empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`)
484
+ - inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`)
485
+ - whitespace is removed from both ends of unquoted values (see more on [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)) (`FOO= some value ` becomes `{FOO: 'some value'}`)
486
+ - single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`)
487
+ - single and double quoted values maintain whitespace from both ends (`FOO=" some value "` becomes `{FOO: ' some value '}`)
488
+ - double quoted values expand new lines (`MULTILINE="new\nline"` becomes
489
+
490
+ ```
491
+ {MULTILINE: 'new
492
+ line'}
493
+ ```
494
+
495
+ - backticks are supported (`` BACKTICK_KEY=`This has 'single' and "double" quotes inside of it.` ``)
496
+
497
+ ### What happens to environment variables that were already set?
498
+
499
+ By default, we will never modify any environment variables that have already been set. In particular, if there is a variable in your `.env` file which collides with one that already exists in your environment, then that variable will be skipped.
500
+
501
+ If instead, you want to override `process.env` use the `override` option.
502
+
503
+ ```javascript
504
+ require('dotenv').config({ override: true })
505
+ ```
506
+
507
+ ### How come my environment variables are not showing up for React?
508
+
509
+ Your React code is run in Webpack, where the `fs` module or even the `process` global itself are not accessible out-of-the-box. `process.env` can only be injected through Webpack configuration.
510
+
511
+ If you are using [`react-scripts`](https://www.npmjs.com/package/react-scripts), which is distributed through [`create-react-app`](https://create-react-app.dev/), it has dotenv built in but with a quirk. Preface your environment variables with `REACT_APP_`. See [this stack overflow](https://stackoverflow.com/questions/42182577/is-it-possible-to-use-dotenv-in-a-react-project) for more details.
512
+
513
+ If you are using other frameworks (e.g. Next.js, Gatsby...), you need to consult their documentation for how to inject environment variables into the client.
514
+
515
+ ### Can I customize/write plugins for dotenv?
516
+
517
+ Yes! `dotenv.config()` returns an object representing the parsed `.env` file. This gives you everything you need to continue setting values on `process.env`. For example:
518
+
519
+ ```js
520
+ const dotenv = require('dotenv')
521
+ const variableExpansion = require('dotenv-expand')
522
+ const myEnv = dotenv.config()
523
+ variableExpansion(myEnv)
524
+ ```
525
+
526
+ ### How do I use dotenv with `import`?
527
+
528
+ Simply..
529
+
530
+ ```javascript
531
+ // index.mjs (ESM)
532
+ import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
533
+ import express from 'express'
534
+ ```
535
+
536
+ A little background..
537
+
538
+ > When you run a module containing an `import` declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed.
539
+ >
540
+ > – [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
541
+
542
+ What does this mean in plain language? It means you would think the following would work but it won't.
543
+
544
+ `errorReporter.mjs`:
545
+ ```js
546
+ class Client {
547
+ constructor (apiKey) {
548
+ console.log('apiKey', apiKey)
549
+
550
+ this.apiKey = apiKey
551
+ }
552
+ }
553
+
554
+ export default new Client(process.env.API_KEY)
555
+ ```
556
+ `index.mjs`:
557
+ ```js
558
+ // Note: this is INCORRECT and will not work
559
+ import * as dotenv from 'dotenv'
560
+ dotenv.config()
561
+
562
+ import errorReporter from './errorReporter.mjs' // process.env.API_KEY will be blank!
563
+ ```
564
+
565
+ `process.env.API_KEY` will be blank.
566
+
567
+ Instead, `index.mjs` should be written as..
568
+
569
+ ```js
570
+ import 'dotenv/config'
571
+
572
+ import errorReporter from './errorReporter.mjs'
573
+ ```
574
+
575
+ Does that make sense? It's a bit unintuitive, but it is how importing of ES6 modules work. Here is a [working example of this pitfall](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-es6-import-pitfall).
576
+
577
+ There are two alternatives to this approach:
578
+
579
+ 1. Preload with dotenvx: `dotenvx run -- node index.js` (_Note: you do not need to `import` dotenv with this approach_)
580
+ 2. Create a separate file that will execute `config` first as outlined in [this comment on #133](https://github.com/motdotla/dotenv/issues/133#issuecomment-255298822)
581
+
582
+ ### Why am I getting the error `Module not found: Error: Can't resolve 'crypto|os|path'`?
583
+
584
+ You are using dotenv on the front-end and have not included a polyfill. Webpack < 5 used to include these for you. Do the following:
585
+
586
+ ```bash
587
+ npm install node-polyfill-webpack-plugin
588
+ ```
589
+
590
+ Configure your `webpack.config.js` to something like the following.
591
+
592
+ ```js
593
+ require('dotenv').config()
594
+
595
+ const path = require('path');
596
+ const webpack = require('webpack')
597
+
598
+ const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
599
+
600
+ module.exports = {
601
+ mode: 'development',
602
+ entry: './src/index.ts',
603
+ output: {
604
+ filename: 'bundle.js',
605
+ path: path.resolve(__dirname, 'dist'),
606
+ },
607
+ plugins: [
608
+ new NodePolyfillPlugin(),
609
+ new webpack.DefinePlugin({
610
+ 'process.env': {
611
+ HELLO: JSON.stringify(process.env.HELLO)
612
+ }
613
+ }),
614
+ ]
615
+ };
package/config.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/config.js ADDED
@@ -0,0 +1,9 @@
1
+ (function () {
2
+ require('./lib/main').config(
3
+ Object.assign(
4
+ {},
5
+ require('./lib/env-options'),
6
+ require('./lib/cli-options')(process.argv)
7
+ )
8
+ )
9
+ })()
@@ -0,0 +1,17 @@
1
+ const re = /^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/
2
+
3
+ module.exports = function optionMatcher (args) {
4
+ const options = args.reduce(function (acc, cur) {
5
+ const matches = cur.match(re)
6
+ if (matches) {
7
+ acc[matches[1]] = matches[2]
8
+ }
9
+ return acc
10
+ }, {})
11
+
12
+ if (!('quiet' in options)) {
13
+ options.quiet = 'true'
14
+ }
15
+
16
+ return options
17
+ }
@@ -0,0 +1,28 @@
1
+ // ../config.js accepts options via environment variables
2
+ const options = {}
3
+
4
+ if (process.env.DOTENV_CONFIG_ENCODING != null) {
5
+ options.encoding = process.env.DOTENV_CONFIG_ENCODING
6
+ }
7
+
8
+ if (process.env.DOTENV_CONFIG_PATH != null) {
9
+ options.path = process.env.DOTENV_CONFIG_PATH
10
+ }
11
+
12
+ if (process.env.DOTENV_CONFIG_QUIET != null) {
13
+ options.quiet = process.env.DOTENV_CONFIG_QUIET
14
+ }
15
+
16
+ if (process.env.DOTENV_CONFIG_DEBUG != null) {
17
+ options.debug = process.env.DOTENV_CONFIG_DEBUG
18
+ }
19
+
20
+ if (process.env.DOTENV_CONFIG_OVERRIDE != null) {
21
+ options.override = process.env.DOTENV_CONFIG_OVERRIDE
22
+ }
23
+
24
+ if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) {
25
+ options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY
26
+ }
27
+
28
+ module.exports = options
package/lib/main.d.ts ADDED
@@ -0,0 +1,179 @@
1
+ // TypeScript Version: 3.0
2
+ /// <reference types="node" />
3
+ import type { URL } from 'url';
4
+
5
+ export interface DotenvParseOutput {
6
+ [name: string]: string;
7
+ }
8
+
9
+ export interface DotenvPopulateOutput {
10
+ [name: string]: string;
11
+ }
12
+
13
+ /**
14
+ * Parses a string or buffer in the .env file format into an object.
15
+ *
16
+ * See https://dotenvx.com/docs
17
+ *
18
+ * @param src - contents to be parsed. example: `'DB_HOST=localhost'`
19
+ * @returns an object with keys and values based on `src`. example: `{ DB_HOST : 'localhost' }`
20
+ */
21
+ export function parse<T extends DotenvParseOutput = DotenvParseOutput>(
22
+ src: string | Buffer
23
+ ): T;
24
+
25
+ export interface DotenvConfigOptions {
26
+ /**
27
+ * Default: `path.resolve(process.cwd(), '.env')`
28
+ *
29
+ * Specify a custom path if your file containing environment variables is located elsewhere.
30
+ * Can also be an array of strings, specifying multiple paths.
31
+ *
32
+ * example: `require('dotenv').config({ path: '/custom/path/to/.env' })`
33
+ * example: `require('dotenv').config({ path: ['/path/to/first.env', '/path/to/second.env'] })`
34
+ */
35
+ path?: string | string[] | URL;
36
+
37
+ /**
38
+ * Default: `utf8`
39
+ *
40
+ * Specify the encoding of your file containing environment variables.
41
+ *
42
+ * example: `require('dotenv').config({ encoding: 'latin1' })`
43
+ */
44
+ encoding?: string;
45
+
46
+ /**
47
+ * Default: `false`
48
+ *
49
+ * Suppress all output (except errors).
50
+ *
51
+ * example: `require('dotenv').config({ quiet: true })`
52
+ */
53
+ quiet?: boolean;
54
+
55
+ /**
56
+ * Default: `false`
57
+ *
58
+ * Turn on logging to help debug why certain keys or values are not being set as you expect.
59
+ *
60
+ * example: `require('dotenv').config({ debug: process.env.DEBUG })`
61
+ */
62
+ debug?: boolean;
63
+
64
+ /**
65
+ * Default: `false`
66
+ *
67
+ * Override any environment variables that have already been set on your machine with values from your .env file.
68
+ *
69
+ * example: `require('dotenv').config({ override: true })`
70
+ */
71
+ override?: boolean;
72
+
73
+ /**
74
+ * Default: `process.env`
75
+ *
76
+ * Specify an object to write your secrets to. Defaults to process.env environment variables.
77
+ *
78
+ * example: `const processEnv = {}; require('dotenv').config({ processEnv: processEnv })`
79
+ */
80
+ processEnv?: DotenvPopulateInput;
81
+
82
+ /**
83
+ * Default: `undefined`
84
+ *
85
+ * Pass the DOTENV_KEY directly to config options. Defaults to looking for process.env.DOTENV_KEY environment variable. Note this only applies to decrypting .env.vault files. If passed as null or undefined, or not passed at all, dotenv falls back to its traditional job of parsing a .env file.
86
+ *
87
+ * example: `require('dotenv').config({ DOTENV_KEY: 'dotenv://:key_1234…@dotenvx.com/vault/.env.vault?environment=production' })`
88
+ */
89
+ DOTENV_KEY?: string;
90
+ }
91
+
92
+ export interface DotenvConfigOutput {
93
+ error?: DotenvError;
94
+ parsed?: DotenvParseOutput;
95
+ }
96
+
97
+ type DotenvError = Error & {
98
+ code:
99
+ | 'MISSING_DATA'
100
+ | 'INVALID_DOTENV_KEY'
101
+ | 'NOT_FOUND_DOTENV_ENVIRONMENT'
102
+ | 'DECRYPTION_FAILED'
103
+ | 'OBJECT_REQUIRED';
104
+ }
105
+
106
+ export interface DotenvPopulateOptions {
107
+ /**
108
+ * Default: `false`
109
+ *
110
+ * Turn on logging to help debug why certain keys or values are not being set as you expect.
111
+ *
112
+ * example: `require('dotenv').config({ debug: process.env.DEBUG })`
113
+ */
114
+ debug?: boolean;
115
+
116
+ /**
117
+ * Default: `false`
118
+ *
119
+ * Override any environment variables that have already been set on your machine with values from your .env file.
120
+ *
121
+ * example: `require('dotenv').config({ override: true })`
122
+ */
123
+ override?: boolean;
124
+ }
125
+
126
+ export interface DotenvPopulateInput {
127
+ [name: string]: string;
128
+ }
129
+
130
+ /**
131
+ * Loads `.env` file contents into process.env by default. If `DOTENV_KEY` is present, it smartly attempts to load encrypted `.env.vault` file contents into process.env.
132
+ *
133
+ * See https://dotenvx.com/docs
134
+ *
135
+ * @param options - additional options. example: `{ path: './custom/path', encoding: 'latin1', quiet: false, debug: true, override: false }`
136
+ * @returns an object with a `parsed` key if successful or `error` key if an error occurred. example: { parsed: { KEY: 'value' } }
137
+ *
138
+ */
139
+ export function config(options?: DotenvConfigOptions): DotenvConfigOutput;
140
+
141
+ /**
142
+ * Loads `.env` file contents into process.env.
143
+ *
144
+ * See https://dotenvx.com/docs
145
+ *
146
+ * @param options - additional options. example: `{ path: './custom/path', encoding: 'latin1', quiet: false, debug: true, override: false }`
147
+ * @returns an object with a `parsed` key if successful or `error` key if an error occurred. example: { parsed: { KEY: 'value' } }
148
+ *
149
+ */
150
+ export function configDotenv(options?: DotenvConfigOptions): DotenvConfigOutput;
151
+
152
+ /**
153
+ * Loads `source` json contents into `target` like process.env.
154
+ *
155
+ * See https://dotenvx.com/docs
156
+ *
157
+ * @param processEnv - the target JSON object. in most cases use process.env but you can also pass your own JSON object
158
+ * @param parsed - the source JSON object
159
+ * @param options - additional options. example: `{ quiet: false, debug: true, override: false }`
160
+ * @returns an object with the keys and values that were actually set
161
+ *
162
+ */
163
+ export function populate(
164
+ processEnv: DotenvPopulateInput,
165
+ parsed: DotenvPopulateInput,
166
+ options?: DotenvConfigOptions
167
+ ): DotenvPopulateOutput;
168
+
169
+ /**
170
+ * Decrypt ciphertext
171
+ *
172
+ * See https://dotenvx.com/docs
173
+ *
174
+ * @param encrypted - the encrypted ciphertext string
175
+ * @param keyStr - the decryption key string
176
+ * @returns {string}
177
+ *
178
+ */
179
+ export function decrypt(encrypted: string, keyStr: string): string;
package/lib/main.js ADDED
@@ -0,0 +1,436 @@
1
+ const fs = require('fs')
2
+ const path = require('path')
3
+ const os = require('os')
4
+ const crypto = require('crypto')
5
+ const vconfig = require('@reimorg/config')
6
+ const packageJson = require('../package.json')
7
+
8
+ const version = packageJson.version
9
+
10
+ // Array of tips to display randomly
11
+ const TIPS = [
12
+ '🔐 encrypt with Dotenvx: https://dotenvx.com',
13
+ '🔐 prevent committing .env to code: https://dotenvx.com/precommit',
14
+ '🔐 prevent building .env in docker: https://dotenvx.com/prebuild',
15
+ '📡 add observability to secrets: https://dotenvx.com/ops',
16
+ '👥 sync secrets across teammates & machines: https://dotenvx.com/ops',
17
+ '🗂️ backup and recover secrets: https://dotenvx.com/ops',
18
+ '✅ audit secrets and track compliance: https://dotenvx.com/ops',
19
+ '🔄 add secrets lifecycle management: https://dotenvx.com/ops',
20
+ '🔑 add access controls to secrets: https://dotenvx.com/ops',
21
+ '🛠️ run anywhere with `dotenvx run -- yourcommand`',
22
+ '⚙️ specify custom .env file path with { path: \'/custom/path/.env\' }',
23
+ '⚙️ enable debug logging with { debug: true }',
24
+ '⚙️ override existing env vars with { override: true }',
25
+ '⚙️ suppress all logs with { quiet: true }',
26
+ '⚙️ write to custom object with { processEnv: myObject }',
27
+ '⚙️ load multiple .env files with { path: [\'.env.local\', \'.env\'] }'
28
+ ]
29
+
30
+ // Get a random tip from the tips array
31
+ function _getRandomTip () {
32
+ return TIPS[Math.floor(Math.random() * TIPS.length)]
33
+ }
34
+
35
+ function parseBoolean (value) {
36
+ if (typeof value === 'string') {
37
+ return !['false', '0', 'no', 'off', ''].includes(value.toLowerCase())
38
+ }
39
+ return Boolean(value)
40
+ }
41
+
42
+ function supportsAnsi () {
43
+ return process.stdout.isTTY // && process.env.TERM !== 'dumb'
44
+ }
45
+
46
+ function dim (text) {
47
+ return supportsAnsi() ? `\x1b[2m${text}\x1b[0m` : text
48
+ }
49
+
50
+ const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg
51
+
52
+ // Parse src into an Object
53
+ function parse (src) {
54
+ const obj = {}
55
+
56
+ // Convert buffer to string
57
+ let lines = src.toString()
58
+
59
+ // Convert line breaks to same format
60
+ lines = lines.replace(/\r\n?/mg, '\n')
61
+
62
+ let match
63
+ while ((match = LINE.exec(lines)) != null) {
64
+ const key = match[1]
65
+
66
+ // Default undefined or null to empty string
67
+ let value = (match[2] || '')
68
+
69
+ // Remove whitespace
70
+ value = value.trim()
71
+
72
+ // Check if double quoted
73
+ const maybeQuote = value[0]
74
+
75
+ // Remove surrounding quotes
76
+ value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2')
77
+
78
+ // Expand newlines if double quoted
79
+ if (maybeQuote === '"') {
80
+ value = value.replace(/\\n/g, '\n')
81
+ value = value.replace(/\\r/g, '\r')
82
+ }
83
+
84
+ // Add to object
85
+ obj[key] = value
86
+ }
87
+
88
+ return obj
89
+ }
90
+
91
+ function _parseVault (options) {
92
+ options = options || {}
93
+
94
+ const vaultPath = _vaultPath(options)
95
+ options.path = vaultPath // parse .env.vault
96
+ const result = DotenvModule.configDotenv(options)
97
+ if (!result.parsed) {
98
+ const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`)
99
+ err.code = 'MISSING_DATA'
100
+ throw err
101
+ }
102
+
103
+ // handle scenario for comma separated keys - for use with key rotation
104
+ // example: DOTENV_KEY="dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod"
105
+ const keys = _dotenvKey(options).split(',')
106
+ const length = keys.length
107
+
108
+ let decrypted
109
+ for (let i = 0; i < length; i++) {
110
+ try {
111
+ // Get full key
112
+ const key = keys[i].trim()
113
+
114
+ // Get instructions for decrypt
115
+ const attrs = _instructions(result, key)
116
+
117
+ // Decrypt
118
+ decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key)
119
+
120
+ break
121
+ } catch (error) {
122
+ // last key
123
+ if (i + 1 >= length) {
124
+ throw error
125
+ }
126
+ // try next key
127
+ }
128
+ }
129
+
130
+ // Parse decrypted .env string
131
+ return DotenvModule.parse(decrypted)
132
+ }
133
+
134
+ function _warn (message) {
135
+ console.error(`[dotenv@${version}][WARN] ${message}`)
136
+ }
137
+
138
+ function _debug (message) {
139
+ console.log(`[dotenv@${version}][DEBUG] ${message}`)
140
+ }
141
+
142
+ function _log (message) {
143
+ console.log(`[dotenv@${version}] ${message}`)
144
+ }
145
+
146
+ function _dotenvKey (options) {
147
+ // prioritize developer directly setting options.DOTENV_KEY
148
+ if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
149
+ return options.DOTENV_KEY
150
+ }
151
+
152
+ // secondary infra already contains a DOTENV_KEY environment variable
153
+ if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
154
+ return process.env.DOTENV_KEY
155
+ }
156
+
157
+ // fallback to empty string
158
+ return ''
159
+ }
160
+
161
+ function _instructions (result, dotenvKey) {
162
+ // Parse DOTENV_KEY. Format is a URI
163
+ let uri
164
+ try {
165
+ uri = new URL(dotenvKey)
166
+ } catch (error) {
167
+ if (error.code === 'ERR_INVALID_URL') {
168
+ const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development')
169
+ err.code = 'INVALID_DOTENV_KEY'
170
+ throw err
171
+ }
172
+
173
+ throw error
174
+ }
175
+
176
+ // Get decrypt key
177
+ const key = uri.password
178
+ if (!key) {
179
+ const err = new Error('INVALID_DOTENV_KEY: Missing key part')
180
+ err.code = 'INVALID_DOTENV_KEY'
181
+ throw err
182
+ }
183
+
184
+ // Get environment
185
+ const environment = uri.searchParams.get('environment')
186
+ if (!environment) {
187
+ const err = new Error('INVALID_DOTENV_KEY: Missing environment part')
188
+ err.code = 'INVALID_DOTENV_KEY'
189
+ throw err
190
+ }
191
+
192
+ // Get ciphertext payload
193
+ const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`
194
+ const ciphertext = result.parsed[environmentKey] // DOTENV_VAULT_PRODUCTION
195
+ if (!ciphertext) {
196
+ const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`)
197
+ err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'
198
+ throw err
199
+ }
200
+
201
+ return { ciphertext, key }
202
+ }
203
+
204
+ function _vaultPath (options) {
205
+ let possibleVaultPath = null
206
+
207
+ if (options && options.path && options.path.length > 0) {
208
+ if (Array.isArray(options.path)) {
209
+ for (const filepath of options.path) {
210
+ if (fs.existsSync(filepath)) {
211
+ possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`
212
+ }
213
+ }
214
+ } else {
215
+ possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`
216
+ }
217
+ } else {
218
+ possibleVaultPath = path.resolve(process.cwd(), '.env.vault')
219
+ }
220
+
221
+ if (fs.existsSync(possibleVaultPath)) {
222
+ return possibleVaultPath
223
+ }
224
+
225
+ return null
226
+ }
227
+
228
+ function _resolveHome (envPath) {
229
+ return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath
230
+ }
231
+
232
+ function _configVault (options) {
233
+ const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || (options && options.debug))
234
+ const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || (options && options.quiet))
235
+
236
+ if (debug || !quiet) {
237
+ _log('Loading env from encrypted .env.vault')
238
+ }
239
+
240
+ const parsed = DotenvModule._parseVault(options)
241
+
242
+ let processEnv = process.env
243
+ if (options && options.processEnv != null) {
244
+ processEnv = options.processEnv
245
+ }
246
+
247
+ DotenvModule.populate(processEnv, parsed, options)
248
+
249
+ return { parsed }
250
+ }
251
+
252
+ function configDotenv (options) {
253
+ const dotenvPath = path.resolve(process.cwd(), '.env')
254
+ let encoding = 'utf8'
255
+ let processEnv = process.env
256
+ if (options && options.processEnv != null) {
257
+ processEnv = options.processEnv
258
+ }
259
+ let debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || (options && options.debug))
260
+ let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || (options && options.quiet))
261
+
262
+ if (options && options.encoding) {
263
+ encoding = options.encoding
264
+ } else {
265
+ if (debug) {
266
+ _debug('No encoding is specified. UTF-8 is used by default')
267
+ }
268
+ }
269
+
270
+ let optionPaths = [dotenvPath] // default, look for .env
271
+ if (options && options.path) {
272
+ if (!Array.isArray(options.path)) {
273
+ optionPaths = [_resolveHome(options.path)]
274
+ } else {
275
+ optionPaths = [] // reset default
276
+ for (const filepath of options.path) {
277
+ optionPaths.push(_resolveHome(filepath))
278
+ }
279
+ }
280
+ }
281
+
282
+ // Build the parsed data in a temporary object (because we need to return it). Once we have the final
283
+ // parsed data, we will combine it with process.env (or options.processEnv if provided).
284
+ let lastError
285
+ const parsedAll = {}
286
+ for (const path of optionPaths) {
287
+ try {
288
+ // Specifying an encoding returns a string instead of a buffer
289
+ const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }))
290
+
291
+ DotenvModule.populate(parsedAll, parsed, options)
292
+ } catch (e) {
293
+ if (debug) {
294
+ _debug(`Failed to load ${path} ${e.message}`)
295
+ }
296
+ lastError = e
297
+ }
298
+ }
299
+
300
+ const populated = DotenvModule.populate(processEnv, parsedAll, options)
301
+
302
+ // handle user settings DOTENV_CONFIG_ options inside .env file(s)
303
+ debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug)
304
+ quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet)
305
+
306
+ if (debug || !quiet) {
307
+ const keysCount = Object.keys(populated).length
308
+ const shortPaths = []
309
+ for (const filePath of optionPaths) {
310
+ try {
311
+ const relative = path.relative(process.cwd(), filePath)
312
+ shortPaths.push(relative)
313
+ } catch (e) {
314
+ if (debug) {
315
+ _debug(`Failed to load ${filePath} ${e.message}`)
316
+ }
317
+ lastError = e
318
+ }
319
+ }
320
+
321
+ _log(`injecting env (${keysCount}) from ${shortPaths.join(',')} ${dim(`-- tip: ${_getRandomTip()}`)}`)
322
+ }
323
+
324
+ if (lastError) {
325
+ return { parsed: parsedAll, error: lastError }
326
+ } else {
327
+ return { parsed: parsedAll }
328
+ }
329
+ }
330
+
331
+ // Populates process.env from .env file
332
+ function config (options) {
333
+ vconfig.get();
334
+ // fallback to original dotenv if DOTENV_KEY is not set
335
+ if (_dotenvKey(options).length === 0) {
336
+ return DotenvModule.configDotenv(options)
337
+ }
338
+
339
+ const vaultPath = _vaultPath(options)
340
+
341
+ // dotenvKey exists but .env.vault file does not exist
342
+ if (!vaultPath) {
343
+ _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`)
344
+
345
+ return DotenvModule.configDotenv(options)
346
+ }
347
+
348
+ return DotenvModule._configVault(options)
349
+ }
350
+
351
+ function decrypt (encrypted, keyStr) {
352
+ const key = Buffer.from(keyStr.slice(-64), 'hex')
353
+ let ciphertext = Buffer.from(encrypted, 'base64')
354
+
355
+ const nonce = ciphertext.subarray(0, 12)
356
+ const authTag = ciphertext.subarray(-16)
357
+ ciphertext = ciphertext.subarray(12, -16)
358
+
359
+ try {
360
+ const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce)
361
+ aesgcm.setAuthTag(authTag)
362
+ return `${aesgcm.update(ciphertext)}${aesgcm.final()}`
363
+ } catch (error) {
364
+ const isRange = error instanceof RangeError
365
+ const invalidKeyLength = error.message === 'Invalid key length'
366
+ const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'
367
+
368
+ if (isRange || invalidKeyLength) {
369
+ const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)')
370
+ err.code = 'INVALID_DOTENV_KEY'
371
+ throw err
372
+ } else if (decryptionFailed) {
373
+ const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY')
374
+ err.code = 'DECRYPTION_FAILED'
375
+ throw err
376
+ } else {
377
+ throw error
378
+ }
379
+ }
380
+ }
381
+
382
+ // Populate process.env with parsed values
383
+ function populate (processEnv, parsed, options = {}) {
384
+ const debug = Boolean(options && options.debug)
385
+ const override = Boolean(options && options.override)
386
+ const populated = {}
387
+
388
+ if (typeof parsed !== 'object') {
389
+ const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate')
390
+ err.code = 'OBJECT_REQUIRED'
391
+ throw err
392
+ }
393
+
394
+ // Set process.env
395
+ for (const key of Object.keys(parsed)) {
396
+ if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
397
+ if (override === true) {
398
+ processEnv[key] = parsed[key]
399
+ populated[key] = parsed[key]
400
+ }
401
+
402
+ if (debug) {
403
+ if (override === true) {
404
+ _debug(`"${key}" is already defined and WAS overwritten`)
405
+ } else {
406
+ _debug(`"${key}" is already defined and was NOT overwritten`)
407
+ }
408
+ }
409
+ } else {
410
+ processEnv[key] = parsed[key]
411
+ populated[key] = parsed[key]
412
+ }
413
+ }
414
+
415
+ return populated
416
+ }
417
+
418
+ const DotenvModule = {
419
+ configDotenv,
420
+ _configVault,
421
+ _parseVault,
422
+ config,
423
+ decrypt,
424
+ parse,
425
+ populate
426
+ }
427
+
428
+ module.exports.configDotenv = DotenvModule.configDotenv
429
+ module.exports._configVault = DotenvModule._configVault
430
+ module.exports._parseVault = DotenvModule._parseVault
431
+ module.exports.config = DotenvModule.config
432
+ module.exports.decrypt = DotenvModule.decrypt
433
+ module.exports.parse = DotenvModule.parse
434
+ module.exports.populate = DotenvModule.populate
435
+
436
+ module.exports = DotenvModule
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@uniconvex/dotenv",
3
+ "version": "1.0.0",
4
+ "description": "Loads environment variables from .env file",
5
+ "main": "lib/main.js",
6
+ "types": "lib/main.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./lib/main.d.ts",
10
+ "require": "./lib/main.js",
11
+ "default": "./lib/main.js"
12
+ },
13
+ "./config": "./config.js",
14
+ "./config.js": "./config.js",
15
+ "./lib/env-options": "./lib/env-options.js",
16
+ "./lib/env-options.js": "./lib/env-options.js",
17
+ "./lib/cli-options": "./lib/cli-options.js",
18
+ "./lib/cli-options.js": "./lib/cli-options.js",
19
+ "./package.json": "./package.json"
20
+ },
21
+ "scripts": {
22
+ "dts-check": "tsc --project tests/types/tsconfig.json",
23
+ "lint": "standard",
24
+ "pretest": "npm run lint && npm run dts-check",
25
+ "test": "tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000",
26
+ "test:coverage": "tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",
27
+ "prerelease": "npm test",
28
+ "release": "standard-version"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git://github.com/uniconvex/dotenv.git"
33
+ },
34
+ "homepage": "https://github.com/uniconvex/dotenv#readme",
35
+ "funding": "https://dotenvx.com",
36
+ "keywords": [
37
+ "dotenv",
38
+ "env",
39
+ ".env",
40
+ "environment",
41
+ "variables",
42
+ "config",
43
+ "settings"
44
+ ],
45
+ "readmeFilename": "README.md",
46
+ "license": "BSD-2-Clause",
47
+ "dependencies": {
48
+ "@reimorg/config": "^1.0.2",
49
+ "sinon": "^14.0.1",
50
+ "standard": "^17.0.0",
51
+ "standard-version": "^9.5.0",
52
+ "tap": "^19.2.0"
53
+ },
54
+ "devDependencies": {
55
+ "@types/node": "^18.11.3",
56
+ "decache": "^4.6.2",
57
+ "typescript": "^4.8.4"
58
+ },
59
+ "engines": {
60
+ "node": ">=12"
61
+ },
62
+ "browser": {
63
+ "fs": false
64
+ }
65
+ }