Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: extract shared .env parse/upsert helper to scripts/lib/envFile.js
Adam Eivy28f5b1bb0256
diff --git a/scripts/lib/envFile.js b/scripts/lib/envFile.jsnew file mode 100644index 0000000000..ef552f8753--- /dev/null+++ b/scripts/lib/envFile.js@@ -0,0 +1,59 @@+/**+ * Minimal .env parse/upsert helpers for setup scripts.+ *+ * ZERO external dependencies — these run before/around `npm install`.+ * Do NOT import from server/lib or any installed package.+ */++import { readFileSync, writeFileSync } from 'fs';++/**+ * Parse a .env file into a key/value map.+ * Tolerates blank lines, # comments, and optional surrounding single/double+ * quotes around values. Returns {} when the file is missing or unreadable.+ *+ * @param {string} filePath - absolute path to the .env file+ * @returns {Record<string, string>}+ */+export function parseEnvFile(filePath) {+ const result = {};+ let content = '';+ try { content = readFileSync(filePath, 'utf8'); } catch { return result; }+ for (const line of content.split('\n')) {+ const trimmed = line.trim();+ if (!trimmed || trimmed.startsWith('#')) continue;+ const idx = trimmed.indexOf('=');+ if (idx === -1) continue;+ const key = trimmed.slice(0, idx).trim();+ let value = trimmed.slice(idx + 1).trim();+ if ((value.startsWith('"') && value.endsWith('"')) ||+ (value.startsWith("'") && value.endsWith("'"))) {+ value = value.slice(1, -1);+ }+ result[key] = value;+ }+ return result;+}++/**+ * Set (or add) a single key in a .env file without touching other lines.+ * If the key already exists, its line is replaced in-place.+ * If it doesn't exist, `KEY=value` is prepended so the file starts with the+ * new entry. Creates the file if it doesn't exist yet.+ *+ * @param {string} filePath - absolute path to the .env file+ * @param {string} key - env var name (e.g. 'PGMODE')+ * @param {string} value - unquoted value to write+ */+export function upsertEnvKey(filePath, key, value) {+ let content = '';+ try { content = readFileSync(filePath, 'utf8'); } catch { /* no .env yet */ }+ const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const pattern = new RegExp(`^${escaped}=.*`, 'm');+ if (pattern.test(content)) {+ content = content.replace(pattern, `${key}=${value}`);+ } else {+ content = `${key}=${value}\n${content}`;+ }+ writeFileSync(filePath, content);+}diff --git a/scripts/lib/envFile.test.js b/scripts/lib/envFile.test.jsnew file mode 100644index 0000000000..4ea755b386--- /dev/null+++ b/scripts/lib/envFile.test.js@@ -0,0 +1,90 @@+import { describe, it, expect, beforeEach } from 'vitest';+import { mkdtempSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { parseEnvFile, upsertEnvKey } from './envFile.js';++let dir;+let envPath;++beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'envFile-test-'));+ envPath = join(dir, '.env');+});++describe('parseEnvFile', () => {+ it('returns {} when file is missing', () => {+ expect(parseEnvFile(join(dir, 'nonexistent.env'))).toEqual({});+ });++ it('parses simple KEY=value pairs', () => {+ writeFileSync(envPath, 'FOO=bar\nBAZ=qux\n');+ expect(parseEnvFile(envPath)).toEqual({ FOO: 'bar', BAZ: 'qux' });+ });++ it('skips blank lines and # comments', () => {+ writeFileSync(envPath, '# comment\n\nFOO=bar\n');+ expect(parseEnvFile(envPath)).toEqual({ FOO: 'bar' });+ });++ it('strips double-quoted values', () => {+ writeFileSync(envPath, 'FOO="hello world"\n');+ expect(parseEnvFile(envPath)).toEqual({ FOO: 'hello world' });+ });++ it('strips single-quoted values', () => {+ writeFileSync(envPath, "FOO='hello world'\n");+ expect(parseEnvFile(envPath)).toEqual({ FOO: 'hello world' });+ });++ it('does not strip mismatched quotes', () => {+ writeFileSync(envPath, "FOO='mismatched\"\n");+ expect(parseEnvFile(envPath)).toEqual({ FOO: "'mismatched\"" });+ });++ it('trims whitespace around key and value', () => {+ writeFileSync(envPath, ' KEY = val \n');+ expect(parseEnvFile(envPath)).toEqual({ KEY: 'val' });+ });++ it('handles first = only when multiple = present', () => {+ writeFileSync(envPath, 'URL=http://a=b\n');+ expect(parseEnvFile(envPath)).toEqual({ URL: 'http://a=b' });+ });+});++describe('upsertEnvKey', () => {+ it('creates .env with the key when file is missing', () => {+ upsertEnvKey(envPath, 'PGMODE', 'docker');+ expect(parseEnvFile(envPath)).toMatchObject({ PGMODE: 'docker' });+ });++ it('prepends when key is absent', () => {+ writeFileSync(envPath, 'OTHER=val\n');+ upsertEnvKey(envPath, 'PGMODE', 'native');+ const parsed = parseEnvFile(envPath);+ expect(parsed).toMatchObject({ PGMODE: 'native', OTHER: 'val' });+ });++ it('replaces existing key in-place', () => {+ writeFileSync(envPath, 'OTHER=val\nPGMODE=docker\nMORE=x\n');+ upsertEnvKey(envPath, 'PGMODE', 'native');+ const parsed = parseEnvFile(envPath);+ expect(parsed).toMatchObject({ PGMODE: 'native', OTHER: 'val', MORE: 'x' });+ });++ it('does not duplicate the key', () => {+ writeFileSync(envPath, 'PGMODE=docker\n');+ upsertEnvKey(envPath, 'PGMODE', 'native');+ upsertEnvKey(envPath, 'PGMODE', 'file');+ const parsed = parseEnvFile(envPath);+ expect(Object.keys(parsed).filter(k => k === 'PGMODE')).toHaveLength(1);+ expect(parsed.PGMODE).toBe('file');+ });++ it('upserts LLM_BACKEND correctly', () => {+ upsertEnvKey(envPath, 'LLM_BACKEND', 'ollama');+ upsertEnvKey(envPath, 'LLM_BACKEND', 'lmstudio');+ expect(parseEnvFile(envPath)).toMatchObject({ LLM_BACKEND: 'lmstudio' });+ });+});diff --git a/scripts/setup-db.js b/scripts/setup-db.jsindex 11c54f7a6e..2f9e760a69 100644--- a/scripts/setup-db.js+++ b/scripts/setup-db.js@@ -13,35 +13,12 @@ import { execFileSync } from 'child_process';import { createInterface } from 'readline';import { dirname, join } from 'path';import { fileURLToPath } from 'url';-import { readFileSync, writeFileSync } from 'fs';+import { parseEnvFile, upsertEnvKey } from './lib/envFile.js';const __dirname = dirname(fileURLToPath(import.meta.url));const rootDir = join(__dirname, '..');-// Parse .env into a key/value map. Tolerates blank lines, # comments, and-// optional surrounding single/double quotes around values. Returns {} when-// the file is missing.-function parseEnvFile() {- const result = {};- let content = '';- try { content = readFileSync(join(rootDir, '.env'), 'utf8'); } catch { return result; }- for (const line of content.split('\n')) {- const trimmed = line.trim();- if (!trimmed || trimmed.startsWith('#')) continue;- const idx = trimmed.indexOf('=');- if (idx === -1) continue;- const key = trimmed.slice(0, idx).trim();- let value = trimmed.slice(idx + 1).trim();- if ((value.startsWith('"') && value.endsWith('"')) ||- (value.startsWith("'") && value.endsWith("'"))) {- value = value.slice(1, -1);- }- result[key] = value;- }- return result;-}--const envFile = parseEnvFile();+const envFile = parseEnvFile(join(rootDir, '.env'));// Resolve PG config from process.env first, then .env, then defaults — so a// user who sets PGPASSWORD in .env (without exporting it into the shell) is// respected the same way getMode() respects PGMODE in .env.@@ -192,18 +169,7 @@ function getDockerHints(issue) {// Write PGMODE to .env (create or update)function setPgMode(mode) {- const envPath = join(rootDir, '.env');- let content = '';- try {- content = readFileSync(envPath, 'utf8');- } catch { /* no .env yet */ }-- if (content.match(/^PGMODE=/m)) {- content = content.replace(/^PGMODE=.*/m, `PGMODE=${mode}`);- } else {- content = `PGMODE=${mode}\n${content}`;- }- writeFileSync(envPath, content);+ upsertEnvKey(join(rootDir, '.env'), 'PGMODE', mode);}// Prompt user to choose storage mode (TTY only)diff --git a/scripts/setup-llm.js b/scripts/setup-llm.jsindex 9dc232d7d6..017cbf22c7 100644--- a/scripts/setup-llm.js+++ b/scripts/setup-llm.js@@ -17,39 +17,15 @@ import { execFileSync } from 'child_process';import { createInterface } from 'readline';import { dirname, join } from 'path';import { fileURLToPath } from 'url';-import { existsSync, readFileSync, writeFileSync } from 'fs';+import { existsSync } from 'fs';+import { parseEnvFile, upsertEnvKey } from './lib/envFile.js';const __dirname = dirname(fileURLToPath(import.meta.url));const rootDir = join(__dirname, '..');const envPath = join(rootDir, '.env');-function parseEnvFile() {- const result = {};- let content = '';- try { content = readFileSync(envPath, 'utf8'); } catch { return result; }- for (const line of content.split('\n')) {- const trimmed = line.trim();- if (!trimmed || trimmed.startsWith('#')) continue;- const idx = trimmed.indexOf('=');- if (idx === -1) continue;- let value = trimmed.slice(idx + 1).trim();- if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {- value = value.slice(1, -1);- }- result[trimmed.slice(0, idx).trim()] = value;- }- return result;-}-function setBackend(backend) {- let content = '';- try { content = readFileSync(envPath, 'utf8'); } catch { /* no .env yet */ }- if (/^LLM_BACKEND=/m.test(content)) {- content = content.replace(/^LLM_BACKEND=.*/m, `LLM_BACKEND=${backend}`);- } else {- content = `LLM_BACKEND=${backend}\n${content}`;- }- writeFileSync(envPath, content);+ upsertEnvKey(envPath, 'LLM_BACKEND', backend);console.log(`✅ Local LLM backend set to ${backend} (LLM_BACKEND in .env)`);}@@ -126,7 +102,7 @@ function promptYesNo(question) {});}-const env = parseEnvFile();+const env = parseEnvFile(envPath);const existing = env.LLM_BACKEND || process.env.LLM_BACKEND;if (existing === 'ollama' || existing === 'lmstudio') {