#!/usr/bin/env python3 """Read a Replit app's .replit (and, for Agent apps, every artifacts/*/.replit-artifact/artifact.toml) and say how it runs on a VM. replit-plan [DIR] print the plan for the app in DIR (default .) replit-plan [DIR] --write OUT also write OUT/Caddyfile, OUT/build.sh, OUT/release.sh (if the app has a schema push), and OUT/app-.service for each server The units run the live release in ~/app with ~/app.env, through ~/bin/app-run; Caddy on port 8000 routes paths the way Replit's router did. Nothing is installed or started: the caller copies the files into place. From https://exe.dev/deploy/migrate-replit """ import json, os, re, shlex, sys, tomllib from pathlib import Path HOME = os.environ.get("HOME", "/home/exedev") USER = os.environ.get("USER", "exedev") def load(p): with open(p, "rb") as f: return tomllib.load(f) def argv(cmd): """A Replit command (string, list, or {args, env} table) as (argv, env).""" env = {} if isinstance(cmd, dict): env = {k: str(v) for k, v in (cmd.get("env") or {}).items()} cmd = cmd.get("args") if cmd is None or cmd == "" or cmd == []: return None, env if isinstance(cmd, str): return ["bash", "-c", cmd], env return [str(a) for a in cmd], env def sh(args, env=None): pre = " ".join(f"{k}={shlex.quote(v)}" for k, v in (env or {}).items()) return (pre + " " if pre else "") + shlex.join(args) def sd(s): """Quote one word for a systemd ExecStart= or Environment= line.""" s = s.replace("\\", "\\\\").replace('"', '\\"').replace("$", "$$").replace("%", "%%") return f'"{s}"' def slug(s): return re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-") or "web" def nix_deps(root): deps = [] p = root / "replit.nix" if p.exists(): deps += re.findall(r"pkgs\.([A-Za-z0-9_.\-]+)", p.read_text()) return deps # What ties the code to Replit, and where each goes on the VM. USES = [ (r"REPLIT_DB_URL|from replit import db|replit\.database|@replit/database", "Replit Database (key-value)", "replitdb, with REPLIT_DB_URL=http://127.0.0.1:8099"), (r"replit\.object_storage|replit-object-storage|@replit/object-storage|REPLIT_SIDECAR_ENDPOINT|PRIVATE_OBJECT_DIR", "App Storage (Object Storage)", "files on the VM's disk, in ~/storage"), (r"AI_INTEGRATIONS_[A-Z]+_BASE_URL", "Replit AI Integrations", "exe.dev's LLM integration, https://llm.int.exe.xyz"), (r"X-Replit-User|replit\.com/oidc|ISSUER_URL|setupAuth|isAuthenticated", "Replit Auth", "exe.dev login (X-ExeDev-Email), or your own Clerk app"), (r"@clerk/|CLERK_SECRET_KEY|clerk_backend", "Clerk Auth", "your own Clerk app, or exe.dev login"), (r"REPLIT_CONNECTORS_HOSTNAME|@replit/connectors-sdk|stripe-replit-sync", "Replit Connectors", "your own API keys in ~/app.env, or an exe.dev integration"), (r"@neondatabase/serverless", "Neon's serverless driver", "the pg driver (it can't reach a local PostgreSQL)"), (r"REPLIT_DOMAINS|REPLIT_DEV_DOMAIN|REPL_ID|REPL_SLUG|REPL_OWNER|REPLIT_DEPLOYMENT|\.replit\.app", "Replit environment variables or domains", "your VM's address, or a variable in ~/app.env"), ] SKIP_DIRS = {".git", "node_modules", ".venv", ".pythonlibs", ".cache", ".local", ".config", "dist", "build", "__pycache__"} SKIP_FILES = {"README.md", "pnpm-lock.yaml", "package-lock.json", "yarn.lock", "uv.lock", "poetry.lock", "bun.lock", ".replit", "replit.md"} def scan(root): """For each of USES, the files that mention it.""" found = {} for d, dirs, files in os.walk(root): dirs[:] = [x for x in dirs if x not in SKIP_DIRS] for f in files: path = Path(d) / f if f in SKIP_FILES or f.endswith(".md") or path.stat().st_size > 1_000_000: continue try: text = path.read_text() except (UnicodeDecodeError, OSError): continue for pat, what, where in USES: if re.search(pat, text): found.setdefault(what, (where, []))[1].append(str(path.relative_to(root))) return found def installer(root): """How to install the app's packages, from its lockfiles.""" steps = [] if (root / "pnpm-lock.yaml").exists(): steps.append("pnpm install --frozen-lockfile") elif (root / "package-lock.json").exists(): steps.append("npm ci") elif (root / "yarn.lock").exists(): steps.append("yarn install --frozen-lockfile") elif (root / "bun.lock").exists() or (root / "bun.lockb").exists(): steps.append("bun install --frozen-lockfile") elif (root / "package.json").exists(): steps.append("npm install") if (root / "uv.lock").exists(): steps.append("uv sync --frozen") elif (root / "pyproject.toml").exists() and "[project]" in (root / "pyproject.toml").read_text(): steps.append("uv sync") elif (root / "requirements.txt").exists(): steps.append("uv venv --allow-existing && uv pip install -r requirements.txt") elif (root / "pyproject.toml").exists(): steps.append("# pyproject.toml has no [project] table (Poetry 1?): convert it, then uv sync") return steps def schema(root): """The command that brings the database schema up to date, as Replit's publishing does for Agent apps (Drizzle's push), if the app has one.""" pm = "pnpm" if (root / "pnpm-lock.yaml").exists() else "npm" for pj in sorted(root.glob("*/*/package.json")): if "node_modules" in pj.parts: continue try: d = json.loads(pj.read_text()) except (OSError, ValueError): continue if "drizzle-kit push" in (d.get("scripts") or {}).get("push", "") and d.get("name"): return f"{pm} --filter {d['name']} run push" if pm == "pnpm" else f"npm --workspace {d['name']} run push" try: scripts = json.loads((root / "package.json").read_text()).get("scripts") or {} except (OSError, ValueError): scripts = {} for name in ("db:push", "db:migrate", "migrate"): if name in scripts: return f"{pm} run {name}" return None def plan(root): rep = load(root / ".replit") if (root / ".replit").exists() else {} p = { "modules": rep.get("modules", []), "nix": (rep.get("nix") or {}).get("packages", []) + nix_deps(root), "target": (rep.get("deployment") or {}).get("deploymentTarget", ""), "install": installer(root), "schema": schema(root), "build": [], "servers": [], # name, argv, env, port, paths, health "static": [], # name, dir, paths, spa "skipped": [], "notes": [], } for w in (rep.get("workflows") or {}).get("workflow", []): cmds = [t.get("args") for t in w.get("tasks", []) if t.get("task") == "shell.exec"] if cmds: p["notes"].append(f"workflow {w.get('name')!r} (Run button only; Replit doesn't publish it): {'; '.join(map(str, cmds))}") arts = sorted(root.glob("artifacts/*/.replit-artifact/artifact.toml")) if arts: p["shape"] = "agent (artifacts)" for a in arts: art = load(a) adir = a.parent.parent.name for svc in art.get("services", []): name = slug(adir if len(art["services"]) == 1 else f"{adir}-{svc.get('name', '')}") prod = svc.get("production") if not prod: p["skipped"].append(f"{name} ({art.get('kind', '?')}, development only)") continue senv = {k: str(v) for k, v in (svc.get("env") or {}).items()} b, benv = argv(prod.get("build")) if b: p["build"].append(sh(b, {**senv, **benv})) paths = svc.get("paths", ["/"]) if prod.get("serve") == "static": spa = any(r.get("to") == "/index.html" for r in prod.get("rewrites", [])) p["static"].append({"name": name, "dir": prod["publicDir"], "paths": paths, "spa": spa}) continue r, renv = argv(prod.get("run")) if not r: p["skipped"].append(f"{name} (no production run command)") continue env = {**senv, **renv} port = int(env.get("PORT") or svc.get("localPort") or 0) env.setdefault("PORT", str(port)) health = ((prod.get("health") or {}).get("startup") or {}).get("path") p["servers"].append({"name": name, "argv": r, "env": env, "port": port, "paths": paths, "health": health}) return p p["shape"] = "classic (.replit)" dep = rep.get("deployment") or {} b, benv = argv(dep.get("build") or rep.get("build")) if b: p["build"].append(sh(b, benv)) if p["target"] == "static": p["static"].append({"name": "web", "dir": dep.get("publicDir", "."), "paths": ["/"], "spa": False}) return p r, renv = argv(dep.get("run") or rep.get("run")) if not r and rep.get("entrypoint"): e = rep["entrypoint"] r = ["python", e] if e.endswith(".py") else ["node", e] if e.endswith("js") else None p["notes"].append(f"no run command: running the entrypoint, {e}") if not r: p["notes"].append("no run command or entrypoint: write app-web.service by hand") return p env = {k: str(v) for k, v in ((rep.get("run") or {}).get("env") or {}).items()} if isinstance(rep.get("run"), dict) else {} env.update(renv) ports = rep.get("ports", []) ext = [x for x in ports if x.get("externalPort") == 80] or ports port = int(ext[0]["localPort"]) if ext else 0 if dep.get("ignorePorts") or p["target"] in ("scheduled",): port = 0 if port: env.setdefault("PORT", str(port)) elif p["target"] != "scheduled": p["notes"].append("no [[ports]]: a background worker, or the app reads $PORT (set PORT in app-web.service)") if p["target"] == "scheduled": p["notes"].append("a Scheduled deployment: the schedule is in Replit's Publishing tool; make a systemd timer") p["servers"].append({"name": "web", "argv": r, "env": env, "port": port, "paths": ["/"], "health": None}) return p def caddyfile(p): out = ["# Written by replit-plan: Replit's router, on port 8000.", "{", "\tadmin off", "\tauto_https off", "}", "", ":8000 {"] routes = [(path, "server", s) for s in p["servers"] if s["port"] for path in s["paths"]] routes += [(path, "static", s) for s in p["static"] for path in s["paths"]] routes.sort(key=lambda r: -len(r[0].rstrip("/"))) # longest prefix first for i, (path, kind, s) in enumerate(routes): prefix = path.rstrip("/") if prefix: out += [f"\t@r{i} path {prefix} {prefix}/*", f"\thandle @r{i} {{"] else: out += ["\thandle {"] if kind == "server": out += [f"\t\treverse_proxy 127.0.0.1:{s['port']}"] else: if prefix: out += [f"\t\turi strip_prefix {prefix}"] out += [f"\t\troot * {HOME}/app/{s['dir'].strip('/')}"] if s["spa"]: out += ["\t\ttry_files {path} /index.html"] out += ["\t\tfile_server"] out += ["\t}"] out += ["}"] return "\n".join(out) + "\n" def unit(s): env = " ".join(sd(f"{k}={v}") for k, v in sorted(s["env"].items())) lines = [ "[Unit]", f"Description=The app's {s['name']} service (the current release in ~/app)", "After=network-online.target postgresql.service replitdb.service", "Wants=network-online.target", "PartOf=app.target", "", "[Service]", f"User={USER}", f"WorkingDirectory={HOME}/app", "Environment=NODE_ENV=production REPLIT_DEPLOYMENT=1", ] if env: lines.append(f"Environment={env}") lines += [ f"EnvironmentFile={HOME}/app.env", f"ExecStart={HOME}/bin/app-run {' '.join(sd(a) for a in s['argv'])}", "Restart=always", "RestartSec=3", "", "[Install]", "WantedBy=app.target", ] return "\n".join(lines) + "\n" def build_sh(p): lines = ["#!/usr/bin/env bash", "# Written by replit-plan: install and build. app-deploy runs this in", "# each new release directory, with ~/app.env loaded.", "set -euxo pipefail", "unset NODE_ENV # the build needs devDependencies"] lines += p["install"] + p["build"] return "\n".join(lines) + "\n" def main(): args = sys.argv[1:] out = None if "--write" in args: i = args.index("--write") out = Path(args[i + 1]) del args[i:i + 2] root = Path(args[0] if args else ".").resolve() if not (root / ".replit").exists(): sys.exit(f"replit-plan: no .replit in {root}. Show hidden files in Replit, or export again.") p = plan(root) print(f"Shape: {p['shape']}" + (f", deploymentTarget {p['target']}" if p["target"] else "")) print(f"Modules: {', '.join(p['modules']) or '-'}") print(f"Nix: {', '.join(p['nix']) or '-'}") print("Install: " + ("; ".join(p["install"]) or "-")) for b in p["build"]: print(f"Build: {b}") for s in p["servers"]: where = f"port {s['port']}, {' '.join(s['paths'])}" if s["port"] else "no port" print(f"Server: app-{s['name']}: {sh(s['argv'])} ({where})" + (f", health {s['health']}" if s["health"] else "")) for s in p["static"]: print(f"Static: {s['dir']} at {' '.join(s['paths'])}" + (" (single-page app)" if s["spa"] else "")) if p["schema"]: print(f"Schema: {p['schema']} (before each release goes live, as Replit's publish does)") for s in p["skipped"]: print(f"Skipped: {s}") for n in p["notes"]: print(f"Note: {n}") for what, (where, files) in scan(root).items(): more = f" and {len(files) - 3} more" if len(files) > 3 else "" print(f"Uses: {what} -> {where}\n in {', '.join(files[:3])}{more}") if out: out.mkdir(parents=True, exist_ok=True) (out / "Caddyfile").write_text(caddyfile(p)) (out / "build.sh").write_text(build_sh(p)) (out / "build.sh").chmod(0o755) if p["schema"]: (out / "release.sh").write_text( "#!/usr/bin/env bash\n# Written by replit-plan: app-deploy runs this in each new release\n" "# before it goes live, to bring the database schema up to date.\n" f"set -euxo pipefail\n{p['schema']}\n") (out / "release.sh").chmod(0o755) for s in p["servers"]: (out / f"app-{s['name']}.service").write_text(unit(s)) checks = [s["health"] or s["paths"][0] for s in p["servers"] if s["port"]] checks += [s["paths"][0] for s in p["static"]] (out / "health").write_text("".join(c + "\n" for c in dict.fromkeys(checks))) (out / "plan.json").write_text(json.dumps(p, indent=1) + "\n") print(f"Wrote: {', '.join(sorted(f.name for f in out.iterdir()))} in {out}") if __name__ == "__main__": main()