@dotrino/terminal-agent 0.53.0 → 0.54.1

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/clipboard.js CHANGED
@@ -15,9 +15,15 @@ import { execFile } from 'node:child_process'
15
15
  /** Los tipos que admite la subida (uploads.js), en orden de preferencia. */
16
16
  export const IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp']
17
17
 
18
+ /** @type {(code: string, message: string) => Error & { code: string }} */
18
19
  const fail = (code, message) => Object.assign(new Error(message), { code })
19
20
 
20
- /** Corre una herramienta y devuelve su salida en bytes. */
21
+ /**
22
+ * Corre una herramienta y devuelve su salida en bytes.
23
+ * @param {string} cmd
24
+ * @param {string[]} args
25
+ * @returns {Promise<Buffer>}
26
+ */
21
27
  function runTool (cmd, args) {
22
28
  return new Promise((resolve, reject) => {
23
29
  execFile(cmd, args, { encoding: 'buffer', maxBuffer: 64 * 1024 * 1024, timeout: 5000, windowsHide: true }, (err, stdout) => {
@@ -31,13 +37,19 @@ function runTool (cmd, args) {
31
37
  })
32
38
  }
33
39
 
34
- /** De la lista de tipos que ofrece el portapapeles, el de imagen que se manda, o null. */
40
+ /**
41
+ * De la lista de tipos que ofrece el portapapeles, el de imagen que se manda, o null.
42
+ * @param {unknown} targets
43
+ */
35
44
  export function pickImageType (targets) {
36
45
  const offered = new Set(String(targets).split(/\r?\n/).map((s) => s.trim()).filter(Boolean))
37
46
  return IMAGE_TYPES.find((t) => offered.has(t)) || null
38
47
  }
39
48
 
40
- /** Lo que contesta `osascript` (`«data PNGf89504E…»`), en bytes; null si no es eso. */
49
+ /**
50
+ * Lo que contesta `osascript` (`«data PNGf89504E…»`), en bytes; null si no es eso.
51
+ * @param {unknown} text
52
+ */
41
53
  export function parseAppleData (text) {
42
54
  const m = /«data PNGf([0-9A-Fa-f]+)»/.exec(String(text))
43
55
  return m ? Buffer.from(m[1], 'hex') : null
@@ -52,12 +64,13 @@ const WINDOWS_SCRIPT = [
52
64
 
53
65
  /**
54
66
  * La imagen del portapapeles, o null si no hay.
55
- * @param {{ platform?: string, env?: object, run?: (cmd:string, args:string[]) => Promise<Buffer> }} [opts]
67
+ * @param {{ platform?: string, env?: Record<string, string | undefined>, run?: (cmd:string, args:string[]) => Promise<Buffer> }} [opts]
56
68
  * @returns {Promise<Buffer|null>}
57
69
  */
58
70
  export async function clipboardImage ({ platform = process.platform, env = process.env, run = runTool } = {}) {
71
+ /** @type {(cmd: string, args: string[]) => Promise<Buffer | null>} */
59
72
  const quiet = async (cmd, args) => {
60
- try { return await run(cmd, args) } catch (e) { if (e.code === 'clipboard-empty') return null; throw e }
73
+ try { return await run(cmd, args) } catch (e) { if (/** @type {Thrown} */ (e).code === 'clipboard-empty') return null; throw e }
61
74
  }
62
75
  if (platform === 'darwin') {
63
76
  const out = await quiet('osascript', ['-e', 'the clipboard as «class PNGf»'])
@@ -81,7 +94,10 @@ export async function clipboardImage ({ platform = process.platform, env = proce
81
94
  throw fail('no-display', 'no graphical session here (neither WAYLAND_DISPLAY nor DISPLAY)')
82
95
  }
83
96
 
84
- /** Una ruta como se teclea en una shell: entre comillas solo si hace falta. */
97
+ /**
98
+ * Una ruta como se teclea en una shell: entre comillas solo si hace falta.
99
+ * @param {string} file
100
+ */
85
101
  export function typedPath (file) {
86
102
  return /^[\w@%+=:,./-]+$/.test(file) ? file : `'${file.replace(/'/g, `'\\''`)}'`
87
103
  }
@@ -93,7 +109,7 @@ export const UPLOAD_PIECE = 96 * 1024
93
109
  * Sube una imagen a la máquina de la consola y devuelve la ruta donde quedó. Va en trozos y
94
110
  * cada uno espera su acuse (`filed`). `ask(msg)` manda un mensaje y resuelve con la respuesta
95
111
  * (`filed` o `fail`); un `fail` se lanza con su `code`.
96
- * @param {(msg: object) => Promise<object>} ask
112
+ * @param {(msg: object) => Promise<{ type?: string, code?: string, message?: string, up?: string, seq?: number, path?: string }>} ask
97
113
  * @param {Buffer} bytes
98
114
  * @param {{ id?: string }} [opts]
99
115
  * @returns {Promise<string>}
package/consoles.js CHANGED
@@ -18,9 +18,15 @@ import os from 'node:os'
18
18
  import { createRequire } from 'node:module'
19
19
 
20
20
  const require = createRequire(import.meta.url)
21
+ /** @type {typeof import('@xterm/headless').Terminal} */
21
22
  const { Terminal } = require('@xterm/headless')
23
+ /** @type {typeof import('@xterm/addon-serialize').SerializeAddon} */
22
24
  const { SerializeAddon } = require('@xterm/addon-serialize')
23
25
 
26
+ /** @typedef {import('./types/agent.js').Viewer} Viewer */
27
+ /** @typedef {import('./types/agent.js').ConsoleInfo} ConsoleInfo */
28
+ /** @typedef {import('./types/agent.js').Pty} Pty */
29
+
24
30
  /** Líneas de historial que se guardan y se devuelven al volver. */
25
31
  export const SCROLLBACK = 1000
26
32
  /**
@@ -44,6 +50,7 @@ export const PIECE_JSON_MAX = 40 * 1024
44
50
  * @returns {string[]}
45
51
  */
46
52
  export function pieces (data, max = PIECE_JSON_MAX) {
53
+ /** @type {string[]} */
47
54
  const out = []
48
55
  let start = 0; let cost = 0
49
56
  for (let i = 0; i < data.length; i++) {
@@ -92,6 +99,8 @@ export const NOTE_MAX = 4000
92
99
  * personal. El título no sirve para esto: lo pone el programa que corre dentro, y uno como Claude
93
100
  * Code pone el nombre de su sesión, sin carpeta. En Linux se lee de /proc; donde no hay /proc
94
101
  * (macOS) no se sabe, y se dice con `null` en vez de dar la carpeta de arranque por buena.
102
+ * @param {number | null | undefined} pid
103
+ * @returns {string | null}
95
104
  */
96
105
  export function cwdOf (pid) {
97
106
  if (!pid) return null
@@ -113,7 +122,11 @@ const HOST = userAtHost()
113
122
 
114
123
  const randomId = () => [...crypto.getRandomValues(new Uint8Array(8))].map((x) => x.toString(16).padStart(2, '0')).join('')
115
124
 
116
- class Console {
125
+ /** Una consola: su shell, su pantalla sin pantalla y quién la mira. */
126
+ export class Console {
127
+ /**
128
+ * @param {{ id: string, n: number, pty: Pty, cols: number, rows: number, origin: 'local' | 'remote', quietMs?: number }} o
129
+ */
117
130
  constructor ({ id, n, pty, cols, rows, origin, quietMs = QUIET_MS }) {
118
131
  this.quietMs = quietMs
119
132
  this.id = id
@@ -136,27 +149,38 @@ class Console {
136
149
  this.rows = rows
137
150
  this.createdAt = Date.now()
138
151
  this.lastActive = Date.now()
152
+ /** @type {Set<Viewer>} */
139
153
  this.viewers = new Set() // sesiones mirando: { onOut(data), onExit(code), onMeta?(info), origin, device?, tag?, size? }
140
154
  // QUIÉN PUSO EL TAMAÑO. Lo gana una pantalla en cuatro momentos y solo en esos: al abrir la
141
155
  // consola, al cambiarse a ella, al pulsar ⤢ y al teclear. Se ajusta en ese instante y nada
142
156
  // queda fijado: la siguiente pantalla que haga una de las cuatro cosas lo cambia. `holder` es la última que lo
143
157
  // hizo; solo a ella se le sigue la pantalla (redimensionar la ventana, girar el teléfono).
144
158
  // Volver a conectarse o que otra pantalla se vaya no cambia el tamaño.
159
+ /** @type {Viewer | null} */
145
160
  this.holder = null
146
161
  // Quién lo tenía cuando se fue (su aparato o su ventana): si ESA pantalla vuelve por una
147
162
  // conexión nueva sin que otra lo haya tomado, sigue siendo la suya (`resume`).
163
+ /** @type {string | null} */
148
164
  this.lastHolder = null
149
165
  this.exited = false
166
+ // Cerrada con `kill` (y por qué pantalla), y los avisos para insistir si la shell no se va.
167
+ this.killed = false
168
+ /** @type {Viewer | null} */
169
+ this.killedBy = null
170
+ /** @type {ReturnType<typeof setTimeout>[]} */
171
+ this._killTimers = []
150
172
  this.screen = new Terminal({ cols, rows, scrollback: SCROLLBACK, allowProposedApi: true })
151
173
  this.serializer = new SerializeAddon()
152
174
  this.screen.loadAddon(this.serializer)
153
175
  this.busy = false // ¿trabajando ahora?
154
176
  this.busySince = 0
177
+ /** @type {number | null} */
155
178
  this.doneAt = null // terminó (o pidió atención) y nadie lo ha atendido
156
179
  this.lastInput = 0
157
180
  this._changing = 0 // desde cuándo hay cambios seguidos
158
181
  this._lastChange = 0
159
- this._quiet = null
182
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
183
+ this._quiet = undefined
160
184
  this.screen.onTitleChange((t) => {
161
185
  this.title = String(t).slice(0, 200)
162
186
  if (!this._changed(Date.now())) this._meta()
@@ -168,6 +192,7 @@ class Console {
168
192
  * Algo cambió (el título o el contenido). Cambios seguidos encienden «trabajando»; un rato sin
169
193
  * ninguno lo apaga. Dos cambios sueltos (el prompt que se redibuja, un comando instantáneo) no
170
194
  * son un programa trabajando. Devuelve si avisó a quien mira.
195
+ * @param {number} now
171
196
  */
172
197
  _changed (now) {
173
198
  if (now - this.lastInput <= ECHO_MS) return false
@@ -179,7 +204,10 @@ class Console {
179
204
  return now - this._changing >= SUSTAIN_MS ? this._setBusy(true) : false
180
205
  }
181
206
 
182
- /** Cambia «trabajando». Al dejar de trabajar tras una tarea de verdad, queda como terminada. */
207
+ /**
208
+ * Cambia «trabajando». Al dejar de trabajar tras una tarea de verdad, queda como terminada.
209
+ * @param {boolean} v
210
+ */
183
211
  _setBusy (v) {
184
212
  if (v === this.busy) return false
185
213
  this.busy = v
@@ -196,7 +224,10 @@ class Console {
196
224
  this._meta()
197
225
  }
198
226
 
199
- /** Cambia la nota. Lo ve al momento quien mira la consola; los demás, en la lista. */
227
+ /**
228
+ * Cambia la nota. Lo ve al momento quien mira la consola; los demás, en la lista.
229
+ * @param {unknown} text
230
+ */
200
231
  setNote (text) {
201
232
  const note = String(text ?? '').slice(0, NOTE_MAX)
202
233
  if (note === this.note) return
@@ -204,7 +235,10 @@ class Console {
204
235
  this._meta()
205
236
  }
206
237
 
207
- /** Cambia la tarea en curso (la del programa). No toca la nota de la persona. */
238
+ /**
239
+ * Cambia la tarea en curso (la del programa). No toca la nota de la persona.
240
+ * @param {unknown} text
241
+ */
208
242
  setTask (text) {
209
243
  const task = String(text ?? '').slice(0, NOTE_MAX)
210
244
  if (task === this.task) return
@@ -213,7 +247,10 @@ class Console {
213
247
  this._meta()
214
248
  }
215
249
 
216
- /** Cambia el título que pone el programa. Vacío, vuelve a mandar el de la shell. */
250
+ /**
251
+ * Cambia el título que pone el programa. Vacío, vuelve a mandar el de la shell.
252
+ * @param {unknown} text
253
+ */
217
254
  setSubject (text) {
218
255
  const subject = String(text ?? '').replace(/\s+/g, ' ').trim().slice(0, 200)
219
256
  if (subject === this.subject) return
@@ -227,7 +264,10 @@ class Console {
227
264
  for (const v of this.viewers) v.onMeta?.(info)
228
265
  }
229
266
 
230
- /** Lo que sale de la shell: a la pantalla sin pantalla y a quien esté mirando. */
267
+ /**
268
+ * Lo que sale de la shell: a la pantalla sin pantalla y a quien esté mirando.
269
+ * @param {string} data
270
+ */
231
271
  _out (data) {
232
272
  const now = Date.now()
233
273
  this.lastActive = now
@@ -236,8 +276,13 @@ class Console {
236
276
  for (const v of this.viewers) v.onOut(data)
237
277
  }
238
278
 
279
+ /** @param {string} data */
239
280
  write (data) { this.lastActive = this.lastInput = Date.now(); this._attended(); this.pty.write(data) }
240
281
 
282
+ /**
283
+ * @param {number} cols
284
+ * @param {number} rows
285
+ */
241
286
  resize (cols, rows) {
242
287
  if (!cols || !rows) return
243
288
  const changed = cols !== this.cols || rows !== this.rows
@@ -255,10 +300,14 @@ class Console {
255
300
  * aparte y se le da después. El `write('', cb)` hace de marca: xterm procesa en orden y
256
301
  * llama al callback justo tras esa marca, así que la foto tiene todo lo anterior y nada
257
302
  * de lo posterior.
303
+ * @param {Viewer} viewer
304
+ * @param {{ scrollback?: number }} [opts]
258
305
  * @returns {Promise<string>} la pantalla serializada
259
306
  */
260
307
  attach (viewer, { scrollback } = {}) {
308
+ /** @type {string[]} */
261
309
  const pending = []
310
+ /** @type {Viewer} */
262
311
  const buffering = { onOut: (d) => pending.push(d), onExit: viewer.onExit }
263
312
  this.viewers.add(buffering)
264
313
  return new Promise((resolve) => {
@@ -283,11 +332,14 @@ class Console {
283
332
  * se hace la foto se guarda y sale detrás, igual que en `attach`, así que no se pierde ni se
284
333
  * repite nada. Empieza por un reinicio del terminal (`ESC c`): el cliente la pinta encima de
285
334
  * lo que tenía sin saber que es una segunda foto.
335
+ * @param {Viewer} viewer
286
336
  * @returns {Promise<string|null>} `null` si ese mirón ya no está
287
337
  */
288
338
  history (viewer) {
289
339
  if (!this.viewers.has(viewer)) return Promise.resolve(null)
340
+ /** @type {string[]} */
290
341
  const pending = []
342
+ /** @type {Viewer} */
291
343
  const buffering = { onOut: (d) => pending.push(d), onExit: viewer.onExit }
292
344
  this.viewers.delete(viewer)
293
345
  this.viewers.add(buffering)
@@ -301,6 +353,7 @@ class Console {
301
353
  })
302
354
  }
303
355
 
356
+ /** @param {Viewer} viewer */
304
357
  detach (viewer) {
305
358
  if (!this.viewers.has(viewer)) return
306
359
  this.viewers.delete(viewer)
@@ -317,6 +370,7 @@ class Console {
317
370
  * con las filas de antes, las últimas por detrás del teclado, hasta que tecleaba.
318
371
  * Vale tanto si su conexión vieja ya se soltó (`lastHolder`) como si sigue enganchada sin
319
372
  * saberse muerta (`holder` es otra sesión de la misma pantalla).
373
+ * @param {Viewer} viewer
320
374
  */
321
375
  resume (viewer) {
322
376
  if (!this.viewers.has(viewer)) return
@@ -329,7 +383,10 @@ class Console {
329
383
  else this._meta()
330
384
  }
331
385
 
332
- /** `viewer` toma el tamaño AHORA: abrió la consola, se cambió a ella, pulsó ⤢ o tecleó. */
386
+ /**
387
+ * `viewer` toma el tamaño AHORA: abrió la consola, se cambió a ella, pulsó ⤢ o tecleó.
388
+ * @param {Viewer} viewer
389
+ */
333
390
  take (viewer) {
334
391
  if (!this.viewers.has(viewer)) return
335
392
  this.holder = viewer
@@ -338,7 +395,10 @@ class Console {
338
395
  else this._meta()
339
396
  }
340
397
 
341
- /** Cambió la pantalla de `viewer` (ventana, giro). Solo se sigue a quien puso el tamaño. */
398
+ /**
399
+ * Cambió la pantalla de `viewer` (ventana, giro). Solo se sigue a quien puso el tamaño.
400
+ * @param {Viewer} viewer
401
+ */
342
402
  sizeFrom (viewer) {
343
403
  if (this.holder === viewer && viewer.size) this.resize(viewer.size.cols, viewer.size.rows)
344
404
  }
@@ -347,9 +407,10 @@ class Console {
347
407
  * `watchers` dice QUIÉN mira: una ventana de esta máquina o un aparato de la cuenta (con
348
408
  * su pubkey), y la etiqueta con la que se presentó (`tag`): así una ventana de la app de
349
409
  * escritorio reconoce, en la lista, cuál es la consola que está mostrando ella. Es lo que deja a la ventana local avisar de que alguien entró desde fuera.
410
+ * @returns {ConsoleInfo}
350
411
  */
351
412
  info () {
352
- const watchers = [...this.viewers].filter((v) => v.origin).map((v) => ({ origin: v.origin, device: v.device || null, tag: v.tag || null }))
413
+ const watchers = [...this.viewers].flatMap((v) => v.origin ? [{ origin: v.origin, device: v.device || null, tag: v.tag || null }] : [])
353
414
  const d = this.holder
354
415
  const sizeBy = d ? { origin: d.origin || null, device: d.device || null, tag: d.tag || null } : null
355
416
  return { id: this.id, n: this.n, activity: this.busy ? 'busy' : 'idle', doneAt: this.doneAt, sizeBy, origin: this.origin, title: this.subject || this.title, shellTitle: this.title, subject: this.subject, note: this.note, task: this.task, host: HOST, cwd: cwdOf(this.pty?.pid), cols: this.cols, rows: this.rows, createdAt: this.createdAt, lastActive: this.lastActive, viewers: this.viewers.size, watchers }
@@ -371,12 +432,16 @@ const REPORTS = new RegExp([
371
432
  '\\x1bP[\\s\\S]*?\\x1b\\\\', // DCS
372
433
  ].join('|'), 'g')
373
434
 
374
- /** ¿Hay algo TECLEADO en `data`, o es solo lo que la terminal contesta por su cuenta? */
435
+ /**
436
+ * ¿Hay algo TECLEADO en `data`, o es solo lo que la terminal contesta por su cuenta?
437
+ * @param {unknown} data
438
+ */
375
439
  export function isTyped (data) { return String(data).replace(REPORTS, '') !== '' }
376
440
 
377
441
 
378
442
  /** Las consolas de este agente. */
379
443
  /** Qué PANTALLA es un mirón, más allá de su conexión: el aparato, o la ventana con su etiqueta. Null si no se sabe. */
444
+ /** @param {Viewer} v */
380
445
  function screenOf (v) {
381
446
  if (v.origin === 'remote') return v.device ? `remote:${v.device}` : null
382
447
  return v.tag ? `local:${v.tag}` : null
@@ -384,16 +449,21 @@ function screenOf (v) {
384
449
 
385
450
  export class ConsoleHub {
386
451
  /**
387
- * @param {{ spawn:(opts:{cols:number,rows:number,cwd:string|null,id:string})=>any }} opts
452
+ * @param {{ spawn:(opts:{cols:number,rows:number,cwd:string|null,id:string})=>Pty, quietMs?: number }} opts
388
453
  * `spawn` lanza la shell (un PTY con `onData`, `onExit`, `write`, `resize`, `kill`). `id` es el de
389
454
  * la consola: va en el entorno de la shell para que lo que corre dentro sepa cuál es la suya.
390
455
  */
391
456
  constructor ({ spawn, quietMs = QUIET_MS }) {
392
457
  this._spawn = spawn
393
458
  this._quietMs = quietMs
459
+ /** @type {Map<string, Console>} */
394
460
  this.consoles = new Map()
395
461
  }
396
462
 
463
+ /**
464
+ * Abre una consola nueva.
465
+ * @param {{ cols?: number, rows?: number, origin?: 'local' | 'remote', cwd?: string | null }} [opts]
466
+ */
397
467
  create ({ cols = 80, rows = 24, origin = 'remote', cwd = null } = {}) {
398
468
  const id = randomId()
399
469
  // Su NÚMERO: el libre más bajo, y no cambia mientras viva. Si se cierra la 1, la 2 sigue
@@ -410,7 +480,7 @@ export class ConsoleHub {
410
480
  pty.onExit(({ exitCode }) => {
411
481
  c.exited = true
412
482
  clearTimeout(c._quiet)
413
- for (const t of c._killTimers || []) clearTimeout(t)
483
+ for (const t of c._killTimers) clearTimeout(t)
414
484
  this.consoles.delete(id)
415
485
  // A cada pantalla se le dice si la consola la cerró OTRA (`byOther`): la shell que termina
416
486
  // sola, o la que cierra la propia pantalla, no lo es. Quien mira decide con eso si se va
@@ -429,12 +499,15 @@ export class ConsoleHub {
429
499
  return c
430
500
  }
431
501
 
502
+ /** @param {Console[]} all */
432
503
  _order (all) { this.consoles = new Map(all.map((c) => [c.id, c])) }
433
504
 
434
505
  /**
435
506
  * El ORDEN del panel, el mismo en todas las ventanas y aparatos: la consola `id` pasa a estar
436
507
  * justo antes de `before` (o al final, con `null` o con una que ya no existe). No cambia su
437
508
  * número, que es fijo. `false` si esa consola ya no existe.
509
+ * @param {string} id
510
+ * @param {string | null} [before]
438
511
  */
439
512
  move (id, before = null) {
440
513
  const c = this.consoles.get(id)
@@ -447,6 +520,7 @@ export class ConsoleHub {
447
520
  return true
448
521
  }
449
522
 
523
+ /** @param {string} id */
450
524
  get (id) { return this.consoles.get(id) || null }
451
525
 
452
526
  /** Las consolas, en el orden del panel (por número hasta que alguien las mueve: `move`). */
@@ -460,6 +534,8 @@ export class ConsoleHub {
460
534
  * la devolvía y el panel enseñaba una consola muerta. Y si la shell no se va con el SIGHUP de
461
535
  * siempre (un `trap '' HUP`, un programa colgado), se insiste: SIGTERM, y después SIGKILL. Antes
462
536
  * la × no hacía nada y la consola se quedaba en la lista para siempre.
537
+ * @param {string} id
538
+ * @param {Viewer | null} [by]
463
539
  */
464
540
  kill (id, by = null) {
465
541
  const c = this.consoles.get(id)
@@ -468,7 +544,9 @@ export class ConsoleHub {
468
544
  c.killedBy = by
469
545
  this.consoles.delete(id)
470
546
  try { c.pty.kill() } catch (_) {}
471
- c._killTimers = [['SIGTERM', KILL_TERM_MS], ['SIGKILL', KILL_KILL_MS]].map(([sig, ms]) => {
547
+ /** @type {[string, number][]} */
548
+ const escalate = [['SIGTERM', KILL_TERM_MS], ['SIGKILL', KILL_KILL_MS]]
549
+ c._killTimers = escalate.map(([sig, ms]) => {
472
550
  const t = setTimeout(() => { if (!c.exited) try { c.pty.kill(sig) } catch (_) {} }, ms)
473
551
  t.unref?.()
474
552
  return t
package/desktop.js CHANGED
@@ -31,20 +31,39 @@ export const DESKTOP_TAG = 'desktop-v'
31
31
  export const BINARY = 'dotrino-terminal-desktop'
32
32
  const PRODUCT = 'dotrino-terminal-desktop'
33
33
 
34
- /** @returns {any} */
34
+ /** No se pudo: con su código, y el archivo bajado si sirve para instalarlo a mano. */
35
+ /** @typedef {{ ok: false, code: string, reason: string, file?: string }} Failure */
36
+ /** Cómo está instalada la app de escritorio. */
37
+ /** @typedef {{ ok: true, kind: 'deb' | 'rpm' | 'tar' | 'win' } | { ok: true, kind: 'mac', app: string }} InstallKind */
38
+ /** La última release del escritorio, con sus archivos. */
39
+ /** @typedef {{ ok: true, version: string, assets: import('@dotrino/update/fetch').ReleaseAsset[] } | { ok: false, reason: string }} DesktopLatest */
40
+ /** Correr una orden del sistema (`execFileSync`, o su doble en las pruebas). */
41
+ /** @typedef {(cmd: string, args: string[], opts?: import('node:child_process').ExecFileSyncOptions) => unknown} RunFn */
42
+
43
+ /**
44
+ * @param {string} code
45
+ * @param {string} reason
46
+ * @param {{ file?: string }} [extra]
47
+ * @returns {Failure}
48
+ */
35
49
  const fail = (code, reason, extra = {}) => ({ ok: false, code, reason, ...extra })
36
50
 
37
- /** La última release del escritorio. `{ ok:false }` si no se pudo mirar, que NO es «al día». */
51
+ /**
52
+ * La última release del escritorio. `{ ok:false }` si no se pudo mirar, que NO es «al día».
53
+ * @param {{ version?: string }} [opts]
54
+ * @returns {Promise<DesktopLatest>}
55
+ */
38
56
  export const latestDesktop = (opts = {}) =>
39
- latestVersion({ source: 'github', repo: REPO, tagPrefix: DESKTOP_TAG, product: PRODUCT, ...opts })
57
+ // Con `source: 'github'` la respuesta buena siempre trae los archivos de la release.
58
+ /** @type {Promise<DesktopLatest>} */ (latestVersion({ source: 'github', repo: REPO, tagPrefix: DESKTOP_TAG, product: PRODUCT, ...opts }))
40
59
 
41
60
  /**
42
61
  * Cómo está instalada la app que corre desde `exe`, que es lo que decide qué archivo se baja
43
62
  * y cómo se pone. Se le pregunta al gestor de paquetes por ESE archivo: mirar solo qué
44
63
  * gestor hay se equivoca con un tarball en una máquina con `dpkg`.
45
64
  *
46
- * @param {any} [o]
47
- * @returns {any} `{ ok:true, kind:'deb'|'rpm'|'tar'|'mac'|'win', app? }` o `{ ok:false, code, reason }`
65
+ * @param {{ exe?: string, platform?: string, arch?: string, run?: RunFn, writable?: (dir: string) => boolean }} [o]
66
+ * @returns {InstallKind | Failure} `{ ok:true, kind:'deb'|'rpm'|'tar'|'mac'|'win', app? }` o `{ ok:false, code, reason }`
48
67
  */
49
68
  export function installKind ({ exe, platform = process.platform, arch = process.arch, run = execFileSync, writable = canWrite } = {}) {
50
69
  if (!exe) return fail('no-exe', 'the desktop app was not found')
@@ -61,6 +80,7 @@ export function installKind ({ exe, platform = process.platform, arch = process.
61
80
  }
62
81
  if (platform !== 'linux') return fail('unsupported-platform', `there is no desktop app for ${platform}`)
63
82
  if (arch !== 'x64') return fail('unsupported-arch', `there is no desktop app for ${arch}`)
83
+ /** @type {(cmd: string, args: string[]) => boolean} */
64
84
  const owns = (cmd, args) => { try { run(cmd, args, { stdio: 'ignore' }); return true } catch (_) { return false } }
65
85
  if (owns('dpkg', ['-S', exe])) return { ok: true, kind: 'deb' }
66
86
  if (owns('rpm', ['-qf', exe])) return { ok: true, kind: 'rpm' }
@@ -68,10 +88,12 @@ export function installKind ({ exe, platform = process.platform, arch = process.
68
88
  return { ok: true, kind: 'tar' }
69
89
  }
70
90
 
91
+ /** @param {string} dir */
71
92
  function canWrite (dir) {
72
93
  try { fs.accessSync(dir, fs.constants.W_OK); return true } catch (_) { return false }
73
94
  }
74
95
 
96
+ /** @type {Record<string, { kind: string, re: RegExp }>} */
75
97
  const MATCH = {
76
98
  deb: { kind: 'deb', re: /_amd64\.deb$/ },
77
99
  rpm: { kind: 'rpm', re: /\.x86_64\.rpm$/ },
@@ -80,15 +102,25 @@ const MATCH = {
80
102
  win: { kind: 'win', re: /-windows-x64\.zip$/ }
81
103
  }
82
104
 
83
- /** El archivo de la release que le toca a esa forma de instalación. */
105
+ /**
106
+ * El archivo de la release que le toca a esa forma de instalación.
107
+ * @param {import('@dotrino/update/fetch').ReleaseAsset[]} assets
108
+ * @param {string} kind
109
+ */
84
110
  export const assetFor = (assets, kind) => pickAsset(assets, [MATCH[kind]])
85
111
 
86
- /** Como root no hace falta `sudo`; si no, se pide en la ventana. */
112
+ /**
113
+ * Como root no hace falta `sudo`; si no, se pide en la ventana.
114
+ * @param {string} cmd
115
+ * @param {string[]} args
116
+ * @param {{ run: RunFn, uid: number | undefined }} o
117
+ */
87
118
  function asRoot (cmd, args, { run, uid }) {
88
119
  const [c, a] = uid === 0 ? [cmd, args] : ['sudo', [cmd, ...args]]
89
120
  run(c, a, { stdio: 'inherit' })
90
121
  }
91
122
 
123
+ /** @type {(cmd: string, run: RunFn) => boolean} */
92
124
  const has = (cmd, run) => { try { run('sh', ['-c', `command -v ${cmd}`], { stdio: 'ignore' }); return true } catch (_) { return false } }
93
125
 
94
126
  /**
@@ -96,6 +128,9 @@ const has = (cmd, run) => { try { run('sh', ['-c', `command -v ${cmd}`], { stdio
96
128
  * (`apt-get`, `dnf`, `zypper`) al que solo desempaqueta (`dpkg`, `rpm`): una versión nueva
97
129
  * puede pedir una librería que la anterior no pedía, y `rpm -U` se para ahí sin traerla.
98
130
  *
131
+ * @param {string} kind
132
+ * @param {string} file
133
+ * @param {{ run?: RunFn }} [o]
99
134
  * @returns {[string, string[]]}
100
135
  */
101
136
  export function packageCommand (kind, file, { run = execFileSync } = {}) {
@@ -111,20 +146,21 @@ export function packageCommand (kind, file, { run = execFileSync } = {}) {
111
146
  * quedó bajado y sirve para instalarlo a mano, va en `file`.
112
147
  *
113
148
  * @param {string} file
114
- * @param {any} how
115
- * @param {any} [o]
116
- * @returns {any}
149
+ * @param {InstallKind} how
150
+ * @param {{ exe?: string, run?: RunFn, uid?: number }} [o]
151
+ * @returns {{ ok: true } | Failure}
117
152
  */
118
153
  export function install (file, how, { exe, run = execFileSync, uid = process.getuid?.() } = {}) {
119
154
  if (how.kind === 'deb' || how.kind === 'rpm') {
120
155
  try { asRoot(...packageCommand(how.kind, file, { run }), { run, uid }); return { ok: true } } catch (e) {
121
- return fail('install-failed', `the package manager did not install it: ${e.message}`, { file })
156
+ return fail('install-failed', `the package manager did not install it: ${/** @type {Thrown} */ (e).message}`, { file })
122
157
  }
123
158
  }
124
159
  if (how.kind === 'tar') {
160
+ if (!exe) return fail('no-exe', 'the desktop app was not found', { file })
125
161
  const work = path.dirname(file)
126
162
  try { run('tar', ['xzf', file, '-C', work], { stdio: ['ignore', 'ignore', 'pipe'] }) } catch (e) {
127
- return fail('unpack-failed', `could not unpack the release: ${String(e.stderr || e.message).trim()}`, { file })
163
+ return fail('unpack-failed', `could not unpack the release: ${String(/** @type {Thrown} */ (e).stderr || /** @type {Thrown} */ (e).message).trim()}`, { file })
128
164
  }
129
165
  const src = fs.readdirSync(work).map((d) => path.join(work, d, BINARY)).find((f) => fs.existsSync(f))
130
166
  if (!src) return fail('bad-tarball', `the tarball has no ${BINARY} inside`, { file })
@@ -149,16 +185,17 @@ export function install (file, how, { exe, run = execFileSync, uid = process.get
149
185
  try { fs.renameSync(fresh, how.app) } catch (e) { fs.renameSync(old, how.app); throw e }
150
186
  return { ok: true }
151
187
  } catch (e) {
152
- return fail('install-failed', `could not replace the app: ${String(e.stderr || e.message).trim()}`, { file })
188
+ return fail('install-failed', `could not replace the app: ${String(/** @type {Thrown} */ (e).stderr || /** @type {Thrown} */ (e).message).trim()}`, { file })
153
189
  } finally {
154
190
  fs.rmSync(work, { recursive: true, force: true })
155
191
  }
156
192
  }
157
193
  if (how.kind === 'win') {
194
+ if (!exe) return fail('no-exe', 'the desktop app was not found', { file })
158
195
  const work = path.dirname(file)
159
196
  // `tar` de Windows (bsdtar, desde Windows 10) desempaqueta un .zip.
160
197
  try { run('tar', ['-xf', file, '-C', work], { stdio: ['ignore', 'ignore', 'pipe'] }) } catch (e) {
161
- return fail('unpack-failed', `could not unpack the release: ${String(e.stderr || e.message).trim()}`, { file })
198
+ return fail('unpack-failed', `could not unpack the release: ${String(/** @type {Thrown} */ (e).stderr || /** @type {Thrown} */ (e).message).trim()}`, { file })
162
199
  }
163
200
  const name = `${BINARY}.exe`
164
201
  const src = [path.join(work, name), ...fs.readdirSync(work).map((d) => path.join(work, d, name))].find((f) => fs.existsSync(f))
@@ -171,19 +208,21 @@ export function install (file, how, { exe, run = execFileSync, uid = process.get
171
208
  fs.renameSync(exe, old)
172
209
  try { fs.copyFileSync(src, exe) } catch (e) { fs.renameSync(old, exe); throw e }
173
210
  } catch (e) {
174
- return fail('install-failed', `could not replace the app: ${e.message}`, { file })
211
+ return fail('install-failed', `could not replace the app: ${/** @type {Thrown} */ (e).message}`, { file })
175
212
  }
176
213
  return { ok: true }
177
214
  }
178
- return fail('unknown-kind', `unknown install kind: ${how.kind}`)
215
+ return fail('unknown-kind', `unknown install kind: ${/** @type {{ kind: string }} */ (how).kind}`)
179
216
  }
180
217
 
181
218
  /**
182
219
  * Todo el camino: mirar, bajar, verificar, instalar. `say(step, data)` va contando por dónde
183
220
  * va, para que quien lo enseñe lo diga en su idioma.
184
221
  *
185
- * @param {any} [o]
186
- * @returns {Promise<any>} `{ ok:true, version, updated, newer?, kind? }` o `{ ok:false, code, reason, file? }`
222
+ * @param {{ exe?: string, current?: string, check?: boolean, say?: (step: string, data: object) => void, latest?: typeof latestDesktop,
223
+ * fetchVerifiedImpl?: typeof fetchVerified, kindOf?: typeof installKind, installImpl?: typeof install }} [o]
224
+ * @returns {Promise<{ ok: true, version: string, updated: boolean, newer?: boolean, kind?: string } | Failure>}
225
+ * `{ ok:true, version, updated, newer?, kind? }` o `{ ok:false, code, reason, file? }`
187
226
  */
188
227
  export async function updateDesktop ({ exe, current, check = false, say = () => {}, latest = latestDesktop, fetchVerifiedImpl = fetchVerified, kindOf = installKind, installImpl = install } = {}) {
189
228
  const r = await latest({ version: current })
@@ -203,11 +242,12 @@ export async function updateDesktop ({ exe, current, check = false, say = () =>
203
242
  try { got = await fetchVerifiedImpl(pick.asset, { repo: REPO, product: PRODUCT, version: current, dir }) } catch (e) {
204
243
  // La comprobación (sigstore → @npmcli/agent) carga módulos ESM con `require()`: Node lo
205
244
  // admite desde 20.19 y 22.12. Con uno anterior no hay con qué verificar, y se dice cuál falta.
206
- if (e.code === 'ERR_REQUIRE_ESM') return fail('node-too-old', `Node ${process.version} cannot load the signature checker (needs 20.19 or 22.12 and later)`)
207
- return fail(e.code || 'download-failed', e.message)
245
+ if (/** @type {Thrown} */ (e).code === 'ERR_REQUIRE_ESM') return fail('node-too-old', `Node ${process.version} cannot load the signature checker (needs 20.19 or 22.12 and later)`)
246
+ return fail(/** @type {Thrown} */ (e).code || 'download-failed', /** @type {Thrown} */ (e).message)
208
247
  }
209
248
  // Lo que no pasa la verificación no se deja en el disco: nadie debe instalarlo a mano.
210
249
  if (!got.ok) return fail(got.code || 'not-verified', got.reason)
250
+ if (!got.file) return fail('download-failed', 'the release file was verified but not kept')
211
251
  say('verified', { name: pick.asset.name, repo: REPO })
212
252
  say('install', { kind: how.kind })
213
253
  const done = installImpl(got.file, how, { exe })
package/downloads.js CHANGED
@@ -21,15 +21,22 @@ export const FETCH_MAX = 50 * 1024 * 1024
21
21
  /** Lo que lleva cada trozo, antes del base64 (el mismo tamaño que las subidas del cliente). */
22
22
  export const FETCH_CHUNK = 96 * 1024
23
23
 
24
+ /** @type {(code: string, message: string) => Error & { code: string }} */
24
25
  const fail = (code, message) => Object.assign(new Error(message), { code })
25
26
 
26
27
  /**
27
28
  * La ruta absoluta de lo que se pide. `~` es la carpeta personal; una ruta relativa cuelga de
28
29
  * `cwd` (la carpeta de la shell de la consola), y sin ella no se adivina: se dice.
29
30
  */
31
+ /**
32
+ * @param {unknown} p
33
+ * @param {string | null} [cwd]
34
+ * @returns {string}
35
+ */
30
36
  export function resolvePath (p, cwd = null) {
31
37
  if (typeof p !== 'string' || !p || p.length > 4096 || p.includes('\0')) throw fail('bad-fetch', 'fetch: needs a `path`')
32
38
  const home = os.homedir()
39
+ /** @param {string} s */
33
40
  const expand = (s) => s === '~' ? home : s.startsWith('~/') ? path.join(home, s.slice(2)) : s
34
41
  const full = expand(p)
35
42
  if (path.isAbsolute(full)) return path.normalize(full)
@@ -43,6 +50,11 @@ export function resolvePath (p, cwd = null) {
43
50
  * @param {string|null} cwd la carpeta de la consola enganchada, para las rutas relativas.
44
51
  * @returns {{ id: string, seq: number, path: string, name: string, size: number, mtime: number, data: string, last?: true }}
45
52
  */
53
+ /**
54
+ * Un trozo de un archivo de esta máquina. `msg` llega de la red: se comprueba campo a campo.
55
+ * @param {any} msg
56
+ * @param {string | null} [cwd]
57
+ */
46
58
  export function readPiece (msg, cwd = null) {
47
59
  const id = typeof msg.id === 'string' ? msg.id.slice(0, 64) : ''
48
60
  const seq = msg.seq
@@ -50,8 +62,8 @@ export function readPiece (msg, cwd = null) {
50
62
  const file = resolvePath(msg.path, cwd)
51
63
  let st
52
64
  try { st = fs.statSync(file) } catch (e) {
53
- if (e.code === 'ENOENT' || e.code === 'ENOTDIR') throw fail('no-file', `no such file: ${file}`)
54
- if (e.code === 'EACCES' || e.code === 'EPERM') throw fail('no-read', `not allowed to read: ${file}`)
65
+ if (/** @type {Thrown} */ (e).code === 'ENOENT' || /** @type {Thrown} */ (e).code === 'ENOTDIR') throw fail('no-file', `no such file: ${file}`)
66
+ if (/** @type {Thrown} */ (e).code === 'EACCES' || /** @type {Thrown} */ (e).code === 'EPERM') throw fail('no-read', `not allowed to read: ${file}`)
55
67
  throw e
56
68
  }
57
69
  if (st.isDirectory()) throw fail('is-dir', `that is a folder: ${file}`)
@@ -63,7 +75,7 @@ export function readPiece (msg, cwd = null) {
63
75
  const buf = Buffer.alloc(len)
64
76
  let fd
65
77
  try { fd = fs.openSync(file, 'r') } catch (e) {
66
- if (e.code === 'EACCES' || e.code === 'EPERM') throw fail('no-read', `not allowed to read: ${file}`)
78
+ if (/** @type {Thrown} */ (e).code === 'EACCES' || /** @type {Thrown} */ (e).code === 'EPERM') throw fail('no-read', `not allowed to read: ${file}`)
67
79
  throw e
68
80
  }
69
81
  try {