import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { fileURLToPath } from "node:url"; export function deploymentRows(payload) { const rows = Array.isArray(payload) ? payload : [payload?.data, payload?.deployments, payload?.items].find(Array.isArray); if (!rows || rows.some((row) => !row || typeof row !== "object")) throw new Error("Unexpected Dokploy deployment response"); return rows; } const identity = (row) => String(row.id ?? row.deploymentId ?? ""); export function knownDeploymentIds(payload) { return deploymentRows(payload).map(identity).filter(Boolean); } export function deploymentState(payload, previousIds) { if ( !Array.isArray(previousIds) || previousIds.some((id) => typeof id !== "string") ) throw new Error("Invalid deployment baseline"); const known = new Set(previousIds); const current = deploymentRows(payload).find( (row) => identity(row) && !known.has(identity(row)), ); if (!current) return "waiting"; const status = String(current.status ?? "unknown").toLowerCase(); return [ "done", "error", "running", "queued", "building", "deploying", "pending", "cancelled", "canceled", ].includes(status) ? status : "unknown"; } export function retryableStatusPoll(curlExit, httpCode, consecutiveFailures) { if ( !Number.isInteger(consecutiveFailures) || consecutiveFailures < 1 || consecutiveFailures > 6 ) return false; return ( [7, 28, 52, 55, 56].includes(curlExit) || (curlExit === 0 && [408, 429, 500, 502, 503, 504].includes(httpCode)) ); } if ( process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1]) ) { try { const [mode, file, code, failures] = process.argv.slice(2); if (mode === "retry") { process.exitCode = retryableStatusPoll( Number(file), Number(code), Number(failures), ) ? 0 : 1; } else { const payload = JSON.parse(readFileSync(file, "utf8")); if (mode === "snapshot") process.stdout.write(JSON.stringify(knownDeploymentIds(payload))); else if (mode === "status") process.stdout.write( deploymentState( payload, JSON.parse(process.env.DOKPLOY_PREVIOUS_DEPLOYMENT_IDS ?? "null"), ), ); else throw new Error("Unknown mode"); } } catch { console.error("Unexpected Dokploy deployment response or baseline."); process.exitCode = 2; } }