hazo_env 0.16.0 → 0.18.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,136 @@
1
+ // hazo_env/src/deploy/idle-slots.ts — `deploy clean --idle-slots`
2
+ //
3
+ // A host running several blue-green apps keeps a full standby checkout per
4
+ // app, each with its own `node_modules` + `.next` — easily 1 GB+ apiece of
5
+ // disk that nothing is using between deploys. This reclaims exactly those
6
+ // two folders from every app's IDLE standby slot, across every state file
7
+ // in ~/.hazo-deploy (not just the current app's), so it runs from anywhere
8
+ // and needs no [deploy] config in cwd.
9
+ //
10
+ // Safety, per slot (any one skips it, with the reason reported):
11
+ // - it is any app's live_dir;
12
+ // - it is (or contains) the current working directory;
13
+ // - a PM2 process's pm2_env.pm_cwd is (or is inside) it;
14
+ // - its last_build is newer than last_switch (built but not yet switched —
15
+ // clearing it would force a rebuild before `deploy switch`).
16
+ // If `pm2 jlist` can't be read, the whole run aborts: without it nothing
17
+ // proves a slot is idle. Only `node_modules` and `.next` are ever removed —
18
+ // never data/, config, .env*, or shared dirs; a target that is a symlink is
19
+ // left alone (it may point into shared storage). Dry-run by default; pass
20
+ // `yes` to delete. All measurement/removal goes through CommandRunner.
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+ import { getStateDir } from './state.js';
24
+ export const IDLE_SLOT_TARGETS = ['node_modules', '.next'];
25
+ export class IdleSlotsAbortError extends Error {
26
+ constructor(message) {
27
+ super(message);
28
+ this.name = 'IdleSlotsAbortError';
29
+ }
30
+ }
31
+ function isSameOrInside(child, parent) {
32
+ const rel = path.relative(parent, child);
33
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
34
+ }
35
+ function readAllStates(warnings) {
36
+ const dir = getStateDir();
37
+ if (!fs.existsSync(dir))
38
+ return [];
39
+ const states = [];
40
+ for (const file of fs.readdirSync(dir).filter((f) => f.endsWith('.json')).sort()) {
41
+ try {
42
+ const state = JSON.parse(fs.readFileSync(path.join(dir, file), 'utf-8'));
43
+ if (state && typeof state.standby_dir === 'string' && typeof state.live_dir === 'string') {
44
+ states.push(state);
45
+ }
46
+ else {
47
+ warnings.push(`skipping state file ${file}: missing live_dir/standby_dir`);
48
+ }
49
+ }
50
+ catch {
51
+ warnings.push(`skipping state file ${file}: not valid JSON`);
52
+ }
53
+ }
54
+ return states;
55
+ }
56
+ function queryPm2Cwds(runner) {
57
+ const result = runner.spawn('pm2 jlist');
58
+ if (result.code !== 0) {
59
+ throw new IdleSlotsAbortError(`pm2 jlist failed (exit ${result.code}): ${result.stderr.trim() || 'no stderr'} — cannot prove any slot is idle, nothing cleaned.`);
60
+ }
61
+ let parsed;
62
+ try {
63
+ parsed = JSON.parse(result.stdout);
64
+ }
65
+ catch {
66
+ throw new IdleSlotsAbortError('pm2 jlist returned unparsable JSON — cannot prove any slot is idle, nothing cleaned.');
67
+ }
68
+ if (!Array.isArray(parsed)) {
69
+ throw new IdleSlotsAbortError('pm2 jlist did not return a list — cannot prove any slot is idle, nothing cleaned.');
70
+ }
71
+ return parsed
72
+ .filter((p) => typeof p.pm2_env?.pm_cwd === 'string')
73
+ .map((p) => ({ name: p.name ?? '(unnamed)', cwd: path.resolve(p.pm2_env.pm_cwd) }));
74
+ }
75
+ function skipReasonFor(state, slot, cwd, liveDirs, pm2Cwds) {
76
+ if (!fs.existsSync(slot))
77
+ return 'slot directory does not exist';
78
+ if (liveDirs.includes(slot))
79
+ return 'it is a live_dir';
80
+ if (isSameOrInside(cwd, slot))
81
+ return 'it is the current working directory';
82
+ const proc = pm2Cwds.find((p) => isSameOrInside(p.cwd, slot));
83
+ if (proc)
84
+ return `PM2 process "${proc.name}" is running from it`;
85
+ if (state.last_build && (!state.last_switch || Date.parse(state.last_build) > Date.parse(state.last_switch))) {
86
+ return `pending build (last_build ${state.last_build} is newer than last_switch ${state.last_switch ?? '(never)'}) — clearing it would force a rebuild before switch`;
87
+ }
88
+ return undefined;
89
+ }
90
+ function measureKb(runner, absPath) {
91
+ const result = runner.spawn(`du -sk ${JSON.stringify(absPath)}`);
92
+ if (result.code !== 0)
93
+ return undefined;
94
+ const kb = Number(result.stdout.trim().split(/\s+/)[0]);
95
+ return Number.isFinite(kb) ? kb : undefined;
96
+ }
97
+ function processTarget(runner, slot, name, yes, warnings) {
98
+ const absPath = path.join(slot, name);
99
+ if (runner.spawn(`test -L ${JSON.stringify(absPath)}`).code === 0) {
100
+ return { name, path: absPath, bytes: 0, skipped: true, skipReason: 'symlink — left alone (may point at shared storage)', removed: false };
101
+ }
102
+ const kb = measureKb(runner, absPath);
103
+ if (kb === undefined) {
104
+ return { name, path: absPath, bytes: 0, skipped: true, skipReason: 'not present', removed: false };
105
+ }
106
+ const bytes = kb * 1024;
107
+ if (!yes)
108
+ return { name, path: absPath, bytes, skipped: false, removed: false };
109
+ const rm = runner.spawn(`rm -rf ${JSON.stringify(absPath)}`);
110
+ if (rm.code !== 0) {
111
+ const error = rm.stderr.trim() || `exit ${rm.code}`;
112
+ warnings.push(`failed to remove ${absPath}: ${error}`);
113
+ return { name, path: absPath, bytes: 0, skipped: false, removed: false, error };
114
+ }
115
+ return { name, path: absPath, bytes, skipped: false, removed: true };
116
+ }
117
+ /** See this file's header. Throws IdleSlotsAbortError only when PM2 state can't be read. */
118
+ export function runCleanIdleSlots(runner, opts = {}) {
119
+ const yes = opts.yes === true;
120
+ const cwd = path.resolve(opts.cwd ?? process.cwd());
121
+ const warnings = [];
122
+ const states = readAllStates(warnings);
123
+ const pm2Cwds = states.length > 0 ? queryPm2Cwds(runner) : [];
124
+ const liveDirs = states.map((s) => path.resolve(s.live_dir));
125
+ const slots = states.map((state) => {
126
+ const slot = path.resolve(state.standby_dir);
127
+ const skipReason = skipReasonFor(state, slot, cwd, liveDirs, pm2Cwds);
128
+ if (skipReason) {
129
+ return { app_name: state.app_name, slot_dir: slot, eligible: false, skipReason, targets: [], bytes: 0 };
130
+ }
131
+ const targets = IDLE_SLOT_TARGETS.map((name) => processTarget(runner, slot, name, yes, warnings));
132
+ const bytes = targets.reduce((sum, t) => sum + t.bytes, 0);
133
+ return { app_name: state.app_name, slot_dir: slot, eligible: true, targets, bytes };
134
+ });
135
+ return { dryRun: !yes, slots, totalBytes: slots.reduce((sum, s) => sum + s.bytes, 0), warnings };
136
+ }
@@ -14,4 +14,6 @@ export * from './switch.js';
14
14
  export * from './rollback.js';
