@bom0792/herdgate 0.9.37 → 0.9.38

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.
@@ -18,6 +18,7 @@
18
18
  <header id="bar">
19
19
  <strong>herdgate</strong>
20
20
  <span id="status" class="pill" role="status" aria-live="polite">offline</span>
21
+ <button id="cmdk-open" type="button" title="Jump — ⌘K / Ctrl-K">⌘K / Ctrl-K</button>
21
22
  <button id="menu" type="button" aria-label="Settings">⋯</button>
22
23
  </header>
23
24
 
@@ -1,16 +1,48 @@
1
- // Fetch the npm release using npm bundled with the same Node, without running install hooks.
2
- import { spawnSync } from 'node:child_process';
3
- import { existsSync, mkdtempSync, rmSync } from 'node:fs';
4
- import { tmpdir } from 'node:os';
5
- import { dirname, join } from 'node:path';
1
+ // npm staging helper + safe self-updater for the Herdgate per-user CLI.
2
+ //
3
+ // withLatest(run) keeps its original contract for the existing callers
4
+ // (windows/cli.mjs "update" and bin/herdgate.mjs "update"): stage the latest
5
+ // @bom0792/herdgate release with the npm bundled beside the same Node, without
6
+ // running install hooks, and hand the staged package directory to run().
7
+ //
8
+ // Run directly (node npm-update.mjs) this module is the safe updater, applying
9
+ // the lessons from herdr-updater:
10
+ // - before ANY change the installed/latest relation is computed with
11
+ // ./update-policy.mjs; "unknown" (unparsable versions) is an error state
12
+ // that exits 1 — it is never treated as "current" and never updated past;
13
+ // - the default policy is "notify": print installed/latest/relation/plan,
14
+ // run no install and write no file except the append-only history
15
+ // "checked" line;
16
+ // - HERDGATE_UPDATE_POLICY=auto may only apply when the installed version is
17
+ // strictly "behind" (npm source), or when the installed commit is an
18
+ // ancestor of the upstream ref found via git merge-base --is-ancestor (git
19
+ // source); same/ahead/diverged/pinned/linked states are held with a reason;
20
+ // - every real apply appends an "updated" history line (from -> to) and keeps
21
+ // the previous install behaviour (staged npm install with --ignore-scripts,
22
+ // then the staged Windows CLI performs the switch).
23
+ import { spawnSync } from "node:child_process";
24
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
25
+ import { tmpdir } from "node:os";
26
+ import { dirname, join, resolve } from "node:path";
27
+ import { fileURLToPath, pathToFileURL } from "node:url";
28
+ import { appendHistory, policyFromEnv, relation } from "./update-policy.mjs";
6
29
 
