Skip to content

Commit 2ff2808

Browse files
committed
✨ Add basic features
1 parent 9859354 commit 2ff2808

File tree

2 files changed

+364
-0
lines changed

2 files changed

+364
-0
lines changed

dist/index.js

Lines changed: 277 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,277 @@
1+
/******/ (() => { // webpackBootstrap
2+
/******/ var __webpack_modules__ = ({
3+
4+
/***/ 437:
5+
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
6+
7+
/* @flow */
8+
/*::
9+
10+
type DotenvParseOptions = {
11+
debug?: boolean
12+
}
13+
14+
// keys and values from src
15+
type DotenvParseOutput = { [string]: string }
16+
17+
type DotenvConfigOptions = {
18+
path?: string, // path to .env file
19+
encoding?: string, // encoding of .env file
20+
debug?: string // turn on logging for debugging purposes
21+
}
22+
23+
type DotenvConfigOutput = {
24+
parsed?: DotenvParseOutput,
25+
error?: Error
26+
}
27+
28+
*/
29+
30+
const fs = __nccwpck_require__(747)
31+
const path = __nccwpck_require__(622)
32+
33+
function log (message /*: string */) {
34+
console.log(`[dotenv][DEBUG] ${message}`)
35+
}
36+
37+
const NEWLINE = '\n'
38+
const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/
39+
const RE_NEWLINES = /\\n/g
40+
const NEWLINES_MATCH = /\n|\r|\r\n/
41+
42+
// Parses src into an Object
43+
function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ {
44+
const debug = Boolean(options && options.debug)
45+
const obj = {}
46+
47+
// convert Buffers before splitting into lines and processing
48+
src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) {
49+
// matching "KEY' and 'VAL' in 'KEY=VAL'
50+
const keyValueArr = line.match(RE_INI_KEY_VAL)
51+
// matched?
52+
if (keyValueArr != null) {
53+
const key = keyValueArr[1]
54+
// default undefined or missing values to empty string
55+
let val = (keyValueArr[2] || '')
56+
const end = val.length - 1
57+
const isDoubleQuoted = val[0] === '"' && val[end] === '"'
58+
const isSingleQuoted = val[0] === "'" && val[end] === "'"
59+
60+
// if single or double quoted, remove quotes
61+
if (isSingleQuoted || isDoubleQuoted) {
62+
val = val.substring(1, end)
63+
64+
// if double quoted, expand newlines
65+
if (isDoubleQuoted) {
66+
val = val.replace(RE_NEWLINES, NEWLINE)
67+
}
68+
} else {
69+
// remove surrounding whitespace
70+
val = val.trim()
71+
}
72+
73+
obj[key] = val
74+
} else if (debug) {
75+
log(`did not match key and value when parsing line ${idx + 1}: ${line}`)
76+
}
77+
})
78+
79+
return obj
80+
}
81+
82+
// Populates process.env from .env file
83+
function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ {
84+
let dotenvPath = path.resolve(process.cwd(), '.env')
85+
let encoding /*: string */ = 'utf8'
86+
let debug = false
87+
88+
if (options) {
89+
if (options.path != null) {
90+
dotenvPath = options.path
91+
}
92+
if (options.encoding != null) {
93+
encoding = options.encoding
94+
}
95+
if (options.debug != null) {
96+
debug = true
97+
}
98+
}
99+
100+
try {
101+
// specifying an encoding returns a string instead of a buffer
102+
const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug })
103+
104+
Object.keys(parsed).forEach(function (key) {
105+
if (!Object.prototype.hasOwnProperty.call(process.env, key)) {
106+
process.env[key] = parsed[key]
107+
} else if (debug) {
108+
log(`"${key}" is already defined in \`process.env\` and will not be overwritten`)
109+
}
110+
})
111+
112+
return { parsed }
113+
} catch (e) {
114+
return { error: e }
115+
}
116+
}
117+
118+
module.exports.config = config
119+
module.exports.parse = parse
120+
121+
122+
/***/ }),
123+
124+
/***/ 351:
125+
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
126+
127+
__nccwpck_require__(437).config()
128+
129+
const VALID_TYPES = [ 'string', 'array', 'boolean' ]
130+
131+
const DEFAULT_OPTIONS = {
132+
required: false,
133+
type: 'string',
134+
disableable: false
135+
}
136+
137+
const getEnvVar = (key) => {
138+
const parsed = process.env[`INPUT_${ key.replace(/ /g, '_').toUpperCase() }`]
139+
const raw = process.env[key]
140+
141+
return parsed || raw || undefined
142+
}
143+
144+
const parseArray = (val) => {
145+
const array = val.split('\n').join(',').split(',')
146+
const filtered = array.filter((n) => n)
147+
148+
return filtered.map((n) => n.trim())
149+
}
150+
151+
const parseBoolean = (val) => {
152+
const trueValue = [ 'true', 'True', 'TRUE' ]
153+
const falseValue = [ 'false', 'False', 'FALSE' ]
154+
155+
if (trueValue.includes(val)) return true
156+
if (falseValue.includes(val)) return false
157+
158+
return new Error('boolean input has to be one of \`true | True | TRUE | false | False | FALSE\`')
159+
}
160+
161+
const parseValue = (val, type) => {
162+
if (type === 'array') {
163+
return parseArray(val)
164+
}
165+
166+
if (type === 'boolean') {
167+
return parseBoolean(val)
168+
}
169+
170+
return val.trim()
171+
}
172+
173+
const getInput = (key, opts) => {
174+
175+
let parsedOptions = key
176+
if (typeof key === 'string') {
177+
parsedOptions = {
178+
key: key,
179+
...opts
180+
}
181+
}
182+
183+
const options = Object.assign({}, DEFAULT_OPTIONS, parsedOptions)
184+
185+
// Check if the provided type is supported
186+
if (VALID_TYPES.includes(options.type) === false) return new Error('option type has to be one of `string | array | boolean`')
187+
188+
// Get the value for the given key
189+
const val = getEnvVar(options.key)
190+
191+
// If variable can be turned off regardless of type, return undefined
192+
if (options.disableable && val === 'false')
193+
return undefined
194+
195+
// Parse value based on type
196+
const parsed = val !== undefined ? parseValue(val, options.type) : undefined
197+
198+
// If value is required throw error, else return default value if specified
199+
if (!parsed) {
200+
if (options.required) return new Error(`Input \`${ options.key }\` is required but was not provided.`)
201+
if (options.default) return options.default
202+
203+
return undefined
204+
}
205+
206+
// Run modifier function if specified
207+
if (options.modifier) return options.modifier(parsed)
208+
209+
// Finally return parsed value
210+
return parsed
211+
}
212+
213+
module.exports = getInput
214+
215+
/***/ }),
216+
217+
/***/ 747:
218+
/***/ ((module) => {
219+
220+
"use strict";
221+
module.exports = require("fs");;
222+
223+
/***/ }),
224+
225+
/***/ 622:
226+
/***/ ((module) => {
227+
228+
"use strict";
229+
module.exports = require("path");;
230+
231+
/***/ })
232+
233+
/******/ });
234+
/************************************************************************/
235+
/******/ // The module cache
236+
/******/ var __webpack_module_cache__ = {};
237+
/******/
238+
/******/ // The require function
239+
/******/ function __nccwpck_require__(moduleId) {
240+
/******/ // Check if module is in cache
241+
/******/ var cachedModule = __webpack_module_cache__[moduleId];
242+
/******/ if (cachedModule !== undefined) {
243+
/******/ return cachedModule.exports;
244+
/******/ }
245+
/******/ // Create a new module (and put it into the cache)
246+
/******/ var module = __webpack_module_cache__[moduleId] = {
247+
/******/ // no module.id needed
248+
/******/ // no module.loaded needed
249+
/******/ exports: {}
250+
/******/ };
251+
/******/
252+
/******/ // Execute the module function
253+
/******/ var threw = true;
254+
/******/ try {
255+
/******/ __webpack_modules__[moduleId](module, module.exports, __nccwpck_require__);
256+
/******/ threw = false;
257+
/******/ } finally {
258+
/******/ if(threw) delete __webpack_module_cache__[moduleId];
259+
/******/ }
260+
/******/
261+
/******/ // Return the exports of the module
262+
/******/ return module.exports;
263+
/******/ }
264+
/******/
265+
/************************************************************************/
266+
/******/ /* webpack/runtime/compat */
267+
/******/
268+
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";/************************************************************************/
269+
/******/
270+
/******/ // startup
271+
/******/ // Load entry module and return exports
272+
/******/ // This entry module is referenced by other modules so it can't be inlined
273+
/******/ var __webpack_exports__ = __nccwpck_require__(351);
274+
/******/ module.exports = __webpack_exports__;
275+
/******/
276+
/******/ })()
277+
;

