@fabioplunser/epd 0.5.7 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +585 -250
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -869,14 +869,13 @@ function validateCrossReferences(cfg) {
869
869
  if (cfg.mode === "docker" && !cfg.registry && cfg.services.some((s) => s.hosts.length > 1)) {}
870
870
  }
871
871
 
872
- // src/commands/init.ts
873
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
874
- import { basename, join as join3 } from "path";
872
+ // src/commands/action.ts
873
+ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
874
+ import { dirname as dirname2, join as join2 } from "path";
875
875
 
876
876
  // src/util/prompt.ts
877
- var isTTY = process.stdin.isTTY && process.stdout.isTTY;
878
877
  function interactive() {
879
- return Boolean(isTTY);
878
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
880
879
  }
881
880
  async function readLine() {
882
881
  for await (const line of console)
@@ -884,21 +883,21 @@ async function readLine() {
884
883
  return "";
885
884
  }
886
885
  async function ask(question, dflt) {
887
- if (!isTTY)
886
+ if (!interactive())
888
887
  return dflt ?? "";
889
888
  process.stdout.write(`${c.cyan("?")} ${question}${dflt ? c.gray(` (${dflt})`) : ""} `);
890
889
  const answer = (await readLine()).trim();
891
890
  return answer || dflt || "";
892
891
  }
893
892
  async function askSecret(question) {
894
- if (!isTTY)
893
+ if (!interactive())
895
894
  return "";
896
895
  process.stdout.write(`${c.cyan("?")} ${question} `);
897
896
  const answer = (await readLine()).trim();
898
897
  return answer;
899
898
  }
900
899
  async function askPassword(question) {
901
- if (!isTTY)
900
+ if (!interactive())
902
901
  return "";
903
902
  process.stdout.write(`${c.cyan("?")} ${question} `);
904
903
  const echo = await setEcho(false);
@@ -920,13 +919,13 @@ async function setEcho(on) {
920
919
  }
921
920
  }
922
921
  async function pressEnter(message) {
923
- if (!isTTY)
922
+ if (!interactive())
924
923
  return;
925
924
  process.stdout.write(`${c.cyan("\u21B5")} ${message} ${c.gray("[Press Enter]")} `);
926
925
  await readLine();
927
926
  }
928
927
  async function confirm(question, dflt = false) {
929
- if (!isTTY)
928
+ if (!interactive())
930
929
  return dflt;
931
930
  const answer = (await ask(`${question} ${dflt ? "[Y/n]" : "[y/N]"}`)).toLowerCase();
932
931
  if (!answer)
@@ -934,7 +933,7 @@ async function confirm(question, dflt = false) {
934
933
  return answer === "y" || answer === "yes";
935
934
  }
936
935
  async function choose(question, options, dflt) {
937
- if (!isTTY)
936
+ if (!interactive())
938
937
  return dflt;
939
938
  console.log(`${c.cyan("?")} ${question}`);
940
939
  options.forEach((o, i) => console.log(` ${i + 1}) ${o.label}${o.value === dflt ? c.gray(" (default)") : ""}`));
@@ -943,10 +942,353 @@ async function choose(question, options, dflt) {
943
942
  return options[idx]?.value ?? dflt;
944
943
  }
945
944
 
945
+ // src/util/proc.ts
946
+ async function run(cmd, opts = {}) {
947
+ const label = opts.label ?? cmd.join(" ");
948
+ log.debug(`local: ${cmd.join(" ")}`);
949
+ const proc = Bun.spawn(cmd, {
950
+ cwd: opts.cwd,
951
+ env: opts.env ? { ...process.env, ...opts.env } : process.env,
952
+ stdin: opts.input !== undefined ? new TextEncoder().encode(opts.input) : "inherit",
953
+ stdout: opts.stream ? "inherit" : "pipe",
954
+ stderr: opts.stream && !opts.captureStderr ? "inherit" : "pipe"
955
+ });
956
+ const [stdout, stderr, code] = await Promise.all([
957
+ opts.stream ? Promise.resolve("") : new Response(proc.stdout).text(),
958
+ opts.stream ? opts.captureStderr ? teeStderr(proc.stderr) : Promise.resolve("") : new Response(proc.stderr).text(),
959
+ proc.exited
960
+ ]);
961
+ const result = { code, stdout: stdout.trim(), stderr: stderr.trim() };
962
+ if (code !== 0 && !opts.allowFailure) {
963
+ throw new EpdError(`command failed (exit ${code}): ${label}`, result.stderr || result.stdout || undefined);
964
+ }
965
+ return result;
966
+ }
967
+ async function teeStderr(stream) {
968
+ const reader = stream.getReader();
969
+ const decoder = new TextDecoder;
970
+ let tail = "";
971
+ try {
972
+ while (true) {
973
+ const { done, value } = await reader.read();
974
+ if (done)
975
+ break;
976
+ process.stderr.write(value);
977
+ tail = (tail + decoder.decode(value, { stream: true })).slice(-65536);
978
+ }
979
+ return (tail + decoder.decode()).slice(-65536);
980
+ } finally {
981
+ reader.releaseLock();
982
+ }
983
+ }
984
+ async function runShell(script, opts = {}) {
985
+ return run(["/bin/sh", "-c", script], { ...opts, label: opts.label ?? script });
986
+ }
987
+ async function which(bin) {
988
+ const r = await run(["/bin/sh", "-c", `command -v ${bin}`], { allowFailure: true });
989
+ return r.code === 0 && r.stdout ? r.stdout.split(`
990
+ `)[0].trim() : null;
991
+ }
992
+ async function requireLocal(bin, hint) {
993
+ if (!await which(bin))
994
+ throw new EpdError(`\`${bin}\` was not found on this machine`, hint);
995
+ }
996
+
997
+ // src/config/types.ts
998
+ function allHosts(cfg) {
999
+ const s = new Set;
1000
+ for (const svc of cfg.services)
1001
+ for (const h of svc.hosts)
1002
+ s.add(h);
1003
+ for (const a of cfg.accessories)
1004
+ s.add(a.host);
1005
+ return [...s];
1006
+ }
1007
+ function proxyHosts(cfg) {
1008
+ if (!cfg.proxy.enabled)
1009
+ return [];
1010
+ const s = new Set;
1011
+ for (const svc of cfg.services)
1012
+ if (svc.routes.length)
1013
+ for (const h of svc.hosts)
1014
+ s.add(h);
1015
+ for (const a of cfg.accessories)
1016
+ if (a.routes.length)
1017
+ s.add(a.host);
1018
+ return [...s];
1019
+ }
1020
+
1021
+ // src/commands/action.ts
1022
+ function detectGitBranch(root) {
1023
+ try {
1024
+ const head = readFileSync2(join2(root, ".git", "HEAD"), "utf8").trim();
1025
+ if (head.startsWith("ref: refs/heads/")) {
1026
+ return head.replace("ref: refs/heads/", "");
1027
+ }
1028
+ } catch {}
1029
+ return "main";
1030
+ }
1031
+ async function listGitBranches(root) {
1032
+ const branches = new Set;
1033
+ try {
1034
+ const res = await run(["git", "branch", "-a", "--format=%(refname:short)"], {
1035
+ cwd: root,
1036
+ allowFailure: true
1037
+ });
1038
+ if (res.code === 0 && res.stdout) {
1039
+ for (const line of res.stdout.split(`
1040
+ `)) {
1041
+ const trimmed = line.trim();
1042
+ if (!trimmed || trimmed === "origin" || trimmed.includes("HEAD"))
1043
+ continue;
1044
+ const name = trimmed.replace(/^origin\//, "");
1045
+ branches.add(name);
1046
+ }
1047
+ }
1048
+ } catch {}
1049
+ const current = detectGitBranch(root);
1050
+ if (current)
1051
+ branches.add(current);
1052
+ if (branches.size === 0)
1053
+ branches.add("main");
1054
+ return [...branches];
1055
+ }
1056
+ function buildWorkflowYaml(opts) {
1057
+ const branch = opts.branch || detectGitBranch(opts.root);
1058
+ const event = opts.event || "push";
1059
+ const cfg = opts.cfg;
1060
+ const destination = opts.destination;
1061
+ const isGhcr = cfg ? cfg.image.toLowerCase().startsWith("ghcr.io") || cfg.registry?.server === "ghcr.io" : true;
1062
+ const isCustomRegistry = cfg?.registry && cfg.registry.server !== "ghcr.io";
1063
+ const secretsNeeded = ["SSH_PRIVATE_KEY"];
1064
+ const envVars = [
1065
+ "SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}"
1066
+ ];
1067
+ if (cfg?.ssh.sudoPassword || cfg && cfg.ssh.user !== "root") {
1068
+ envVars.push("EPD_SUDO_PASSWORD: ${{ secrets.EPD_SUDO_PASSWORD }}");
1069
+ secretsNeeded.push("EPD_SUDO_PASSWORD");
1070
+ }
1071
+ if (cfg?.dns?.provider === "cloudflare" || process.env.CLOUDFLARE_API_TOKEN) {
1072
+ envVars.push("CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}");
1073
+ secretsNeeded.push("CLOUDFLARE_API_TOKEN");
1074
+ }
1075
+ if (cfg?.dns?.provider === "hetzner" || process.env.HETZNER_API_TOKEN) {
1076
+ envVars.push("HETZNER_API_TOKEN: ${{ secrets.HETZNER_API_TOKEN }}");
1077
+ secretsNeeded.push("HETZNER_API_TOKEN");
1078
+ }
1079
+ if (cfg?.build.secrets) {
1080
+ for (const envName of Object.values(cfg.build.secrets)) {
1081
+ if (!envVars.some((e) => e.startsWith(`${envName}:`))) {
1082
+ envVars.push(`${envName}: \${{ secrets.${envName} }}`);
1083
+ secretsNeeded.push(envName);
1084
+ }
1085
+ }
1086
+ }
1087
+ if (isCustomRegistry) {
1088
+ secretsNeeded.push("REGISTRY_PASSWORD");
1089
+ }
1090
+ const deployCmd = `epd deploy${destination ? ` -d ${destination}` : ""}`;
1091
+ let steps = ` - name: Checkout repository
1092
+ uses: actions/checkout@v4
1093
+
1094
+ - name: Set up Docker Buildx
1095
+ uses: docker/setup-buildx-action@v3
1096
+ `;
1097
+ if (isGhcr) {
1098
+ steps += `
1099
+ - name: Log in to GitHub Container Registry
1100
+ uses: docker/login-action@v3
1101
+ with:
1102
+ registry: ghcr.io
1103
+ username: \${{ github.actor }}
1104
+ password: \${{ secrets.GITHUB_TOKEN }}
1105
+ `;
1106
+ } else if (isCustomRegistry && cfg?.registry) {
1107
+ steps += `
1108
+ - name: Log in to Container Registry
1109
+ uses: docker/login-action@v3
1110
+ with:
1111
+ registry: ${cfg.registry.server}
1112
+ username: ${cfg.registry.username}
1113
+ password: \${{ secrets.REGISTRY_PASSWORD }}
1114
+ `;
1115
+ }
1116
+ steps += `
1117
+ - name: Setup Bun
1118
+ uses: oven-sh/setup-bun@v2
1119
+ with:
1120
+ bun-version: latest
1121
+
1122
+ - name: Install EPD
1123
+ run: bun install -g @fabioplunser/epd
1124
+
1125
+ - name: Deploy with EPD
1126
+ env:
1127
+ ${envVars.map((v) => ` ${v}`).join(`
1128
+ `)}
1129
+ run: ${deployCmd}
1130
+ `;
1131
+ let onBlock = "";
1132
+ if (event === "push") {
1133
+ onBlock = ` push:
1134
+ branches: [${branch}]
1135
+ workflow_dispatch:`;
1136
+ } else if (event === "pull_request") {
1137
+ onBlock = ` pull_request:
1138
+ branches: [${branch}]
1139
+ workflow_dispatch:`;
1140
+ } else if (event === "both") {
1141
+ onBlock = ` push:
1142
+ branches: [${branch}]
1143
+ pull_request:
1144
+ branches: [${branch}]
1145
+ workflow_dispatch:`;
1146
+ } else {
1147
+ onBlock = ` workflow_dispatch:`;
1148
+ }
1149
+ const yaml = `name: Deploy
1150
+
1151
+ on:
1152
+ ${onBlock}
1153
+
1154
+ concurrency:
1155
+ group: deploy-\${{ github.ref }}
1156
+ cancel-in-progress: false
1157
+
1158
+ jobs:
1159
+ deploy:
1160
+ name: Deploy
1161
+ runs-on: ubuntu-latest
1162
+ permissions:
1163
+ contents: read${isGhcr ? `
1164
+ packages: write` : ""}
1165
+
1166
+ steps:
1167
+ ${steps.trimEnd()}
1168
+ `;
1169
+ return { yaml, secretsNeeded };
1170
+ }
1171
+ var ghAction = {
1172
+ name: "gh-action",
1173
+ aliases: ["ci", "github-action", "action"],
1174
+ summary: "Generate a GitHub Actions deploy workflow",
1175
+ options: {
1176
+ branch: { type: "string", short: "b" },
1177
+ event: { type: "string", short: "e" },
1178
+ on: { type: "string" },
1179
+ file: { type: "string", short: "o" },
1180
+ force: { type: "boolean", short: "f" }
1181
+ },
1182
+ help: () => `${c.bold("epd gh-action")} \u2014 generate a GitHub Actions workflow for automatic deployment
1183
+
1184
+ Creates a ready-to-use GitHub Actions workflow (.github/workflows/deploy.yml) tailored
1185
+ to your project's epd.yml configuration.
1186
+
1187
+ Options
1188
+ -b, --branch <name> Git branch that triggers deploy (e.g. main, master)
1189
+ -e, --event <event> Trigger event: push, pull_request, both, or manual (default: push)
1190
+ -o, --file <path> Output path (default: .github/workflows/deploy.yml)
1191
+ -d, --destination <dst> Target destination overlay (e.g. staging, production)
1192
+ -f, --force Overwrite existing workflow file without prompting
1193
+
1194
+ Aliases
1195
+ epd ci, epd github-action, epd action
1196
+ `,
1197
+ async run(ctx) {
1198
+ let cfg;
1199
+ let root = process.cwd();
1200
+ try {
1201
+ const loaded = ctx.load();
1202
+ cfg = loaded.config;
1203
+ root = cfg.root;
1204
+ } catch {}
1205
+ let branch = ctx.values.branch;
1206
+ let event = ctx.values.event || ctx.values.on;
1207
+ if (!branch && interactive()) {
1208
+ const branches = await listGitBranches(root);
1209
+ const current = detectGitBranch(root);
1210
+ const defaultBranch = branches.includes("main") ? "main" : branches.includes("master") ? "master" : current || "main";
1211
+ const branchChoices = branches.map((b) => ({
1212
+ value: b,
1213
+ label: b === current ? `${b} ${c.gray("(current)")}` : b
1214
+ }));
1215
+ branchChoices.push({ value: "__custom__", label: "Other / custom branch name..." });
1216
+ const selected = await choose("Which branch should trigger the deployment workflow?", branchChoices, defaultBranch);
1217
+ if (selected === "__custom__") {
1218
+ branch = (await ask("Enter git branch name:", defaultBranch)).trim() || defaultBranch;
1219
+ } else {
1220
+ branch = selected;
1221
+ }
1222
+ } else if (!branch) {
1223
+ branch = detectGitBranch(root);
1224
+ }
1225
+ if (!event && interactive()) {
1226
+ const eventChoices = [
1227
+ { value: "push", label: `On push to ${c.bold(branch)} (includes merged pull requests)` },
1228
+ { value: "pull_request", label: `On pull request targeting ${c.bold(branch)}` },
1229
+ { value: "both", label: `Both on push and pull request targeting ${c.bold(branch)}` },
1230
+ { value: "manual", label: "Manual trigger only (workflow_dispatch)" }
1231
+ ];
1232
+ event = await choose("When should the deployment workflow run?", eventChoices, "push");
1233
+ } else if (!event) {
1234
+ event = "push";
1235
+ }
1236
+ const destination = ctx.loadOptions.destination;
1237
+ const defaultFile = join2(root, ".github", "workflows", destination ? `deploy-${destination}.yml` : "deploy.yml");
1238
+ const targetFile = ctx.values.file || defaultFile;
1239
+ if (existsSync2(targetFile) && !ctx.values.force) {
1240
+ const ok = interactive() && await confirm(`${targetFile} already exists. Overwrite?`, false);
1241
+ if (!ok) {
1242
+ log.info(`Aborted. Use ${c.cyan("--force")} to overwrite.`);
1243
+ return;
1244
+ }
1245
+ }
1246
+ const { yaml, secretsNeeded } = buildWorkflowYaml({
1247
+ root,
1248
+ branch,
1249
+ event,
1250
+ destination,
1251
+ cfg
1252
+ });
1253
+ mkdirSync(dirname2(targetFile), { recursive: true });
1254
+ writeFileSync(targetFile, yaml);
1255
+ log.ok(`wrote ${c.bold(targetFile)}`);
1256
+ console.log(`
1257
+ ${c.bold("GitHub Repository Secrets needed:")}`);
1258
+ console.log(`Go to: ${c.cyan("Settings > Secrets and variables > Actions > New repository secret")}
1259
+ `);
1260
+ for (const secret of secretsNeeded) {
1261
+ if (secret === "SSH_PRIVATE_KEY") {
1262
+ console.log(` \u2022 ${c.bold("SSH_PRIVATE_KEY")} Your SSH private key (e.g. ~/.ssh/id_ed25519) to access ${cfg && allHosts(cfg).length > 0 ? allHosts(cfg).join(", ") : "your server"}`);
1263
+ } else if (secret === "EPD_SUDO_PASSWORD") {
1264
+ console.log(` \u2022 ${c.bold("EPD_SUDO_PASSWORD")} Sudo password for ${cfg?.ssh.user || "server user"}`);
1265
+ } else if (secret === "CLOUDFLARE_API_TOKEN") {
1266
+ console.log(` \u2022 ${c.bold("CLOUDFLARE_API_TOKEN")} Cloudflare API Token for DNS updates`);
1267
+ } else if (secret === "HETZNER_API_TOKEN") {
1268
+ console.log(` \u2022 ${c.bold("HETZNER_API_TOKEN")} Hetzner DNS API Token`);
1269
+ } else if (secret === "REGISTRY_PASSWORD") {
1270
+ console.log(` \u2022 ${c.bold("REGISTRY_PASSWORD")} Password/Token for ${cfg?.registry?.server || "container registry"}`);
1271
+ } else {
1272
+ console.log(` \u2022 ${c.bold(secret)} Build/environment secret`);
1273
+ }
1274
+ }
1275
+ console.log(`
1276
+ Next steps:`);
1277
+ console.log(` git add ${targetFile}`);
1278
+ console.log(` git commit -m "Add GitHub Actions deployment workflow"`);
1279
+ console.log(` git push
1280
+ `);
1281
+ }
1282
+ };
1283
+
1284
+ // src/commands/init.ts
1285
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
1286
+ import { basename, join as join4 } from "path";
1287
+
946
1288
  // src/util/auth.ts
947
- import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync, chmodSync } from "fs";
1289
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2, chmodSync } from "fs";
948
1290
  import { homedir as homedir2 } from "os";
949
- import { join as join2 } from "path";
1291
+ import { join as join3 } from "path";
950
1292
  import { spawn } from "child_process";
951
1293
  function openBrowser(url) {
952
1294
  try {
@@ -966,33 +1308,33 @@ function openBrowser(url) {
966
1308
  }
967
1309
  }
968
1310
  function getGlobalAuthPath() {
969
- const xdgDir = join2(homedir2(), ".config", "epd");
970
- const fallbackDir = join2(homedir2(), ".epd");
971
- if (existsSync2(join2(xdgDir, "auth.json")))
972
- return join2(xdgDir, "auth.json");
973
- if (existsSync2(join2(fallbackDir, "auth.json")))
974
- return join2(fallbackDir, "auth.json");
975
- return join2(xdgDir, "auth.json");
1311
+ const xdgDir = join3(homedir2(), ".config", "epd");
1312
+ const fallbackDir = join3(homedir2(), ".epd");
1313
+ if (existsSync3(join3(xdgDir, "auth.json")))
1314
+ return join3(xdgDir, "auth.json");
1315
+ if (existsSync3(join3(fallbackDir, "auth.json")))
1316
+ return join3(fallbackDir, "auth.json");
1317
+ return join3(xdgDir, "auth.json");
976
1318
  }
977
1319
  function getGlobalAuth() {
978
1320
  const path = getGlobalAuthPath();
979
- if (!existsSync2(path))
1321
+ if (!existsSync3(path))
980
1322
  return {};
981
1323
  try {
982
- return JSON.parse(readFileSync2(path, "utf8"));
1324
+ return JSON.parse(readFileSync3(path, "utf8"));
983
1325
  } catch {
984
1326
  return {};
985
1327
  }
986
1328
  }
987
1329
  function saveGlobalAuth(updater) {
988
- const dir = join2(homedir2(), ".config", "epd");
989
- if (!existsSync2(dir)) {
990
- mkdirSync(dir, { recursive: true, mode: 448 });
1330
+ const dir = join3(homedir2(), ".config", "epd");
1331
+ if (!existsSync3(dir)) {
1332
+ mkdirSync2(dir, { recursive: true, mode: 448 });
991
1333
  }
992
- const file = join2(dir, "auth.json");
1334
+ const file = join3(dir, "auth.json");
993
1335
  const current = getGlobalAuth();
994
1336
  const next = updater(current);
995
- writeFileSync(file, JSON.stringify(next, null, 2) + `
1337
+ writeFileSync2(file, JSON.stringify(next, null, 2) + `
996
1338
  `, { mode: 384 });
997
1339
  try {
998
1340
  chmodSync(file, 384);
@@ -1018,8 +1360,8 @@ function clearLinkDecline(provider, root = process.cwd()) {
1018
1360
  }));
1019
1361
  }
1020
1362
  function saveProjectEnv(entries, root = process.cwd()) {
1021
- const envPath = join2(root, ".env");
1022
- let content = existsSync2(envPath) ? readFileSync2(envPath, "utf8") : "";
1363
+ const envPath = join3(root, ".env");
1364
+ let content = existsSync3(envPath) ? readFileSync3(envPath, "utf8") : "";
1023
1365
  for (const [key, val] of Object.entries(entries)) {
1024
1366
  const regex = new RegExp(`^${key}=.*$`, "m");
1025
1367
  const line = `${key}=${val}`;
@@ -1034,17 +1376,17 @@ function saveProjectEnv(entries, root = process.cwd()) {
1034
1376
  `;
1035
1377
  }
1036
1378
  }
1037
- writeFileSync(envPath, content, "utf8");
1379
+ writeFileSync2(envPath, content, "utf8");
1038
1380
  }
1039
1381
  function getCloudflareToken(root = process.cwd()) {
1040
1382
  if (process.env.CLOUDFLARE_API_TOKEN)
1041
1383
  return process.env.CLOUDFLARE_API_TOKEN;
1042
1384
  if (process.env.CF_DNS_API_TOKEN)
1043
1385
  return process.env.CF_DNS_API_TOKEN;
1044
- const envPath = join2(root, ".env");
1045
- if (existsSync2(envPath)) {
1386
+ const envPath = join3(root, ".env");
1387
+ if (existsSync3(envPath)) {
1046
1388
  try {
1047
- const parsed = parseDotenv(readFileSync2(envPath, "utf8"));
1389
+ const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
1048
1390
  if (parsed.CLOUDFLARE_API_TOKEN)
1049
1391
  return parsed.CLOUDFLARE_API_TOKEN;
1050
1392
  if (parsed.CF_DNS_API_TOKEN)
@@ -1059,10 +1401,10 @@ function getCloudflareTokenSource(root = process.cwd()) {
1059
1401
  return "environment variable (CLOUDFLARE_API_TOKEN)";
1060
1402
  if (process.env.CF_DNS_API_TOKEN)
1061
1403
  return "environment variable (CF_DNS_API_TOKEN)";
1062
- const envPath = join2(root, ".env");
1063
- if (existsSync2(envPath)) {
1404
+ const envPath = join3(root, ".env");
1405
+ if (existsSync3(envPath)) {
1064
1406
  try {
1065
- const parsed = parseDotenv(readFileSync2(envPath, "utf8"));
1407
+ const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
1066
1408
  if (parsed.CLOUDFLARE_API_TOKEN || parsed.CF_DNS_API_TOKEN)
1067
1409
  return ".env file";
1068
1410
  } catch {}
@@ -1077,10 +1419,10 @@ function getHetznerToken(root = process.cwd()) {
1077
1419
  return process.env.HETZNER_API_TOKEN;
1078
1420
  if (process.env.HCLOUD_TOKEN)
1079
1421
  return process.env.HCLOUD_TOKEN;
1080
- const envPath = join2(root, ".env");
1081
- if (existsSync2(envPath)) {
1422
+ const envPath = join3(root, ".env");
1423
+ if (existsSync3(envPath)) {
1082
1424
  try {
1083
- const parsed = parseDotenv(readFileSync2(envPath, "utf8"));
1425
+ const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
1084
1426
  if (parsed.HETZNER_API_TOKEN)
1085
1427
  return parsed.HETZNER_API_TOKEN;
1086
1428
  if (parsed.HCLOUD_TOKEN)
@@ -1095,10 +1437,10 @@ function getHetznerTokenSource(root = process.cwd()) {
1095
1437
  return "environment variable (HETZNER_API_TOKEN)";
1096
1438
  if (process.env.HCLOUD_TOKEN)
1097
1439
  return "environment variable (HCLOUD_TOKEN)";
1098
- const envPath = join2(root, ".env");
1099
- if (existsSync2(envPath)) {
1440
+ const envPath = join3(root, ".env");
1441
+ if (existsSync3(envPath)) {
1100
1442
  try {
1101
- const parsed = parseDotenv(readFileSync2(envPath, "utf8"));
1443
+ const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
1102
1444
  if (parsed.HETZNER_API_TOKEN || parsed.HCLOUD_TOKEN)
1103
1445
  return ".env file";
1104
1446
  } catch {}
@@ -1564,14 +1906,14 @@ class CloudflareClient {
1564
1906
  // src/commands/init.ts
1565
1907
  function detect(root) {
1566
1908
  const name = basename(root).toLowerCase().replace(/[^a-z0-9_-]/g, "-");
1567
- const hasDockerfile = existsSync3(join3(root, "Dockerfile"));
1568
- const pkgPath = join3(root, "package.json");
1569
- if (existsSync3(pkgPath)) {
1909
+ const hasDockerfile = existsSync4(join4(root, "Dockerfile"));
1910
+ const pkgPath = join4(root, "package.json");
1911
+ if (existsSync4(pkgPath)) {
1570
1912
  let pkg = {};
1571
1913
  try {
1572
- pkg = JSON.parse(readFileSync3(pkgPath, "utf8"));
1914
+ pkg = JSON.parse(readFileSync4(pkgPath, "utf8"));
1573
1915
  } catch {}
1574
- const bun = existsSync3(join3(root, "bun.lockb")) || existsSync3(join3(root, "bun.lock"));
1916
+ const bun = existsSync4(join4(root, "bun.lockb")) || existsSync4(join4(root, "bun.lock"));
1575
1917
  const scripts = pkg.scripts ?? {};
1576
1918
  const runner = bun ? "bun" : "npm";
1577
1919
  return {
@@ -1584,13 +1926,13 @@ function detect(root) {
1584
1926
  hasDockerfile
1585
1927
  };
1586
1928
  }
1587
- if (existsSync3(join3(root, "pyproject.toml")) || existsSync3(join3(root, "requirements.txt"))) {
1929
+ if (existsSync4(join4(root, "pyproject.toml")) || existsSync4(join4(root, "requirements.txt"))) {
1588
1930
  return { name, runtime: "python", port: 8000, install: "pip install -r requirements.txt", start: "python -m uvicorn main:app --host 127.0.0.1 --port $PORT", hasDockerfile };
1589
1931
  }
1590
- if (existsSync3(join3(root, "Gemfile"))) {
1932
+ if (existsSync4(join4(root, "Gemfile"))) {
1591
1933
  return { name, runtime: "ruby", port: 3000, install: "bundle install --deployment", start: "bundle exec rails server -p $PORT", hasDockerfile };
1592
1934
  }
1593
- if (existsSync3(join3(root, "go.mod"))) {
1935
+ if (existsSync4(join4(root, "go.mod"))) {
1594
1936
  return { name, runtime: "go", port: 8080, build: "go build -o server .", start: "./server", hasDockerfile };
1595
1937
  }
1596
1938
  return { name, runtime: "unknown", port: 3000, hasDockerfile };
@@ -1811,8 +2153,8 @@ Options
1811
2153
  --force Overwrite an existing epd.yml`,
1812
2154
  async run(ctx) {
1813
2155
  const root = process.cwd();
1814
- const target = join3(root, "epd.yml");
1815
- if (existsSync3(target) && !ctx.values.force) {
2156
+ const target = join4(root, "epd.yml");
2157
+ if (existsSync4(target) && !ctx.values.force) {
1816
2158
  throw new EpdError("epd.yml already exists", "Pass --force to overwrite it.");
1817
2159
  }
1818
2160
  const detected = detect(root);
@@ -1919,7 +2261,7 @@ Options
1919
2261
  registryUser = await ask("Registry username", process.env.USER ?? "");
1920
2262
  image = `${registryServer ? `${registryServer}/` : ""}${registryUser}/${name}`;
1921
2263
  }
1922
- writeFileSync2(target, template({
2264
+ writeFileSync3(target, template({
1923
2265
  name,
1924
2266
  mode,
1925
2267
  sshUser: sshUser || "root",
@@ -1940,7 +2282,7 @@ Options
1940
2282
  if (wantDockerfile) {
1941
2283
  const df = DOCKERFILES[detected.runtime];
1942
2284
  if (df) {
1943
- writeFileSync2(join3(root, "Dockerfile"), df);
2285
+ writeFileSync3(join4(root, "Dockerfile"), df);
1944
2286
  log.ok(`wrote ${c.bold("Dockerfile")} \u2014 check the build and start commands`);
1945
2287
  } else {
1946
2288
  log.warn(`no Dockerfile template for ${detected.runtime}; write one yourself or use \`mode: process\``);
@@ -1948,39 +2290,10 @@ Options
1948
2290
  }
1949
2291
  const wantCi = Boolean(ctx.values.ci) || interactive() && await confirm("Generate GitHub Actions deploy workflow (.github/workflows/deploy.yml)?", false);
1950
2292
  if (wantCi) {
1951
- const workflowDir = join3(root, ".github", "workflows");
1952
- mkdirSync2(workflowDir, { recursive: true });
1953
- const ciYaml = `name: Deploy
1954
-
1955
- on:
1956
- push:
1957
- branches: [main]
1958
-
1959
- concurrency:
1960
- group: deploy-\${{ github.ref }}
1961
- cancel-in-progress: false
1962
-
1963
- jobs:
1964
- deploy:
1965
- runs-on: ubuntu-latest
1966
- steps:
1967
- - name: Checkout repository
1968
- uses: actions/checkout@v4
1969
-
1970
- - name: Setup Bun
1971
- uses: oven-sh/setup-bun@v2
1972
- with:
1973
- bun-version: latest
1974
-
1975
- - name: Install EPD
1976
- run: bun install -g @fabioplunser/epd
1977
-
1978
- - name: Deploy with EPD
1979
- env:
1980
- SSH_PRIVATE_KEY: \${{ secrets.SSH_PRIVATE_KEY }}
1981
- ${cloudflareToken || useCloudflare ? "CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}\n " : ""}${hetznerToken || useHetzner ? "HETZNER_API_TOKEN: ${{ secrets.HETZNER_API_TOKEN }}\n " : ""}run: epd deploy
1982
- `;
1983
- writeFileSync2(join3(workflowDir, "deploy.yml"), ciYaml);
2293
+ const workflowDir = join4(root, ".github", "workflows");
2294
+ mkdirSync3(workflowDir, { recursive: true });
2295
+ const { yaml } = buildWorkflowYaml({ root });
2296
+ writeFileSync3(join4(workflowDir, "deploy.yml"), yaml);
1984
2297
  log.ok(`wrote ${c.bold(".github/workflows/deploy.yml")}`);
1985
2298
  }
1986
2299
  console.log(`
@@ -1992,82 +2305,6 @@ Next steps:`);
1992
2305
  }
1993
2306
  };
1994
2307
 
1995
- // src/util/proc.ts
1996
- async function run(cmd, opts = {}) {
1997
- const label = opts.label ?? cmd.join(" ");
1998
- log.debug(`local: ${cmd.join(" ")}`);
1999
- const proc = Bun.spawn(cmd, {
2000
- cwd: opts.cwd,
2001
- env: opts.env ? { ...process.env, ...opts.env } : process.env,
2002
- stdin: opts.input !== undefined ? new TextEncoder().encode(opts.input) : "inherit",
2003
- stdout: opts.stream ? "inherit" : "pipe",
2004
- stderr: opts.stream && !opts.captureStderr ? "inherit" : "pipe"
2005
- });
2006
- const [stdout, stderr, code] = await Promise.all([
2007
- opts.stream ? Promise.resolve("") : new Response(proc.stdout).text(),
2008
- opts.stream ? opts.captureStderr ? teeStderr(proc.stderr) : Promise.resolve("") : new Response(proc.stderr).text(),
2009
- proc.exited
2010
- ]);
2011
- const result = { code, stdout: stdout.trim(), stderr: stderr.trim() };
2012
- if (code !== 0 && !opts.allowFailure) {
2013
- throw new EpdError(`command failed (exit ${code}): ${label}`, result.stderr || result.stdout || undefined);
2014
- }
2015
- return result;
2016
- }
2017
- async function teeStderr(stream) {
2018
- const reader = stream.getReader();
2019
- const decoder = new TextDecoder;
2020
- let tail = "";
2021
- try {
2022
- while (true) {
2023
- const { done, value } = await reader.read();
2024
- if (done)
2025
- break;
2026
- process.stderr.write(value);
2027
- tail = (tail + decoder.decode(value, { stream: true })).slice(-65536);
2028
- }
2029
- return (tail + decoder.decode()).slice(-65536);
2030
- } finally {
2031
- reader.releaseLock();
2032
- }
2033
- }
2034
- async function runShell(script, opts = {}) {
2035
- return run(["/bin/sh", "-c", script], { ...opts, label: opts.label ?? script });
2036
- }
2037
- async function which(bin) {
2038
- const r = await run(["/bin/sh", "-c", `command -v ${bin}`], { allowFailure: true });
2039
- return r.code === 0 && r.stdout ? r.stdout.split(`
2040
- `)[0].trim() : null;
2041
- }
2042
- async function requireLocal(bin, hint) {
2043
- if (!await which(bin))
2044
- throw new EpdError(`\`${bin}\` was not found on this machine`, hint);
2045
- }
2046
-
2047
- // src/config/types.ts
2048
- function allHosts(cfg) {
2049
- const s = new Set;
2050
- for (const svc of cfg.services)
2051
- for (const h of svc.hosts)
2052
- s.add(h);
2053
- for (const a of cfg.accessories)
2054
- s.add(a.host);
2055
- return [...s];
2056
- }
2057
- function proxyHosts(cfg) {
2058
- if (!cfg.proxy.enabled)
2059
- return [];
2060
- const s = new Set;
2061
- for (const svc of cfg.services)
2062
- if (svc.routes.length)
2063
- for (const h of svc.hosts)
2064
- s.add(h);
2065
- for (const a of cfg.accessories)
2066
- if (a.routes.length)
2067
- s.add(a.host);
2068
- return [...s];
2069
- }
2070
-
2071
2308
  // src/core/names.ts
2072
2309
  var SLOTS = ["blue", "green"];
2073
2310
  var otherSlot = (s) => s === "blue" ? "green" : "blue";
@@ -2284,11 +2521,11 @@ true`, { allowFailure: true, stream: true, label: `${host.name}: install package
2284
2521
  }
2285
2522
 
2286
2523
  // src/core/ssh.ts
2287
- import { mkdirSync as mkdirSync3 } from "fs";
2524
+ import { chmodSync as chmodSync2, existsSync as existsSync5, mkdirSync as mkdirSync4, writeFileSync as writeFileSync4 } from "fs";
2288
2525
  import { tmpdir } from "os";
2289
- import { join as join4 } from "path";
2290
- var controlDir = join4(tmpdir(), `epd-${process.getuid?.() ?? 0}`);
2291
- mkdirSync3(controlDir, { recursive: true, mode: 448 });
2526
+ import { join as join5 } from "path";
2527
+ var controlDir = join5(tmpdir(), `epd-${process.getuid?.() ?? 0}`);
2528
+ mkdirSync4(controlDir, { recursive: true, mode: 448 });
2292
2529
  var sudoPasswords = new Map;
2293
2530
  var promptQueue = Promise.resolve();
2294
2531
  function needsSudoPassword(res) {
@@ -2344,7 +2581,7 @@ class Host {
2344
2581
  `);
2345
2582
  }
2346
2583
  sshOptions() {
2347
- const socket = join4(controlDir, `${hash32(`${this.cfg.user}@${this.name}:${this.cfg.port}`).toString(36)}.sock`);
2584
+ const socket = join5(controlDir, `${hash32(`${this.cfg.user}@${this.name}:${this.cfg.port}`).toString(36)}.sock`);
2348
2585
  const args = [
2349
2586
  "-o",
2350
2587
  "BatchMode=yes",
@@ -2363,8 +2600,25 @@ class Host {
2363
2600
  "-p",
2364
2601
  String(this.cfg.port)
2365
2602
  ];
2366
- if (this.cfg.key)
2367
- args.push("-i", this.cfg.key, "-o", "IdentitiesOnly=yes");
2603
+ let keyPath = this.cfg.key;
2604
+ if (!keyPath) {
2605
+ const rawEnvKey = process.env.SSH_PRIVATE_KEY || process.env.EPD_SSH_KEY;
2606
+ if (rawEnvKey) {
2607
+ if (rawEnvKey.includes("-----BEGIN") || rawEnvKey.includes(`
2608
+ `)) {
2609
+ keyPath = join5(controlDir, "ci_id_rsa");
2610
+ try {
2611
+ writeFileSync4(keyPath, rawEnvKey.trim() + `
2612
+ `, { mode: 384 });
2613
+ chmodSync2(keyPath, 384);
2614
+ } catch {}
2615
+ } else if (existsSync5(rawEnvKey)) {
2616
+ keyPath = rawEnvKey;
2617
+ }
2618
+ }
2619
+ }
2620
+ if (keyPath)
2621
+ args.push("-i", keyPath, "-o", "IdentitiesOnly=yes");
2368
2622
  if (this.cfg.proxyJump)
2369
2623
  args.push("-J", this.cfg.proxyJump);
2370
2624
  for (const o of this.cfg.options)
@@ -2402,7 +2656,7 @@ ${script}
2402
2656
  const pw = await askSudoPassword(this.sudoKey, this.target);
2403
2657
  if (pw)
2404
2658
  res = await this.ssh(body, true, pw, opts.stream, label);
2405
- else if (!opts.allowFailure)
2659
+ else
2406
2660
  throw new EpdError(`${this.name}: sudo needs a password for ${this.target}`, this.sudoHint());
2407
2661
  }
2408
2662
  if (useSudo && res.code !== 0 && needsSudoPassword(res) && !opts.allowFailure) {
@@ -2471,7 +2725,10 @@ mv -f ${shq(path)}.tmp ${shq(path)}`, { label: `${this.name}: write ${path}` });
2471
2725
  async ping() {
2472
2726
  const res = await this.exec("echo epd-ok", { allowFailure: true, sudo: false });
2473
2727
  if (res.code !== 0 || !res.stdout.includes("epd-ok")) {
2474
- throw new EpdError(`cannot reach ${this.target}:${this.cfg.port}`, res.stderr || "Check that the host is up and your SSH key is authorized.");
2728
+ const isPublickey = res.stderr.includes("Permission denied (publickey)");
2729
+ const hint = isPublickey ? "SSH key authentication failed. Ensure the SSH key is in ~/.ssh/authorized_keys on the server and has NO passphrase (passphrases cannot be entered in non-interactive CI)." : res.stderr || "Check that the host is up and your SSH key is authorized.";
2730
+ throw new EpdError(`cannot reach ${this.target}:${this.cfg.port}`, res.stderr ? `${res.stderr}
2731
+ ${hint}` : hint);
2475
2732
  }
2476
2733
  }
2477
2734
  }
@@ -2491,9 +2748,9 @@ function host(name, cfg) {
2491
2748
  }
2492
2749
 
2493
2750
  // src/core/ssh-setup.ts
2494
- import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync4 } from "fs";
2751
+ import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync5 } from "fs";
2495
2752
  import { homedir as homedir3 } from "os";
2496
- import { join as join5 } from "path";
2753
+ import { join as join6 } from "path";
2497
2754
  var setupQueue = Promise.resolve();
2498
2755
  async function prepareSsh(host, canInstallKey = interactive()) {
2499
2756
  const probe = () => run([
@@ -2556,9 +2813,9 @@ async function publicKeyFor(host) {
2556
2813
  const identityIndex = options.indexOf("-i");
2557
2814
  const identity = identityIndex >= 0 ? options[identityIndex + 1] : undefined;
2558
2815
  if (identity) {
2559
- if (existsSync4(`${identity}.pub`))
2560
- return validateKey(readFileSync4(`${identity}.pub`, "utf8"));
2561
- if (!existsSync4(identity))
2816
+ if (existsSync6(`${identity}.pub`))
2817
+ return validateKey(readFileSync5(`${identity}.pub`, "utf8"));
2818
+ if (!existsSync6(identity))
2562
2819
  throw new EpdError(`SSH identity does not exist: ${identity}`);
2563
2820
  const proc = Bun.spawn(["ssh-keygen", "-y", "-f", identity], {
2564
2821
  stdin: "inherit",
@@ -2577,17 +2834,17 @@ async function publicKeyFor(host) {
2577
2834
  const selected = keys.length === 1 ? "0" : await choose("Which SSH agent key should EPD authorize?", keys.map((key, index) => ({ value: String(index), label: key.split(/\s+/).slice(2).join(" ") || `Agent key ${index + 1}` })), "0");
2578
2835
  return validateKey(keys[Number(selected)]);
2579
2836
  }
2580
- const sshDir = join5(homedir3(), ".ssh");
2837
+ const sshDir = join6(homedir3(), ".ssh");
2581
2838
  for (const name of ["id_ed25519", "id_ecdsa", "id_rsa"]) {
2582
- const path = join5(sshDir, `${name}.pub`);
2583
- if (existsSync4(path))
2584
- return validateKey(readFileSync4(path, "utf8"));
2839
+ const path = join6(sshDir, `${name}.pub`);
2840
+ if (existsSync6(path))
2841
+ return validateKey(readFileSync5(path, "utf8"));
2585
2842
  }
2586
- const keyPath = join5(sshDir, "id_ed25519");
2587
- if (existsSync4(keyPath)) {
2843
+ const keyPath = join6(sshDir, "id_ed25519");
2844
+ if (existsSync6(keyPath)) {
2588
2845
  throw new EpdError(`Missing public key for ${keyPath}`, "Load it with ssh-add, or set ssh.key to its path, then retry.");
2589
2846
  }
2590
- mkdirSync4(sshDir, { recursive: true, mode: 448 });
2847
+ mkdirSync5(sshDir, { recursive: true, mode: 448 });
2591
2848
  log.info(`Creating ${keyPath}; ssh-keygen will ask you for a passphrase`);
2592
2849
  const generated = await run(["ssh-keygen", "-t", "ed25519", "-f", keyPath, "-C", "epd"], { stream: true, allowFailure: true });
2593
2850
  if (generated.code !== 0)
@@ -2595,7 +2852,7 @@ async function publicKeyFor(host) {
2595
2852
  const loaded = await run(["ssh-add", keyPath], { stream: true, allowFailure: true });
2596
2853
  if (loaded.code !== 0)
2597
2854
  log.warn("Could not load the new key into ssh-agent; encrypted keys require ssh-add before deployment");
2598
- return validateKey(readFileSync4(`${keyPath}.pub`, "utf8"));
2855
+ return validateKey(readFileSync5(`${keyPath}.pub`, "utf8"));
2599
2856
  }
2600
2857
  function validateKey(value) {
2601
2858
  const key = value.trim();
@@ -2606,7 +2863,7 @@ function validateKey(value) {
2606
2863
  }
2607
2864
 
2608
2865
  // src/proxy/detect.ts
2609
- import { existsSync as existsSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
2866
+ import { existsSync as existsSync7, readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "fs";
2610
2867
  import { basename as basename2, resolve as resolve2 } from "path";
2611
2868
  async function detectExistingProxy(host, checkPorts = [80, 443]) {
2612
2869
  const portsSet = new Set(checkPorts);
@@ -2722,34 +2979,54 @@ function getConfigDomains(cfg) {
2722
2979
  }
2723
2980
  return domains.size ? [...domains] : [cfg.name.toLowerCase() + ".example.com"];
2724
2981
  }
2725
- function getServiceUpstreamPort(cfg) {
2982
+ function getServiceUpstreamPorts(cfg) {
2726
2983
  const mainSvc = cfg.services[0];
2727
2984
  if (!mainSvc)
2728
- return 8080;
2729
- if (mainSvc.hostPort)
2730
- return mainSvc.hostPort;
2731
- if (mainSvc.port > 1024)
2732
- return mainSvc.port;
2733
- return 8080;
2734
- }
2735
- function generateCaddyConfig(cfg, upstreamHost = "127.0.0.1", upstreamPort = getServiceUpstreamPort(cfg)) {
2985
+ return { blue: 8080, green: 8096 };
2986
+ return {
2987
+ blue: hostPort(cfg, mainSvc, "blue", 0),
2988
+ green: hostPort(cfg, mainSvc, "green", 0)
2989
+ };
2990
+ }
2991
+ function getServiceUpstreamPort(cfg) {
2992
+ return getServiceUpstreamPorts(cfg).blue;
2993
+ }
2994
+ function generateCaddyConfig(cfg, upstreamHost = "127.0.0.1", upstreamPort) {
2736
2995
  const domains = getConfigDomains(cfg);
2996
+ const ports = getServiceUpstreamPorts(cfg);
2997
+ const bluePort = upstreamPort ?? ports.blue;
2998
+ const greenPort = upstreamPort ? upstreamPort + 16 : ports.green;
2999
+ const healthPath = cfg.services[0]?.health.path || "/";
2737
3000
  return `# EPD Reverse Proxy Configuration for ${cfg.name}
2738
3001
  ${domains.join(", ")} {
2739
- reverse_proxy ${upstreamHost}:${upstreamPort}
3002
+ reverse_proxy ${upstreamHost}:${bluePort} ${upstreamHost}:${greenPort} {
3003
+ health_uri ${healthPath}
3004
+ health_interval 2s
3005
+ health_timeout 1s
3006
+ lb_policy first
3007
+ }
2740
3008
  }
2741
3009
  `;
2742
3010
  }
2743
- function generateNginxConfig(cfg, upstreamHost = "127.0.0.1", upstreamPort = getServiceUpstreamPort(cfg)) {
3011
+ function generateNginxConfig(cfg, upstreamHost = "127.0.0.1", upstreamPort) {
2744
3012
  const domains = getConfigDomains(cfg);
3013
+ const ports = getServiceUpstreamPorts(cfg);
3014
+ const bluePort = upstreamPort ?? ports.blue;
3015
+ const greenPort = upstreamPort ? upstreamPort + 16 : ports.green;
3016
+ const upstreamName = `epd_${cfg.name.toLowerCase().replace(/[^a-z0-9_]/g, "_")}`;
2745
3017
  return `# EPD Reverse Proxy Configuration for ${cfg.name}
3018
+ upstream ${upstreamName} {
3019
+ server ${upstreamHost}:${bluePort} max_fails=1 fail_timeout=5s;
3020
+ server ${upstreamHost}:${greenPort} max_fails=1 fail_timeout=5s;
3021
+ }
3022
+
2746
3023
  server {
2747
3024
  listen 80;
2748
3025
  listen [::]:80;
2749
3026
  server_name ${domains.join(" ")};
2750
3027
 
2751
3028
  location / {
2752
- proxy_pass http://${upstreamHost}:${upstreamPort};
3029
+ proxy_pass http://${upstreamName};
2753
3030
  proxy_http_version 1.1;
2754
3031
  proxy_set_header Upgrade $http_upgrade;
2755
3032
  proxy_set_header Connection "upgrade";
@@ -2800,10 +3077,10 @@ http:
2800
3077
  }
2801
3078
  function updateLocalConfigDisableProxy(configPath = "epd.yml") {
2802
3079
  const configFile = resolve2(configPath);
2803
- if (!existsSync5(configFile))
3080
+ if (!existsSync7(configFile))
2804
3081
  return;
2805
3082
  try {
2806
- const raw = readFileSync5(configFile, "utf8");
3083
+ const raw = readFileSync6(configFile, "utf8");
2807
3084
  if (/^\s*proxy\s*:\s*false\b/m.test(raw))
2808
3085
  return;
2809
3086
  let updated = raw;
@@ -2815,7 +3092,7 @@ function updateLocalConfigDisableProxy(configPath = "epd.yml") {
2815
3092
  `);
2816
3093
  }
2817
3094
  if (updated !== raw) {
2818
- writeFileSync3(configFile, updated, "utf8");
3095
+ writeFileSync5(configFile, updated, "utf8");
2819
3096
  log.ok("Updated epd.yml: set proxy: false");
2820
3097
  }
2821
3098
  } catch (err) {
@@ -2902,8 +3179,8 @@ ${c.gray(snippet)}`);
2902
3179
  log.plain(`
2903
3180
  ${c.yellow("!")} Unrecognized reverse proxy detected (${detected.details}).`);
2904
3181
  const customConfig = await ask("Provide path to your custom proxy configuration file to deploy (or leave empty to configure manually):");
2905
- if (customConfig && existsSync5(customConfig)) {
2906
- const content = readFileSync5(customConfig, "utf8");
3182
+ if (customConfig && existsSync7(customConfig)) {
3183
+ const content = readFileSync6(customConfig, "utf8");
2907
3184
  const defaultRemote = `/etc/proxy/${basename2(customConfig)}`;
2908
3185
  const remotePath = await ask(`Remote destination path on ${host.name}:`, defaultRemote);
2909
3186
  await host.writeFile(remotePath, content);
@@ -2914,35 +3191,77 @@ ${c.yellow("!")} Unrecognized reverse proxy detected (${detected.details}).`);
2914
3191
  }
2915
3192
  return true;
2916
3193
  }
2917
- async function checkExistingProxySetup(host, cfg) {
3194
+ async function syncExternalProxy(host, cfg) {
2918
3195
  const detected = await detectExistingProxy(host);
2919
3196
  if (!detected)
2920
3197
  return;
2921
3198
  const domains = getConfigDomains(cfg);
2922
- const upstreamPort = getServiceUpstreamPort(cfg);
2923
- log.host(host.name, `proxy is disabled in epd.yml; active ${detected.name} detected on port(s) ${detected.ports.join("/")}`);
3199
+ const ports = getServiceUpstreamPorts(cfg);
2924
3200
  if (detected.type === "caddy") {
2925
3201
  const caddyfile = await host.readFile("/etc/caddy/Caddyfile") ?? "";
2926
- const confDExists = await host.readFile(`/etc/caddy/conf.d/${cfg.name}.caddy`) !== null;
2927
- const isConfigured = confDExists || domains.some((d) => caddyfile.includes(d));
2928
- if (isConfigured) {
2929
- log.host(host.name, `Caddy is already configured for ${domains.join(", ")}`);
2930
- } else if (interactive()) {
2931
- const install = await confirm(`Would you like EPD to generate and install the Caddy configuration for ${domains.join(", ")}?`, true);
2932
- if (install) {
2933
- const snippet = generateCaddyConfig(cfg, "127.0.0.1", upstreamPort);
2934
- await host.writeFile(`/etc/caddy/conf.d/${cfg.name}.caddy`, snippet);
2935
- if (!caddyfile.includes("import conf.d/*") && !caddyfile.includes("import /etc/caddy/conf.d/*")) {
2936
- await host.writeFile("/etc/caddy/Caddyfile", `${caddyfile}
2937
- import /etc/caddy/conf.d/*
2938
- `);
2939
- }
3202
+ const confDFile = `/etc/caddy/conf.d/${cfg.name}.caddy`;
3203
+ const confD = await host.readFile(confDFile);
3204
+ const hasBothPorts = (text) => text.includes(String(ports.blue)) && text.includes(String(ports.green));
3205
+ if (confD && hasBothPorts(confD)) {
3206
+ return;
3207
+ }
3208
+ if (confD && !hasBothPorts(confD)) {
3209
+ const snippet = generateCaddyConfig(cfg, "127.0.0.1");
3210
+ await host.writeFile(confDFile, snippet);
3211
+ await host.exec("systemctl reload caddy || caddy reload || true", { allowFailure: true });
3212
+ log.host(host.name, `updated Caddy configuration in ${confDFile} for zero-downtime blue/green failover`);
3213
+ return;
3214
+ }
3215
+ const hasDomain = domains.some((d) => caddyfile.includes(d));
3216
+ if (hasDomain && hasBothPorts(caddyfile)) {
3217
+ return;
3218
+ }
3219
+ if (hasDomain && !hasBothPorts(caddyfile)) {
3220
+ const singlePortRegex = new RegExp(`reverse_proxy\\s+(?:(?:https?://)?127\\.0\\.0\\.1:)?${ports.blue}\\b[^\\n{]*`, "g");
3221
+ if (singlePortRegex.test(caddyfile)) {
3222
+ const healthPath = cfg.services[0]?.health.path || "/";
3223
+ const replacement = `reverse_proxy 127.0.0.1:${ports.blue} 127.0.0.1:${ports.green} {
3224
+ health_uri ${healthPath}
3225
+ health_interval 2s
3226
+ health_timeout 1s
3227
+ lb_policy first
3228
+ }`;
3229
+ const updated = caddyfile.replace(singlePortRegex, replacement);
3230
+ await host.writeFile("/etc/caddy/Caddyfile", updated);
2940
3231
  await host.exec("systemctl reload caddy || caddy reload || true", { allowFailure: true });
2941
- log.ok(`${host.name}: Caddy configuration installed and reloaded`);
3232
+ log.host(host.name, `updated /etc/caddy/Caddyfile for ${domains.join(", ")} to include blue/green ports (${ports.blue}/${ports.green})`);
3233
+ return;
2942
3234
  }
2943
3235
  }
3236
+ const snippet = generateCaddyConfig(cfg, "127.0.0.1");
3237
+ await host.writeFile(confDFile, snippet);
3238
+ if (!caddyfile.includes("import conf.d/*") && !caddyfile.includes("import /etc/caddy/conf.d/*")) {
3239
+ await host.writeFile("/etc/caddy/Caddyfile", `${caddyfile}
3240
+ import /etc/caddy/conf.d/*
3241
+ `);
3242
+ }
3243
+ await host.exec("systemctl reload caddy || caddy reload || true", { allowFailure: true });
3244
+ log.host(host.name, `installed Caddy configuration in ${confDFile} and reloaded Caddy`);
3245
+ } else if (detected.type === "nginx") {
3246
+ const confPath = `/etc/nginx/sites-available/${cfg.name}.conf`;
3247
+ const confContent = await host.readFile(confPath);
3248
+ const hasBothPorts = confContent && confContent.includes(String(ports.blue)) && confContent.includes(String(ports.green));
3249
+ if (!hasBothPorts) {
3250
+ const snippet = generateNginxConfig(cfg, "127.0.0.1");
3251
+ await host.writeFile(confPath, snippet);
3252
+ await host.exec(`ln -sf ${shq(confPath)} /etc/nginx/sites-enabled/${cfg.name}.conf && nginx -t && systemctl reload nginx || true`, { allowFailure: true });
3253
+ log.host(host.name, `installed/updated Nginx configuration for ${domains.join(", ")} with blue/green upstreams`);
3254
+ }
2944
3255
  }
2945
3256
  }
3257
+ async function checkExistingProxySetup(host, cfg) {
3258
+ const detected = await detectExistingProxy(host);
3259
+ if (!detected)
3260
+ return;
3261
+ const domains = getConfigDomains(cfg);
3262
+ log.host(host.name, `proxy is disabled in epd.yml; active ${detected.name} detected on port(s) ${detected.ports.join("/")}`);
3263
+ await syncExternalProxy(host, cfg);
3264
+ }
2946
3265
 
2947
3266
  // src/proxy/ports.ts
2948
3267
  async function checkProxyPorts(host, ports, cfg) {
@@ -3498,7 +3817,7 @@ else
3498
3817
  cat ${shq(dir)}/info 2>/dev/null || echo '{}'
3499
3818
  exit 9
3500
3819
  fi`, { allowFailure: true });
3501
- if (res.code !== 0) {
3820
+ if (res.code === 9) {
3502
3821
  await this.release();
3503
3822
  let held = {};
3504
3823
  try {
@@ -3507,6 +3826,10 @@ fi`, { allowFailure: true });
3507
3826
  throw new EpdError(`${this.cfg.name} is locked on ${host.name}`, held.by ? `Held by ${held.by} since ${held.at} (${held.what}).
3508
3827
  If that deploy died, run: epd lock release` : "Run `epd lock release` if a previous deploy was interrupted.");
3509
3828
  }
3829
+ if (res.code !== 0) {
3830
+ await this.release();
3831
+ throw new EpdError(`failed to acquire deploy lock on ${host.name}`, res.stderr || res.stdout || undefined);
3832
+ }
3510
3833
  this.held.push(host);
3511
3834
  }
3512
3835
  log.debug(`lock acquired on ${this.held.length} host(s)`);
@@ -3519,7 +3842,7 @@ If that deploy died, run: epd lock release` : "Run `epd lock release` if a previ
3519
3842
  }
3520
3843
  static async forceRelease(cfg, hosts) {
3521
3844
  for (const host of hosts)
3522
- await host.exec(`rm -rf ${shq(paths(cfg).lock)}`, { allowFailure: true });
3845
+ await host.exec(`rm -rf ${shq(paths(cfg).lock)}`);
3523
3846
  }
3524
3847
  static async status(cfg, hosts) {
3525
3848
  const out = [];
@@ -3678,12 +4001,12 @@ function recordDeploy(state, version, by, keep) {
3678
4001
  }
3679
4002
 
3680
4003
  // src/deploy/image.ts
3681
- import { existsSync as existsSync6 } from "fs";
3682
- import { join as join6 } from "path";
4004
+ import { existsSync as existsSync8 } from "fs";
4005
+ import { join as join7 } from "path";
3683
4006
  async function resolveVersion(cfg, explicit) {
3684
4007
  if (explicit)
3685
4008
  return { id: explicit, source: "explicit", dirty: false };
3686
- if (existsSync6(join6(cfg.root, ".git")) && await which("git")) {
4009
+ if (existsSync8(join7(cfg.root, ".git")) && await which("git")) {
3687
4010
  const sha = await run(["git", "-C", cfg.root, "rev-parse", "--short=12", "HEAD"], { allowFailure: true });
3688
4011
  if (sha.code === 0 && sha.stdout) {
3689
4012
  const status = await run(["git", "-C", cfg.root, "status", "--porcelain"], { allowFailure: true });
@@ -3698,8 +4021,8 @@ async function hasBuildx() {
3698
4021
  return (await run(["docker", "buildx", "version"], { allowFailure: true })).code === 0;
3699
4022
  }
3700
4023
  async function buildImage(cfg, version, env) {
3701
- const dockerfile = join6(cfg.root, cfg.build.dockerfile);
3702
- if (!existsSync6(dockerfile)) {
4024
+ const dockerfile = join7(cfg.root, cfg.build.dockerfile);
4025
+ if (!existsSync8(dockerfile)) {
3703
4026
  throw new EpdError(`${cfg.build.dockerfile} not found`, "Add a Dockerfile, point build.dockerfile at yours, or switch to `mode: process`.");
3704
4027
  }
3705
4028
  const ref = imageRef(cfg, version);
@@ -3712,7 +4035,7 @@ async function buildImage(cfg, version, env) {
3712
4035
  async function buildWithBuildx(cfg, ref, version, env) {
3713
4036
  const args = ["docker", "buildx", "build"];
3714
4037
  args.push("--platform", cfg.build.platform);
3715
- args.push("--file", join6(cfg.root, cfg.build.dockerfile));
4038
+ args.push("--file", join7(cfg.root, cfg.build.dockerfile));
3716
4039
  args.push("--tag", ref, "--tag", `${cfg.image}:latest`);
3717
4040
  if (cfg.build.target)
3718
4041
  args.push("--target", cfg.build.target);
@@ -3745,7 +4068,7 @@ async function buildWithLegacyDocker(cfg, ref, version, env) {
3745
4068
  if (cfg.build.platform !== localPlatform) {
3746
4069
  log.warn(`buildx is not installed, so the image is built for ${localPlatform} rather than ${cfg.build.platform}. ` + `Install buildx to cross-build, or set build.platform: ${localPlatform}.`);
3747
4070
  }
3748
- const args = ["docker", "build", "--file", join6(cfg.root, cfg.build.dockerfile), "--tag", ref, "--tag", `${cfg.image}:latest`];
4071
+ const args = ["docker", "build", "--file", join7(cfg.root, cfg.build.dockerfile), "--tag", ref, "--tag", `${cfg.image}:latest`];
3749
4072
  if (cfg.build.target)
3750
4073
  args.push("--target", cfg.build.target);
3751
4074
  for (const [k, v] of Object.entries(cfg.build.args))
@@ -3978,8 +4301,8 @@ ${args.map((a) => shq(a)).join(" ")} >/dev/null`, { label: `${host.name}: access
3978
4301
  }
3979
4302
 
3980
4303
  // src/deploy/process.ts
3981
- import { existsSync as existsSync7 } from "fs";
3982
- import { join as join7 } from "path";
4304
+ import { existsSync as existsSync9 } from "fs";
4305
+ import { join as join8 } from "path";
3983
4306
  var asUser = { sudo: false };
3984
4307
  var pm2 = (cfg, args) => `${pathPrelude(cfg)} pm2 ${args}`;
3985
4308
  function releaseDir(cfg, version) {
@@ -3990,7 +4313,7 @@ async function uploadSource(host, cfg, version) {
3990
4313
  const p = paths(cfg);
3991
4314
  await host.exec(`mkdir -p ${shq(p.releases)} ${shq(p.shared)}`, asUser);
3992
4315
  if (cfg.process.source === "git") {
3993
- if (!existsSync7(join7(cfg.root, ".git")))
4316
+ if (!existsSync9(join8(cfg.root, ".git")))
3994
4317
  throw new EpdError('process.source is "git" but this is not a git repository');
3995
4318
  log.host(host.name, `uploading HEAD as ${version}`);
3996
4319
  await host.pipeInto(`mkdir -p ${shq(dest)} && tar -x -C ${shq(dest)}`, ["/bin/sh", "-c", `git -C ${shq(cfg.root)} archive --format=tar HEAD`]);
@@ -4570,6 +4893,12 @@ async function deploy(loaded, opts = {}) {
4570
4893
  const hosts = targetHosts.map((h) => host(h, cfg.ssh));
4571
4894
  const version = (await resolveVersion(cfg, opts.version)).id;
4572
4895
  log.step(`Deploying ${c.bold(cfg.name)} ${c.cyan(version)}${cfg.destination ? ` \u2192 ${cfg.destination}` : ""} to ${targetHosts.length} host(s)`);
4896
+ for (const host of hosts) {
4897
+ await host.ping();
4898
+ if (host.user !== "root") {
4899
+ await host.exec("true", { label: `${host.target}: sudo authorization` });
4900
+ }
4901
+ }
4573
4902
  if (!opts.skipHooks && cfg.hooks.preBuild)
4574
4903
  await hook(cfg, "pre_build", cfg.hooks.preBuild, version);
4575
4904
  if (cfg.mode === "docker" && !opts.reuse) {
@@ -4698,6 +5027,8 @@ async function deployToHost(d) {
4698
5027
  if (cfg.proxy.enabled && (hasSvcRoutes || hasAccRoutes)) {
4699
5028
  await writeRoutes(host, cfg, buildEndpoints(cfg, host.name, live), buildAccessoryEndpoints(cfg, host.name));
4700
5029
  log.host(host.name, "routes updated");
5030
+ } else if (!cfg.proxy.enabled && (hasSvcRoutes || hasAccRoutes)) {
5031
+ await syncExternalProxy(host, cfg);
4701
5032
  }
4702
5033
  for (const svc of services) {
4703
5034
  const old = previous.get(svc.name);
@@ -4922,6 +5253,9 @@ Options
4922
5253
  await prepareSsh(host);
4923
5254
  log.host(host.name, "SSH key authentication succeeded");
4924
5255
  await host.exec("true", { label: `${host.target}: sudo authorization` });
5256
+ if (host.user !== "root") {
5257
+ await host.exec(`echo ${shq(`${host.user} ALL=(ALL) NOPASSWD:ALL`)} > /etc/sudoers.d/epd && chmod 440 /etc/sudoers.d/epd`, { allowFailure: true, label: `${host.target}: configure passwordless sudo` });
5258
+ }
4925
5259
  }
4926
5260
  await pool(hosts, 4, async (host) => {
4927
5261
  await host.ping();
@@ -6666,9 +7000,9 @@ function stripAnsi2(str) {
6666
7000
  }
6667
7001
 
6668
7002
  // src/core/update.ts
6669
- import { chmodSync as chmodSync2, existsSync as existsSync8, mkdirSync as mkdirSync5, readFileSync as readFileSync6, renameSync, writeFileSync as writeFileSync4 } from "fs";
7003
+ import { chmodSync as chmodSync3, existsSync as existsSync10, mkdirSync as mkdirSync6, readFileSync as readFileSync7, renameSync, writeFileSync as writeFileSync6 } from "fs";
6670
7004
  import { homedir as homedir4 } from "os";
6671
- import { dirname as dirname2, join as join8 } from "path";
7005
+ import { dirname as dirname3, join as join9 } from "path";
6672
7006
  function parseSemver(v) {
6673
7007
  const clean = v.replace(/^v/, "").trim();
6674
7008
  const parts = clean.split("-")[0].split(".").map((n) => Number(n) || 0);
@@ -6688,13 +7022,13 @@ function isNewer(current, latest) {
6688
7022
  return lPatch > cPatch;
6689
7023
  }
6690
7024
  function getCachePath() {
6691
- return join8(homedir4(), ".epd", "update-check.json");
7025
+ return join9(homedir4(), ".epd", "update-check.json");
6692
7026
  }
6693
7027
  function readCache() {
6694
7028
  try {
6695
7029
  const p = getCachePath();
6696
- if (existsSync8(p)) {
6697
- return JSON.parse(readFileSync6(p, "utf8"));
7030
+ if (existsSync10(p)) {
7031
+ return JSON.parse(readFileSync7(p, "utf8"));
6698
7032
  }
6699
7033
  } catch {}
6700
7034
  return null;
@@ -6702,9 +7036,9 @@ function readCache() {
6702
7036
  function writeCache(latestVersion) {
6703
7037
  try {
6704
7038
  const p = getCachePath();
6705
- mkdirSync5(dirname2(p), { recursive: true });
7039
+ mkdirSync6(dirname3(p), { recursive: true });
6706
7040
  const data = { lastChecked: Date.now(), latestVersion };
6707
- writeFileSync4(p, JSON.stringify(data));
7041
+ writeFileSync6(p, JSON.stringify(data));
6708
7042
  } catch {}
6709
7043
  }
6710
7044
  async function fetchLatestNpmVersion() {
@@ -6771,8 +7105,8 @@ async function performUpdate(targetVersion) {
6771
7105
  throw new Error(`HTTP ${res.status} ${res.statusText}`);
6772
7106
  const buf = await res.arrayBuffer();
6773
7107
  const tmpPath = `${execPath}.tmp.${Date.now()}`;
6774
- writeFileSync4(tmpPath, Buffer.from(buf));
6775
- chmodSync2(tmpPath, 493);
7108
+ writeFileSync6(tmpPath, Buffer.from(buf));
7109
+ chmodSync3(tmpPath, 493);
6776
7110
  renameSync(tmpPath, execPath);
6777
7111
  return true;
6778
7112
  }
@@ -7556,8 +7890,8 @@ Options
7556
7890
  };
7557
7891
 
7558
7892
  // src/commands/backup.ts
7559
- import { createWriteStream, mkdirSync as mkdirSync6, statSync } from "fs";
7560
- import { dirname as dirname3, join as join9, resolve as resolve3 } from "path";
7893
+ import { createWriteStream, mkdirSync as mkdirSync7, statSync } from "fs";
7894
+ import { dirname as dirname4, join as join10, resolve as resolve3 } from "path";
7561
7895
  function detectAccessoryType(decl, cfg) {
7562
7896
  const name = decl.name;
7563
7897
  const img = (decl.image || "").toLowerCase();
@@ -7648,7 +7982,7 @@ Options
7648
7982
  targets = accessories.map((a) => detectAccessoryType(a, cfg));
7649
7983
  }
7650
7984
  const outBaseDir = resolve3(process.cwd(), "backups");
7651
- mkdirSync6(outBaseDir, { recursive: true });
7985
+ mkdirSync7(outBaseDir, { recursive: true });
7652
7986
  for (const target of targets) {
7653
7987
  const host2 = host(target.hostName, cfg.ssh);
7654
7988
  const isRunning = await host2.test(`docker ps -q -f name=${shq(`^${target.containerName}$`)} | grep -q .`);
@@ -7659,8 +7993,8 @@ Options
7659
7993
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-").replace("T", "_").slice(0, 19);
7660
7994
  const ext = target.type === "volume" ? "tar.gz" : "sql.gz";
7661
7995
  const filename = `${cfg.name}-${target.name}-${timestamp}.${ext}`;
7662
- const localFile = ctx.values.output ? resolve3(String(ctx.values.output)) : join9(outBaseDir, filename);
7663
- mkdirSync6(dirname3(localFile), { recursive: true });
7996
+ const localFile = ctx.values.output ? resolve3(String(ctx.values.output)) : join10(outBaseDir, filename);
7997
+ mkdirSync7(dirname4(localFile), { recursive: true });
7664
7998
  let dumpCmd = "";
7665
7999
  if (target.type === "postgres") {
7666
8000
  dumpCmd = `docker exec ${shq(target.containerName)} pg_dump -U ${shq(target.dbUser)} ${shq(target.dbName)} | gzip -9`;
@@ -7707,7 +8041,7 @@ Options
7707
8041
  };
7708
8042
 
7709
8043
  // src/commands/restore.ts
7710
- import { createReadStream, existsSync as existsSync9 } from "fs";
8044
+ import { createReadStream, existsSync as existsSync11 } from "fs";
7711
8045
  import { basename as basename3, resolve as resolve4 } from "path";
7712
8046
  var restore = {
7713
8047
  name: "restore",
@@ -7728,7 +8062,7 @@ Options
7728
8062
  if (!backupPath)
7729
8063
  throw new EpdError("Please provide a path to the backup file to restore.");
7730
8064
  const absPath = resolve4(backupPath);
7731
- if (!existsSync9(absPath))
8065
+ if (!existsSync11(absPath))
7732
8066
  throw new EpdError(`Backup file not found: ${absPath}`);
7733
8067
  const loaded = ctx.load();
7734
8068
  const cfg = loaded.config;
@@ -7854,7 +8188,8 @@ var commands = [
7854
8188
  ssl,
7855
8189
  top,
7856
8190
  backup,
7857
- restore
8191
+ restore,
8192
+ ghAction
7858
8193
  ];
7859
8194
 
7860
8195
  // src/cli.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabioplunser/epd",
3
- "version": "0.5.7",
3
+ "version": "0.5.9",
4
4
  "description": "Easy Project Deployer — deploy any project to one or many servers with Docker or PM2, fronted by Traefik.",
5
5
  "type": "module",
6
6
  "author": "Fabio Plünser",