15
15
  export * from './share.js';
16
16
  export * from './help.js';
17
+ export * from './preflight.js';
18
+ export * from './idle-slots.js';
17
19
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/deploy/index.ts"],"names":[],"mappings":"AAUA,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC;AAC9B,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/deploy/index.ts"],"names":[],"mappings":"AAUA,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC;AAC9B,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC"}
@@ -24,3 +24,5 @@ export * from './switch.js';
24
24
  export * from './rollback.js';
25
25
  export * from './share.js';
26
26
  export * from './help.js';
27
+ export * from './preflight.js';
28
+ export * from './idle-slots.js';
@@ -19,6 +19,12 @@ export interface RunInitResult {
19
19
  * every existing caller of `runInit` is unaffected).
20
20
  */
21
21
  sharedDirsLinked: EnsureLinkResult[];
22
+ /**
23
+ * Slot dirs whose `.git/info/exclude` gained a `config/hazo_env_config.ini`
24
+ * entry (the INI is per-slot, so it must never be committed). Local to each
25
+ * clone, so it never dirties a tracked .gitignore.
26
+ */
27
+ configExcludedFrom: string[];
22
28
  }
23
29
  /**
24
30
  * Create the peer (standby) directory: resolve its path, abort if it
@@ -1 +1 @@
1
- {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/deploy/init.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAe,MAAM,YAAY,CAAC;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAgDzD,MAAM,WAAW,cAAc;IAC7B,iFAAiF;IACjF,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,oEAAoE;IACpE,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B;;;;;OAKG;IACH,gBAAgB,EAAE,gBAAgB,EAAE,CAAC;CACtC;AA0CD;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,cAAmB,GAAG,aAAa,CA0D7G"}
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/deploy/init.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAe,MAAM,YAAY,CAAC;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAoDzD,MAAM,WAAW,cAAc;IAC7B,iFAAiF;IACjF,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,oEAAoE;IACpE,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B;;;;;OAKG;IACH,gBAAgB,EAAE,gBAAgB,EAAE,CAAC;IACrC;;;;OAIG;IACH,kBAAkB,EAAE,MAAM,EAAE,CAAC;CAC9B;AA0CD;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,cAAmB,GAAG,aAAa,CAgE7G"}
@@ -19,6 +19,7 @@ import { resolvePeerDir } from './peer.js';
19
19
  import { writeState } from './state.js';
20
20
  import { getEnv } from '../index.client.js';
21
21
  import { ensureLinks } from './shared-dirs.js';
22
+ import { deployConfigPinsDirSuffix, excludeDeployConfigFromGit } from './preflight.js';
22
23
  const CONFIG_RELATIVE_PATH = path.join('config', 'hazo_env_config.ini');
23
24
  // Matches resolve/files.ts's DEFAULT_DATA_ROOT — kept as a local literal
24
25
  // rather than importing that module, since resolveFilesConfig()/
@@ -50,12 +51,16 @@ function swapDirSuffixValue(value) {
50
51
  /**
51
52
  * Swap the `dir_suffix = <value>` line in the INI's [deploy] section to its
52
53
  * blue/green opposite, leaving every other byte of the file untouched.
54
+ *
55
+ * An INI with no `dir_suffix` line is returned unchanged: the suffix is then
56
+ * inferred from each slot's directory name (see `inferColorFromDir`), so both
57
+ * slots share one byte-identical — committable — file.
53
58
  */
