@mono-labs/cli 0.1.289 → 0.1.292

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 (34) hide show
  1. package/dist/lib/commands/build-process/buildBaseEnv.d.ts +9 -1
  2. package/dist/lib/commands/build-process/buildBaseEnv.d.ts.map +1 -1
  3. package/dist/lib/commands/build-process/buildBaseEnv.js +16 -5
  4. package/dist/lib/commands/build-process/cliFactory.d.ts.map +1 -1
  5. package/dist/lib/commands/build-process/cliFactory.js +18 -20
  6. package/dist/lib/commands/build-process/runMonoCommand.d.ts +13 -0
  7. package/dist/lib/commands/build-process/runMonoCommand.d.ts.map +1 -1
  8. package/dist/lib/commands/build-process/runMonoCommand.js +74 -5
  9. package/dist/lib/commands/build-process/runners/errors.d.ts +16 -0
  10. package/dist/lib/commands/build-process/runners/errors.d.ts.map +1 -0
  11. package/dist/lib/commands/build-process/runners/errors.js +42 -0
  12. package/dist/lib/commands/build-process/runners/processManager.d.ts +5 -0
  13. package/dist/lib/commands/build-process/runners/processManager.d.ts.map +1 -1
  14. package/dist/lib/commands/build-process/runners/processManager.js +29 -19
  15. package/dist/lib/commands/build-process/runners/runBackground.d.ts +2 -1
  16. package/dist/lib/commands/build-process/runners/runBackground.d.ts.map +1 -1
  17. package/dist/lib/commands/build-process/runners/runBackground.js +5 -5
  18. package/dist/lib/commands/build-process/runners/runForeground.d.ts.map +1 -1
  19. package/dist/lib/commands/build-process/runners/runForeground.js +3 -4
  20. package/dist/lib/commands/prune/prune.d.ts.map +1 -1
  21. package/dist/lib/commands/prune/prune.js +3 -1
  22. package/dist/lib/index.d.ts.map +1 -1
  23. package/dist/lib/index.js +26 -13
  24. package/dist/tsconfig.tsbuildinfo +1 -1
  25. package/lib/commands/build-process/buildBaseEnv.ts +19 -8
  26. package/lib/commands/build-process/cliFactory.ts +18 -19
  27. package/lib/commands/build-process/runMonoCommand.ts +89 -6
  28. package/lib/commands/build-process/runners/errors.ts +42 -0
  29. package/lib/commands/build-process/runners/processManager.ts +25 -16
  30. package/lib/commands/build-process/runners/runBackground.ts +7 -5
  31. package/lib/commands/build-process/runners/runForeground.ts +3 -6
  32. package/lib/commands/prune/prune.ts +3 -1
  33. package/lib/index.ts +29 -13
  34. package/package.json +4 -4
@@ -1,10 +1,12 @@
1
1
  import { runForeground } from './runners/runForeground'
2
2
  import { runBackground } from './runners/runBackground'
3
- import { killAllBackground } from './runners/processManager'
3
+ import { killAllBackground, killTree } from './runners/processManager'
4
+ import type { ChildProcess } from 'node:child_process'
4
5
  import { getMonoConfig } from '../loadFromRoot'
5
6
  import { buildBaseEnv } from './buildBaseEnv'
6
7
  import { mergeData } from './dataLayer'
7
8
  import { writeLog } from '@mono-labs/shared'
9
+ import { INJECTED_KEYS_VAR } from '@mono-labs/project'
8
10
 
