Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions .claude/skills/dev-server/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
---
name: dev-server
description: Use when starting, restarting or troubleshooting kasane's local dev server, or choosing which database it talks to. Triggers include "run the dev server", "start the app locally", "run against a local database", "copy production into local", "refresh the local db", "run against production", "dev:local", "dev:production", or Docker and `supabase start` failures.
---

# Dev Server

One parameter picks the database: `local` or `production`.

```bash
bun run dev:local # local Supabase, freshly copied from production
bun run dev:production # production Supabase, nothing imported
```

Both wrap `scripts/dev.sh <local|production>`. Anything after `--` goes to `expo start`:

```bash
bun run dev:local -- --web
bun run dev:local -- --keep --web # reuse the local data, skip the copy
bun run dev:production -- --ios
```

## Which one to use

| Target | Database | Use it when |
| ------------ | ------------------------------------------ | --------------------------------------------------------------------------------- |
| `local` | Docker stack at `http://127.0.0.1:54321` | testing a migration, writing user data, or anything you would not do to real rows |
| `production` | `https://obtgldkascmxbtpnvscn.supabase.co` | checking real behaviour against live data, read-only UI work |

Default to `local` when the change writes data or touches `supabase/migrations/`. Writes from `production` hit real users' rows.

## What `local` does

```mermaid
flowchart TD
A[dev.sh local] --> B{Docker running?}
B -- no --> C[open -a Docker, wait up to 120s]
B -- yes --> D[supabase start]
C --> D
D --> E{--keep?}
E -- yes --> H
E -- no --> F[db dump --remote=SUPABASE_DB_URL, data only, public + auth]
F --> G[db reset, truncate, load snapshot in one transaction]
G --> H[read API_URL + PUBLISHABLE_KEY from supabase status]
H --> I[expo start with EXPO_PUBLIC_SUPABASE_* set]
```

1. Dumps production's data (`public` and `auth` schemas) to `supabase/.snapshots/production-data.sql` (gitignored).
2. `supabase db reset --local` rebuilds the schema from `supabase/migrations/`, so local always has the committed schema.
3. Truncates every `public` and `auth` table (the migrations seed catalog rows) and loads the snapshot in a single transaction. A failed load leaves the clean reset, never a half import.
4. Starts Expo with `EXPO_PUBLIC_SUPABASE_URL` and `EXPO_PUBLIC_SUPABASE_PUBLISHABLE_KEY` pointing at the local stack.

Because `auth.users` is copied, production logins work locally with the same password. Local mail goes to Mailpit at `http://127.0.0.1:54324`; Studio is at `http://127.0.0.1:54323`.

## One-time setup for the copy

The dump needs production's Postgres connection string. It is a secret, so it lives in `scripts/.env.local` (matched by `.env*.local` in `.gitignore`), never in `app/` or `src/`:

```bash
# scripts/.env.local
SUPABASE_DB_URL="postgresql://postgres.obtgldkascmxbtpnvscn:<password>@aws-0-<region>.pooler.supabase.com:5432/postgres"
```

Get it from the Supabase dashboard: Connect, Session pooler. An exported `SUPABASE_DB_URL` in the shell wins over the file. Use `envsync` to carry `scripts/.env.local` to another Mac.

Docker Desktop and `psql` (`brew install libpq` or Postgres.app) must be installed. The Supabase CLI runs through `bunx supabase`, so it needs no install.

## How the switch works

`src/api/supabaseConfig.ts` calls `resolveSupabaseTarget`, which uses the `EXPO_PUBLIC_*` override only when **both** values are set and falls back to production otherwise. A half-set environment can never pair a local URL with the production key.

`production` runs Expo with both variables explicitly unset, so a stray export in your shell cannot redirect it.

> [!WARNING]
> Metro caches modules with `EXPO_PUBLIC_*` values already inlined. `dev.sh` passes `--clear` whenever the target differs from the last run (`supabase/.temp/dev-target`), and `build:web` always clears, so a production export never ships the local URL. Never set these variables in a `.env` file: Expo loads `.env` for `build:web` too.

## Troubleshooting

| Symptom | Fix |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------- |
| `SUPABASE_DB_URL is not set` | Add it to `scripts/.env.local`, or rerun with `--keep` |
| `Docker did not start within 120s` | Open Docker Desktop by hand, then rerun |
| Port `54321`/`54322` already allocated | Another Supabase project is running: `bunx supabase stop --project-id <other>` |
| Load fails with a missing column | Production has schema the repo's migrations lack. Pull it into a migration (`supabase-migration`) |
| App still shows the other database's data | Rerun with `-- --clear`; also clear the TanStack Query cache by signing out or clearing site data |
| Done for the day | `bunx supabase stop` (keeps data) or `bunx supabase stop --no-backup` (drops it) |

## Don't