src/index.js

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
require('dotenv').config()
2+
3+
const VALID_TYPES = [ 'string', 'array', 'boolean' ]
4+
5+
const DEFAULT_OPTIONS = {
6+
required: false,
7+
type: 'string',
8+
disableable: false
9+
}
10+
11+
const getEnvVar = (key) => {
12+
const parsed = process.env[`INPUT_${ key.replace(/ /g, '_').toUpperCase() }`]
13+
const raw = process.env[key]
14+
15+
return parsed || raw || undefined
16+
}
17+
18+
const parseArray = (val) => {
19+
const array = val.split('\n').join(',').split(',')
20+
const filtered = array.filter((n) => n)
21+
22+
return filtered.map((n) => n.trim())
23+
}
24+
25+
const parseBoolean = (val) => {
26+
const trueValue = [ 'true', 'True', 'TRUE' ]
27+
const falseValue = [ 'false', 'False', 'FALSE' ]
28+
29+
if (trueValue.includes(val)) return true
30+
if (falseValue.includes(val)) return false
31+
32+
return new Error('boolean input has to be one of \`true | True | TRUE | false | False | FALSE\`')
33+
}
34+
35+
const parseValue = (val, type) => {
36+
if (type === 'array') {
37+
return parseArray(val)
38+
}
39+
40+
if (type === 'boolean') {
41+
return parseBoolean(val)
42+
}
43+
44+
return val.trim()
45+
}
46+
47+
const getInput = (key, opts) => {
48+
49+
let parsedOptions = key
50+
if (typeof key === 'string') {
51+
parsedOptions = {
52+
key: key,
53+
...opts
54+
}
55+
}
56+
57+
const options = Object.assign({}, DEFAULT_OPTIONS, parsedOptions)
58+
59+
// Check if the provided type is supported
60+
if (VALID_TYPES.includes(options.type) === false) return new Error('option type has to be one of `string | array | boolean`')
61+
62+
// Get the value for the given key
63+
const val = getEnvVar(options.key)
64+
65+
// If variable can be turned off regardless of type, return undefined
66+
if (options.disableable && val === 'false')
67+
return undefined
68+
69+
// Parse value based on type
70+
const parsed = val !== undefined ? parseValue(val, options.type) : undefined
71+
72+
// If value is required throw error, else return default value if specified
73+
if (!parsed) {
74+
if (options.required) return new Error(`Input \`${ options.key }\` is required but was not provided.`)
75+
if (options.default) return options.default
76+
77+
return undefined
78+
}
79+
80+
// Run modifier function if specified
81+
if (options.modifier) return options.modifier(parsed)
82+
83+
// Finally return parsed value
84+
return parsed
85+
}
86+
87+
module.exports = getInput

0 commit comments

Comments
 (0)