File size: 2,006 Bytes
7f88bdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { spawn } from "node:child_process";
import fs from "node:fs";
import path from "node:path";

const repoRoot = process.cwd();
const envLocalPath = path.join(repoRoot, ".env.local");

function loadEnv(filePath) {
  if (!fs.existsSync(filePath)) {
    return {};
  }

  const env = {};
  const lines = fs.readFileSync(filePath, "utf8").split(/\r?\n/);
  for (const raw of lines) {
    const line = raw.trim();
    if (!line || line.startsWith("#")) {
      continue;
    }
    const idx = line.indexOf("=");
    if (idx < 0) {
      continue;
    }
    const key = line.slice(0, idx).trim();
    const value = line.slice(idx + 1);
    env[key] = value;
  }

  return env;
}

function normalizeDatabaseUrl(env) {
  const current = env.DATABASE_URL;
  if (!current) {
    return env;
  }

  let normalized = current.trim();
  if (
    (normalized.startsWith('"') && normalized.endsWith('"')) ||
    (normalized.startsWith("'") && normalized.endsWith("'"))
  ) {
    normalized = normalized.slice(1, -1);
  }

  if (normalized.startsWith(":postgresql://")) {
    normalized = normalized.slice(1);
  }

  normalized = normalized.replace(
    /(postgres(?:ql)?:\/\/[^:/?#]+:)\[([^\]]+)\](@)/i,
    "$1$2$3"
  );

  return {
    ...env,
    DATABASE_URL: normalized
  };
}

const localEnv = loadEnv(envLocalPath);
const normalizedLocalEnv = normalizeDatabaseUrl(localEnv);
const pythonExe =
  process.env.PYTHON_EXE ||
  normalizedLocalEnv.PYTHON_EXE ||
  "C:\\Users\\Angelah\\AppData\\Local\\Programs\\Python\\Python311\\python.exe";

const mergedEnv = normalizeDatabaseUrl({
  ...normalizedLocalEnv,
  ...process.env
});

const child = spawn(pythonExe, ["apps/worker/src/worker/main.py"], {
  cwd: repoRoot,
  env: mergedEnv,
  stdio: "inherit"
});

child.on("exit", (code, signal) => {
  if (signal) {
    process.kill(process.pid, signal);
    return;
  }
  process.exit(code ?? 0);
});

child.on("error", (error) => {
  console.error(`Failed to start worker: ${error.message}`);
  process.exit(1);
});