@aikyroon/installer-core 1.1.0 → 1.1.5

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.
Files changed (70) hide show
  1. package/dist/api.d.ts +5 -0
  2. package/dist/api.d.ts.map +1 -1
  3. package/dist/api.js +21 -4
  4. package/dist/api.js.map +1 -1
  5. package/dist/cli.d.ts.map +1 -1
  6. package/dist/cli.js +73 -14
  7. package/dist/cli.js.map +1 -1
  8. package/dist/doctor.d.ts.map +1 -1
  9. package/dist/doctor.js +38 -4
  10. package/dist/doctor.js.map +1 -1
  11. package/dist/download.d.ts +12 -0
  12. package/dist/download.d.ts.map +1 -1
  13. package/dist/download.js +133 -7
  14. package/dist/download.js.map +1 -1
  15. package/dist/downloadsCache.d.ts +54 -0
  16. package/dist/downloadsCache.d.ts.map +1 -0
  17. package/dist/downloadsCache.js +153 -0
  18. package/dist/downloadsCache.js.map +1 -0
  19. package/dist/errors.d.ts +57 -0
  20. package/dist/errors.d.ts.map +1 -0
  21. package/dist/errors.js +153 -0
  22. package/dist/errors.js.map +1 -0
  23. package/dist/fsRetry.d.ts +14 -0
  24. package/dist/fsRetry.d.ts.map +1 -0
  25. package/dist/fsRetry.js +58 -0
  26. package/dist/fsRetry.js.map +1 -0
  27. package/dist/index.d.ts +11 -2
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +10 -1
  30. package/dist/index.js.map +1 -1
  31. package/dist/install.d.ts +14 -0
  32. package/dist/install.d.ts.map +1 -1
  33. package/dist/install.js +466 -52
  34. package/dist/install.js.map +1 -1
  35. package/dist/lock.d.ts +7 -0
  36. package/dist/lock.d.ts.map +1 -0
  37. package/dist/lock.js +97 -0
  38. package/dist/lock.js.map +1 -0
  39. package/dist/logger.d.ts +21 -0
  40. package/dist/logger.d.ts.map +1 -1
  41. package/dist/logger.js +151 -1
  42. package/dist/logger.js.map +1 -1
  43. package/dist/manifest.d.ts +16 -2
  44. package/dist/manifest.d.ts.map +1 -1
  45. package/dist/manifest.js +30 -3
  46. package/dist/manifest.js.map +1 -1
  47. package/dist/processes.d.ts +28 -3
  48. package/dist/processes.d.ts.map +1 -1
  49. package/dist/processes.js +116 -7
  50. package/dist/processes.js.map +1 -1
  51. package/dist/retry.d.ts +26 -0
  52. package/dist/retry.d.ts.map +1 -0
  53. package/dist/retry.js +54 -0
  54. package/dist/retry.js.map +1 -0
  55. package/dist/shortcuts.js +10 -3
  56. package/dist/shortcuts.js.map +1 -1
  57. package/dist/types.d.ts +17 -0
  58. package/dist/types.d.ts.map +1 -1
  59. package/dist/uninstall.d.ts.map +1 -1
  60. package/dist/uninstall.js +5 -2
  61. package/dist/uninstall.js.map +1 -1
  62. package/dist/verify.d.ts +4 -3
  63. package/dist/verify.d.ts.map +1 -1
  64. package/dist/verify.js +14 -3
  65. package/dist/verify.js.map +1 -1
  66. package/dist/version.d.ts +10 -0
  67. package/dist/version.d.ts.map +1 -0
  68. package/dist/version.js +22 -0
  69. package/dist/version.js.map +1 -0
  70. package/package.json +1 -1
package/dist/install.js CHANGED
@@ -3,19 +3,51 @@ import fs from 'fs-extra';
3
3
  import { getLatestVersionInfo } from './api.js';
4
4
  import { defaultApiUrl, defaultInstallRoot, normalizeApiUrl, stripTrailingSep } from './config.js';
5
5
  import { downloadAndVerify } from './download.js';
6
+ import { findCachedPackage, formatBytes, pruneDownloads, recordDownload } from './downloadsCache.js';
7
+ import { EXIT, InstallError } from './errors.js';
6
8
  import { extractArchive, isTarball, locateBinary } from './extract.js';
7
- import { writeInstalledVersion, writeJsonAtomic } from './manifest.js';
9
+ import { removeQuiet, removeWithRetry, renameWithRetry } from './fsRetry.js';
10
+ import { acquireLock, releaseLock } from './lock.js';
11
+ import { markInstallInProgress, readInstalledVersion, writeInstalledVersion, writeJsonAtomic, } from './manifest.js';
8
12
  import { detectPlatform, resolveComponent } from './platform.js';
9
13
  import { ensurePythonLauncher } from './python.js';
