Repository navigation
Expand file tree
/
Copy pathdev.sh
More file actions
executable file
·457 lines (413 loc) · 15.7 KB
/
Copy pathdev.sh
File metadata and controls
executable file
·457 lines (413 loc) · 15.7 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
#!/usr/bin/env bash
set -euo pipefail
# ─── dev.sh — single entry point for local development ────────────────
# Default: `./dev.sh` brings up a healthy live-reload dev environment.
# - Infra (redis, convex, convex-dashboard) runs in Docker; TrailBase is
# parked and only starts with `./dev.sh full`.
# - Backend + frontend run natively with live reload.
#
# Commands:
# ./dev.sh Start infra in Docker + backend + frontend natively (default).
# ./dev.sh up Same as above.
# ./dev.sh full Start everything in Docker (infra + app profiles).
# ./dev.sh down Stop everything (both profiles).
# ./dev.sh status Show container + native-process status.
# ./dev.sh logs [svc] Tail container logs (default: backend if running, else redis).
# ./dev.sh restart-be Restart native backend only (frees port, re-launches).
# ./dev.sh restart-fe Restart native frontend only (kills .next, re-launches).
#
# Re-running `./dev.sh` is idempotent: ports are freed, containers reconciled,
# health-checked, then backend + frontend are relaunched.
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
COMPOSE_FILE="$SCRIPT_DIR/docker-compose.yml"
ENV_FILE="$SCRIPT_DIR/.env.docker"
WEB_DIR="$SCRIPT_DIR/web"
BACKEND_DIR="$WEB_DIR/backend"
LOG_DIR="/tmp/codebase-dev"
mkdir -p "$LOG_DIR"
BACKEND_LOG="$LOG_DIR/backend.log"
FRONTEND_LOG="$LOG_DIR/frontend.log"
BACKEND_PID_FILE="$LOG_DIR/backend.pid"
FRONTEND_PID_FILE="$LOG_DIR/frontend.pid"
BACKEND_PORT="${BACKEND_PORT:-3001}"
# 3333, not Next's default 3000: generated scaffold projects under
# backend/generated-projects run their own `next dev`, which grabs 3000 and
# silently squats it when the real app is down — /admin then 404s because the
# request never reaches our middleware. Keep the app off the default port.
FRONTEND_PORT="${FRONTEND_PORT:-3333}"
CONVEX_PORT="${CONVEX_PORT:-3232}"
TRAILBASE_PORT="${TRAILBASE_PORT:-4000}"
TRAILBASE_MODE="${TRAILBASE_MODE:-single}"
TRAILBASE_CONTROL_PORT="${TRAILBASE_CONTROL_PORT:-$TRAILBASE_PORT}"
TRAILBASE_CONTROL_BASE_URL="${TRAILBASE_CONTROL_BASE_URL:-http://127.0.0.1:${TRAILBASE_CONTROL_PORT}}"
TRAILBASE_PUBLIC_BASE_URL="${TRAILBASE_PUBLIC_BASE_URL:-http://localhost:${TRAILBASE_PORT}}"
TRAILBASE_HEALTH_URL="${TRAILBASE_HEALTH_URL:-http://localhost:${TRAILBASE_PORT}/api/healthcheck}"
export CONVEX_SELF_HOSTED_URL="${CONVEX_SELF_HOSTED_URL:-http://127.0.0.1:${CONVEX_PORT}}"
export NEXT_PUBLIC_CONVEX_URL="${NEXT_PUBLIC_CONVEX_URL:-http://127.0.0.1:${CONVEX_PORT}}"
# OrbStack auto-detect (harmless if absent)
if [ -z "${DOCKER_HOST:-}" ] && [ -S "$HOME/.orbstack/run/docker.sock" ]; then
export DOCKER_HOST="unix://$HOME/.orbstack/run/docker.sock"
fi
DC_ARGS=(-f "$COMPOSE_FILE")
[ -f "$ENV_FILE" ] && DC_ARGS=(--env-file "$ENV_FILE" "${DC_ARGS[@]}")
dc() { docker compose "${DC_ARGS[@]}" "$@"; }
# ─── Output helpers ───────────────────────────────────────────────────
red() { printf '\033[0;31m%s\033[0m\n' "$*"; }
green() { printf '\033[0;32m%s\033[0m\n' "$*"; }
cyan() { printf '\033[0;36m%s\033[0m\n' "$*"; }
dim() { printf '\033[0;90m%s\033[0m\n' "$*"; }
step() { cyan "── $1"; }
ok() { green " ✓ $1"; }
fail() { red " ✗ $1"; }
# ─── Port + process helpers ───────────────────────────────────────────
free_port() {
local port="$1" pids
pids=$(lsof -ti :"$port" -sTCP:LISTEN 2>/dev/null || true)
if [ -n "$pids" ]; then
echo "$pids" | xargs kill -9 2>/dev/null || true
for _ in {1..10}; do
lsof -ti :"$port" -sTCP:LISTEN >/dev/null 2>&1 || return 0
sleep 0.2
done
fail "port $port still busy"
return 1
fi
}
# free_port only kills the pid holding the LISTENING socket. For `next dev`
# that is the child next-server — the parent supervisor keeps running and keeps
# writing .next/trace, so a following `rm -rf .next` dies with "Directory not
# empty" and, under `set -e`, aborts the script with the frontend already
# stopped. Reap the whole tree for this checkout before touching .next.
kill_frontend_tree() {
pkill -9 -f "${WEB_DIR}/node_modules/.bin/next" 2>/dev/null || true
for _ in {1..10}; do
pgrep -f "${WEB_DIR}/node_modules/.bin/next" >/dev/null 2>&1 || return 0
sleep 0.2
done
}
# Retries once after reaping stragglers: a live writer recreates entries between
# rm's readdir and unlink, so a single failure is not proof the dir is stuck.
remove_next_cache() {
[ -d "$WEB_DIR/.next" ] || return 0
rm -rf "$WEB_DIR/.next" 2>/dev/null && return 0
kill_frontend_tree
rm -rf "$WEB_DIR/.next" 2>/dev/null && return 0
fail "could not remove $WEB_DIR/.next — a process is still writing to it"
return 1
}
stop_pm2_app_if_present() {
local app="$1"
command -v pm2 >/dev/null 2>&1 || return 0
if pm2 describe "$app" >/dev/null 2>&1; then
pm2 delete "$app" >/dev/null 2>&1 || true
ok "Stopped PM2 app $app"
fi
}
stop_conflicting_pm2_apps() {
stop_pm2_app_if_present codebase-backend-dev
stop_pm2_app_if_present codebase-frontend-dev
}
# A port can be held by a *different* checkout of this repo (parallel agents run
# several at once). A healthy HTTP response from such a listener is misleading:
# it is not this tree's server. Compare the listener's cwd to the expected dir.
listener_owned_by_dir() {
local port="$1" expected_dir="$2" pid cwd
while IFS= read -r pid; do
[ -n "$pid" ] || continue
cwd=$(lsof -a -p "$pid" -d cwd -Fn 2>/dev/null | sed -n 's/^n//p' | head -1)
[ "$cwd" = "$expected_dir" ] && return 0
done < <(lsof -ti :"$port" -sTCP:LISTEN 2>/dev/null || true)
return 1
}
report_foreign_listener() {
local name="$1" port="$2" expected_dir="$3" pid cwd
fail "$name port $port is owned by another checkout"
while IFS= read -r pid; do
[ -n "$pid" ] || continue
cwd=$(lsof -a -p "$pid" -d cwd -Fn 2>/dev/null | sed -n 's/^n//p' | head -1)
dim " pid $pid cwd ${cwd:-unknown}; expected $expected_dir"
done < <(lsof -ti :"$port" -sTCP:LISTEN 2>/dev/null || true)
}
wait_http() {
local name="$1" url="$2" retries="${3:-30}" port="${4:-}" expected_dir="${5:-}"
for i in $(seq 1 "$retries"); do
if curl -sf -o /dev/null "$url" 2>/dev/null; then
if [ -n "$port" ] && ! listener_owned_by_dir "$port" "$expected_dir"; then
report_foreign_listener "$name" "$port" "$expected_dir"
return 1
fi
ok "$name healthy"
return 0
fi
sleep 1
done
fail "$name not healthy at $url"
return 1
}
# Lighter check: any HTTP response counts as "listening" (accepts 2xx/4xx/5xx).
wait_listening() {
local name="$1" url="$2" retries="${3:-30}"
for i in $(seq 1 "$retries"); do
if curl -s -o /dev/null --max-time 1 "$url" 2>/dev/null; then
ok "$name listening"
return 0
fi
sleep 1
done
fail "$name not responding at $url"
return 1
}
wait_redis() {
for i in $(seq 1 30); do
if redis-cli ping 2>/dev/null | grep -q PONG; then
ok "Redis healthy"
return 0
fi
sleep 1
done
fail "Redis not responding"
return 1
}
# Build the sandbox image used by previewSandbox.js / buildSandbox.js. Cached
# layers make this ~3s when nothing changed — far cheaper than the silent
# exit-125 ("no matching entries in passwd file") you get when the local
# image predates a Dockerfile change.
ensure_sandbox_image() {
local dockerfile="$BACKEND_DIR/docker/Dockerfile.build"
local tag="codebase-build-sandbox:latest"
if ! docker build -q -t "$tag" -f "$dockerfile" "$BACKEND_DIR/docker/" >/dev/null; then
fail "sandbox image build failed — preview/build will not work"
return 1
fi
ok "Sandbox image fresh ($tag)"
}
clean_frontend_cache_if_corrupt() {
if [ ! -d "$WEB_DIR/.next" ]; then
return 0
fi
if ! ( cd "$WEB_DIR" && node scripts/check-next-cache.mjs . >"$LOG_DIR/next-cache-check.log" 2>&1 ); then
step "Clearing corrupt Next.js cache"
dim " details: $LOG_DIR/next-cache-check.log"
remove_next_cache
ok "Removed stale .next cache"
fi
}
# buildSandbox and the agent shell tool both read a missing `build-net` as
# "Docker unavailable" and silently downgrade to stripped-env builds, so the
# sandboxed path never runs locally. Creating the bridge needs no root; only
# the iptables egress allowlist does, and that stays with
# backend/docker/setup-build-net.sh on real build workers.
ensure_sandbox_network() {
local net="${SANDBOX_NETWORK:-build-net}"
if docker network inspect "$net" >/dev/null 2>&1; then
ok "Sandbox network present ($net)"
return 0
fi
if docker network create \
--driver bridge \
--subnet "${SANDBOX_BRIDGE_SUBNET:-172.31.0.0/24}" \
--opt "com.docker.network.bridge.name=br-${net}" \
"$net" >/dev/null 2>&1; then
ok "Sandbox network created ($net)"
else
fail "could not create sandbox network '$net' — builds will run stripped-env"
fi
}
# npm 11 refuses Node < 20.17, and on an older runtime Next's lockfile patcher
# dies with "Cannot read properties of undefined (reading 'os')". Inside a
# generated project that surfaces only as an unexplained "npm run build failed",
# so resolve a supported interpreter up front and put it on the children's PATH.
NODE_MIN="20.17.0"
node_version_ok() {
local bin="$1" ver
[ -x "$bin" ] || return 1
ver="$("$bin" -v 2>/dev/null)" || return 1
ver="${ver#v}"
[ "$(printf '%s\n%s\n' "$NODE_MIN" "$ver" | sort -V | head -1)" = "$NODE_MIN" ]
}
ensure_supported_node() {
local candidate
for candidate in \
"$(command -v node 2>/dev/null)" \
/opt/homebrew/opt/node@24/bin/node \
/opt/homebrew/opt/node@22/bin/node \
/opt/homebrew/opt/node@20/bin/node \
/usr/local/opt/node@22/bin/node \
/usr/local/opt/node@20/bin/node \
"${NVM_DIR:-/nonexistent}"/versions/node/*/bin/node
do
if node_version_ok "$candidate"; then
PATH="$(dirname "$candidate"):$PATH"
export PATH
ok "Node $("$candidate" -v) ($(dirname "$candidate"))"
return 0
fi
done
fail "no Node >= $NODE_MIN found — generated-project builds will fail in Next's lockfile patcher"
}
start_native_backend_process() {
(
cd "$BACKEND_DIR"
PORT="$BACKEND_PORT" \
FRONTEND_PORT="$FRONTEND_PORT" \
TRAILBASE_MODE="$TRAILBASE_MODE" \
TRAILBASE_CONTROL_PORT="$TRAILBASE_CONTROL_PORT" \
TRAILBASE_CONTROL_BASE_URL="$TRAILBASE_CONTROL_BASE_URL" \
TRAILBASE_PUBLIC_BASE_URL="$TRAILBASE_PUBLIC_BASE_URL" \
nohup npm run dev >"$BACKEND_LOG" 2>&1 &
echo $! >"$BACKEND_PID_FILE"
)
}
start_native_frontend_process() {
(
cd "$WEB_DIR"
PORT="$FRONTEND_PORT" nohup npm run dev -- -p "$FRONTEND_PORT" >"$FRONTEND_LOG" 2>&1 &
echo $! >"$FRONTEND_PID_FILE"
)
}
# The Convex container starts empty of *our* code — it serves whatever function
# bundle was last pushed. Without this, a branch that adds a Convex function
# renders a UI calling a function the deployment has never heard of, and the
# only symptom is "Could not find public function" in the browser.
push_convex_functions() {
( cd "$WEB_DIR" && npm run convex:push ) >>"$LOG_DIR/convex-push.log" 2>&1
}
# ─── Commands ─────────────────────────────────────────────────────────
cmd_up() {
step "Starting infrastructure (redis, convex, convex-dashboard)"
dc --profile infra up -d
step "Waiting for infra health"
wait_redis
wait_http "Convex" "http://localhost:${CONVEX_PORT}/version" 30
step "Pushing Convex functions"
if push_convex_functions; then
ok "Convex functions deployed"
else
fail "Convex push failed — see $LOG_DIR/convex-push.log (panels will report 'Could not find public function')"
fi
step "Freeing native ports"
stop_conflicting_pm2_apps
free_port "$BACKEND_PORT"
free_port "$FRONTEND_PORT"
step "Ensuring sandbox image"
ensure_sandbox_image
ensure_sandbox_network
ensure_supported_node
step "Starting backend natively (live reload via node --watch)"
start_native_backend_process
wait_listening "Backend" "http://localhost:${BACKEND_PORT}/health" 60
step "Starting frontend natively (HMR via next dev)"
clean_frontend_cache_if_corrupt
start_native_frontend_process
wait_listening "Frontend" "http://localhost:${FRONTEND_PORT}" 60
echo ""
green "Dev environment ready"
dim " Frontend: http://localhost:${FRONTEND_PORT}"
dim " Backend: http://localhost:${BACKEND_PORT}"
dim " Convex: http://localhost:${CONVEX_PORT}"
dim " Redis: localhost:6379"
echo ""
dim " Logs: ./dev.sh logs <svc> (tail) "
dim " tail -f $BACKEND_LOG"
dim " tail -f $FRONTEND_LOG"
}
cmd_full() {
step "Starting all services in Docker (infra + app profiles)"
dc --profile infra --profile trailbase --profile app up -d --build
step "Waiting for backend + frontend to listen"
wait_http "Convex" "http://localhost:${CONVEX_PORT}/version" 30
wait_http "TrailBase" "$TRAILBASE_HEALTH_URL" 60
wait_listening "Backend" "http://localhost:${BACKEND_PORT}/health" 60
wait_listening "Frontend" "http://localhost:${FRONTEND_PORT}" 60
echo ""
green "Full-stack containerized dev environment ready"
}
_kill_pid_file() {
local file="$1"
if [ -f "$file" ]; then
local pid
pid=$(cat "$file" 2>/dev/null || true)
[ -n "$pid" ] && kill "$pid" 2>/dev/null || true
rm -f "$file"
fi
}
cmd_down() {
step "Stopping native backend + frontend"
_kill_pid_file "$BACKEND_PID_FILE"
_kill_pid_file "$FRONTEND_PID_FILE"
free_port "$BACKEND_PORT" || true
free_port "$FRONTEND_PORT" || true
ok "Native processes stopped"
step "Stopping containers (both profiles)"
dc --profile infra --profile trailbase --profile app down
ok "Containers stopped"
}
cmd_status() {
step "Containers"
dc --profile infra --profile trailbase --profile app ps
echo ""
step "Native processes"
for pair in "backend:$BACKEND_PORT" "frontend:$FRONTEND_PORT"; do
name="${pair%:*}"; port="${pair##*:}"
if lsof -ti :"$port" -sTCP:LISTEN >/dev/null 2>&1; then
ok "$name listening on :$port"
else
dim "$name not running"
fi
done
}
cmd_logs() {
local svc="${1:-}"
if [ -z "$svc" ]; then
if [ -s "$BACKEND_LOG" ]; then
svc="backend-native"
else
svc="redis"
fi
fi
case "$svc" in
backend-native) exec tail -f "$BACKEND_LOG" ;;
frontend-native) exec tail -f "$FRONTEND_LOG" ;;
*) exec dc logs -f --tail 100 "$svc" ;;
esac
}
cmd_restart_be() {
step "Restarting native backend"
stop_pm2_app_if_present codebase-backend-dev
_kill_pid_file "$BACKEND_PID_FILE"
free_port "$BACKEND_PORT" || true
ensure_supported_node
ensure_sandbox_network
start_native_backend_process
wait_listening "Backend" "http://localhost:${BACKEND_PORT}/health" 60
}
cmd_restart_fe() {
step "Restarting native frontend"
stop_pm2_app_if_present codebase-frontend-dev
_kill_pid_file "$FRONTEND_PID_FILE"
free_port "$FRONTEND_PORT" || true
kill_frontend_tree
remove_next_cache
ensure_supported_node
ensure_sandbox_network
start_native_frontend_process
wait_http "Frontend" "http://localhost:${FRONTEND_PORT}" 60
}
# ─── Dispatch ─────────────────────────────────────────────────────────
case "${1:-up}" in
""|up) cmd_up ;;
full) cmd_full ;;
down) cmd_down ;;
status) cmd_status ;;
logs) shift; cmd_logs "${1:-}" ;;
restart-be) cmd_restart_be ;;
restart-fe) cmd_restart_fe ;;
help|-h|--help)
grep -E '^#( |$)' "$0" | sed 's/^# \{0,1\}//'
;;
*)
fail "Unknown command: $1"
echo "Try: ./dev.sh help"
exit 1
;;
esac