@dotenvx/dotenvx 2.30.0 → 2.31.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.
@@ -0,0 +1,56 @@
1
+ // Pure final pass over independently inferred file rules. Never mutates inputs.
2
+ module.exports = function normalizeEnvfile ({ files, codeDeclarations = [] }) {
3
+ const hasNamedEnvironment = files.some(file => !['.env', '.env.example'].includes(file.filename))
4
+ const rootFiles = []
5
+ const environments = []
6
+ for (const file of files) {
7
+ if (file.filename === '.env.example' || (file.filename === '.env' && !hasNamedEnvironment)) rootFiles.push(file)
8
+ else environments.push(file)
9
+ }
10
+
11
+ const encrypted = rootFiles.some(file => file.hasValues) && rootFiles.every(file => !file.hasValues || file.encrypted)
12
+ const root = new Map()
13
+ for (const file of rootFiles) {
14
+ for (const item of file.declarations) {
15
+ const previous = root.get(item.name)
16
+ root.set(item.name, { ...item, encrypted: Boolean(previous?.encrypted || item.encrypted) })
17
+ }
18
+ }
19
+
20
+ if (environments.length > 1) {
21
+ for (const item of environments[0].declarations) {
22
+ const matches = environments.map(file => file.declarations.find(other => other.name === item.name))
23
+ if (!root.has(item.name) && matches.every(other => other && other.type === item.type && other.optional === item.optional)) {
24
+ // Keep encryption differences in their file scopes, not the shared declaration.
25
+ root.set(item.name, { ...item, encrypted })
26
+ }
27
+ }
28
+ }
29
+
30
+ const blocks = environments.map(file => {
31
+ const overridesEncryption = file.encrypted !== encrypted
32
+ const declarations = file.declarations.flatMap(item => {
33
+ const inherited = root.get(item.name)
34
+ const defaults = inherited
35
+ ? { ...inherited, encrypted: overridesEncryption ? file.encrypted : inherited.encrypted }
36
+ : { encrypted: file.encrypted }
37
+ const overrides = Object.fromEntries(Object.entries(item).filter(([key, value]) => key !== 'name' && value !== defaults[key]))
38
+ return inherited && !Object.keys(overrides).length ? [] : [{ name: item.name, ...overrides }]
39
+ })
40
+ return { filename: file.filename, ...(overridesEncryption ? { encrypted: file.encrypted } : {}), declarations }
41
+ })
42
+
43
+ const names = new Set(files.flatMap(file => file.declarations.map(item => item.name)))
44
+ const code = []
45
+ for (const item of codeDeclarations) {
46
+ if (names.has(item.name)) continue
47
+ names.add(item.name)
48
+ code.push({ ...item, optional: true })
49
+ }
50
+ const declarations = [...root.values()].map(item => {
51
+ const result = { ...item }
52
+ if (result.encrypted === encrypted) delete result.encrypted
53
+ return result
54
+ })
55
+ return { encrypted, declarations, files: blocks, codeDeclarations: code }
56
+ }
@@ -0,0 +1,26 @@
1
+ function declaration (item) {
2
+ let line = `env "${item.name}"`
3
+ if (item.type) line += `, type: "${item.type}"`
4
+ if (item.encrypted !== undefined) line += `, encrypted: ${item.encrypted}`
5
+ if (item.optional !== undefined) line += `, optional: ${item.optional}`
6
+ return line
7
+ }
8
+
9
+ module.exports = function renderEnvfile (document) {
10
+ const sections = [`encrypted ${document.encrypted}`]
11
+ if (document.declarations.length) sections.push(document.declarations.map(declaration).join('\n'))
12
+ for (const file of document.files) {
13
+ const quote = file.filename.includes('"') ? "'" : '"'
14
+ if (file.filename.includes(quote) || /[\r\n\0*?[\]{}]/.test(file.filename)) {
15
+ throw new Error(`Unsupported Envfile filename: ${file.filename}`)
16
+ }
17
+ const lines = [`file ${quote}${file.filename}${quote} do`]
18
+ if (file.encrypted !== undefined) lines.push(` encrypted ${file.encrypted}`)
19
+ lines.push(...file.declarations.map(item => ` ${declaration(item)}`), 'end')
20
+ sections.push(lines.join('\n'))
21
+ }
22
+ if (document.codeDeclarations.length) {
23
+ sections.push('# additionally found in code\n' + document.codeDeclarations.map(declaration).join('\n'))
24
+ }
25
+ return sections.join('\n\n') + '\n'
26
+ }
@@ -1,5 +1,5 @@
1
- const isValidUrl = require('./isValidUrl')
2
- const isValidEmail = require('./isValidEmail')
1
+ const isValidUrl = require('../../helpers/isValidUrl')
2
+ const isValidEmail = require('../../helpers/isValidEmail')
3
3
  const { isIP } = require('node:net')
