#!/bin/zsh set -euo pipefail ROOT_DIR="$(cd "$(dirname "$0")" && pwd)" BACKEND_PORT=8000 FRONTEND_PORT=5173 require_file() { local path="$1" local message="$2" if [[ ! -e "$path" ]]; then echo "$message" read -r -k 1 "?按任意键关闭..." exit 1 fi } require_command() { local name="$1" if ! command -v "$name" >/dev/null 2>&1; then echo "缺少命令: $name" read -r -k 1 "?按任意键关闭..." exit 1 fi } is_port_listening() { local port="$1" lsof -iTCP:"$port" -sTCP:LISTEN -t >/dev/null 2>&1 } wait_for_http() { local url="$1" local max_attempts="$2" local attempt=1 while (( attempt <= max_attempts )); do if curl -fsS "$url" >/dev/null 2>&1; then return 0 fi sleep 1 (( attempt++ )) done return 1 } open_backend_terminal() { osascript - "$ROOT_DIR" <<'APPLESCRIPT' on run argv set rootDir to item 1 of argv tell application "Terminal" activate do script "cd " & quoted form of rootDir & " && exec ./.venv/bin/python -m uvicorn app.main:app --host 127.0.0.1 --port 8000" end tell end run APPLESCRIPT } open_frontend_terminal() { osascript - "$ROOT_DIR" <<'APPLESCRIPT' on run argv set rootDir to item 1 of argv tell application "Terminal" activate do script "cd " & quoted form of (rootDir & "/frontend-admin") & " && exec npm run dev -- --host 0.0.0.0 --port 5173" end tell end run APPLESCRIPT } require_file "$ROOT_DIR/.venv/bin/python" "未找到 Python 虚拟环境: .venv/bin/python" require_file "$ROOT_DIR/frontend-admin/package.json" "未找到前端工程: frontend-admin/package.json" require_command npm require_command curl require_command lsof require_command osascript if ! is_port_listening "$BACKEND_PORT"; then echo "启动后端..." open_backend_terminal else echo "后端已在 $BACKEND_PORT 端口运行" fi if ! is_port_listening "$FRONTEND_PORT"; then echo "启动前端..." open_frontend_terminal else echo "前端已在 $FRONTEND_PORT 端口运行" fi echo "等待服务就绪..." if ! wait_for_http "http://127.0.0.1:$BACKEND_PORT/health" 30; then echo "后端启动失败,请检查新打开的 Terminal 窗口" read -r -k 1 "?按任意键关闭..." exit 1 fi if ! wait_for_http "http://127.0.0.1:$FRONTEND_PORT/" 30; then echo "前端启动失败,请检查新打开的 Terminal 窗口" read -r -k 1 "?按任意键关闭..." exit 1 fi open "http://127.0.0.1:$FRONTEND_PORT/" echo echo "启动成功" echo "前端: http://127.0.0.1:$FRONTEND_PORT/" echo "后端: http://127.0.0.1:$BACKEND_PORT/" echo read -r -k 1 "?按任意键关闭..."