# The bridge

The **bridge** is the seam every shell implements: the Swift WKWebView shell, the Rust/Tauri
shell, and the web fallback in JS. It is deliberately small and dumb. It moves product ids,
achievement ids and strings, and it knows nothing about entitlements, the config or the
game; the JS API (`createNative`) does all of that once, on top of it.

A bridge is two functions:

- `call(method, args)` returns a promise of the method's result;
- `on(event, listener)` subscribes to an event pushed from the shell and returns an
  unsubscribe function.

`BRIDGE_METHODS` and `BRIDGE_EVENTS` are the whole protocol, as data. The contract suite
checks every bridge against them, and shell code is generated from them, so the list here
is the only place the protocol is written down.

## Methods

| method | args | result |
| --- | --- | --- |
| `info` | `{}` | `{ target, shell, durability, capabilities: [name] }` |
| `products.owned` | `{}` | `{ owned: [productId] }` |
| `products.purchase` | `{ productId }` | `{ status, owned: [productId] }` |
| `products.restore` | `{}` | `{ owned: [productId] }` |
| `achievements.unlocked` | `{}` | `{ unlocked: [achievementId] }` |
| `achievements.unlock` | `{ achievementId }` | `{ unlocked: [achievementId] }` |
| `store.get` | `{ key }` | `{ value }`, where `value` is a string or `null` |
| `store.set` | `{ key, value }` | `{}` |
| `store.remove` | `{ key }` | `{}` |
| `store.keys` | `{}` | `{ keys: [key] }` |
| `splash.hide` | `{}` | `{}` |
| `lifecycle.settled` | `{}` | `{}` |
| `awake.set` | `{ on }` | `{ on }`, the state the system is really in |
| `links.open` | `{ url }` | `{}` |
| `share.open` | `{ title?, text?, url?, files?: [{ name, type, base64 }] }` | `{ status }` |
| `reviews.request` | `{}` | `{ status }`: `requested` (the store was asked, and decides whether to show its prompt) or `unavailable` |
| `reviews.open` | `{}` | `{ opened }`: whether the store's write-a-review page for this app was opened |
| `tasks.schedule` | `{ every, network }`, `every` in ms (at least 15 minutes) | `{ status }`: `background`, `foreground` or `unavailable` |
| `tasks.cancel` | `{}` | `{}` |
| `tasks.info` | `{}` | `{ every, lastRun }`, ms, `null` when not scheduled or never run |
| `tasks.due` | `{}` | `{ due, deadline }`: a run the system woke the app for, waiting for the page; asking takes it |
| `tasks.done` | `{ ok }` | `{}`: the run is over; the shell records it and tells the system |
| `media.update` | `{ title, artist?, album?, duration?, position?, playing, artwork?, rate?, skip?: { back, forward } }`, times in seconds | `{ status }`: `background`, `foreground` or `unavailable` |
| `media.stop` | `{}` | `{}`: nothing is playing; the system's controls go away |
| `location.current` | `{}` | `{ fix }`: where the device is now, or `null` (not allowed, location off, or no fix within 15 s) |
| `location.watch` | `{ distance }`, metres between fixes (0 for every one) | `{ status }`: `background`, `foreground`, `denied`, `off` or `unavailable` |
| `location.stop` | `{}` | `{}` |
| `location.fixes` | `{}` | `{ fixes: [fix] }`: the fixes the shell has kept since the page last asked, oldest first; asking empties the list |
| `permissions.query` | `{ name }` | `{ state }` |
| `permissions.request` | `{ name }` | `{ state }`, after asking the player if the platform still allows asking |
| `permissions.settings` | `{ name }` | `{ opened }`: whether the system's page where the player can change it was opened |
| `notifications.schedule` | `{ id, title, body, at }`, `at` in ms since 1970 | `{ status }` |
| `notifications.cancel` | `{ id }` | `{}` |
| `notifications.pending` | `{}` | `{ ids: [id] }` |
| `notifications.opened` | `{}` | `{ ids: [id] }`: the notifications the player opened the app through that the page has not been told about, oldest first; asking empties the list |
| `files.info` | `{}` | `{ kind, visible, synced }` |
| `files.list` | `{}` | `{ files: [{ name, size, modified }] }`, `modified` in ms since 1970 |
| `files.read` | `{ name }` | `{ base64 }`, `null` for a file that is not there |
| `files.write` | `{ name, base64 }` | `{}`; replaces the whole file, or leaves the old one |
| `files.remove` | `{ name }` | `{}`; a file that is not there is not an error |
| `settings.values` | `{}` | `{ values: { key: value }, show }`: what is stored, by stored key (`display.size`), and whether the app was opened to show its settings |
| `settings.set` | `{ key, value }` | `{}`; `value` is a boolean, a number or a string |
| `net.text` | `{ url }` | `{ status: 'ok', code, type, text }`, `{ status: 'failed', reason }` or `{ status: 'unavailable' }` |
| `downloads.start` | `{ url, name, bytes? }` | `{ status: 'started' }` or `{ status: 'unavailable' }`; the end comes as a `downloads` event |
| `downloads.list` | `{}` | `{ files: [{ name, size, total, ranged, type, src }] }` |
| `downloads.remove` | `{ name }` | `{}` |