4
4
 
5
5
  function validate (example = {}, env = {}, options = {}) {
@@ -1,6 +1,6 @@
1
1
  const validate = require('./validate')
2
2
  const encryptedSources = require('./encryptedSources')
3
- const Errors = require('./errors')
3
+ const Errors = require('../../helpers/errors')
4
4
 
5
5
  module.exports = function validateEnvfile (schema, env, processedEnvs) {
6
6
  const messages = new Set()
@@ -11,7 +11,7 @@ class Checklist extends Enquirer.prompts.MultiSelect {
11
11
 
12
12
  indicator (choice) {
13
13
  if (choice.action) return ' '
14
- return choice.enabled ? '●' : this.styles.muted('○')
14
+ return choice.enabled ? '◉' : this.styles.muted('○')
15
15
  }
16
16
 
17
17
  async renderChoice (choice, index) {
@@ -234,7 +234,7 @@ class Errors {
234
234
  }
235
235
 
236
236
  envfileRequired () {
237
- const e = new Error('[ENVFILE_REQUIRED] validate requires an Envfile')
237
+ const e = new Error('[ENVFILE_REQUIRED] check requires an Envfile')
238
238
  e.code = 'ENVFILE_REQUIRED'
239
239
  e.messageWithHelp = e.message
240
240
  return e
@@ -74,6 +74,22 @@ async function multiselect ({ message, choices, initial = [], submitLabel }, con
74
74
  }
75
75
  }
76
76
 
77
+ async function input ({ message }, context) {
78
+ try {
79
+ const answer = await enquirer.prompt({
80
+ type: 'input',
81
+ name: 'value',
82
+ message,
83
+ ...enquirerOptions(context)
84
+ })
85
+ return answer.value
86
+ } catch {
87
+ const error = new Error('prompt cancelled')
88
+ error.code = 'PROMPT_CANCELLED'
89
+ throw error
90
+ }
91
+ }
92
+
77
93
  async function confirm ({ message, initial = false }, context) {
78
94
  try {
79
95
  const answer = await enquirer.prompt({
@@ -125,6 +141,7 @@ async function password ({ message, prefix, separator }, context) {
125
141
  }
126
142
 
127
143
  module.exports = {
144
+ input,
128
145
  confirm,
129
146
  multiselect,
130
147
  password,
package/src/lib/main.js CHANGED
@@ -424,8 +424,12 @@ function resolveNoNative (options = {}) {
424
424
  return options.noNative === true || options.native === false
425
425
  }
426
426
 
427
+ /** @type {import('./main').withEvents} */
428
+ const withEvents = () => require('./events/sdk')({ config, get, set })
429
+
430
+ // Keep named bindings here so Node can detect CommonJS exports for ESM imports.
427
431
  module.exports = {
428
- withEvents: () => require('./events/sdk')({ config, get, set }),
432
+ withEvents,
429
433
  // dotenv proxies
430
434
  config,
431
435
  parse,
@@ -2,7 +2,16 @@ const fs = require('node:fs')
2
2
  const path = require('node:path')
3
3
  const { scan, encrypted } = require('@dotenvx/primitives')
4
4
 
5
- module.exports = function init ({ directory = process.cwd(), envFile } = {}) {
5
+ const normalizeEnvfile = require('../envfile/rendering/normalizeEnvfile')
6
+ const renderEnvfile = require('../envfile/rendering/renderEnvfile')
7
+
8
+ function declaration (name) {
9
+ if (/(^|_)port$/i.test(name)) return { name, type: 'port' }
10
+ if (/(^|_)url$/i.test(name)) return { name, type: 'url' }
11
+ return { name }
12
+ }
13
+
14
+ module.exports = function init ({ directory = process.cwd(), envFile, envFiles, sourceKeys = [], onFile = () => {} } = {}) {
6
15
  const target = path.resolve(directory, 'Envfile')
7
16
  // lstat also preserves dangling symlinks. Never overwrite an existing Envfile.
8
17
  try {
@@ -14,36 +23,49 @@ module.exports = function init ({ directory = process.cwd(), envFile } = {}) {
14
23
 
15
24
  const sources = []
16
25
  const names = new Set()
17
- let requireEncryption = false
18
- for (const candidate of envFile ? [envFile] : ['.env.example', '.env']) {
26
+ const files = []
27
+ const candidates = envFiles || (envFile ? [envFile] : ['.env.example', '.env'])
28
+ const relativeFilename = candidate => path.relative(path.resolve(directory), path.resolve(directory, candidate)).split(path.sep).join('/')
29
+ for (const candidate of candidates) {
19
30
  let src
20
31
  try {
21
32
  src = fs.readFileSync(path.resolve(directory, candidate), 'utf8')
22
33
  } catch (error) {
23
- if (envFile || error.code !== 'ENOENT') throw error
34
+ if (envFiles || envFile || error.code !== 'ENOENT') throw error
24
35
  continue
25
36
  }
37
+ onFile(candidate)
26
38
  sources.push(candidate)
27
39
  // scan preserves every assignment as an array, without decrypting or expanding.
28
- for (const [key, values] of Object.entries(scan(src).parsed)) {
29
- if (/^DOTENV_(?:PUBLIC|PRIVATE)_KEY(?:_|$)/.test(key)) continue
30
- names.add(key)
31
- if (values.some(value => encrypted(value))) requireEncryption = true
40
+ const entries = Object.entries(scan(src).parsed).filter(([key]) => !key.startsWith('DOTENV_PUBLIC_KEY'))
41
+ for (const [key] of entries) {
42
+ if (!/^DOTENV_PRIVATE_KEY(?:_|$)/.test(key)) names.add(key)
32
43
  }
44
+ files.push({
45
+ filename: relativeFilename(candidate),
46
+ hasValues: entries.length > 0,
47
+ encrypted: entries.length > 0 && entries.every(([, values]) => values.every(value => encrypted(value))),
48
+ declarations: entries.filter(([key]) => !/^DOTENV_PRIVATE_KEY(?:_|$)/.test(key)).map(([key, values]) => ({
49
+ ...declaration(key), encrypted: values.some(value => encrypted(value))
50
+ }))
51
+ })
33
52
  }
34
53
 
54
+ const inputCount = names.size
55
+ const codeDeclarations = sourceKeys.filter(key => !/^DOTENV_(?:PUBLIC|PRIVATE)_KEY(?:_|$)/.test(key)).map(declaration)
56
+ for (const item of codeDeclarations) names.add(item.name)
57
+ const addedFromSource = names.size - inputCount
35
58
  const keys = [...names]
36
59
  const invalid = keys.filter(key => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
37
60
  if (invalid.length) throw new Error(`Unsupported Envfile variable names: ${invalid.join(', ')}`)
38
61
 
39
- const declarations = keys.map(key => `env "${key}"`).join('\n')
40
- const content = `encrypted ${requireEncryption}\n` +
41
- (declarations ? `\n${declarations}\n` : '')
62
+ const document = normalizeEnvfile({ files, codeDeclarations })
63
+ const content = renderEnvfile(document)
42
64
  try {
43
65
  fs.writeFileSync(target, content, { flag: 'wx' })
44
66
  } catch (error) {
45
67
  if (error.code === 'EEXIST') return { created: false }
46
68
  throw error
47
69
  }
48
- return { created: true, source: sources.join(', '), count: keys.length }
70
+ return { created: true, source: sources.join(', '), count: keys.length, addedFromSource }
49
71
  }
@@ -2,8 +2,8 @@ const envsResolver = require('../resolvers/envs')
2
2
  const Session = require('../../db/session')
3
3
  const buildCommandEnvs = require('../helpers/buildCommandEnvs')
4
4
  const resolveEnvKeysFile = require('../helpers/resolveEnvKeysFile')
5
- const readEnvfile = require('../helpers/readEnvfile')
6
- const validateEnvfile = require('../helpers/validateEnvfile')
5
+ const readEnvfile = require('../envfile/parsing/readEnvfile')
6
+ const validateEnvfile = require('../envfile/validation/validateEnvfile')
7
7
  const normalizeDotenvConfigPath = require('../helpers/normalizeDotenvConfigPath')
8
8
  const Errors = require('../helpers/errors')
9
9
  const { determine } = require('../helpers/envResolution')
@@ -1,17 +0,0 @@
1
- const initEnvfile = require('../../lib/services/init')
2
- const { logger } = require('../../shared/logger')
3
- const catchAndLog = require('../../lib/helpers/catchAndLog')
4
-
5
- module.exports = function define () {
6
- try {
7
- const { created } = initEnvfile({ envFile: this.opts().envFile })
8
- if (created) {
9
- logger.success('≡ defined (Envfile)')
10
- } else {
11
- logger.info('○ Envfile already exists (unchanged)')
12
- }
13
- } catch (error) {
14
- catchAndLog(error)
15
- return { exitCode: 1, error }
16
- }
17
- }