9
11
  export function getAllowAllKeys(cfg: any): string[] {
10
12
  const decls = cfg.options ?? {}
@@ -18,6 +20,58 @@ export function getAllowAllKeys(cfg: any): string[] {
18
20
  .map(([k]) => k)
19
21
  }
20
22
 
23
+ const PROFILE_KEYS = ['CDK_DEPLOY_PROFILE', 'AWS_PROFILE'] as const
24
+
25
+ /**
26
+ * AWS profile for a command. Highest priority first:
27
+ * 1. the command's `environments` block (direct config, `$KEY` refs already resolved)
28
+ * 2. real shell variables
29
+ * 3. values from the command's env files
30
+ * Within each source CDK_DEPLOY_PROFILE wins over AWS_PROFILE.
31
+ */
32
+ export function resolveAwsProfile(
33
+ envConfig: Record<string, any>,
34
+ baseEnv: NodeJS.ProcessEnv
35
+ ): string {
36
+ return resolveAwsProfileWithSource(envConfig, baseEnv).profile
37
+ }
38
+
39
+ export type AwsProfileSource = 'config' | 'shell' | 'files' | 'default'
40
+
41
+ export function resolveAwsProfileWithSource(
42
+ envConfig: Record<string, any>,
43
+ baseEnv: NodeJS.ProcessEnv
44
+ ): { profile: string; source: AwsProfileSource } {
45
+ const injected = new Set((baseEnv[INJECTED_KEYS_VAR] ?? '').split(',').filter(Boolean))
46
+ const fromConfig = (k: string) => envConfig[k]
47
+ const fromShell = (k: string) => (injected.has(k) ? undefined : baseEnv[k])
48
+ const fromFiles = (k: string) => (injected.has(k) ? baseEnv[k] : undefined)
49
+
50
+ const sources: [AwsProfileSource, (k: string) => unknown][] = [
51
+ ['config', fromConfig],
52
+ ['shell', fromShell],
53
+ ['files', fromFiles],
54
+ ]
55
+ for (const [source, read] of sources) {
56
+ for (const key of PROFILE_KEYS) {
57
+ const value = read(key)
58
+ if (typeof value === 'string' && value.trim()) return { profile: value, source }
59
+ }
60
+ }
61
+ return { profile: 'default', source: 'default' }
62
+ }
63
+
64
+ /**
65
+ * Record in baseEnv whether the AWS_PROFILE mono hands to children is injected. A profile from
66
+ * env files or the 'default' fallback is injected, so a nested mono command may replace it; one
67
+ * from the shell or the environments block is explicit and is kept like a shell variable.
68
+ */
69
+ function markAwsProfileProvenance(baseEnv: NodeJS.ProcessEnv, source: AwsProfileSource): void {
70
+ const keys = (baseEnv[INJECTED_KEYS_VAR] ?? '').split(',').filter((k) => k && k !== 'AWS_PROFILE')
71
+ if (source === 'files' || source === 'default') keys.push('AWS_PROFILE')
72
+ baseEnv[INJECTED_KEYS_VAR] = keys.join(',')
73
+ }
74
+
21
75
  /**
22
76
  * Orchestrate execution of a single mono command definition.
23
77
  * Phases:
@@ -32,10 +86,9 @@ export async function runMonoCommand(configObject: any, options: any = {}): Prom
32
86
  mergeData({ ...options })
33
87
 
34
88
  // Resolve which env files this command loads (per-command `envFiles` or the defaults)
35
- const { baseEnv, keymap, files: envFiles } = buildBaseEnv(configObject, config)
89
+ const { baseEnv, keymap, files: envFiles, inheritedFromParent } = buildBaseEnv(configObject, config)
36
90
 
37
91
  const prodConfig = configObject.environments?.prod ?? {}
38
- const awsProfile = process.env.CDK_DEPLOY_PROFILE || process.env.AWS_PROFILE || 'default'
39
92
  const envObjBase: Record<string, any> = options.prod ? { ...prodConfig } : { ...devConfig }
40
93
 
41
94
  Object.keys(envObjBase).forEach((k) => {
@@ -48,7 +101,12 @@ export async function runMonoCommand(configObject: any, options: any = {}): Prom
48
101
  envObjBase[k] = (keymap as any)[refKey] || ''
49
102
  }
50
103
  })
104
+ const { profile: awsProfile, source: awsProfileSource } = resolveAwsProfileWithSource(
105
+ envObjBase,
106
+ baseEnv
107
+ )
51
108
  envObjBase.AWS_PROFILE = awsProfile
109
+ markAwsProfileProvenance(baseEnv, awsProfileSource)
52
110
 
53
111
  const envKeys = Object.keys(baseEnv).filter((k) => k.startsWith('MONO_'))
54
112
  const envMapList = config.envMap ?? ['FAILURE']
@@ -69,7 +127,10 @@ export async function runMonoCommand(configObject: any, options: any = {}): Prom
69
127
  console.log(`→ Executing mono command: ${configObject.name || 'Unnamed Command'}`)
70
128
  console.log(`→ Using AWS profile: ${awsProfile}`)
71
129
  console.log(`→ Using environment: ${options.stage ? 'stage' : 'dev'}`)
72
- console.log(`→ Env files: ${envFiles.length ? envFiles.join(', ') : '(none)'}`)
130
+ console.log(
131
+ `→ Env files: ${envFiles.length ? envFiles.join(', ') : '(none)'}` +
132
+ (inheritedFromParent ? " (from parent mono command; this command's envFiles ignored)" : '')
133
+ )
73
134
  console.log('→ Environment variables:', envObj)
74
135
 
75
136
  // Run preactions sequentially
@@ -82,13 +143,35 @@ export async function runMonoCommand(configObject: any, options: any = {}): Prom
82
143
  const bg = actions.slice(0, -1)
83
144
  const fg = actions[actions.length - 1]
84
145
 
146
+ // A background action that fails while the foreground is still running fails the whole
147
+ // command: the foreground is stopped and mono exits with the background's code. Once the
148
+ // foreground is done, background exits are caused by our own cleanup kill and are ignored.
149
+ let stopping = false
150
+ let fgChild: ChildProcess | undefined
151
+ let failBackground: (err: unknown) => void = () => {}
152
+ const backgroundFailed = new Promise<never>((_, reject) => {
153
+ failBackground = reject
154
+ })
155
+ backgroundFailed.catch(() => {}) // only observed through the race below
156
+
85
157
  for (const cmd of bg) {
86
- void runBackground(cmd, envObj, 'background', false, baseEnv)
158
+ runBackground(cmd, envObj, 'background', false, baseEnv).catch((err) => {
159
+ if (stopping) return
160
+ console.error(`✖ Background action failed: ${(err as Error)?.message ?? err}`)
161
+ failBackground(err)
162
+ })
87
163
  }
88
164
 
89
165
  try {
90
- await runBackground(fg, envObj, 'foreground', true, baseEnv)
166
+ await Promise.race([
167
+ runBackground(fg, envObj, 'foreground', true, baseEnv, (child) => {
168
+ fgChild = child
169
+ }),
170
+ backgroundFailed,
171
+ ])
91
172
  } finally {
173
+ stopping = true
174
+ if (fgChild) killTree(fgChild)
92
175
  killAllBackground()
93
176
  }
94
177
  }
@@ -0,0 +1,42 @@
1
+ import os from 'node:os'
2
+
3
+ /**
4
+ * A failure that knows which exit code mono should end with.
5
+ *
6
+ * Every runner rejects with this, and the top-level handler in `lib/index.ts` turns it into
7
+ * `process.exitCode`. Nothing between the runner and that handler may swallow it.
8
+ */
9
+ export class MonoCommandError extends Error {
10
+ readonly exitCode: number
11
+
12
+ constructor(message: string, exitCode = 1) {
13
+ super(message)
14
+ this.name = 'MonoCommandError'
15
+ // 0 would report success for a failure, so never allow it here.
16
+ this.exitCode = Number.isInteger(exitCode) && exitCode > 0 ? exitCode : 1
17
+ }
18
+ }
19
+
20
+ /** Shell convention: a child killed by a signal exits with 128 + the signal number. */
21
+ export function exitCodeFromChild(code: number | null, signal: NodeJS.Signals | null): number {
22
+ if (signal) {
23
+ const num = (os.constants.signals as Record<string, number>)[signal]
24
+ return num ? 128 + num : 1
25
+ }
26
+ return code ?? 1
27
+ }
28
+
29
+ export function childFailure(
30
+ cmd: string,
31
+ code: number | null,
32
+ signal: NodeJS.Signals | null,
33
+ detail = ''
34
+ ): MonoCommandError {
35
+ const how = signal ? `was killed by signal ${signal}` : `exited with code ${code}`
36
+ return new MonoCommandError(`${cmd} ${how}${detail}`, exitCodeFromChild(code, signal))
37
+ }
38
+
39
+ /** Exit code to use for any error reaching the top level. */
40
+ export function exitCodeOf(err: unknown): number {
41
+ return err instanceof MonoCommandError ? err.exitCode : 1
42
+ }
@@ -21,25 +21,34 @@ function isRunning(child: ChildProcess): boolean {
21
21
  return Boolean(child.pid) && child.exitCode === null && child.signalCode === null
22
22
  }
23
23
 
24
+ /**
25
+ * Kill a child and everything it started, if it is still running.
26
+ * `detached` children lead their own process group on POSIX, so the whole group is signalled.
27
+ */
28
+ export function killTree(child: ChildProcess, detached = false): void {
29
+ if (!isRunning(child)) return
30
+ try {
31
+ if (process.platform === 'win32') {
32
+ spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], {
33
+ shell: true,
34
+ stdio: 'ignore',
35
+ windowsHide: true,
36
+ })
37
+ } else if (detached) {
38
+ process.kill(-(child.pid as number), 'SIGTERM')
39
+ } else {
40
+ child.kill('SIGTERM')
41
+ }
42
+ } catch {
43
+ // ignore
44
+ }
45
+ }
46
+
24
47
  export function killAllBackground(): void {
25
48
  for (const child of Array.from(bgChildren)) {
26
49
  bgChildren.delete(child)
27
- if (!isRunning(child)) continue
28
- try {
29
- if (process.platform === 'win32') {
30
- spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], {
31
- shell: true,
32
- stdio: 'ignore',
33
- windowsHide: true,
34
- })
35
- } else {
36
- // Registered children are always spawned `detached`, so they lead their own process
37
- // group and the negative-pid form is ours to signal.
38
- process.kill(-(child.pid as number), 'SIGTERM')
39
- }
40
- } catch {
41
- // ignore
42
- }
50
+ // Registered children are always spawned `detached`.
51
+ killTree(child, true)
43
52
  }