| Don't | Why |
| ----------------------------------------------------- | -------------------------------------------------------------------- |
| Commit `supabase/.snapshots/` or `scripts/.env.local` | They hold real user data and a database password |
| Run migrations against production from `dev.sh` | It only reads production. Migrations go through `supabase-migration` |
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ The rules above are the always-on baseline. These skills carry the depth — rea
| iOS / Android / web / Tauri differences | `cross-platform-parity` |
| Logic in `src/data/`, `src/state/`, `src/api/` | `domain-tests` |
| Routing, deep links, Netlify fallback, MangaDex proxy | `e2e` |
| Running the dev server, local vs production database | `dev-server` |
| Schema, columns, policies, RLS | `supabase-migration` |
| Adding a series that has no catalog entry | `arc-mapping` |
| Changing a series already in the catalog | `mapping-correction` |
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
"main": "expo-router/entry",
"scripts": {
"start": "expo start",
"dev:local": "bash scripts/dev.sh local",
"dev:production": "bash scripts/dev.sh production",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"build:web": "expo export -p web",
"build:web": "expo export -p web --clear",
"typecheck": "tsc --noEmit",
"lint": "oxlint",
"lint:fix": "oxlint --fix",
Expand Down
168 changes: 168 additions & 0 deletions scripts/dev.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
#!/usr/bin/env bash
# Starts the Expo dev server against one Supabase target.
#
# scripts/dev.sh local [--keep] [-- <expo start args>]
# scripts/dev.sh production [-- <expo start args>]
#
# local Starts the local Supabase stack in Docker, copies production's
# data into it (public and auth schemas), then serves the app
# against http://127.0.0.1:54321. Pass --keep to skip the copy and
# reuse whatever the local database already holds.
# production Serves the app against the production project. Imports nothing.
#
# The copy reads SUPABASE_DB_URL, production's Postgres connection string,
# from the environment or from scripts/.env.local (gitignored). It is a
# service-level secret and never reaches app/ or src/.
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SNAPSHOT_DIR="$ROOT/supabase/.snapshots"
SNAPSHOT="$SNAPSHOT_DIR/production-data.sql"
LAST_TARGET_FILE="$ROOT/supabase/.temp/dev-target"
LOCAL_DB_URL="postgresql://postgres:postgres@127.0.0.1:54322/postgres"

usage() {
sed -n '2,15p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
exit 1
}

TARGET="${1:-}"
[[ "$TARGET" == "local" || "$TARGET" == "production" ]] || usage
shift

KEEP=false
EXPO_ARGS=()
while (($#)); do
case "$1" in
--keep) KEEP=true ;;
--) shift; EXPO_ARGS+=("$@"); break ;;
*) EXPO_ARGS+=("$1") ;;
esac
shift
done

cd "$ROOT"

# Metro caches modules with EXPO_PUBLIC_* values already inlined, so switching
# targets without clearing it can keep serving the old database URL.
clear_flag_if_target_changed() {
mkdir -p "$(dirname "$LAST_TARGET_FILE")"
local last=""
[[ -f "$LAST_TARGET_FILE" ]] && last="$(cat "$LAST_TARGET_FILE")"
echo "$TARGET" >"$LAST_TARGET_FILE"
[[ "$last" != "$TARGET" ]] && echo "--clear"
return 0
}

ensure_docker() {
docker info >/dev/null 2>&1 && return 0
echo "Docker is not running; starting Docker Desktop..."
open -a Docker
local waited=0
until docker info >/dev/null 2>&1; do
((waited >= 120)) && { echo "Docker did not start within 120s." >&2; exit 1; }
sleep 2
waited=$((waited + 2))
done
}

load_db_url() {
[[ -n "${SUPABASE_DB_URL:-}" ]] && return 0
if [[ -f "$ROOT/scripts/.env.local" ]]; then
set -a
# shellcheck disable=SC1091
source "$ROOT/scripts/.env.local"
set +a
fi
[[ -n "${SUPABASE_DB_URL:-}" ]] || {
cat >&2 <<'EOF'
SUPABASE_DB_URL is not set. Add production's connection string to
scripts/.env.local (Supabase dashboard, Connect, Session pooler):

SUPABASE_DB_URL="postgresql://postgres.obtgldkascmxbtpnvscn:<password>@aws-0-<region>.pooler.supabase.com:5432/postgres"

Or rerun with --keep to use the data already in the local database.
EOF
exit 1
}
}

import_production() {
load_db_url
mkdir -p "$SNAPSHOT_DIR"

echo "Dumping production data (public, auth)..."
bunx supabase db dump \
--remote="$SUPABASE_DB_URL" \
--data-only \
--use-copy \
--schema public,auth \
--exclude auth.schema_migrations \
--file "$SNAPSHOT"

echo "Resetting the local database to the committed migrations..."
bunx supabase db reset --local

# The migrations seed catalog rows, so empty every table the dump covers
# before loading it, and load in one transaction so a failure leaves the
# freshly reset database rather than a half-imported one.
echo "Loading the production snapshot..."
psql "$LOCAL_DB_URL" --quiet -v ON_ERROR_STOP=1 --single-transaction \
-c "set session_replication_role = replica;" \
-c "do \$\$
declare t text;
begin
select string_agg(format('%I.%I', schemaname, tablename), ', ')
into t
from pg_tables
where schemaname in ('public', 'auth')
and tablename <> 'schema_migrations';
if t is not null then
execute 'truncate table ' || t || ' cascade';
end if;
end \$\$;" \
-f "$SNAPSHOT"

echo "Local database now mirrors production."
}

