# Build and ship an iPhone app with Exact, exact build and AppDrop

You are an agent with a shell. The user wants an iPhone app. You will write it with
Exact, build it into an IPA with the exact build service (no Mac or Xcode needed),
and hand the user an AppDrop link that installs it on their phone. You do not need
a copy of Exact (expo/exact): the service makes the app, and its guides are on GitHub.

If you are not starting fresh (you already have an Exact app), get a token (step 0),
then skip to step 3 and read https://exact.appdrop.app/docs for the build API. Its
commit (`exact=`) is in its app.json's `$schema` when the service made it, else that
of the checkout `exact new` made it with; its guides are at the URLs in step 1.

## 0. Get a build token

Every request needs a build token. If `~/.exact-build-token` exists, use it:
`EXACT_TOKEN=$(cat ~/.exact-build-token)`. Otherwise get one with the user's
Expo account:

```sh
API=https://exact.appdrop.app
curl -sS -X POST $API/auth/device > /tmp/exact-login.json
python3 -c 'import json; print(json.load(open("/tmp/exact-login.json"))["url"])'
```

Send the user that URL. Tell them: "Open this, sign in to Expo, approve, and
send me the number it shows." (The page says EAS CLI for now; that is expected.)
When they send the number, exchange it for the token:

```sh
REQ=$(python3 -c 'import json; print(json.load(open("/tmp/exact-login.json"))["request_id"])')
curl -sS -X POST $API/auth/device/$REQ -H 'Content-Type: application/json' \
  -d '{"match":"NUMBER"}' > /tmp/exact-token.json
python3 -c 'import json,os; d=json.load(open("/tmp/exact-token.json")); t=d.get("token")
if not t: raise SystemExit(d)
p=os.path.expanduser("~/.exact-build-token"); open(os.open(p,os.O_WRONLY|os.O_CREAT|os.O_TRUNC,0o600),"w").write(t); print("saved for", d["username"])'
rm -f /tmp/exact-token.json; EXACT_TOKEN=$(cat ~/.exact-build-token)
```

If the answer's `status` is `authorization_pending` or `slow_down`, the user has
not approved yet: wait `retry_after` seconds and send the same request again. If
it is `access_denied`, `expired_token` or `invalid_grant`, start over. The token
lasts 30 days. Never print it. If it stops working (`401`), get a new one.

A token from an Expo login has a worker-time budget: 15 minutes an hour, 60
minutes a day and 4 hours a week, and 4 builds at once (a rebuild with `base`
uses a few seconds of it). `curl -sS $API/usage -H "Authorization: Bearer $EXACT_TOKEN"`
shows what is used and when each window frees up.
A failed build never counts if the service caused it, or if it was refused:
the upload broke a rule the build checks before compiling your code (a bad
archive or app.json, an asset name, a permission purpose string, a top-level
await). The first 30 minutes of user-triggered build failures (i.e. a compile
error) each week do not count towards your usage limits. A build with a mistake
in the app fails in about 5 seconds with the compiler's errors, which the weekly
free allowance covers, so you can build to check.

## What you need

`python3`, `curl`, `tar`, and Node with `npx` (for AppDrop). Not git, Rust or an
Exact checkout: do not clone expo/exact for an app. A checkout (with `bun` and Rust)
is needed only to change Exact itself (step 2), for `exact new --game`, `--snapback`
or `--rust`, or to check the Contract on this machine rather than by building.

## 1. Make the app

Ask the service for a new app, made with the SDK it builds:

```sh
NAME=groceries   # the app's folder: lowercase words joined by hyphens
API=https://exact.appdrop.app APP=~/$NAME
EXACT_COMMIT=$(curl -sS $API/sdk -H "Authorization: Bearer $EXACT_TOKEN" \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)["main"]["upstream"])')
code=$(curl -sS -o /tmp/app-new.tar.gz -w '%{http_code}' "$API/new?name=$NAME&exact=$EXACT_COMMIT" \
  -H "Authorization: Bearer $EXACT_TOKEN")
if [ "$code" = 200 ]; then tar -xzf /tmp/app-new.tar.gz -C ~ && cd $APP; else cat /tmp/app-new.tar.gz; fi
DOCS=https://raw.githubusercontent.com/expo/exact/$EXACT_COMMIT/docs
```

It starts from the `one-screen` pattern (a total, quick-add buttons, a dated log).
Add `&pattern=<name>` for another, such as `list-detail` or `tabs`: the app's
AGENTS.md lists the ones its commit has, and an unknown name is refused with that
list. `site`, a website, adds app.json keys and a `.env`, so its first build is a
full one, not the 15-second first build the others get. `&title=`
and `&id=` set the app's name and bundle id (default: from the name, and
`com.exact.<name>-<random>`). A `502` or `503` means GitHub could not be read just
now: wait the `Retry-After` seconds and ask again.

Read `curl -sS $DOCS/start-here.md` first. It is the only required reading. Its
`bun exact.mjs` commands need a checkout: skip them. To look up a name, read the
card (`$DOCS/card.md`) or a recipe (`$DOCS/recipes/<name>.md`). Then write the app:
the views in `$APP/app.contract`, the data in `$APP/app.ts`. Replace
the pattern's screen and its tests in `app.test.contract` with the app's.

Nothing checks the app on this machine: the build does (step 3). A build with a
mistake fails in about 5 seconds, and its `diagnostics` list each compiler error by
file, line and column. Do not run `exact setup`, `exact ios` or any local native
build. This machine does not need to build iOS: the service does it.

## 2. Pin the SDK version (do this)