44
53
  bgChildren.clear()
45
54
  }
@@ -1,7 +1,8 @@
1
- import { spawn } from 'child_process'
1
+ import { spawn, type ChildProcess } from 'child_process'
2
2
  import { replaceTokens } from '../dataLayer'
3
3
  import { registerBackground } from './processManager'
4
4
  import { writeLog } from '@mono-labs/shared'
5
+ import { childFailure } from './errors'
5
6
 
6
7
  function createdExpandedEnv(envObj: Record<string, unknown>): Record<string, unknown> {
7
8
  const expandedEnv: Record<string, unknown> = {}
@@ -17,7 +18,8 @@ export function runBackground(
17
18
  envObj: Record<string, unknown> = {},
18
19
  logName = 'background',
19
20
  attached = false,
20
- baseEnv: NodeJS.ProcessEnv = process.env
21
+ baseEnv: NodeJS.ProcessEnv = process.env,
22
+ onSpawn?: (child: ChildProcess) => void
21
23
  ): Promise<void> {
22
24
  const isWin = process.platform === 'win32'
23
25
 
@@ -45,15 +47,15 @@ export function runBackground(
45
47
  // completion right below, so there is never anything left of it to clean up — and by the
46
48
  // time `runMonoCommand`'s `finally` fires, its pid is the OS's to reuse.
47
49
  if (!attached) registerBackground(child)
50
+ onSpawn?.(child)
48
51
 
49
52
  child.once('error', (err) => {
50
53
  reject(err)
51
54
  })
52
55
 
53
56
  child.once('exit', (code, signal) => {
54
- if (signal) return reject(new Error(`${cmd} exited via signal ${signal}`))
55
- if (code === 0) return resolve()
56
- reject(new Error(`${cmd} exited with code ${code}`))
57
+ if (code === 0 && !signal) return resolve()
58
+ reject(childFailure(outCmd, code, signal))
57
59
  })
58
60
  })
59
61
  }
