herdr-remote 0.2.18 → 0.2.20

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 (95) hide show
  1. package/bin/herdr-remote.js +3 -225
  2. package/dist/agent-status.js +130 -0
  3. package/dist/binary-plist.js +157 -0
  4. package/dist/cli.js +255 -0
  5. package/dist/config.js +270 -0
  6. package/dist/connector/agent-watch.js +110 -0
  7. package/dist/connector/font-server.js +165 -0
  8. package/dist/connector/host-connector.js +430 -0
  9. package/dist/connector/lock.js +66 -0
  10. package/dist/connector/main.js +18 -0
  11. package/dist/connector/sessions.js +366 -0
  12. package/dist/connector/update-report.js +67 -0
  13. package/dist/connector/wire.js +42 -0
  14. package/{src → dist}/exit-codes.js +1 -4
  15. package/dist/font-subset.js +110 -0
  16. package/dist/herdr-api.js +246 -0
  17. package/dist/herdr-command.js +223 -0
  18. package/dist/herdr-plugin.js +116 -0
  19. package/dist/herdr-server.js +189 -0
  20. package/dist/i18n/en.js +223 -0
  21. package/dist/i18n/index.js +48 -0
  22. package/dist/i18n/zh.js +222 -0
  23. package/dist/keepalive/detached.js +78 -0
  24. package/dist/keepalive/environment.js +44 -0
  25. package/dist/keepalive/index.js +110 -0
  26. package/dist/keepalive/launchd.js +117 -0
  27. package/dist/keepalive/systemd.js +108 -0
  28. package/dist/keepalive/types.js +1 -0
  29. package/dist/lib/process.js +12 -0
  30. package/dist/lifecycle.js +59 -0
  31. package/dist/net-interfaces.js +73 -0
  32. package/dist/pasted-files.js +115 -0
  33. package/dist/paths.js +62 -0
  34. package/dist/pty-session.js +96 -0
  35. package/dist/relay-client.js +106 -0
  36. package/dist/relay-urls.js +99 -0
  37. package/dist/runtime.js +106 -0
  38. package/dist/service.js +260 -0
  39. package/dist/settings-model.js +298 -0
  40. package/dist/socket-discovery.js +48 -0
  41. package/dist/supervisor.js +319 -0
  42. package/dist/terminal-font/deps.js +73 -0
  43. package/dist/terminal-font/files.js +354 -0
  44. package/dist/terminal-font/formats.js +335 -0
  45. package/dist/terminal-font/index.js +187 -0
  46. package/dist/terminal-font/readers.js +316 -0
  47. package/dist/terminal-font/terminals.js +128 -0
  48. package/dist/terminal-palette.js +339 -0
  49. package/dist/tui/App.js +195 -0
  50. package/dist/tui/api.js +79 -0
  51. package/dist/tui/components/TextField.js +50 -0
  52. package/dist/tui/components/common.js +80 -0
  53. package/dist/tui/index.js +36 -0
  54. package/dist/tui/mouse/index.js +164 -0
  55. package/dist/tui/mouse/protocol.js +96 -0
  56. package/dist/tui/mouse/source.js +74 -0
  57. package/dist/tui/screens/About.js +166 -0
  58. package/dist/tui/screens/Herdr.js +74 -0
  59. package/dist/tui/screens/Keepalive.js +84 -0
  60. package/dist/tui/screens/Overview.js +36 -0
  61. package/dist/tui/screens/Pair.js +74 -0
  62. package/dist/tui/screens/Relay.js +242 -0
  63. package/dist/tui/screens/Services.js +63 -0
  64. package/dist/tui/screens/Wizard.js +235 -0
  65. package/dist/tui/terminal.js +39 -0
  66. package/dist/tui/theme.js +33 -0
  67. package/dist/updater.js +382 -0
  68. package/herdr-plugin.toml +1 -1
  69. package/package.json +8 -8
  70. package/dist/tui.mjs +0 -5775
  71. package/src/agent-status.js +0 -139
  72. package/src/binary-plist.js +0 -146
  73. package/src/config.js +0 -454
  74. package/src/font-subset.js +0 -110
  75. package/src/herdr-api.js +0 -244
  76. package/src/herdr-command.js +0 -231
  77. package/src/herdr-plugin.js +0 -130
  78. package/src/herdr-server.js +0 -201
  79. package/src/host-connector.js +0 -1069
  80. package/src/i18n/en.js +0 -240
  81. package/src/i18n/index.js +0 -56
  82. package/src/i18n/zh.js +0 -239
  83. package/src/keepalive.js +0 -460
  84. package/src/lifecycle.js +0 -62
  85. package/src/net-interfaces.js +0 -76
  86. package/src/pasted-files.js +0 -176
  87. package/src/pty-session.js +0 -92
  88. package/src/service.js +0 -530
  89. package/src/settings-model.js +0 -323
  90. package/src/socket-discovery.js +0 -60
  91. package/src/state.js +0 -47
  92. package/src/supervisor.js +0 -250
  93. package/src/terminal-font.js +0 -1204
  94. package/src/terminal-palette.js +0 -325
  95. package/src/updater.js +0 -394