start_local() {
ensure_docker
bunx supabase start

if [[ "$KEEP" == true ]]; then
echo "--keep: skipping the production import."
else
import_production
fi

local status api_url key
status="$(bunx supabase status -o env)"
api_url="$(sed -n 's/^API_URL="\{0,1\}\([^"]*\)"\{0,1\}$/\1/p' <<<"$status")"
key="$(sed -n 's/^PUBLISHABLE_KEY="\{0,1\}\([^"]*\)"\{0,1\}$/\1/p' <<<"$status")"
[[ -n "$key" ]] || key="$(sed -n 's/^ANON_KEY="\{0,1\}\([^"]*\)"\{0,1\}$/\1/p' <<<"$status")"
[[ -n "$api_url" && -n "$key" ]] || {
echo "Could not read the local API URL and key from 'supabase status'." >&2
exit 1
}

echo "Serving against local Supabase at $api_url (Studio: http://127.0.0.1:54323)"
local clear
clear="$(clear_flag_if_target_changed)"
EXPO_PUBLIC_SUPABASE_URL="$api_url" \
EXPO_PUBLIC_SUPABASE_PUBLISHABLE_KEY="$key" \
exec bunx expo start ${clear:+"$clear"} ${EXPO_ARGS[@]+"${EXPO_ARGS[@]}"}
}

start_production() {
echo "Serving against production Supabase."
local clear
clear="$(clear_flag_if_target_changed)"
exec env -u EXPO_PUBLIC_SUPABASE_URL -u EXPO_PUBLIC_SUPABASE_PUBLISHABLE_KEY \
bunx expo start ${clear:+"$clear"} ${EXPO_ARGS[@]+"${EXPO_ARGS[@]}"}
}

case "$TARGET" in
local) start_local ;;
production) start_production ;;
esac
61 changes: 56 additions & 5 deletions src/api/supabaseConfig.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,68 @@
import { describe, expect, it } from "bun:test";
import { SUPABASE_PUBLISHABLE_KEY, SUPABASE_URL } from "./supabaseConfig";
import {
PRODUCTION_SUPABASE_PUBLISHABLE_KEY,
PRODUCTION_SUPABASE_URL,
resolveSupabaseTarget,
} from "./supabaseConfig";

describe("SUPABASE_PUBLISHABLE_KEY", () => {
describe("PRODUCTION_SUPABASE_PUBLISHABLE_KEY", () => {
// This module is imported by the client bundle and by `scripts/`, so a
// secret pasted here would ship to every browser. Only the publishable key
// format is allowed.
it("is a publishable key, never a secret or service-role key", () => {
expect(SUPABASE_PUBLISHABLE_KEY.startsWith("sb_publishable_")).toBe(true);
expect(
PRODUCTION_SUPABASE_PUBLISHABLE_KEY.startsWith("sb_publishable_"),
).toBe(true);
});
});

describe("SUPABASE_URL", () => {
describe("PRODUCTION_SUPABASE_URL", () => {
it("points at the project over https", () => {
expect(SUPABASE_URL).toBe("https://obtgldkascmxbtpnvscn.supabase.co");
expect(PRODUCTION_SUPABASE_URL).toBe(
"https://obtgldkascmxbtpnvscn.supabase.co",
);
});
});

describe("resolveSupabaseTarget", () => {
const production = {
url: PRODUCTION_SUPABASE_URL,
publishableKey: PRODUCTION_SUPABASE_PUBLISHABLE_KEY,
};

it("uses production when no override is set", () => {
expect(
resolveSupabaseTarget({ url: undefined, publishableKey: undefined }),
).toEqual(production);
});

it("uses the override when both values are set", () => {
expect(
resolveSupabaseTarget({
url: "http://127.0.0.1:54321",
publishableKey: "sb_publishable_local",
}),
).toEqual({
url: "http://127.0.0.1:54321",
publishableKey: "sb_publishable_local",
});
});

it("never pairs a local URL with the production key", () => {
expect(
resolveSupabaseTarget({
url: "http://127.0.0.1:54321",
publishableKey: undefined,
}),
).toEqual(production);
expect(
resolveSupabaseTarget({ url: undefined, publishableKey: "sb_local" }),
).toEqual(production);
});

it("treats empty strings as unset", () => {
expect(resolveSupabaseTarget({ url: "", publishableKey: "" })).toEqual(
production,
);
});
});
Loading
Loading