@@ -1,6 +1,7 @@
1
1
  import { spawn } from 'child_process';
2
2
  import { replaceTokens, setData } from '../dataLayer';
3
3
  import { filterUnwantedEnvVars } from '../../../filterUnwantedEnvVars';
4
+ import { childFailure } from './errors';
4
5
 
5
6
  // Regex to capture tokens like: {out:field value}
6
7
  const TOKEN_RX = /\{out:(?<field>[^\s}]+)\s+(?<value>[^\s}]+)\}/g;
@@ -52,12 +53,8 @@ export function runForeground(
52
53
  }
53
54
  }
54
55
 
55
- if (signal)
56
- return reject(new Error(`${cmd} exited via signal ${signal}`));
57
- if (code === 0) return resolve(lastLine);
58
- reject(
59
- new Error(`${cmd} exited with code ${code}. Last line: ${lastLine}`)
60
- );
56
+ if (code === 0 && !signal) return resolve(lastLine);
57
+ reject(childFailure(newCmd, code, signal, `. Last line: ${lastLine}`));
61
58
  });
62
59
  });
63
60
  }
@@ -26,7 +26,7 @@ export function pruneRepo() {
26
26
  const branchesToDelete = localBranches.filter((branch) => !remoteBranches.includes(branch))
27
27
  if (branchesToDelete.length === 0) {
28
28
  log('No local branches to delete.')
29
- process.exit(0)
29
+ return
30
30
  }
31
31
 
32
32
  // Delete untracked local branches
@@ -39,6 +39,7 @@ export function pruneRepo() {
39
39
  } catch (caught: unknown) {
40
40
  const error = caught as { message?: string }
41
41
  err(`Failed to delete branch ${branch}:`, error.message ?? String(caught))
42
+ process.exitCode = 1
42
43
  }
43
44
  })
