everything-dev
Version:
A consolidated product package for building Module Federation apps with oRPC APIs.
69 lines (67 loc) • 2.77 kB
JavaScript
import { pgliteDefaultUrl } from "./defaults.mjs";
import { existsSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { parse } from "dotenv";
//#region src/db/binding.ts
/**
* Materialize the environment a spawned tool needs to reach the binding's
* database: the canonical secret name mapped to the resolved URL. The process
* that resolves bindings (the CLI composition root) pushes this into spawned
* children so they never re-derive secrets from ambient state.
*/
function bindingEnv(binding) {
return { [binding.secretName]: binding.url };
}
/**
* The zero-config local database: a persistent, file-backed PGlite data dir
* resolved per workspace process (`.bos/db` relative to the workspace cwd).
* No ports, no docker — concurrent projects never collide. This default is a
* runtime-driver concern only: drizzle-kit commands (db:push/db:studio/
* db:migrate) need a real postgres DSN in the environment.
*
* Single-sourced in `defaults.json` (read by plain-node tooling like the
* regression env too) — never hardcode the literal elsewhere. Scaffolded
* templates and plugin secret defaults deliberately keep their own frozen
* copy: a database location is pinned at init, it must not silently follow
* a framework upgrade.
*/
const PGLITE_DEFAULT_URL = pgliteDefaultUrl;
function findEnvFile(startDir) {
if (!startDir) return void 0;
let current = startDir;
for (let i = 0; i < 15; i++) {
const candidate = join(current, ".env");
if (existsSync(candidate)) return candidate;
const parent = dirname(current);
if (parent === current) return void 0;
current = parent;
}
}
/**
* Resolve the connection URL for a workspace identity.
*
* Resolution order:
* 1. the canonical secret in the provided environment
* 2. the canonical secret in the nearest `.env` walked up from the
* workspace directory (existing environment wins — values are not
* overridden, matching dotenv semantics)
* 3. the persistent local default (`PGLITE_DEFAULT_URL`) — consumed by the
* runtime driver (`createDatabaseDriver`), so boot migrations apply
* zero-config against the workspace's `.bos/db` data dir
*
* drizzle-kit commands need a postgres DSN; feeding them the pglite default
* fails loudly at connect time.
*/
function resolveDatabaseUrl(identity, options = {}) {
const direct = (options.env ?? process.env)[identity.secretName];
if (direct) return direct;
const envFile = findEnvFile(identity.workspaceDir);
if (envFile) try {
const fromFile = parse(readFileSync(envFile, "utf-8"))[identity.secretName];
if (fromFile) return fromFile;
} catch {}
return PGLITE_DEFAULT_URL;
}
//#endregion
export { PGLITE_DEFAULT_URL, bindingEnv, resolveDatabaseUrl };
//# sourceMappingURL=binding.mjs.map