veodl 1.10.0 → 1.11.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.
@@ -0,0 +1,72 @@
1
+ import { terminalColumns } from './terminal-size.js';
2
+ import { stripVTControlCharacters } from 'node:util';
3
+
4
+ /** A bounded region in the normal terminal buffer, with the cursor at its end. */
5
+ export function createInlineRegion(stream) {
6
+ let source;
7
+ let live;
8
+ let visible = false;
9
+ let painting = false;
10
+ let closed = false;
11
+ let lastSize = '';
12
+ let rendered = [];
13
+ const logs = [];
14
+ const erase = () => {
15
+ if (!visible) return;
16
+ const width = terminalColumns(stream);
17
+ const lastReflows = process.platform === 'win32' && (stream === process.stdout || stream === process.stderr);
18
+ const above = rendered.reduce((sum, line, index) => sum + (index === rendered.length - 1 && !lastReflows ? 1 : Math.max(1, Math.ceil(stripVTControlCharacters(line).length / width))), 0) - 1;
19
+ if (above) stream.write(`\x1b[${above}A`);
20
+ stream.write('\r\x1b[2K\x1b[J');
21
+ };
22
+ const textOf = render => render().replace(/\r?\n$/, '').replace(/\r\n/g, '\n');
23
+ const render = () => {
24
+ if (closed || painting) return;
25
+ painting = true;
26
+ try {
27
+ const width = terminalColumns(stream);
28
+ const height = Math.max(1, (stream.rows || 24) - 1);
29
+ lastSize = `${width}:${height}`;
30
+ erase();
31
+ const sourceRows = source ? textOf(source).split('\n') : [];
32
+ const progress = live ? textOf(live).split('\n') : [];
33
+ const logLines = () => logs.flatMap(log => textOf(log).split('\n'));
34
+ // Commit older status messages above the region before it outgrows the
35
+ // viewport. Source, logs and progress stay in chronological order and
36
+ // re-render together when the terminal is resized.
37
+ while (logs.length && sourceRows.length + logLines().length + progress.length > height) {
38
+ stream.write(textOf(logs.shift()).replace(/\n/g, '\r\n') + '\r\n');
39
+ }
40
+ const contents = [...sourceRows, ...logLines(), ...progress];
41
+ if (!contents.length) { visible = false; return; }
42
+ const lines = contents;
43
+ stream.write('\r' + lines.join('\r\n'));
44
+ rendered = lines;
45
+ visible = true;
46
+ } finally { painting = false; }
47
+ };
48
+ const resize = () => {
49
+ const size = `${terminalColumns(stream)}:${Math.max(1, (stream.rows || 24) - 1)}`;
50
+ if (size !== lastSize) render();
51
+ };
52
+ stream.on?.('resize', resize);
53
+ const timer = setInterval(resize, 150);
54
+ timer.unref?.();
55
+ const commit = () => {
56
+ erase();
57
+ const lines = [...[source].filter(Boolean).map(textOf), ...logs.map(textOf)];
58
+ if (lines.length) stream.write(lines.join('\n').replace(/\n/g, '\r\n') + '\r\n');
59
+ source = undefined; logs.length = 0; live = undefined; visible = false;
60
+ };
61
+ return {
62
+ source(value) { commit(); source = value; render(); },
63
+ log(value) { logs.push(value); render(); },
64
+ live(value) { live = value; render(); },
65
+ commit,
66
+ close() {
67
+ if (closed) return;
68
+ commit(); closed = true;
69
+ clearInterval(timer); stream.removeListener?.('resize', resize);
70
+ },
71
+ };
72
+ }
@@ -92,6 +92,17 @@ export async function inspectMedia(file, { checkAudio = false, signal, runner =
92
92
  return result;
93
93
  }
94
94
 
95
+ /** A fast post-download container/stream check; it does not decode the full file. */
96
+ export async function verifySavedMedia(file, { audio = false, signal, inspect = inspectMedia } = {}) {
97
+ let report;
98
+ try { report = await inspect(file, { signal }); }
99
+ catch (error) { throw new Error(`Verification failed for ${file}: ${error.message}`); }
100
+ if (audio ? !report.hasAudioTrack : !report.hasVideoTrack) {
101
+ throw new Error(`Verification failed for ${file}: no ${audio ? 'audio' : 'video'} track found.`);
102
+ }
103
+ return report;
104
+ }
105
+
95
106
  export async function inspectRun(id, { checkAudio = false, searchRoot, signal, root, inspect = inspectMedia } = {}) {
96
107
  if (!RUN_ARCHIVE_ID.test(id)) throw new Error('Run ids have 6 letters or digits. List active runs with veo runs --json or finished attempts with veo history --json.');
97
108
  const archive = await readRunArchive(id, root);
@@ -104,10 +104,15 @@ export async function interactiveArgs(config, { signal, input = process.stdin, o
104
104
  if (type === 'video' && ['mp3', 'm4a', 'aac', 'opus', 'flac', 'wav'].includes(defaults.format)) args.push('--format', 'mp4');
105
105
  if (type === 'audio' && ['mp4', 'mkv', 'webm', 'mov'].includes(defaults.format)) args.push('--format', 'mp3');
106
106
  const directory = (await question(`Output directory [${defaults.output || process.cwd()}]: `)).trim() || defaults.output || process.cwd();
107
- args.push('-o', directory, '--resume');
108
- const skipDefault = defaults.skipExisting === false ? 'n' : 'y';
109
- const skip = await choose(`Skip previously downloaded videos? (y/n) [${skipDefault}]: `, ['y', 'n'], skipDefault);
110
- args.push(skip === 'y' ? '--skip-existing' : '--no-skip-existing');
107
+ args.push('-o', directory);
108
+ if (defaults.incognito) {
109
+ args.push('--no-resume', '--no-skip-existing');
110
+ } else {
111
+ args.push('--resume');
112
+ const skipDefault = defaults.skipExisting === false ? 'n' : 'y';
113
+ const skip = await choose(`Skip previously downloaded videos? (y/n) [${skipDefault}]: `, ['y', 'n'], skipDefault);
114
+ args.push(skip === 'y' ? '--skip-existing' : '--no-skip-existing');
115
+ }
111
116
  output.write(`Ready: ${type}, ${directory}\n`);
112
117
  if (await choose('Start download? (y/n) [y]: ', ['y', 'n'], 'y') === 'n') return null;
113
118
  return args;
package/src/jobs.js CHANGED
@@ -1,13 +1,17 @@
1
1
  import { runPool, serialQueue, reducedLimit, formatTimings } from './execution.js';
2
- import { styleText } from './progress.js';
2
+ import { styleText, terminalText } from './progress.js';
3
3
  import path from 'node:path';
4
- import { lstat, readdir } from 'node:fs/promises';
4
+ import { lstat, mkdtemp, readdir, rm } from 'node:fs/promises';
5
+ import os from 'node:os';
5
6
  import { randomUUID } from 'node:crypto';
6
7
  import { cacheBase } from './paths.js';
7
8
  import { publicOptions, readJson, writeJson } from './state.js';
8
9
  import { cleanText, readableError, validateUrl } from './utils.js';
10
+ import { RUN_ARCHIVE_ID } from './run-archive.js';
11
+ import { folderLink } from './path-links.js';
9
12
 
10
- export async function retryOptions(file) {
13
+ export async function retryOptions(file, root = cacheBase()) {
14
+ if (RUN_ARCHIVE_ID.test(file)) file = await retryJobForRun(file, root);
11
15
  const job = await readJson(path.resolve(file), null);
12
16
  if (job?.version !== 1 || !Array.isArray(job.items)) throw new Error('Invalid retry job file.');
13
17
  const pending = job.items.filter(item => !['saved', 'skipped'].includes(item.status));
@@ -22,6 +26,24 @@ export async function retryOptions(file) {
22
26
  });
23
27
  }
24
28
 
29
+ /** Resolve a persistent run ID using its original retry job, including older runs. */
30
+ async function retryJobForRun(id, root) {
31
+ const { listRuns } = await import('./runs.js');
32
+ const runs = await listRuns(root);
33
+ if (runs.some(run => run.id === id && run.alive)) throw new Error(`Run ${id} is still active. Stop it before retrying.`);
34
+ const directory = path.join(path.resolve(root), 'jobs');
35
+ const entries = await readdir(directory, { withFileTypes: true }).catch(error => {
36
+ if (error.code === 'ENOENT') return [];
37
+ throw error;
38
+ });
39
+ for (const entry of entries.filter(entry => entry.isFile() && /^\d{13}-[a-f0-9-]{36}\.json$/.test(entry.name)).sort((a, b) => b.name.localeCompare(a.name))) {
40
+ const file = path.join(directory, entry.name);
41
+ const job = await readJson(file, null).catch(error => { if (error instanceof SyntaxError) return null; throw error; });
42
+ if (job?.runId === id) return file;
43
+ }
44
+ throw new Error(`No retry job found for run ${id}. Retry jobs may have been removed by veo flush.`);
45
+ }
46
+
25
47
  /**
26
48
  * Location of one run's job file. It is created before the first download starts
27
49
  * so `veo runs <id>` can report per-item progress from it.
@@ -53,6 +75,13 @@ export async function latestFailedJob(root = cacheBase()) {
53
75
  }
54
76
 
55
77
  export async function runJob(options, { download, reporter, signal, openFile, stdout = process.stdout, stderr = process.stderr, jobFile, items, recordStats, recordHistory, runId, archiveRoot } = {}) {
78
+ if (options.incognito) {
79
+ runId = undefined;
80
+ recordStats = undefined;
81
+ recordHistory = undefined;
82
+ }
83
+ const concurrency = options.concurrentDownloads ?? 2;
84
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 4) throw new Error('Concurrent downloads must be between 1 and 4.');
56
85
  const file = jobFile || jobFilePath();
57
86
  const requests = items || options.urls.map(url => ({ ...options, url }));
58
87
  const job = { version: 1, ...(runId ? { runId } : {}), startedAt: new Date().toISOString(), options: publicOptions({ ...options, output: path.resolve(options.output) }),
@@ -60,17 +89,17 @@ export async function runJob(options, { download, reporter, signal, openFile, st
60
89
  // Each retry item can have its own playlist selection.
61
90
  job.items.forEach((item, index) => { item.options = publicOptions(requests[index]); });
62
91
  const { cleanupDownloadCache } = await import('./download-cache.js');
63
- await cleanupDownloadCache();
92
+ if (!options.incognito) await cleanupDownloadCache();
93
+ const privateRoot = options.incognito ? await mkdtemp(path.join(os.tmpdir(), 'veo-incognito-')) : null;
64
94
  const queue = serialQueue();
65
- const persist = () => queue(() => writeJson(file, job));
95
+ const persist = () => options.incognito ? Promise.resolve() : queue(() => writeJson(file, job));
66
96
  await persist();
67
97
  const activeTargets = new Map();
68
98
  const totals = { saved: 0, skipped: 0, failed: 0 };
69
99
  const adaptiveState = { divisor: 1 };
70
100
  const archiveTools = runId ? await import('./run-archive.js') : null;
71
- const concurrency = options.concurrentDownloads ?? 2;
72
- if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 4) throw new Error('Concurrent downloads must be between 1 and 4.');
73
- await runPool(requests, () => reducedLimit(concurrency, adaptiveState), async (request, index) => {
101
+ try {
102
+ await runPool(requests, () => reducedLimit(concurrency, adaptiveState), async (request, index) => {
74
103
  const targetKey = JSON.stringify([request.url, path.resolve(request.output)]);
75
104
  const previous = activeTargets.get(targetKey);
76
105
  let release;
@@ -96,7 +125,10 @@ export async function runJob(options, { download, reporter, signal, openFile, st
96
125
  let title;
97
126
  const publish = async files => {
98
127
  if (!options.json) for (const target of files) {
99
- if (!published.has(target)) stdout.write(styleText(stdout, `Saved: ${cleanText(target)}`, 'success', options.color !== false) + '\n');
128
+ if (!published.has(target)) {
129
+ const display = terminalText(stdout, `Saved: ${cleanText(target)}`);
130
+ stdout.write(styleText(stdout, display.startsWith('Saved: ') ? `Saved: ${folderLink(stdout, target, display.slice(7))}` : display, 'success', options.color !== false) + '\n');
131
+ }
100
132
  published.add(target);
101
133
  }
102
134
  if (request.open && !opened && files.length) {
@@ -109,7 +141,8 @@ export async function runJob(options, { download, reporter, signal, openFile, st
109
141
  try {
110
142
  item.status = 'running';
111
143
  await persist();
112
- const result = await download(request, { reporter: itemReporter, signal, adaptiveState, skipCacheCleanup: true, onEntry: async entry => {
144
+ const result = await download(request, { reporter: itemReporter, signal, adaptiveState, skipCacheCleanup: true,
145
+ ...(privateRoot ? { localRoot: privateRoot } : {}), onEntry: async entry => {
113
146
  await captureFiles(entry.files);
114
147
  item.entries.push(entry);
115
148
  await persist();
@@ -132,9 +165,10 @@ export async function runJob(options, { download, reporter, signal, openFile, st
132
165
  item.status = signal?.aborted ? 'cancelled' : 'failed';
133
166
  item.error = readableError(error);
134
167
  if (!signal?.aborted) failed++;
135
- item.files = item.entries.flatMap(entry => entry.files || []);
168
+ item.files = [...new Set([...item.entries.flatMap(entry => entry.files || []), ...(error.files || [])])];
136
169
  if (options.json) stdout.write(`${JSON.stringify({ url: request.url, status: item.status, profile: request.profile || null, error: item.error, files: item.files, ...(runId ? { runId } : {}) })}\n`);
137
- else stderr.write(styleText(stderr, `veo: ${cleanText(request.url)}: ${item.error}`, 'error', options.color !== false) + '\n');
170
+ else stderr.write(styleText(stderr, terminalText(stderr, `veo: ${item.error} (${request.url})`), 'error', options.color !== false) + '\n');
171
+ if (error.verificationFailed && !options.json) for (const file of item.files) stderr.write(`Saved file retained: ${cleanText(file)}\n`);
138
172
  }
139
173
  if (recordStats) {
140
174
  try {
@@ -156,7 +190,10 @@ export async function runJob(options, { download, reporter, signal, openFile, st
156
190
  await persist();
157
191
  totals.saved += saved; totals.skipped += skipped; totals.failed += failed;
158
192
  } finally { release(); if (activeTargets.get(targetKey) === current) activeTargets.delete(targetKey); }
159
- }, { signal }).catch(error => { if (!signal?.aborted) throw error; });
193
+ }, { signal }).catch(error => { if (!signal?.aborted) throw error; });
194
+ } finally {
195
+ if (privateRoot) await rm(privateRoot, { recursive: true, force: true });
196
+ }
160
197
  const { saved, skipped, failed } = totals;
161
198
  if (runId) {
162
199
  try {
@@ -175,7 +212,7 @@ export async function runJob(options, { download, reporter, signal, openFile, st
175
212
  }
176
213
  if (Object.keys(totals).length) stderr.write(styleText(stderr, formatTimings(totals), 'muted', options.color !== false && !options.json) + '\n');
177
214
  }
178
- if (unfinished) stderr.write(`Retry failed/unfinished downloads: veo --retry-failed "${file}"\n`);
215
+ if (unfinished && !options.incognito) stderr.write(`Retry failed/unfinished downloads: veo --retry-failed ${runId || `"${file}"`}\n`);
179
216
  if (unfinished) reporter.fail(Boolean(signal?.aborted)); else reporter.complete();
180
217
  return signal?.aborted ? 130 : unfinished ? 1 : 0;
181
218
  }
package/src/naming.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import { lstat, mkdir } from 'node:fs/promises';
3
+ import { randomBytes } from 'node:crypto';
3
4
  import { sanitizeTitle } from './utils.js';
4
5
 
5
6
  const FIELDS = new Set(['title', 'id', 'channel', 'year', 'playlist', 'index']);
@@ -17,6 +18,9 @@ export function validateTemplate(template, { folders = false } = {}) {
17
18
  }
18
19
 
19
20
  export function mediaDestination(options, metadata, fallbackTitle) {
21
+ if (options.neutralFilename) {
22
+ return { directory: path.resolve(options.output), title: `video-${randomBytes(6).toString('hex')}` };
23
+ }
20
24
  const fields = {
21
25
  title: metadata.title || metadata.id || 'video', id: metadata.id || 'unknown',
22
26
  channel: metadata.channel || metadata.uploader || 'Unknown channel',
package/src/output.js CHANGED
@@ -1,61 +1,78 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
- import { styleText } from './progress.js';
3
-
4
- const settings = new AsyncLocalStorage();
5
- export const withOutputSettings = (enabled, work) => settings.run({ enabled }, work);
6
-
7
- export function outputOptions(args) {
8
- let profile, color;
9
- const remaining = [];
10
- for (let i = 0; i < args.length; i++) {
11
- const arg = args[i];
12
- if (arg === '--') { remaining.push(...args.slice(i)); break; }
13
- if (arg === '--profile' || arg.startsWith('--profile=')) {
14
- profile = arg === '--profile' ? args[++i] : arg.slice(10);
15
- if (!profile || profile.startsWith('--')) throw new Error('--profile requires a profile name.');
16
- } else {
17
- if (arg === '--color') color = true;
18
- if (arg === '--no-color') color = false;
19
- remaining.push(arg);
20
- }
21
- }
22
- return { profile, color, remaining };
23
- }
24
-
25
- export function formatOutput(text, stream, enabled = settings.getStore()?.enabled !== false) {
26
- return text.split(/(\r?\n)/).map(line => {
27
- if (!line.trim() || /\x1b/.test(line)) return line;
28
- const value = line.trim();
29
- let role = 'muted';
30
- if (/^(?:veo (?:stats|history|runs|stop|doctor|flush|update|backend|alias|uninstall)\b|veo \d[^ ]* doctor|ID\s+PID\s+STATE|Usage:|Options:|Commands:|Examples:|\d+\. )/.test(value)) role = 'title';
31
- if (/^(?:\[?OK\]?\s|Saved:|Flushed:|Stopped\b|Removed\b|Config OK:|Statistics reset|Managed tools are ready)|\bis up to date\b|\bupdated to\b|\binstalled and will be used\b/i.test(value)) role = 'success';
32
- if (/^(?:\[?FAIL\]?\s|Error:|veo: (?!note:))|Status:\s*(?:failed|cancelled)/i.test(value)) role = 'error';
33
- if (/Status:\s*saved/.test(value)) role = 'success';
34
- if (/^(?:Videos saved|Audio saved|Download time):/.test(value)) role = 'title';
35
- if (/^Total failures:\s*[1-9]/.test(value)) role = 'error';
36
- if (/^[1-9]\d* problems? found/.test(value)) role = 'error';
37
- if (/^No problems found/.test(value)) role = 'success';
38
- if (/^Config reset:/.test(value)) role = 'success';
39
- if (/^Summary:/.test(value)) role = /\b[1-9]\d* failed\b|cancelled/.test(value) ? 'error' : 'success';
40
- return styleText(stream, line, role, enabled);
41
- }).join('');
42
- }
43
-
44
- // Wrap only application-owned prose; no global stream monkey-patching.
45
- export function outputStream(stream, { enabled = settings.getStore()?.enabled !== false, plain = false } = {}) {
46
- if (plain || !enabled || !stream.isTTY) return stream;
47
- return {
48
- isTTY: stream.isTTY,
49
- get columns() { return stream.columns; },
50
- write(chunk, ...args) {
51
- if (typeof chunk !== 'string') return stream.write(chunk, ...args);
52
- return stream.write(formatOutput(chunk, stream, enabled), ...args);
53
- },
54
- };
55
- }
56
-
57
- export function commandOutput(args, ...streams) {
58
- const enabled = (outputOptions(args).color ?? settings.getStore()?.enabled) !== false;
59
- const plain = args.includes('--json');
60
- return [args.filter(arg => arg !== '--no-color' && arg !== '--color'), ...streams.map(stream => outputStream(stream, { enabled, plain }))];
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { styleText, terminalText, terminalTitle } from './progress.js';
3
+ import { linkOutputPaths } from './path-links.js';
4
+ import { terminalColumns } from './terminal-size.js';
5
+
6
+ const settings = new AsyncLocalStorage();
7
+ export const withOutputSettings = (enabled, work) => settings.run({ enabled }, work);
8
+
9
+ export function outputOptions(args) {
10
+ let profile, color;
11
+ const remaining = [];
12
+ for (let i = 0; i < args.length; i++) {
13
+ const arg = args[i];
14
+ if (arg === '--') { remaining.push(...args.slice(i)); break; }
15
+ if (arg === '--profile' || arg.startsWith('--profile=')) {
16
+ profile = arg === '--profile' ? args[++i] : arg.slice(10);
17
+ if (!profile || profile.startsWith('--')) throw new Error('--profile requires a profile name.');
18
+ } else {
19
+ if (arg === '--color') color = true;
20
+ if (arg === '--no-color') color = false;
21
+ remaining.push(arg);
22
+ }
23
+ }
24
+ return { profile, color, remaining };
25
+ }
26
+
27
+ export function formatOutput(text, stream, enabled = settings.getStore()?.enabled !== false) {
28
+ return text.split(/(\r?\n)/).map(line => {
29
+ if (!line.trim() || /\x1b/.test(line)) return line;
30
+ const value = line.trim();
31
+ const original = line;
32
+ // Limit display values, keeping help, JSON/config text and runnable commands intact.
33
+ if (stream.isTTY) {
34
+ const indent = line.match(/^\s*/)[0];
35
+ const available = { isTTY: true, columns: Math.max(2, terminalColumns(stream) - indent.length) };
36
+ if (/^\d+\. /.test(value)) line = terminalTitle(available, value).split('\n').map(part => indent + part).join('\n');
37
+ else if (/^(?:URL[s]?:|Saved:|Would save:|File:|Missing:|Output:|Job:|Error:|Profile:|Media:|Format:|Streams:|Source:|Title:|Command directory:|Config OK:|veo:|\[?(?:OK|FAIL)\]?\s|[0-9a-z]{6}\s+\d+\s|https?:\/\/)/.test(value)
38
+ || /^\s{6,}\S/.test(line)) line = indent + terminalText(available, value);
39
+ }
40
+ let role = 'muted';
41
+ if (/^(?:veo (?:stats|history|runs|stop|doctor|flush|update|backend|alias|uninstall)\b|veo \d[^ ]* doctor|ID\s+PID\s+STATE|Usage:|Options:|Commands:|Examples:|\d+\. )/.test(value)) role = 'title';
42
+ if (/^(?:\[?OK\]?\s|Saved:|Flushed:|Stopped\b|Removed\b|Config OK:|Statistics reset|Managed tools are ready)|\bis up to date\b|\bupdated to\b|\binstalled and will be used\b/i.test(value)) role = 'success';
43
+ if (/^(?:\[?FAIL\]?\s|Error:|veo: (?!note:))|Status:\s*(?:failed|cancelled)/i.test(value)) role = 'error';
44
+ if (/Status:\s*saved/.test(value)) role = 'success';
45
+ if (/^(?:Videos saved|Audio saved|Download time):/.test(value)) role = 'title';
46
+ if (/^Total failures:\s*[1-9]/.test(value)) role = 'error';
47
+ if (/^[1-9]\d* problems? found/.test(value)) role = 'error';
48
+ if (/^No problems found/.test(value)) role = 'success';
49
+ if (/^Config reset:/.test(value)) role = 'success';
50
+ if (/^Summary:/.test(value)) role = /\b[1-9]\d* failed\b|cancelled/.test(value) ? 'error' : 'success';
51
+ return styleText(stream, linkOutputPaths(stream, original, line), role, enabled);
52
+ }).join('');
53
+ }
54
+
55
+ // Wrap only application-owned prose; no global stream monkey-patching.
56
+ export function outputStream(stream, { enabled = settings.getStore()?.enabled !== false, plain = false } = {}) {
57
+ if (plain || !stream.isTTY) return stream;
58
+ return {
59
+ isTTY: stream.isTTY,
60
+ get columns() { return terminalColumns(stream); },
61
+ on(event, listener) { stream.on?.(event, listener); },
62
+ removeListener(event, listener) { stream.removeListener?.(event, listener); },
63
+ write(chunk, ...args) {
64
+ if (typeof chunk !== 'string') return stream.write(chunk, ...args);
65
+ // Live redraw frames already carry erase/cursor sequences; prose fitting
66
+ // and role styling must not touch them, otherwise the invisible styling
67
+ // bytes push raw lines past the terminal width.
68
+ if (chunk.includes('\x1b')) return stream.write(chunk, ...args);
69
+ return stream.write(formatOutput(chunk, stream, enabled), ...args);
70
+ },
71
+ };
72
+ }
73
+
74
+ export function commandOutput(args, ...streams) {
75
+ const enabled = (outputOptions(args).color ?? settings.getStore()?.enabled) !== false;
76
+ const plain = args.includes('--json');
77
+ return [args.filter(arg => arg !== '--no-color' && arg !== '--color'), ...streams.map(stream => outputStream(stream, { enabled, plain }))];
61
78
  }