44
45
 
@@ -46,5 +47,6 @@ export function pruneRepo() {
46
47
  } catch (caught: unknown) {
47
48
  const error = caught as { message?: string }
48
49
  err('An error occurred:', error.message ?? String(caught))
50
+ process.exitCode = 1
49
51
  }
50
52
  }
package/lib/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  loadMergedEnv,
3
+ envFilesFromEnv,
3
4
  getInjectedEnvKeys,
4
5
  getLoadedEnvFiles,
5
6
  ENV_FILES_VAR,
@@ -15,12 +16,14 @@ import { program } from './app'
15
16
  import './commands/prune/index'
16
17
  import './commands/build-process/index'
17
18
  import { getMonoConfig } from './commands/loadFromRoot'
19
+ import { exitCodeFromChild, exitCodeOf } from './commands/build-process/runners/errors'
18
20
  import { executeCommandsIfWorkspaceAction } from './commands/build-process/test'
19
21
 
20
22
  const { config } = getMonoConfig() as any
21
23
 
22
- // Global default from .mono/config.json `envFiles`; falls back to MONOLABS_ENV_FILES, then .env + .env.local
23
- loadMergedEnv(config.envFiles)
24
+ // MONOLABS_ENV_FILES (the selection of a parent mono command) wins, then .mono/config.json
25
+ // `envFiles`, then .env + .env.local
26
+ loadMergedEnv(envFilesFromEnv() ?? config.envFiles)
24
27
 
