dotenv-webpack 8.1.1 → 9.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/README.md CHANGED
@@ -19,9 +19,6 @@ A secure webpack plugin that supports dotenv and other environment variables and
19
19
  <img alt="Vulnerabilities Score" src="https://snyk-widget.herokuapp.com/badge/npm/dotenv-webpack/badge.svg" />
20
20
  <img alt="Known Vulnerabilities" src="https://snyk.io/test/github/mrsteele/dotenv-webpack/badge.svg" />
21
21
  <object id="badge" data="https://snyk-widget.herokuapp.com/badge/npm/dotenv-webpack/badge.svg" type="image/svg+xml"></object>
22
- <a href="https://www.dotenv.org/get-started?r=3" target="_blank">
23
- <img alt="dotenv-vault" src="https://badge.dotenv.org/works-with.svg?r=3" />
24
- </a>
25
22
  </div>
26
23
 
27
24
  ## Installation
package/package.json CHANGED
@@ -1,18 +1,16 @@
1
1
  {
2
2
  "name": "dotenv-webpack",
3
3
  "description": "A simple webpack plugin to support dotenv.",
4
- "version": "8.1.1",
5
- "main": "index.js",
4
+ "version": "9.0.0",
5
+ "main": "src/index.js",
6
6
  "scripts": {
7
7
  "precommit": "npm run lint",
8
8
  "prepush": "npm t",
9
- "lint": "standard",
9
+ "lint": "XDG_CACHE_HOME=./.cache standard",
10
10
  "predoc": "rimraf docs",
11
11
  "doc": "jsdoc src/index.js -d docs",
12
- "pretest": "npm run build",
13
12
  "test": "jest",
14
- "prebuild": "rimraf dist",
15
- "build": "babel --copy-files --out-dir dist src",
13
+ "build": "node -e \"require('./src')\"",
16
14
  "travis": "npm run lint && npm t"
17
15
  },
18
16
  "repository": {
@@ -38,41 +36,34 @@
38
36
  "webpack",
39
37
  "plugin"
40
38
  ],
41
- "author": "Matt Steele <matt@omnionline.us> (http://omnionline.us/)",
39
+ "author": "Matt Steele <hi@mrsteele.dev> (http://mrsteele.dev/)",
42
40
  "license": "MIT",
43
41
  "bugs": {
44
42
  "url": "https://github.com/mrsteele/dotenv-webpack/issues"
45
43
  },
46
44
  "homepage": "https://github.com/mrsteele/dotenv-webpack#readme",
47
45
  "engines": {
48
- "node": ">=10"
46
+ "node": ">=18.18.0"
49
47
  },
50
48
  "peerDependencies": {
51
49
  "webpack": "^4 || ^5"
52
50
  },
53
51
  "dependencies": {
54
- "dotenv-defaults": "^2.0.2"
52
+ "dotenv-defaults": "^5.0.2"
55
53
  },
56
54
  "devDependencies": {
57
- "@babel/cli": "^7.13.0",
58
- "@babel/core": "^7.13.8",
59
- "@babel/preset-env": "^7.13.9",
60
- "@babel/register": "^7.13.8",
61
- "husky": "^7.0.1",
62
- "jest": "^27.0.4",
63
- "jsdoc": "^3.6.10",
64
- "rimraf": "^3.0.0",
65
- "sinon": "^11.1.1",
66
- "standard": "^16.0.3",
67
- "webpack": "^5.24.3"
55
+ "husky": "^9.1.7",
56
+ "jest": "^30.2.0",
57
+ "jsdoc": "^4.0.5",
58
+ "rimraf": "^6.0.1",
59
+ "sinon": "^21.0.0",
60
+ "standard": "^17.1.2",
61
+ "webpack": "^5.102.1"
68
62
  },
69
63
  "files": [
70
- "dist"
64
+ "src",
65
+ "types/index.d.ts"
71
66
  ],
72
- "browser": "browser.js",
73
- "babel": {
74
- "presets": [
75
- "@babel/preset-env"
76
- ]
77
- }
67
+ "browser": "src/index.js",
68
+ "types": "types/index.d.ts"
78
69
  }