A purchase `status` is `purchased`, `cancelled`, `pending` (e.g. Ask to Buy) or `failed`.
A share `status` is `shared`, `cancelled` or `unavailable`.
A permission `state` is `granted`, `denied`, `prompt` (the player has not been asked, or may
be asked again) or `unavailable` (this install has no such thing).
A notification `status` is `scheduled`, `denied` (the player has not allowed notifications)
or `unavailable`.
A `fix` is `{ latitude, longitude, accuracy, altitude, altitudeAccuracy, heading, speed, at }`:
degrees, metres (accuracy is the radius the device is within), degrees from north, metres per
second, and `at` in ms since 1970, with `null` for what the device does not know. A watch
`status` is `background` (fixes keep coming when the player leaves the app), `foreground`
(only while the app is in front), `denied` (the player has not allowed location: nothing is
asked, `permissions.request` does that) or `unavailable`.

`durability` says what survives: `reinstall` (a cloud store holds the saves now: iCloud,
Steam Cloud), `backup` (they are in the device's own backup, so they come back with a
reinstall or a new phone if the player has backups on, perhaps a day old: Android),
`device` (they survive a restart but not a reinstall) or `session` (memory only, e.g. a
locked-down web view). It can change while the app runs (the player signs in to iCloud), and
a `store.changed` event carries the new value when it does.

`capabilities` lists the capabilities this install really has: the ones the app's config
declares (see Config), less any this target or this install lacks.

## Capabilities gate methods

`METHOD_CAPABILITY` says which capability each gated method belongs to. A shell is built with
the app's config and **refuses a gated method whose capability the config does not declare**,
with an error naming the capability. That check is the shell's own: the page is on the other
side of a trust boundary, so a shell never takes the page's word for what is declared.

A declared capability the target lacks is not an error. The method answers anyway:
`awake.set` with `{ on: false }`, `share.open` and `reviews.request` with
`{ status: 'unavailable' }`, `reviews.open` with `{ opened: false }`. `links.open`
rejects a URL the config's `openExternal` list does not allow, and anything that is not an
`https:` or `mailto:` link.

`media.update` can say more than the title: `artwork`, an https image the config's `network`
allows, which the shell fetches and shows on the lock screen, in Now Playing and in the
notification; `rate`, the playback speed, so the system's progress runs at it; and
`skip: { back, forward }`, seconds, which puts skip buttons in place of next and previous (a
podcast's controls, not a playlist's). The system's skip buttons then reach the page as
`skipForward` and `skipBackward`, with their seconds.

