@danhachuel/jobfinder 0.1.15 → 0.1.17

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/scripts/cli.mjs CHANGED
@@ -1,43 +1,79 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * JobFinder CLI launcher (npx entrypoint).
3
+ * JobFinder CLI launcher (npx entrypoint) — runtime permanente + daemon.
4
4
  *
5
- * Commands:
6
- * jobfinder install create ~/.jobfinder/ skeleton (safe to re-run)
7
- * jobfinder start the local server (backend + UI) on localhost:4040
8
- * jobfinder start alias of the default command
9
- * jobfinder --version print version info
10
- * jobfinder --help print usage
5
+ * ARQUITETURA (0.1.17, espelha o @danhachuel/pandanews):
11
6
  *
12
- * Flags:
13
- * --port <n> override the API/UI port (default: 4040)
14
- * --host <addr> bind address (default: 127.0.0.1)
15
- * --data-dir <path> override the data directory (default: ~/.jobfinder or $JOBFINDER_HOME)
16
- * --open / --no-open open/do not open the browser on start
17
- * --dry-run start with automation in dry-run mode (nothing is really sent)
7
+ * 1. RUNTIME PERMANENTE. O código do servidor é copiado para
8
+ * ~/.jobfinder/runtime (src/server + src/ui/dist + package.json). O
9
+ * Express NUNCA sobe de dentro do cache do npx: no Windows o npx
10
+ * renomeia/limpa esse cache ao final e o Windows devolve EBUSY quando
11
+ * um processo vivo segura arquivos lá dentro — o que derrubava o app.
12
+ *
13
+ * 2. DAEMON. O servidor sobe DESTACADO (detached + windowsHide), com stdio
14
+ * direto no arquivo ~/.jobfinder/jobfinder.log — não herda o console.
15
+ * O terminal volta ao prompt na hora; fechar o MobaXterm/PowerShell não
16
+ * mata o servidor.
17
+ *
18
+ * 3. LOCK DE PID. ~/.jobfinder/jobfinder.pid registra a instância. `stop`
19
+ * encerra por PID (taskkill /PID /T no Windows) e, como rede de
20
+ * segurança, por quem estiver dono da porta.
21
+ *
22
+ * Comandos:
23
+ * jobfinder install cria o esqueleto ~/.jobfinder/ (idempotente)
24
+ * jobfinder inicia em background (daemon) — padrão
25
+ * jobfinder start alias do padrão
26
+ * jobfinder --foreground sobe preso a este terminal (depuração)
27
+ * jobfinder stop | kill encerra o daemon
28
+ * jobfinder --version | --help
18
29
  */
19
30
  import fs from 'node:fs';
20
31
  import path from 'node:path';
21
32
  import os from 'node:os';
22
33
  import process from 'node:process';
23
34
  import { fileURLToPath } from 'node:url';
35
+ import { spawn, spawnSync } from 'node:child_process';
36
+ import { createRequire } from 'node:module';
24
37
 
25
- import { ensureDataDir, resolveDataDir, isDataDirHealthy } from '../src/server/storage/bootstrap.mjs';
26
- import { spawnWorker } from '../src/server/workerRuntime.mjs';
38
+ import { ensureDataDir, isDataDirHealthy } from '../src/server/storage/bootstrap.mjs';
27
39
 