10
- import { stopKyroonProcesses } from './processes.js';
14
+ import { anyProcessHoldingDir, isProcessAlive, stopKyroonProcesses } from './processes.js';
11
15
  import { createShortcuts } from './shortcuts.js';
12
16
  import { verifyInstall } from './verify.js';
13
17
  import * as log from './logger.js';
18
+ // ---------------------------------------------------------------------------
19
+ // Interrupção cooperativa (Ctrl+C)
20
+ //
21
+ // Matar o processo no meio da troca de arquivos é exatamente o que corrompia a
22
+ // instalação. Em vez de morrer na hora, o sinal levanta uma bandeira: o fluxo
23
+ // termina a operação atômica em curso e para no próximo ponto seguro.
24
+ // ---------------------------------------------------------------------------
25
+ let abortRequested = false;
26
+ export function requestGracefulAbort() {
27
+ abortRequested = true;
28
+ }
29
+ export function isAbortRequested() {
30
+ return abortRequested;
31
+ }
32
+ function throwIfAborted(step) {
33
+ if (!abortRequested)
34
+ return;
35
+ throw new InstallError('Instalação interrompida a pedido do usuário.', {
36
+ step,
37
+ exitCode: EXIT.INTERRUPTED,
38
+ hint: 'Nenhum arquivo ficou pela metade. Execute o instalador novamente quando quiser.',
39
+ });
40
+ }
14
41
  /**
15
42
  * Installs the requested components "flat" under `<installRoot>/<component>/`,
16
43
  * each with its own copy of the native updater (win/linux/macOS). Mirrors the
17
44
  * launcher-less `install.ps1` flow: detect -> download(+SHA256) -> stop -> python
18
45
  * -> extract -> updater -> manifest -> shortcuts -> activate/start.
46
+ *
47
+ * A substituição dos arquivos é ATÔMICA: o pacote é extraído e validado num
48
+ * diretório de staging irmão e só então trocado por `rename`, com backup e
49
+ * rollback. Em nenhum momento o diretório do componente fica parcialmente
50
+ * apagado — que era a causa raiz da perda de arquivos relatada em campo.
19
51
  */
