justmux 0.1.0 → 0.1.2

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.
package/README.md CHANGED
@@ -13,8 +13,20 @@ justmux
13
13
 
14
14
  Run the same npm install command to update to the latest release.
15
15
 
16
- The npm package selects a precompiled native binary for macOS or Linux on x64
17
- or arm64. No Rust compiler, installation script, or download on first launch is
16
+ Global installations also check npm at most once a day when launched
17
+ interactively without a command, including `--fullscreen`. A newer version opens
18
+ a compact TUI picker with `Update`, `Skip`, and `Skip this version`, in that
19
+ order. Use Up/Down and Enter, or press 1, 2, or 3. `Update` is initially selected
20
+ and installs that exact version, then exits; run `jm` again afterward. `Skip`
21
+ (also Esc) continues this launch. `Skip this version` suppresses reminders for
22
+ that version, including on later days; a different release can prompt again.
23
+ Ctrl+C cancels startup. The picker restores terminal input and the cursor
24
+ before continuing. Checks have a three-second timeout and offline failures do
25
+ not block use. Set `JUSTMUX_NO_UPDATE_CHECK=1` to disable them. Help, version,
26
+ direct commands, CI, and piped runs skip checks.
27
+
28
+ The npm package selects a precompiled native binary for macOS ARM64 or Linux
29
+ x64. No Rust compiler, installation script, or download on first launch is
18
30
  required. Keep npm optional dependencies enabled so the matching binary can be
19
31
  installed. Node.js 22.15.0 or newer is required (Node.js 24 LTS is recommended) to replace the launcher process
20
32
  with the native executable; JustMux does not leave a Node process supervising tmux.
package/bin/justmux.cjs CHANGED
@@ -1,9 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- try {
5
- require('../lib/launcher.cjs').run(process.argv.slice(2));
6
- } catch (error) {
4
+ async function main() {
5
+ const args = process.argv.slice(2);
6
+ const result = await require('../lib/update.cjs').maybeUpdate(args);
7
+ if (result.action === 'exit') {
8
+ process.exitCode = result.code;
9
+ return;
10
+ }
11
+ require('../lib/launcher.cjs').run(args);
12
+ }
13
+
14
+ main().catch((error) => {
7
15
  process.stderr.write(`justmux: ${error.message}\n`);
8
16
  process.exitCode = 1;
9
- }
17
+ });
package/lib/launcher.cjs CHANGED
@@ -4,16 +4,14 @@ const fs = require('node:fs');
4
4
  const path = require('node:path');
5
5
 
6
6
  const SUPPORTED_PLATFORMS = Object.freeze([
7
- Object.freeze({ platform: 'darwin', arch: 'x64', target: 'x86_64-apple-darwin' }),
8
7
  Object.freeze({ platform: 'darwin', arch: 'arm64', target: 'aarch64-apple-darwin' }),
9
8
  Object.freeze({ platform: 'linux', arch: 'x64', target: 'x86_64-unknown-linux-musl' }),
10
- Object.freeze({ platform: 'linux', arch: 'arm64', target: 'aarch64-unknown-linux-musl' }),
11
9
  ]);
12
10
 