@@ -0,0 +1,53 @@
1
+ import path from 'node:path';
2
+ import { statSync } from 'node:fs';
3
+ import { pathToFileURL } from 'node:url';
4
+
5
+ export function supportsPathLinks(stream, env = process.env) {
6
+ return Boolean(stream.isTTY && env.TERM !== 'dumb' &&
7
+ (env.WT_SESSION || env.TERM_PROGRAM === 'iTerm.app' || env.TERM_PROGRAM === 'WezTerm' ||
8
+ env.TERM_PROGRAM === 'vscode' || env.KITTY_WINDOW_ID || Number(env.VTE_VERSION) >= 5000));
9
+ }
10
+
11
+ // File links target their containing folder so clicking does not play the media.
12
+ export function folderLink(stream, target, label = target, env = process.env) {
13
+ const safeLabel = String(label).replace(/[\x00-\x1f\x7f-\x9f]/g, ' ');
14
+ if (!supportsPathLinks(stream, env)) return safeLabel;
15
+ try {
16
+ const absolute = path.resolve(target);
17
+ const folder = statSync(absolute).isDirectory() ? absolute : path.dirname(absolute);
18
+ const url = pathToFileURL(folder + path.sep).href;
19
+ return `\x1b]8;;${url}\x1b\\${safeLabel}\x1b]8;;\x1b\\`;
20
+ } catch { return safeLabel; }
21
+ }
22
+
23
+ // Recognize absolute paths in application prose before display truncation.
24
+ // Resolve the longest existing candidate so spaces and parentheses in names survive.
25
+ export function linkOutputPaths(stream, original, displayed = original, env = process.env) {
26
+ if (!supportsPathLinks(stream, env) || /\x1b/.test(original) ||
27
+ /^\s*(?:["{[]|Retry:|Usage:|Manual command:|Run with|Stop:|Cleanup:)/.test(original)) return displayed;
28
+ const matches = [...original.matchAll(/(?:^|[\s("'])([A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/(?!\/))/g)];
29
+ for (const match of matches.reverse()) {
30
+ const start = match.index + match[0].length - match[1].length;
31
+ const rest = original.slice(start);
32
+ const ends = [rest.length];
33
+ for (let i = rest.length - 1; i > 0; i--) {
34
+ if (/[\s)"',;:.]/.test(rest[i])) ends.push(i);
35
+ }
36
+ let target;
37
+ for (const end of ends) {
38
+ const candidate = rest.slice(0, end);
39
+ try { statSync(candidate); target = candidate; break; } catch { /* try a prose boundary */ }
40
+ }
41
+ if (!target) continue;
42
+ // Truncation has already happened; keep the complete destination in the URL.
43
+ if (displayed.slice(start, start + target.length) === target) {
44
+ displayed = displayed.slice(0, start) + folderLink(stream, target, target, env) + displayed.slice(start + target.length);
45
+ } else {
46
+ const visible = displayed.slice(start);
47
+ if (visible.endsWith('…') && target.startsWith(visible.slice(0, -1))) {
48
+ displayed = displayed.slice(0, start) + folderLink(stream, target, visible, env);
49
+ }
50
+ }
51
+ }
52
+ return displayed;
53
+ }