package/src/index.js ADDED
@@ -0,0 +1,210 @@
1
+ const dotenv = require('dotenv-defaults')
2
+ const fs = require('fs')
3
+
4
+ // Mostly taken from here: https://github.com/motdotla/dotenv-expand/blob/master/lib/main.js#L4
5
+ const interpolate = (env, vars) => {
6
+ const matches = env.match(/\$([a-zA-Z0-9_]+)|\${([a-zA-Z0-9_]+)}/g) || []
7
+
8
+ matches.forEach((match) => {
9
+ const key = match.replace(/\$|{|}/g, '')
10
+ let variable = vars[key] || ''
11
+ variable = interpolate(variable, vars)
12
+ env = env.replace(match, variable)
13
+ })
14
+
15
+ return env
16
+ }
17
+
18
+ const isMainThreadElectron = (target) =>
19
+ target.startsWith('electron') && target.endsWith('main')
20
+
21
+ class Dotenv {
22
+ /**
23
+ * The dotenv-webpack plugin.
24
+ * @param {Object} options - The parameters.
25
+ * @param {String} [options.path=./.env] - The location of the environment variable.
26
+ * @param {Boolean|String} [options.safe=false] - If false ignore safe-mode, if true load `'./.env.example'`, if a string load that file as the sample.
27
+ * @param {Boolean} [options.systemvars=false] - If true, load system environment variables.
28
+ * @param {Boolean} [options.silent=false] - If true, suppress warnings, if false, display warnings.
29
+ * @param {String} [options.prefix=process.env.] - The prefix, used to denote environment variables.
30
+ * @returns {webpack.DefinePlugin}
31
+ */
32
+ constructor (config = {}) {
33
+ this.config = Object.assign({}, {
34
+ path: './.env',
35
+ prefix: 'process.env.'
36
+ }, config)
37
+ }
38
+
39
+ apply (compiler) {
40
+ const variables = this.gatherVariables()
41
+ const target = compiler.options.target ?? 'web'
42
+ const version = (compiler.webpack && compiler.webpack.version) || '4'
43
+ const data = this.formatData({
44
+ variables,
45
+ target,
46
+ version
47
+ })
48
+ const DefinePlugin = (compiler.webpack && compiler.webpack.DefinePlugin) || require('webpack').DefinePlugin
49
+
50
+ new DefinePlugin(data).apply(compiler)
51
+ }
52
+
53
+ gatherVariables () {
54
+ const { safe, allowEmptyValues } = this.config
55
+ const vars = this.initializeVars()
56
+
57
+ const { env, blueprint } = this.getEnvs()
58
+
59
+ Object.keys(blueprint).forEach(key => {
60
+ const value = Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : env[key]
61
+
62
+ const isMissing = typeof value === 'undefined' || value === null ||
63
+ (!allowEmptyValues && value === '')
64
+
65
+ if (safe && isMissing) {
66
+ throw new Error(`Missing environment variable: ${key}`)
67
+ } else {
68
+ vars[key] = value
69
+ }
70
+ })
71
+
72
+ // add the leftovers
73
+ if (safe) {
74
+ Object.keys(env).forEach((key) => {
75
+ if (!Object.prototype.hasOwnProperty.call(vars, key)) {
76
+ vars[key] = env[key]
77
+ }
78
+ })
79
+ }
80
+
81
+ return vars
82
+ }
83
+
84
+ initializeVars () {
85
+ return (this.config.systemvars) ? Object.assign({}, process.env) : {}
86
+ }
87
+
88
+ getEnvs () {
89
+ const { path, silent, safe } = this.config
90
+
91
+ const env = dotenv.parse(this.loadFile({
92
+ file: path,
93
+ silent
94
+ }), this.getDefaults())
95
+
96
+ let blueprint = env
97
+ if (safe) {
98
+ let file = `${path}.example`
99
+ if (safe !== true) {
100
+ file = safe
101
+ }
102
+ blueprint = dotenv.parse(this.loadFile({
103
+ file,
104
+ silent
105
+ }))
106
+ }
107
+
108
+ return {
109
+ env,
110
+ blueprint
111
+ }
112
+ }
113
+
114
+ getDefaults () {
115
+ const { path, silent, defaults } = this.config
116
+
117
+ if (defaults) {
118
+ return this.loadFile({
119
+ file: defaults === true ? `${path}.defaults` : defaults,
120
+ silent
121
+ })
122
+ }
123
+
124
+ return ''
125
+ }
126
+
127
+ formatData ({ variables = {}, target, version }) {
128
+ const { expand, prefix } = this.config
129
+ const formatted = Object.keys(variables).reduce((obj, key) => {
130
+ const v = variables[key]
131
+ const vKey = `${prefix}${key}`
132
+ let vValue
133
+ if (expand) {
134
+ if (v.substring(0, 2) === '\\$') {
135
+ vValue = v.substring(1)
136
+ } else if (v.indexOf('\\$') > 0) {
137
+ vValue = v.replace(/\\\$/g, '$')
138
+ } else {
139
+ vValue = interpolate(v, variables)
140
+ }
141
+ } else {
142
+ vValue = v
143
+ }
144
+
145
+ obj[vKey] = JSON.stringify(vValue)
146
+
147
+ return obj
148
+ }, {})
149
+
150
+ // We have to stub any remaining `process.env`s due to Webpack 5 not polyfilling it anymore
151
+ // https://github.com/mrsteele/dotenv-webpack/issues/240#issuecomment-710231534
152
+ // However, if someone targets Node or Electron `process.env` still exists, and should therefore be kept
153
+ // https://webpack.js.org/configuration/target
154
+ if (this.shouldStub({ target, version })) {
155
+ // Results in `"MISSING_ENV_VAR".NAME` which is valid JS
156
+ formatted['process.env'] = '"MISSING_ENV_VAR"'
157
+ }
158
+
159
+ return formatted
160
+ }
161
+
162
+ shouldStub ({ target: targetInput, version }) {
163
+ if (!version.startsWith('5')) {
164
+ return false
165
+ }
166
+
167
+ const targets = Array.isArray(targetInput) ? targetInput : [targetInput]
168
+
169
+ return targets.every(
170
+ target =>
171
+ // If configured prefix is 'process.env'
172
+ this.config.prefix === 'process.env.' &&
173
+ // If we're not configured to never stub
174
+ this.config.ignoreStub !== true &&
175
+ // And
176
+ (
177
+ // We are configured to always stub
178
+ this.config.ignoreStub === false ||
179
+ // Or if we should according to the target
180
+ (!target.includes('node') && !isMainThreadElectron(target))
181
+ )
182
+ )
183
+ }
184
+
185
+ /**
186
+ * Load a file.
187
+ * @param {String} config.file - The file to load.
188
+ * @param {Boolean} config.silent - If true, suppress warnings, if false, display warnings.
189
+ * @returns {Object}
190
+ */
191
+ loadFile ({ file, silent }) {
192
+ try {
193
+ return fs.readFileSync(file, 'utf8')
194
+ } catch (err) {
195
+ this.warn(`Failed to load ${file}.`, silent)
196
+ return {}
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Displays a console message if 'silent' is falsey
202
+ * @param {String} msg - The message.
203
+ * @param {Boolean} silent - If true, display the message, if false, suppress the message.
204
+ */
205
+ warn (msg, silent) {
206
+ !silent && console.warn(msg)
207
+ }
208
+ }
209
+
210
+ module.exports = Dotenv
@@ -0,0 +1,22 @@
1
+ import type { Compiler } from 'webpack'
2
+
3
+ declare namespace DotenvWebpack {
4
+ interface DotenvOptions {
5
+ path?: string | false
6
+ safe?: boolean | string
7
+ allowEmptyValues?: boolean
8
+ systemvars?: boolean
9
+ silent?: boolean
10
+ expand?: boolean
11
+ defaults?: boolean | string
12
+ ignoreStub?: boolean
13
+ prefix?: string
14
+ }
15
+ }
16
+
17
+ declare class Dotenv {
18
+ constructor(config?: DotenvWebpack.DotenvOptions)
19
+ apply(compiler: Compiler): void
20
+ }
21
+
22
+ export = Dotenv
package/browser.js DELETED
@@ -1,3 +0,0 @@
1
- const plugin = require('./dist').default
2
-
3
- module.exports = plugin
package/dist/index.js DELETED
@@ -1,268 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports["default"] = void 0;
7
-
8
- var _dotenvDefaults = _interopRequireDefault(require("dotenv-defaults"));
9
-
10
- var _fs = _interopRequireDefault(require("fs"));
11
-
12
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
13
-
14
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
15
-
16
- function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
17
-
18
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
19
-
20
- // Mostly taken from here: https://github.com/motdotla/dotenv-expand/blob/master/lib/main.js#L4
21
- var interpolate = function interpolate(env, vars) {
22
- var matches = env.match(/\$([a-zA-Z0-9_]+)|\${([a-zA-Z0-9_]+)}/g) || [];
23
- matches.forEach(function (match) {
24
- var key = match.replace(/\$|{|}/g, '');
25
- var variable = vars[key] || '';
26
- variable = interpolate(variable, vars);
27
- env = env.replace(match, variable);
28
- });
29
- return env;
30
- };
31
-
32
- var isMainThreadElectron = function isMainThreadElectron(target) {
33
- return target.startsWith('electron') && target.endsWith('main');
34
- };
35
-
36
- var Dotenv = /*#__PURE__*/function () {
37
- /**
38
- * The dotenv-webpack plugin.
39
- * @param {Object} options - The parameters.
40
- * @param {String} [options.path=./.env] - The location of the environment variable.
41
- * @param {Boolean|String} [options.safe=false] - If false ignore safe-mode, if true load `'./.env.example'`, if a string load that file as the sample.
42
- * @param {Boolean} [options.systemvars=false] - If true, load system environment variables.
43
- * @param {Boolean} [options.silent=false] - If true, suppress warnings, if false, display warnings.
44
- * @param {String} [options.prefix=process.env.] - The prefix, used to denote environment variables.
45
- * @returns {webpack.DefinePlugin}
46
- */
47
- function Dotenv() {
48
- var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
49
-
50
- _classCallCheck(this, Dotenv);
51
-
52
- this.config = Object.assign({}, {
53
- path: './.env',
54
- prefix: 'process.env.'
55
- }, config);
56
- }
57
-
58
- _createClass(Dotenv, [{
59
- key: "apply",
60
- value: function apply(compiler) {
61
- var _compiler$options$tar;
62
-
63
- var variables = this.gatherVariables();
64
- var target = (_compiler$options$tar = compiler.options.target) !== null && _compiler$options$tar !== void 0 ? _compiler$options$tar : 'web';
65
- var version = compiler.webpack && compiler.webpack.version || '4';
66
- var data = this.formatData({
67
- variables: variables,
68
- target: target,
69
- version: version
70
- });
71
-
72
- var DefinePlugin = compiler.webpack && compiler.webpack.DefinePlugin || require('webpack').DefinePlugin;
73
-
74
- new DefinePlugin(data).apply(compiler);
75
- }
76
- }, {
77
- key: "gatherVariables",
78
- value: function gatherVariables() {
79
- var _this$config = this.config,
80
- safe = _this$config.safe,
81
- allowEmptyValues = _this$config.allowEmptyValues;
82
- var vars = this.initializeVars();
83
-
84
- var _this$getEnvs = this.getEnvs(),
85
- env = _this$getEnvs.env,
86
- blueprint = _this$getEnvs.blueprint;
87
-
88
- Object.keys(blueprint).forEach(function (key) {
89
- var value = Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : env[key];
90
- var isMissing = typeof value === 'undefined' || value === null || !allowEmptyValues && value === '';
91
-
92
- if (safe && isMissing) {
93
- throw new Error("Missing environment variable: ".concat(key));
94
- } else {
95
- vars[key] = value;
96
- }
97
- }); // add the leftovers
98
-
99
- if (safe) {
100
- Object.keys(env).forEach(function (key) {
101
- if (!Object.prototype.hasOwnProperty.call(vars, key)) {
102
- vars[key] = env[key];
103
- }
104
- });
105
- }
106
-
107
- return vars;
108
- }
109
- }, {
110
- key: "initializeVars",
111
- value: function initializeVars() {
112
- return this.config.systemvars ? Object.assign({}, process.env) : {};
113
- }
114
- }, {
115
- key: "getEnvs",
116
- value: function getEnvs() {
117
- var _this$config2 = this.config,
118
- path = _this$config2.path,
119
- silent = _this$config2.silent,
120
- safe = _this$config2.safe;
121
-
122
- var env = _dotenvDefaults["default"].parse(this.loadFile({
123
- file: path,
124
- silent: silent
125
- }), this.getDefaults());
126
-
127
- var blueprint = env;
128
-
129
- if (safe) {
130
- var file = "".concat(path, ".example");
131
-
132
- if (safe !== true) {
133
- file = safe;
134
- }
135
-
136
- blueprint = _dotenvDefaults["default"].parse(this.loadFile({
137
- file: file,
138
- silent: silent
139
- }));
140
- }
141
-
142
- return {
143
- env: env,
144
- blueprint: blueprint
145
- };
146
- }
147
- }, {
148
- key: "getDefaults",
149
- value: function getDefaults() {
150
- var _this$config3 = this.config,
151
- path = _this$config3.path,
152
- silent = _this$config3.silent,
153
- defaults = _this$config3.defaults;
154
-
155
- if (defaults) {
156
- return this.loadFile({
157
- file: defaults === true ? "".concat(path, ".defaults") : defaults,
158
- silent: silent
159
- });
160
- }
161
-
162
- return '';
163
- }
164
- }, {
165
- key: "formatData",
166
- value: function formatData(_ref) {
167
- var _ref$variables = _ref.variables,
168
- variables = _ref$variables === void 0 ? {} : _ref$variables,
169
- target = _ref.target,
170
- version = _ref.version;
171
- var _this$config4 = this.config,
172
- expand = _this$config4.expand,
173
- prefix = _this$config4.prefix;
174
- var formatted = Object.keys(variables).reduce(function (obj, key) {
175
- var v = variables[key];
176
- var vKey = "".concat(prefix).concat(key);
177
- var vValue;
178
-
179
- if (expand) {
180
- if (v.substring(0, 2) === '\\$') {
181
- vValue = v.substring(1);
182
- } else if (v.indexOf('\\$') > 0) {
183
- vValue = v.replace(/\\\$/g, '$');
184
- } else {
185
- vValue = interpolate(v, variables);
186
- }
187
- } else {
188
- vValue = v;
189
- }
190
-
191
- obj[vKey] = JSON.stringify(vValue);
192
- return obj;
193
- }, {}); // We have to stub any remaining `process.env`s due to Webpack 5 not polyfilling it anymore
194
- // https://github.com/mrsteele/dotenv-webpack/issues/240#issuecomment-710231534
195
- // However, if someone targets Node or Electron `process.env` still exists, and should therefore be kept
196
- // https://webpack.js.org/configuration/target
197
-
198
- if (this.shouldStub({
199
- target: target,
200
- version: version
201
- })) {
202
- // Results in `"MISSING_ENV_VAR".NAME` which is valid JS
203
- formatted['process.env'] = '"MISSING_ENV_VAR"';
204
- }
205
-
206
- return formatted;
207
- }
208
- }, {
209
- key: "shouldStub",
210
- value: function shouldStub(_ref2) {
211
- var _this = this;
212
-
213
- var targetInput = _ref2.target,
214
- version = _ref2.version;
215
-
216
- if (!version.startsWith('5')) {
217
- return false;
218
- }
219
-
220
- var targets = Array.isArray(targetInput) ? targetInput : [targetInput];
221
- return targets.every(function (target) {
222
- return (// If configured prefix is 'process.env'
223
- _this.config.prefix === 'process.env.' && // If we're not configured to never stub
224
- _this.config.ignoreStub !== true && ( // And
225
- // We are configured to always stub
226
- _this.config.ignoreStub === false || // Or if we should according to the target
227
- !target.includes('node') && !isMainThreadElectron(target))
228
- );
229
- });
230
- }
231
- /**
232
- * Load a file.
233
- * @param {String} config.file - The file to load.
234
- * @param {Boolean} config.silent - If true, suppress warnings, if false, display warnings.
235
- * @returns {Object}
236
- */
237
-
238
- }, {
239
- key: "loadFile",
240
- value: function loadFile(_ref3) {
241
- var file = _ref3.file,
242
- silent = _ref3.silent;
243
-
244
- try {
245
- return _fs["default"].readFileSync(file, 'utf8');
246
- } catch (err) {
247
- this.warn("Failed to load ".concat(file, "."), silent);
248
- return {};
249
- }
250
- }
251
- /**
252
- * Displays a console message if 'silent' is falsey
253
- * @param {String} msg - The message.
254
- * @param {Boolean} silent - If true, display the message, if false, suppress the message.
255
- */
256
-
257
- }, {
258
- key: "warn",
259
- value: function warn(msg, silent) {
260
- !silent && console.warn(msg);
261
- }
262
- }]);
263
-
264
- return Dotenv;
265
- }();
266
-
267
- var _default = Dotenv;
268
- exports["default"] = _default;
package/index.js DELETED
@@ -1,16 +0,0 @@
1
- 'use strict'
2
-
3
- let plugin
4
- try {
5
- plugin = require('./dist').default
6
- } catch (err) {
7
- if (err.code === 'MODULE_NOT_FOUND') {
8
- require('babel-register')
9
- plugin = require('./src').default
10
- } else {
11
- console.log(err)
12
- process.exit(1)
13
- }
14
- }
15
-
16
- module.exports = plugin