hopdeck 1.5.6 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -0
- package/README.en.md +9 -5
- package/README.md +9 -5
- package/SECURITY.md +3 -1
- package/bin/hopdeck.js +749 -346
- package/lib/atomic.js +57 -0
- package/lib/background.js +67 -0
- package/lib/clipboard.js +41 -0
- package/lib/codex-history.js +2 -2
- package/lib/config.js +22 -0
- package/lib/deepsearch.js +34 -23
- package/lib/executable.js +28 -13
- package/lib/git.js +34 -2
- package/lib/history.js +273 -68
- package/lib/i18n.js +59 -4
- package/lib/image-worker.js +76 -0
- package/lib/images.js +24 -5
- package/lib/input.js +55 -0
- package/lib/links.js +25 -8
- package/lib/lru.js +39 -0
- package/lib/profile.js +48 -0
- package/lib/provider-setup.js +152 -0
- package/lib/provider.js +7 -1
- package/lib/style.js +14 -4
- package/lib/text.js +16 -5
- package/lib/textfile.js +18 -0
- package/lib/tmux.js +22 -0
- package/lib/windows-terminal.js +11 -5
- package/lib/winshell.js +21 -0
- package/lib/wsl.js +15 -0
- package/package.json +3 -2
package/lib/images.js
CHANGED
|
@@ -80,9 +80,10 @@ function decodePNG(buf) {
|
|
|
80
80
|
}
|
|
81
81
|
const ch = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[ctype];
|
|
82
82
|
if (!w || !h || inter !== 0 || !ch || w * h > 40e6 || (ctype === 3 && !plte)) return null;
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
83
|
+
const bpp = Math.max(1, (ch * depth) >> 3), stride = Math.ceil((w * ch * depth) / 8), size = (stride + 1) * h;
|
|
84
|
+
if (![1, 2, 4, 8, 16].includes(depth)) return null;
|
|
85
|
+
const raw = require('zlib').inflateSync(Buffer.concat(idat), { maxOutputLength: size });
|
|
86
|
+
if (raw.length !== size) return null;
|
|
86
87
|
const px = Buffer.alloc(stride * h);
|
|
87
88
|
for (let y = 0; y < h; y++) {
|
|
88
89
|
const f = raw[y * (stride + 1)], src = y * (stride + 1) + 1, dst = y * stride, prev = dst - stride;
|
|
@@ -145,6 +146,10 @@ function decodeViaSips(buf, run = cp.spawnSync) {
|
|
|
145
146
|
/** PNG (propio) o JPEG (si está jpeg-js); en macOS, lo demás con sips. Devuelve { w, h, rgba } o null. */
|
|
146
147
|
function decodeImage(img) {
|
|
147
148
|
const buf = Buffer.from(img.data, 'base64');
|
|
149
|
+
return decodeNative(buf) || (process.platform === 'darwin' ? decodeViaSips(buf) : null);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function decodeNative(buf) {
|
|
148
153
|
let d = null;
|
|
149
154
|
try {
|
|
150
155
|
if (buf.length > 8 && buf.readUInt32BE(0) === 0x89504e47) d = decodePNG(buf);
|
|
@@ -153,7 +158,21 @@ function decodeImage(img) {
|
|
|
153
158
|
if (jpeg) { const j = jpeg.decode(buf, { useTArray: true, formatAsRGBA: true, maxMemoryUsageInMB: 512 }); d = { w: j.width, h: j.height, rgba: j.data }; }
|
|
154
159
|
}
|
|
155
160
|
} catch { /* formato corrupto o demasiado grande */ }
|
|
156
|
-
return d
|
|
161
|
+
return d;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function decodeImageAsync(img) {
|
|
165
|
+
const buf = Buffer.from(img.data, 'base64'), decoded = decodeNative(buf);
|
|
166
|
+
if (decoded || process.platform !== 'darwin') return decoded;
|
|
167
|
+
let dir;
|
|
168
|
+
try {
|
|
169
|
+
dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'hopdeck-sips-'));
|
|
170
|
+
const src = path.join(dir, 'in.' + sniffExt(buf)), dst = path.join(dir, 'out.png');
|
|
171
|
+
await fs.promises.writeFile(src, buf);
|
|
172
|
+
await new Promise((resolve, reject) => cp.execFile('sips', ['-s', 'format', 'png', '-Z', '1600', src, '--out', dst],
|
|
173
|
+
{ timeout: 8000 }, (err) => err ? reject(err) : resolve()));
|
|
174
|
+
return decodePNG(await fs.promises.readFile(dst));
|
|
175
|
+
} catch { return null; } finally { if (dir) await fs.promises.rm(dir, { recursive: true, force: true }).catch(() => {}); }
|
|
157
176
|
}
|
|
158
177
|
|
|
159
178
|
/** Reduce con filtro de caja y compone sobre un fondo oscuro. Devuelve RGB (3 bytes por píxel). */
|
|
@@ -196,4 +215,4 @@ function halfBlocks(rgb, tw, th2) {
|
|
|
196
215
|
return rows;
|
|
197
216
|
}
|
|
198
217
|
|
|
199
|
-
module.exports = { collectImages, extractImages, findImageByNumber, decodePNG, decodeImage, decodeViaSips, sniffExt, scaleBox, fitSize, halfBlocks };
|
|
218
|
+
module.exports = { collectImages, extractImages, findImageByNumber, decodePNG, decodeImage, decodeImageAsync, decodeViaSips, sniffExt, scaleBox, fitSize, halfBlocks };
|
package/lib/input.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const { StringDecoder } = require('string_decoder');
|
|
3
|
+
|
|
4
|
+
const ESC = '\x1b', PASTE = ESC + '[200~', END = ESC + '[201~';
|
|
5
|
+
|
|
6
|
+
function tokenEnd(s, i) {
|
|
7
|
+
const ch = s[i + 1];
|
|
8
|
+
if (ch === undefined) return -1;
|
|
9
|
+
if (ch === '[' || ch === 'O') {
|
|
10
|
+
let j = i + 2;
|
|
11
|
+
if (ch === '[' && s[j] === '[') { // F1–F5 en la consola de Linux
|
|
12
|
+
if (s[j + 1] === undefined) return -1;
|
|
13
|
+
if (/[A-E]/.test(s[j + 1])) return j + 2;
|
|
14
|
+
}
|
|
15
|
+
while (j < s.length && /[ -?]/.test(s[j])) j++;
|
|
16
|
+
if (j === s.length) return -1;
|
|
17
|
+
if (!/[@-~]/.test(s[j])) return j;
|
|
18
|
+
if (s.startsWith(PASTE, i)) {
|
|
19
|
+
const end = s.indexOf(END, j + 1);
|
|
20
|
+
return end < 0 ? -1 : end + END.length;
|
|
21
|
+
}
|
|
22
|
+
return j + 1;
|
|
23
|
+
}
|
|
24
|
+
if (ch === ']' || ch === 'P') {
|
|
25
|
+
const end = /\x07|\x1b\\/.exec(s.slice(i + 2));
|
|
26
|
+
return end ? i + 2 + end.index + end[0].length : -1;
|
|
27
|
+
}
|
|
28
|
+
const code = s.codePointAt(i + 1);
|
|
29
|
+
return i + (code < 32 || code === 127 ? 1 : code > 0xffff ? 3 : 2);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function createInput({ onFlush = () => {}, delay = 25, setTimer = setTimeout, clearTimer = clearTimeout } = {}) {
|
|
33
|
+
const decoder = new StringDecoder('utf8');
|
|
34
|
+
let pending = '', timer;
|
|
35
|
+
function cancel() { if (timer !== undefined) { clearTimer(timer); timer = undefined; } }
|
|
36
|
+
function feed(chunk) {
|
|
37
|
+
cancel();
|
|
38
|
+
const s = pending + decoder.write(chunk), tokens = [];
|
|
39
|
+
let i = 0;
|
|
40
|
+
while (i < s.length) {
|
|
41
|
+
const end = s[i] === ESC ? tokenEnd(s, i) : i + (s.codePointAt(i) > 0xffff ? 2 : 1);
|
|
42
|
+
if (end < 0) break;
|
|
43
|
+
tokens.push(s.slice(i, end)); i = end;
|
|
44
|
+
}
|
|
45
|
+
pending = s.slice(i);
|
|
46
|
+
if (pending) {
|
|
47
|
+
timer = setTimer(() => { const token = pending; pending = ''; timer = undefined; onFlush([token]); }, delay);
|
|
48
|
+
timer?.unref?.();
|
|
49
|
+
}
|
|
50
|
+
return tokens;
|
|
51
|
+
}
|
|
52
|
+
return { feed, reset() { cancel(); pending = ''; decoder.end(); } };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
module.exports = { createInput, PASTE, END };
|
package/lib/links.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
const cp = require('child_process');
|
|
3
3
|
const fs = require('fs');
|
|
4
|
+
const { isWSL } = require('./wsl');
|
|
4
5
|
|
|
5
6
|
function webUrl(text) {
|
|
6
7
|
if (typeof text !== 'string' || text.length > 8192 || !/^https?:\/\//i.test(text) || /[\s\x00-\x1f\x7f]/u.test(text)) return null;
|
|
@@ -11,6 +12,15 @@ function webUrl(text) {
|
|
|
11
12
|
function urlAt(term, y, col) {
|
|
12
13
|
const buffer = term.buffer.active, row = buffer.viewportY + y, line = buffer.getLine(row);
|
|
13
14
|
if (!line || col < 0 || col >= term.cols) return null;
|
|
15
|
+
let cell = line.getCell(col);
|
|
16
|
+
if (cell?.getWidth() === 0 && col > 0) cell = line.getCell(col - 1);
|
|
17
|
+
// xterm 6 keeps OSC 8 destinations on cells, even when only a label is drawn.
|
|
18
|
+
// Headless has no public link lookup API; keep its version-specific access here.
|
|
19
|
+
const linkId = cell?.extended?.urlId;
|
|
20
|
+
if (linkId) {
|
|
21
|
+
try { return webUrl(term._core?._oscLinkService?.getLinkData(linkId)?.uri); }
|
|
22
|
+
catch { return null; }
|
|
23
|
+
}
|
|
14
24
|
const maxRows = Math.max(1, Math.ceil(16384 / term.cols)); let start = row, end = row;
|
|
15
25
|
while (start > 0 && row - start < maxRows && buffer.getLine(start)?.isWrapped) start--;
|
|
16
26
|
while (end + 1 < buffer.length && end - start < maxRows && buffer.getLine(end + 1)?.isWrapped) end++;
|
|
@@ -40,17 +50,24 @@ function urlAt(term, y, col) {
|
|
|
40
50
|
return null;
|
|
41
51
|
}
|
|
42
52
|
|
|
43
|
-
function
|
|
53
|
+
function spawnOpener(command, target, { spawn, onError }) {
|
|
54
|
+
return new Promise((resolve) => {
|
|
55
|
+
const fail = (error) => { try { onError?.(error, command); } catch { /* */ } resolve(false); };
|
|
56
|
+
try {
|
|
57
|
+
const child = spawn(command, [target], { stdio: 'ignore', detached: true, windowsHide: true, shell: false });
|
|
58
|
+
child.once('error', fail); child.once('spawn', () => resolve(true)); child.unref();
|
|
59
|
+
} catch (error) { fail(error); }
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function openUrl(text, { platform = process.platform, env = process.env, spawn = cp.spawn, readFile = fs.readFileSync, onError } = {}) {
|
|
44
64
|
const url = webUrl(text); if (!url) return false;
|
|
45
65
|
if (env.HOPDECK_OPEN_LOG) {
|
|
46
|
-
try { fs.appendFileSync(env.HOPDECK_OPEN_LOG, url + '\n'); return true; } catch { return false; }
|
|
66
|
+
try { fs.appendFileSync(env.HOPDECK_OPEN_LOG, url + '\n'); return Promise.resolve(true); } catch { return Promise.resolve(false); }
|
|
47
67
|
}
|
|
48
68
|
// URLs never enter cmd.exe or a shell: &, %, quotes and other URL characters stay data.
|
|
49
|
-
const command = platform === 'win32' || env
|
|
50
|
-
|
|
51
|
-
const child = spawn(command, [url], { stdio: 'ignore', detached: true, windowsHide: true, shell: false });
|
|
52
|
-
child.on('error', () => {}); child.unref(); return true;
|
|
53
|
-
} catch { return false; }
|
|
69
|
+
const command = platform === 'win32' || isWSL({ platform, env, readFile }) ? 'explorer.exe' : platform === 'darwin' ? 'open' : 'xdg-open';
|
|
70
|
+
return spawnOpener(command, url, { spawn, onError });
|
|
54
71
|
}
|
|
55
72
|
|
|
56
|
-
module.exports = { webUrl, urlAt, openUrl };
|
|
73
|
+
module.exports = { webUrl, urlAt, openUrl, spawnOpener };
|
package/lib/lru.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
class LRU {
|
|
4
|
+
constructor(limit, maxBytes = Infinity) {
|
|
5
|
+
this.limit = limit; this.maxBytes = maxBytes; this.bytes = 0; this.entries = new Map();
|
|
6
|
+
}
|
|
7
|
+
get size() { return this.entries.size; }
|
|
8
|
+
peek(key) { return this.entries.get(key)?.value; }
|
|
9
|
+
get(key) {
|
|
10
|
+
const entry = this.entries.get(key);
|
|
11
|
+
if (!entry) return undefined;
|
|
12
|
+
this.entries.delete(key); this.entries.set(key, entry);
|
|
13
|
+
return entry.value;
|
|
14
|
+
}
|
|
15
|
+
delete(key) {
|
|
16
|
+
const entry = this.entries.get(key);
|
|
17
|
+
if (!entry) return false;
|
|
18
|
+
this.bytes -= entry.bytes;
|
|
19
|
+
return this.entries.delete(key);
|
|
20
|
+
}
|
|
21
|
+
set(key, value, bytes = 0) {
|
|
22
|
+
this.delete(key);
|
|
23
|
+
if (bytes > this.maxBytes) return;
|
|
24
|
+
this.entries.set(key, { value, bytes }); this.bytes += bytes;
|
|
25
|
+
this.trim();
|
|
26
|
+
}
|
|
27
|
+
weigh(key, bytes) {
|
|
28
|
+
const entry = this.entries.get(key);
|
|
29
|
+
if (!entry) return;
|
|
30
|
+
if (bytes > this.maxBytes) { this.delete(key); return; }
|
|
31
|
+
this.bytes += bytes - entry.bytes; entry.bytes = bytes;
|
|
32
|
+
this.trim();
|
|
33
|
+
}
|
|
34
|
+
trim() {
|
|
35
|
+
while (this.size > this.limit || this.bytes > this.maxBytes) this.delete(this.entries.keys().next().value);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
module.exports = { LRU };
|
package/lib/profile.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const file = process.env.HOPDECK_PROFILE;
|
|
4
|
+
const noop = () => {};
|
|
5
|
+
const disabled = { enabled: false, reloadMs: 20000, mark: noop, first: noop, now: noop, duration: noop, frame: noop, scanEnd: noop, start: noop, baseline: noop };
|
|
6
|
+
|
|
7
|
+
function createProfile() {
|
|
8
|
+
const { appendFileSync } = require('node:fs');
|
|
9
|
+
const { performance, monitorEventLoopDelay } = require('node:perf_hooks');
|
|
10
|
+
const now = () => performance.now();
|
|
11
|
+
const delay = monitorEventLoopDelay({ resolution: 10 });
|
|
12
|
+
const override = Number(process.env.HOPDECK_RELOAD_MS);
|
|
13
|
+
const reloadMs = Number.isInteger(override) && override > 0 && override <= 0x7fffffff ? override : 20000;
|
|
14
|
+
const seen = new Set(), frames = [];
|
|
15
|
+
let maps, timer, previousCpu, previousTime;
|
|
16
|
+
function mark(ev, data) {
|
|
17
|
+
try { appendFileSync(file, JSON.stringify({ t: now(), ev, ...data }) + '\n', { mode: 0o600 }); } catch { /* medición opcional */ }
|
|
18
|
+
}
|
|
19
|
+
function first(ev) {
|
|
20
|
+
if (!seen.has(ev)) { seen.add(ev); mark(ev); }
|
|
21
|
+
}
|
|
22
|
+
function sample(reason) {
|
|
23
|
+
const t = now(), cpu = process.cpuUsage(), { rss, heapUsed } = process.memoryUsage();
|
|
24
|
+
const eventLoop = delay.count ? { p50: delay.percentile(50) / 1e6, p99: delay.percentile(99) / 1e6, max: delay.max / 1e6 } : null;
|
|
25
|
+
mark('sample', { reason, wallMs: t - previousTime, cpu: { user: cpu.user - previousCpu.user, system: cpu.system - previousCpu.system }, rss, heapUsed, eventLoop, maps: maps() });
|
|
26
|
+
previousCpu = cpu; previousTime = t; delay.reset();
|
|
27
|
+
frames.sort((a, b) => a - b);
|
|
28
|
+
const count = frames.length;
|
|
29
|
+
mark('renderEmbed', { reason, count, p50: frames[Math.ceil(count * 0.5) - 1] ?? null, p95: frames[Math.ceil(count * 0.95) - 1] ?? null, max: frames[count - 1] ?? null });
|
|
30
|
+
frames.length = 0;
|
|
31
|
+
}
|
|
32
|
+
function start(readMaps) {
|
|
33
|
+
maps = readMaps; previousTime = now(); previousCpu = process.cpuUsage();
|
|
34
|
+
delay.enable();
|
|
35
|
+
timer = setInterval(() => sample('interval'), 10000).unref();
|
|
36
|
+
}
|
|
37
|
+
function baseline() {
|
|
38
|
+
sample('baseline');
|
|
39
|
+
timer.refresh();
|
|
40
|
+
}
|
|
41
|
+
process.once('exit', () => { if (maps) { sample('exit'); delay.disable(); } });
|
|
42
|
+
return { enabled: true, reloadMs, mark, first, now, start, baseline,
|
|
43
|
+
duration: (ev, startTime, data) => mark(ev, { ms: now() - startTime, ...data }),
|
|
44
|
+
frame: (startTime) => frames.push(now() - startTime),
|
|
45
|
+
scanEnd: (projects) => mark('scanEnd', { projects: projects.length, sessions: projects.reduce((n, p) => n + p.sessions.length, 0) }) };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
module.exports = file ? createProfile() : disabled;
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const os = require('os');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const cp = require('child_process');
|
|
6
|
+
const { findExecutable } = require('./executable');
|
|
7
|
+
const { clean } = require('./style');
|
|
8
|
+
|
|
9
|
+
const PROVIDERS = {
|
|
10
|
+
claude: { label: 'Claude Code', origin: 'https://claude.ai', shell: 'bash', login: ['auth', 'login'], status: ['auth', 'status'] },
|
|
11
|
+
codex: { label: 'Codex', origin: 'https://chatgpt.com/codex', shell: 'sh', login: ['login'], status: ['login', 'status'] },
|
|
12
|
+
};
|
|
13
|
+
function installerFor(id, platform = process.platform) {
|
|
14
|
+
const info = PROVIDERS[id];
|
|
15
|
+
if (!info || !['win32', 'darwin', 'linux'].includes(platform)) throw new Error('Unsupported provider or platform');
|
|
16
|
+
return { ...info, url: info.origin + (platform === 'win32' ? '/install.ps1' : '/install.sh'), interpreter: platform === 'win32' ? 'powershell.exe' : info.shell };
|
|
17
|
+
}
|
|
18
|
+
function canPrompt({ env = process.env, input = process.stdin, output = process.stdout } = {}) {
|
|
19
|
+
return !!input.isTTY && !!output.isTTY && !env.HOPDECK_NOPROMPT && !(env.CI && !['0', 'false'].includes(env.CI));
|
|
20
|
+
}
|
|
21
|
+
function findProvider(id, { env = process.env, platform = process.platform, home = os.homedir(), find = findExecutable } = {}) {
|
|
22
|
+
if (!PROVIDERS[id]) return find(id, { env, platform });
|
|
23
|
+
const hit = find(id, { env, platform }); if (hit) return hit;
|
|
24
|
+
const paths = platform === 'win32' ? path.win32 : path.posix, win = platform === 'win32';
|
|
25
|
+
const dirs = [paths.join(home, '.local', 'bin')];
|
|
26
|
+
if (id === 'claude' && !win) dirs.push(paths.join(home, '.claude', 'local'));
|
|
27
|
+
if (id === 'codex') {
|
|
28
|
+
if (env.CODEX_INSTALL_DIR && paths.isAbsolute(env.CODEX_INSTALL_DIR)) dirs.unshift(env.CODEX_INSTALL_DIR);
|
|
29
|
+
if (win && env.LOCALAPPDATA) dirs.push(paths.join(env.LOCALAPPDATA, 'Programs', 'OpenAI', 'Codex', 'bin'));
|
|
30
|
+
}
|
|
31
|
+
for (const dir of dirs) {
|
|
32
|
+
const file = paths.join(dir, id + (win ? '.exe' : ''));
|
|
33
|
+
try {
|
|
34
|
+
if (!fs.statSync(file).isFile()) continue;
|
|
35
|
+
if (!win) fs.accessSync(file, fs.constants.X_OK);
|
|
36
|
+
const key = Object.keys(env).find((k) => k.toLowerCase() === 'path') || 'PATH';
|
|
37
|
+
env[key] = dir + (win ? ';' : ':') + (env[key] || '');
|
|
38
|
+
return file;
|
|
39
|
+
} catch { /* another installation location */ }
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Bounded HTTPS download. Only installerFor() supplies the initial URL.
|
|
45
|
+
async function downloadInstaller(url, file, fetchImpl = fetch) {
|
|
46
|
+
const allowed = Object.keys(PROVIDERS).flatMap((id) => ['win32', 'linux'].map((platform) => installerFor(id, platform).url));
|
|
47
|
+
if (!allowed.includes(url)) throw new Error('Unknown installer source');
|
|
48
|
+
const signal = AbortSignal.timeout(45000);
|
|
49
|
+
for (let redirects = 0; redirects <= 5; redirects++) {
|
|
50
|
+
const target = new URL(url);
|
|
51
|
+
if (target.protocol !== 'https:' || target.username || target.password) throw new Error('Installer requires HTTPS');
|
|
52
|
+
const response = await fetchImpl(url, { redirect: 'manual', signal });
|
|
53
|
+
if ([301, 302, 303, 307, 308].includes(response.status)) {
|
|
54
|
+
await response.body?.cancel();
|
|
55
|
+
const location = response.headers.get('location'); if (!location) throw new Error('Invalid installer redirect');
|
|
56
|
+
url = new URL(location, url).href; continue;
|
|
57
|
+
}
|
|
58
|
+
if (!response.ok || !response.body) throw new Error('Installer download failed (HTTP ' + response.status + ')');
|
|
59
|
+
const reader = response.body.getReader(), chunks = []; let size = 0;
|
|
60
|
+
try {
|
|
61
|
+
while (true) {
|
|
62
|
+
const { done, value } = await reader.read(); if (done) break;
|
|
63
|
+
size += value.byteLength; if (size > 2 * 1024 * 1024) throw new Error('Installer download is too large');
|
|
64
|
+
chunks.push(Buffer.from(value));
|
|
65
|
+
}
|
|
66
|
+
} finally { await reader.cancel().catch(() => {}); }
|
|
67
|
+
const data = Buffer.concat(chunks);
|
|
68
|
+
if (!data.length || /^\s*(?:<!doctype|<html)/i.test(data.toString('utf8', 0, 80))) throw new Error('Invalid installer response');
|
|
69
|
+
fs.writeFileSync(file, data, { mode: 0o600, flag: 'wx' }); return;
|
|
70
|
+
}
|
|
71
|
+
throw new Error('Too many installer redirects');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function runCommand(bin, args, { env = process.env, stdio = 'inherit', timeout = 600000 } = {}) {
|
|
75
|
+
return new Promise((resolve, reject) => {
|
|
76
|
+
let command = bin, argv = args, verbatim = false;
|
|
77
|
+
if (process.platform === 'win32' && /\.(cmd|bat)$/i.test(bin)) {
|
|
78
|
+
if (/["%\r\n]/.test(bin) || args.some((arg) => !/^[\w-]+$/.test(arg))) return reject(new Error('Unsupported batch command'));
|
|
79
|
+
command = env.ComSpec || 'cmd.exe'; argv = ['/d', '/v:off', '/s', '/c', `""${bin}" ${args.join(' ')}"`]; verbatim = true;
|
|
80
|
+
}
|
|
81
|
+
const child = cp.spawn(command, argv, { env: { ...env, HOPDECK_SKIP: '1' }, stdio, windowsHide: true, windowsVerbatimArguments: verbatim });
|
|
82
|
+
let timedOut = false, interrupted = false;
|
|
83
|
+
const stop = () => {
|
|
84
|
+
if (process.platform === 'win32' && child.pid) cp.spawnSync('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true, timeout: 5000 });
|
|
85
|
+
else child.kill();
|
|
86
|
+
};
|
|
87
|
+
const onInterrupt = () => { interrupted = true; stop(); };
|
|
88
|
+
process.on('SIGINT', onInterrupt);
|
|
89
|
+
const timer = timeout > 0 ? setTimeout(() => { timedOut = true; stop(); }, timeout) : null;
|
|
90
|
+
const cleanup = () => { clearTimeout(timer); process.removeListener('SIGINT', onInterrupt); };
|
|
91
|
+
child.once('error', (error) => { cleanup(); reject(error); });
|
|
92
|
+
child.once('close', (code) => { cleanup(); resolve(interrupted ? 130 : timedOut ? 124 : code ?? 1); });
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function installProvider(id, { platform = process.platform, env = process.env, find = findExecutable, download = downloadInstaller, run = runCommand } = {}) {
|
|
97
|
+
const plan = installerFor(id, platform);
|
|
98
|
+
const interpreter = find(plan.interpreter, { env, platform }) || (platform === 'win32' && find('pwsh.exe', { env, platform }));
|
|
99
|
+
if (!interpreter) throw new Error('Required interpreter: ' + plan.interpreter);
|
|
100
|
+
const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'hopdeck-provider-')));
|
|
101
|
+
try {
|
|
102
|
+
const file = path.join(dir, platform === 'win32' ? 'install.ps1' : 'install.sh');
|
|
103
|
+
await download(plan.url, file);
|
|
104
|
+
const args = platform === 'win32'
|
|
105
|
+
? ['-NoLogo', '-NoProfile', '-Command', "$ErrorActionPreference='Stop'; & ([ScriptBlock]::Create([IO.File]::ReadAllText($env:HOPDECK_INSTALL_SCRIPT)))"] : [file];
|
|
106
|
+
return await run(interpreter, args, { env: { ...env, ...(id === 'codex' ? { CODEX_NON_INTERACTIVE: '1' } : {}), HOPDECK_INSTALL_SCRIPT: file } });
|
|
107
|
+
} finally {
|
|
108
|
+
// The random directory belongs to this invocation; never remove a computed parent.
|
|
109
|
+
if (path.dirname(dir) === fs.realpathSync(os.tmpdir()) && path.basename(dir).startsWith('hopdeck-provider-')) fs.rmSync(dir, { recursive: true, force: true });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function chooseProvider({ ask, T, output = process.stdout }) {
|
|
114
|
+
output.write('\n » Hopdeck\n\n ' + T.setupChoose + '\n ' + T.setupChoices + '\n');
|
|
115
|
+
return ask((key) => key === '1' ? 'claude' : key === '2' ? 'codex' : key === '\x1b' || /^[qQ]$/.test(key) ? null : undefined);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function ensureProvider({ id, config, save, ask, T, env = process.env, input = process.stdin, output = process.stdout,
|
|
119
|
+
find = () => findProvider(id, { env }), install = () => installProvider(id, { env }), run = runCommand }) {
|
|
120
|
+
const info = installerFor(id), interactive = canPrompt({ env, input, output });
|
|
121
|
+
let bin = find(), approved = false;
|
|
122
|
+
if (!bin && !interactive) { output.write(T.setupUnavailable(info.label, id) + '\n'); return false; }
|
|
123
|
+
while (!bin) {
|
|
124
|
+
if (!approved) {
|
|
125
|
+
output.write('\n » Hopdeck\n\n ' + T.setupMissing(info.label) + '\n ' + T.setupInstallInfo + '\n ' + T.setupSource(info.url) + '\n\n ' + T.setupInstallKeys + '\n');
|
|
126
|
+
approved = await ask((key) => /^[\r\n]+$/.test(key) || /^[syi]$/i.test(key) ? true : key === '\x1b' || /^[nq]$/i.test(key) ? false : undefined);
|
|
127
|
+
if (!approved) { output.write(T.setupCancelled + '\n'); return false; }
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
output.write('\n ' + T.setupInstalling(info.label) + '\n');
|
|
131
|
+
const code = await install(); if (code === 130) return false; if (code !== 0) throw new Error('Installer exit: ' + code);
|
|
132
|
+
bin = find(); if (!bin || await run(bin, ['--version'], { env, stdio: 'ignore', timeout: 15000 }) !== 0) throw new Error('Installed command unavailable');
|
|
133
|
+
config.providerLoginPending = true; save(); output.write('\n ' + T.setupInstalled(info.label) + '\n');
|
|
134
|
+
} catch (error) {
|
|
135
|
+
bin = null; output.write('\n ' + T.setupFailed(info.label) + '\n ' + clean(error.message).slice(0, 300) + '\n ' + T.setupRetryKeys + '\n');
|
|
136
|
+
if (!await ask((key) => /^[rR]$/.test(key) ? true : /^[\r\n]+$/.test(key) || key === '\x1b' ? false : undefined)) return false;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (!config.providerLoginPending || !interactive) return true;
|
|
140
|
+
try { if (await run(bin, info.status, { env, stdio: 'ignore', timeout: 15000 }) === 0) { config.providerLoginPending = false; save(); return true; } } catch { /* ask the CLI to authenticate */ }
|
|
141
|
+
while (true) {
|
|
142
|
+
output.write('\n ' + T.setupLoginInfo(info.label) + '\n ' + T.setupLoginKeys + '\n');
|
|
143
|
+
const choice = await ask((key) => /^[\r\n]+$/.test(key) ? 'login' : /^[mM]$/.test(key) ? 'later' : key === '\x1b' ? 'quit' : undefined);
|
|
144
|
+
if (choice !== 'login') return choice === 'later';
|
|
145
|
+
let code = 1; try { code = await run(bin, info.login, { env }); } catch { /* preserve pending login */ }
|
|
146
|
+
if (code === 130) return false;
|
|
147
|
+
if (code === 0) { config.providerLoginPending = false; save(); output.write(T.setupLoginDone + '\n'); return true; }
|
|
148
|
+
output.write(T.setupLoginFailed + '\n');
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
module.exports = { installerFor, canPrompt, findProvider, downloadInstaller, runCommand, installProvider, chooseProvider, ensureProvider };
|
package/lib/provider.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
const path = require('path');
|
|
3
3
|
const os = require('os');
|
|
4
|
+
const { readConfig } = require('./config');
|
|
4
5
|
|
|
5
6
|
// Hopdeck options precede the options forwarded to the selected CLI.
|
|
6
7
|
function parseProvider(argv, fallback = 'claude') {
|
|
@@ -12,12 +13,17 @@ function parseProvider(argv, fallback = 'claude') {
|
|
|
12
13
|
return { id, args };
|
|
13
14
|
}
|
|
14
15
|
|
|
15
|
-
const
|
|
16
|
+
const argv = require.main && /hopdeck\.js$/.test(require.main.filename) ? process.argv.slice(2) : [];
|
|
17
|
+
const value = readConfig().value?.defaultProvider;
|
|
18
|
+
const preferred = ['claude', 'codex'].includes(value) ? value : null;
|
|
19
|
+
const explicit = !!process.env.HOPDECK_PROVIDER || argv[0] === '--provider' || !!argv[0]?.startsWith('--provider=');
|
|
20
|
+
const selected = parseProvider(argv, process.env.HOPDECK_PROVIDER || preferred || 'claude');
|
|
16
21
|
const isCodex = selected.id === 'codex';
|
|
17
22
|
// Child Hopdeck instances (including tmux panes) inherit the selected provider.
|
|
18
23
|
process.env.HOPDECK_PROVIDER = selected.id;
|
|
19
24
|
module.exports = {
|
|
20
25
|
...selected, isCodex, parseProvider,
|
|
26
|
+
explicit, preferred,
|
|
21
27
|
label: isCodex ? 'Codex' : 'Claude',
|
|
22
28
|
configFile: path.join(os.homedir(), isCodex ? '.hopdeck-codex.json' : '.hopdeck.json'),
|
|
23
29
|
launchArgs: (session, extra = []) => [...(session ? (isCodex ? ['resume', session.id] : ['--resume', session.id]) : []), ...extra],
|
package/lib/style.js
CHANGED
|
@@ -4,11 +4,21 @@ const TRUE = /truecolor|24bit/i.test(process.env.COLORTERM || '') || !!process.e
|
|
|
4
4
|
const NOCOL = !!process.env.NO_COLOR; // https://no-color.org
|
|
5
5
|
// tema, por orden de prioridad: HOPDECK_THEME=light|dark → la elección guardada con "hopdeck theme" → COLORFGBG (fondo claro
|
|
6
6
|
// termina en ;7 o ;15) → oscuro
|
|
7
|
-
const savedTheme =
|
|
8
|
-
const THEME_FROM = process.env.HOPDECK_THEME ? 'env' : savedTheme
|
|
9
|
-
const LIGHT = THEME_FROM === 'env' ? process.env.HOPDECK_THEME === 'light' : THEME_FROM === 'config' ? savedTheme
|
|
7
|
+
const savedTheme = process.env.HOPDECK_THEME ? '' : require('./config').readConfig().value?.theme;
|
|
8
|
+
const THEME_FROM = process.env.HOPDECK_THEME ? 'env' : ['light', 'dark'].includes(savedTheme) ? 'config' : 'auto';
|
|
9
|
+
const LIGHT = THEME_FROM === 'env' ? process.env.HOPDECK_THEME === 'light' : THEME_FROM === 'config' ? savedTheme === 'light' : /;(7|15)$/.test(process.env.COLORFGBG || '');
|
|
10
10
|
const fg = (r, g, b, n) => (NOCOL ? '' : TRUE ? `\x1b[38;2;${r};${g};${b}m` : `\x1b[38;5;${n}m`);
|
|
11
11
|
const bg = (r, g, b, n) => (NOCOL ? '' : TRUE ? `\x1b[48;2;${r};${g};${b}m` : `\x1b[48;5;${n}m`);
|
|
12
|
+
const LEVELS = [0, 95, 135, 175, 215, 255];
|
|
13
|
+
function rgbTo256(r, g, b) {
|
|
14
|
+
const nearest = (v) => v < 48 ? 0 : v < 115 ? 1 : Math.min(5, Math.floor((v - 115) / 40) + 2);
|
|
15
|
+
const ri = nearest(r), gi = nearest(g), bi = nearest(b);
|
|
16
|
+
const gray = Math.max(0, Math.min(23, Math.round(((r + g + b) / 3 - 8) / 10)));
|
|
17
|
+
const v = 8 + 10 * gray;
|
|
18
|
+
const cubeDist = (r - LEVELS[ri]) ** 2 + (g - LEVELS[gi]) ** 2 + (b - LEVELS[bi]) ** 2;
|
|
19
|
+
const grayDist = (r - v) ** 2 + (g - v) ** 2 + (b - v) ** 2;
|
|
20
|
+
return grayDist < cubeDist ? 232 + gray : 16 + 36 * ri + 6 * gi + bi;
|
|
21
|
+
}
|
|
12
22
|
const R = '\x1b[0m';
|
|
13
23
|
const PALETTES = {
|
|
14
24
|
light: {
|
|
@@ -71,4 +81,4 @@ function fit(segs, width, base = '') {
|
|
|
71
81
|
return out;
|
|
72
82
|
}
|
|
73
83
|
|
|
74
|
-
module.exports = { TRUE, NOCOL, LIGHT, THEME_FROM, setTheme, isLight, fg, bg, R, C, cw, strW, fit, clean };
|
|
84
|
+
module.exports = { rgbTo256, TRUE, NOCOL, LIGHT, THEME_FROM, setTheme, isLight, fg, bg, R, C, cw, strW, fit, clean };
|
package/lib/text.js
CHANGED
|
@@ -1,12 +1,22 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
// Texto: nombres de carpeta, rutas cortas, búsqueda difusa y ajuste de línea.
|
|
3
3
|
const os = require('os');
|
|
4
|
+
const path = require('path');
|
|
4
5
|
const { strW } = require('./style');
|
|
5
6
|
|
|
6
7
|
const baseName = (p) => p.split(/[\\/]/).filter(Boolean).pop() || p;
|
|
8
|
+
function samePath(a, b, platform = process.platform) {
|
|
9
|
+
const paths = platform === 'win32' ? path.win32 : path.posix;
|
|
10
|
+
a = paths.resolve(a); b = paths.resolve(b);
|
|
11
|
+
return platform === 'win32' || platform === 'darwin' ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
12
|
+
}
|
|
7
13
|
const tidy = (s) => s.replace(/\s+/g, ' ').trim();
|
|
8
14
|
const home = os.homedir();
|
|
9
|
-
|
|
15
|
+
function shortPath(p, { home: h = home, platform = process.platform } = {}) {
|
|
16
|
+
const win = platform === 'win32', prefix = p.slice(0, h.length), next = p[h.length];
|
|
17
|
+
const matches = win ? prefix.toLowerCase() === h.toLowerCase() : prefix === h;
|
|
18
|
+
return matches && (p.length === h.length || next === '/' || (win && next === '\\')) ? '~' + p.slice(h.length) : p;
|
|
19
|
+
}
|
|
10
20
|
|
|
11
21
|
/**
|
|
12
22
|
* Minúsculas y sin acentos («Visión» → «vision», «ñ» → «n»). Cada letra se pliega por separado, así el resultado mide lo mismo
|
|
@@ -26,9 +36,10 @@ const queryWords = (q) => fold(q).split(/\s+/).filter(Boolean);
|
|
|
26
36
|
const matchWords = (ws, folded) => ws.every((w) => folded.includes(w));
|
|
27
37
|
|
|
28
38
|
/** Coincidencia difusa: cada palabra de la consulta debe aparecer como subsecuencia. -1 si no coincide. */
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
39
|
+
const fuzzy = (q, text) => fuzzyWords(queryWords(q), fold(text));
|
|
40
|
+
function fuzzyWords(words, t) {
|
|
41
|
+
let total = 0;
|
|
42
|
+
for (const term of words) {
|
|
32
43
|
let pos = -1, run = 0, score = 0;
|
|
33
44
|
const sub = t.indexOf(term);
|
|
34
45
|
if (sub >= 0) { total += 10 + term.length * 3 - Math.min(sub, 30) / 3; continue; }
|
|
@@ -57,4 +68,4 @@ function wrapText(text, width) {
|
|
|
57
68
|
return out;
|
|
58
69
|
}
|
|
59
70
|
|
|
60
|
-
module.exports = { baseName, tidy, home, shortPath, fold, queryWords, matchWords, fuzzy, wrapText };
|
|
71
|
+
module.exports = { samePath, baseName, tidy, home, shortPath, fold, queryWords, matchWords, fuzzy, fuzzyWords, wrapText };
|
package/lib/textfile.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
|
|
4
|
+
const BOMS = { utf8: Buffer.from([0xef, 0xbb, 0xbf]), utf16le: Buffer.from([0xff, 0xfe]), utf16be: Buffer.from([0xfe, 0xff]) };
|
|
5
|
+
function readText(file) {
|
|
6
|
+
const bytes = fs.readFileSync(file);
|
|
7
|
+
const detected = Object.keys(BOMS).find((key) => bytes.subarray(0, BOMS[key].length).equals(BOMS[key]));
|
|
8
|
+
const encoding = detected || 'utf8', bom = Boolean(detected);
|
|
9
|
+
const body = bytes.subarray(bom ? BOMS[encoding].length : 0);
|
|
10
|
+
const text = encoding === 'utf16be' ? Buffer.from(body).swap16().toString('utf16le') : body.toString(encoding);
|
|
11
|
+
return { text, encoding, bom, eol: text.match(/\r?\n/)?.[0] || '\n' };
|
|
12
|
+
}
|
|
13
|
+
function writeText(file, text, { encoding = 'utf8', bom = false } = {}) {
|
|
14
|
+
const body = encoding === 'utf16be' ? Buffer.from(text, 'utf16le').swap16() : Buffer.from(text, encoding);
|
|
15
|
+
fs.writeFileSync(file, bom ? Buffer.concat([BOMS[encoding], body]) : body);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
module.exports = { readText, writeText };
|
package/lib/tmux.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const { createHash } = require('crypto');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
|
|
5
|
+
const escapeTmux = (value) => value.replace(/#/g, '##');
|
|
6
|
+
function parseTmuxVersion(output) {
|
|
7
|
+
const match = /^tmux\s+(?:next-)?(\d+)\.(\d+)/.exec(output.trim());
|
|
8
|
+
return match ? { major: Number(match[1]), minor: Number(match[2]) } : null;
|
|
9
|
+
}
|
|
10
|
+
function canUseTmux(env, tmuxVersion) {
|
|
11
|
+
return (tmuxVersion?.major > 3 || (tmuxVersion?.major === 3 && tmuxVersion.minor >= 1)) && !env.TMUX && !env.HOPDECK_NOTMUX && !env.HOPDECK_EMBED;
|
|
12
|
+
}
|
|
13
|
+
// tmux con HOPDECK_TMUX; si no, el terminal embebido; tmux también es la alternativa cuando no hay node-pty.
|
|
14
|
+
function tmuxMode({ env, tmuxVersion, deps }) {
|
|
15
|
+
const tmuxOk = canUseTmux(env, tmuxVersion);
|
|
16
|
+
if (env.HOPDECK_TMUX && tmuxOk) return 'tmux';
|
|
17
|
+
if (deps && !env.HOPDECK_NOEMBED) return 'embedded';
|
|
18
|
+
return tmuxOk ? 'tmux' : 'full';
|
|
19
|
+
}
|
|
20
|
+
const tmuxSession = (id, configDir) => 'hopdeck-' + id + '-' + createHash('sha1').update(path.resolve(configDir)).digest('hex').slice(0, 8);
|
|
21
|
+
|
|
22
|
+
module.exports = { escapeTmux, parseTmuxVersion, canUseTmux, tmuxMode, tmuxSession };
|
package/lib/windows-terminal.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
const fs = require('fs');
|
|
4
4
|
const path = require('path');
|
|
5
5
|
const cp = require('child_process');
|
|
6
|
+
const { isWSL } = require('./wsl');
|
|
6
7
|
|
|
7
8
|
/** Quita comentarios y comas finales de un JSON con comentarios (settings.json de Windows Terminal). */
|
|
8
9
|
function stripJsonc(t) {
|
|
@@ -19,7 +20,7 @@ function stripJsonc(t) {
|
|
|
19
20
|
}
|
|
20
21
|
/** ¿Qué hace Ctrl+V en Windows Terminal? 'paste' (pega texto: no deja pasar imágenes), 'custom' (reasignado) o null si no se puede leer. */
|
|
21
22
|
function wtCtrlV(text) {
|
|
22
|
-
let j; try { j = JSON.parse(stripJsonc(text)); } catch { return null; }
|
|
23
|
+
let j; try { j = JSON.parse(stripJsonc(text.replace(/^\uFEFF/, ''))); } catch { return null; }
|
|
23
24
|
const list = [...(Array.isArray(j.actions) ? j.actions : []), ...(Array.isArray(j.keybindings) ? j.keybindings : [])];
|
|
24
25
|
const mine = list.filter((a) => a && [].concat(a.keys || []).some((k) => String(k).toLowerCase() === 'ctrl+v'));
|
|
25
26
|
if (!mine.length) return 'paste'; // sin reasignar: Windows Terminal usa su atajo por defecto (pegar)
|
|
@@ -28,12 +29,17 @@ function wtCtrlV(text) {
|
|
|
28
29
|
const c = last.command !== undefined ? last.command : last.id ? (/PasteFromClipboard$/i.test(last.id) ? 'paste' : defs.get(last.id)) : undefined; // formato nuevo: la tecla apunta a una acción por "id"
|
|
29
30
|
return c === 'paste' || (c && typeof c === 'object' && c.action === 'paste') ? 'paste' : 'custom';
|
|
30
31
|
}
|
|
31
|
-
function wtSettingsFile() {
|
|
32
|
-
let base =
|
|
33
|
-
if (!base &&
|
|
32
|
+
function wtSettingsFile({ env = process.env, platform = process.platform, exec = cp.execFileSync } = {}) {
|
|
33
|
+
let base = env.LOCALAPPDATA;
|
|
34
|
+
if (!base && isWSL({ env, platform })) { try { base = exec('wslpath', ['-u', exec('cmd.exe', ['/c', 'echo %LOCALAPPDATA%'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()], { encoding: 'utf8' }).trim(); } catch { /* */ } }
|
|
34
35
|
if (!base) return null;
|
|
35
36
|
const cands = [];
|
|
36
|
-
|
|
37
|
+
const preferred = ['Microsoft.WindowsTerminal_8wekyb3d8bbwe', 'Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe'];
|
|
38
|
+
const packages = path.join(base, 'Packages');
|
|
39
|
+
try {
|
|
40
|
+
const others = fs.readdirSync(packages).filter((d) => /^Microsoft\.WindowsTerminal/.test(d) && !preferred.includes(d));
|
|
41
|
+
for (const dir of [...preferred, ...others]) cands.push(path.join(packages, dir, 'LocalState', 'settings.json'));
|
|
42
|
+
} catch { /* */ }
|
|
37
43
|
cands.push(path.join(base, 'Microsoft', 'Windows Terminal', 'settings.json'));
|
|
38
44
|
return cands.find((f) => fs.existsSync(f)) || null;
|
|
39
45
|
}
|
package/lib/winshell.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const escapeCmd = (s) => s.replace(/[()\[\]%!^"<>&|;, *?]/g, '^$&');
|
|
4
|
+
function cmdLine(bin, args) {
|
|
5
|
+
// cmd /s quita las comillas exteriores. El escapado del nombre conserva la ruta
|
|
6
|
+
// como una unidad; %* en los shims .cmd añade una segunda pasada para los argumentos.
|
|
7
|
+
const batch = /\.cmd$/i.test(bin);
|
|
8
|
+
if (/["\r\n\0]/.test(bin) || args.some((arg) => /[\r\n\0]/.test(arg))) {
|
|
9
|
+
throw Object.assign(new Error('Invalid Windows command line'), { code: 'HOPDECK_CMD_LINE' });
|
|
10
|
+
}
|
|
11
|
+
const quoted = args.map((arg) => {
|
|
12
|
+
const value = '"' + arg.replace(/(\\*)"/g, '$1$1\\"').replace(/\\+$/, '$&$&') + '"';
|
|
13
|
+
const escaped = escapeCmd(value);
|
|
14
|
+
return batch ? escapeCmd(escaped) : escaped;
|
|
15
|
+
});
|
|
16
|
+
// Las comillas protegen los espacios, pero cmd expande % y ! dentro de ellas.
|
|
17
|
+
const command = /[%!]/.test(bin) ? escapeCmd(bin) : '"' + bin + '"';
|
|
18
|
+
return [command, ...quoted].join(' ');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
module.exports = { cmdLine };
|
package/lib/wsl.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
|
|
4
|
+
let microsoft;
|
|
5
|
+
function isWSL({ env = process.env, platform = process.platform, readFile = fs.readFileSync } = {}) {
|
|
6
|
+
if (platform !== 'linux') return false;
|
|
7
|
+
if (env.WSL_DISTRO_NAME) return true;
|
|
8
|
+
if (readFile === fs.readFileSync && microsoft !== undefined) return microsoft;
|
|
9
|
+
let detected = false;
|
|
10
|
+
try { detected = /microsoft/i.test(readFile('/proc/sys/kernel/osrelease', 'utf8')); } catch { /* sin procfs */ }
|
|
11
|
+
if (readFile === fs.readFileSync) microsoft = detected;
|
|
12
|
+
return detected;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
module.exports = { isWSL };
|