@@ -0,0 +1,246 @@
1
+ /**
2
+ * One question for Herdr's local socket API.
3
+ *
4
+ * Everything else in this package talks to Herdr by spawning a client into a
5
+ * PTY and shipping the bytes. That is the terminal. This is the side channel:
6
+ * the one place that asks Herdr *about* itself rather than drawing it, so a
7
+ * phone can answer "does anything need me?" without navigating a TUI through a
8
+ * 40-column viewport.
9
+ *
10
+ * The wire format is newline-delimited JSON over the Unix socket:
11
+ *
12
+ * request {"id":"…","method":"session.snapshot","params":{}}
13
+ * response {"id":"…","result":{…}} or {"id":"…","error":{"code","message"}}
14
+ *
15
+ * One request per connection, which is why this is a function and not a client.
16
+ * Herdr closes the socket once it has answered: against 0.9.1 a second request
17
+ * written to the same connection meets `EPIPE`. A long-lived client that
18
+ * reconnects on close therefore turns into a connect-answer-close loop about
19
+ * once a second, busy regardless of how rarely it actually asks anything. The
20
+ * `herdr` CLI connects per command for the same reason, and so does this.
21
+ *
22
+ * Subscriptions are the exception Herdr does keep open — `events.subscribe`
23
+ * holds the connection. Focus and agent-detection events let the caller refresh
24
+ * the focused pane immediately, with a slow poll retained as a fallback.
25
+ *
26
+ * Nothing here may affect a terminal session. Herdr's server is an ordinary
27
+ * process that can be restarted under a running herdr-remote, and when it is,
28
+ * the PTYs keep streaming while this quietly fails and is asked again later.
29
+ */
30
+ import net from 'node:net';
31
+ /** How long one question waits, connection included. */
32
+ const REQUEST_TIMEOUT_MS = 10_000;
33
+ /** An answer this long is not an answer. Guards a socket that never newlines. */
34
+ const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
35
+ /** A subscription that disappears should recover without keeping a dead socket busy. */
36
+ const SUBSCRIBE_RETRY_BASE_MS = 1_000;
37
+ const SUBSCRIBE_RETRY_MAX_MS = 10_000;
38
+ let requestCounter = 0;
39
+ /**
40
+ * Ask Herdr one thing.
41
+ *
42
+ * Resolves with the `result` object, rejects for a refused connection, a
43
+ * timeout, an unparseable answer, or an `error` response — in which case
44
+ * `error.code` is Herdr's own code.
45
+ */
46
+ function requestHerdr(socketPath, method, params = {}, options = {}) {
47
+ const { timeout = REQUEST_TIMEOUT_MS, connect = net.connect } = options;
48
+ requestCounter += 1;
49
+ const id = `herdr-remote:${requestCounter}`;
50
+ return new Promise((resolve, reject) => {
51
+ let socket;
52
+ let buffer = '';
53
+ let settled = false;
54
+ const finish = (error, result) => {
55
+ if (settled)
56
+ return;
57
+ settled = true;
58
+ clearTimeout(timer);
59
+ if (socket) {
60
+ socket.removeAllListeners();
61
+ socket.destroy();
62
+ }
63
+ if (error)
64
+ reject(error);
65
+ else
66
+ resolve(result);
67
+ };
68
+ const timer = setTimeout(() => finish(new Error(`Herdr API did not answer ${method} in time`)), timeout);
69
+ if (typeof timer.unref === 'function')
70
+ timer.unref();
71
+ try {
72
+ socket = connect(socketPath);
73
+ }
74
+ catch (error) {
75
+ finish(error);
76
+ return;
77
+ }
78
+ const connection = socket;
79
+ connection.setEncoding('utf8');
80
+ connection.on('connect', () => {
81
+ connection.write(`${JSON.stringify({ id, method, params })}\n`);
82
+ });
83
+ connection.on('data', (chunk) => {
84
+ buffer += chunk;
85
+ if (buffer.length > MAX_RESPONSE_BYTES) {
86
+ finish(new Error('Herdr API sent an oversized response'));
87
+ return;
88
+ }
89
+ const newline = buffer.indexOf('\n');
90
+ if (newline === -1)
91
+ return;
92
+ let message;
93
+ try {
94
+ message = JSON.parse(buffer.slice(0, newline));
95
+ }
96
+ catch {
97
+ finish(new Error('Herdr API sent a line that is not JSON'));
98
+ return;
99
+ }
100
+ if (message.error) {
101
+ const error = Object.assign(new Error(message.error.message || 'Herdr API request failed'), {
102
+ code: message.error.code || 'herdr_api_error',
103
+ });
104
+ finish(error);
105
+ return;
106
+ }
107
+ finish(null, message.result);
108
+ });
109
+ connection.on('error', (error) => finish(error));
110
+ // Herdr hanging up before it answered is the ordinary shape of "the server
111
+ // is not running", not something that needs its own diagnosis.
112
+ connection.on('close', () => finish(new Error(`Herdr API closed before answering ${method}`)));
113
+ });
114
+ }
115
+ /**
116
+ * Subscribe to Herdr's event stream and reconnect if its local server restarts.
117
+ *
118
+ * The initial response is an acknowledgement (`result.type` is
119
+ * `subscription_started`); later lines are envelopes with `event` and `data`.
120
+ * They share a socket, but are separate NDJSON messages. A subscription never
121
+ * starts or writes to a terminal, so an unavailable socket is only a reason to
122
+ * retry this side channel.
123
+ */
124
+ function subscribeHerdr(socketPath, subscriptions, onEvent, options = {}) {
125
+ const { connect = net.connect, retryBaseMs = SUBSCRIBE_RETRY_BASE_MS, retryMaxMs = SUBSCRIBE_RETRY_MAX_MS, } = options;
126
+ let socket = null;
127
+ let reconnectTimer = null;
128
+ let handshakeTimer = null;
129
+ let retryCount = 0;
130
+ let closed = false;
131
+ const scheduleReconnect = () => {
132
+ if (closed || reconnectTimer)
133
+ return;
134
+ const delay = Math.min(retryBaseMs * 2 ** retryCount, retryMaxMs);
135
+ retryCount += 1;
136
+ reconnectTimer = setTimeout(() => {
137
+ reconnectTimer = null;
138
+ open();
139
+ }, delay);
140
+ if (typeof reconnectTimer.unref === 'function')
141
+ reconnectTimer.unref();
142
+ };
143
+ const open = () => {
144
+ if (closed)
145
+ return;
146
+ let current;
147
+ try {
148
+ current = connect(socketPath);
149
+ }
150
+ catch {
151
+ scheduleReconnect();
152
+ return;
153
+ }
154
+ socket = current;
155
+ let buffer = '';
156
+ let requestId = null;
157
+ let acknowledged = false;
158
+ const clearHandshake = () => {
159
+ if (handshakeTimer)
160
+ clearTimeout(handshakeTimer);
161
+ handshakeTimer = null;
162
+ };
163
+ current.setEncoding('utf8');
164
+ current.on('connect', () => {
165
+ requestCounter += 1;
166
+ requestId = `herdr-remote:subscription:${requestCounter}`;
167
+ current.write(`${JSON.stringify({
168
+ id: requestId,
169
+ method: 'events.subscribe',
170
+ params: { subscriptions },
171
+ })}\n`);
172
+ handshakeTimer = setTimeout(() => current.destroy(), REQUEST_TIMEOUT_MS);
173
+ if (typeof handshakeTimer.unref === 'function')
174
+ handshakeTimer.unref();
175
+ });
176
+ current.on('data', (chunk) => {
177
+ buffer += chunk;
178
+ if (Buffer.byteLength(buffer, 'utf8') > MAX_RESPONSE_BYTES) {
179
+ current.destroy();
180
+ return;
181
+ }
182
+ let newline = buffer.indexOf('\n');
183
+ for (; newline !== -1; newline = buffer.indexOf('\n')) {
184
+ const line = buffer.slice(0, newline);
185
+ buffer = buffer.slice(newline + 1);
186
+ if (!line)
187
+ continue;
188
+ let message;
189
+ try {
190
+ message = JSON.parse(line);
191
+ }
192
+ catch {
193
+ current.destroy();
194
+ return;
195
+ }
196
+ if (message?.id === requestId) {
197
+ clearHandshake();
198
+ if (message.error) {
199
+ current.destroy();
200
+ return;
201
+ }
202
+ acknowledged = true;
203
+ retryCount = 0;
204
+ }
205
+ else if (acknowledged &&
206
+ typeof message?.event === 'string' &&
207
+ message.data &&
208
+ typeof message.data === 'object') {
209
+ try {
210
+ onEvent(message);
211
+ }
212
+ catch (error) {
213
+ // A handler's bug must not end the subscription, but must not vanish either.
214
+ process.stderr.write(`herdr-remote: Herdr event handler failed: ${error instanceof Error ? error.message : error}\n`);
215
+ }
216
+ }
217
+ }
218
+ });
219
+ current.on('error', () => { });
220
+ current.on('close', () => {
221
+ clearHandshake();
222
+ if (socket === current)
223
+ socket = null;
224
+ scheduleReconnect();
225
+ });
226
+ };
227
+ open();
228
+ return {
229
+ close() {
230
+ if (closed)
231
+ return;
232
+ closed = true;
233
+ if (reconnectTimer)
234
+ clearTimeout(reconnectTimer);
235
+ if (handshakeTimer)
236
+ clearTimeout(handshakeTimer);
237
+ reconnectTimer = null;
238
+ handshakeTimer = null;
239
+ const active = socket;
240
+ socket = null;
241
+ if (active)
242
+ active.destroy();
243
+ },
244
+ };
245
+ }
246
+ export { requestHerdr, subscribeHerdr };
@@ -0,0 +1,223 @@
1
+ // How a spawned Herdr is located.
2
+ //
3
+ // `HERDR_BIN_PATH` is what the service layer hands to the host connector, and
4
+ // it is also the escape hatch for an install that is not on `PATH`. Neither is
5
+ // enough on its own once a service manager is in the picture: `systemd --user`
6
+ // and `launchd` start their units with a minimal `PATH` that contains none of
7
+ // the directories a user-level install writes to. A bare `herdr` then reaches
8
+ // `execvp(3)` inside the forked PTY child, which prints
9
+ // "execvp(3) failed.: No such file or directory" and exits — the failure the
10
+ // browser sees as an endless reconnect loop.
11
+ //
12
+ // So the name is resolved to an absolute path here, ahead of any spawn:
13
+ // an honoured override first, then `PATH`, then the handful of directories
14
+ // installers actually use.
15
+ import fs from 'node:fs';
16
+ import os from 'node:os';
17
+ import path from 'node:path';
18
+ import { spawnSync } from 'node:child_process';
19
+ // The same MAJOR.MINOR.PATCH comparison the self-updater uses. A second copy
20
+ // would be a second place for 0.9.10 to sort below 0.9.9.
21
+ import { compareVersions } from './updater.js';
22
+ const COMMAND_NAME = 'herdr';
23
+ /**
24
+ * The oldest Herdr this release is written against.
25
+ *
26
+ * 0.9.0 gave every client its own view, which is what one PTY per browser
27
+ * window rests on. 0.9.1 is what makes that model behave: window titles follow
28
+ * each client's own view instead of another client's selection, activating a
29
+ * machine in the background stops resizing somebody else's focused pane, and a
30
+ * large paste no longer disconnects the client — and pasting is how an image
31
+ * reaches an agent from a phone.
32
+ */
33
+ const MIN_HERDR_VERSION = '0.9.1';
34
+ /** Where a user-level install lands, in the order we trust it. */
35
+ const FALLBACK_DIRECTORIES = [
36
+ '~/.local/bin',
37
+ '~/.cargo/bin',
38
+ '~/bin',
39
+ '/opt/homebrew/bin',
40
+ '/usr/local/bin',
41
+ '/home/linuxbrew/.linuxbrew/bin',
42
+ '/usr/bin',
43
+ ];
44
+ function expandHome(directory, home) {
45
+ if (directory === '~')
46
+ return home;
47
+ if (directory.startsWith('~/'))
48
+ return path.join(home, directory.slice(2));
49
+ return directory;
50
+ }
51
+ /** Windows keeps the executable bit in the extension instead of the mode. */
52
+ function candidateNames(base = COMMAND_NAME) {
53
+ return process.platform === 'win32'
54
+ ? [base, `${base}.exe`, `${base}.cmd`, `${base}.bat`]
55
+ : [base];
56
+ }
57
+ function isExecutableFile(candidate) {
58
+ try {
59
+ if (!fs.statSync(candidate).isFile())
60
+ return false;
61
+ fs.accessSync(candidate, fs.constants.X_OK);
62
+ return true;
63
+ }
64
+ catch {
65
+ return false;
66
+ }
67
+ }
68
+ function findInDirectory(directory, names = candidateNames()) {
69
+ if (!directory)
70
+ return null;
71
+ for (const name of names) {
72
+ const candidate = path.join(directory, name);
73
+ if (isExecutableFile(candidate))
74
+ return candidate;
75
+ }
76
+ return null;
77
+ }
78
+ function findOnSearchPath(searchPath, names = candidateNames()) {
79
+ for (const entry of String(searchPath || '').split(path.delimiter)) {
80
+ const found = findInDirectory(entry.trim(), names);
81
+ if (found)
82
+ return found;
83
+ }
84
+ return null;
85
+ }
86
+ function fallbackDirectories(home = os.homedir()) {
87
+ return FALLBACK_DIRECTORIES.map((directory) => expandHome(directory, home));
88
+ }
89
+ function looksLikePath(value) {
90
+ return value.includes('/') || value.includes(path.sep);
91
+ }
92
+ /**
93
+ * Honour `HERDR_BIN_PATH`.
94
+ *
95
+ * It is documented as the executable, but a directory is an easy thing to
96
+ * write there, and a bare name — someone copying `herdr` into a unit file —
97
+ * still has to go through the search. A value that resolves to nothing is
98
+ * treated as absent rather than fatal: a stale override left behind by a
99
+ * moved install is precisely the case we are trying to survive.
100
+ */
101
+ function resolveOverride(value, searchPath) {
102
+ const trimmed = String(value || '').trim();
103
+ if (!trimmed)
104
+ return null;
105
+ if (looksLikePath(trimmed)) {
106
+ const absolute = path.resolve(trimmed);
107
+ if (isExecutableFile(absolute))
108
+ return absolute;
109
+ return findInDirectory(absolute);
110
+ }
111
+ return findOnSearchPath(searchPath, candidateNames(trimmed));
112
+ }
113
+ /**
114
+ * Everything known about where Herdr is, so callers can report it and not only
115
+ * spawn it.
116
+ *
117
+ * `source` is `env` for an honoured `HERDR_BIN_PATH`, `path` for a hit on
118
+ * `PATH`, `fallback` for one of the well-known install directories, and
119
+ * `unresolved` when nothing matched. In that last case `command` is still the
120
+ * bare name: `PATH` may be right in a way we cannot see from here, and letting
121
+ * the spawn proceed keeps the old behaviour for anyone relying on it.
122
+ */
123
+ function findHerdrCommand({ env = process.env, home = os.homedir(), directories = fallbackDirectories(home), } = {}) {
124
+ const override = resolveOverride(env.HERDR_BIN_PATH, env.PATH);
125
+ if (override)
126
+ return { command: override, source: 'env', found: true };
127
+ const onPath = findOnSearchPath(env.PATH);
128
+ if (onPath)
129
+ return { command: onPath, source: 'path', found: true };
130
+ for (const directory of directories) {
131
+ const found = findInDirectory(directory);
132
+ if (found)
133
+ return { command: found, source: 'fallback', found: true };
134
+ }
135
+ return { command: COMMAND_NAME, source: 'unresolved', found: false };
136
+ }
137
+ function resolveHerdrCommand(options) {
138
+ return findHerdrCommand(options).command;
139
+ }
140
+ /**
141
+ * Re-check a command resolved earlier. A connector outlives the install that
142
+ * was missing when it started, and an absolute path outlives the binary it
143
+ * pointed at, so neither answer stays true for the life of the service.
144
+ */
145
+ function verifyHerdrCommand(command, options = {}) {
146
+ if (typeof command === 'string' && looksLikePath(command) && isExecutableFile(command)) {
147
+ return { command, source: 'verified', found: true };
148
+ }
149
+ return findHerdrCommand(options);
150
+ }
151
+ /** `herdr 0.9.1`, `herdr 0.10.0-preview.2` — the three numbers are all we compare. */
152
+ function parseHerdrVersion(output) {
153
+ const match = /(\d+)\.(\d+)\.(\d+)/.exec(String(output || ''));
154
+ return match ? `${match[1]}.${match[2]}.${match[3]}` : null;
155
+ }
156
+ /**
157
+ * Whether an install is new enough.
158
+ *
159
+ * An unreadable version counts as new enough. Not knowing is not evidence of an
160
+ * old Herdr, and a warning nobody can act on is worse than no warning.
161
+ */
162
+ function meetsMinimum(version, minimum = MIN_HERDR_VERSION) {
163
+ if (!version)
164
+ return true;
165
+ return compareVersions(version, minimum) >= 0;
166
+ }
167
+ /**
168
+ * Ask an install what it is.
169
+ *
170
+ * Deliberately the binary and not the socket: `--version` answers before the
171
+ * server is up, which is when the TUI and the plugin registration ask.
172
+ *
173
+ * `ok` is whether the command ran at all — the presence check registration has
174
+ * always used. `version` is null whenever the output could not be read, and
175
+ * `supported` is true in that case for the reason `meetsMinimum` explains.
176
+ */
177
+ function herdrVersion({ command, timeout = 10_000, ...lookup } = {}) {
178
+ const resolved = command || resolveHerdrCommand(lookup);
179
+ const unknown = {
180
+ command: resolved,
181
+ version: null,
182
+ raw: null,
183
+ supported: true,
184
+ ok: false,
185
+ };
186
+ let result;
187
+ try {
188
+ result = spawnSync(resolved, ['--version'], { encoding: 'utf8', timeout });
189
+ }
190
+ catch {
191
+ return unknown;
192
+ }
193
+ // Status 1 has always counted as present: a binary that answers at all is
194
+ // installed, whatever it thinks of the flag.
195
+ if (result.error || (result.status !== 0 && result.status !== 1))
196
+ return unknown;
197
+ const raw = `${result.stdout || ''}${result.stderr || ''}`.trim();
198
+ const version = parseHerdrVersion(raw);
199
+ return {
200
+ command: resolved,
201
+ version,
202
+ raw: raw || null,
203
+ supported: meetsMinimum(version),
204
+ ok: true,
205
+ };
206
+ }
207
+ /** The one line that tells a user why an older Herdr is a problem here. */
208
+ function herdrOutdatedMessage(version) {
209
+ return (`Herdr ${version} is older than ${MIN_HERDR_VERSION}, which herdr-remote is written against. ` +
210
+ 'Run "herdr update" — window titles, background machine activation and large pastes all ' +
211
+ 'misbehave in browser windows before that release.');
212
+ }
213
+ /** The one message a user needs to fix a missing install themselves. */
214
+ function herdrNotFoundMessage({ env = process.env, home = os.homedir(), directories = fallbackDirectories(home), } = {}) {
215
+ const override = String(env.HERDR_BIN_PATH || '').trim();
216
+ const parts = [`Herdr executable "${COMMAND_NAME}" was not found.`];
217
+ if (override)
218
+ parts.push(`HERDR_BIN_PATH=${override} does not point at an executable.`);
219
+ parts.push(directories.length ? `Searched PATH and ${directories.join(', ')}.` : 'Searched PATH.');
220
+ parts.push('Install Herdr or set HERDR_BIN_PATH to its full path, then restart herdr-remote.');
221
+ return parts.join(' ');
222
+ }
223
+ export { FALLBACK_DIRECTORIES, MIN_HERDR_VERSION, fallbackDirectories, findHerdrCommand, herdrNotFoundMessage, herdrOutdatedMessage, herdrVersion, meetsMinimum, parseHerdrVersion, resolveHerdrCommand, verifyHerdrCommand, };
@@ -0,0 +1,116 @@
1
+ // Registration with the Herdr CLI.
2
+ //
3
+ // Installing from npm puts this package somewhere under a global node_modules
4
+ // tree; Herdr learns about it with `herdr plugin link <path>`. Doing that from
5
+ // here means the user never has to find the install directory themselves.
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { spawnSync } from 'node:child_process';
9
+ import { PACKAGE_ROOT } from './paths.js';
10
+ import { herdrVersion, resolveHerdrCommand } from './herdr-command.js';
11
+ const PLUGIN_ID = 'herdr.remote.web';
12
+ const MANIFEST_NAME = 'herdr-plugin.toml';
13
+ function manifestPath() {
14
+ return path.join(PACKAGE_ROOT, MANIFEST_NAME);
15
+ }
16
+ // Registration also runs from `herdr plugin` actions and from the service
17
+ // manager, neither of which is guaranteed the PATH the user installed with, so
18
+ // the command is resolved rather than named.
19
+ function runHerdr(args, { timeout = 15_000 } = {}) {
20
+ const result = spawnSync(resolveHerdrCommand(), args, { encoding: 'utf8', timeout });
21
+ if (result.error?.code === 'ENOENT') {
22
+ throw Object.assign(new Error('herdr command not found'), { code: 'HERDR_NOT_FOUND' });
23
+ }
24
+ return result;
25
+ }
26
+ /**
27
+ * Parse `herdr plugin list`. Lines look like:
28
+ * - herdr.remote.web (Herdr Remote Web) enabled [local:/path/to/package]
29
+ *
30
+ * Herdr appends diagnostics inside the brackets when something is wrong, e.g.
31
+ * `[local:/path; 1 warning(s)]`, so everything from the first `;` is dropped
32
+ * before the path is read.
33
+ */
34
+ function parsePluginList(output) {
35
+ const plugins = [];
36
+ for (const line of String(output || '').split('\n')) {
37
+ const match = /^-\s+(\S+)\s+\((.*?)\)\s+(\S+)(?:\s+\[(.*)\])?/.exec(line.trim());
38
+ if (!match)
39
+ continue;
40
+ const [, id, name, state, rawSource] = match;
41
+ const source = rawSource ? rawSource.split(';')[0].trim() : null;
42
+ plugins.push({
43
+ id,
44
+ name,
45
+ enabled: state === 'enabled',
46
+ source,
47
+ warnings: rawSource?.includes(';')
48
+ ? rawSource.slice(rawSource.indexOf(';') + 1).trim()
49
+ : null,
50
+ localPath: source?.startsWith('local:') ? source.slice('local:'.length) : null,
51
+ });
52
+ }
53
+ return plugins;
54
+ }
55
+ function registrationStatus() {
56
+ if (!fs.existsSync(manifestPath())) {
57
+ return { available: false, registered: false, reason: 'manifest missing' };
58
+ }
59
+ // Carried on every answer: the screen that shows registration is also the one
60
+ // that has to say the installed Herdr is too old for this plugin.
61
+ const { version, supported } = herdrVersion();
62
+ const installed = { version, versionSupported: supported };
63
+ let result;
64
+ try {
65
+ result = runHerdr(['plugin', 'list']);
66
+ }
67
+ catch (error) {
68
+ if (error.code === 'HERDR_NOT_FOUND')
69
+ return { available: false, registered: false, reason: 'herdr not found' };
70
+ throw error;
71
+ }
72
+ if (result.status !== 0) {
73
+ return {
74
+ available: true,
75
+ registered: false,
76
+ reason: String(result.stderr || '').trim(),
77
+ ...installed,
78
+ };
79
+ }
80
+ const plugins = parsePluginList(result.stdout);
81
+ const entry = plugins.find((plugin) => plugin.id === PLUGIN_ID);
82
+ if (!entry)
83
+ return { available: true, registered: false, packageRoot: PACKAGE_ROOT, ...installed };
84
+ return {
85
+ available: true,
86
+ registered: true,
87
+ enabled: entry.enabled,
88
+ linkedPath: entry.localPath,
89
+ // A stale link pointing at an old checkout is the main failure mode after
90
+ // switching from a source install to npm.
91
+ stale: entry.localPath ? path.resolve(entry.localPath) !== path.resolve(PACKAGE_ROOT) : false,
92
+ packageRoot: PACKAGE_ROOT,
93
+ ...installed,
94
+ };
95
+ }
96
+ function register() {
97
+ const current = registrationStatus();
98
+ if (current.registered && current.stale) {
99
+ // Herdr refuses to link a second plugin with the same id, so drop the old
100
+ // link before pointing it at this install.
101
+ runHerdr(['plugin', 'unlink', PLUGIN_ID]);
102
+ }
103
+ const result = runHerdr(['plugin', 'link', PACKAGE_ROOT]);
104
+ if (result.status !== 0) {
105
+ throw new Error(String(result.stderr || result.stdout || '').trim() || 'herdr plugin link failed');
106
+ }
107
+ return { ok: true, path: PACKAGE_ROOT, output: String(result.stdout || '').trim() };
108
+ }
109
+ function unregister() {
110
+ const result = runHerdr(['plugin', 'unlink', PLUGIN_ID]);
111
+ if (result.status !== 0) {
112
+ throw new Error(String(result.stderr || result.stdout || '').trim() || 'herdr plugin unlink failed');
113
+ }
114
+ return { ok: true, output: String(result.stdout || '').trim() };
115
+ }
116
+ export { parsePluginList, registrationStatus, register, unregister };