import { spawnSync } from 'node:child_process' import { EventEmitter } from 'node:events' import path from 'node:path' import { pathToFileURL } from 'node:url' import { afterEach, describe, expect, it } from 'vitest' import { activeSeedExitGuard, createSeeder, guardSeedExit, type SeedExitProcess } from '../src/exports/seed.js' const guardFile = pathToFileURL(path.resolve(import.meta.dirname, '../src/modules/seed/exitGuard.ts')).href /** A `process` stand-in: `beforeExit` is emitted by the test, `exit` is recorded. */ function fakeProcess() { const emitter = new EventEmitter() const exits: number[] = [] const proc: { exitCode?: null | number | string } & SeedExitProcess = { exit: (code) => {exits.push(code)}, off: (event, listener) => emitter.off(event, listener), on: (event, listener) => emitter.on(event, listener), } return { emit: () => emitter.emit('beforeExit'), exits, listeners: () => emitter.listenerCount('beforeExit'), proc } } afterEach(() => activeSeedExitGuard()?.dispose()) describe('guardSeedExit', () => { it('fails a run that ends before Payload initialized', () => { const fake = fakeProcess() const lines: string[] = [] guardSeedExit({ log: (l) => lines.push(l), process: fake.proc }) fake.emit() expect(fake.exits).toEqual([1]) expect(fake.proc.exitCode).toBe(1) expect(lines[0]).toMatch(/^\[seed\] ended before Payload initialized/) }) it('fails a run that ends after createSeeder but before summary()', () => { const fake = fakeProcess() const lines: string[] = [] const guard = guardSeedExit({ label: '[seed-form]', log: (l) => lines.push(l), process: fake.proc }) createSeeder({ config: { localization: false } } as never, { guard: false, log: () => {} }) expect(guard.state).toBe('initialized') fake.emit() expect(fake.exits).toEqual([1]) expect(lines[0]).toMatch(/^\[seed-form\] ended before the seed finished/) }) it('leaves a finished run alone (summary() ends it), and dispose() removes the listener', () => { const fake = fakeProcess() const guard = guardSeedExit({ log: () => {}, process: fake.proc }) const seed = createSeeder({ config: { localization: false } } as never, { guard: false, log: () => {} }) seed.summary() expect(guard.state).toBe('finished') fake.emit() expect(fake.exits).toEqual([]) guard.dispose() expect(fake.listeners()).toBe(0) expect(activeSeedExitGuard()).toBeNull() }) it('a second guard replaces the first (one listener)', () => { const fake = fakeProcess() guardSeedExit({ log: () => {}, process: fake.proc }) const second = guardSeedExit({ log: () => {}, process: fake.proc }) expect(fake.listeners()).toBe(1) expect(activeSeedExitGuard()).toBe(second) }) }) /** * The real thing in a child process, started the way `payload run` starts a script: `void start()` and * `await import(script)`. Exit codes and messages must match what an operator sees in Coolify's Terminal. */ describe('guardSeedExit in a real process', () => { const run = (body: string) => { const script = `import { guardSeedExit } from '${guardFile}' const start = async () => { try { ${body} } catch (error) { console.error('Error running script:', error.message) process.exit(1) } } void start()` return spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8', timeout: 20_000 }) } it('an await that never settles: exit 1 with the reason, not a silent 0', () => { const r = run(`guardSeedExit()\n await new Promise(() => {}) // getPayload() left with nothing keeping the loop alive`) expect(r.status).toBe(1) expect(r.stderr).toMatch(/\[seed\] ended before Payload initialized/) }) it('without the guard the same script exits 0 silently (the failure the guard exists for)', () => { const r = run(`await new Promise(() => {})`) expect(r.status).toBe(0) expect(`${r.stdout}${r.stderr}`).toBe('') }) it('a finished run exits with its own code; an error and a refusal keep exit 1 and their message', () => { expect(run(`const g = guardSeedExit()\n g.initialized(); g.finished()\n console.log('summary')\n process.exit(0)`)).toMatchObject({ status: 0, stdout: 'summary\n' }) const failed = run(`const g = guardSeedExit()\n g.initialized(); g.finished()\n process.exit(1)`) expect(failed.status).toBe(1) expect(failed.stderr).not.toMatch(/ended before/) const refused = run(`guardSeedExit()\n throw new Error('[seed] full seed refused: NODE_ENV=production and no record list.')`) expect(refused.status).toBe(1) expect(refused.stderr).toMatch(/full seed refused/) expect(refused.stderr).not.toMatch(/ended before/) }) it('a dry run that ends naturally after summary() exits 0', () => { const r = run(`const g = guardSeedExit()\n g.initialized(); g.finished()`) expect(r.status).toBe(0) }) })