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