20
52
  export async function installComponents(options) {
21
53
  const platform = detectPlatform();
@@ -26,6 +58,7 @@ export async function installComponents(options) {
26
58
  const selected = dedupeComponents(options.components);
27
59
  const specs = selected.map((name) => requireSpec(name, platform));
28
60
  await fs.ensureDir(installRoot);
61
+ log.openFileLog(installRoot);
29
62
  const downloadsDir = path.join(installRoot, 'downloads');
30
63
  await fs.ensureDir(downloadsDir);
31
64
  log.banner('Kyroon Enterprise Installer', [
@@ -33,7 +66,33 @@ export async function installComponents(options) {
33
66
  `Components : ${selected.join(', ')}`,
34
67
  `API URL : ${apiUrl}`,
35
68
  `InstallRoot : ${installRoot}`,
69
+ `Log : ${log.fileLogPath() ?? '(console apenas)'}`,
36
70
  ]);
71
+ // Impede que dois instaladores (ou o Updater agendado) mexam no mesmo
72
+ // diretório ao mesmo tempo — corrida que também corrompe a instalação.
73
+ await acquireLock(installRoot);
74
+ try {
75
+ // Retoma uma troca interrompida por queda de energia/kill numa execução anterior.
76
+ await recoverInterruptedSwaps(installRoot);
77
+ return await runInstall({
78
+ platform,
79
+ apiUrl,
80
+ installRoot,
81
+ downloadsDir,
82
+ specs,
83
+ selected,
84
+ wantService,
85
+ wantStart,
86
+ force: options.force ?? false,
87
+ activationCode: options.activationCode,
88
+ });
89
+ }
90
+ finally {
91
+ await releaseLock(installRoot);
92
+ }
93
+ }
94
+ async function runInstall(ctx) {
95
+ const { platform, apiUrl, installRoot, downloadsDir, specs, selected } = ctx;
37
96
  // 1) Detect versions (components + native updater when distributed).
38
97
  log.step('[1/7] Detecting latest versions...');
39
98
  const updaterSpec = resolveComponent('updater', platform); // win/linux/macOS (null only on unsupported RIDs)
@@ -48,19 +107,65 @@ export async function installComponents(options) {
48
107
  infos.set(spec.name, info);
49
108
  log.info(`${spec.display} v${info.versionBuild}`);
50
109
  }
51
- // 2) Download everything (no running binary is touched yet).
110
+ // 1.5) O que realmente precisa ser (re)instalado?
111
+ //
112
+ // Sem esta comparação, `kyroon update` chamado duas vezes baixava e trocava
113
+ // tudo duas vezes. A referência é o `installed-version.json` de cada
114
+ // componente (mesmo critério do Updater .NET: comparação por SHA256).
115
+ const pending = [];
116
+ const upToDate = [];
117
+ for (const spec of specs) {
118
+ if (!ctx.force && (await isUpToDate(path.join(installRoot, spec.name), spec, infos.get(spec.name)))) {
119
+ upToDate.push(spec);
120
+ }
121
+ else {
122
+ pending.push(spec);
123
+ }
124
+ }
125
+ for (const spec of upToDate) {
126
+ log.success(`${spec.display} já está na v${infos.get(spec.name).versionBuild} — nada a baixar.`);
127
+ }
128
+ throwIfAborted('[1/7] Detecting latest versions');
129
+ // 2) Download apenas do que mudou (no running binary is touched yet).
52
130
  log.step('[2/7] Downloading packages...');
131
+ const needsUpdaterPackage = pending.length > 0 || (await anyUpdaterOutdated(installRoot, upToDate, updaterInfo));
53
132
  let updaterArchive = null;
54
- if (updaterSpec && updaterInfo) {
133
+ if (updaterSpec && updaterInfo && needsUpdaterPackage) {
55
134
  updaterArchive = await downloadAndVerify(updaterInfo, 'updater', downloadsDir);
135
+ await recordDownload(downloadsDir, 'updater', updaterInfo, updaterArchive, updaterSpec.fileType);
56
136
  }
57
137
  const archives = new Map();
58
- for (const spec of specs) {
59
- archives.set(spec.name, await downloadAndVerify(infos.get(spec.name), spec.name, downloadsDir));
138
+ for (const spec of pending) {
139
+ const info = infos.get(spec.name);
140
+ const cached = await findCachedPackage(downloadsDir, spec.name, info);
141
+ if (cached) {
142
+ // Acontece quando uma execução anterior baixou tudo e falhou depois — a
143
+ // segunda tentativa não repete os gigabytes.
144
+ log.info(`${spec.display}: pacote v${cached.versionBuild} já está em downloads/ (${formatBytes(cached.sizeBytes)}).`);
145
+ }
146
+ const file = await downloadAndVerify(info, spec.name, downloadsDir);
147
+ // Índice do cache: permite reaproveitar o pacote e descartar os antigos.
148
+ await recordDownload(downloadsDir, spec.name, info, file, spec.fileType);
149
+ archives.set(spec.name, file);
150
+ }
151
+ if (pending.length === 0)
152
+ log.info('Nenhum pacote para baixar — tudo já está atualizado.');
153
+ throwIfAborted('[2/7] Downloading packages');
154
+ // 3) Stop running processes (e CONFIRMA que saíram da memória).
155
+ //
156
+ // Só quando há algo a trocar: um `update` com tudo em dia não pode derrubar
157
+ // o Worker e o App que o usuário está usando.
158
+ const updaterArchiveForRefresh = updaterSpec && updaterInfo && updaterArchive
159
+ ? { spec: updaterSpec, info: updaterInfo, archive: updaterArchive }
160
+ : null;
161
+ if (pending.length > 0) {
162
+ log.step('[3/7] Stopping running Kyroon processes...');
163
+ await stopKyroonProcesses(platform);
164
+ }
165
+ else {
166
+ log.step('[3/7] Stopping running Kyroon processes...');
167
+ log.info('Nada a substituir — os componentes em execução foram preservados.');
60
168
  }
61
- // 3) Stop running processes.
62
- log.step('[3/7] Stopping running Kyroon processes...');
63
- await stopKyroonProcesses(platform);
64
169
  // 3.5) Ensure Python launcher for the Worker JSONL hooks.
65
170
  if (selected.includes('worker')) {
66
171
  await ensurePythonLauncher(platform).catch((err) => log.warn(`ensurePythonLauncher failed: ${err instanceof Error ? err.message : String(err)}`));
@@ -69,31 +174,60 @@ export async function installComponents(options) {
69
174
  log.step('[4/7] Installing components...');
70
175
  const installed = [];
71
176
  const binByComponent = new Map();
177
+ const failures = [];
72
178
  for (const spec of specs) {
179
+ throwIfAborted('[4/7] Installing components');
73
180
  const info = infos.get(spec.name);
74
181
  const componentDir = path.join(installRoot, spec.name);
75
- log.info(`${spec.display} -> ${componentDir}`);
76
- await cleanComponentDir(componentDir);
77
- await extractArchive(archives.get(spec.name), componentDir, {
78
- strip: stripFor(spec.name, info.fileName, platform),
79
- });
80
- await fs.remove(archives.get(spec.name));
81
- const binary = await locateBinary(componentDir, spec.binary);
82
- if (!binary)
83
- throw new Error(`${spec.binary} not found in ${componentDir} after extraction.`);
84
- await ensureExecutable(platform, binary);
85
- if (updaterSpec && updaterInfo && updaterArchive) {
86
- await installUpdater(componentDir, updaterArchive, updaterInfo, updaterSpec);
87
- }
88
- await writeInstalledVersion(componentDir, spec, info, platform, apiUrl);
89
- installed.push({ name: spec.name, dir: componentDir, binary, version: info.versionBuild });
90
- binByComponent.set(spec.name, binary);
91
- }
92
- if (updaterArchive)
93
- await fs.remove(updaterArchive);
182
+ // Já está na versão mais recente: nada é baixado nem trocado. Ainda assim
183
+ // o updater embutido é conferido — pular o componente não pode congelar o
184
+ // mecanismo que faz as próximas atualizações.
185
+ if (!pending.includes(spec)) {
186
+ try {
187
+ if (updaterArchiveForRefresh)
188
+ await refreshUpdaterIfNeeded(componentDir, updaterArchiveForRefresh);
189
+ const binary = await locateBinary(componentDir, spec.binary);
190
+ if (!binary)
191
+ throw new InstallError(`${spec.binary} não encontrado em ${componentDir}.`);
192
+ installed.push({ name: spec.name, dir: componentDir, binary, version: info.versionBuild, skipped: true });
193
+ binByComponent.set(spec.name, binary);
194
+ }
195
+ catch (err) {
196
+ failures.push({ spec, error: err });
197
+ log.error(`${spec.display}: ${err instanceof Error ? err.message : String(err)}`);
198
+ }
199
+ continue;
200
+ }
201
+ try {
202
+ const outcome = await installOneComponent({
203
+ spec,
204
+ info,
205
+ archive: archives.get(spec.name),
206
+ installRoot,
207
+ platform,
208
+ apiUrl,
209
+ updater: updaterArchiveForRefresh,
210
+ });
211
+ installed.push(outcome);
212
+ binByComponent.set(spec.name, outcome.binary);
213
+ }
214
+ catch (err) {
215
+ // BUG-08: a falha de um componente não pode cancelar os outros — e o
216
+ // usuário precisa saber o que ficou instalado e o que não ficou.
217
+ failures.push({ spec, error: err });
218
+ log.error(`${spec.display}: ${err instanceof Error ? err.message : String(err)}`);
219
+ log.warn(`${spec.display} não foi instalado — seguindo com os demais componentes.`);
220
+ }
221
+ }
222
+ // Os pacotes ficam em `downloads/` para a próxima execução; só as versões
223
+ // antigas são descartadas (senão o cache cresceria para sempre).
224
+ await pruneDownloads(downloadsDir);
225
+ if (failures.length > 0 && installed.length === 0) {
226
+ throw asInstallError(failures[0].error, failures, specs.length, installed.length);
227
+ }
94
228
  // 5) Shortcuts + boot auto-start.
95
229
  log.step('[5/7] Creating shortcuts and boot auto-start...');
96
- if (wantService) {
230
+ if (ctx.wantService) {
97
231
  const targets = [];
98
232
  for (const c of ['app', 'worker']) {
99
233
  const binary = binByComponent.get(c);
@@ -108,9 +242,9 @@ export async function installComponents(options) {
108
242
  // 6) Activation + start.
109
243
  log.step('[6/7] Activation and startup...');
110
244
  await activateAndStart(platform, binByComponent, {
111
- activationCode: options.activationCode,
112
- service: wantService,
113
- start: wantStart,
245
+ activationCode: ctx.activationCode,
246
+ service: ctx.wantService,
247
+ start: ctx.wantStart,
114
248
  });
115
249
  // 7) Verify the install is complete and runnable ("tudo certinho").
116
250
  log.step('[7/7] Verifying installation...');
@@ -118,14 +252,268 @@ export async function installComponents(options) {
118
252
  const problems = await verifyInstall(result, platform);
119
253
  const hard = problems.filter((p) => p.hard);
120
254
  if (hard.length > 0) {
121
- throw new Error(`Install verification failed: ${hard.map((p) => `${p.component} (${p.message})`).join('; ')}`);
255
+ throw new InstallError(`A verificação final falhou: ${hard.map((p) => `${p.component} (${p.message})`).join('; ')}`, { hint: "Execute 'repair' para refazer a instalação dos componentes com problema." });
256
+ }
257
+ if (failures.length > 0) {
258
+ throw asInstallError(failures[0].error, failures, specs.length, installed.length);
122
259
  }
123
- log.banner('Kyroon Enterprise installed!', [
260
+ const changed = installed.filter((c) => !c.skipped);
261
+ log.banner(changed.length === 0 ? 'Kyroon Enterprise já está atualizado!' : 'Kyroon Enterprise installed!', [
124
262
  `Install root : ${installRoot}`,
125
- ...installed.map((c) => `${c.name} : ${c.dir}`),
263
+ ...installed.map((c) => `${c.name} : v${c.version}${c.skipped ? ' (já atualizado)' : ''} — ${c.dir}`),
264
+ ...(log.fileLogPath() ? [`Log : ${log.fileLogPath()}`] : []),
126
265
  ]);
127
266
  return result;
128
267
  }
268
+ /** Consolida as falhas por componente numa mensagem única e acionável. */
269
+ function asInstallError(first, failures, total, ok) {
270
+ const names = failures.map((f) => f.spec.name).join(',');
271
+ return new InstallError(`${ok} de ${total} componentes instalados. Falhou: ${names}.`, {
272
+ cause: first,
273
+ exitCode: first instanceof InstallError ? first.exitCode : undefined,
274
+ hint: first instanceof InstallError && first.hint
275
+ ? first.hint
276
+ : `Execute 'repair -c ${names}' para tentar novamente apenas o que faltou.`,
277
+ });
278
+ }
279
+ async function installOneComponent(args) {
280
+ const { spec, info, archive, installRoot, platform, apiUrl, updater } = args;
281
+ const componentDir = path.join(installRoot, spec.name);
282
+ const staging = path.join(installRoot, `.staging-${spec.name}-${process.pid}`);
283
+ const backup = path.join(installRoot, `.backup-${spec.name}-${process.pid}`);
284
+ log.info(`${spec.display} -> ${componentDir}`);
285
+ // ── Fase 1: montar a nova versão COMPLETA em staging ────────────────────
286
+ // Nada em `componentDir` é tocado aqui. Se qualquer coisa falhar, a
287
+ // instalação atual continua íntegra e funcionando.
288
+ await removeWithRetry(staging, { label: `${spec.name} staging` });
289
+ await fs.ensureDir(staging);
290
+ try {
291
+ await extractArchive(archive, staging, { strip: stripFor(spec.name, info.fileName, platform) });
292
+ const stagedBinary = await locateBinary(staging, spec.binary);
293
+ if (!stagedBinary) {
294
+ throw new InstallError(`O pacote do ${spec.display} não contém ${spec.binary} — instalação abortada sem alterar ${componentDir}.`, { hint: 'Nenhum arquivo foi perdido. Tente novamente; se persistir, informe o suporte.' });
295
+ }
296
+ await ensureExecutable(platform, stagedBinary);
297
+ if (updater) {
298
+ await installUpdater(staging, updater.archive, updater.info, updater.spec);
299
+ }
300
+ else {
301
+ await carryOverUpdater(componentDir, staging);
302
+ }
303
+ // Manifesto definitivo já vai dentro do staging: assim, no instante em que
304
+ // a troca termina, o diretório final já está consistente.
305
+ await writeInstalledVersion(staging, spec, info, platform, apiUrl, 'ok');
306
+ }
307
+ catch (err) {
308
+ await removeQuiet(staging);
309
+ throw err;
310
+ }
311
+ // ── Fase 2: portão antes de tocar no destino ────────────────────────────
312
+ if (await anyProcessHoldingDir(platform, componentDir)) {
313
+ await removeQuiet(staging);
314
+ throw new InstallError(`Não foi possível atualizar ${componentDir}: ainda há processos do Kyroon em execução nessa pasta.`, {
315
+ exitCode: EXIT.LOCKED,
316
+ hint: 'Feche o Kyroon App, o Kyroon Terminal e o Worker (ícone ao lado do relógio), ' +
317
+ 'aguarde 10 segundos e execute o instalador novamente. Nenhum arquivo foi alterado.',
318
+ });
319
+ }
320
+ // ── Fase 3: troca atômica com backup e rollback ─────────────────────────
321
+ const hadPrevious = await fs.pathExists(componentDir);
322
+ if (hadPrevious) {
323
+ // Marca "em transição": se o processo morrer daqui em diante, o estado é
324
+ // DETECTÁVEL (verify/doctor/Updater veem `installing` e mandam reparar) em
325
+ // vez de o manifesto antigo seguir mentindo que está tudo certo.
326
+ await markInstallInProgress(componentDir, spec, info, platform, apiUrl).catch((err) => log.debug(`não foi possível marcar ${spec.name} como 'installing': ${String(err)}`));
327
+ }
328
+ let swapped = false;
329
+ try {
330
+ if (hadPrevious) {
331
+ await removeWithRetry(backup, { label: `${spec.name} backup antigo` });
332
+ await renameWithRetry(componentDir, backup, { label: `${spec.name}: backup` });
333
+ }
334
+ await renameWithRetry(staging, componentDir, { label: `${spec.name}: publicação` });
335
+ swapped = true;
336
+ }
337
+ catch (err) {
338
+ // Rollback: restaura a versão anterior INTEIRA.
339
+ if (hadPrevious && !swapped && (await fs.pathExists(backup))) {
340
+ try {
341
+ await removeWithRetry(componentDir, { attempts: 3 });
342
+ await renameWithRetry(backup, componentDir, { attempts: 8 });
343
+ log.warn(`${spec.display}: alteração revertida — a versão anterior foi preservada.`);
344
+ }
345
+ catch (rollbackErr) {
346
+ log.error(`${spec.display}: FALHA CRÍTICA no rollback — a versão anterior ficou em ${backup}. ` +
347
+ `Detalhe: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`);
348
+ }
349
+ }
350
+ await removeQuiet(staging);
351
+ throw new InstallError(`Falha ao substituir os arquivos do ${spec.display}: ${err instanceof Error ? err.message : String(err)}`, { cause: err, exitCode: EXIT.ROLLBACK });
352
+ }
353
+ await removeQuiet(backup);
354
+ // O pacote NÃO é apagado: fica em `downloads/` para que a próxima execução
355
+ // (`update` rodado de novo, `repair`) não precise baixar tudo outra vez.
356
+ // `pruneDownloads` cuida de descartar as versões antigas.
357
+ const binary = await locateBinary(componentDir, spec.binary);
358
+ if (!binary) {
359
+ throw new InstallError(`${spec.binary} não encontrado em ${componentDir} após a instalação.`, {
360
+ hint: "Execute 'repair' para refazer a instalação deste componente.",
361
+ });
362
+ }
363
+ log.success(`${spec.display} v${info.versionBuild} instalado.`);
364
+ return { name: spec.name, dir: componentDir, binary, version: info.versionBuild };
365
+ }
366
+ // ---------------------------------------------------------------------------
367
+ // "Preciso mesmo mexer neste componente?"
368
+ // ---------------------------------------------------------------------------
369
+ /**
370
+ * `true` quando o componente já está na versão publicada e íntegro.
371
+ *
372
+ * A comparação é por **SHA256** — o mesmo critério do `Kyroon.Updater` (.NET) —
373
+ * e não por número de versão, para que um rebuild da mesma versão também seja
374
+ * detectado. Exige ainda que a instalação tenha terminado (`status !== 'installing'`)
375
+ * e que o executável exista de fato: um manifesto "em dia" apontando para uma
376
+ * pasta mutilada é justamente o cenário que deixava a máquina quebrada em
377
+ * silêncio, e ele tem que resultar em REINSTALAR, não em pular.
378
+ */
379
+ async function isUpToDate(componentDir, spec, info) {
380
+ const manifest = await readInstalledVersion(componentDir);
381
+ if (!manifest)
382
+ return false;
383
+ if (manifest.status === 'installing')
384
+ return false;
385
+ if (manifest.sha256?.toLowerCase() !== info.sha256.toLowerCase())
386
+ return false;
387
+ return (await locateBinary(componentDir, spec.binary)) !== null;
388
+ }
389
+ /** SHA do updater atualmente instalado sob `<componentDir>/updater`. */
390
+ async function installedUpdaterSha(componentDir) {
391
+ try {
392
+ const sentinel = await fs.readJson(path.join(componentDir, 'updater', '.updater-version.json'));
393
+ const sha = sentinel.sha256;
394
+ return typeof sha === 'string' ? sha.toLowerCase() : null;
395
+ }
396
+ catch {
397
+ return null;
398
+ }
399
+ }
400
+ /**
401
+ * Algum componente "em dia" está com um updater desatualizado? Se sim, o pacote
402
+ * do updater precisa ser baixado mesmo sem nenhum componente para trocar —
403
+ * caso contrário pular componentes congelaria o mecanismo de atualização.
404
+ */
405
+ async function anyUpdaterOutdated(installRoot, upToDate, updaterInfo) {
406
+ if (!updaterInfo)
407
+ return false;
408
+ const expected = updaterInfo.sha256.toLowerCase();
409
+ for (const spec of upToDate) {
410
+ if ((await installedUpdaterSha(path.join(installRoot, spec.name))) !== expected)
411
+ return true;
412
+ }
413
+ return false;
414
+ }
415
+ /** Troca o `updater/` de um componente que não foi reinstalado, se estiver velho. */
416
+ async function refreshUpdaterIfNeeded(componentDir, updater) {
417
+ if (!(await fs.pathExists(componentDir)))
418
+ return;
419
+ if ((await installedUpdaterSha(componentDir)) === updater.info.sha256.toLowerCase())
420
+ return;
421
+ // Mesma disciplina do componente: monta ao lado e troca por rename.
422
+ const staging = path.join(componentDir, `.updater-new-${process.pid}`);
423
+ const old = path.join(componentDir, `.updater-old-${process.pid}`);
424
+ const target = path.join(componentDir, 'updater');
425
+ await removeWithRetry(staging);
426
+ try {
427
+ await installUpdater(staging, updater.archive, updater.info, updater.spec, { asDir: true });
428
+ const hadPrevious = await fs.pathExists(target);
429
+ if (hadPrevious)
430
+ await renameWithRetry(target, old);
431
+ try {
432
+ await renameWithRetry(staging, target);
433
+ }
434
+ catch (err) {
435
+ if (hadPrevious)
436
+ await renameWithRetry(old, target).catch(() => { });
437
+ throw err;
438
+ }
439
+ await removeQuiet(old);
440
+ log.info(`Updater atualizado para v${updater.info.versionBuild} em ${componentDir}.`);
441
+ }
442
+ catch (err) {
443
+ await removeQuiet(staging);
444
+ // Updater desatualizado não impede o uso do componente — avisa e segue.
445
+ log.warn(`Não foi possível atualizar o updater em ${componentDir}: ` +
446
+ `${err instanceof Error ? err.message : String(err)}`);
447
+ }
448
+ }
449
+ /**
450
+ * Recupera uma troca interrompida por morte abrupta do processo (queda de
451
+ * energia, kill -9) numa execução ANTERIOR: se sobrou `.backup-<comp>-<pid>` e
452
+ * o diretório do componente não existe, devolve o backup ao lugar.
453
+ */
454
+ async function recoverInterruptedSwaps(installRoot) {
455
+ let entries;
456
+ try {
457
+ entries = await fs.readdir(installRoot);
458
+ }
459
+ catch {
460
+ return;
461
+ }
462
+ // Trocas do `updater/` interrompidas (são internas a cada componente).
463
+ for (const component of ['worker', 'terminal', 'app']) {
464
+ await recoverUpdaterSwap(path.join(installRoot, component));
465
+ }
466
+ for (const entry of entries) {
467
+ const match = /^\.backup-(worker|terminal|app)-\d+$/.exec(entry);
468
+ if (!match) {
469
+ if (/^\.staging-(worker|terminal|app)-\d+$/.test(entry)) {
470
+ await removeQuiet(path.join(installRoot, entry));
471
+ }
472
+ continue;
473
+ }
474
+ const component = match[1];
475
+ const backupDir = path.join(installRoot, entry);
476
+ const componentDir = path.join(installRoot, component);
477
+ if (await fs.pathExists(componentDir)) {
478
+ await removeQuiet(backupDir); // troca concluiu; backup é lixo
479
+ continue;
480
+ }
481
+ try {
482
+ await renameWithRetry(backupDir, componentDir, { label: `recuperar ${component}` });
483
+ log.warn(`${component}: uma instalação anterior foi interrompida no meio da troca — ` +
484
+ 'a versão que estava instalada foi restaurada.');
485
+ }
486
+ catch (err) {
487
+ log.warn(`${component}: não foi possível restaurar automaticamente ${backupDir}: ` +
488
+ `${err instanceof Error ? err.message : String(err)}`);
489
+ }
490
+ }
491
+ }
492
+ /** Idem para a troca isolada do `updater/` dentro de um componente. */
493
+ async function recoverUpdaterSwap(componentDir) {
494
+ let entries;
495
+ try {
496
+ entries = await fs.readdir(componentDir);
497
+ }
498
+ catch {
499
+ return;
500
+ }
501
+ const target = path.join(componentDir, 'updater');
502
+ for (const entry of entries) {
503
+ if (/^\.updater-new-\d+$/.test(entry)) {
504
+ await removeQuiet(path.join(componentDir, entry));
505
+ continue;
506
+ }
507
+ if (!/^\.updater-old-\d+$/.test(entry))
508
+ continue;
509
+ const old = path.join(componentDir, entry);
510
+ if (await fs.pathExists(target)) {
511
+ await removeQuiet(old);
512
+ continue;
513
+ }
514
+ await renameWithRetry(old, target).catch(() => log.warn(`Não foi possível restaurar o updater a partir de ${old}.`));
515
+ }
516
+ }
129
517
  /** Guarantees a POSIX binary is executable (zip extraction can drop the bit). */
130
518
  async function ensureExecutable(platform, binary) {
131
519
  if (platform.os === 'win')
@@ -146,13 +534,13 @@ function dedupeComponents(components) {
146
534
  out.push(c);
147
535
  }
148
536
  if (out.length === 0)
149
- throw new Error('No components selected to install.');
537
+ throw new InstallError('Nenhum componente selecionado para instalar.');
150
538
  return out;
151
539
  }
152
540
  function requireSpec(name, platform) {
153
541
  const spec = resolveComponent(name, platform);
154
542
  if (!spec) {
155
- throw new Error(`Component '${name}' is not distributed for ${platform.slug}.`);
543
+ throw new InstallError(`O componente '${name}' não é distribuído para ${platform.slug}.`);
156
544
  }
157
545
  return spec;
158
546
  }
@@ -164,22 +552,31 @@ function stripFor(name, fileName, platform) {
164
552
  return 0;
165
553
  return 1;
166
554
  }
167
- /** Wipes a component dir but preserves `updater/` and `installed-version.json`. */
168
- async function cleanComponentDir(dir) {
169
- if (!(await fs.pathExists(dir))) {
170
- await fs.ensureDir(dir);
555
+ /**
556
+ * Sem pacote de updater para este RID, preserva o `updater/` já instalado
557
+ * copiando-o para o staging (o swap substitui a pasta inteira, então o que não
558
+ * for carregado junto se perde).
559
+ */
560
+ async function carryOverUpdater(componentDir, staging) {
561
+ const from = path.join(componentDir, 'updater');
562
+ if (!(await fs.pathExists(from)))
171
563
  return;
564
+ try {
565
+ await fs.copy(from, path.join(staging, 'updater'), { overwrite: true, errorOnExist: false });
566
+ log.debug(`updater/ preservado a partir de ${from}`);
172
567
  }
173
- for (const entry of await fs.readdir(dir)) {
174
- if (entry === 'updater' || entry === 'installed-version.json')
175
- continue;
176
- await fs.remove(path.join(dir, entry));
568
+ catch (err) {
569
+ log.warn(`Não foi possível preservar o updater existente: ${err instanceof Error ? err.message : String(err)}`);
177
570
  }
178
571
  }
179
- /** Installs a fresh copy of the native updater under `<componentDir>/updater`. */
180
- async function installUpdater(componentDir, updaterArchive, updaterInfo, updaterSpec) {
181
- const updaterDir = path.join(componentDir, 'updater');
182
- await fs.remove(updaterDir);
572
+ /**
573
+ * Installs a fresh copy of the native updater under `<componentDir>/updater`.
574
+ * Com `asDir`, o primeiro argumento JÁ É o diretório de destino do updater
575
+ * (usado pela troca isolada do `refreshUpdaterIfNeeded`).
576
+ */
577
+ async function installUpdater(componentDir, updaterArchive, updaterInfo, updaterSpec, opts = {}) {
578
+ const updaterDir = opts.asDir ? componentDir : path.join(componentDir, 'updater');
579
+ await removeWithRetry(updaterDir, { label: 'updater' });
183
580
  await fs.ensureDir(updaterDir);
184
581
  await extractArchive(updaterArchive, updaterDir, { strip: isTarball(updaterInfo.fileName) ? 1 : 0 });
185
582
  const bin = await locateBinary(updaterDir, updaterSpec.binary);
@@ -213,16 +610,21 @@ async function activateAndStart(platform, binByComponent, opts) {
213
610
  log.info('Startup skipped.');
214
611
  return;
215
612
  }
216
- if (workerBin) {
613
+ if (workerBin && !(await alreadyRunning(platform, workerBin))) {
217
614
  try {
218
- execa(workerBin, [], { detached: true, stdio: 'ignore', cwd: path.dirname(workerBin) }).unref();
615
+ // Windows: no args -> the Worker opens its System Tray (stays alive and
616
+ // consumes tasks). Linux/macOS: bare invocation only prints help and
617
+ // exits, so it MUST be launched as `run`/daemon to stay alive and pick
618
+ // up tasks (host.WaitForShutdownAsync blocks on SIGINT/SIGTERM).
619
+ const workerArgs = platform.os === 'win' ? [] : ['run'];
620
+ execa(workerBin, workerArgs, { detached: true, stdio: 'ignore', cwd: path.dirname(workerBin) }).unref();
219
621
  }
220
622
  catch (err) {
221
623
  log.warn(`Could not start Worker: ${err instanceof Error ? err.message : String(err)}`);
222
624
  }
223
625
  }
224
626
  const appBin = binByComponent.get('app');
225
- if (appBin) {
627
+ if (appBin && !(await alreadyRunning(platform, appBin))) {
226
628
  try {
227
629
  if (platform.os === 'osx') {
228
630
  // The macOS app is a `.app` bundle (kyroon_app.app) and cannot be
@@ -238,4 +640,16 @@ async function activateAndStart(platform, binByComponent, opts) {
238
640
  }
239
641
  }
240
642
  }
643
+ /**
644
+ * Um componente que não foi substituído continua rodando — relançá-lo abriria
645
+ * uma segunda instância. Só sobe o que está fora do ar.
646
+ */
647
+ async function alreadyRunning(platform, binary) {
648
+ const name = path.basename(binary, path.extname(binary));
649
+ if (await isProcessAlive(platform, name)) {
650
+ log.info(`${name} já está em execução — não será iniciado novamente.`);
651
+ return true;
652
+ }
653
+ return false;
654
+ }
241
655
  //# sourceMappingURL=install.js.map