@adonisjs/env 4.0.0-0 → 4.0.0-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,41 +1,147 @@
1
- <div align="center">
2
- <img src="https://res.cloudinary.com/adonisjs/image/upload/q_100/v1558612869/adonis-readme_zscycu.jpg" width="600px">
3
- </div>
4
-
5
- <br />
6
-
7
- <div align="center">
8
- <h3>AdonisJS Env Provider</h3>
9
- <p>Provider to parse and load environment variables from a local <code>.env</code> file. Comes with first class support for <strong>variables substitution</strong>.</p>
10
- </div>
11
-
12
- <br />
13
-
14
- <div align="center">
15
-
16
- [![gh-workflow-image]][gh-workflow-url] [![npm-image]][npm-url] ![][typescript-image] [![license-image]][license-url] [![synk-image]][synk-url]
17
-
18
- </div>
19
-
20
- <div align="center">
21
- <h3>
22
- <a href="https://adonisjs.com">
23
- Website
24
- </a>
25
- <span> | </span>
26
- <a href="https://docs.adonisjs.com/guides/environment-variables">
27
- Guides
28
- </a>
29
- <span> | </span>
30
- <a href="CONTRIBUTING.md">
31
- Contributing
32
- </a>
33
- </h3>
34
- </div>
35
-
36
- <div align="center">
37
- <sub>Built with ❤︎ by <a href="https://twitter.com/AmanVirk1">Harminder Virk</a>
38
- </div>
1
+ # @adonisjs/env
2
+ > Environment variables parser and validator used by the AdonisJS.
3
+
4
+ [![gh-workflow-image]][gh-workflow-url] [![typescript-image]][typescript-url] [![npm-image]][npm-url] [![license-image]][license-url] [![synk-image]][synk-url]
5
+
6
+ > **Note:** This package is framework agnostic and can also be used outside of AdonisJS.
7
+
8
+ The `@adonisjs/env` package encapsulates the workflow around loading, parsing, and validating environment variables.
9
+
10
+ ## Setup
11
+ Install the package from the npm packages registry as follows.
12
+
13
+ ```sh
14
+ npm i @adonisjs/env
15
+
16
+ yarn add @adonisjs/env
17
+ ```
18
+
19
+ ## EnvLoader
20
+ The `EnvLoader` class is responsible for loading the environment variable files from the disk and returning their contents as a string.
21
+
22
+ ```ts
23
+ import { EnvLoader } from '@adonisjs/env'
24
+
25
+ const lookupPath = new URL('./', import.meta.url)
26
+ const loader = new EnvLoader(lookupPath)
27
+
28
+ const { envContents, currentEnvContents } = await loader.load()
29
+ ```
30
+
31
+ ### `envContents`
32
+
33
+ - The `envContents` is read from the `.env` file from the root of the `lookupPath`.
34
+ - No exceptions are raised if the `.env` file is missing. In brief, it is optional to have a `.env` file.
35
+ - If the `ENV_PATH` environment variable is set, the loader will use that instead of the `.env` file. This allows overwriting the location of the dot-env file.
36
+
37
+
38
+ ### `currentEnvContents`
39
+
40
+ - The `currentEnvContents` contents are read from the `.env.[NODE_ENV]` file.
41
+ - If the current `NODE_ENV = 'development'`, then the contents of this variable will be from the `.env.development` file and so on.
42
+ - The contents of this file should take precendence over the `.env` file.
43
+
44
+ ## EnvParser
45
+ The `EnvParser` class is responsible for parsing the contents of the `.env` file(s) and converting them into an object.
46
+
47
+ ```ts
48
+ import { EnvLoader, EnvParser } from '@adonisjs/env'
49
+
50
+ const lookupPath = new URL('./', import.meta.url)
51
+ const loader = new EnvLoader(lookupPath)
52
+ const { envContents, currentEnvContents } = await loader.load()
53
+
54
+ const envParser = new EnvParser(envContents)
55
+ const currentEnvParser = new EnvParser(currentEnvContents)
56
+
57
+ console.log(envParser.parse()) // { key: value }
58
+ console.log(currentEnvParser.parse()) // { key: value }
59
+ ```
60
+
61
+ The return value of `parser.parse` is an object with key-value pair. The parser also has support for interpolation.
62
+
63
+ You can also instruct the parser to prefer existing `process.env` values when they exist. When `preferProcessEnv` is set to `true`, the value from the env contents will be discarded in favor of existing `process.env` value.
64
+
65
+ ```ts
66
+ new EnvParser(envContents, { preferProcessEnv: true })
67
+ ```
68
+
69
+ ## Validating environment variables
70
+ Once you have the parsed objects, you can optionally validate them against a pre-defined schema. We recommend validation for the following reasons.
71
+
72
+ - Fail early if one or more environment variables are missing.
73
+ - Cast values to specific data types.
74
+ - Have type safety alongside runtime safety.
75
+
76
+ ```ts
77
+ import { Env } from '@adonisjs/env'
78
+
79
+ const validate = Env.rules({
80
+ PORT: Env.schema.number(),
81
+ HOST: Env.schema.string({ format: 'host' })
82
+ })
83
+ ```
84
+
85
+ The `Env.schema` is a reference to the [@poppinss/validator-lite](https://github.com/poppinss/validator-lite) `schema` object. Make sure to go through the package README to view all the available methods and options.
86
+
87
+ The `Env.rules` method returns a function to validate the environment variables. The return value is the validated object with type information inferred from the schema.
88
+
89
+ ```ts
90
+ validate(process.env)
91
+ ```
92
+
93
+ Following is a complete example of using the `EnvLoader`, `EnvParser`, and the validator to set up environment variables.
94
+
95
+ ```ts
96
+ import { EnvLoader, EnvParser, Env } from '@adonisjs/env'
97
+
98
+ const lookupPath = new URL('./', import.meta.url)
99
+ const loader = new EnvLoader(lookupPath)
100
+ const { envContents, currentEnvContents } = await loader.load()
101
+
102
+ /**
103
+ * Loop over all the current env parsed values and let
104
+ * them take precedence over the existing process.env
105
+ * values.
106
+ */
107
+ const currentEnvValues = new EnvParser(currentEnvContents).parse()
108
+ Object.keys(currentEnvValues).forEach((key) => {
109
+ process.env[key] = currentEnvValues[key]
110
+ })
111
+
112
+ const envValues = new EnvParser(envContents, { preferProcessEnv: true }).parse()
113
+
114
+ /**
115
+ * Loop over all the parsed env values and set
116
+ * them on "process.env"
117
+ *
118
+ * However, if the value already exists on "process.env", then
119
+ * do not overwrite it, instead update the envValues
120
+ * object.
121
+ */
122
+ Object.keys(envValues).forEach((key) => {
123
+ if (process.env[key]) {
124
+ envValues[key] = process.env[key]
125
+ } else {
126
+ process.env[key] = envValues[key]
127
+ }
128
+ })
129
+
130
+ // Now perform the validation
131
+ const validate = Env.rules({
132
+ PORT: Env.schema.number(),
133
+ HOST: Env.schema.string({ format: 'host' })
134
+ })
135
+
136
+ const validated = validate({ ...envValues, ...currentEnvValues })
137
+ const env = new Env(validated)
138
+
139
+ env.get('PORT') // is a number
140
+ env.get('HOST') // is a string
141
+ env.get('NODE_ENV') // is unknown, hence a string or undefined
142
+ ```
143
+
144
+ The above code may seem like a lot of work to set up environment variables. However, you have fine-grained control over each step. In the case of AdonisJS, all this boilerplate is hidden inside the framework's application bootstrapping logic.
39
145
 
40
146
  [gh-workflow-image]: https://img.shields.io/github/workflow/status/adonisjs/env/test?style=for-the-badge
41
147
  [gh-workflow-url]: https://github.com/adonisjs/env/actions/workflows/test.yml "Github action"
@@ -0,0 +1,6 @@
1
+ import { Exception } from '@poppinss/utils';
2
+ export declare class InvalidEnvVariablesException extends Exception {
3
+ static status: number;
4
+ static code: string;
5
+ static message: string;
6
+ }
@@ -0,0 +1,6 @@
1
+ import { Exception } from '@poppinss/utils';
2
+ export class InvalidEnvVariablesException extends Exception {
3
+ static status = 500;
4
+ static code = 'E_INVALID_ENV_VARIABLES';
5
+ static message = 'Validation failed for one or more environment variables';
6
+ }
@@ -1,6 +1,8 @@
1
1
  import { DotenvParseOutput } from 'dotenv';
2
2
  export declare class EnvParser {
3
3
  #private;
4
- constructor(envContents: string);
4
+ constructor(envContents: string, options?: {
5
+ preferProcessEnv: boolean;
6
+ });
5
7
  parse(): DotenvParseOutput;
6
8
  }
@@ -1,14 +1,21 @@
1
1
  import dotenv from 'dotenv';
2
2
  export class EnvParser {
3
3
  #envContents;
4
- constructor(envContents) {
4
+ #preferProcessEnv = false;
5
+ constructor(envContents, options) {
6
+ if (options?.preferProcessEnv) {
7
+ this.#preferProcessEnv = true;
8
+ }
5
9
  this.#envContents = envContents;
6
10
  }
7
11
  #getValue(key, parsed) {
12
+ if (this.#preferProcessEnv && process.env[key]) {
13
+ return process.env[key];
14
+ }
8
15
  if (parsed[key]) {
9
16
  return this.#interpolate(parsed[key], parsed);
10
17
  }
11
- return '';
18
+ return process.env[key] || '';
12
19
  }
13
20
  #interpolateMustache(token, parsed) {
14
21
  const closingBrace = token.indexOf('}');
@@ -53,7 +60,7 @@ export class EnvParser {
53
60
  parse() {
54
61
  const envCollection = dotenv.parse(this.#envContents.trim());
55
62
  return Object.keys(envCollection).reduce((result, key) => {
56
- result[key] = this.#interpolate(envCollection[key], envCollection);
63
+ result[key] = this.#getValue(key, envCollection);
57
64
  return result;
58
65
  }, {});
59
66
  }
@@ -1,12 +1,26 @@
1
+ import { InvalidEnvVariablesException } from './exceptions/invalid_env_variables.js';
1
2
  export class EnvValidator {
2
3
  #schema;
4
+ #error;
3
5
  constructor(schema) {
4
6
  this.#schema = schema;
7
+ this.#error = new InvalidEnvVariablesException();
5
8
  }
6
9
  validate(values) {
7
- return Object.keys(this.#schema).reduce((result, key) => {
8
- result[key] = this.#schema[key](key, values[key]);
10
+ const cause = [];
11
+ const validated = Object.keys(this.#schema).reduce((result, key) => {
12
+ try {
13
+ result[key] = this.#schema[key](key, values[key]);
14
+ }
15
+ catch (error) {
16
+ cause.push(`- ${error.message}`);
17
+ }
9
18
  return result;
10
19
  }, { ...values });
20
+ if (cause.length) {
21
+ this.#error.cause = cause.join('\n');
22
+ throw this.#error;
23
+ }
24
+ return validated;
11
25
  }
12
26
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adonisjs/env",
3
- "version": "4.0.0-0",
3
+ "version": "4.0.0-2",
4
4
  "description": "Environment variable manager for Node.js",
5
5
  "main": "build/index.js",
6
6
  "type": "module",