@dotenvx/dotenvx 2.29.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.
Files changed (85) hide show
  1. package/CHANGELOG.md +24 -1
  2. package/README.md +81 -749
  3. package/package.json +5 -5
  4. package/src/cli/actions/armor/down.js +1 -1
  5. package/src/cli/actions/armor/move.js +1 -1
  6. package/src/cli/actions/armor/open.js +1 -1
  7. package/src/cli/actions/armor/pull.js +1 -1
  8. package/src/cli/actions/armor/push.js +1 -1
  9. package/src/cli/actions/armor/up.js +1 -1
  10. package/src/cli/actions/{validate.js → check.js} +5 -5
  11. package/src/cli/actions/curl.js +2 -2
  12. package/src/cli/actions/decrypt.js +4 -10
  13. package/src/cli/actions/del.js +3 -5
  14. package/src/cli/actions/encrypt.js +4 -10
  15. package/src/cli/actions/ext/genexample.js +1 -1
  16. package/src/cli/actions/ext/prebuild.js +1 -1
  17. package/src/cli/actions/ext/scan.js +2 -3
  18. package/src/cli/actions/feedback.js +42 -0
  19. package/src/cli/actions/get.js +4 -7
  20. package/src/cli/actions/init.js +56 -2
  21. package/src/cli/actions/keychain/down.js +1 -1
  22. package/src/cli/actions/keychain/pull.js +1 -1
  23. package/src/cli/actions/keychain/push.js +1 -1
  24. package/src/cli/actions/keychain/up.js +1 -1
  25. package/src/cli/actions/keypair.js +3 -3
  26. package/src/cli/actions/lock/down.js +2 -3
  27. package/src/cli/actions/lock/up.js +2 -3
  28. package/src/cli/actions/login.js +2 -2
  29. package/src/cli/actions/logout.js +1 -1
  30. package/src/cli/actions/ls.js +1 -1
  31. package/src/cli/actions/protect.js +4 -1
  32. package/src/cli/actions/protectDocker.js +2 -2
  33. package/src/cli/actions/protectProcess.js +4 -1
  34. package/src/cli/actions/protectStdin.js +1 -0
  35. package/src/cli/actions/run.js +5 -6
  36. package/src/cli/actions/set.js +5 -9
  37. package/src/cli/actions/settings/device.js +2 -2
  38. package/src/cli/actions/settings/hostname.js +2 -2
  39. package/src/cli/actions/settings/off.js +1 -1
  40. package/src/cli/actions/settings/on.js +1 -1
  41. package/src/cli/actions/settings/path.js +2 -2
  42. package/src/cli/actions/settings/token.js +2 -2
  43. package/src/cli/actions/settings/username.js +2 -2
  44. package/src/cli/commandAction.js +16 -0
  45. package/src/cli/commands/armor.js +10 -9
  46. package/src/cli/commands/custody.js +6 -4
  47. package/src/cli/commands/ext.js +4 -3
  48. package/src/cli/commands/lock.js +3 -2
  49. package/src/cli/commands/native.js +5 -4
  50. package/src/cli/commands/primitives.js +46 -0
  51. package/src/cli/commands/settings.js +8 -7
  52. package/src/cli/dotenvx.js +45 -24
  53. package/src/lib/api/postFeedback.js +31 -0
  54. package/src/lib/envfile/discovery/discoverEnvFiles.js +29 -0
  55. package/src/lib/envfile/discovery/extractEnvKeys.js +173 -0
  56. package/src/lib/envfile/discovery/scanSource.js +79 -0
  57. package/src/lib/{helpers → envfile/parsing}/readEnvfile.js +3 -3
  58. package/src/lib/envfile/rendering/normalizeEnvfile.js +56 -0
  59. package/src/lib/envfile/rendering/renderEnvfile.js +26 -0
  60. package/src/lib/{helpers → envfile/validation}/validate.js +2 -2
  61. package/src/lib/{helpers → envfile/validation}/validateEnvfile.js +1 -1
  62. package/src/lib/events/backends/armor.js +31 -0
  63. package/src/lib/events/background.js +59 -0
  64. package/src/lib/events/catalog.js +14 -0
  65. package/src/lib/events/cli.js +40 -0
  66. package/src/lib/events/delivery.js +89 -0
  67. package/src/lib/events/index.js +73 -0
  68. package/src/lib/events/metadata.js +25 -0
  69. package/src/lib/events/sdk.js +44 -0
  70. package/src/lib/events/worker.js +29 -0
  71. package/src/lib/events/workerEnvironment.js +14 -0
  72. package/src/lib/helpers/checklist.js +9 -4
  73. package/src/lib/helpers/errors.js +1 -1
  74. package/src/lib/helpers/executeCommand.js +12 -1
  75. package/src/lib/helpers/hasPlaintextSecrets.js +2 -6
  76. package/src/lib/helpers/prompts.js +17 -0
  77. package/src/lib/main.d.ts +14 -0
  78. package/src/lib/main.js +15 -3
  79. package/src/lib/services/init.js +34 -12
  80. package/src/lib/services/validate.js +2 -2
  81. package/src/cli/actions/define.js +0 -17
  82. /package/src/lib/{grammars → envfile/parsing}/envfile.peggy +0 -0
  83. /package/src/lib/{helpers → envfile/parsing}/envfileParser.js +0 -0
  84. /package/src/lib/{helpers → envfile/parsing}/formatEnvfileSyntaxError.js +0 -0
  85. /package/src/lib/{helpers → envfile/validation}/encryptedSources.js +0 -0