Always send the commit from step 1, so the build uses its SDK (the service cuts a
snapshot of expo/exact main every 4 hours, and on demand): add
`?exact=$EXACT_COMMIT` to every build URL in steps 3 and 4. Without it, the build
uses the service's default SDK, which can differ from the one the app was made with.

Only if the app needs a change to Exact itself: check out that commit
(`git clone https://github.com/expo/exact ~/exact && git -C ~/exact checkout $EXACT_COMMIT`),
change files inside `~/exact`, and send that change with the app as
`.exact-sdk.patch` at the app's root, made before the tarball in step 3. Make the
change on the commit from step 1: a patch from a newer checkout carries every
upstream commit since the snapshot and is refused as too big.

```sh
git -C ~/exact add -N .
git -C ~/exact diff --full-index --binary --no-renames $EXACT_COMMIT > $APP/.exact-sdk.patch
```

A patched build is slower: it never reuses a base build, and it compiles the
SDK code you changed (about 20 seconds to a few minutes). A patch that conflicts
with the service's own SDK changes fails and names the files. Delete the file
when you no longer need the change. Details: https://exact.appdrop.app/docs

## 3. Build it

```sh
API=https://exact.appdrop.app
cd $APP && tar czhf /tmp/app.tar.gz --exclude=node_modules --exclude=.exact .
ID=$(curl -sS -X POST "$API/build?exact=$EXACT_COMMIT" \
  -H "Authorization: Bearer $EXACT_TOKEN" \
  -H "Content-Type: application/gzip" --data-binary @/tmp/app.tar.gz \
  | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("id") or sys.exit(d.get("error")))')
```

`h` packs the files links point to: a link out of the app (`assets` -> a folder elsewhere) is refused. Keep
`--exclude=.exact`: an app made with a checkout of Exact has `.exact/checkout`, a link to that checkout, and `h`
would pack the whole checkout (the service ignores the link itself). A refused archive (a zip, no `app.contract` at
the root, over a limit) prints the reason and no build starts.

Poll until the build finishes (a fresh app takes about 15 seconds):

```sh
until S=$(curl -sS "$API/$ID/" -H "Authorization: Bearer $EXACT_TOKEN"); \
  echo "$S" | python3 -c 'import json,sys; s=json.loads(sys.stdin.read(),strict=False)["status"]; sys.exit(s not in ("succeeded","failed"))'; \
do sleep 2; done
echo "$S" | python3 -c 'import json,sys; d=json.loads(sys.stdin.read(),strict=False); print(d["status"]); print(d.get("note","")); print((d.get("sdk") or {}).get("note",""))
for e in d.get("diagnostics",[]): print("%s:%s:%s [%s] %s" % (e["file"],e["line"],e["col"],e["id"],e["message"]))
print(d.get("error","")[-4000:])'
```

If the status has a `note` or an `sdk.note`, tell the user what it says in plain
words. It names what the IPA leaves out or which SDK built the app: for example,
that the app declares an Apple Watch app the IPA does not include. The phone app
is complete.

- If `status` is `failed`, `diagnostics` lists the compiler's errors (`file`, `line`,
  `col`, `id`, `message`) and `error` holds its whole output. Fix the app and build
  again. But if `sdk.snapshotDue` is set, the build used an older SDK
  than your commit (none newer was cut yet), and the error's last line says
  so: tell the user, and build again after that time before changing the app.
- If you get `429` or `503`, wait for the `Retry-After` seconds, then retry. A
  `429` with `"window": "hour"`, `"day"` or `"week"` means the worker-time
  budget is spent: tell the user when it frees (`available_at`) rather than
  waiting hours. Prefer `?base=` rebuilds: they cost seconds, not minutes.

When it succeeded, download the IPA:

```sh
curl -sS -o /tmp/app.ipa "$API/$ID.ipa" -H "Authorization: Bearer $EXACT_TOKEN"
```

## 4. Rebuild after changes (fast)

After you edit the app, build with `?base=$ID` (the last successful build). If no
native code changed, the build takes about 4 seconds. Use the new id as the base
for the next rebuild. Without `?base=`, the service uses your last successful
build of the same app (by app.json's `app.id` and `app.name`) as the base; send
`?base=none` for a full build.

When native code did change (your app's Rust, Swift, app.json), the service keeps
what your last build of the app compiled, so the rebuild compiles only what
changed. These build caches are yours alone. `GET /usage` shows their size
(`build_caches`), and `curl -sS -X DELETE $API/caches -H "Authorization: Bearer $EXACT_TOKEN"`
drops them, which makes your next build of each app a cold one.

An upload byte-identical to one of your builds from the last 24 hours (same
files, same `exact` and options) is answered in about a second with that
build's IPA, without a worker and with no worker time charged. Its status says
`reused` with the build it came from. An app with npm dependencies and no
`bun.lock` gets the newest versions when it builds, so an identical re-upload
returns the versions the earlier build got: change a byte in the app (or add a
lockfile) to build it fresh.

```sh
curl -sS -X POST "$API/build?exact=$EXACT_COMMIT&base=$ID" ...   # the same headers and body as step 3
```

## 5. Send it to the user

```sh
npx -y appdrop /tmp/app.ipa
```

AppDrop signs the IPA and prints a link like `https://appdrop.app/d/…`. Send the
user the link: they open it on their iPhone to install the app.

## Reference

- Build API: https://exact.appdrop.app/docs
- Exact's guides, at the commit you build with: `$DOCS/start-here.md`, `$DOCS/card.md`,
  `$DOCS/recipes/`, `$DOCS/patterns/` (https://github.com/expo/exact)
