wishforge-ide/scripts/env-file.test.mjs
eust-w 90a76f2d59 🐛 Make the local POC setup safe to rerun
- It allowed every IPv4 address of the en* interfaces as a web origin,
  public ones included; it now takes only private LAN addresses, as
  npm run local:network does.
- It rewrote .env.local in place, where a crash lost the generated
  secrets, and missed `export` assignments; the file is now replaced
  atomically through scripts/env-file.mjs.
- A binding file it could not read made it create a second project
  and environment; only a missing one means a first setup now.
- A runner registered for a replaced environment is registered again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:33:30 +08:00

29 lines
1.5 KiB
JavaScript

import assert from 'node:assert/strict';
import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { replaceEnvFile, setEnvValues } from './env-file.mjs';
test('sets values where they stand, exported or not, without duplicates, and appends new ones', () => {
const source = '# Local settings\nexport WF_WEB_HOST=127.0.0.1\nDATABASE_URL=postgres://keep\nWF_WEB_HOST=::1\n';
assert.equal(
setEnvValues(source, { WF_WEB_HOST: '0.0.0.0', WF_WEB_PORT: '3000' }),
'# Local settings\nWF_WEB_HOST=0.0.0.0\nDATABASE_URL=postgres://keep\nWF_WEB_PORT=3000\n',
);
assert.throws(() => setEnvValues('', { WF_TOKEN: 'one\nWF_DEV_AUTH_TOKEN=two' }), /single-line/);
});
test('replaces the file whole, or leaves it as it was when it changed meanwhile', async t => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'wishforge-env-'));
t.after(() => rm(directory, { recursive: true, force: true }));
const file = path.join(directory, '.env.local');
await writeFile(file, 'A=1\n', { mode: 0o600 });
await replaceEnvFile(file, 'A=1\n', 'A=2\n');
assert.equal(await readFile(file, 'utf8'), 'A=2\n');
await assert.rejects(replaceEnvFile(file, 'A=1\n', 'A=3\n'), /changed while it was being updated/);
assert.equal(await readFile(file, 'utf8'), 'A=2\n');
// No temporary copy of the secrets is left behind.
assert.deepEqual(await readdir(directory), ['.env.local']);
});