13
11
  function platformPackageName(mainName, platform, arch) {
14
12
  if (!SUPPORTED_PLATFORMS.some((entry) => entry.platform === platform && entry.arch === arch)) {
15
13
  throw new Error(
16
- `Unsupported platform ${platform}/${arch}. JustMux supports macOS and Linux on x64 and arm64.`,
14
+ `Unsupported platform ${platform}/${arch}. JustMux supports macOS arm64 and Linux x64.`,
17
15
  );
18
16
  }
19
17
  return `${mainName}-${platform}-${arch}`;
@@ -0,0 +1,145 @@
1
+ 'use strict';
2
+
3
+ const readline = require('node:readline');
4
+
5
+ const CHOICES = Object.freeze([
6
+ { label: 'Update', value: 'update' },
7
+ { label: 'Skip', value: 'skip' },
8
+ { label: 'Skip this version', value: 'skip-version' },
9
+ ]);
10
+ const SIGNALS = Object.freeze({ SIGINT: 130, SIGTERM: 143, SIGHUP: 129, SIGQUIT: 131 });
11
+
12
+ /** An inline picker. All terminal changes end before npm or the Rust UI runs. */
13
+ function updatePrompt({ currentVersion, latestVersion }, runtime = process) {
14
+ const input = runtime.stdin;
15
+ const output = runtime.stdout;
16
+ if (!input?.isTTY || !output?.isTTY || typeof input.setRawMode !== 'function') {
17
+ return Promise.resolve('skip');
18
+ }
19
+ return new Promise((resolve) => {
20
+ const wasRaw = input.isRaw === true;
21
+ const wasFlowing = input.readableFlowing === true;
22
+ let selected = 0;
23
+ let height = 0;
24
+ let changedRaw = false;
25
+ let cursorHidden = false;
26
+ let finished = false;
27
+ const signalHandlers = new Map();
28
+ const size = () => ({
29
+ width: Math.max(0, (Number.isInteger(output.columns) && output.columns > 0 ? output.columns : 80) - 1),
30
+ rows: Number.isInteger(output.rows) && output.rows > 0 ? output.rows : 24,
31
+ });
32
+ const moveToTop = (lines) => `\r${lines > 1 ? `\x1b[${lines - 1}A` : ''}`;
33
+ const draw = () => {
34
+ const { width, rows } = size();
35
+ const options = CHOICES.map((choice, index) => ({
36
+ text: `${index === selected ? '>' : ' '} ${index + 1}. ${choice.label}`,
37
+ active: index === selected,
38
+ }));
39
+ const title = { text: ' JustMux update available' };
40
+ const versions = { text: ` ${currentVersion} -> ${latestVersion}` };
41
+ const footer = { text: ' Up/Down select | Enter confirm | Esc skip' };
42
+ const blank = { text: '' };
43
+ let lines;
44
+ if (rows >= 8) lines = [title, versions, blank, ...options, blank, footer];
45
+ else if (rows >= 6) lines = [title, versions, ...options, footer];
46
+ else if (rows >= 5) lines = [versions, ...options, footer];
47
+ else if (rows >= 4) lines = [versions, ...options];
48
+ else {
49
+ const start = Math.min(Math.max(0, selected - rows + 1), CHOICES.length - rows);
50
+ lines = options.slice(start, start + rows);
51
+ }
52
+ // Never print into the final column: wrapping would invalidate the
53
+ // relative cursor position, especially in a narrow tmux popup.
54
+ const previousHeight = Math.min(height, rows);
55
+ const nextHeight = Math.max(previousHeight, lines.length);
56
+ const rendered = Array.from({ length: nextHeight }, (_, index) => {
57
+ const line = lines[index] ?? blank;
58
+ const text = line.text.slice(0, width);
59
+ return `\x1b[2K${line.active ? `\x1b[7m${text}\x1b[0m` : text}`;
60
+ });
61
+ output.write(`${moveToTop(previousHeight)}${rendered.join('\r\n')}`);
62
+ height = nextHeight;
63
+ };
64
+ const finish = (answer) => {
65
+ if (finished) return;
66
+ finished = true;
67
+ input.removeListener('keypress', onKey);
68
+ input.removeListener('end', onEnd);
69
+ input.removeListener('close', onEnd);
70
+ input.removeListener('error', onEnd);
71
+ output.removeListener('resize', redraw);
72
+ output.removeListener('error', onEnd);
73
+ for (const [signal, handler] of signalHandlers) runtime.removeListener(signal, handler);
74
+ try {
75
+ const visibleHeight = Math.min(height, size().rows);
76
+ if (visibleHeight) {
77
+ output.write(`${moveToTop(visibleHeight)}${Array(visibleHeight).fill('\x1b[2K').join('\r\n')}${moveToTop(visibleHeight)}`);
78
+ }
79
+ } catch { /* Restoring input and the cursor must still run. */ }
80
+ try { if (cursorHidden) output.write('\x1b[0m\x1b[?25h'); } catch { /* Output may have closed. */ }
81
+ try { if (changedRaw) input.setRawMode(wasRaw); } catch { /* Input may have closed. */ }
82
+ if (!wasFlowing) input.pause();
83
+ resolve(answer);
84
+ };
85
+ const onEnd = () => finish('skip');
86
+ const redraw = () => {
87
+ if (finished) return;
88
+ try { draw(); } catch { finish('skip'); }
89
+ };
90
+ const onKey = (_text, key = {}) => {
91
+ if (finished) return;
92
+ if (key.ctrl) {
93
+ if (key.name === 'c') finish({ action: 'exit', code: 130 });
94
+ else if (key.name === 'd') finish('skip');
95
+ return;
96
+ }
97
+ // Node marks a standalone Esc as meta:true as well as Alt shortcuts.
98
+ if (key.meta && key.name !== 'escape') return;
99
+ switch (key.name) {
100
+ case 'up': case 'k':
101
+ selected = (selected + CHOICES.length - 1) % CHOICES.length;
102
+ redraw();
103
+ break;
104
+ case 'down': case 'j': case 'tab':
105
+ selected = (selected + 1) % CHOICES.length;
106
+ redraw();
107
+ break;
108
+ case 'return': case 'enter':
109
+ finish(CHOICES[selected].value);
110
+ break;
111
+ case 'escape':
112
+ finish('skip');
113
+ break;
114
+ default: {
115
+ const choice = CHOICES[Number(key.name) - 1];
116
+ if (choice) finish(choice.value);
117
+ }
118
+ }
119
+ };
120
+ try {
121
+ for (const [signal, code] of Object.entries(SIGNALS)) {
122
+ const handler = () => finish({ action: 'exit', code });
123
+ signalHandlers.set(signal, handler);
124
+ runtime.on(signal, handler);
125
+ }
126
+ input.on('keypress', onKey);
127
+ input.on('end', onEnd);
128
+ input.on('close', onEnd);
129
+ input.on('error', onEnd);
130
+ output.on('resize', redraw);
131
+ output.on('error', onEnd);
132
+ readline.emitKeypressEvents(input);
133
+ if (!wasRaw) {
134
+ changedRaw = true;
135
+ input.setRawMode(true);
136
+ }
137
+ cursorHidden = true;
138
+ output.write('\x1b[?25l');
139
+ draw();
140
+ input.resume();
141
+ } catch { finish('skip'); }
142
+ });
143
+ }
144
+
145
+ module.exports = { updatePrompt };
package/lib/update.cjs ADDED
@@ -0,0 +1,207 @@
1
+ 'use strict';
2
+
3
+ const nativeFs = require('node:fs');
4
+ const os = require('node:os');
5
+ const path = require('node:path');
6
+ const { spawn } = require('node:child_process');
7
+ const { updatePrompt } = require('./update-prompt.cjs');
8
+
9
+ const DAY = 24 * 60 * 60 * 1000;
10
+ const BODY_LIMIT = 64 * 1024;
11
+ const CONTINUE = Object.freeze({ action: 'continue' });
12
+ const VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
13
+ const PACKAGE = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
14
+
15
+ function versionParts(version) {
16
+ const match = typeof version === 'string' && VERSION.exec(version);
17
+ if (!match) throw new Error('Invalid semantic version');
18
+ const prerelease = match[4]?.split('.') ?? [];
19
+ if (prerelease.some((part) => /^0\d+$/.test(part))) throw new Error('Invalid semantic version');
20
+ return { core: match.slice(1, 4).map(BigInt), prerelease };
21
+ }
22
+
23
+ function compareVersions(left, right) {
24
+ const a = versionParts(left);
25
+ const b = versionParts(right);
26
+ for (let i = 0; i < 3; i++) {
27
+ if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
28
+ }
29
+ if (!a.prerelease.length || !b.prerelease.length) {
30
+ return Number(!a.prerelease.length) - Number(!b.prerelease.length);
31
+ }
32
+ for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i++) {
33
+ const x = a.prerelease[i];
34
+ const y = b.prerelease[i];
35
+ if (x === y) continue;
36
+ if (x === undefined) return -1;
37
+ if (y === undefined) return 1;
38
+ const numericX = /^\d+$/.test(x);
39
+ const numericY = /^\d+$/.test(y);
40
+ if (numericX !== numericY) return numericX ? -1 : 1;
41
+ return (numericX ? BigInt(x) < BigInt(y) : x < y) ? -1 : 1;
42
+ }
43
+ return 0;
44
+ }
45
+
46
+ // Resolve links first: `npm link` to a source checkout is not an installation
47
+ // this updater should replace. Local node_modules and npx caches are excluded.
48
+ function detectGlobalPrefix(packageRoot, name, fs = nativeFs) {
49
+ if (!PACKAGE.test(name ?? '')) return null;
50
+ const actual = fs.realpathSync(packageRoot);
51
+ let directory = actual;
52
+ for (const segment of name.split('/').reverse()) {
53
+ if (path.basename(directory) !== segment) return null;
54
+ directory = path.dirname(directory);
55
+ }
56
+ if (path.basename(directory) !== 'node_modules' || path.basename(path.dirname(directory)) !== 'lib') {
57
+ return null;
58
+ }
59
+ return path.dirname(path.dirname(directory));
60
+ }
61
+
62
+ function defaultCachePath(runtime = process) {
63
+ const env = runtime.env ?? {};
64
+ if (env.XDG_CACHE_HOME && path.isAbsolute(env.XDG_CACHE_HOME)) {
65
+ return path.join(env.XDG_CACHE_HOME, 'justmux', 'update.json');
66
+ }
67
+ const home = env.HOME || os.homedir();
68
+ return path.join(home, runtime.platform === 'darwin' ? 'Library/Caches' : '.cache', 'justmux', 'update.json');
69
+ }
70
+
71
+ async function fetchLatest(name, { fetchImpl = globalThis.fetch, timeoutMs = 3000 } = {}) {
72
+ if (!PACKAGE.test(name ?? '') || typeof fetchImpl !== 'function') throw new Error('Invalid update request');
73
+ const timeout = Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.min(timeoutMs, 3000) : 3000;
74
+ const controller = new AbortController();
75
+ let timer;
76
+ const deadline = new Promise((_, reject) => {
77
+ timer = setTimeout(() => {
78
+ controller.abort();
79
+ reject(new Error('Update check timed out'));
80
+ }, timeout);
81
+ });
82
+ try {
83
+ return await Promise.race([deadline, (async () => {
84
+ const response = await fetchImpl(`https://registry.npmjs.org/${encodeURIComponent(name)}/latest`, {
85
+ method: 'GET', redirect: 'error', signal: controller.signal,
86
+ headers: { Accept: 'application/json' },
87
+ });
88
+ if (!response.ok) {
89
+ await response.body?.cancel();
90
+ throw new Error('Update metadata unavailable');
91
+ }
92
+ if (Number(response.headers.get('content-length')) > BODY_LIMIT) {
93
+ await response.body?.cancel();
94
+ throw new Error('Update metadata too large');
95
+ }
96
+ const reader = response.body?.getReader();
97
+ if (!reader) throw new Error('Missing update metadata');
98
+ const chunks = [];
99
+ let length = 0;
100
+ try {
101
+ while (true) {
102
+ const { done, value } = await reader.read();
103
+ if (done) break;
104
+ length += value.byteLength;
105
+ if (length > BODY_LIMIT) {
106
+ await reader.cancel();
107
+ throw new Error('Update metadata too large');
108
+ }
109
+ chunks.push(Buffer.from(value));
110
+ }
111
+ } finally { reader.releaseLock(); }
112
+ const metadata = JSON.parse(Buffer.concat(chunks, length).toString('utf8'));
113
+ if (metadata.name !== name) throw new Error('Update package name mismatch');
114
+ versionParts(metadata.version);
115
+ return metadata.version;
116
+ })()]);
117
+ } finally {
118
+ clearTimeout(timer);
119
+ controller.abort();
120
+ }
121
+ }
122
+
123
+ function nativeInstall(executable, args, options) {
124
+ return new Promise((resolve) => {
125
+ const child = spawn(executable, args, options);
126
+ child.once('error', () => resolve({ status: 1 }));
127
+ child.once('close', (status, signal) => resolve({ status, signal }));
128
+ });
129
+ }
130
+
131
+ const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
132
+
133
+ /** An optional startup step; errors must never stop the native application. */
134
+ async function maybeUpdate(args, options = {}) {
135
+ const runtime = options.runtime ?? process;
136
+ const env = runtime.env ?? {};
137
+ if (!Array.isArray(args) || !(args.length === 0 || (args.length === 1 && args[0] === '--fullscreen'))
138
+ || !runtime.stdin?.isTTY || !runtime.stdout?.isTTY || env.CI
139
+ || env.JUSTMUX_NO_UPDATE_CHECK === '1' || env.NO_UPDATE_CHECK === '1'
140
+ || !((runtime.platform === 'darwin' && runtime.arch === 'arm64') || (runtime.platform === 'linux' && runtime.arch === 'x64'))) {
141
+ return CONTINUE;
142
+ }
143
+ try {
144
+ const fs = options.fs ?? nativeFs;
145
+ const packageRoot = options.packageRoot ?? path.resolve(__dirname, '..');
146
+ const manifest = options.manifest ?? JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
147
+ versionParts(manifest.version);
148
+ const prefix = detectGlobalPrefix(packageRoot, manifest.name, fs);
149
+ if (!prefix) return CONTINUE;
150
+ const cachePath = options.cachePath ?? defaultCachePath(runtime);
151
+ const now = (options.now ?? Date.now)();
152
+ if (!Number.isFinite(now) || now < 0) return CONTINUE;
153
+ let cache;
154
+ let dismissedVersion;
155
+ try {
156
+ cache = JSON.parse(fs.readFileSync(cachePath, 'utf8'));
157
+ if (typeof cache.dismissedVersion === 'string') {
158
+ try {
159
+ versionParts(cache.dismissedVersion);
160
+ dismissedVersion = cache.dismissedVersion;
161
+ } catch { /* Ignore invalid saved dismissals. */ }
162
+ }
163
+ versionParts(cache.version);
164
+ if (!Number.isFinite(cache.time) || cache.time < 0 || cache.time > now || now - cache.time >= DAY) cache = undefined;
165
+ } catch { cache = undefined; }
166
+ const save = () => {
167
+ try {
168
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
169
+ fs.writeFileSync(cachePath, `${JSON.stringify(cache)}\n`, { mode: 0o600 });
170
+ } catch { /* A read-only cache must not prevent starting JustMux. */ }
171
+ };
172
+ if (!cache) {
173
+ cache = { version: manifest.version, time: now, ...(dismissedVersion && { dismissedVersion }) };
174
+ // Persist attempts as well as successes: offline launches do not repeat
175
+ // a network timeout on every invocation throughout the same day.
176
+ save();
177
+ try {
178
+ cache.version = await fetchLatest(manifest.name, options);
179
+ save();
180
+ } catch { return CONTINUE; }
181
+ }
182
+ if (compareVersions(cache.version, manifest.version) <= 0 || cache.dismissedVersion === cache.version
183
+ || (!versionParts(manifest.version).prerelease.length && versionParts(cache.version).prerelease.length)) return CONTINUE;
184
+ const answer = await (options.prompt ?? updatePrompt)(
185
+ { currentVersion: manifest.version, latestVersion: cache.version }, runtime,
186
+ );
187
+ if (answer?.action === 'exit') return answer;
188
+ if (answer === 'skip-version') {
189
+ cache.dismissedVersion = cache.version;
190
+ save();
191
+ }
192
+ if (answer !== 'update') return CONTINUE;
193
+ const installArgs = ['install', '--global', '--prefix', prefix, `${manifest.name}@${cache.version}`, '--include=optional'];
194
+ let result;
195
+ try {
196
+ result = await (options.install ?? nativeInstall)('npm', installArgs, { stdio: 'inherit', shell: false });
197
+ } catch { result = { status: 1 }; }
198
+ if (result?.status === 0 && !result.signal) {
199
+ runtime.stdout.write('JustMux updated. Run jm again to start the new version.\n');
200
+ return { action: 'exit', code: 0 };
201
+ }
202
+ runtime.stdout.write(`JustMux update failed. Continuing with the installed version.\nTo retry: npm ${installArgs.map(quote).join(' ')}\n`);
203
+ return CONTINUE;
204
+ } catch { return CONTINUE; }
205
+ }
206
+
207
+ module.exports = { maybeUpdate, compareVersions, detectGlobalPrefix, defaultCachePath, fetchLatest, updatePrompt };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "justmux",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "A modern slash-command interface for tmux. Just tmux. Just simpler.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -31,10 +31,8 @@
31
31
  "LICENSE"
32
32
  ],
33
33
  "optionalDependencies": {
34
- "justmux-darwin-x64": "0.1.0",
35
- "justmux-darwin-arm64": "0.1.0",
36
- "justmux-linux-x64": "0.1.0",
37
- "justmux-linux-arm64": "0.1.0"
34
+ "justmux-darwin-arm64": "0.1.2",
35
+ "justmux-linux-x64": "0.1.2"
38
36
  },
39
37
  "publishConfig": {
40
38
  "access": "public",