28
- /**
29
- * Process resilience for the launcher — installed before anything else runs
30
- * so the CLI can never vanish silently (terminal back at the prompt with no
31
- * explanation):
32
- *
33
- * 1. unhandledRejection — since Node 15 any unhandled promise rejection
34
- * terminates the process immediately. Log it instead of dying without
35
- * a trace.
36
- * 2. EPIPE on stdio — when the shell behind stdout disappears (Windows
37
- * terminals, MobaXterm, redirection), the next console.log throws an
38
- * unhandled 'error' and kills the launcher.
39
- * 3. uncaughtException — log loudly and exit with a visible reason.
40
- */
40
+ const require = createRequire(import.meta.url);
41
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
42
+ const PKG_ROOT = path.resolve(__dirname, '..');
43
+ const pkg = require('../package.json');
44
+
45
+ const VISUAL_VERSION = pkg.version;
46
+ const NPM_VERSION = String(pkg.version)
47
+ .split('.')
48
+ .map((part) => String(Number(part)))
49
+ .join('.');
50
+
51
+ /* ------------------------------------------------------------------ *
52
+ * Caminhos: lar estável, runtime permanente, lock de PID *
53
+ * ------------------------------------------------------------------ */
54
+
55
+ /** Raiz de instalação estável: JOBFINDER_HOME > JOBFINDER_DATA_DIR > ~/.jobfinder. */
56
+ export function resolveHome() {
57
+ if (process.env.JOBFINDER_HOME) return path.resolve(process.env.JOBFINDER_HOME);
58
+ if (process.env.JOBFINDER_DATA_DIR) return path.resolve(process.env.JOBFINDER_DATA_DIR);
59
+ return path.join(os.homedir(), '.jobfinder');
60
+ }
61
+
62
+ export function runtimeDir(home) {
63
+ return path.join(home, 'runtime');
64
+ }
65
+
66
+ export function serverEntry(home) {
67
+ return path.join(runtimeDir(home), 'src', 'server', 'index.mjs');
68
+ }
69
+
70
+ export function pidFilePath(home) {
71
+ return path.join(home, 'jobfinder.pid');
72
+ }
73
+
74
+ /* ------------------------------------------------------------------ *
75
+ * Resiliência do launcher *
76
+ * ------------------------------------------------------------------ */
41
77
  process.on('unhandledRejection', (reason) => {
42
78
  const message = reason instanceof Error ? reason.message : String(reason);
43
79
  console.error(`[jobfinder] unhandled promise rejection ignored: ${message}`);
@@ -48,291 +84,567 @@ process.on('uncaughtException', (err) => {
48
84
  });
49
85
  for (const stream of [process.stdout, process.stderr]) {
50
86
  stream?.on?.('error', (err) => {
51
- if (err?.code === 'EPIPE') return;
87
+ if (err?.code === 'EPIPE') return; // terminal/pipe fechado: seguir working
52
88
  console.error(`[jobfinder] stdio error: ${err?.code ?? ''} ${err?.message ?? err}`);
53
89
  });
54
90
  }
55
91
 
56
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
57
- const ROOT = path.resolve(__dirname, '..');
58
- const UI_DIST = path.join(ROOT, 'src', 'ui', 'dist');
59
-
60
- const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
61
- const VISUAL_VERSION = pkg.version;
62
- const NPM_VERSION = normalizeNpmVersion(pkg.version);
63
-
64
- /** npm normalizes SemVer: 0.0.01 -> 0.0.1, 0.1.00 -> 0.1.0 */
65
- function normalizeNpmVersion(v) {
66
- return v
67
- .split('.')
68
- .map((part) => String(Number(part)))
69
- .join('.');
70
- }
71
-
92
+ /* ------------------------------------------------------------------ *
93
+ * USO *
94
+ * ------------------------------------------------------------------ */
72
95
  const USAGE = `
73
96
  JobFinder — LinkedIn automation platform
74
97
 
75
- Usage:
76
- jobfinder install Create the JSON data store (~/.jobfinder/)
77
- jobfinder [start] [flags] Start the app at http://localhost:4040
78
- jobfinder --version Show version
79
- jobfinder --help Show this help
98
+ Uso:
99
+ jobfinder install Cria o esqueleto JSON em ~/.jobfinder/ (idempotente)
100
+ jobfinder Inicia o servidor EM BACKGROUND (daemon)
101
+ jobfinder start Alias do padrão
102
+ jobfinder --foreground Sobe preso a este terminal (para depuração)
103
+ jobfinder stop | kill Encerra o daemon em background
80
104
 
81
- Flags:
82
- --port <n> Port to listen on (default 4040)
83
- --host <addr> Bind address (default 127.0.0.1)
84
- --data-dir <path> Data directory (default ~/.jobfinder, override with JOBFINDER_HOME)
85
- --dry-run Run with automations in dry-run mode (no real LinkedIn actions)
105
+ Opcoes:
106
+ --port <n> Porta (padrão 4040)
107
+ --host <addr> Endereço (padrão 127.0.0.1)
108
+ --data-dir <path> Diretório de dados (padrão ~/.jobfinder)
109
+ --dry-run Força o modo dry-run (nenhuma ação real no LinkedIn)
110
+ --foreground Não destaca: prende o servidor a este terminal
111
+ --help Mostra esta ajuda
112
+ --version Mostra a versão
86
113
 
87
- Install commands (canonical npm version):
114
+ Instalação (versão canônica do npm):
88
115
  npx --yes @danhachuel/jobfinder@${NPM_VERSION} install
89
116
  npx --yes @danhachuel/jobfinder@${NPM_VERSION}
117
+
118
+ Recomendado no Windows (evita o EBUSY do npx, que limpa o próprio cache):
119
+ npm install -g @danhachuel/jobfinder@latest
90
120
  `;
91
121
 
92
- function parseArgs(argv) {
93
- const args = { command: null, port: null, host: null, dataDir: null, dryRun: false };
94
- const rest = [...argv];
95
- const first = rest[0];
96
- if (first && !first.startsWith('-')) {
97
- args.command = first;
98
- rest.shift();
99
- }
100
- for (let i = 0; i < rest.length; i += 1) {
101
- const token = rest[i];
102
- switch (token) {
103
- case '--port':
104
- args.port = Number(rest[i + 1]);
105
- i += 1;
106
- break;
107
- case '--host':
108
- args.host = rest[i + 1];
109
- i += 1;
110
- break;
111
- case '--data-dir':
112
- args.dataDir = rest[i + 1];
113
- i += 1;
114
- break;
115
- // Deprecated no-ops: the browser is never opened automatically.
116
- // The flags are still accepted so existing commands keep working.
117
- case '--open':
118
- case '--no-open':
119
- break;
120
- case '--dry-run':
121
- args.dryRun = true;
122
- break;
123
- case '--help':
124
- case '-h':
125
- args.command = 'help';
126
- break;
127
- case '--version':
128
- case '-v':
129
- args.command = 'version';
130
- break;
131
- default:
132
- if (token.startsWith('-')) {
133
- console.warn(`[jobfinder] ignoring unknown flag: ${token}`);
134
- }
135
- break;
122
+ /** Copia uma pasta sem node_modules (runtime enxuto). */
123
+ function copyTree(from, to) {
124
+ fs.mkdirSync(to, { recursive: true });
125
+ for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
126
+ if (entry.name === 'node_modules' || entry.name === '.git') continue;
127
+ const src = path.join(from, entry.name);
128
+ const dest = path.join(to, entry.name);
129
+ if (entry.isDirectory()) {
130
+ copyTree(src, dest);
131
+ } else {
132
+ fs.copyFileSync(src, dest);
136
133
  }
137
134
  }
138
- return args;
139
135
  }
140
136
 
141
- function printBanner() {
142
- const line = '-'.repeat(58);
143
- console.log(line);
144
- console.log(` JobFinder v${VISUAL_VERSION} (npm: ${NPM_VERSION})`);
145
- console.log(' LinkedIn Automation • Intelligent Workflows');
146
- console.log(line);
147
- }
137
+ /**
138
+ * RUNTIME PERMANENTE: copia src/server + src/ui/dist para ~/.jobfinder/runtime
139
+ * e instala lá as dependências de produção. Só repovoa quando falta o
140
+ * entrypoint ou quando a versão mudou.
141
+ *
142
+ * As dependências são instaladas DENTRO do runtime (nunca um symlink/junction
143
+ * para o cache do npx): é isso que garante que o daemon não segure arquivos
144
+ * dentro do cache — a causa raiz do EBUSY no Windows.
145
+ *
146
+ * @param {string} home raiz estável
147
+ * @returns {string} caminho do servidor a executar
148
+ */
149
+ export function setupRuntime(home) {
150
+ const dest = runtimeDir(home);
151
+ const entry = serverEntry(home);
152
+ const haveVersion = fs.existsSync(path.join(dest, '.version'))
153
+ ? fs.readFileSync(path.join(dest, '.version'), 'utf8').trim()
154
+ : '';
155
+ const missing = !fs.existsSync(entry);
148
156
 
149
- function commandInstall({ dataDir }) {
150
- const resolved = resolveDataDir(dataDir);
151
- printBanner();
152
- const report = ensureDataDir(resolved);
153
- console.log(` Data directory: ${resolved}`);
154
- if (report.created.length) {
155
- console.log(` Created: ${report.created.join(', ')}`);
156
- } else {
157
- console.log(' Already initialized — no files were changed.');
158
- }
159
- if (!isDataDirHealthy(resolved)) {
160
- console.error('[jobfinder] data directory is incomplete. Check permissions and try again.');
161
- process.exitCode = 1;
162
- return;
157
+ if (missing || haveVersion !== VISUAL_VERSION) {
158
+ if (missing) {
159
+ console.log('Preparando o runtime permanente (~/.jobfinder/runtime) — o servidor não roda mais do cache do npx...');
160
+ } else {
161
+ console.log(`Runtime defasado (${haveVersion || 'sem versão'} -> ${VISUAL_VERSION}) — atualizando a cópia...`);
162
+ }
163
+ const tmp = `${dest}.tmp-${process.pid}`;
164
+ fs.rmSync(tmp, { recursive: true, force: true });
165
+ fs.mkdirSync(path.join(tmp, 'src'), { recursive: true });
166
+ // Apenas o necessário ao servidor Express: código + UI buildada.
167
+ copyTree(path.join(PKG_ROOT, 'src', 'server'), path.join(tmp, 'src', 'server'));
168
+ const uiDist = path.join(PKG_ROOT, 'src', 'ui', 'dist');
169
+ if (fs.existsSync(uiDist)) {
170
+ copyTree(uiDist, path.join(tmp, 'src', 'ui', 'dist'));
171
+ }
172
+ // package.json enxuto: só o que o servidor precisa. Sem pm2 (ferramenta do
173
+ // launcher, não do runtime) e sem devDependencies.
174
+ const runtimePkg = {
175
+ name: pkg.name,
176
+ version: VISUAL_VERSION,
177
+ private: true,
178
+ type: 'module',
179
+ dependencies: { ...(pkg.dependencies ?? {}) },
180
+ // playwright continua opcional: só o Easy Apply ao vivo o usa.
181
+ ...(pkg.optionalDependencies?.playwright
182
+ ? { optionalDependencies: { playwright: pkg.optionalDependencies.playwright } }
183
+ : {}),
184
+ };
185
+ fs.writeFileSync(path.join(tmp, 'package.json'), `${JSON.stringify(runtimePkg, null, 2)}\n`, 'utf8');
186
+ fs.writeFileSync(path.join(tmp, '.version'), `${VISUAL_VERSION}\n`, 'utf8');
187
+ // Swap atômico: no Windows, rename sobre destino existente falha (EPERM).
188
+ fs.rmSync(dest, { recursive: true, force: true });
189
+ fs.renameSync(tmp, dest);
190
+ console.log(`Código copiado para ${dest}`);
191
+
192
+ installRuntimeDependencies(dest);
193
+ console.log(`Runtime pronto em ${dest}`);
163
194
  }
164
- console.log('\nNext steps:');
165
- console.log(` 1. Connect LinkedIn in the app (Integracoes) — official API or cookies.txt fallback`);
166
- console.log(` 2. Pick an LLM provider (OpenAI, Anthropic, DeepSeek or local Ollama) in Config`);
167
- console.log(` 3. Start the app: npx --yes @danhachuel/jobfinder@${NPM_VERSION}`);
195
+
196
+ return entry;
168
197
  }
169
198
 
170
- async function commandStart({ port, host, dataDir, dryRun }) {
171
- const resolved = resolveDataDir(dataDir);
172
- ensureDataDir(resolved);
199
+ /** Instala as dependências de produção dentro do runtime (silencioso). */
200
+ function installRuntimeDependencies(runtimeRoot) {
201
+ const modules = path.join(runtimeRoot, 'node_modules');
202
+ if (fs.existsSync(path.join(modules, 'express', 'package.json'))) return true;
173
203
 
174
- if (!fs.existsSync(path.join(UI_DIST, 'index.html'))) {
175
- console.warn(
176
- '[jobfinder] UI build not found (src/ui/dist). The API will run, but the UI will be blank.\n' +
177
- ' Build it with: npm run build (requires the UI dependencies installed)'
204
+ console.log('Instalando dependências do runtime (express, mammoth, pdfjs-dist)...');
205
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
206
+ const { NODE_OPTIONS: _appPreloads, ...cleanEnv } = process.env;
207
+ const result = spawnSync(
208
+ npm,
209
+ ['install', '--prefix', runtimeRoot, '--omit=dev', '--no-audit', '--no-fund', '--no-save', '--loglevel=error'],
210
+ // `shell: true` é obrigatório no Windows: .cmd/.bat não executam sem ele
211
+ // desde o Node 18.20 (spawn falha com EINVAL).
212
+ {
213
+ windowsHide: true,
214
+ shell: process.platform === 'win32',
215
+ stdio: ['ignore', 'pipe', 'pipe'],
216
+ encoding: 'utf8',
217
+ env: cleanEnv,
218
+ }
219
+ );
220
+ if (result.error || result.status !== 0) {
221
+ // Falha aqui é fatal: sem dependências o servidor não sobe. Melhor
222
+ // abortar com mensagem clara do que spawnar um processo que vai morrer.
223
+ throw new Error(
224
+ `falha ao instalar as dependências do runtime: ${(result.error?.message ?? result.stderr ?? result.stdout ?? '').trim()
225
+ .split('\n')
226
+ .slice(0, 3)
227
+ .join(' ')} (instale manualmente: npm install --prefix ${runtimeRoot})`
178
228
  );
179
229
  }
230
+ return true;
231
+ }
180
232
 
181
- printBanner();
182
- const listenPort = port || Number(process.env.JOBFINDER_PORT) || 4040;
183
- const listenHost = host || process.env.JOBFINDER_HOST || '127.0.0.1';
184
- const url = `http://${listenHost === '0.0.0.0' ? 'localhost' : listenHost}:${listenPort}`;
185
- console.log(` Data directory : ${resolved}`);
186
- console.log(` Mode : ${dryRun ? 'DRY-RUN (no real actions are sent)' : 'live'}`);
187
- console.log(` URL : ${url}`);
188
- console.log(' Press Ctrl+C to stop.\n');
189
-
190
- // ------------------------------------------------------------------ *
191
- // ARCHITECTURE (0.1.13): the Express server runs INSIDE this process.
192
- //
193
- // `start()` imports src/server/index.mjs in-process and app.listen()
194
- // opens a real TCP socket on 4040. A listening server socket keeps the
195
- // Node event loop open MATHEMATICALLY — nothing about the terminal
196
- // (MobaXterm, the npx wrapper, output redirection, closed pipes) can
197
- // empty the loop and take the process down anymore. The worker stays a
198
- // separate child so its heavy tasks never block the server.
199
- // ------------------------------------------------------------------ *
200
- process.env.JOBFINDER_DATA_DIR = resolved;
201
- process.env.JOBFINDER_PORT = String(listenPort);
202
- process.env.JOBFINDER_HOST = listenHost;
203
- // Version: read from THIS file's package.json (never cwd) and handed to the
204
- // server via env. Under npx the cwd is the user's directory, so a server
205
- // that read its own version from cwd would print 0.0.00.
206
- process.env.JOBFINDER_VERSION = VISUAL_VERSION;
207
- if (dryRun) process.env.JOBFINDER_DRY_RUN = '1';
208
-
209
- // Supervisão do worker. O CLI NUNCA depende do worker para viver: ele
210
- // roda com stdio ['ignore','ignore','ignore'] (logs em arquivo) e, se
211
- // morrer, o launcher apenas registra e reinicia — o servidor segue.
212
- let worker = null;
213
- let workerRestarts = 0;
214
- let stopping = false;
215
- let serverRef = null;
216
-
217
- const stopChildren = () => {
218
- if (worker && worker.exitCode === null && worker.signalCode === null) {
219
- worker.kill('SIGTERM');
220
- // Hard deadline: a worker that ignores SIGTERM must not linger.
221
- setTimeout(() => {
222
- if (worker.exitCode === null && worker.signalCode === null) worker.kill('SIGKILL');
223
- }, 2000).unref();
224
- }
225
- };
233
+ /** Entrypoint a executar: runtime permanente (padrão) ou o próprio pacote (dev). */
234
+ export function resolveServerEntry(home) {
235
+ if (process.env.JOBFINDER_NO_RUNTIME === '1' && fs.existsSync(path.join(PKG_ROOT, 'src', 'server', 'index.mjs'))) {
236
+ return path.join(PKG_ROOT, 'src', 'server', 'index.mjs');
237
+ }
238
+ return setupRuntime(home);
239
+ }
240
+
241
+ /** PID vivo? (EPERM = vivo, mas de outro usuário). */
242
+ function isAlive(pid) {
243
+ if (!pid || !Number.isInteger(Number(pid)) || Number(pid) <= 0) return false;
244
+ try {
245
+ process.kill(Number(pid), 0);
246
+ return true;
247
+ } catch (err) {
248
+ return err?.code === 'EPERM';
249
+ }
250
+ }
226
251
 
227
- const startWorker = () => {
228
- // JOBFINDER_TAKEOVER: o launcher acabou de subir (o supervisor anterior
229
- // já se foi) ou observou a saída do worker — heartbeat velha não pode
230
- // bloquear este spawn.
231
- worker = spawnWorker({ env: { JOBFINDER_DATA_DIR: resolved, JOBFINDER_TAKEOVER: '1' } });
232
- worker.on('exit', (code, signal) => {
233
- const reason = signal ? `signal ${signal}` : `code ${code}`;
234
- console.error(`\n[jobfinder] worker encerrou (${reason}). O servidor web continua rodando.`);
235
- const serverAlive = Boolean(serverRef?.listening);
236
- if (!stopping && serverAlive && workerRestarts < 5) {
237
- workerRestarts += 1;
238
- console.error(`[jobfinder] reiniciando o worker (tentativa ${workerRestarts}/5)...`);
239
- // Re-check `stopping`: um shutdown que começa enquanto este timer
240
- // está pendente nunca pode deixar um órfão para trás.
241
- setTimeout(() => {
242
- if (!stopping) startWorker();
243
- }, 3000);
252
+ /** Mata a árvore de processos por PID — sempre em silêncio (sem janela). */
253
+ export function killTree(pid) {
254
+ if (!isAlive(pid)) return;
255
+ try {
256
+ if (process.platform === 'win32') {
257
+ spawnSync('taskkill', ['/pid', String(pid), '/f', '/t'], {
258
+ windowsHide: true, // CREATE_NO_WINDOW — sem tela preta
259
+ detached: true, // grupo isolado, imune a Ctrl+C do console
260
+ stdio: 'ignore', // taskkill não escreve no terminal
261
+ });
262
+ } else {
263
+ try {
264
+ process.kill(-Number(pid), 'SIGKILL'); // grupo: mata os filhos também
265
+ } catch {
266
+ process.kill(Number(pid), 'SIGTERM');
244
267
  }
268
+ }
269
+ } catch {
270
+ /* processo já não existia */
271
+ }
272
+ }
273
+
274
+ /** Descobre o PID dono de uma porta em LISTEN (Windows: netstat; Unix: null). */
275
+ function pidOfPort(port) {
276
+ if (process.platform !== 'win32') return null;
277
+ try {
278
+ const result = spawnSync('netstat', ['-ano'], {
279
+ windowsHide: true,
280
+ detached: true,
281
+ stdio: ['ignore', 'pipe', 'ignore'],
245
282
  });
246
- return worker;
247
- };
283
+ if (result.status !== 0 || !result.stdout) return null;
284
+ const target = `:${port}`;
285
+ for (const line of result.stdout.toString().split(/\r?\n/)) {
286
+ if (!line.includes(target) || !/LISTENING/i.test(line)) continue;
287
+ const columns = line.trim().split(/\s+/);
288
+ const pid = Number(columns[columns.length - 1]);
289
+ if (Number.isInteger(pid) && pid > 0) return pid;
290
+ }
291
+ } catch {
292
+ /* netstat indisponível — seguimos sem a rede de segurança */
293
+ }
294
+ return null;
295
+ }
248
296
 
249
- // Keep-alive inquebrável: timer de 24h SEM unref. Segurança extra — o
250
- // socket do servidor (abaixo) já é a garantia principal. Nunca use unref()
251
- // aqui: um timer solto é o que permite o loop esvaziar e o processo sumir.
252
- const keepAliveTimer = setInterval(() => {}, 24 * 60 * 60 * 1000);
253
-
254
- // Forensic trail: se o launcher morrer, o motivo fica visível. `beforeExit`
255
- // avisa ANTES de o loop esvaziar (com os handles ativos) e permite re-armar
256
- // o keep-alive; `exit` registra o código final.
257
- process.on('beforeExit', (code) => {
258
- const handles = process.getActiveResourcesInfo?.() ?? [];
259
- console.error(
260
- `[jobfinder] launcher: event loop esvaziando (beforeExit code=${code}) — ` +
261
- `handles: ${handles.join(', ') || 'NENHUM'}`
297
+ /** Lê o lock de PID (corrompido nunca impede o arranque). */
298
+ export function readPidLock(home) {
299
+ try {
300
+ const data = JSON.parse(fs.readFileSync(pidFilePath(home), 'utf8'));
301
+ if (!data || typeof data !== 'object') return null;
302
+ return {
303
+ pid: Number.isInteger(data.pid) ? data.pid : null,
304
+ port: Number.isInteger(data.port) ? data.port : null,
305
+ version: typeof data.version === 'string' ? data.version : null,
306
+ };
307
+ } catch {
308
+ return null;
309
+ }
310
+ }
311
+
312
+ function writePidLock(home, pid, port) {
313
+ try {
314
+ fs.writeFileSync(
315
+ pidFilePath(home),
316
+ `${JSON.stringify({ pid, port, version: VISUAL_VERSION, criado: new Date().toISOString() }, null, 2)}\n`,
317
+ 'utf8'
262
318
  );
263
- if (!stopping) {
264
- console.error('[jobfinder] launcher: re-armando o keep-alive para nao voltar ao prompt.');
265
- clearInterval(keepAliveTimer);
266
- setInterval(() => {}, 24 * 60 * 60 * 1000);
319
+ } catch {
320
+ /* lock é melhor esforço — nunca derruba o arranque */
321
+ }
322
+ }
323
+
324
+ export function clearPidLock(home) {
325
+ try {
326
+ fs.unlinkSync(pidFilePath(home));
327
+ } catch {
328
+ /* já removido */
329
+ }
330
+ }
331
+
332
+ /**
333
+ * Mata instâncias anteriores antes de subir uma nova: PIDs do lock + quem
334
+ * estiver dono da porta (o lock pode ficar obsoleto se o processo foi morto
335
+ * externamente). Sem isso cada start empilhava outro servidor zombie e a
336
+ * UI nova era servida por um backend de versão velha.
337
+ */
338
+ export async function killPreviousInstances(home, port) {
339
+ let killed = 0;
340
+ const lock = readPidLock(home);
341
+ if (lock?.pid && lock.pid !== process.pid && isAlive(lock.pid)) {
342
+ killTree(lock.pid);
343
+ killed += 1;
344
+ }
345
+ const owner = pidOfPort(port);
346
+ if (owner && owner !== process.pid) {
347
+ killTree(owner);
348
+ killed += 1;
349
+ }
350
+ if (killed > 0) {
351
+ console.log(`Encerrando instância anterior (${killed} processo(s))...`);
352
+ // 1s para o SO liberar arquivos e portas — sem isso o bind pode falhar.
353
+ await new Promise((resolve) => setTimeout(resolve, 1000));
354
+ }
355
+ clearPidLock(home);
356
+ return killed;
357
+ }
358
+
359
+ /* ------------------------------------------------------------------ *
360
+ * Health poll *
361
+ * ------------------------------------------------------------------ */
362
+ async function waitHealth(port, attempts = 40, intervalMs = 500) {
363
+ for (let i = 0; i < attempts; i += 1) {
364
+ try {
365
+ const res = await fetch(`http://127.0.0.1:${port}/api/health`);
366
+ if (res.ok) return true;
367
+ } catch {
368
+ /* ainda subindo */
267
369
  }
370
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
371
+ }
372
+ return false;
373
+ }
374
+
375
+ /* ------------------------------------------------------------------ *
376
+ * Comandos *
377
+ * ------------------------------------------------------------------ */
378
+ function commandInstall({ dataDir }) {
379
+ const home = resolveHome();
380
+ fs.mkdirSync(home, { recursive: true });
381
+ ensureDataDir(home);
382
+ console.log(` Diretório de dados: ${home}`);
383
+ if (!isDataDirHealthy(home)) {
384
+ console.error('[jobfinder] diretório de dados incompleto. Verifique permissões e tente novamente.');
385
+ process.exitCode = 1;
386
+ return;
387
+ }
388
+ console.log('\nPróximos passos:');
389
+ console.log(` 1. Iniciar: npx --yes @danhachuel/jobfinder@${NPM_VERSION}`);
390
+ console.log(` 2. Abrir: http://127.0.0.1:4040`);
391
+ console.log(` 3. Parar: npx --yes @danhachuel/jobfinder@${NPM_VERSION} stop`);
392
+ }
393
+
394
+ /**
395
+ * Sobe o servidor EM BACKGROUND (daemon), a partir do runtime permanente.
396
+ * O terminal volta ao prompt — é o comportamento correto de um daemon.
397
+ */
398
+ async function commandDaemon(args) {
399
+ const home = resolveHome();
400
+ fs.mkdirSync(home, { recursive: true });
401
+ ensureDataDir(home);
402
+
403
+ const port = args.port || Number(process.env.JOBFINDER_PORT) || 4040;
404
+ const host = args.host || process.env.JOBFINDER_HOST || '127.0.0.1';
405
+ const logFile = path.join(home, 'jobfinder.log');
406
+
407
+ // Runtime permanente: sem ele o servidor não sobe (e não vale a pena
408
+ // spawnar um processo que morreria em seguida).
409
+ let entry;
410
+ try {
411
+ entry = resolveServerEntry(home);
412
+ } catch (err) {
413
+ console.error(`[jobfinder] ${err?.message ?? err}`);
414
+ process.exit(1);
415
+ return;
416
+ }
417
+
418
+ await killPreviousInstances(home, port);
419
+
420
+ console.log(` Iniciando o JobFinder em background (porta ${port})...`);
421
+ console.log(` Log: ${logFile}`);
422
+
423
+ // stdio por FD (obrigatório com detached no Windows) — direto no arquivo,
424
+ // NUNCA herdando o console: um terminal hostil não pode perturbar o daemon.
425
+ const logFd = fs.openSync(logFile, 'a');
426
+ const child = spawn(process.execPath, [entry], {
427
+ detached: true, // CREATE_NEW_PROCESS_GROUP: imune a Ctrl+C do console
428
+ windowsHide: true, // sem janela de console fantasma
429
+ creationFlags: process.platform === 'win32' ? 0x00000200 : 0,
430
+ stdio: ['ignore', logFd, logFd],
431
+ env: {
432
+ ...process.env,
433
+ JOBFINDER_HOME: home,
434
+ JOBFINDER_DATA_DIR: home,
435
+ JOBFINDER_PORT: String(port),
436
+ JOBFINDER_HOST: host,
437
+ JOBFINDER_MODE: 'daemon',
438
+ JOBFINDER_VERSION: VISUAL_VERSION,
439
+ ...(args.dryRun ? { JOBFINDER_DRY_RUN: '1' } : {}),
440
+ ...(process.env.JOBFINDER_NO_WORKER ? { JOBFINDER_NO_WORKER: process.env.JOBFINDER_NO_WORKER } : {}),
441
+ },
268
442
  });
269
- process.on('exit', (code) => {
270
- console.error(`[jobfinder] launcher exiting with code ${code}.`);
271
- });
443
+ fs.closeSync(logFd); // o filho tem a sua própria cópia herdada
444
+ child.unref(); // o launcher pode morrer sem levar o servidor junto
272
445
 
273
- // Sinais: o primeiro encerra o worker e deixa o shutdown gracioso do
274
- // servidor (registrado dentro de start(), abaixo) rodar; o segundo força.
275
- const forward = (signal) => () => {
276
- if (stopping) {
277
- process.exit(1);
278
- }
279
- stopping = true;
280
- stopChildren();
281
- };
282
- process.on('SIGINT', forward('SIGINT'));
283
- process.on('SIGTERM', forward('SIGTERM'));
284
- // Windows-only (Ctrl+Break) — harmless no-op on other platforms.
285
- process.on('SIGBREAK', forward('SIGBREAK'));
446
+ if (!child.pid) {
447
+ console.error('[jobfinder] falha ao iniciar o servidor em background.');
448
+ clearPidLock(home);
449
+ process.exit(1);
450
+ }
451
+ writePidLock(home, child.pid, port);
286
452
 
287
- // No auto-open: the terminal prints the URL and waits for the user.
288
- // Opening a browser window on the user's machine without being asked
289
- // is not acceptable for a hosted (SaaS) product.
453
+ const up = await waitHealth(port);
454
+ const shown = host === '0.0.0.0' ? 'localhost' : host;
455
+ if (up) {
456
+ console.log('');
457
+ console.log(`JobFinder iniciado em background (PID: ${child.pid}). Acesse http://${shown}:${port}`);
458
+ console.log(`Para encerrar: npx --yes @danhachuel/jobfinder@${NPM_VERSION} stop`);
459
+ return;
460
+ }
461
+ console.error('');
462
+ console.error(`O servidor não respondeu em http://${shown}:${port}/api/health.`);
463
+ console.error(`Diagnóstico completo em: ${logFile}`);
464
+ process.exit(1);
465
+ }
466
+
467
+ /**
468
+ * Foreground (depuração): sobe o servidor do runtime preso a este terminal,
469
+ * com a saída encaminhada por pipe (nunca `inherit`).
470
+ */
471
+ async function commandForeground(args) {
472
+ const home = resolveHome();
473
+ fs.mkdirSync(home, { recursive: true });
474
+ ensureDataDir(home);
290
475
 
291
- // Sobe o servidor Express NO PRÓPRIO PROCESSO (dinâmico: mantém --help,
292
- // --version e install leves, sem carregar o Express).
476
+ const port = args.port || Number(process.env.JOBFINDER_PORT) || 4040;
477
+ const host = args.host || process.env.JOBFINDER_HOST || '127.0.0.1';
478
+ let entry;
293
479
  try {
294
- const { start } = await import('../src/server/index.mjs');
295
- ({ server: serverRef } = await start());
480
+ entry = resolveServerEntry(home);
296
481
  } catch (err) {
297
- console.error('[jobfinder] falha ao iniciar o servidor:', err?.message ?? err);
298
- stopChildren();
482
+ console.error(`[jobfinder] ${err?.message ?? err}`);
299
483
  process.exit(1);
484
+ return;
485
+ }
486
+
487
+ console.log(` JobFinder v${VISUAL_VERSION} (npm: ${NPM_VERSION}) — modo foreground (depuração)`);
488
+ console.log(` Servidor: ${entry}`);
489
+ console.log(` URL : http://${host === '0.0.0.0' ? 'localhost' : host}:${port}`);
490
+ console.log(' Pressione Ctrl+C para encerrar.\n');
491
+
492
+ const child = spawn(process.execPath, [entry], {
493
+ windowsHide: true,
494
+ creationFlags: process.platform === 'win32' ? 0x00000200 : 0,
495
+ stdio: ['ignore', 'pipe', 'pipe'],
496
+ env: {
497
+ ...process.env,
498
+ JOBFINDER_HOME: home,
499
+ JOBFINDER_DATA_DIR: home,
500
+ JOBFINDER_PORT: String(port),
501
+ JOBFINDER_HOST: host,
502
+ JOBFINDER_MODE: 'foreground',
503
+ JOBFINDER_VERSION: VISUAL_VERSION,
504
+ ...(args.dryRun ? { JOBFINDER_DRY_RUN: '1' } : {}),
505
+ ...(process.env.JOBFINDER_NO_WORKER ? { JOBFINDER_NO_WORKER: process.env.JOBFINDER_NO_WORKER } : {}),
506
+ },
507
+ });
508
+
509
+ child.stdout.on('data', (chunk) => process.stdout.write(chunk));
510
+ child.stderr.on('data', (chunk) => process.stderr.write(chunk));
511
+ child.stdout.on('error', (err) => err?.code !== 'EPIPE' && console.error('[jobfinder] stdout', err?.message));
512
+ child.stderr.on('error', (err) => err?.code !== 'EPIPE' && console.error('[jobfinder] stderr', err?.message));
513
+
514
+ let stopping = false;
515
+ const stopChild = (signal) => () => {
516
+ if (stopping) process.exit(1); // segundo Ctrl+C força
517
+ stopping = true;
518
+ killTree(child.pid);
519
+ setTimeout(() => process.exit(0), 2000).unref();
520
+ };
521
+ process.on('SIGINT', stopChild('SIGINT'));
522
+ process.on('SIGTERM', stopChild('SIGTERM'));
523
+ process.on('SIGBREAK', stopChild('SIGBREAK'));
524
+
525
+ // Âncora inquebrável do launcher: o filho NÃO é detached, mas ainda assim
526
+ // garantimos um handle ativo (runtime-guard).
527
+ setInterval(() => {}, 2147483647);
528
+
529
+ const exit = await new Promise((resolve) => {
530
+ child.on('exit', (code, signal) => resolve({ code, signal }));
531
+ });
532
+ console.error(`[jobfinder] servidor encerrou (${exit.signal ? `signal ${exit.signal}` : `code ${exit.code}`}).`);
533
+ clearPidLock(home);
534
+ process.exit(exit.code ?? (exit.signal ? 1 : 0));
535
+ }
536
+
537
+ /** Encerra o daemon: lock de PID + dono da porta (rede de segurança). */
538
+ async function commandStop() {
539
+ const home = resolveHome();
540
+ const lock = readPidLock(home);
541
+ // Porta: env > lock > padrão (o lock sabe em qual porta a instância subiu).
542
+ const port = Number(process.env.JOBFINDER_PORT) || lock?.port || 4040;
543
+ let killed = 0;
544
+
545
+ const candidates = [lock?.pid, pidOfPort(port)].filter((pid) => pid && pid !== process.pid);
546
+ for (const pid of candidates) {
547
+ if (isAlive(pid)) {
548
+ killTree(pid);
549
+ killed += 1;
550
+ }
300
551
  }
301
552
 
302
- if (process.env.JOBFINDER_NO_WORKER === '1') {
303
- console.log(' Worker : disabled (JOBFINDER_NO_WORKER=1)');
304
- } else {
305
- startWorker();
306
- console.log(` Worker : automação em segundo plano (pid ${worker.pid})`);
553
+ // Confirma que a porta deixou de responder antes de declarar vitória.
554
+ const down = await new Promise(async (resolve) => {
555
+ for (let i = 0; i < 20; i += 1) {
556
+ let up = false;
557
+ try {
558
+ up = (await fetch(`http://127.0.0.1:${port}/api/health`)).ok;
559
+ } catch {
560
+ up = false;
561
+ }
562
+ if (!up) return resolve(true);
563
+ await new Promise((r) => setTimeout(r, 300));
564
+ }
565
+ resolve(false);
566
+ });
567
+
568
+ clearPidLock(home);
569
+ if (killed > 0 || down) {
570
+ console.log(`JobFinder encerrado (${killed || 1} processo(s)).`);
571
+ return;
307
572
  }
573
+ console.log('Nenhuma instância do JobFinder em execução.');
308
574
  }
309
575
 
310
- function commandVersion() {
311
- console.log(`JobFinder v${VISUAL_VERSION} (npm: ${NPM_VERSION})`);
312
- console.log(`os: ${os.type()} ${os.arch()} • node: ${process.version}`);
576
+ /* ------------------------------------------------------------------ *
577
+ * Argumentos *
578
+ * ------------------------------------------------------------------ */
579
+ function parseArgs(argv) {
580
+ const args = {
581
+ command: null,
582
+ foreground: false,
583
+ port: null,
584
+ host: null,
585
+ dataDir: null,
586
+ dryRun: false,
587
+ help: false,
588
+ version: false,
589
+ };
590
+ const rest = [...argv];
591
+ const first = rest[0];
592
+ if (first && !first.startsWith('-')) {
593
+ args.command = first;
594
+ rest.shift();
595
+ }
596
+ for (let i = 0; i < rest.length; i += 1) {
597
+ const token = rest[i];
598
+ switch (token) {
599
+ case '--port': args.port = Number(rest[i + 1]); i += 1; break;
600
+ case '--host': args.host = rest[i + 1]; i += 1; break;
601
+ case '--data-dir': args.dataDir = rest[i + 1]; i += 1; break;
602
+ case '--dry-run': args.dryRun = true; break;
603
+ case '--foreground': case '-f': args.foreground = true; break;
604
+ case '--daemon': break; // comportamento padrão; aceito por compatibilidade
605
+ case '--help': case '-h': args.help = true; break;
606
+ case '--version': case '-v': args.version = true; break;
607
+ case 'stop': case 'kill': args.command = 'stop'; break;
608
+ default:
609
+ if (token.startsWith('-')) console.warn(`[jobfinder] ignorando flag desconhecida: ${token}`);
610
+ break;
611
+ }
612
+ }
613
+ return args;
313
614
  }
314
615
 
315
616
  async function main() {
316
617
  const args = parseArgs(process.argv.slice(2));
317
- switch (args.command) {
318
- case 'install':
319
- commandInstall(args);
320
- break;
321
- case 'help':
322
- console.log(USAGE.trim());
323
- break;
324
- case 'version':
325
- commandVersion();
326
- break;
327
- case 'start':
328
- case null:
329
- await commandStart(args);
330
- break;
331
- default:
332
- console.error(`[jobfinder] unknown command: ${args.command}`);
333
- console.log(USAGE.trim());
334
- process.exit(1);
618
+
619
+ if (args.help) {
620
+ console.log(USAGE.trim());
621
+ return;
335
622
  }
623
+ if (args.version) {
624
+ console.log(`JobFinder v${VISUAL_VERSION} (npm: ${NPM_VERSION})`);
625
+ console.log(`os: ${os.type()} ${os.arch()} • node: ${process.version}`);
626
+ console.log(`home: ${resolveHome()}`);
627
+ return;
628
+ }
629
+ if (args.command === 'install') {
630
+ commandInstall(args);
631
+ return;
632
+ }
633
+ if (args.command === 'stop') {
634
+ await commandStop();
635
+ return;
636
+ }
637
+ if (args.foreground) {
638
+ await commandForeground(args);
639
+ return;
640
+ }
641
+ if (args.command === 'start' || args.command === 'daemon' || args.command === null) {
642
+ await commandDaemon(args);
643
+ return;
644
+ }
645
+ console.error(`[jobfinder] comando desconhecido: ${args.command}`);
646
+ console.log(USAGE.trim());
647
+ process.exit(1);
336
648
  }
337
649
 
338
- await main();
650
+ await main();