#!/usr/bin/env node // Builds a product's .env files from its env template (crosscode.env-template/1, // docs/AGENT-1.0-PLAN.md §5). Used by `crosscode install` (files don't exist yet: written whole) // and `crosscode deploy` (files exist: only variables they don't have are appended, with a // comment; existing lines are never changed or removed). // // node envtpl.cjs --template --dir [--config ] // [--product events] [--var domain=… --var apiPort=…] [--fallback NAME=value] // [--release events@x.y.z] [--check] // // Values by layer: generated → environment variables CROSSCODE_GEN_ (so secrets never // appear in arguments or files other than the .env); server / defaults → the config's layers; // install → the config's install[product], else the variable's `from` filled with --var values. // Then --fallback, then the template's `default`. A required variable with no value stops // everything before any file is written (exit 3, the names on stderr). // --check: only says what would be added. Prints names only, never values. 'use strict'; const fs = require('fs'); const path = require('path'); function parseArgs(argv) { const out = { vars: {}, fallback: {}, check: false }; for (let i = 0; i < argv.length; i++) { const a = argv[i]; const next = () => { if (i + 1 >= argv.length) throw new Error(`${a} needs a value`); return argv[++i]; }; if (a === '--template') out.template = next(); else if (a === '--dir') out.dir = next(); else if (a === '--config') out.config = next(); else if (a === '--product') out.product = next(); else if (a === '--release') out.release = next(); else if (a === '--check') out.check = true; else if (a === '--var' || a === '--fallback') { const v = next(); const eq = v.indexOf('='); if (eq < 1) throw new Error(`${a} ${v}: expected NAME=value`); out[a === '--var' ? 'vars' : 'fallback'][v.slice(0, eq)] = v.slice(eq + 1); } else throw new Error(`Unknown option ${a}`); } if (!out.template || !out.dir) throw new Error('--template and --dir are required'); return out; } /** KEY names a .env file already sets (comments and blank lines ignored, `export KEY=` allowed). */ function keysIn(text) { const keys = new Set(); for (const line of text.split(/\r?\n/)) { const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line); if (m) keys.add(m[1]); } return keys; } function fill(from, vars) { let missing = false; const value = from.replace(/\{([A-Za-z]+)\}/g, (_, k) => { if (vars[k] === undefined || vars[k] === '') missing = true; return vars[k] ?? ''; }); return missing ? undefined : value; } /** A value as a .env line: bare when safe, otherwise double-quoted (dotenv's rules). */ function line(name, value) { if (/[\r\n]/.test(value)) throw new Error(`${name}: values can't contain newlines`); return /^[A-Za-z0-9_./:@,+=%-]*$/.test(value) ? `${name}=${value}` : `${name}="${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`; } function resolve(variable, ctx) { let value; const nonEmpty = v => (v === undefined || v === null || String(v) === '' ? undefined : String(v)); switch (variable.layer) { case 'generated': value = nonEmpty(process.env[`CROSSCODE_GEN_${variable.name}`]); break; case 'server': value = nonEmpty(ctx.config.server?.[variable.name]); break; case 'defaults': value = nonEmpty(ctx.config.defaults?.[variable.name]); break; case 'install': value = nonEmpty(ctx.config.install?.[ctx.product]?.[variable.name]); if (value === undefined && variable.from) value = nonEmpty(fill(variable.from, ctx.vars)); break; default: throw new Error(`${variable.name}: unknown layer ${variable.layer}`); } if (value === undefined) value = nonEmpty(ctx.fallback[variable.name]); if (value === undefined) value = nonEmpty(variable.default); return value; } function plan(opts) { const template = JSON.parse(fs.readFileSync(opts.template, 'utf8')); if (template.schema !== 'crosscode.env-template/1') throw new Error(`${opts.template} isn't a crosscode.env-template/1`); const config = opts.config ? JSON.parse(fs.readFileSync(opts.config, 'utf8')) : {}; const ctx = { config, vars: opts.vars, fallback: opts.fallback, product: opts.product || template.product }; const files = []; const missing = []; for (const [rel, variables] of Object.entries(template.files)) { if (rel.includes('..') || path.isAbsolute(rel)) throw new Error(`Bad file name in the template: ${rel}`); const file = path.join(opts.dir, rel); const exists = fs.existsSync(file); const have = exists ? keysIn(fs.readFileSync(file, 'utf8')) : new Set(); const add = []; for (const v of variables) { if (have.has(v.name)) continue; const value = resolve(v, ctx); if (value === undefined) { if (v.required) missing.push(`${v.name} (${v.layer}, ${rel})`); continue; } add.push({ name: v.name, value }); } files.push({ rel, file, exists, add }); } return { files, missing }; } function write({ files }, release) { const date = new Date().toISOString().slice(0, 10); for (const f of files) { if (!f.add.length) continue; const lines = f.add.map(a => line(a.name, a.value)); let text; if (!f.exists) { text = `# Written by crosscode from env.template.json${release ? ` (${release})` : ''}, ${date}.\n${lines.join('\n')}\n`; } else { const current = fs.readFileSync(f.file, 'utf8'); text = `${current}${current === '' || current.endsWith('\n') ? '' : '\n'}\n# Added by crosscode ${date}${release ? ` (${release})` : ''}\n${lines.join('\n')}\n`; } fs.mkdirSync(path.dirname(f.file), { recursive: true }); const tmp = `${f.file}.crosscode-${process.pid}`; fs.writeFileSync(tmp, text, { mode: 0o600 }); if (f.exists) { const st = fs.statSync(f.file); try { fs.chownSync(tmp, st.uid, st.gid); } catch { /* not root: same owner anyway */ } fs.chmodSync(tmp, st.mode & 0o777); } fs.renameSync(tmp, f.file); } } function main() { let opts; try { opts = parseArgs(process.argv.slice(2)); } catch (e) { console.error(`envtpl: ${e.message}`); process.exit(2); } const result = plan(opts); if (result.missing.length) { console.error(`Required settings with no value: ${result.missing.join(', ')}`); process.exit(3); } for (const f of result.files) { if (!f.add.length) continue; const names = f.add.map(a => a.name).join(', '); console.log(`${f.rel}: ${opts.check ? 'would add' : f.exists ? 'added' : 'wrote'} ${names}`); } if (!opts.check) write(result, opts.release); } if (require.main === module) main(); module.exports = { parseArgs, keysIn, fill, line, plan, write };