Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

2.1 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { existsSync, readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { parseEnv } from "node:util";

// Values from .env.local override the caller's environment (it is the file
// `pnpm dev:up` writes); plain .env only fills in what is not already set.
export function loadDotEnv(): void {
  for (const file of [".env", ".env.local"]) {
    if (!existsSync(file)) continue;
    for (const [key, value] of Object.entries(
      parseEnv(readFileSync(file, "utf8"))
    )) {
      if (file === ".env.local" || process.env[key] === undefined)
        process.env[key] = value;
    }
  }
}

export function readLocalScriptConfig<const Keys extends readonly string[]>(
  names: Keys,
  environment: Record<string, string | undefined>
): { [Key in Keys[number]]: string } {
  const local = existsSync(".env")
    ? parseEnv(readFileSync(".env", "utf8"))
    : {};
  const localOverride = existsSync(".env.local")
    ? parseEnv(readFileSync(".env.local", "utf8"))
    : {};
  const values = Object.fromEntries(
    names.map((name) => [
      name,
      localOverride[name] ?? environment[name] ?? local[name]
    ])
  );
  const missing = names.filter((name) => !values[name]?.trim());
  if (missing.length) {
    throw new Error(
      `Missing required local configuration: ${missing.join(", ")}. Set these values in your local environment or ignored .env file.`
    );
  }
  return values as {
    [Key in Keys[number]]: string;
  };
}

export function createScriptClient(
  url: string,
  publicKey: string,
  apiKey: string
) {
  // The database workspace declares and pins this dependency; root scripts do not.
  const fromDatabase = createRequire(
    new URL("../../packages/database/package.json", import.meta.url)
  );
  const { createClient } = fromDatabase("@supabase/supabase-js");
  return createClient(url, publicKey, {
    global: { headers: { "carbon-key": apiKey } }
  });
}