25
28
  const homeBin = path.join(os.homedir(), 'bin')
26
29
  const PATH = [homeBin, process.env.PATH].filter(Boolean).join(path.delimiter)
@@ -49,25 +52,38 @@ program.on('command:*', (operands: string[]) => {
49
52
 
50
53
  const args = ['workspace', workspace, ...rest]
51
54
 
55
+ // Every child (workspace preactions and the yarn fallback) gets the full env, injected values included
56
+ const childEnv: NodeJS.ProcessEnv = {
57
+ ...process.env,
58
+ ...envObj,
59
+ PATH,
60
+ [ENV_FILES_VAR]: getLoadedEnvFiles().join(path.delimiter),
61
+ [INJECTED_KEYS_VAR]: getInjectedEnvKeys().join(','),
62
+ }
63
+
52
64
  console.error(`Unknown command. Falling back2 to: yarn ${args.join(' ')}`)
53
- executeCommandsIfWorkspaceAction(args, preactions, envObj)
65
+ executeCommandsIfWorkspaceAction(args, preactions, childEnv)
54
66
 
55
67
  const child = spawn('yarn', args, {
56
68
  stdio: 'inherit',
57
69
  shell: process.platform === 'win32',
58
- env: {
59
- ...process.env,
60
- ...envObj,
61
- PATH,
62
- [ENV_FILES_VAR]: getLoadedEnvFiles().join(path.delimiter),
63
- [INJECTED_KEYS_VAR]: getInjectedEnvKeys().join(','),
64
- },
70
+ env: childEnv,
71
+ })
72
+
73
+ child.on('error', (err) => {
74
+ console.error(`✖ mono: failed to start yarn: ${err.message}`)
75
+ process.exitCode = 1
65
76
  })
66
77
 
67
- child.on('exit', (code) => {
78
+ child.on('exit', (code, signal) => {
68
79
  writeLog('Child process exited with code:', code)
69
- process.exitCode = code ?? 1
80
+ process.exitCode = exitCodeFromChild(code, signal)
70
81
  })
71
82
  })
72
83
 
73
- program.parse()
84
+ // The single place where a mono failure becomes an exit code. Command actions are async, so
85
+ // parseAsync is required: with parse() a rejected action is dropped and mono exits 0.
86
+ program.parseAsync().catch((err: unknown) => {
87
+ console.error(`✖ mono: ${(err as Error)?.message ?? err}`)
88
+ process.exitCode = exitCodeOf(err)
89
+ })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mono-labs/cli",
3
- "version": "0.1.289",
3
+ "version": "0.1.292",
4
4
  "type": "commonjs",
5
5
  "description": "A CLI tool for building and deploying projects",
6
6
  "main": "dist/index.js",
@@ -27,7 +27,7 @@
27
27
  "build": "tsc",
28
28
  "start": "node bin/mono.js",
29
29
  "dev": "node bin/mono.js",
30
- "test": "echo \"Error: no test specified\" && exit 1",
30
+ "test": "tsc && node --test test/exit-codes.test.js test/env-provenance.test.js",
31
31
  "deploy": "tsc && npm publish --access public --registry https://registry.npmjs.org/",
32
32
  "release:patch": "npm version patch -m \"chore: release %s\" && npm publish --access public",
33
33
  "release:minor": "npm version minor -m \"chore: release %s\" && npm publish --access public",
@@ -45,8 +45,8 @@
45
45
  "node": ">=20.0.0"
46
46
  },
47
47
  "dependencies": {
48
- "@mono-labs/shared": "0.1.289",
49
- "@mono-labs/project": "0.1.289",
48
+ "@mono-labs/shared": "0.1.292",
49
+ "@mono-labs/project": "0.1.292",
50
50
  "chalk": "^4.1.2",
51
51
  "commander": "^11.1.0",
52
52
  "cross-spawn": "^7.0.6",