54
59
  function swapDirSuffixInIni(iniContent) {
55
60
  const pattern = /^(\s*dir_suffix\s*=\s*)(\S+)(\s*)$/m;
56
61
  const match = iniContent.match(pattern);
57
62
  if (!match) {
58
- throw new Error('Could not find a "dir_suffix = ..." line in hazo_env_config.ini to swap.');
63
+ return iniContent;
59
64
  }
60
65
  const swapped = swapDirSuffixValue(match[2]);
61
66
  return iniContent.replace(pattern, `$1${swapped}$3`);
@@ -144,6 +149,11 @@ export function runInit(config, runner, opts = {}) {
144
149
  envFilesMissing.push(envFile);
145
150
  }
146
151
  }
152
+ // Only a dir_suffix-pinning INI is per-slot; one without it (suffix
153
+ // inferred from the dir name) is meant to be committed, so leave git alone.
154
+ const configExcludedFrom = deployConfigPinsDirSuffix(currentDir)
155
+ ? [currentDir, peerDir].filter((dir) => excludeDeployConfigFromGit(dir))
156
+ : [];
147
157
  const state = {
148
158
  app_name: config.app_name,
149
159
  live_dir: currentDir,
@@ -152,5 +162,5 @@ export function runInit(config, runner, opts = {}) {
152
162
  staging_port: config.staging_port,
153
163
  };
154
164
  writeState(state);
155
- return { currentDir, peerDir, originUrl, envFilesCopied, envFilesMissing, sharedDirsLinked };
165
+ return { currentDir, peerDir, originUrl, envFilesCopied, envFilesMissing, sharedDirsLinked, configExcludedFrom };
156
166
  }
@@ -4,6 +4,15 @@
4
4
  * doesn't end in a recognized color suffix.
5
5
  */
6
6
  export declare function swapColorSuffix(dirName: string): string | undefined;
