@danhachuel/jobfinder 0.1.15 → 0.1.16
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/CHANGELOG.md +22 -0
- package/README.md +66 -0
- package/ecosystem.config.cjs +36 -0
- package/package.json +9 -2
- package/scripts/cli.mjs +151 -1
- package/scripts/manual-tests/fase4-npx-start.mjs +35 -18
- package/scripts/manual-tests/fase5-daemon.mjs +168 -0
- package/scripts/start-windows.cmd +9 -0
- package/scripts/start-windows.ps1 +108 -0
- package/src/ui/dist/assets/{index-DtY7qbQR.js → index-BIl6BJNG.js} +1 -1
- package/src/ui/dist/index.html +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,28 @@ All notable changes to JobFinder are documented in this file.
|
|
|
6
6
|
|
|
7
7
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
8
8
|
|
|
9
|
+
## [0.1.16] — 2026-11-22
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- **Modo daemon (`node scripts/cli.mjs --daemon`)**: o servidor sobe **detached** do terminal interativo e sobrevive ao fechamento da sessão — a resposta definitiva ao terminal (MobaXterm, wrapper do `npx`, PowerShell) que mata o processo filho. `stdio: ['ignore', <log>, <log>]` (nunca `inherit`), `windowsHide`, `creationFlags: CREATE_NEW_PROCESS_GROUP`, estado do daemon em `jobfinder-daemon.json` via **JsonStore** (atômico, nunca `fs.writeFileSync`). O terminal volta ao prompt em ~300 ms.
|
|
14
|
+
- **Comando `stop`** (`--stop` / `--daemon-stop`): encerra o daemon com SIGTERM, espera o encerramento gracioso, força com SIGKILL se necessário e limpa o pid do registro. Roda limpo quando não há daemon.
|
|
15
|
+
- **`scripts/start-windows.ps1`** (+ wrapper `start-windows.cmd` para duplo clique): detecta porta em uso, sobe o daemon via `Start-Process` (desacoplado dos pipes do terminal — com `&` ou `Start-Process -Wait` o PowerShell fica pendurado esperando handles do processo nativo), confere o `/api/health` e informa PID, log e como parar. Flag `-Local` usa o working copy; `-Version` fixa a versão do npm.
|
|
16
|
+
- **`ecosystem.config.cjs` + scripts PM2** (`pm2:start`, `pm2:stop`, `daemon:logs`): JobFinder como serviço real, com reinício automático em caso de crash. `pm2` entra como **optionalDependency** — a regra do projeto é executar nativamente, sem infraestrutura obrigatória; sem pm2 tudo continua funcionando.
|
|
17
|
+
- **README**: nova seção "Rodando como Serviço (Windows/Linux)" comparando as quatro formas (foreground / `--daemon` / script Windows / PM2).
|
|
18
|
+
|
|
19
|
+
### Notas
|
|
20
|
+
|
|
21
|
+
- O daemon grava o log em `~/.jobfinder/jobfinder.log` (respeita `JOBFINDER_HOME`/`JOBFINDER_DATA_DIR`).
|
|
22
|
+
- `JOBFINDER_MODE=daemon` é propagado ao processo para identificar o modo no ambiente.
|
|
23
|
+
- Validado: `npm ci` continua instalando pm2 como dependência opcional sem falhar (245 pacotes).
|
|
24
|
+
|
|
25
|
+
### Tests
|
|
26
|
+
|
|
27
|
+
- Nova suíte `scripts/manual-tests/fase5-daemon.mjs` — **21 verificações, 0 falhas**: launcher volta ao prompt com código 0 em < 8 s, pid registrado, HTTP 200, log em disco com a versão correta (não `0.0.00`), daemon sobrevive à morte do terminal, rodar duas vezes não duplica, `stop` encerra e limpa o registro, `stop` sem daemon não quebra.
|
|
28
|
+
- PM2 validado ponta a ponta: `pm2 start ecosystem.config.cjs` → app `online` (pid + uptime), `/api/health` 200, `pm2 stop` → `stopped`.
|
|
29
|
+
- Script Windows validado ponta a ponta (`-Local`): start → HTTP 200 e `exit 0` sem travar; `-Stop` → porta não responde mais e `exit 0`.
|
|
30
|
+
|
|
9
31
|
## [0.1.15] — 2026-11-21
|
|
10
32
|
|
|
11
33
|
### Fixed
|
package/README.md
CHANGED
|
@@ -85,9 +85,75 @@ Alternative: create the account directly in `~/.jobfinder/auth.json` (see the `u
|
|
|
85
85
|
node scripts/cli.mjs start --port 3031 # custom port
|
|
86
86
|
node scripts/cli.mjs start --data-dir . # custom data directory
|
|
87
87
|
node scripts/cli.mjs start --dry-run # force dry-run
|
|
88
|
+
node scripts/cli.mjs --daemon # background (terminal fica livre)
|
|
89
|
+
node scripts/cli.mjs stop # encerra o daemon
|
|
88
90
|
node scripts/cli.mjs --version # version info
|
|
89
91
|
```
|
|
90
92
|
|
|
93
|
+
## Rodando como Serviço (Windows/Linux)
|
|
94
|
+
|
|
95
|
+
Alguns terminais — MobaXterm, wrappers do `npx`, sessões de PowerShell — podem encerrar o
|
|
96
|
+
processo filho a qualquer momento. Quando você precisa que o JobFinder **sobreviva ao
|
|
97
|
+
terminal**, use uma das três formas abaixo.
|
|
98
|
+
|
|
99
|
+
### 1. Foreground (via npx) — ideal para ver os logs
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
npx --yes @danhachuel/jobfinder@0.1.16
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
O servidor roda neste terminal; `Ctrl+C` encerra. Perfeito para depurar, ruim para deixar
|
|
106
|
+
rodando: se o terminal fechar, o app morre.
|
|
107
|
+
|
|
108
|
+
### 2. Daemon nativo — `node scripts/cli.mjs --daemon`
|
|
109
|
+
|
|
110
|
+
O servidor sobe **detached** do terminal, com o log em `~/.jobfinder/jobfinder.log`. O
|
|
111
|
+
terminal volta ao prompt na hora.
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
# pacote publicado (qualquer SO)
|
|
115
|
+
npx --yes @danhachuel/jobfinder@0.1.16 --daemon --port 4040
|
|
116
|
+
npx --yes @danhachuel/jobfinder@0.1.16 stop
|
|
117
|
+
|
|
118
|
+
# working copy
|
|
119
|
+
node scripts/cli.mjs --daemon --port 4040
|
|
120
|
+
node scripts/cli.mjs stop
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### 3. Script nativo do Windows — `scripts\start-windows.ps1`
|
|
124
|
+
|
|
125
|
+
Duplo clique ou PowerShell: detecta porta em uso, sobe o daemon, confere o `/api/health` e
|
|
126
|
+
informa o PID e o caminho do log.
|
|
127
|
+
|
|
128
|
+
```powershell
|
|
129
|
+
.\scripts\start-windows.ps1 # versão latest do npm
|
|
130
|
+
.\scripts\start-windows.ps1 -Version 0.1.16 # versão fixa
|
|
131
|
+
.\scripts\start-windows.ps1 -Local # working copy (desenvolvimento)
|
|
132
|
+
.\scripts\start-windows.ps1 -Stop # encerra
|
|
133
|
+
.\scripts\start-windows.cmd # wrapper para duplo clique
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### 4. PM2 — serviço de verdade (Windows e Linux)
|
|
137
|
+
|
|
138
|
+
Reinicia em caso de crash, gerencia logs e sobrevive ao fechamento da sessão.
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
npm i -g pm2 # ou: npx pm2
|
|
142
|
+
npm run pm2:start # sobe (ecosystem.config.cjs)
|
|
143
|
+
npm run daemon:logs # acompanha os logs
|
|
144
|
+
npm run pm2:stop # para
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
`pm2` é dependência **opcional**: sem ela o app continua funcionando normalmente pelos
|
|
148
|
+
caminhos 1–3 — a regra do projeto é executar nativamente, sem infraestrutura obrigatória.
|
|
149
|
+
|
|
150
|
+
| Forma | Sobrevive ao terminal? | Logs | Uso |
|
|
151
|
+
|---|---|---|---|
|
|
152
|
+
| Foreground (npx) | não | no terminal | depuração rápida |
|
|
153
|
+
| `--daemon` | sim | `~/.jobfinder/jobfinder.log` | servidor local simples |
|
|
154
|
+
| `start-windows.ps1` | sim | `~/.jobfinder/jobfinder.log` | Windows, duplo clique |
|
|
155
|
+
| PM2 | sim (reinicia) | `pm2 logs` | serviço de longo prazo |
|
|
156
|
+
|
|
91
157
|
## Screenshots
|
|
92
158
|
|
|
93
159
|
> Painel, Postagens, Conexões, Cascatas de DM, Vagas, Candidaturas, Integrações e Configurações — see the walkthrough in the app header (**Ver tutorial**) or open the app to explore in dry-run mode. Screenshots are published with each release in the GitHub Releases.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PM2 — JobFinder como serviço de background real (Windows e Linux).
|
|
3
|
+
*
|
|
4
|
+
* npm i -g pm2 # ou: npx pm2
|
|
5
|
+
* npm run start:daemon # sobe
|
|
6
|
+
* npm run daemon:logs # acompanha
|
|
7
|
+
* npm run daemon:stop # para
|
|
8
|
+
*
|
|
9
|
+
* O CLI continua sendo o entrypoint: toda a supervisão do worker, os sinais
|
|
10
|
+
* e o keep-alive do event loop são os mesmos do modo foreground. O PM2 apenas
|
|
11
|
+
* garante que o processo sobreviva ao fechamento do terminal e reinicia em
|
|
12
|
+
* caso de crash.
|
|
13
|
+
*/
|
|
14
|
+
module.exports = {
|
|
15
|
+
apps: [
|
|
16
|
+
{
|
|
17
|
+
name: 'jobfinder',
|
|
18
|
+
script: 'scripts/cli.mjs',
|
|
19
|
+
interpreter: 'node',
|
|
20
|
+
// Modo serviço: não trava o terminal e sobrevive ao fechamento da sessão.
|
|
21
|
+
instances: 1,
|
|
22
|
+
exec_mode: 'fork',
|
|
23
|
+
autorestart: true,
|
|
24
|
+
max_restarts: 10,
|
|
25
|
+
restart_delay: 3000,
|
|
26
|
+
// Logs por processo fiquem em ~/.jobfinder (o PM2 gerencia os seus em
|
|
27
|
+
// ~/.pm2/logs; aqui o app escreve o log de aplicação).
|
|
28
|
+
out_file: null,
|
|
29
|
+
error_file: null,
|
|
30
|
+
env: {
|
|
31
|
+
NODE_ENV: 'production',
|
|
32
|
+
JOBFINDER_MODE: 'daemon',
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
],
|
|
36
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@danhachuel/jobfinder",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.16",
|
|
4
4
|
"description": "JobFinder — LinkedIn automation platform (posts, connections/DMs, job matching) with a React + Vite UI. Intelligent workflows, JSON storage.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"linkedin",
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
"scripts/",
|
|
22
22
|
"src/server/",
|
|
23
23
|
"src/ui/dist/",
|
|
24
|
+
"ecosystem.config.cjs",
|
|
24
25
|
"CHANGELOG.md",
|
|
25
26
|
"README.md",
|
|
26
27
|
"LICENSE"
|
|
@@ -32,6 +33,11 @@
|
|
|
32
33
|
"dev:ui": "npm --prefix src/ui run dev",
|
|
33
34
|
"build": "npm --prefix src/ui run build",
|
|
34
35
|
"start": "node scripts/cli.mjs start",
|
|
36
|
+
"start:daemon": "node scripts/cli.mjs --daemon",
|
|
37
|
+
"daemon:stop": "node scripts/cli.mjs stop",
|
|
38
|
+
"daemon:logs": "pm2 logs jobfinder",
|
|
39
|
+
"pm2:start": "pm2 start ecosystem.config.cjs",
|
|
40
|
+
"pm2:stop": "pm2 stop ecosystem.config.cjs",
|
|
35
41
|
"smoke": "node scripts/cli.mjs install && node scripts/cli.mjs --version"
|
|
36
42
|
},
|
|
37
43
|
"engines": {
|
|
@@ -43,7 +49,8 @@
|
|
|
43
49
|
"pdfjs-dist": "^6.5.438"
|
|
44
50
|
},
|
|
45
51
|
"optionalDependencies": {
|
|
46
|
-
"playwright": "^1.65.0"
|
|
52
|
+
"playwright": "^1.65.0",
|
|
53
|
+
"pm2": "^6.0.14"
|
|
47
54
|
},
|
|
48
55
|
"devDependencies": {
|
|
49
56
|
"concurrently": "^10.0.7"
|
package/scripts/cli.mjs
CHANGED
|
@@ -21,8 +21,10 @@ import path from 'node:path';
|
|
|
21
21
|
import os from 'node:os';
|
|
22
22
|
import process from 'node:process';
|
|
23
23
|
import { fileURLToPath } from 'node:url';
|
|
24
|
+
import { spawn } from 'node:child_process';
|
|
24
25
|
|
|
25
26
|
import { ensureDataDir, resolveDataDir, isDataDirHealthy } from '../src/server/storage/bootstrap.mjs';
|
|
27
|
+
import { JsonStore } from '../src/server/storage/jsonStore.mjs';
|
|
26
28
|
import { spawnWorker } from '../src/server/workerRuntime.mjs';
|
|
27
29
|
|
|
28
30
|
/**
|
|
@@ -83,6 +85,8 @@ Flags:
|
|
|
83
85
|
--host <addr> Bind address (default 127.0.0.1)
|
|
84
86
|
--data-dir <path> Data directory (default ~/.jobfinder, override with JOBFINDER_HOME)
|
|
85
87
|
--dry-run Run with automations in dry-run mode (no real LinkedIn actions)
|
|
88
|
+
--daemon Run detached from this terminal (background service)
|
|
89
|
+
--stop Stop the daemon started with --daemon
|
|
86
90
|
|
|
87
91
|
Install commands (canonical npm version):
|
|
88
92
|
npx --yes @danhachuel/jobfinder@${NPM_VERSION} install
|
|
@@ -90,7 +94,7 @@ Install commands (canonical npm version):
|
|
|
90
94
|
`;
|
|
91
95
|
|
|
92
96
|
function parseArgs(argv) {
|
|
93
|
-
const args = { command: null, port: null, host: null, dataDir: null, dryRun: false };
|
|
97
|
+
const args = { command: null, port: null, host: null, dataDir: null, dryRun: false, daemon: false };
|
|
94
98
|
const rest = [...argv];
|
|
95
99
|
const first = rest[0];
|
|
96
100
|
if (first && !first.startsWith('-')) {
|
|
@@ -120,6 +124,16 @@ function parseArgs(argv) {
|
|
|
120
124
|
case '--dry-run':
|
|
121
125
|
args.dryRun = true;
|
|
122
126
|
break;
|
|
127
|
+
// Daemon mode: the server runs detached from this terminal (background
|
|
128
|
+
// service). The terminal returns to the prompt immediately.
|
|
129
|
+
case '--daemon':
|
|
130
|
+
args.daemon = true;
|
|
131
|
+
break;
|
|
132
|
+
// Shorthand to stop a daemon started with --daemon.
|
|
133
|
+
case '--daemon-stop':
|
|
134
|
+
case '--stop':
|
|
135
|
+
args.command = 'stop';
|
|
136
|
+
break;
|
|
123
137
|
case '--help':
|
|
124
138
|
case '-h':
|
|
125
139
|
args.command = 'help';
|
|
@@ -307,6 +321,131 @@ async function commandStart({ port, host, dataDir, dryRun }) {
|
|
|
307
321
|
}
|
|
308
322
|
}
|
|
309
323
|
|
|
324
|
+
/** True when a pid exists (EPERM = alive but owned by another user). */
|
|
325
|
+
function isPidAlive(pid) {
|
|
326
|
+
if (!pid || !Number.isInteger(Number(pid)) || Number(pid) <= 0) return false;
|
|
327
|
+
try {
|
|
328
|
+
process.kill(Number(pid), 0);
|
|
329
|
+
return true;
|
|
330
|
+
} catch (err) {
|
|
331
|
+
return err?.code === 'EPERM';
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Daemon mode (0.1.16): the server runs DETACHED from the interactive
|
|
337
|
+
* terminal, so nothing the terminal does afterwards can kill it.
|
|
338
|
+
*
|
|
339
|
+
* A hostile terminal (MobaXterm wrapper, PowerShell, npx) can TerminateProcess
|
|
340
|
+
* the foreground child at any moment; a detached process with its own stdio
|
|
341
|
+
* pointed at a log file is immune to that. The terminal returns to the prompt
|
|
342
|
+
* immediately — that is the expected behaviour of a daemon.
|
|
343
|
+
*/
|
|
344
|
+
async function commandDaemon(args) {
|
|
345
|
+
const resolved = resolveDataDir(args.dataDir);
|
|
346
|
+
ensureDataDir(resolved);
|
|
347
|
+
|
|
348
|
+
const store = new JsonStore(resolved);
|
|
349
|
+
const info = store.read('jobfinder-daemon.json', null) ?? {};
|
|
350
|
+
if (isPidAlive(info.pid)) {
|
|
351
|
+
console.log(`JobFinder ja esta rodando em background (pid ${info.pid}).`);
|
|
352
|
+
console.log(` URL : http://${info.host ?? '127.0.0.1'}:${info.port ?? 4040}`);
|
|
353
|
+
console.log(` Log : ${info.logFile ?? path.join(resolved, 'jobfinder.log')}`);
|
|
354
|
+
console.log(` Parar: npx --yes @danhachuel/jobfinder@${NPM_VERSION} stop`);
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const port = args.port || Number(process.env.JOBFINDER_PORT) || 4040;
|
|
359
|
+
const host = args.host || process.env.JOBFINDER_HOST || '127.0.0.1';
|
|
360
|
+
const logFile = path.join(resolved, 'jobfinder.log');
|
|
361
|
+
|
|
362
|
+
printBanner();
|
|
363
|
+
fs.mkdirSync(path.dirname(logFile), { recursive: true });
|
|
364
|
+
const logFd = fs.openSync(logFile, 'a');
|
|
365
|
+
|
|
366
|
+
const child = spawn(process.execPath, [path.join(__dirname, 'cli.mjs'), 'start', '--port', String(port), '--host', host, ...(args.dryRun ? ['--dry-run'] : [])], {
|
|
367
|
+
detached: true,
|
|
368
|
+
// stdio de arquivo: o daemon NUNCA herda os pipes do terminal. Se o canalho
|
|
369
|
+
// do MobaXterm fechar, o daemon não sente — e o log fica em disco.
|
|
370
|
+
stdio: ['ignore', logFd, logFd],
|
|
371
|
+
windowsHide: true,
|
|
372
|
+
creationFlags: process.platform === 'win32' ? 0x00000200 : 0,
|
|
373
|
+
env: {
|
|
374
|
+
...process.env,
|
|
375
|
+
JOBFINDER_MODE: 'daemon',
|
|
376
|
+
JOBFINDER_DATA_DIR: resolved,
|
|
377
|
+
JOBFINDER_PORT: String(port),
|
|
378
|
+
JOBFINDER_HOST: host,
|
|
379
|
+
JOBFINDER_VERSION: VISUAL_VERSION,
|
|
380
|
+
},
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
child.on('error', (err) => {
|
|
384
|
+
console.error(`[jobfinder] falha ao iniciar o daemon: ${err?.message ?? err}`);
|
|
385
|
+
process.exit(1);
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
// Estado do daemon via JsonStore (atômico) — nunca fs.writeFileSync solto.
|
|
389
|
+
store.write('jobfinder-daemon.json', {
|
|
390
|
+
pid: child.pid,
|
|
391
|
+
port,
|
|
392
|
+
host,
|
|
393
|
+
logFile,
|
|
394
|
+
startedAt: new Date().toISOString(),
|
|
395
|
+
version: VISUAL_VERSION,
|
|
396
|
+
mode: 'daemon',
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
child.unref();
|
|
400
|
+
|
|
401
|
+
const shown = host === '0.0.0.0' ? 'localhost' : host;
|
|
402
|
+
console.log(` Data directory : ${resolved}`);
|
|
403
|
+
console.log(` Mode : daemon (background)`);
|
|
404
|
+
console.log(` URL : http://${shown}:${port}`);
|
|
405
|
+
console.log(` PID : ${child.pid}`);
|
|
406
|
+
console.log(` Log : ${logFile}`);
|
|
407
|
+
console.log(`\nRodando em background — este terminal esta livre.`);
|
|
408
|
+
console.log(` Parar com: npx --yes @danhachuel/jobfinder@${NPM_VERSION} stop`);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** Stop the daemon recorded in jobfinder-daemon.json (SIGTERM, then SIGKILL). */
|
|
412
|
+
async function commandStop() {
|
|
413
|
+
const resolved = resolveDataDir();
|
|
414
|
+
const store = new JsonStore(resolved);
|
|
415
|
+
const info = store.read('jobfinder-daemon.json', null) ?? {};
|
|
416
|
+
|
|
417
|
+
if (!isPidAlive(info.pid)) {
|
|
418
|
+
console.log('Nenhum daemon do JobFinder rodando.');
|
|
419
|
+
store.write('jobfinder-daemon.json', { ...info, pid: null, stoppedAt: new Date().toISOString() });
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
const pid = Number(info.pid);
|
|
424
|
+
console.log(`Parando o JobFinder (pid ${pid})...`);
|
|
425
|
+
try {
|
|
426
|
+
process.kill(pid, 'SIGTERM');
|
|
427
|
+
} catch (err) {
|
|
428
|
+
console.error(`[jobfinder] falha ao sinalizar o processo: ${err?.message ?? err}`);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// Espera o encerramento gracioso; força se necessário.
|
|
432
|
+
for (let i = 0; i < 20; i += 1) {
|
|
433
|
+
if (!isPidAlive(pid)) break;
|
|
434
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
435
|
+
}
|
|
436
|
+
if (isPidAlive(pid)) {
|
|
437
|
+
console.error('[jobfinder] encerramento gracioso expirou — forcando (SIGKILL).');
|
|
438
|
+
try {
|
|
439
|
+
process.kill(pid, 'SIGKILL');
|
|
440
|
+
} catch {
|
|
441
|
+
/* best effort */
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
store.write('jobfinder-daemon.json', { ...info, pid: null, stoppedAt: new Date().toISOString() });
|
|
446
|
+
console.log('JobFinder parado.');
|
|
447
|
+
}
|
|
448
|
+
|
|
310
449
|
function commandVersion() {
|
|
311
450
|
console.log(`JobFinder v${VISUAL_VERSION} (npm: ${NPM_VERSION})`);
|
|
312
451
|
console.log(`os: ${os.type()} ${os.arch()} • node: ${process.version}`);
|
|
@@ -314,6 +453,17 @@ function commandVersion() {
|
|
|
314
453
|
|
|
315
454
|
async function main() {
|
|
316
455
|
const args = parseArgs(process.argv.slice(2));
|
|
456
|
+
|
|
457
|
+
// --daemon tem precedência sobre start/null, mas nunca sobre install/help/version.
|
|
458
|
+
if (args.daemon && !['install', 'help', 'version', 'stop'].includes(args.command)) {
|
|
459
|
+
await commandDaemon(args);
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
if (args.command === 'stop') {
|
|
463
|
+
await commandStop();
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
|
|
317
467
|
switch (args.command) {
|
|
318
468
|
case 'install':
|
|
319
469
|
commandInstall(args);
|
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Reprodução do cenário real:
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* Reprodução do cenário real: o binário rodando a partir de um diretório
|
|
3
|
+
* ESTRANHO (fora do repo), como o usuário faz no MobaXterm / PowerShell.
|
|
4
|
+
*
|
|
5
|
+
* Uso:
|
|
6
|
+
* node scripts/manual-tests/fase4-npx-start.mjs # build local
|
|
7
|
+
* node scripts/manual-tests/fase4-npx-start.mjs --remote 0.1.15 # pacote publicado via npx
|
|
5
8
|
*
|
|
6
9
|
* Verifica:
|
|
7
10
|
* 1. a versão impressa é a correta (não 0.0.00)
|
|
8
11
|
* 2. o processo continua vivo depois do banner (event loop retido)
|
|
9
12
|
* 3. o servidor responde HTTP 200
|
|
10
13
|
* 4. o terminal não volta ao prompt sozinho
|
|
11
|
-
*
|
|
12
|
-
* Uso: node scripts/manual-tests/fase4-npx-start.mjs [versao]
|
|
13
14
|
*/
|
|
14
15
|
import { spawn } from 'node:child_process';
|
|
15
16
|
import fs from 'node:fs';
|
|
@@ -37,18 +38,32 @@ function check(name, condition, extra = '') {
|
|
|
37
38
|
}
|
|
38
39
|
}
|
|
39
40
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
// Roda o CLI LOCAL a partir de um diretório estranho — reproduz o ambiente do
|
|
44
|
-
// npx (cwd != raiz do pacote) sem depender de publicação prévia.
|
|
41
|
+
// Modo remoto: usa o pacote PUBLICADO via npx (validação real da release).
|
|
42
|
+
const remoteIndex = process.argv.indexOf('--remote');
|
|
43
|
+
const REMOTE_VERSION = remoteIndex > -1 ? process.argv[remoteIndex + 1] : null;
|
|
45
44
|
const REPO_ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.slice(1)), '..', '..');
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
});
|
|
51
|
-
|
|
45
|
+
|
|
46
|
+
if (REMOTE_VERSION) {
|
|
47
|
+
console.log(`\n== npx @danhachuel/jobfinder@${REMOTE_VERSION} em ${FOREIGN_CWD} ==`);
|
|
48
|
+
} else {
|
|
49
|
+
console.log(`\n== JobFinder (build local) em ${FOREIGN_CWD} ==`);
|
|
50
|
+
console.log('(equivalente ao `npx @danhachuel/jobfinder@<versao>`: mesmo cwd estranho, mesmo binário)');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// `shell: true` é obrigatório no Windows para spawnar um .cmd (npx.cmd).
|
|
54
|
+
const npx = REMOTE_VERSION
|
|
55
|
+
? spawn(`npx --yes @danhachuel/jobfinder@${REMOTE_VERSION} start --port ${PORT}`, {
|
|
56
|
+
cwd: FOREIGN_CWD,
|
|
57
|
+
shell: true,
|
|
58
|
+
env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_NO_WORKER: '1' },
|
|
59
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
60
|
+
})
|
|
61
|
+
: spawn(process.execPath, [path.join(REPO_ROOT, 'scripts', 'cli.mjs'), 'start', '--port', String(PORT)], {
|
|
62
|
+
cwd: FOREIGN_CWD,
|
|
63
|
+
env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_NO_WORKER: '1' },
|
|
64
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
65
|
+
});
|
|
66
|
+
const cli = npx;
|
|
52
67
|
|
|
53
68
|
let out = '';
|
|
54
69
|
let err = '';
|
|
@@ -73,9 +88,11 @@ check('servidor respondeu HTTP na porta', httpOk);
|
|
|
73
88
|
|
|
74
89
|
// 2. versão correta no output (a linha do servidor, não só o banner do CLI)
|
|
75
90
|
const serverLine = out.split('\n').find((l) => l.includes('listening on')) ?? '';
|
|
91
|
+
const expected = REMOTE_VERSION ? REMOTE_VERSION.replace(/^0\./, '0.') : /0\.1\.\d+/.source;
|
|
92
|
+
const expectedRe = REMOTE_VERSION ? new RegExp(REMOTE_VERSION.replace(/\./g, '\\.')) : /0\.1\.\d+/;
|
|
76
93
|
const versionLine = out.split('\n').find((l) => /^JobFinder\s+v?\d/.test(l.trim())) ?? '';
|
|
77
|
-
check('versão correta (não 0.0.00)',
|
|
78
|
-
check('linha do listen traz a versão correta',
|
|
94
|
+
check('versão correta (não 0.0.00)', expectedRe.test(versionLine) && !versionLine.includes('0.0.00'), versionLine.trim());
|
|
95
|
+
check('linha do listen traz a versão correta', expectedRe.test(serverLine) && !serverLine.includes('0.0.00'), serverLine.trim());
|
|
79
96
|
|
|
80
97
|
// 3. o processo PRECISA continuar vivo (não voltar ao prompt)
|
|
81
98
|
await delay(8000);
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Modo daemon (0.1.16): o servidor sobrevive ao terminal.
|
|
3
|
+
*
|
|
4
|
+
* 1. `--daemon` volta ao prompt IMEDIATO (processo pai sai com código 0)
|
|
5
|
+
* 2. o servidor continua vivo em background, detached do terminal
|
|
6
|
+
* 3. responde HTTP 200
|
|
7
|
+
* 4. o log em ~/.jobfinder/jobfinder.log tem o banner e a versão correta
|
|
8
|
+
* 5. `stop` encerra o daemon (HTTP falha depois)
|
|
9
|
+
* 6. rodar duas vezes não duplica (detecta o pid ativo)
|
|
10
|
+
* 7. matar o terminal não mata o daemon (o teste simula: o PAI morre)
|
|
11
|
+
*
|
|
12
|
+
* Uso: node scripts/manual-tests/fase5-daemon.mjs
|
|
13
|
+
*/
|
|
14
|
+
import { spawn } from 'node:child_process';
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import os from 'node:os';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import process from 'node:process';
|
|
19
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
20
|
+
|
|
21
|
+
const PORT = 4455;
|
|
22
|
+
const HOME = path.join(os.tmpdir(), `jobfinder-fase5-${Date.now()}`);
|
|
23
|
+
const APP = `http://127.0.0.1:${PORT}`;
|
|
24
|
+
const REPO = path.resolve(path.dirname(new URL(import.meta.url).pathname.slice(1)), '..', '..');
|
|
25
|
+
let passed = 0;
|
|
26
|
+
let failed = 0;
|
|
27
|
+
|
|
28
|
+
function check(name, condition, extra = '') {
|
|
29
|
+
if (condition) {
|
|
30
|
+
passed += 1;
|
|
31
|
+
console.log(` OK ${name}${extra ? ` — ${extra}` : ''}`);
|
|
32
|
+
} else {
|
|
33
|
+
failed += 1;
|
|
34
|
+
console.log(` FAIL ${name}${extra ? ` — ${extra}` : ''}`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function isAlive(pid) {
|
|
39
|
+
if (!pid) return false;
|
|
40
|
+
try {
|
|
41
|
+
process.kill(Number(pid), 0);
|
|
42
|
+
return true;
|
|
43
|
+
} catch (err) {
|
|
44
|
+
return err?.code === 'EPERM';
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function daemonPid() {
|
|
49
|
+
try {
|
|
50
|
+
const info = JSON.parse(fs.readFileSync(path.join(HOME, 'jobfinder-daemon.json'), 'utf8'));
|
|
51
|
+
return info.pid ?? null;
|
|
52
|
+
} catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function health() {
|
|
58
|
+
try {
|
|
59
|
+
const res = await fetch(`${APP}/api/health`);
|
|
60
|
+
return res.ok ? await res.json() : null;
|
|
61
|
+
} catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const CLI = [path.join(REPO, 'scripts', 'cli.mjs')];
|
|
67
|
+
|
|
68
|
+
/* ------------------------------------------------------------------ */
|
|
69
|
+
console.log('\n== 1. --daemon volta ao prompt imediatamente ==');
|
|
70
|
+
const started = Date.now();
|
|
71
|
+
const launcher = spawn(process.execPath, [...CLI, '--daemon', '--port', String(PORT)], {
|
|
72
|
+
cwd: os.tmpdir(), // cwd estranho, como o do usuário
|
|
73
|
+
env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_NO_WORKER: '1' },
|
|
74
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
75
|
+
});
|
|
76
|
+
let launcherOut = '';
|
|
77
|
+
launcher.stdout.on('data', (d) => { launcherOut += String(d); });
|
|
78
|
+
launcher.stderr.on('data', (d) => { launcherOut += String(d); });
|
|
79
|
+
|
|
80
|
+
const launcherExit = await new Promise((resolve) => {
|
|
81
|
+
launcher.on('exit', (code) => resolve(code));
|
|
82
|
+
setTimeout(() => resolve(null), 20000);
|
|
83
|
+
});
|
|
84
|
+
const elapsed = Date.now() - started;
|
|
85
|
+
check('launcher saiu com código 0', launcherExit === 0, `code=${launcherExit}`);
|
|
86
|
+
check('launcher voltou ao prompt rápido (<8s)', elapsed < 8000, `${elapsed}ms`);
|
|
87
|
+
check('saída informa PID e log', /PID\s+:\s+\d+/.test(launcherOut) && /jobfinder\.log/.test(launcherOut));
|
|
88
|
+
|
|
89
|
+
console.log('\n== 2. Daemon vivo em background ==');
|
|
90
|
+
const pid = daemonPid();
|
|
91
|
+
check('pid do daemon registrado', pid !== null && pid > 0, `pid=${pid}`);
|
|
92
|
+
check('processo do daemon está rodando', isAlive(pid));
|
|
93
|
+
|
|
94
|
+
let httpData = null;
|
|
95
|
+
for (let i = 0; i < 30; i += 1) {
|
|
96
|
+
httpData = await health();
|
|
97
|
+
if (httpData) break;
|
|
98
|
+
await delay(500);
|
|
99
|
+
}
|
|
100
|
+
check('daemon responde HTTP 200', httpData?.ok === true, httpData ? `version=${httpData.version}` : 'sem resposta');
|
|
101
|
+
check('versão correta no /health (não 0.0.00)', /0\.1\.\d+/.test(httpData?.version ?? ''), httpData?.version);
|
|
102
|
+
|
|
103
|
+
console.log('\n== 3. Log em disco ==');
|
|
104
|
+
const logFile = path.join(HOME, 'jobfinder.log');
|
|
105
|
+
check('arquivo de log existe', fs.existsSync(logFile));
|
|
106
|
+
const logContent = fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf8') : '';
|
|
107
|
+
check('log tem o banner de startup', /JobFinder v0\.1\.\d+/.test(logContent));
|
|
108
|
+
check('log NÃO tem versão 0.0.00', !logContent.includes('0.0.00'));
|
|
109
|
+
check('log registra o worker/porta', logContent.length > 50, `${logContent.length} bytes`);
|
|
110
|
+
|
|
111
|
+
console.log('\n== 4. Sobrevive à morte do terminal (o launcher já morreu) ==');
|
|
112
|
+
check('launcher (terminal) já saiu', launcherExit === 0);
|
|
113
|
+
check('daemon continua vivo depois que o terminal morreu', isAlive(pid) && (await health())?.ok === true);
|
|
114
|
+
|
|
115
|
+
console.log('\n== 5. Rodar duas vezes não duplica ==');
|
|
116
|
+
const second = spawn(process.execPath, [...CLI, '--daemon', '--port', String(PORT)], {
|
|
117
|
+
cwd: os.tmpdir(),
|
|
118
|
+
env: { ...process.env, JOBFINDER_HOME: HOME, JOBFINDER_NO_WORKER: '1' },
|
|
119
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
120
|
+
});
|
|
121
|
+
let secondOut = '';
|
|
122
|
+
second.stdout.on('data', (d) => { secondOut += String(d); });
|
|
123
|
+
const secondExit = await new Promise((resolve) => {
|
|
124
|
+
second.on('exit', (code) => resolve(code));
|
|
125
|
+
setTimeout(() => resolve(null), 15000);
|
|
126
|
+
});
|
|
127
|
+
check('segunda execução detecta o daemon ativo', secondExit === 0 && /ja esta rodando/.test(secondOut), secondOut.split('\n')[0] ?? '');
|
|
128
|
+
check('pid continua o mesmo (não duplicou)', daemonPid() === pid);
|
|
129
|
+
|
|
130
|
+
console.log('\n== 6. stop encerra o daemon ==');
|
|
131
|
+
const stop = spawn(process.execPath, [...CLI, 'stop'], {
|
|
132
|
+
cwd: os.tmpdir(),
|
|
133
|
+
env: { ...process.env, JOBFINDER_HOME: HOME },
|
|
134
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
135
|
+
});
|
|
136
|
+
let stopOut = '';
|
|
137
|
+
stop.stdout.on('data', (d) => { stopOut += String(d); });
|
|
138
|
+
const stopExit = await new Promise((resolve) => {
|
|
139
|
+
stop.on('exit', (code) => resolve(code));
|
|
140
|
+
setTimeout(() => resolve(null), 20000);
|
|
141
|
+
});
|
|
142
|
+
check('stop saiu com código 0', stopExit === 0, `code=${stopExit}`);
|
|
143
|
+
check('stop informa que parou', /parado/i.test(stopOut), stopOut.split('\n')[0] ?? '');
|
|
144
|
+
await delay(1500);
|
|
145
|
+
check('processo do daemon não existe mais', !isAlive(pid));
|
|
146
|
+
const afterStop = await health();
|
|
147
|
+
check('HTTP não responde mais', afterStop === null);
|
|
148
|
+
check('pid foi limpo no registro', daemonPid() === null, `pid=${daemonPid()}`);
|
|
149
|
+
|
|
150
|
+
console.log('\n== 7. stop sem daemon não quebra ==');
|
|
151
|
+
const stopAgain = spawn(process.execPath, [...CLI, 'stop'], {
|
|
152
|
+
cwd: os.tmpdir(),
|
|
153
|
+
env: { ...process.env, JOBFINDER_HOME: HOME },
|
|
154
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
155
|
+
});
|
|
156
|
+
let stopAgainOut = '';
|
|
157
|
+
stopAgain.stdout.on('data', (d) => { stopAgainOut += String(d); });
|
|
158
|
+
const stopAgainExit = await new Promise((resolve) => {
|
|
159
|
+
stopAgain.on('exit', (code) => resolve(code));
|
|
160
|
+
setTimeout(() => resolve(null), 15000);
|
|
161
|
+
});
|
|
162
|
+
check('stop sem daemon roda limpo', stopAgainExit === 0, stopAgainOut.split('\n')[0] ?? '');
|
|
163
|
+
|
|
164
|
+
// Limpeza de segurança
|
|
165
|
+
try { spawn(process.execPath, [...CLI, 'stop'], { cwd: os.tmpdir(), env: { ...process.env, JOBFINDER_HOME: HOME } }); } catch { /* ignore */ }
|
|
166
|
+
|
|
167
|
+
console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
|
|
168
|
+
process.exit(failed ? 1 : 0);
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
@echo off
|
|
2
|
+
REM ============================================================
|
|
3
|
+
REM JobFinder - execucao em background no Windows (duplo clique)
|
|
4
|
+
REM Chama o script PowerShell, que sobe o servidor DETACHED do
|
|
5
|
+
REM terminal. Use start-windows.cmd stop para encerrar.
|
|
6
|
+
REM ============================================================
|
|
7
|
+
setlocal
|
|
8
|
+
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0start-windows.ps1" %*
|
|
9
|
+
exit /b %ERRORLEVEL%
|