@@ -0,0 +1,73 @@
1
+ const { performance } = require('perf_hooks')
2
+ const safe = require('./metadata')
3
+ const catalog = require('./catalog')
4
+ const createDelivery = require('./delivery')
5
+ const createBackground = require('./background')
6
+ const armor = require('./backends/armor')
7
+ const { version } = require('../helpers/packageJson')
8
+
9
+ module.exports = function createEvents (name, options = {}, config = {}) {
10
+ let backend
11
+ let delivery
12
+ let selectedOptions
13
+ try {
14
+ selectedOptions = safe.options(config.eventOptions || options)
15
+ if (Object.prototype.hasOwnProperty.call(catalog, name)) {
16
+ if (config.background && !Object.prototype.hasOwnProperty.call(config, 'backend')) delivery = createBackground(options)
17
+ else backend = Object.prototype.hasOwnProperty.call(config, 'backend') ? config.backend : armor(options)
18
+ }
19
+ } catch {} // Missing credentials, keychain failures, and setup are optional.
20
+
21
+ delivery = delivery || createDelivery(backend, config.timeoutMs)
22
+ const started = performance.now()
23
+ const runtime = name.startsWith('sdk/') ? { sdk_version: version, sdk_language: 'javascript' } : { cli_version: version }
24
+ let completion
25
+ let failed = false
26
+ let details = {}
27
+
28
+ function record (metadata = {}, outcome = 'success', terminal = false) {
29
+ try {
30
+ if (completion) return
31
+ const eventOptions = safe.options(selectedOptions)
32
+ delivery.write({
33
+ name,
34
+ occurred_at: new Date().toISOString(),
35
+ outcome: outcome === 'success' ? 'success' : 'unsuccessful',
36
+ metadata: { ...safe.metadata(metadata), ...(Object.keys(eventOptions).length ? { options: eventOptions } : {}), ...runtime }
37
+ }, terminal)
38
+ } catch {}
39
+ }
40
+
41
+ return {
42
+ record,
43
+ file (row, metadata = {}) {
44
+ try {
45
+ if (completion) return
46
+ details.error_count = (details.error_count || 0) + (row.error ? 1 : 0)
47
+ if (row.error) failed = true
48
+ record({
49
+ output: options.stdout ? 'stdout' : 'file',
50
+ ...(details.key !== undefined ? { key: details.key } : {}),
51
+ ...metadata,
52
+ phase: 'file',
53
+ file: row.envFilepath,
54
+ changed: !row.error && !!row.changed,
55
+ ...(row.error ? { error_code: safe.errorCode(row.error) } : {})
56
+ }, row.error ? 'unsuccessful' : 'success')
57
+ } catch {}
58
+ },
59
+ add (metadata) { try { details = { ...details, ...safe.metadata(metadata) } } catch {} },
60
+ fail (error) {
61
+ failed = true
62
+ try { details.error_code = safe.errorCode(error) } catch {}
63
+ },
64
+ complete (outcome, metadata = {}) {
65
+ if (!completion) {
66
+ record({ ...details, ...metadata, phase: 'complete', duration_ms: Math.round(performance.now() - started) }, outcome || (failed ? 'unsuccessful' : 'success'), true)
67
+ completion = delivery.close()
68
+ }
69
+ return completion
70
+ },
71
+ flush: delivery.flush
72
+ }
73
+ }
@@ -0,0 +1,25 @@
1
+ // Event metadata is an allowlist, not a copy of command options or debug logs.
2
+ const fields = new Set(['key', 'file', 'files', 'changed', 'output', 'action', 'phase', 'decision', 'reason', 'error_code', 'error_count', 'warning_count', 'injected_count', 'proxied_count', 'exit_code', 'signal', 'duration_ms', 'filter', 'ignore', 'scope', 'executable'])
3
+ const optionFields = new Set(['envFile', 'envKeysFile', 'key', 'includeKey', 'excludeKey', 'stdout', 'plain', 'armor', 'native', '1password', 'bitwarden', 'create', 'overload', 'all', 'strict', 'convention', 'ignore', 'mask', 'redact', 'format', 'prettyPrint', 'pp', 'docker', 'gitFile', 'gitProcess', 'quiet', 'verbose', 'debug', 'logLevel', 'path', 'encoding', 'override', 'encrypt', 'noArmor', 'noNative', 'no1Password', 'noBitwarden'])
4
+
5
+ function value (input) {
6
+ if (input === null || typeof input === 'boolean') return input
7
+ if (typeof input === 'number' && Number.isFinite(input)) return input
8
+ if (typeof input === 'string') return input.slice(0, 1024)
9
+ if (Array.isArray(input)) return input.slice(0, 100).map(item => value(item)).filter(item => item !== undefined && !Array.isArray(item))
10
+ }
11
+
12
+ function select (input, allowed) {
13
+ const output = {}
14
+ for (const key of allowed) {
15
+ const selected = value(input[key])
16
+ if (selected !== undefined) output[key] = selected
17
+ }
18
+ return output
19
+ }
20
+
21
+ module.exports = {
22
+ metadata: input => select(input, fields),
23
+ options: input => select(input, optionFields),
24
+ errorCode: error => /^[A-Z][A-Z0-9_]{0,79}$/.test(error && error.code) ? error.code : 'COMMAND_FAILED'
25
+ }
@@ -0,0 +1,44 @@
1
+ const createEvents = require('./index')
2
+
3
+ // An explicit, scoped SDK facade. Sync methods stay sync; applications can flush
4
+ // completed calls before shutdown without global hooks or process.exit changes.
5
+ module.exports = function withEvents (sdk, config = {}) {
6
+ const pending = new Set()
7
+
8
+ function complete (events) {
9
+ const completion = events.complete().catch(() => {})
10
+ pending.add(completion)
11
+ completion.finally(() => pending.delete(completion))
12
+ }
13
+
14
+ function invoke (name, options, metadata, action) {
15
+ const events = createEvents(`sdk/${name}`, options, config)
16
+ events.add(metadata)
17
+ try {
18
+ const result = action(events)
19
+ if (result && typeof result.then === 'function') {
20
+ return result.then(value => {
21
+ complete(events)
22
+ return value
23
+ }, error => {
24
+ events.fail(error)
25
+ complete(events)
26
+ throw error
27
+ })
28
+ }
29
+ complete(events)
30
+ return result
31
+ } catch (error) {
32
+ events.fail(error)
33
+ complete(events)
34
+ throw error
35
+ }
36
+ }
37
+
38
+ return {
39
+ config: (options = {}) => invoke('config', options, {}, events => sdk.config(options, events)),
40
+ get: (key, options = {}) => invoke('get', options, { key }, events => sdk.get(key, options, events)),
41
+ set: (key, value, options = {}) => invoke('set', options, { key }, events => sdk.set(key, value, options, events)),
42
+ async flushEvents () { await Promise.all([...pending]) }
43
+ }
44
+ }
@@ -0,0 +1,29 @@
1
+ const armor = require('./backends/armor')
2
+
3
+ // Internal, short-lived worker. No output, local logs, or retries.
4
+ module.exports = function deliverEvents () {
5
+ let input = ''
6
+ const stop = () => process.exit(0)
7
+ const timer = setTimeout(stop, 5000)
8
+ process.stdin.setEncoding('utf8')
9
+ process.stdin.on('error', stop)
10
+ process.stdin.on('data', chunk => {
11
+ input += chunk
12
+ if (Buffer.byteLength(input) > 1024 * 1024) stop()
13
+ })
14
+ process.stdin.on('end', async () => {
15
+ try {
16
+ const { options, events } = JSON.parse(input)
17
+ if (!Array.isArray(events) || events.length > 256) return
18
+ const backend = armor(options)
19
+ if (backend) {
20
+ for (let offset = 0; offset < events.length; offset += 50) {
21
+ await backend.send(events.slice(offset, offset + 50), { signal: AbortSignal.timeout(500) })
22
+ }
23
+ }
24
+ } catch {} finally {
25
+ clearTimeout(timer)
26
+ stop()
27
+ }
28
+ })
29
+ }
@@ -0,0 +1,14 @@
1
+ // Only account discovery, native credential-store access, and network settings.
2
+ // In particular, do not propagate application secrets or runtime injection flags.
3
+ const allowed = new Set([
4
+ 'DOTENVX_CONFIG', 'DOTENVX_NO_ARMOR',
5
+ 'HOME', 'USERPROFILE', 'HOMEDRIVE', 'HOMEPATH', 'APPDATA', 'LOCALAPPDATA',
6
+ 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_RUNTIME_DIR', 'DBUS_SESSION_BUS_ADDRESS',
7
+ 'PATH', 'PATHEXT', 'SYSTEMROOT', 'WINDIR', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL',
8
+ 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY',
9
+ 'NODE_EXTRA_CA_CERTS', 'NODE_USE_SYSTEM_CA', 'SSL_CERT_FILE', 'SSL_CERT_DIR'
10
+ ])
11
+
12
+ module.exports = function workerEnvironment (env = process.env) {
13
+ return Object.fromEntries(Object.entries(env).filter(([key]) => allowed.has(key.toUpperCase())))
14
+ }
@@ -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) {
@@ -36,9 +36,14 @@ class Checklist extends Enquirer.prompts.MultiSelect {
36
36
  return super.selected.filter(choice => !choice.action)
37
37
  }
38
38
 
39
- format () {
40
- if (!this.state.submitted || this.state.cancelled) return ''
41
- return this.selected.map(choice => this.styles.primary(choice.message)).join(', ')
39
+ async render () {
40
+ if (this.state.submitted && !this.state.cancelled) {
41
+ this.clear(this.state.size)
42
+ this.state.prompt = ''
43
+ this.state.size = 0
44
+ return
45
+ }
46
+ return super.render()
42
47
  }
43
48
  }
44
49
 
@@ -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
@@ -5,6 +5,7 @@ const { logger } = require('./../../shared/logger')
5
5
  const Errors = require('./errors')
6
6
  const { createRedactedStreamWriter, redactOutput } = require('./redactOutput')
7
7
  const ptyCommand = require('./ptyCommand')
8
+ const { finished } = require('stream/promises')
8
9
 
9
10
  async function executeCommand (commandArgs, env, sensitiveValues = [], onComplete) {
10
11
  const FORWARD_SIGNAL_GRACE_MS = 1000
@@ -18,8 +19,11 @@ async function executeCommand (commandArgs, env, sensitiveValues = [], onComplet
18
19
 
19
20
  let child
20
21
  let commandExitCode
22
+ let commandError
23
+ let commandSignal
21
24
  let signalSent
22
25
  let sigintCount = 0
26
+ const outputFinished = []
23
27
  const signalForwardTimers = new Set()
24
28
  const otherSignalHandlers = new Map()
25
29
  const isInteractiveTTY = Boolean(process.stdin && process.stdin.isTTY)
@@ -137,12 +141,14 @@ async function executeCommand (commandArgs, env, sensitiveValues = [], onComplet
137
141
  const stdoutWriter = createRedactedStreamWriter(process.stdout, sensitiveValues, child.stdout)
138
142
  child.stdout.on('data', stdoutWriter.write)
139
143
  child.stdout.once('end', stdoutWriter.flush)
144
+ outputFinished.push(finished(child.stdout).catch(() => {}))
140
145
  }
141
146
 
142
147
  if (redactStderr && child.stderr) {
143
148
  const stderrWriter = createRedactedStreamWriter(process.stderr, sensitiveValues, child.stderr)
144
149
  child.stderr.on('data', stderrWriter.write)
145
150
  child.stderr.once('end', stderrWriter.flush)
151
+ outputFinished.push(finished(child.stderr).catch(() => {}))
146
152
  }
147
153
 
148
154
  process.on('SIGINT', sigintHandler)
@@ -164,6 +170,8 @@ async function executeCommand (commandArgs, env, sensitiveValues = [], onComplet
164
170
  throw error
165
171
  }
166
172
  } catch (error) {
173
+ commandSignal = signalSent || error.signal
174
+ if (error.code === 'ENOENT') commandError = { code: 'COMMAND_NOT_FOUND' }
167
175
  const commandExited = Number.isInteger(error.exitCode) && (error.code === 'COMMAND_EXITED_WITH_CODE' || error.command)
168
176
 
169
177
  // no color on these errors as they can be standard errors for things like jest exiting with exitCode 1 for a single failed test.
@@ -178,6 +186,9 @@ async function executeCommand (commandArgs, env, sensitiveValues = [], onComplet
178
186
  // Exit with the error code from the command process, or 1 if unavailable
179
187
  commandExitCode = error.exitCode || 1
180
188
  } finally {
189
+ // Child exit can precede pipe EOF. Let redaction flush its held-back tail
190
+ // before the action returns and the CLI exits.
191
+ await Promise.all(outputFinished)
181
192
  signalForwardTimers.forEach(timer => clearTimeout(timer))
182
193
  signalForwardTimers.clear()
183
194
 
@@ -192,7 +203,7 @@ async function executeCommand (commandArgs, env, sensitiveValues = [], onComplet
192
203
  if (onComplete) await onComplete()
193
204
  }
194
205
 
195
- if (commandExitCode) process.exit(commandExitCode)
206
+ return { exitCode: commandExitCode || 0, signal: commandSignal, error: commandError }
196
207
  }
197
208
 
198
209
  module.exports = executeCommand
@@ -1,11 +1,7 @@
1
- const { scan, encrypted } = require('@dotenvx/primitives')
1
+ const { sealed } = require('@dotenvx/primitives')
2
2
 
3
3
  function hasPlaintextSecrets (src) {
4
- const { parsed } = scan(src)
5
- return Object.entries(parsed).some(([key, values]) => {
6
- if (key.startsWith('DOTENV_PUBLIC_KEY') || key.endsWith('_PLAIN')) return false
7
- return values.some(value => value.trim() !== '' && !encrypted(value))
8
- })
4
+ return !sealed(src)
9
5
  }
10
6
 
11
7
  module.exports = hasPlaintextSecrets
@@ -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.d.ts CHANGED
@@ -1,5 +1,19 @@
1
1
  import type { URL } from 'url';
2
2
 
3
+ export interface EventSdk {
4
+ config: typeof config;
5
+ get: typeof get;
6
+ set: typeof set;
7
+ /** Flush event delivery for calls that have completed. Await operations first. */
8
+ flushEvents(): Promise<void>;
9
+ }
10
+
11
+ /**
12
+ * Create an explicitly instrumented SDK client using connected Armor. config() remains synchronous;
13
+ * get()/set() preserve their results and errors. Plain SDK calls are unchanged.
14
+ */
15
+ export function withEvents(): EventSdk;
16
+
3
17
  export interface DotenvParseOptions {
4
18
  /**
5
19
  * Override any environment variables that have already been set on your machine with values from your .env file.
package/src/lib/main.js CHANGED
@@ -42,7 +42,7 @@ function uniqueInjectedKeys (processedEnvs) {
42
42
  }
43
43
 
44
44
  /** @type {import('./main').config} */
45
- const config = function (options = {}) {
45
+ const config = function (options = {}, events) {
46
46
  options = normalizeDotenvConfigQuiet(options)
47
47
  options = normalizeDotenvConfigConvention(options)
48
48
  options = normalizeDotenvConfigIgnore(options)
@@ -148,6 +148,7 @@ const config = function (options = {}) {
148
148
  }
149
149
  }
150
150
 
151
+ if (events) events.add({ files: readableFilepaths, injected_count: uniqueInjectedKeys(processedEnvs).size })
151
152
  let msg = `injected env (${uniqueInjectedKeys(processedEnvs).size})`
152
153
  if (readableFilepaths.length > 0) {
153
154
  msg += ` from ${readableFilepaths.join(', ')}`
@@ -155,11 +156,13 @@ const config = function (options = {}) {
155
156
  logger.success(`⟐ ${msg}`)
156
157
 
157
158
  if (lastError) {
159
+ if (events) events.fail(lastError)
158
160
  return { parsed: parsedAll, error: lastError }
159
161
  } else {
160
162
  return { parsed: parsedAll }
161
163
  }
162
164
  } catch (error) {
165
+ if (events) events.fail(error)
163
166
  if (strict) throw error // throw immediately if strict
164
167
 
165
168
  logger.error(error.messageWithHelp || error.message)
@@ -223,7 +226,7 @@ const parse = function (src, options = {}) {
223
226
  }
224
227
 
225
228
  /* @type {import('./main').set} */
226
- const set = async function (key, value, options = {}) {
229
+ const set = async function (key, value, options = {}, events) {
227
230
  options = normalizeDotenvConfigQuiet(options)
228
231
 
229
232
  // encrypt
@@ -288,7 +291,9 @@ const set = async function (key, value, options = {}) {
288
291
  logger.verbose(`${processedEnv.key} set${withEncryption} (${processedEnv.envFilepath})`)
289
292
  logger.debug(`${processedEnv.key} set${withEncryption} to ${processedEnv.value} (${processedEnv.envFilepath})`)
290
293
  }
294
+ if (events) events.file(processedEnv, { key, output: 'file' })
291
295
  }
296
+ if (events) events.add({ error_count: processedEnvs.filter(env => env.error).length })
292
297
 
293
298
  let keyAddedSuffix = ''
294
299
  const localKeyAddedEnv = processedEnvs.find((processedEnv) => processedEnv.localPrivateKeyAdded)
@@ -323,7 +328,7 @@ const set = async function (key, value, options = {}) {
323
328
  }
324
329
 
325
330
  /* @type {import('./main').get} */
326
- const get = async function (key, options = {}) {
331
+ const get = async function (key, options = {}, events) {
327
332
  options = normalizeDotenvConfigConvention(options)
328
333
  options = normalizeDotenvConfigIgnore(options)
329
334
 
@@ -359,11 +364,13 @@ const get = async function (key, options = {}) {
359
364
  continue // ignore error
360
365
  }
361
366
 
367
+ if (events) events.fail(error)
362
368
  if (options.strict) throw error // throw immediately if strict
363
369
 
364
370
  logger.error(error.messageWithHelp || error.message)
365
371
  }
366
372
 
373
+ if (events) events.add({ error_count: (errors || []).filter(error => !ignore.includes(error.code)).length })
367
374
  if (key) {
368
375
  const single = parsed[key]
369
376
  if (single === undefined) {
@@ -417,7 +424,12 @@ function resolveNoNative (options = {}) {
417
424
  return options.noNative === true || options.native === false
418
425
  }
419
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.
420
431
  module.exports = {
432
+ withEvents,
421
433
  // dotenv proxies
422
434
  config,
423
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
- process.exitCode = 1
16
- }
17
- }