7
+ /**
8
+ * Infer a slot's color from its directory basename: "kinstripe-blue" ->
9
+ * "blue", "gotimer-green" -> "green". Returns `undefined` when the basename
10
+ * has no recognized color suffix (e.g. an unsuffixed `~/kinstripe` checkout
11
+ * or a dev machine clone). Used by `resolveDeployConfig()` as the fallback
12
+ * for an INI with no `dir_suffix` line — which is what lets the INI be
13
+ * committed to git (identical in both slots).
14
+ */
15
+ export declare function inferColorFromDir(dir: string): string | undefined;
7
16
  /**
8
17
  * Resolve the absolute path to the peer (standby) directory for `currentDir`.
9
18
  *
@@ -1 +1 @@
1
- {"version":3,"file":"peer.d.ts","sourceRoot":"","sources":["../../src/deploy/peer.ts"],"names":[],"mappings":"AAcA;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAQnE;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,MAAM,CAwBnG"}
1
+ {"version":3,"file":"peer.d.ts","sourceRoot":"","sources":["../../src/deploy/peer.ts"],"names":[],"mappings":"AAcA;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAQnE;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAMjE;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,MAAM,CAwBnG"}
@@ -23,6 +23,22 @@ export function swapColorSuffix(dirName) {
23
23
  }
24
24
  return undefined;
25
25
  }
26
+ /**
27
+ * Infer a slot's color from its directory basename: "kinstripe-blue" ->
28
+ * "blue", "gotimer-green" -> "green". Returns `undefined` when the basename
29
+ * has no recognized color suffix (e.g. an unsuffixed `~/kinstripe` checkout
30
+ * or a dev machine clone). Used by `resolveDeployConfig()` as the fallback
31
+ * for an INI with no `dir_suffix` line — which is what lets the INI be
32
+ * committed to git (identical in both slots).
33
+ */
34
+ export function inferColorFromDir(dir) {
35
+ const basename = path.basename(path.resolve(dir));
36
+ for (const color of Object.keys(SUFFIX_SWAP)) {
37
+ if (basename.endsWith(`-${color}`))
38
+ return color;
39
+ }
40
+ return undefined;
41
+ }
26
42
  /**
27
43
  * Resolve the absolute path to the peer (standby) directory for `currentDir`.
28
44
  *
@@ -0,0 +1,33 @@
1
+ import type { CommandRunner } from './types.js';
2
+ export declare const DEPLOY_CONFIG_RELATIVE_PATH: string;
3
+ /** Default number of trailing output lines shown for a failed command. */
4
+ export declare const FAILURE_OUTPUT_TAIL_LINES = 40;
5
+ /**
6
+ * Warning text when `cwd/package.json` exists but lists hazo_env in neither
7
+ * dependencies nor devDependencies; undefined otherwise (including when
8
+ * there is no package.json at all).
9
+ */
10
+ export declare function cliDependencyWarning(cwd: string): string | undefined;
11
+ /** True when config/hazo_env_config.ini is tracked by git in `cwd`. */
12
+ export declare function isDeployConfigGitTracked(runner: CommandRunner, cwd: string): boolean;
13
+ /**
14
+ * True when `cwd`'s config/hazo_env_config.ini pins `dir_suffix` explicitly.
15
+ * Such a file differs between blue and green, so it must not be tracked in
16
+ * git. Without the line, the suffix is inferred from the slot dir name and
17
+ * the file is identical in both slots — safe to commit.
18
+ */
19
+ export declare function deployConfigPinsDirSuffix(cwd: string): boolean;
20
+ export declare const TRACKED_DEPLOY_CONFIG_MESSAGE: string;
21
+ /**
22
+ * Add the per-slot config path to `<dir>/.git/info/exclude` (local to that
23
+ * clone, so it never dirties a tracked .gitignore). Returns true if an entry
24
+ * was added; false if `dir` isn't a git checkout or the entry already exists.
25
+ */
26
+ export declare function excludeDeployConfigFromGit(dir: string): boolean;
27
+ /**
28
+ * Describe a failed CommandRunner.exec: the error's first line plus the tail
29
+ * of the command's captured stdout+stderr (execSync errors carry both as
30
+ * properties). Falls back to the plain message when no output was captured.
31
+ */
32
+ export declare function commandFailureDetail(e: unknown, tailLines?: number): string;
33
+ //# sourceMappingURL=preflight.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preflight.d.ts","sourceRoot":"","sources":["../../src/deploy/preflight.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,eAAO,MAAM,2BAA2B,QAA6C,CAAC;AAEtF,0EAA0E;AAC1E,eAAO,MAAM,yBAAyB,KAAK,CAAC;AAE5C;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAcpE;AAED,uEAAuE;AACvE,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAGpF;AAKD;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAI9D;AAED,eAAO,MAAM,6BAA6B,QASyD,CAAC;AAEpG;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAW/D;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,EAAE,OAAO,EAAE,SAAS,SAA4B,GAAG,MAAM,CAc9F"}
@@ -0,0 +1,109 @@
1
+ // hazo_env/src/deploy/preflight.ts — Operator-mistake checks shared by deploy commands
2
+ //
3
+ // Each helper encodes a failure mode hit on a real deploy (GoTimer, 2026-11):
4
+ // - hazo_env not listed in the app's package.json: works once via a manual
5
+ // install, then `deploy build`'s own `npm ci` removes it and the next
6
+ // `npx hazo_env` fetches a standalone copy that can't resolve its peers.
7
+ // - config/hazo_env_config.ini tracked in git while pinning `dir_suffix`:
8
+ // the value differs per slot, so a tracked copy is either overwritten by
9
+ // `git pull` (wrong suffix) or blocks the pull against the slot's
10
+ // untracked copy. Since 0.18.0 an INI WITHOUT `dir_suffix` (inferred from
11
+ // the slot dir name) is identical in both slots and may be tracked.
12
+ // - a failed install/build reporting only Next's last line ("Failed to type
13
+ // check.") because the actual tsc errors went to stdout, which execSync
14
+ // keeps on the error object rather than in its message.
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ export const DEPLOY_CONFIG_RELATIVE_PATH = path.join('config', 'hazo_env_config.ini');
18
+ /** Default number of trailing output lines shown for a failed command. */
19
+ export const FAILURE_OUTPUT_TAIL_LINES = 40;
20
+ /**
21
+ * Warning text when `cwd/package.json` exists but lists hazo_env in neither
22
+ * dependencies nor devDependencies; undefined otherwise (including when
23
+ * there is no package.json at all).
24
+ */
25
+ export function cliDependencyWarning(cwd) {
26
+ const pkgPath = path.join(cwd, 'package.json');
27
+ if (!fs.existsSync(pkgPath))
28
+ return undefined;
29
+ let pkg;
30
+ try {
31
+ pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ if (pkg.dependencies?.hazo_env || pkg.devDependencies?.hazo_env)
37
+ return undefined;
38
+ return ('hazo_env is not in this app\'s package.json — the build\'s own `npm ci` will remove it, so the next ' +
39
+ '`npx hazo_env` will fetch a standalone copy that cannot load its peers. Add it: npm i -D hazo_env');
40
+ }
41
+ /** True when config/hazo_env_config.ini is tracked by git in `cwd`. */
42
+ export function isDeployConfigGitTracked(runner, cwd) {
43
+ const result = runner.spawn(`git ls-files --error-unmatch ${DEPLOY_CONFIG_RELATIVE_PATH}`, { cwd });
44
+ return result.code === 0;
45
+ }
46
+ /** Matches an active (uncommented) `dir_suffix = ...` line anywhere in the INI. */
47
+ const DIR_SUFFIX_LINE = /^\s*dir_suffix\s*=/m;
48
+ /**
49
+ * True when `cwd`'s config/hazo_env_config.ini pins `dir_suffix` explicitly.
50
+ * Such a file differs between blue and green, so it must not be tracked in
51
+ * git. Without the line, the suffix is inferred from the slot dir name and
52
+ * the file is identical in both slots — safe to commit.
53
+ */
54
+ export function deployConfigPinsDirSuffix(cwd) {
55
+ const iniPath = path.join(cwd, DEPLOY_CONFIG_RELATIVE_PATH);
56
+ if (!fs.existsSync(iniPath))
57
+ return false;
58
+ return DIR_SUFFIX_LINE.test(fs.readFileSync(iniPath, 'utf-8'));
59
+ }
60
+ export const TRACKED_DEPLOY_CONFIG_MESSAGE = `${DEPLOY_CONFIG_RELATIVE_PATH} is tracked in git but pins dir_suffix, which differs between blue and ` +
61
+ `green — a pull would overwrite this slot's copy or conflict with it. Either:\n` +
62
+ ` (a) delete the "dir_suffix = ..." line and commit — the suffix is then inferred from the slot ` +
63
+ `directory name ("<app>-blue" / "<app>-green"), so one committed file serves both slots; or\n` +
64
+ ` (b) untrack it and keep a per-slot copy:\n` +
65
+ ` git rm --cached ${DEPLOY_CONFIG_RELATIVE_PATH}\n` +
66
+ ` echo "${DEPLOY_CONFIG_RELATIVE_PATH}" >> .gitignore\n` +
67
+ ` git commit -m "untrack per-slot hazo_env config" && git push\n` +
68
+ ` (restore each slot's copy from the peer slot with dir_suffix swapped if a pull deleted it).`;
69
+ /**
70
+ * Add the per-slot config path to `<dir>/.git/info/exclude` (local to that
71
+ * clone, so it never dirties a tracked .gitignore). Returns true if an entry
72
+ * was added; false if `dir` isn't a git checkout or the entry already exists.
73
+ */
74
+ export function excludeDeployConfigFromGit(dir) {
75
+ const gitDir = path.join(dir, '.git');
76
+ if (!fs.existsSync(gitDir) || !fs.statSync(gitDir).isDirectory())
77
+ return false;
78
+ const entry = DEPLOY_CONFIG_RELATIVE_PATH.split(path.sep).join('/');
79
+ const excludePath = path.join(gitDir, 'info', 'exclude');
80
+ const existing = fs.existsSync(excludePath) ? fs.readFileSync(excludePath, 'utf-8') : '';
81
+ if (existing.split('\n').some((line) => line.trim() === entry || line.trim() === `/${entry}`))
82
+ return false;
83
+ fs.mkdirSync(path.dirname(excludePath), { recursive: true });
84
+ const prefix = existing.length > 0 && !existing.endsWith('\n') ? '\n' : '';
85
+ fs.appendFileSync(excludePath, `${prefix}# per-slot blue/green deploy config (hazo_env)\n${entry}\n`, 'utf-8');
86
+ return true;
87
+ }
88
+ /**
89
+ * Describe a failed CommandRunner.exec: the error's first line plus the tail
90
+ * of the command's captured stdout+stderr (execSync errors carry both as
91
+ * properties). Falls back to the plain message when no output was captured.
92
+ */
93
+ export function commandFailureDetail(e, tailLines = FAILURE_OUTPUT_TAIL_LINES) {
94
+ const message = e instanceof Error ? e.message : String(e);
95
+ if (!e || typeof e !== 'object')
96
+ return message;
97
+ const { stdout, stderr } = e;
98
+ const output = [stdout, stderr]
99
+ .map((s) => (typeof s === 'string' ? s : Buffer.isBuffer(s) ? s.toString('utf-8') : ''))
100
+ .filter((s) => s.trim().length > 0)
101
+ .join('\n')
102
+ .trimEnd();
103
+ if (!output)
104
+ return message;
105
+ const lines = output.split('\n');
106
+ const tail = lines.slice(-tailLines);
107
+ const header = lines.length > tailLines ? `last ${tailLines} of ${lines.length} output lines` : 'command output';
108
+ return `${message.split('\n')[0]}\n--- ${header} ---\n${tail.join('\n')}`;
109
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"verify.d.ts","sourceRoot":"","sources":["../../src/deploy/verify.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAe9D,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,YAAY,GAAG,kBAAkB,CAAC;AAC3E,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;AAE5D,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,eAAe,CAAC;IACtB,MAAM,EAAE,iBAAiB,CAAC;IAC1B,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,gBAAgB;IAC/B,0FAA0F;IAC1F,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;;;;;;;OAUG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,+DAA+D;IAC/D,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,gFAAgF;IAChF,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,iBAAiB,EAAE,CAAC;IAC5B,2FAA2F;IAC3F,SAAS,EAAE,OAAO,CAAC;CACpB;AAiID;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,gBAAqB,GAAG,eAAe,CA2DnH"}
1
+ {"version":3,"file":"verify.d.ts","sourceRoot":"","sources":["../../src/deploy/verify.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAe9D,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,YAAY,GAAG,kBAAkB,CAAC;AAC3E,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;AAE5D,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,eAAe,CAAC;IACtB,MAAM,EAAE,iBAAiB,CAAC;IAC1B,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,gBAAgB;IAC/B,0FAA0F;IAC1F,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;;;;;;;OAUG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,+DAA+D;IAC/D,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,gFAAgF;IAChF,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,iBAAiB,EAAE,CAAC;IAC5B,2FAA2F;IAC3F,SAAS,EAAE,OAAO,CAAC;CACpB;AAoID;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,gBAAqB,GAAG,eAAe,CAgEnH"}
@@ -145,6 +145,8 @@ function checkMigrationParity(cwd, liveDir) {
145
145
  .join('; ');
146
146
  return { name: 'migration-parity', status: 'fail', detail };
147
147
  }
148
+ /** curl's exit code for "connection refused", as reported by checkHealth. */
149
+ const CURL_CONNECTION_REFUSED = 'curl_exit_7';
148
150
  /**
149
151
  * Run all three verify checks against `cwd` (the standby directory, which
150
152
  * should already be running on `config.staging_port`). Every check runs
@@ -172,7 +174,11 @@ export function runVerify(config, runner, opts = {}) {
172
174
  checks.push({
173
175
  name: 'health',
174
176
  status: 'fail',
175
- detail: `${healthUrl} returned "${result.lastCode}" (expected 200) after ${attempts} attempt(s).`,
177
+ detail: `${healthUrl} returned "${result.lastCode}" (expected 200) after ${attempts} attempt(s).` +
178
+ (result.lastCode === CURL_CONNECTION_REFUSED
179
+ ? ` Nothing is listening on staging port ${config.staging_port} — run "hazo-env deploy build" first ` +
180
+ `(it starts the standby app as "${config.app_name}-staging"), or check "pm2 ls".`
181
+ : ''),
176
182
  });
177
183
  }
178
184
  }
@@ -0,0 +1,8 @@
1
+ /** Peer dependency names declared in this package's own package.json. */
2
+ export declare function readPeerNames(): string[];
3
+ /**
4
+ * If `err` is an ERR_MODULE_NOT_FOUND for one of `peerNames`, return a
5
+ * user-facing explanation and fix; otherwise undefined (caller rethrows).
6
+ */
7
+ export declare function missingPeerMessage(err: unknown, peerNames?: string[]): string | undefined;
8
+ //# sourceMappingURL=peer-hint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"peer-hint.d.ts","sourceRoot":"","sources":["../src/peer-hint.ts"],"names":[],"mappings":"AAYA,yEAAyE;AACzE,wBAAgB,aAAa,IAAI,MAAM,EAAE,CAQxC;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,EAAE,SAAS,GAAE,MAAM,EAAoB,GAAG,MAAM,GAAG,SAAS,CAmB1G"}
@@ -0,0 +1,49 @@
1
+ // hazo_env/src/peer-hint.ts — Friendly message for a missing peer dependency
2
+ //
3
+ // hazo_env's peers (hazo_core, hazo_config, ...) are only resolvable when the
4
+ // CLI runs from inside an app that installs them. `npx hazo_env ...` outside
5
+ // such an app (or in an app where hazo_env isn't a dependency, so npx fetches
6
+ // a lone copy into ~/.npm/_npx) dies at module load with a raw
7
+ // ERR_MODULE_NOT_FOUND stack. This turns that into an actionable message.
8
+ // Deliberately import-free (beyond node builtins) so it can run before any
9
+ // peer has been loaded.
10
+ import fs from 'node:fs';
11
+ /** Peer dependency names declared in this package's own package.json. */
12
+ export function readPeerNames() {
13
+ try {
14
+ const pkgUrl = new URL('../package.json', import.meta.url);
15
+ const pkg = JSON.parse(fs.readFileSync(pkgUrl, 'utf-8'));
16
+ return Object.keys(pkg.peerDependencies ?? {});
17
+ }
18
+ catch {
19
+ return [];
20
+ }
21
+ }
22
+ /**
23
+ * If `err` is an ERR_MODULE_NOT_FOUND for one of `peerNames`, return a
24
+ * user-facing explanation and fix; otherwise undefined (caller rethrows).
25
+ */
26
+ export function missingPeerMessage(err, peerNames = readPeerNames()) {
27
+ if (!err || typeof err !== 'object')
28
+ return undefined;
29
+ const e = err;
30
+ if (e.code !== 'ERR_MODULE_NOT_FOUND' || typeof e.message !== 'string')
31
+ return undefined;
32
+ const match = e.message.match(/Cannot find package '([^']+)'/);
33
+ if (!match)
34
+ return undefined;
35
+ const pkg = match[1];
36
+ if (!peerNames.includes(pkg))
37
+ return undefined;
38
+ return [
39
+ `hazo-env: cannot load its peer dependency "${pkg}".`,
40
+ '',
41
+ 'hazo_env must run from inside your app, where its peers are installed. Running it via',
42
+ 'npx outside the app (or in an app that does not list hazo_env as a dependency) fetches a',
43
+ 'standalone copy that cannot see them.',
44
+ '',
45
+ 'Fix: cd into the app directory and install it as a devDependency, then re-run:',
46
+ ' npm i -D hazo_env',
47
+ ' npx hazo_env <command>',
48
+ ].join('\n');
49
+ }
@@ -0,0 +1,2 @@
1
+ export declare function missingConfigMessage(filePath: string, cwd?: string): string;
2
+ //# sourceMappingURL=config-hint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-hint.d.ts","sourceRoot":"","sources":["../../src/resolve/config-hint.ts"],"names":[],"mappings":"AAUA,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,GAAE,MAAsB,GAAG,MAAM,CAe1F"}
@@ -0,0 +1,23 @@
1
+ // hazo_env/src/resolve/config-hint.ts — Error text for a missing hazo_env_config.ini
2
+ //
3
+ // The INI is per-slot in a blue/green deploy (dir_suffix differs) and must
4
+ // stay untracked, so a slot can legitimately lose it (e.g. a pull that
5
+ // removes a previously-tracked copy). When the cwd looks like a slot dir,
6
+ // point at the peer slot's copy with the exact command to restore it.
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ export function missingConfigMessage(filePath, cwd = process.cwd()) {
10
+ const base = `Config file not found: ${filePath}. Create config/hazo_env_config.ini.`;
11
+ const match = path.basename(cwd).match(/^(.*)-(blue|green)$/);
12
+ if (!match)
13
+ return base;
14
+ const [, stem, suffix] = match;
15
+ const peerSuffix = suffix === 'blue' ? 'green' : 'blue';
16
+ const peerConfig = path.join(path.dirname(cwd), `${stem}-${peerSuffix}`, 'config', 'hazo_env_config.ini');
17
+ if (!fs.existsSync(peerConfig)) {
18
+ return `${base} In a blue/green slot, copy the peer slot's file and set dir_suffix = ${suffix} (keep it out of git).`;
19
+ }
20
+ return (`${base} This looks like the "${suffix}" slot — restore it from the peer slot with dir_suffix swapped ` +
21
+ `(the file is per-slot; keep it out of git):\n` +
22
+ ` sed 's/^\\(dir_suffix *= *\\)${peerSuffix}/\\1${suffix}/' ${JSON.stringify(peerConfig)} > config/hazo_env_config.ini`);
23
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../../src/resolve/connect.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAmB5E;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,GAAE,qBAA0B,GAAG,WAAW,CA+GlF"}
1
+ {"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../../src/resolve/connect.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAoB5E;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,GAAE,qBAA0B,GAAG,WAAW,CA+GlF"}
@@ -5,6 +5,7 @@ import { HazoConfigError } from 'hazo_core';
5
5
  import { getEnv } from '../index.client.js';
6
6
  import { substitutePlaceholders } from './secrets.js';
7
7
  import { resolveFilesConfig } from './files.js';
8
+ import { missingConfigMessage } from './config-hint.js';
8
9
  function findConfigFile(pkg) {
9
10
  return path.resolve(process.cwd(), 'config', `${pkg}_config.ini`);
10
11
  }
@@ -17,7 +18,7 @@ function loadConfig() {
17
18
  throw new HazoConfigError({
18
19
  code: 'HAZO_ENV_CONFIG_FILE_MISSING',
19
20
  pkg: 'hazo_env',
20
- message: `Config file not found: ${filePath}. Create config/hazo_env_config.ini.`,
21
+ message: missingConfigMessage(filePath),
21
22
  });
22
23
  }
23
24
  }
@@ -1 +1 @@
1
- {"version":3,"file":"deploy.d.ts","sourceRoot":"","sources":["../../src/resolve/deploy.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAyRvD;;;;GAIG;AACH,wBAAgB,mBAAmB,IAAI,YAAY,CA+DlD"}
1
+ {"version":3,"file":"deploy.d.ts","sourceRoot":"","sources":["../../src/resolve/deploy.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AA0RvD;;;;GAIG;AACH,wBAAgB,mBAAmB,IAAI,YAAY,CAqElD"}
@@ -8,8 +8,9 @@ import os from 'node:os';
8
8
  import path from 'node:path';
9
9
  import { HazoConfig } from 'hazo_config/server';
10
10
  import { HazoConfigError } from 'hazo_core';
11
- import { resolvePeerDir } from '../deploy/peer.js';
11
+ import { inferColorFromDir, resolvePeerDir } from '../deploy/peer.js';
12
12
  import { resolveConnectConfig } from './connect.js';
13
+ import { missingConfigMessage } from './config-hint.js';
13
14
  const DEFAULTS = {
14
15
  prod_port: 3000,
15
16
  staging_port: 3001,
@@ -35,7 +36,7 @@ function loadConfig() {
35
36
  throw new HazoConfigError({
36
37
  code: 'HAZO_ENV_CONFIG_FILE_MISSING',
37
38
  pkg: 'hazo_env',
38
- message: `Config file not found: ${filePath}. Create config/hazo_env_config.ini.`,
39
+ message: missingConfigMessage(filePath),
39
40
  });
40
41
  }
41
42
  }
@@ -292,12 +293,17 @@ export function resolveDeployConfig() {
292
293
  message: '[deploy] section is missing required field "app_name".',
293
294
  });
294
295
  }
295
- const dir_suffix = section['dir_suffix'];
296
+ // An explicit `dir_suffix` wins; otherwise infer it from the slot dir's
297
+ // basename ("<app>-blue" / "<app>-green"). Omitting it is what lets the INI
298
+ // be committed to git — both slots then hold a byte-identical file.
299
+ const dir_suffix = (section['dir_suffix']?.trim() || inferColorFromDir(process.cwd()));
296
300
  if (!dir_suffix) {
297
301
  throw new HazoConfigError({
298
302
  code: 'HAZO_ENV_CONFIG_MISSING_DEPLOY_DIR_SUFFIX',
299
303
  pkg: 'hazo_env',
300
- message: '[deploy] section is missing required field "dir_suffix".',
304
+ message: '[deploy] section is missing "dir_suffix" and it could not be inferred: the app directory name ' +
305
+ `("${path.basename(process.cwd())}") does not end in "-blue" or "-green". Rename the slot directory ` +
306
+ '(e.g. "myapp-blue") or set dir_suffix explicitly.',
301
307
  });
302
308
  }
303
309
  const db_strategy_raw = section['db_strategy'] ?? DEFAULTS.db_strategy;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hazo_env",
3
- "version": "0.16.0",
3
+ "version": "0.18.0",
4
4
  "description": "Canonical environment resolver — typed env names, per-env DB/file/secret config, doctor and CLI for hazo apps",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -19,7 +19,7 @@
19
19
  "./package.json": "./package.json"
20
20
  },
21
21
  "bin": {
22
- "hazo-env": "./dist/cli.js"
22
+ "hazo-env": "./dist/bin.js"
23
23
  },
24
24
  "files": [
25
25
  "dist",