@bhanulabs/wacli 0.0.0-stage → 1.0.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/src/media.js ADDED
@@ -0,0 +1,441 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { existsSync, mkdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { HOME, logger } from './config.js';
7
+
8
+ const MB = 1024 * 1024;
9
+ const MAX_MEDIA = 100 * MB; // WhatsApp's limit for photos/videos/audio
10
+ const MAX_DOCUMENT = 2048 * MB; // and for documents
11
+
12
+ const MIME = {
13
+ jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', gif: 'image/gif',
14
+ bmp: 'image/bmp', tif: 'image/tiff', tiff: 'image/tiff', heic: 'image/heic', heif: 'image/heif', avif: 'image/avif',
15
+ mp4: 'video/mp4', mov: 'video/quicktime', '3gp': 'video/3gpp', mkv: 'video/x-matroska', webm: 'video/webm', avi: 'video/x-msvideo',
16
+ mp3: 'audio/mpeg', m4a: 'audio/mp4', aac: 'audio/aac', ogg: 'audio/ogg', opus: 'audio/ogg', wav: 'audio/wav', amr: 'audio/amr',
17
+ pdf: 'application/pdf', txt: 'text/plain', csv: 'text/csv', zip: 'application/zip', json: 'application/json',
18
+ doc: 'application/msword', docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
19
+ xls: 'application/vnd.ms-excel', xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
20
+ ppt: 'application/vnd.ms-powerpoint', pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
21
+ };
22
+ // Images we convert to JPEG and send as a photo. GIF stays a file so it keeps its animation.
23
+ const PHOTO = new Set(['jpg', 'jpeg', 'png', 'webp', 'bmp', 'tif', 'tiff', 'avif', 'heic', 'heif']);
24
+ // WhatsApp only plays these inline; other video formats go as files.
25
+ const VIDEO = new Set(['mp4', '3gp']);
26
+ const AUDIO = new Set(['mp3', 'm4a', 'aac', 'ogg', 'opus', 'amr']);
27
+
28
+ const ext = (file) => path.extname(file).slice(1).toLowerCase();
29
+
30
+ export function kindOf(file) {
31
+ const e = ext(file);
32
+ if (PHOTO.has(e)) return 'photo';
33
+ if (VIDEO.has(e)) return 'video';
34
+ if (AUDIO.has(e)) return 'audio';
35
+ return 'file';
36
+ }
37
+
38
+ export const KIND_ICON = { photo: '📷', video: '🎥', audio: '🎤', file: '📄', gif: '🎞️' };
39
+
40
+ export function formatSize(bytes) {
41
+ if (bytes >= MB) return `${(bytes / MB).toFixed(bytes >= 10 * MB ? 0 : 1)} MB`;
42
+ return `${Math.max(1, Math.round(bytes / 1024))} KB`;
43
+ }
44
+
45
+ function existingFile(p) {
46
+ try {
47
+ const st = statSync(p);
48
+ return st.isFile() ? { path: path.resolve(p), size: st.size } : null;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ /** Turns one pasted path (in any shell's quoting style) into a local path. */
55
+ function normalizePath(p) {
56
+ p = p.trim();
57
+ if (/^file:\/\//i.test(p)) {
58
+ try { return fileURLToPath(p); } catch { return p; }
59
+ }
60
+ if (p === '~' || p.startsWith('~/') || p.startsWith('~\\')) p = path.join(os.homedir(), p.slice(1));
61
+ if (process.platform === 'win32') {
62
+ // Git Bash / MSYS style /c/Users/... and WSL style /mnt/c/Users/...
63
+ const m = /^\/(?:mnt\/)?([a-z])\/(.*)$/i.exec(p);
64
+ if (m) p = `${m[1].toUpperCase()}:/${m[2]}`;
65
+ }
66
+ return p;
67
+ }
68
+
69
+ /**
70
+ * Dropping files onto a terminal "types" their paths. Returns the files if `text` is
71
+ * nothing but one or more paths to existing files, otherwise null (so it's normal text).
72
+ */
73
+ export function parseDroppedFiles(text) {
74
+ text = String(text || '').trim();
75
+ if (!text || text.length > 10000) return null;
76
+
77
+ // Some terminals don't quote a single path with spaces in it.
78
+ const whole = existingFile(normalizePath(text.replace(/^(["'])(.*)\1$/s, '$2')));
79
+ if (whole) return [whole];
80
+
81
+ const files = [];
82
+ const re = process.platform === 'win32'
83
+ ? /"([^"]+)"|'([^']+)'|(\S+)/g
84
+ : /"([^"]+)"|'([^']+)'|((?:\\.|\S)+)/g; // macOS/Linux escape spaces as "\ "
85
+ for (const m of text.matchAll(re)) {
86
+ let p = m[1] ?? m[2] ?? m[3];
87
+ if (m[3] && process.platform !== 'win32') p = p.replace(/\\(.)/g, '$1');
88
+ const f = existingFile(normalizePath(p));
89
+ if (!f) return null;
90
+ files.push(f);
91
+ }
92
+ return files.length ? files : null;
93
+ }
94
+
95
+ /** Does this look like it could be a path (cheap check before touching the disk)? */
96
+ export function looksLikePath(text) {
97
+ return /^\s*(["']?([a-z]:[\\/]|[\\/]|~[\\/]|\.{1,2}[\\/]|file:\/\/))/i.test(text);
98
+ }
99
+
100
+ /** Describes a file for the attachment bar. Throws if it can't be sent. */
101
+ export function describe(file) {
102
+ const kind = file.kind || kindOf(file.path);
103
+ const name = file.name || path.basename(file.path);
104
+ const limit = kind === 'file' ? MAX_DOCUMENT : MAX_MEDIA;
105
+ if (file.size > limit) throw new Error(`${name} is too big (${formatSize(file.size)}, max ${formatSize(limit)})`);
106
+ if (file.size === 0) throw new Error(`${name} is empty`);
107
+ return { ...file, name, kind };
108
+ }
109
+
110
+ // ---------------- clipboard (Alt+V): GIFs from Win + . , screenshots, copied files ----------------
111
+
112
+ export const TMP_DIR = path.join(HOME, 'tmp');
113
+
114
+ /** Files fetched from the clipboard/web are kept only until sent; clear leftovers from last time. */
115
+ export function cleanTmp() {
116
+ rmSync(TMP_DIR, { recursive: true, force: true });
117
+ }
118
+
119
+ function tmpFile(ext) {
120
+ mkdirSync(TMP_DIR, { recursive: true });
121
+ return path.join(TMP_DIR, `${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`);
122
+ }
123
+
124
+ // Reads the Windows clipboard: copied files, an <img> in copied HTML (the emoji panel's GIFs
125
+ // arrive like this), or a bitmap (screenshots). Prints one line of JSON.
126
+ const CLIPBOARD_PS = `
127
+ Add-Type -AssemblyName System.Windows.Forms, System.Drawing
128
+ $d = [System.Windows.Forms.Clipboard]::GetDataObject()
129
+ $r = @{}
130
+ if ($d) {
131
+ if ($d.GetDataPresent('FileDrop')) { $r.files = @($d.GetData('FileDrop')) }
132
+ if ($d.GetDataPresent('HTML Format')) {
133
+ $h = [string]$d.GetData('HTML Format')
134
+ if ($h -match '<img[^>]+src="([^"]+)"') { $r.imgSrc = $matches[1] }
135
+ }
136
+ if ($d.GetDataPresent('Bitmap')) {
137
+ $img = [System.Windows.Forms.Clipboard]::GetImage()
138
+ if ($img) { $img.Save($env:WACLI_CLIP_OUT, [System.Drawing.Imaging.ImageFormat]::Png); $r.image = $env:WACLI_CLIP_OUT }
139
+ }
140
+ if ($d.GetDataPresent('Text')) { $r.text = [string]$d.GetData('Text') }
141
+ }
142
+ $r | ConvertTo-Json -Compress
143
+ `;
144
+
145
+ /** Runs a program and resolves to its stdout as a Buffer. */
146
+ function runProgram(cmd, args, { env } = {}) {
147
+ return new Promise((resolve, reject) => {
148
+ execFile(cmd, args, { encoding: 'buffer', maxBuffer: 128 * MB, timeout: 15000, windowsHide: true, env: env || process.env },
149
+ (err, stdout, stderr) => {
150
+ if (err) reject(Object.assign(err, { stderr: String(stderr || '') }));
151
+ else resolve(stdout);
152
+ });
153
+ });
154
+ }
155
+
156
+ /** What the clipboard readers use; tests swap these out. */
157
+ export const clipboardSystem = { run: runProgram, platform: process.platform, env: process.env };
158
+
159
+ /**
160
+ * Every reader returns the same shape:
161
+ * { files?: [path], imgSrc?: url from copied HTML, image?: temp file with a copied image, text?: string }
162
+ */
163
+ async function readWindowsClipboard() {
164
+ const out = tmpFile('png');
165
+ let stdout;
166
+ try {
167
+ stdout = await clipboardSystem.run('powershell.exe', ['-NoProfile', '-NonInteractive', '-STA', '-Command', CLIPBOARD_PS],
168
+ { env: { ...clipboardSystem.env, WACLI_CLIP_OUT: out } });
169
+ } catch (err) {
170
+ throw new Error(`Couldn't read the clipboard: ${err.message}`);
171
+ }
172
+ try {
173
+ return JSON.parse(stdout.toString('utf8').trim() || '{}');
174
+ } catch {
175
+ return {};
176
+ }
177
+ }
178
+
179
+ // macOS: JavaScript for Automation (built into every Mac via osascript) talking to NSPasteboard.
180
+ // Writes a copied image to argv[0] and prints JSON.
181
+ const CLIPBOARD_JXA = `
182
+ ObjC.import('AppKit');
183
+ function run(argv) {
184
+ var out = argv[0];
185
+ var pb = $.NSPasteboard.generalPasteboard;
186
+ var r = {};
187
+ var str = function (type) {
188
+ var s = pb.stringForType(type);
189
+ return (s && !s.isNil()) ? ObjC.unwrap(s) : null;
190
+ };
191
+ try {
192
+ var urls = pb.readObjectsForClassesOptions($([$.NSURL]), $({}));
193
+ if (urls && !urls.isNil() && urls.count > 0) {
194
+ var files = [];
195
+ for (var i = 0; i < urls.count; i++) {
196
+ var u = urls.objectAtIndex(i);
197
+ if (u.isFileURL) files.push(ObjC.unwrap(u.path));
198
+ }
199
+ if (files.length) r.files = files;
200
+ }
201
+ } catch (e) {}
202
+ try {
203
+ var html = str('public.html');
204
+ if (html) {
205
+ var m = /<img[^>]+src="([^"]+)"/i.exec(html);
206
+ if (m) r.imgSrc = m[1];
207
+ }
208
+ } catch (e) {}
209
+ try {
210
+ var types = [['public.png', 'png'], ['public.jpeg', 'jpg'], ['public.tiff', 'tiff']];
211
+ for (var t = 0; t < types.length; t++) {
212
+ var data = pb.dataForType(types[t][0]);
213
+ if (data && !data.isNil() && data.length > 0) {
214
+ var file = out + '.' + types[t][1];
215
+ if (data.writeToFileAtomically(file, true)) r.image = file;
216
+ break;
217
+ }
218
+ }
219
+ } catch (e) {}
220
+ try {
221
+ var text = str('public.utf8-plain-text');
222
+ if (text) r.text = text;
223
+ } catch (e) {}
224
+ return JSON.stringify(r);
225
+ }
226
+ `;
227
+
228
+ async function readMacClipboard() {
229
+ const out = tmpFile('clip').replace(/\.clip$/, ''); // the script adds .png / .jpg / .tiff
230
+ let stdout;
231
+ try {
232
+ stdout = await clipboardSystem.run('osascript', ['-l', 'JavaScript', '-e', CLIPBOARD_JXA, out]);
233
+ } catch (err) {
234
+ throw new Error(`Couldn't read the clipboard: ${(err.stderr || err.message).trim()}`);
235
+ }
236
+ try {
237
+ return JSON.parse(stdout.toString('utf8').trim() || '{}');
238
+ } catch {
239
+ return {};
240
+ }
241
+ }
242
+
243
+ // Linux: wl-paste (Wayland, package "wl-clipboard") or xclip (X11).
244
+ const IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/bmp', 'image/tiff', 'image/gif'];
245
+ const IMAGE_EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/bmp': 'bmp', 'image/tiff': 'tiff', 'image/gif': 'gif' };
246
+
247
+ function linuxTools() {
248
+ const { env } = clipboardSystem;
249
+ const wl = {
250
+ name: 'wl-paste',
251
+ list: () => clipboardSystem.run('wl-paste', ['--list-types']),
252
+ get: (type) => clipboardSystem.run('wl-paste', ['--no-newline', '--type', type]),
253
+ };
254
+ const x = {
255
+ name: 'xclip',
256
+ list: () => clipboardSystem.run('xclip', ['-selection', 'clipboard', '-t', 'TARGETS', '-o']),
257
+ get: (type) => clipboardSystem.run('xclip', ['-selection', 'clipboard', '-t', type, '-o']),
258
+ };
259
+ const tools = [];
260
+ if (env.WAYLAND_DISPLAY) tools.push(wl);
261
+ if (env.DISPLAY) tools.push(x);
262
+ if (!tools.length) tools.push(wl, x); // unknown session: try both
263
+ return tools;
264
+ }
265
+
266
+ async function readLinuxClipboard() {
267
+ let tool = null;
268
+ let types = [];
269
+ let missing = 0;
270
+ for (const t of linuxTools()) {
271
+ try {
272
+ types = (await t.list()).toString('utf8').split('\n').map((s) => s.trim()).filter(Boolean);
273
+ tool = t;
274
+ break;
275
+ } catch (err) {
276
+ if (err.code === 'ENOENT') { missing++; continue; }
277
+ // The tool ran but the clipboard is empty (both tools exit with an error then).
278
+ tool = t;
279
+ types = [];
280
+ break;
281
+ }
282
+ }
283
+ if (!tool) {
284
+ throw new Error(missing
285
+ ? 'To paste from the clipboard, install wl-clipboard (Wayland) or xclip (X11), e.g. sudo apt install wl-clipboard xclip'
286
+ : "Couldn't read the clipboard");
287
+ }
288
+
289
+ const r = {};
290
+ const get = async (type) => { try { return await tool.get(type); } catch { return null; } };
291
+ const has = (type) => types.includes(type);
292
+
293
+ // Files copied in a file manager
294
+ const uriType = has('text/uri-list') ? 'text/uri-list' : has('x-special/gnome-copied-files') ? 'x-special/gnome-copied-files' : null;
295
+ if (uriType) {
296
+ const list = (await get(uriType))?.toString('utf8') || '';
297
+ const files = list.split(/\r?\n/).map((s) => s.trim())
298
+ .filter((s) => /^file:\/\//i.test(s))
299
+ .map((s) => { try { return fileURLToPath(s); } catch { return null; } })
300
+ .filter(Boolean);
301
+ if (files.length) r.files = files;
302
+ }
303
+ if (has('text/html')) {
304
+ const html = (await get('text/html'))?.toString('utf8') || '';
305
+ const m = /<img[^>]+src="([^"]+)"/i.exec(html);
306
+ if (m) r.imgSrc = m[1];
307
+ }
308
+ const imageType = IMAGE_TYPES.find(has) || types.find((t) => t.startsWith('image/'));
309
+ if (imageType) {
310
+ const data = await get(imageType);
311
+ if (data?.length) {
312
+ const file = tmpFile(IMAGE_EXT[imageType] || 'png');
313
+ writeFileSync(file, data);
314
+ r.image = file;
315
+ }
316
+ }
317
+ const textType = ['text/plain;charset=utf-8', 'UTF8_STRING', 'text/plain', 'STRING'].find(has);
318
+ if (textType) {
319
+ const text = (await get(textType))?.toString('utf8');
320
+ if (text) r.text = text;
321
+ }
322
+ return r;
323
+ }
324
+
325
+ const decodeHtml = (s) => s.replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>');
326
+
327
+ async function download(url, ext, wantType) {
328
+ const res = await fetch(url, { signal: AbortSignal.timeout(30000), redirect: 'follow' });
329
+ if (!res.ok) throw new Error(`download failed (HTTP ${res.status})`);
330
+ const type = res.headers.get('content-type') || '';
331
+ if (wantType && !type.startsWith(wantType)) throw new Error(`expected ${wantType}, got ${type || 'unknown'}`);
332
+ const buf = Buffer.from(await res.arrayBuffer());
333
+ if (buf.length > MAX_MEDIA) throw new Error('too big');
334
+ const file = tmpFile(ext);
335
+ writeFileSync(file, buf);
336
+ return { path: file, size: buf.length };
337
+ }
338
+
339
+ /**
340
+ * A GIF from GIPHY. WhatsApp's "GIFs" are really short looping MP4s, and GIPHY serves an
341
+ * MP4 next to every GIF, so we fetch that and send it with gifPlayback (no conversion needed).
342
+ */
343
+ async function fetchGiphy(url) {
344
+ const id = /\/media\/(?:[^/]+\/)?([A-Za-z0-9]+)\/[^/]+\.(?:gif|webp|mp4)/.exec(url)?.[1]
345
+ || /giphy\.com\/(?:gifs|stickers)\/(?:[^/?#]*-)?([A-Za-z0-9]+)\/?(?:[?#].*)?$/.exec(url)?.[1]; // a giphy.com page link
346
+ const candidates = [url.replace(/\/[^/]+\.(gif|webp)(\?.*)?$/i, '/giphy.mp4')];
347
+ if (id) candidates.push(`https://media.giphy.com/media/${id}/giphy.mp4`);
348
+ let lastErr;
349
+ for (const mp4 of candidates) {
350
+ try {
351
+ const f = await download(mp4, 'mp4', 'video/mp4');
352
+ return { ...f, kind: 'gif', name: 'GIF from GIPHY' };
353
+ } catch (err) {
354
+ lastErr = err;
355
+ }
356
+ }
357
+ throw new Error(`Couldn't get the GIF: ${lastErr?.message}`);
358
+ }
359
+
360
+ const isGiphy = (url) => /^https?:\/\/([a-z0-9-]+\.)*giphy\.com\//i.test(url);
361
+
362
+ /**
363
+ * What Alt+V should attach: a list of files ready for describe(), or throws a message to show.
364
+ * Works on Windows (PowerShell), macOS (osascript) and Linux (wl-paste or xclip).
365
+ */
366
+ export async function filesFromClipboard() {
367
+ const { platform } = clipboardSystem;
368
+ const clip = platform === 'win32' ? await readWindowsClipboard()
369
+ : platform === 'darwin' ? await readMacClipboard()
370
+ : await readLinuxClipboard();
371
+ const keepImage = (clip.image && existsSync(clip.image)) ? clip.image : null;
372
+ const dropImage = () => { if (keepImage) rmSync(keepImage, { force: true }); };
373
+
374
+ // 1. Copied files (Explorer, Finder, a Linux file manager)
375
+ if (clip.files?.length) {
376
+ dropImage();
377
+ const files = clip.files.map((p) => { try { const st = statSync(p); return st.isFile() ? { path: p, size: st.size } : null; } catch { return null; } }).filter(Boolean);
378
+ if (files.length) return files;
379
+ }
380
+
381
+ const src = clip.imgSrc ? decodeHtml(clip.imgSrc) : null;
382
+ // 2. A GIF picked in the emoji panel (Win + .) arrives as HTML with a GIPHY link
383
+ if (src && isGiphy(src)) {
384
+ dropImage();
385
+ return [await fetchGiphy(src)];
386
+ }
387
+ // 3. An image: screenshots (Win + Shift + S, Cmd + Ctrl + Shift + 4, PrtScn), "Copy image" in a browser
388
+ if (keepImage) {
389
+ return [{ path: keepImage, size: statSync(keepImage).size, kind: 'photo', name: `Pasted image.${ext(keepImage) || 'png'}` }];
390
+ }
391
+ // 4. An image link without a bitmap
392
+ if (src && /^https?:\/\//i.test(src)) {
393
+ const e = ext(new URL(src).pathname) || 'jpg';
394
+ if (e === 'gif') throw new Error('Only GIFs from GIPHY can be sent as GIFs. Save it and drag it in to send it as a file.');
395
+ const f = await download(src, PHOTO.has(e) ? e : 'jpg', 'image/');
396
+ return [{ ...f, kind: 'photo', name: 'Pasted image' }];
397
+ }
398
+ // 5. Copied text that is a GIPHY link or a file path
399
+ const text = clip.text?.trim();
400
+ if (text && isGiphy(text) && !/\s/.test(text)) return [await fetchGiphy(text)];
401
+ if (text) {
402
+ const files = parseDroppedFiles(text);
403
+ if (files) return files;
404
+ }
405
+ throw new Error('No image, GIF or file on the clipboard');
406
+ }
407
+
408
+ /** Baileys message content for a file. The caption goes with photos, videos and files. */
409
+ export async function buildContent(att, caption) {
410
+ const e = ext(att.path);
411
+ const mimetype = MIME[e] || 'application/octet-stream';
412
+ const asFile = () => ({ document: { url: att.path }, mimetype, fileName: att.name, ...(caption && { caption }) });
413
+
414
+ if (att.kind === 'gif') {
415
+ // Plays and loops like a GIF on the phone.
416
+ return { video: { url: att.path }, gifPlayback: true, mimetype: 'video/mp4', ...(caption && { caption }) };
417
+ }
418
+ if (att.kind === 'photo') {
419
+ try {
420
+ // Like the phone app: fix rotation, cap the size, send as JPEG.
421
+ const sharp = (await import('sharp')).default;
422
+ const image = await sharp(att.path, { failOn: 'none' })
423
+ .rotate()
424
+ .resize({ width: 2560, height: 2560, fit: 'inside', withoutEnlargement: true })
425
+ .flatten({ background: '#ffffff' })
426
+ .jpeg({ quality: 85 })
427
+ .toBuffer();
428
+ return { image, mimetype: 'image/jpeg', ...(caption && { caption }) };
429
+ } catch (err) {
430
+ logger.warn({ err, file: att.path }, 'could not convert image, sending as a file');
431
+ return asFile();
432
+ }
433
+ }
434
+ if (att.kind === 'video' && att.size <= MAX_MEDIA) {
435
+ return { video: { url: att.path }, mimetype, ...(caption && { caption }) };
436
+ }
437
+ if (att.kind === 'audio' && att.size <= MAX_MEDIA) {
438
+ return { audio: { url: att.path }, mimetype: e === 'opus' ? 'audio/ogg; codecs=opus' : mimetype };
439
+ }
440
+ return asFile();
441
+ }
package/src/sixel.js ADDED
@@ -0,0 +1,184 @@
1
+ import { inflateSync } from 'node:zlib';
2
+ import { logger } from './config.js';
3
+
4
+ /**
5
+ * Inline photo previews with sixel graphics (Windows Terminal 1.22+, WezTerm, foot, mlterm, xterm -ti 340…).
6
+ *
7
+ * The terminal is asked once at startup whether it supports sixel (it lists "4" in its
8
+ * device attributes) and how many pixels a text cell has. Windows Terminal draws sixel
9
+ * images on a virtual 10x20 pixel cell whatever the font size, which is also the default here.
10
+ */
11
+ export const graphics = { sixel: false, cellW: 10, cellH: 20 };
12
+
13
+ /** Asks the terminal what it can do. Call before anything else reads stdin. */
14
+ export function detectGraphics({ enabled = true } = {}) {
15
+ const env = process.env.WACLI_IMAGES;
16
+ if (!enabled || env === '0' || !process.stdin.isTTY || !process.stdout.isTTY) return Promise.resolve();
17
+ return new Promise((resolve) => {
18
+ const { stdin, stdout } = process;
19
+ let reply = '';
20
+ const finish = () => {
21
+ clearTimeout(timer);
22
+ stdin.off('data', onData);
23
+ stdin.setRawMode(false);
24
+ stdin.pause();
25
+ const da = /\x1b\[\?([\d;]*)c/.exec(reply);
26
+ graphics.sixel = env === '1' || Boolean(da && da[1].split(';').includes('4'));
27
+ const cell = /\x1b\[6;(\d+);(\d+)t/.exec(reply);
28
+ if (cell && +cell[1] > 0 && +cell[2] > 0) { graphics.cellH = +cell[1]; graphics.cellW = +cell[2]; }
29
+ logger.info({ graphics, reply: JSON.stringify(reply) }, 'terminal graphics');
30
+ resolve();
31
+ };
32
+ const onData = (d) => {
33
+ reply += d.toString('latin1');
34
+ // Every terminal answers the device-attributes query, and it was asked last.
35
+ if (/\x1b\[\?[\d;]*c/.test(reply)) finish();
36
+ };
37
+ const timer = setTimeout(finish, 700);
38
+ stdin.setRawMode(true);
39
+ stdin.on('data', onData);
40
+ stdin.resume();
41
+ stdout.write('\x1b[16t\x1b[c'); // cell size in pixels, then device attributes
42
+ });
43
+ }
44
+
45
+ // ---------------- making a preview ----------------
46
+
47
+ /**
48
+ * Scales a photo to fit `maxCols` x `maxRows` text cells and reduces it to a palette.
49
+ * Returns { cols, rows, w, h, pixels: Uint8Array of palette indexes, palette: [[r,g,b]] }.
50
+ */
51
+ export async function makePreview(file, maxCols, maxRows) {
52
+ const sharp = (await import('sharp')).default;
53
+ const { cellW, cellH } = graphics;
54
+ const png = await sharp(file, { failOn: 'none' })
55
+ .rotate()
56
+ .resize({ width: maxCols * cellW, height: maxRows * cellH, fit: 'inside', withoutEnlargement: true })
57
+ .flatten({ background: '#ffffff' })
58
+ .png({ palette: true, colors: 255, dither: 0.8, effort: 4 })
59
+ .toBuffer();
60
+ const img = decodeIndexedPng(png);
61
+ return { ...img, cols: Math.ceil(img.w / cellW), rows: Math.ceil(img.h / cellH) };
62
+ }
63
+
64
+ /** Size in cells a w x h photo will get, matching makePreview (for laying out before it's ready). */
65
+ export function previewCells(w, h, maxCols, maxRows) {
66
+ if (!w || !h) return null;
67
+ const { cellW, cellH } = graphics;
68
+ const s = Math.min(1, (maxCols * cellW) / w, (maxRows * cellH) / h);
69
+ return { cols: Math.ceil(Math.round(w * s) / cellW), rows: Math.ceil(Math.round(h * s) / cellH) };
70
+ }
71
+
72
+ /** Minimal PNG reader for the palette PNGs sharp writes (color type 3, no interlace). */
73
+ function decodeIndexedPng(buf) {
74
+ let pos = 8;
75
+ let w = 0, h = 0, depth = 8, type = 0, interlace = 0;
76
+ let palette = [];
77
+ const idat = [];
78
+ while (pos < buf.length) {
79
+ const len = buf.readUInt32BE(pos);
80
+ const kind = buf.toString('ascii', pos + 4, pos + 8);
81
+ const data = buf.subarray(pos + 8, pos + 8 + len);
82
+ if (kind === 'IHDR') {
83
+ w = data.readUInt32BE(0); h = data.readUInt32BE(4);
84
+ depth = data[8]; type = data[9]; interlace = data[12];
85
+ } else if (kind === 'PLTE') {
86
+ palette = [];
87
+ for (let i = 0; i + 2 < data.length; i += 3) palette.push([data[i], data[i + 1], data[i + 2]]);
88
+ } else if (kind === 'IDAT') idat.push(data);
89
+ else if (kind === 'IEND') break;
90
+ pos += 12 + len;
91
+ }
92
+ if (type !== 3 || interlace !== 0) throw new Error(`unexpected PNG (type ${type}, interlace ${interlace})`);
93
+
94
+ const raw = inflateSync(Buffer.concat(idat));
95
+ const stride = Math.ceil((w * depth) / 8);
96
+ const rows = Buffer.alloc(stride * h);
97
+ let prev = Buffer.alloc(stride);
98
+ for (let y = 0; y < h; y++) {
99
+ const filter = raw[y * (stride + 1)];
100
+ const line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1));
101
+ const out = rows.subarray(y * stride, (y + 1) * stride);
102
+ for (let i = 0; i < stride; i++) {
103
+ const a = i > 0 ? out[i - 1] : 0; // bytes per pixel is 1 for palette images
104
+ const b = prev[i];
105
+ const c = i > 0 ? prev[i - 1] : 0;
106
+ let v = line[i];
107
+ if (filter === 1) v += a;
108
+ else if (filter === 2) v += b;
109
+ else if (filter === 3) v += (a + b) >> 1;
110
+ else if (filter === 4) {
111
+ const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
112
+ v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
113
+ }
114
+ out[i] = v & 0xff;
115
+ }
116
+ prev = out;
117
+ }
118
+
119
+ const pixels = new Uint8Array(w * h);
120
+ const perByte = 8 / depth;
121
+ const mask = (1 << depth) - 1;
122
+ for (let y = 0; y < h; y++) {
123
+ for (let x = 0; x < w; x++) {
124
+ const byte = rows[y * stride + Math.floor(x / perByte)];
125
+ const shift = 8 - depth * ((x % perByte) + 1);
126
+ pixels[y * w + x] = (byte >> shift) & mask;
127
+ }
128
+ }
129
+ return { w, h, pixels, palette };
130
+ }
131
+
132
+ // ---------------- encoding ----------------
133
+
134
+ /**
135
+ * Sixel data for rows [fromRow, fromRow + rowCount) of text cells of a preview, so a photo
136
+ * that's partly scrolled out of view can still be drawn.
137
+ */
138
+ export function encodeSixel(img, fromRow = 0, rowCount = img.rows) {
139
+ const { w, pixels, palette } = img;
140
+ const y0 = Math.min(img.h, fromRow * graphics.cellH);
141
+ const y1 = Math.min(img.h, (fromRow + rowCount) * graphics.cellH);
142
+ const h = y1 - y0;
143
+ if (h <= 0) return '';
144
+
145
+ const used = new Set();
146
+ for (let i = y0 * w; i < y1 * w; i++) used.add(pixels[i]);
147
+ // P2=1: pixels we don't set stay as they are. "1;1;w;h = square pixels and the image size.
148
+ let out = `\x1bP0;1;0q"1;1;${w};${h}`;
149
+ for (const i of used) {
150
+ const [r, g, b] = palette[i] || [0, 0, 0];
151
+ out += `#${i};2;${Math.round((r * 100) / 255)};${Math.round((g * 100) / 255)};${Math.round((b * 100) / 255)}`;
152
+ }
153
+
154
+ for (let y = y0; y < y1; y += 6) {
155
+ const band = new Map(); // color -> six-pixel column bits across the row
156
+ const bandH = Math.min(6, y1 - y);
157
+ for (let dy = 0; dy < bandH; dy++) {
158
+ const rowStart = (y + dy) * w;
159
+ for (let x = 0; x < w; x++) {
160
+ const c = pixels[rowStart + x];
161
+ let bits = band.get(c);
162
+ if (!bits) band.set(c, (bits = new Uint8Array(w)));
163
+ bits[x] |= 1 << dy;
164
+ }
165
+ }
166
+ let first = true;
167
+ for (const [c, bits] of band) {
168
+ out += `${first ? '' : '$'}#${c}`;
169
+ first = false;
170
+ // run-length encode: !<count><char>
171
+ let x = 0;
172
+ while (x < w) {
173
+ const v = bits[x];
174
+ let n = 1;
175
+ while (x + n < w && bits[x + n] === v) n++;
176
+ const ch = String.fromCharCode(63 + v);
177
+ out += n > 3 ? `!${n}${ch}` : ch.repeat(n);
178
+ x += n;
179
+ }
180
+ }
181
+ if (y + 6 < y1) out += '-'; // next band (not after the last, so the screen can't scroll)
182
+ }
183
+ return out + '\x1b\\';
184
+ }