7
- export function withLatest(run) {
30
+ const PACKAGE = "@bom0792/herdgate";
31
+ const here = dirname(fileURLToPath(import.meta.url));
32
+
33
+ /** npm-cli.js shipped beside the current Node, if any (same candidates as before). */
34
+ function bundledNpmCli() {
8
35
  const nodeDir = dirname(process.execPath);
9
- const npm = [
10
- join(nodeDir, 'node_modules', 'npm', 'bin', 'npm-cli.js'),
11
- ...(process.platform === 'win32' ? [] : [join(nodeDir, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js')]),
12
- ...(nodeDir === '/usr/bin' ? ['/usr/share/nodejs/npm/bin/npm-cli.js'] : []),
13
- ].find(existsSync);
36
+ return [
37
+ join(nodeDir, "node_modules", "npm", "bin", "npm-cli.js"),
38
+ ...(process.platform === "win32" ? [] : [join(nodeDir, "..", "lib", "node_modules", "npm", "bin", "npm-cli.js")]),
39
+ ...(nodeDir === "/usr/bin" ? ["/usr/share/nodejs/npm/bin/npm-cli.js"] : []),
40
+ ].find(existsSync) ?? null;
41
+ }
42
+
43
+ // Fetch the npm release using npm bundled with the same Node, without running install hooks.
44
+ export function withLatest(run) {
45
+ const npm = bundledNpmCli();
14
46
  if (!npm) throw new Error('npm was not found beside Node; use a Node 22+ distribution with npm');
15
47
  const work = mkdtempSync(join(tmpdir(), 'herdgate-update-'));
16
48
  try {
@@ -24,3 +56,221 @@ export function withLatest(run) {
24
56
  rmSync(work, { recursive: true, force: true, maxRetries: 3 });
25
57
  }
26
58
  }
59
+
60
+ // ---- safe updater (direct run) ----
61
+
62
+ /** Run npm, preferring an npm from PATH (where tests stub it); the bundled npm-cli.js is the fallback. */
63
+ function npmRun(args, { timeout = 120_000 } = {}) {
64
+ if (process.platform === "win32") {
65
+ const command = ["npm", ...args]
66
+ .map((arg) => (/[ \t"^&|<>()!]/.test(arg) ? `"${arg.replaceAll('"', '""')}"` : arg))
67
+ .join(" ");
68
+ return spawnSync(command, { encoding: "utf8", shell: true, windowsHide: true, timeout });
69
+ }
70
+ const fromPath = spawnSync("npm", args, { encoding: "utf8", shell: false, windowsHide: true, timeout });
71
+ if (!fromPath.error || fromPath.error.code !== "ENOENT") return fromPath;
72
+ const bundled = bundledNpmCli();
73
+ return bundled
74
+ ? spawnSync(process.execPath, [bundled, ...args], { encoding: "utf8", shell: false, windowsHide: true, timeout })
75
+ : fromPath;
76
+ }
77
+
78
+ /** Latest published version, or null when npm cannot answer. */
79
+ function npmLatestVersion(pkg) {
80
+ const result = npmRun(["view", pkg, "version"], { timeout: 30_000 });
81
+ if (result.error || result.status !== 0) return null;
82
+ const version = (result.stdout ?? "").trim().split("\n").pop()?.trim();
83
+ return version || null;
84
+ }
85
+
86
+ /** Version of the package this module was shipped in, or null (never guessed). */
87
+ function installedPackageVersion() {
88
+ try {
89
+ const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8"));
90
+ return typeof pkg.version === "string" ? pkg.version : null;
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+
96
+ /** Stage the latest release exactly like withLatest, but through the resolved npm. */
97
+ function stageLatest() {
98
+ const work = mkdtempSync(join(tmpdir(), "herdgate-update-"));
99
+ try {
100
+ const result = npmRun(["install", "--prefix", work, "--global=false", "--no-save", "--package-lock=false",
101
+ "--ignore-scripts", "--no-audit", "--no-fund", "--prefer-online", `${PACKAGE}@latest`]);
102
+ if (result.error) throw result.error;
103
+ if (result.status !== 0) throw new Error(`could not download ${PACKAGE} from npm; nothing was changed`);
104
+ return work;
105
+ } catch (error) {
106
+ rmSync(work, { recursive: true, force: true, maxRetries: 3 });
107
+ throw error;
108
+ }
109
+ }
110
+
111
+ // ---- git source ----
112
+
113
+ function git(checkout, args) {
114
+ return spawnSync("git", ["-C", checkout, ...args], { encoding: "utf8", shell: false, windowsHide: true, timeout: 30_000 });
115
+ }
116
+
117
+ function gitText(checkout, args) {
118
+ const result = git(checkout, args);
119
+ return result.status === 0 ? result.stdout.trim() : null;
120
+ }
121
+
122
+ /** Classify a checkout: behind/ahead/same by ancestry, pinned (detached HEAD) or linked (no upstream). */
123
+ function gitRelation(checkout) {
124
+ const head = gitText(checkout, ["rev-parse", "HEAD"]);
125
+ if (!head) return { relation: "unknown", head: null, upstream: null, upstreamSha: null };
126
+ const branch = gitText(checkout, ["rev-parse", "--abbrev-ref", "HEAD"]);
127
+ const detached = !branch || branch === "HEAD";
128
+ const upstream = detached ? null : gitText(checkout, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
129
+ const upstreamSha = upstream ? gitText(checkout, ["rev-parse", upstream]) : null;
130
+ if (!upstream || !upstreamSha) {
131
+ return { relation: detached ? "pinned" : "linked", head, upstream, upstreamSha: null };
132
+ }
133
+ if (head === upstreamSha) return { relation: "same", head, upstream, upstreamSha };
134
+ // Only an installed ref that is an ancestor of upstream may be fast-forwarded.
135
+ if (git(checkout, ["merge-base", "--is-ancestor", head, upstreamSha]).status === 0) {
136
+ return { relation: "behind", head, upstream, upstreamSha };
137
+ }
138
+ if (git(checkout, ["merge-base", "--is-ancestor", upstreamSha, head]).status === 0) {
139
+ return { relation: "ahead", head, upstream, upstreamSha };
140
+ }
141
+ return { relation: "diverged", head, upstream, upstreamSha };
142
+ }
143
+
144
+ /** Nearest enclosing git work tree, or null (an npm-installed package has none). */
145
+ function findCheckout(start) {
146
+ for (let dir = resolve(start);;) {
147
+ if (existsSync(join(dir, ".git"))) return dir;
148
+ const parent = dirname(dir);
149
+ if (parent === dir) return null;
150
+ dir = parent;
151
+ }
152
+ }
153
+
154
+ // ---- reporting and policies ----
155
+
156
+ function fail(message) {
157
+ console.error(`herdgate update: ${message}`);
158
+ process.exitCode = 1;
159
+ }
160
+
161
+ /** Append one history line; on failure report and stop (return null). */
162
+ function record(stateDir, entry) {
163
+ try {
164
+ return appendHistory(stateDir, entry);
165
+ } catch (error) {
166
+ fail(`could not append the update history: ${error instanceof Error ? error.message : String(error)}`);
167
+ return null;
168
+ }
169
+ }
170
+
171
+ function updateFromNpm(policy, stateDir, env) {
172
+ const pkg = env.HERDGATE_UPDATE_PACKAGE || PACKAGE;
173
+ const installed = env.HERDGATE_UPDATE_INSTALLED || installedPackageVersion();
174
+ const latest = env.HERDGATE_UPDATE_LATEST || npmLatestVersion(pkg);
175
+ const rel = relation(installed, latest);
176
+ console.log(`source: npm package ${pkg}`);
177
+ console.log(`policy: ${policy}`);
178
+ console.log(`installed: ${installed ?? "<unknown>"}`);
179
+ console.log(`latest: ${latest ?? "<unknown>"}`);
180
+ console.log(`relation: ${rel}`);
181
+ if (rel === "unknown") {
182
+ return fail(`cannot compare installed "${installed ?? ""}" with latest "${latest ?? ""}": unparsable version — refusing to guess or update`);
183
+ }
184
+ if (policy === "notify") {
185
+ console.log(rel === "behind"
186
+ ? `plan: stage ${pkg}@${latest} with npm --ignore-scripts and switch the per-user CLI; set HERDGATE_UPDATE_POLICY=auto to apply`
187
+ : `plan: nothing to apply (relation ${rel})`);
188
+ if (!record(stateDir, { from: installed, to: latest, relation: rel, action: "checked" })) return;
189
+ console.log(`history: ${join(stateDir, "update-history.jsonl")} (append-only)`);
190
+ return;
191
+ }
192
+ if (rel !== "behind") {
193
+ console.log("held — applying would be a downgrade/no-op");
194
+ record(stateDir, { from: installed, to: latest, relation: rel, action: "held" });
195
+ return;
196
+ }
197
+ let work;
198
+ try {
199
+ work = stageLatest();
200
+ } catch (error) {
201
+ return fail(error instanceof Error ? error.message : String(error));
202
+ }
203
+ try {
204
+ if (!record(stateDir, { from: installed, to: latest, relation: rel, action: "updated" })) return;
205
+ console.log(`updated: ${installed} -> ${latest}`);
206
+ // Keep the previous apply behaviour: the staged Windows CLI switches the publisher.
207
+ const stagedCli = join(work, "node_modules", "@bom0792", "herdgate", "bin", "herdgate.mjs");
208
+ if (process.platform === "win32" && existsSync(stagedCli)) {
209
+ const switched = spawnSync(process.execPath, [stagedCli, "tui", "update"], { stdio: "inherit", shell: false, windowsHide: true, timeout: 120_000 });
210
+ if (switched.error) throw switched.error;
211
+ if (switched.status) process.exitCode = switched.status;
212
+ }
213
+ } catch (error) {
214
+ fail(error instanceof Error ? error.message : String(error));
215
+ } finally {
216
+ rmSync(work, { recursive: true, force: true, maxRetries: 3 });
217
+ }
218
+ }
219
+
220
+ function updateFromGit(policy, stateDir, checkout) {
221
+ const rel = gitRelation(checkout);
222
+ console.log(`source: git checkout ${checkout}`);
223
+ console.log(`policy: ${policy}`);
224
+ console.log(`installed: ${rel.head ?? "<unknown>"}${rel.head ? " (HEAD)" : ""}`);
225
+ console.log(`upstream: ${rel.upstream ? `${rel.upstream}${rel.upstreamSha ? ` (${rel.upstreamSha})` : ""}` : "<none>"}`);
226
+ console.log(`relation: ${rel.relation}`);
227
+ if (rel.relation === "unknown") {
228
+ return fail(`cannot determine the state of the git checkout at ${checkout} — refusing to guess or update`);
229
+ }
230
+ if (policy === "notify") {
231
+ console.log(rel.relation === "behind"
232
+ ? `plan: fast-forward HEAD to ${rel.upstream} (${rel.upstreamSha}); set HERDGATE_UPDATE_POLICY=auto to apply`
233
+ : `plan: nothing to apply (relation ${rel.relation})`);
234
+ if (!record(stateDir, { from: rel.head, to: rel.upstreamSha, relation: rel.relation, action: "checked" })) return;
235
+ console.log(`history: ${join(stateDir, "update-history.jsonl")} (append-only)`);
236
+ return;
237
+ }
238
+ if (rel.relation !== "behind") {
239
+ const reason = rel.relation === "ahead" ? "applying would be a downgrade/no-op"
240
+ : rel.relation === "same" ? "applying would be a no-op"
241
+ : rel.relation === "diverged" ? "the checkout diverged from upstream; only a fast-forward is safe"
242
+ : rel.relation === "pinned" ? "the checkout is pinned to a detached ref"
243
+ : "the branch has no upstream to fast-forward to";
244
+ console.log(`held — ${reason}`);
245
+ record(stateDir, { from: rel.head, to: rel.upstreamSha, relation: rel.relation, action: "held" });
246
+ return;
247
+ }
248
+ const merged = git(checkout, ["merge", "--ff-only", rel.upstreamSha]);
249
+ if (merged.error || merged.status !== 0) {
250
+ return fail(`fast-forwarding to ${rel.upstream} failed; the checkout was not changed${merged.stderr ? `: ${merged.stderr.trim()}` : ""}`);
251
+ }
252
+ const applied = gitText(checkout, ["rev-parse", "HEAD"]) ?? rel.upstreamSha;
253
+ if (!record(stateDir, { from: rel.head, to: applied, relation: "behind", action: "updated" })) return;
254
+ console.log(`updated: ${rel.head} -> ${applied}`);
255
+ }
256
+
257
+ function main() {
258
+ const env = process.env;
259
+ const policy = policyFromEnv(env);
260
+ const stateDir = env.HERDGATE_UPDATE_STATE_DIR || (env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "Herdgate", "cli") : null);
261
+ if (!stateDir) {
262
+ return fail("nowhere to record the update history; set HERDGATE_UPDATE_STATE_DIR (or LOCALAPPDATA)");
263
+ }
264
+ const checkout = env.HERDGATE_UPDATE_CHECKOUT || findCheckout(here);
265
+ return checkout ? updateFromGit(policy, stateDir, checkout) : updateFromNpm(policy, stateDir, env);
266
+ }
267
+
268
+ // Only act when executed directly; importing callers keep using withLatest unchanged.
269
+ const executedDirectly = (() => {
270
+ try {
271
+ return Boolean(process.argv[1]) && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
272
+ } catch {
273
+ return false;
274
+ }
275
+ })();
276
+ if (executedDirectly) main();
@@ -0,0 +1,98 @@
1
+ // Safe update policy primitives shared by the Herdgate updaters.
2
+ //
3
+ // Lessons baked in from herdr-updater:
4
+ // - never guess a version: anything that does not parse as strict semver is
5
+ // null, and a failed comparison is the ERROR state "unknown" — it is never
6
+ // silently treated as "current" or "up to date";
7
+ // - order only by semver precedence (0.10.0 > 0.9.0 > 0.9.0-rc.1), never by
8
+ // string or numeric inequality;
9
+ // - update decisions are recorded in an append-only JSONL history.
10
+ import { appendFileSync, mkdirSync } from "node:fs";
11
+ import { hostname } from "node:os";
12
+ import { join } from "node:path";
13
+
14
+ export const HISTORY_FILE = "update-history.jsonl";
15
+
16
+ // Official semver grammar; build metadata is allowed but ignored for precedence.
17
+ const VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;
18
+ const NUMERIC = /^\d+$/;
19
+
20
+ /** Parse a strict semver string into precedence parts; anything else is null (never a guess). */
21
+ export function parseVersion(value) {
22
+ if (typeof value !== "string") return null;
23
+ const match = VERSION.exec(value.trim());
24
+ if (!match) return null;
25
+ return {
26
+ major: Number(match[1]),
27
+ minor: Number(match[2]),
28
+ patch: Number(match[3]),
29
+ prerelease: match[4] ? match[4].split(".") : [],
30
+ };
31
+ }
32
+
33
+ /** Compare two versions by semver precedence: -1 | 0 | 1, or null when either side does not parse. */
34
+ export function compareVersions(a, b) {
35
+ const left = parseVersion(a);
36
+ const right = parseVersion(b);
37
+ if (!left || !right) return null;
38
+ for (const part of ["major", "minor", "patch"]) {
39
+ if (left[part] !== right[part]) return left[part] < right[part] ? -1 : 1;
40
+ }
41
+ const ra = left.prerelease;
42
+ const rb = right.prerelease;
43
+ if (!ra.length || !rb.length) {
44
+ if (ra.length === rb.length) return 0;
45
+ // A prerelease sorts below the plain release: 0.9.0 > 0.9.0-rc.1.
46
+ return ra.length ? -1 : 1;
47
+ }
48
+ const shared = Math.min(ra.length, rb.length);
49
+ for (let i = 0; i < shared; i++) {
50
+ const x = ra[i];
51
+ const y = rb[i];
52
+ const xn = NUMERIC.test(x);
53
+ const yn = NUMERIC.test(y);
54
+ if (xn && yn) {
55
+ const order = Number(x) - Number(y);
56
+ if (order) return order < 0 ? -1 : 1;
57
+ } else if (xn !== yn) {
58
+ // Numeric identifiers sort below alphanumeric ones.
59
+ return xn ? -1 : 1;
60
+ } else if (x !== y) {
61
+ return x < y ? -1 : 1;
62
+ }
63
+ }
64
+ if (ra.length === rb.length) return 0;
65
+ // A larger set of pre-release fields has higher precedence: alpha < alpha.1.
66
+ return ra.length < rb.length ? -1 : 1;
67
+ }
68
+
69
+ /** installed vs latest: same | behind | ahead, or unknown (parse failed — an error state, not "current"). */
70
+ export function relation(installed, latest) {
71
+ const order = compareVersions(installed, latest);
72
+ if (order === null) return "unknown";
73
+ return order < 0 ? "behind" : order > 0 ? "ahead" : "same";
74
+ }
75
+
76
+ /** HERDGATE_UPDATE_POLICY: only the exact value "auto" opts in; anything else fails closed to notify. */
77
+ export function policyFromEnv(env) {
78
+ return env && env.HERDGATE_UPDATE_POLICY === "auto" ? "auto" : "notify";
79
+ }
80
+
81
+ /** Append one decision record as JSONL; the file is only ever appended to, never rewritten. */
82
+ export function appendHistory(stateDir, record) {
83
+ if (!stateDir || typeof stateDir !== "string") throw new TypeError("appendHistory requires a state directory");
84
+ if (!record || typeof record !== "object") throw new TypeError("appendHistory requires a record");
85
+ mkdirSync(stateDir, { recursive: true });
86
+ const entry = {
87
+ at: typeof record.at === "string" && record.at ? record.at : new Date().toISOString(),
88
+ from: record.from ?? null,
89
+ to: record.to ?? null,
90
+ relation: record.relation ?? null,
91
+ action: record.action ?? null,
92
+ };
93
+ const host = record.host ?? hostname();
94
+ if (host) entry.host = host;
95
+ // Flag "a" positions at the end and never truncates an existing history.
96
+ appendFileSync(join(stateDir, HISTORY_FILE), JSON.stringify(entry) + "\n", { flag: "a" });
97
+ return entry;
98
+ }