`downloads.start` fetches a file (a podcast episode, a video) straight to disk in the app's
caches folder, where the system may clear it when space runs short (the app fetches it again),
under a plain file name, from an https address `network` allows, checked again where a redirect
lands. `bytes: [first, last]` asks for that range; `total` is then the whole file's size (from
the Content-Range), and `ranged` true. The page plays or reads it at `src`, an address the shell
serves with byte ranges (Apple's media stack plays nothing served any other way), in pieces a
few megabytes long however much is asked for, so a large file never sits in memory whole. A
`downloads` event says each one ended: `{ name, status: 'done', size, total, ranged, type, src }`,
`{ name, status: 'failed', reason }` or `{ name, status: 'cancelled' }` (removed while running).
It exists for what a page cannot keep itself: Apple's web view will not play audio the page
stored, nor keep a file of hundreds of megabytes.

`net.text` reads text (a feed, a page) in the shell's own code, where a page's CORS rules do
not apply, so it can read what the page itself may not: most podcast feeds send no CORS
header. It is the `network` capability's, and reads only what the config's `network` list
allows, by `allowedLink`'s rule, checked again by the shell and again on where any redirect
leads; https only, at most 25 MB, for at most 30 seconds. A shell with no HTTP client of its
own (Tauri, for now) answers `{ status: 'unavailable' }`.

The `permissions.*` methods take the name of a permission, which is also the capability that
gates them: a shell refuses a `name` the config does not declare, and any name that is not a
permission. `notifications.schedule` with an `id` already pending replaces that
notification. A notification the player taps is reported twice over, so it cannot be missed:
as a `notification` event if the page is listening, and in `notifications.opened`, which
holds it until the page asks (a tap can start the app before any page exists).

Location never asks the player: `location.current` and `location.watch` answer `null` and
`denied` until `permissions.request` with `location` has been granted. While the device's
location is switched off (the player's to turn on, in the system's settings, whatever the
app's permission), `location.watch` answers `off` and records nothing; a shell must not
claim a watch it cannot feed.

`permissions.settings` opens the system's page where the player can change what stands in
the way of a permission, for a button beside "not allowed" or "switched off": on Android the
device's Location page while location is switched off, and otherwise the app's own page
(its notification settings for `notifications`); on iOS the app's page in Settings (iOS has
no public way to its Location Services switch); on a Mac the matching pane of Privacy &
Security, or Notifications. `{ opened: false }` where there is no such page (the web,
Linux). A run with nobody there answers as if it had opened it. A watch runs until
`location.stop`, or until the app ends. The shell keeps every fix the watch gets, in order and
on disk, and tells the page with a `location` event; the page takes them with
`location.fixes`. A page the system paused or stopped while the watch ran takes what was kept
when it runs again, so a fix is never lost and never delivered twice.

The `files.*` methods work in one folder, the app's own. `kind` says what it is: `icloud`
(the app's iCloud Drive folder), `folder` (a plain folder the player can find) or `private`
(storage only the app sees); `visible` and `synced` say the same two facts directly. A
`name` is one plain file name, never a path, and a shell refuses a name with a separator or
a leading dot whatever the page says. `files.list` leaves out anything the app did not
write under such a name. Bytes cross as base64, because the bridge moves strings.

The `settings.*` methods keep the values of the settings the config's `settings` schema
declares, where the platform keeps an app's settings (`UserDefaults` on Apple platforms, which
the iOS Settings app writes too; `SharedPreferences` on Android; the page's storage on the
web). `settings.values` answers only what is stored: the API fills in defaults and reads each
value against the schema, since a platform's own page may store anything its field allows. A
shell refuses `settings.set` for a key the schema does not declare and for a value of the
wrong kind (a toggle's must be a boolean, a number's a number, the rest a string). `show` is
true once, when the system opened the app to show its settings (Android's App info gear): a
`settings.show` event can come before any page exists.

`lifecycle.settled` tells the shell the page has finished its pause work (its `pause`
listeners and its save queue). A shell that holds the app awake while it is being
backgrounded stops holding when it hears it; every other shell answers `{}`.

## Events

| event | payload |
| --- | --- |
| `pause` | `{}` (the app was backgrounded, or the device is going to sleep) |
| `resume` | `{}` |
| `owned` | `{ owned: [productId] }` (ownership changed outside a purchase call: an approved Ask to Buy, a refund) |
| `store.changed` | `{ keys: [key], durability? }` (saves changed from outside this run: another device through the cloud, another tab; or what survives changed) |
| `notification` | `{ id }` (the player opened the app through this notification) |
| `scroll.top` | `{}` (the system asks the open page to scroll back to its top: a tap on an iPhone's status bar) |
| `files.changed` | `{}` (the app's folder changed from outside: the player's other device, or the player in Finder; list again) |
| `task` | `{ deadline }` (the system woke the app for its background task) |
| `media` | `{ command, position? }` (one of the system's media buttons) |
| `location` | `{}` (the shell has fixes for the page: take them with `location.fixes`) |
| `settings.changed` | `{ keys: [key] }` (settings changed outside this page: in the iOS Settings app, by another window; read them again) |
| `settings.show` | `{}` (the system asks the app to show its settings: Android's App info gear, the Mac's Settings…) |

After `store.changed`, `store.get` answers the new value for each key, or `null` for one that
was removed. When the same key was written here and elsewhere, the shell decides which
survives (the last writer), and `store.get` says which.

A bridge may report `pause` or `resume` more than once in a row (its web view and its
shell can both notice). `createNative` turns that into a strict alternation for the game.

A `pause` listener may return a promise for the work the pause starts. A bridge whose shell
holds the app awake waits for those promises before it lets go; the API's listener returns
one that settles after the game's own pause listeners and its queued saves.

## Errors

A method that fails rejects its promise with an `Error` whose `message` says why. A purchase
the player cancels is **not** an error, it is `{ status: 'cancelled' }`.

`fixProblem(fix)` says what is wrong with a fix a shell sent, or `null` when it is one:
latitude and longitude in range, an accuracy, a time, and the rest numbers or `null`.
