# Distribution and updates

These are the features you need after exporting when you sell a visual novel commercially. All of them are set in `build` in `liminalia.json` and with environment variables,
and if you don't set them, the game is exported as before (pass private keys and passwords in environment variables, and write only the names of those environment variables in `liminalia.json`).
For signing and updating Studio itself, see [Distributing the authoring app (Liminalia Studio)](#制作アプリliminalia-studioの配布).

`lim doctor [project] [--target mac,windows,linux,android,ios,steam,update]` checks in one go whether you have the tools needed for exporting
(Node, Chromium, Electron, ffmpeg, cwebp, the Developer ID and notarization credentials, makensis, osslsigncode, the Android SDK, a JDK, bundletool, the release key,
Xcode, the signing team, the App Store Connect API key, steamcmd and depots, the private key for signing updates, and the encryption key). If anything that the project's settings use, or that the targets listed in `--target` need,
is missing, it shows "×" with how to install it, and exits with code 1. It doesn't install anything or create any keys.

## Code signing and notarization

### Mac (Developer ID and notarization)

If you write the name or SHA-1 of a signing certificate in your keychain in `build.mac.signIdentity` (the environment variable `LIMINALIA_MAC_SIGN_IDENTITY` takes precedence),
the app is signed from the inside out (helper apps, frameworks and native libraries first) with the hardened runtime, entitlements and a timestamp
(@electron/osx-sign). If you don't write it, or write `-`, the app is ad hoc signed as before (enough only for running it on your own Mac).

```json
"build": { "mac": { "signIdentity": "Developer ID Application: Example Inc. (ABCDE12345)", "notaryProfile": "liminalia-notary" } }
```

- If you leave out the entitlements, the export creates the ones Electron needs (JIT and the executable memory it uses). In the Steam-connected version, library validation is also turned off,
  because the app loads the Steam library signed by Valve. To provide your own, write the path of the plist in `build.mac.entitlements`
- Notarization happens if credentials are available (`build.mac.notarize: false` or `LIMINALIA_NOTARIZE=0` signs only). The credentials are one of the following
  - A keychain profile: `build.mac.notaryProfile` or `LIMINALIA_NOTARY_PROFILE` (create it with `xcrun notarytool store-credentials <name>`; recommended)
  - An App Store Connect API key: `LIMINALIA_NOTARY_KEY` (the path of the .p8), `LIMINALIA_NOTARY_KEY_ID`, `LIMINALIA_NOTARY_ISSUER`
  - An Apple ID: `LIMINALIA_NOTARY_APPLE_ID`, `LIMINALIA_NOTARY_PASSWORD` (an app-specific password), `LIMINALIA_NOTARY_TEAM_ID`
- For notarization, the app is zipped and sent with `xcrun notarytool submit --wait`. If it passes, it's stapled with `xcrun stapler staple`, and `spctl` checks that Gatekeeper accepts it.
  If it doesn't pass, the export stops and shows the reason from `notarytool log` (this takes a few minutes)
- Signing and notarization only work on a Mac. If the certificate isn't in the keychain, the export stops before building

### Windows (Authenticode)

In `build.windows.sign`, write either a certificate (PFX) and the environment variable that holds its password, or an external signing command. The executable and the installer
(`build.windows.installer`) are signed.

```json
"build": { "windows": { "sign": { "pfx": "certs/code-signing.pfx", "passwordEnv": "LIMINALIA_WIN_PFX_PASSWORD" } } }
```

- With a PFX, signing uses signtool (Windows SDK) on Windows, and osslsigncode (`brew install osslsigncode`, `apt install osslsigncode`) on Mac and Linux.
  The timestamp (RFC 3161) server is `timestampUrl` (default `http://timestamp.digicert.com`). The password isn't put in command arguments; it's passed in a file that only you can read
- The environment variables `LIMINALIA_WIN_PFX` (the path of the PFX) and `LIMINALIA_WIN_SIGN_COMMAND` take precedence over the settings. The tools' locations can be set with `LIMINALIA_OSSLSIGNCODE` and `LIMINALIA_SIGNTOOL`
- Since 2023, OV and EV certificates keep their keys in hardware (a token or a cloud HSM), so they often can't be passed as a PFX. In that case, use an external signing command.
  `{file}` is replaced with the path of the file to sign. For example, Azure Trusted Signing from a Mac or Linux with [jsign](https://ebourg.github.io/jsign/):
  ```json
  "build": { "windows": { "sign": { "command": ["jsign", "--storetype", "TRUSTEDSIGNING", "--keystore", "weu.codesigning.azure.net", "--alias", "account/profile", "--tsaurl", "http://timestamp.acs.microsoft.com", "{file}"] } } }
  ```
  Pass secrets such as access tokens as jsign's documentation describes. The command runs without a shell, so things like `$VAR` aren't expanded
  (don't write secrets in `liminalia.json`; have the command read them from environment variables or files)
- If a tool (osslsigncode, signtool), the certificate or the password is missing, the export stops before building and shows the reason and how to install what's missing.
  With `ifMissing: "skip"`, it only warns and exports without signing (for trial exports on your own computer, for example)

## Windows installer

If `build.windows.installer` is `true` (or an object with settings), `lim build windows` makes `<name>_<version>_Setup.exe` in addition to the folder and zip
(with NSIS's makensis. If signing is set up, the installer is signed too).

```json
"build": { "windows": { "installer": { "perMachine": false, "desktopShortcut": true, "languages": ["ja", "en"] } } }
```

- The installer's screens are in Japanese and English (chosen by Windows' display language; `languages` narrows the choice). The player can choose where to install, and on the last screen, whether to launch the game and create a desktop shortcut
- It creates a Start menu shortcut and registers the uninstaller in Apps & features. Uninstalling deletes only the installed files
  (anything the player put in the install folder, and save data, are kept). If a previous version is installed, it's removed with that version's uninstaller before installing
- By default it installs for the current user only (`%LOCALAPPDATA%\Programs\<name>`; no administrator rights needed). With `perMachine: true`, it installs for all users (Program Files; administrator rights needed)
- makensis is required: `brew install makensis` on Mac, `apt install nsis` or similar on Linux, and https://nsis.sourceforge.io/Download on Windows.
  You can set its location with `LIMINALIA_MAKENSIS`. If it isn't found, the export stops before building and shows how to install it (with `LIMINALIA_INSTALLER=0`, it exports without making the installer)
- The uninstaller (Uninstall.exe) is created at install time, so it isn't signed

## Icons

If you set `build.icon` to a 1024px PNG, it's used to make the icons of the Mac version (.icns), the Windows version (.ico; or the .ico in `build.winIcon`), the Linux version (the picture of the `.desktop` file),
the browser version (the picture used when it's added to a home screen) and the mobile versions. The template (`lim new`) includes a placeholder icon, `icon.png`.

- If `build.icon` is missing, isn't found, or is still the template's placeholder, exporting a desktop version shows a warning
  (without an icon, the Mac version gets Electron's icon and the Windows and Linux versions get none)
- For builds connected to Steam (`build.steam`), the export stops instead of warning

## Packaging (zip and dmg)

The Windows version gets a folder and a zip by default (`LIMINALIA_ZIP=0` skips the zip). For the Mac and browser versions, a zip and a dmg are made only when you ask for them.

```json
"build": { "mac": { "zip": true, "dmg": true }, "browser": { "zip": true } }
```

```bash
lim build mac,browser --zip --dmg   # make them for this export only (--zip is the zip of the Mac and browser versions, --dmg is the Mac dmg)
```

| Setting | What's made |
|---|---|
| `build.mac.zip` | `<name>.zip` (next to the app). Made with `ditto -c -k --sequesterRsrc --keepParent`, which keeps the symbolic links inside frameworks, execute permissions and signatures (the same form as Compress in the Finder; meant to be opened on a Mac) |
| `build.mac.dmg` | `<name>.dmg` (next to the app). Made with `hdiutil`, containing the app and `Applications`, a link to `/Applications` (open it and drag the app onto the link to install). The volume name is the name of the exported file |
| `build.browser.zip` | `<out>/browser/<id>.zip`. Contains the contents of the exported folder, with `index.html` at the top of the zip (you can upload it as is as an HTML game on itch.io) |

- The order of precedence is `--zip` and `--dmg` on `lim build`, then the environment variables `LIMINALIA_ZIP` and `LIMINALIA_DMG` (`1` or `0`), then `liminalia.json`
- When notarizing, the app is packaged after it's stapled (the dmg itself isn't signed; the app inside is already stapled). The app is packaged as exported, before the launch check
- A dmg can only be made on a Mac (on other OSes, if `build.mac.dmg` is set, the export stops before building)
- The license notices for third-party components are included too. Every export puts `THIRD_PARTY_LICENSES.txt` (for the loading code Vite adds to the build) in the game's content,
  and the browser version has it at the top of the folder and the zip. Desktop versions also put it next to Electron's `LICENSE` and `LICENSES.chromium.html`: inside the app folder for Windows and Linux,
  and next to the app for Mac, where the zip and dmg include them alongside the app. If you repackage the game yourself, include these three
- Before building, `lim build` shows an estimate of the free space the whole export needs (besides copying the assets: Electron, `assets.asar`, the encrypted copy of the assets, and the zip, dmg and installer) along with the free space,
  and stops if there isn't enough (before it runs out partway). Assets on the same disk are cloned and use almost no space, so they aren't counted; the asar, encryption and packaging write the content, so they are.
  If the temporary folder is on another disk, the working space is compared with the free space there
- On Studio's export screen too, these appear under "Package as" when you choose Mac or Browser. Changes are saved to `liminalia.json` right away, and `lim build` uses the same settings

### Size (the engine bundle, language files and the Mac CPU)

- The engine bundle that's exported (`engine/*.js`) doesn't include the command descriptions (summaries, parameter descriptions, examples, search words and their English).
  Studio, VS Code and `lim reference` read them, but the game doesn't. The size of the bundle appears in the export's progress ("Engine and plugins") and in `lim size`.
  In the engine repository, a test (`packages/cli/test/engine-bundle.test.ts`) fails if the template project's bundle goes over 230 KB gzipped
- Electron's language files (`locales/*.pak` on Windows and Linux, `*.lproj` on Mac) are included only for the game's languages (`languages`) and English
  (both Simplified and Traditional for Chinese). Without a file for the OS language, Electron's menus and dialogs are in English.
  To keep other languages, list them in `build.desktop.locales` (`["fr", "ko"]`); `"all"` keeps every language (as before)
- The Mac version is universal by default (one app that runs on both Apple Silicon and Intel). Players can get one download without knowing their Mac's CPU,
  and Intel Macs remain in use through macOS 26, so the default stays. Splitting it by CPU leaves Electron for one CPU only and makes it about half the size
  (for the template game, universal is a 493 MB app and a 222 MB zip; arm64 alone is a 257 MB app and a 118 MB zip).
  Narrow it to one with `build.mac.arch` (`"universal"`, `"arm64"` or `"x64"`) or the environment variable `LIMINALIA_MAC_ARCH` (which takes precedence). To ship both, export each one and make a separate zip for each
- The Windows and Linux versions are x64 by default. Change them with `build.windows.arch` (`"x64"`, `"arm64"` or `"ia32"`) and `build.linux.arch` (`"x64"` or `"arm64"`),
  or with the environment variables `LIMINALIA_WINDOWS_ARCH` and `LIMINALIA_LINUX_ARCH` (which take precedence)
- The environment variable `LIMINALIA_ARCH` applies to every target exported at once, when there's no variable for that target (on Windows and Linux, the Mac's `universal` is the same as not setting it).
  If its value doesn't fit a target, the export stops before building anything (`LIMINALIA_ARCH=ia32 lim build mac,windows` stops at the Mac version; use the per-target variables to set each one)

```json
"build": { "mac": { "arch": "arm64" }, "windows": { "arch": "ia32" }, "linux": { "arch": "arm64" } }
```

```bash
LIMINALIA_MAC_ARCH=arm64 lim build mac --zip   # for Apple Silicon
LIMINALIA_MAC_ARCH=x64 lim build mac --zip     # for Intel
LIMINALIA_MAC_ARCH=arm64 LIMINALIA_WINDOWS_ARCH=ia32 lim build mac,windows   # per target in one export
```

### Linux version

The Linux version gets a folder and `<name>.tar.gz` by default (`LIMINALIA_ZIP=0` skips the tar.gz). The export writes the tar.gz itself, with root (0) as the owner,
and permissions set to 755 for folders and executables and 644 for everything else (it doesn't include your user number and name, and executables keep their permission even when exported on Windows).

| File | What it is |
|---|---|
| `<executable>.sh` | Starts the game. Where Chromium's sandbox can't be used (Ubuntu 24.04 and later restrict user namespaces with AppArmor, and extracting the archive doesn't make `chrome-sandbox` setuid root), it starts the game with `--no-sandbox`. `LIMINALIA_SANDBOX=1` never adds it, and `0` always adds it |
| `<id>.desktop` | The menu entry. So that it opens from the extracted folder, it looks for the launcher next to itself. The launcher rewrites it with absolute paths to the current location (`Exec` and `Icon`) every time it starts, so after starting the game once you can copy it to `~/.local/share/applications/` to add it to the menu |
| `icon.png` | A copy of `build.icon` (PNG). The picture of the `.desktop` file |

- You can also start the executable directly (`build.executableName`, or the project's id if that's not set). Where the sandbox can be used, it works the same
- When distributing on Steam, choose the launcher in the launch options

## Electron fuses in the desktop versions

After building the desktop versions (Mac, Windows and Linux) and before signing, the export changes Electron's fuses (switches burned into the executable).
Plain Electron lets anyone run the game's executable as Node (`ELECTRON_RUN_AS_NODE`), inject code with `NODE_OPTIONS`,
and inspect it with `--inspect` (which can also reveal the encryption key).

| Fuse | Default | What it does |
|---|---|---|
| `RunAsNode` | Off | `ELECTRON_RUN_AS_NODE=1` can't run the game's executable as Node |
| `EnableNodeOptionsEnvironmentVariable` | Off | `NODE_OPTIONS` is ignored |
| `EnableNodeCliInspectArguments` | Off | `--inspect` and similar options are ignored |
| `OnlyLoadAppFromAsar` | On when the app is in an asar | Loads only from `resources/app.asar` (a `resources/app` folder can't replace it) |
| `EnableEmbeddedAsarIntegrityValidation` | On for Mac and Windows when the app is in an asar | The game doesn't start if the file lists of `app.asar` or `assets.asar` were changed |

- For asar integrity, the packager registers `app.asar` (on Mac, `ElectronAsarIntegrity` in Info.plist and a digest inside Electron Framework; on Windows, a resource in the executable),
  and the export adds the assets' `assets.asar`, which it adds later, to the same list, because an app with an asar that isn't in the list doesn't start.
  If it can't be added (an unknown version of Electron, for example), the export shows a warning and exports without the integrity check
- Linux's Electron doesn't check asar integrity, so the Linux version doesn't turn it on
- If `build.asar` is `false` (`LIMINALIA_ASAR=0`), the two asar fuses stay off
- To change them one by one, set names to `true` or `false` in `build.desktop.fuses`. `false` leaves the fuses alone (as before)

```json
"build": { "desktop": { "fuses": { "EnableEmbeddedAsarIntegrityValidation": false } } }
```

You can check what was burned in with `npx @electron/fuses read --app <app>` (the .app on Mac, the .exe on Windows, the executable on Linux).
The authoring app (Liminalia Studio) also ignores `NODE_OPTIONS` (it keeps `RunAsNode`, because AI assistants run its MCP server with the app's executable,
and keeps `--inspect`, which Playwright uses to connect when checking the packaged app).

## The exported page (CSP, title and home screen icons)

The `index.html` of the browser and desktop versions includes a Content Security Policy (`<meta http-equiv="Content-Security-Policy">`).
The game loads only from the same place as the game, and outside scripts and scripts inside HTML parts don't run.

| Directive | Default |
|---|---|
| `script-src` | The engine's files and the script the export writes into `index.html` to install the Service Worker (by the hash of its content) |
| `style-src` | `'self' 'unsafe-inline'` (the engine writes styles directly on elements) |
| `img-src`, `media-src`, `font-src`, `connect-src` | `'self' data: blob:` (save thumbnails, layered sprites and so on). `connect-src` also gets the origins of `build.crashReport.url` and `build.analytics.url`, and of `build.feedback.url` for a test build |
| `object-src`, `frame-src`, `worker-src`, `manifest-src`, `base-uri` | `'self'` (`worker-src` also `blob:`) |
| `form-action` | `'none'` |

When you use plugins that load outside things (outside APIs, embedded videos, WebAssembly and so on), add them per directive with `build.csp`. `false` removes that directive,
and setting `build.csp` to `false` leaves the CSP out (as before).

```json
"build": { "csp": { "connect-src": ["https://api.example.com"], "frame-src": ["https://www.youtube.com"], "script-src": ["'wasm-unsafe-eval'"] } }
```

The page title (`<title>`) is the game's `title`, and the description (`<meta name="description">` and the home screen description) is `description` in `liminalia.json`.
The same title and description go into the Open Graph tags (`og:title` and `og:description`) used when the URL is shared on social media (there's no image, since it needs the absolute URL of where the game is published).
The page language (`<html lang>` and the home screen `lang`) is the original language (the first of `languages`, or `ja` if it isn't set).
The pictures used when the game is added to a home screen are made from `build.icon` (PNG): 192px, 512px, a maskable 512px that isn't cut off when cropped to a circle, and a 180px apple-touch-icon for iPhone.
The page doesn't stop zooming (`user-scalable=no`). The game screen stops double-tap and pinch zooming with CSS (`touch-action`), so controls don't change.

## Test builds (leaving feedback while playing)

Builds for testers and clients can include a way to leave feedback on the scene while playing. Product exports don't include it (when it's left out, its code isn't in the engine bundle at all).

```bash
lim build [project] browser --feedback     # a test build (the same for the Mac version and others)
```

```json
"build": {
  "feedback": { "url": "https://example.com/feedback" },
  "variants": { "test": { "feedback": true } }
}
```

- A test build is made with `lim build --feedback`, "Test build" in the authoring app's export screen, or an edition with `feedback: true` (`--variant test`)
- A test build isn't exported to the same place as the product. The browser version goes to `<out>/browser/<id>-test` (`<id>-<name>-test` for an edition), and the desktop and smartphone versions get `_test` in their names
  (`<out>/windows/<name>_test_<datetime>/`; the Windows installer installs it as a separate app from the product). `feedback: true` is written to `project/build.json` and `build-history.jsonl`
- A test build exports images and sounds that the scenario or characters use but that don't exist yet as stand-ins (a card with "MISSING" and the asset's name for images, silence for sounds).
  This lets people read a scenario before the art and sound are ready. The cards are the same size as the dev server's (screen size for backgrounds, a person's shape for sprites, 16:9 for images). Other kinds of missing assets, such as videos,
  and names that differ only in case still stop a test build. Product exports stop on missing assets as before
- `lim publish itch`, `lim publish steam`, `lim update-manifest` and `lim patch` stop if what they upload (or start from) is a test build. Add `--allow-test` to upload a test build
- In a test build, "Feedback" at the top left and F8 take a screenshot of the page and open the feedback panel. Each piece of feedback carries the script file and line,
  the page key (which points to the same page even after lines are added), the screenshot, the name (remembered), the time, and the version and edition
- With `build.feedback.url`, feedback is sent as a POST of JSON (`kind: "liminalia-feedback"`; as with `build.crashReport`, you provide the receiving side).
  Without it, the player saves `<project ID>-<date-time>.liminalia-feedback.json` and passes it on (on phones, through the share sheet)
- Feedback you receive becomes comments on its script lines with "Import feedback…" in Studio's Comments screen (docs/studio.md, "Comments"). JSON received at the URL can be imported the same way once saved as a file

## Crash records and source maps

Exported games keep a record of one uncaught exception (["Crash reports" in player.md](player.md#クラッシュレポート)). If you write `build.crashReport.url`,
the game asks the player at the next launch and then sends that JSON as a POST (you provide the receiving side). The record contains the following.

| Field | Contents |
|---|---|
| `message`, `stack`, `kind` | The exception's message and stack. `kind` is `error` (an uncaught exception) or `rejection` (an unhandled Promise rejection) |
| `source` | Where in the program the exception happened (`engine/….js:line:column` in the exported bundle; only for `error`) |
| `at`, `step` | The last page shown (`file:line`), and the position of the command being run (when it stopped on a command partway through a page) |
| `trail`, `diagnostics` | The pages shown before it stopped (the last 10 pages) and the runtime diagnostics (the last 10; `file:line [code] message`) |
| `version`, `build`, `engine`, `platform`, `language`, `screen`, `userAgent`, `date` | The game version, the export date and time, the engine version (`engine` in `project/build.json`), the environment it was played in (`browser`, `desktop`, `ios`, `android`), the language, the screen size, the browser, and the date and time |

The positions in `stack` and `source` are positions in the minified bundle, so map them back to the original program with source maps. `build.sourcemap` chooses whether to make them (by default they aren't made).

```json
"build": { "sourcemap": "separate" }
```

- `"separate"`: they aren't put in the files you distribute, and are kept in `sourcemaps/<project ID>-<export date-time>/` in the export folder. The date and time are the same as `build` in the record,
  so you can pick the ones that match a record you receive. To map positions back, use `lim crash` (below).
  They pile up with every export, so only the newest `build.keepSourcemaps` (or `build.keep` if that isn't set) for each name are kept and the rest are deleted ("Cleaning up exports" below).
  To keep them for reading records from distributed versions, raise `build.keepSourcemaps`, set it to `0` (delete nothing) or copy them outside `dist`
- `"include"`: they're put in the export (players can see the original program in their developer tools. The code of the project's plugins can be seen too, so think it over before choosing this for a release)

The environment variable `LIMINALIA_BUILD_SOURCEMAP=1` also includes them, the same as `"include"` (for looking into what makes up the bundle).

Pass a record you receive to `lim crash`, and it picks the source map copy by the `build` time in the record, maps the positions in `source` and `stack` back to the original files and lines,
and shows them next to the script positions (`at`, `step`, `trail`, `diagnostics`). If you copied the source maps somewhere else, give that folder with `--maps`.

```bash
lim crash crash.json             # add --json for JSON output
lim crash crash.json --maps ~/maps/game-2026-11-08T01-02-03-004Z
```

If there's no matching copy or no position could be mapped back, the exit code is 1 (the script positions are still shown). From an AI assistant, the MCP tool `read_crash_report` reads the same thing.

## Play statistics (optional)

To find out how often each choice is picked and where players stop playing, write a destination in `build.analytics.url`. If you don't, nothing is sent (the default).

```json
"build": { "analytics": { "url": "https://example.com/analytics" } }
```

- The first time the exported game starts, it asks the player whether it may send them. It sends them only if the player answers "Yes"; until the player answers, and if they answer "No," nothing is sent.
  The player can change this at any time with "Send play statistics" in Settings (the answer is remembered on that device). The development server, the preview in Studio and automated checks (`lim playtest` and so on) don't ask and don't send
- Only the choices picked (the choice's line, which of the options shown it was, out of how many, and the jump target) and the last page shown when the game was closed or sent to the background are sent.
  The text (which can include names players entered), variables, saves, and IDs that identify a device or person aren't sent. Events are grouped by a marker made for each launch (`session`)
- They're sent together as a POST every 20 choices and when the game is closed or sent to the background. The body is JSON (`Content-Type` is `text/plain`, to avoid the browser's preflight request)

```json
{
  "project": "my_game", "version": "1.0.0", "session": "3f1c…", "platform": "browser", "language": "",
  "events": [
    { "type": "choice", "at": "chapter1:120", "option": 1, "options": 3, "target": "chapter1#north", "time": 640 },
    { "type": "leave", "at": "chapter2:48", "time": 1830 }
  ]
}
```

For the share of each option, count the `choice` events with the same `at` by `option`. For where players stopped, count the last `leave` of each `session` (a player who keeps playing gets a different `session` at the next launch).
You provide the receiving side (your own server), and include it in your store declarations and the game's privacy policy ("Store declarations" below).

## Cleaning up exports

The Mac, Windows, Linux and iOS versions are exported to `<out>/<target>/<name>_<datetime>/`, and the Android version to `<out>/android/<name>_<datetime>.apk`, so they pile up with every export.

```bash
lim clean [project] --keep 2 --dry-run   # only shows what would be deleted and how big it is
lim clean [project] --keep 2             # keeps the newest 2 for each name and deletes the rest (narrow the targets with --target mac,windows)
lim clean [project] --target sourcemaps   # cleans up only the source map copies (when build.sourcemap is "separate")
```

```json
"build": { "keep": 5, "keepSourcemaps": 20 }
```

- Every `lim build` deletes old exports in the target's folder, keeping only the newest `build.keep` of them (the environment variable `LIMINALIA_KEEP` takes precedence).
  If it's left out, 3 are kept. `0` deletes nothing (the default before 2026-11; to keep a distributed version as the base for patches, copy it outside `dist` or set `0`).
  This number is also used when you leave `--keep` out of `lim clean` (1 if it isn't set or is `0`)
- Exports are counted per name before the date and time (exports of an edition with `--variant` have a different name, and Android `.apk` and `.aab` files are also counted separately).
  Items whose names aren't in the date-and-time form, the browser version (overwritten every time), `patches/` and `update/` aren't touched
- Exports from Studio's export screen work the same as `lim build`, so `build.keep` applies to them too
- Source map copies (`<out>/sourcemaps/<name>-<datetime>/`) are also deleted on every export, keeping the newest `build.keepSourcemaps` for each name
  (the same number as `build.keep` if it's left out; `0` deletes nothing). When you leave `--keep` out, `lim clean` uses this number (or `build.keep`'s if it isn't set or is `0`)

## Export records (the game version and the engine version)

Each export records the game version and the version of the engine it used, both in what's exported and in the export folder (the record stays after old exports are cleaned up).

| Where | Contents |
|---|---|
| `project/build.json` in the exported game | `id`, `version` (the game version: `version` in `liminalia.json` or the environment variable `LIMINALIA_VERSION`; empty if neither is set), `engine` (the engine version), `variant`, `feedback` (`true` for a test build) and `date`. It's in the browser, desktop and smartphone versions alike |
| `build-history.jsonl` in the export folder | One line of JSON is added for each export: `date`, `id`, `version` (the game version; `1.0.0`, the version the export used, if it isn't set), `engine`, `targets`, `variant`, `feedback` (`true` for a test build) and `outputs` (what was exported, as paths from the export folder) |

- The engine version is the same number as `lim --version` ([versioning.md](versioning.md)). The end of the export shows "Game version 1.2.0, engine version 0.2.0"
- The engine version isn't written into the program (`engine/*.js` and `index.html`). Raising the version alone doesn't change the game itself, so `lim patch` can still make a patch
- The export that `lim patch` makes for comparison isn't recorded

## Encrypting assets and scenarios

```json
"build": { "encrypt": true, "browser": { "encrypt": true } }
```

| Setting | What's encrypted | Where it's decrypted | Where the key is stored |
|---|---|---|---|
| `build.encrypt` | The desktop version's assets (inside assets.asar), scenarios, data, translations, characters, flowchart and included packs | The app (when main.cjs serves them over `liminalia://`) | `.liminalia/encrypt-key` |
| `build.browser.encrypt` | The browser version's assets, the game's content and included packs | The Service Worker (`lm-sw.js`; index.html registers it before loading the engine) | `.liminalia/encrypt-key-browser` |
| `lim pack` (`--encrypt desktop`, `browser`, `off`) | The pack's scenarios, data, translations, characters and assets (`pack.json` stays as it is) | The game the pack is installed in | One of the above |

- The format is the magic number `LMEN`, a 16-byte IV and AES-256-CTR content. Files without the magic number are read as they are, so unencrypted packs can be mixed in
- The IV is derived from the key, the file's relative path and a hash of its content (HMAC). Files whose content doesn't change come out the same in every export,
  so delta updates on Steam and itch.io (butler) only send the files you changed. The readers take the IV from the file, so encrypted files from earlier exports still read as before
- By default, `lim pack` uses the desktop key in a project with `build.encrypt`, the browser key if there's only `build.browser.encrypt`, and doesn't encrypt if there's neither.
  When `lim update-manifest --pack packs/<id>` exports a project's pack on the spot, it also encrypts it with the desktop key if `build.encrypt` is set
- There's one key per project, and exports for every OS use the same key. `.liminalia/` is kept out of version control (by the template's `.gitignore`).
  If you lose the key, you can no longer use `lim pack` to make packs that fit the game you've already distributed (`lim patch` still can, because it uses the key inside the previous export). Back up the key like your other secrets
- Anyone can read the browser key from the published page. It's a separate key so that the desktop key can't be read
- The browser version needs a Service Worker for this, so it can only be played on https pages (itch.io and so on) or at `http://localhost` (it can't be opened from file://).
  When Service Workers can't be used, the page shows why. Range requests for audio and video are answered with slices of the decrypted content
- The mobile versions (Android, iOS) aren't encrypted

Limits: the key is inside the distributed game (game.json in the desktop version, lm-sw.js in the browser version). This keeps assets from being seen just by opening the folder,
or from being read directly by other tools, but anyone who takes the trouble to investigate the game can break it. It's no substitute for DRM or copyright protection.

### Playing the browser version offline

So that it can be played offline after being opened once, the browser version caches the engine, scenarios and data with a Service Worker (`lm-sw.js`, the same file as for encryption)
(`build.browser.offline`, default true). Assets are cached when they're used. With `"all"`, all the assets are also cached when the game is opened (mind the download size for large games).
Web fonts loaded by plugins and themes (the `.woff2` `.woff` `.ttf` `.otf` files exported with the engine; they're split into files by the characters they cover, over a thousand in a large game) aren't fetched when the game is opened; they're cached when they're used (fonts in the asset folders are handled like other assets).
With `false`, no Service Worker is registered.
- Unencrypted exports register the Service Worker after the page has loaded (so they can still be played as before from `file://` and non-https locations, where it can't be registered. On localhost, it is registered).
  Encrypted exports register the Service Worker before loading the engine, as before, keep encrypted files encrypted in the cache, and decrypt them when serving them
- The page is fetched from the network first, and the cache is used if there's no response within 3 seconds. Files whose names include a hash of their content (`engine/` and assets with `?v=`) and `project/` (scenarios, data)
  are served from the cache first (the cache is per export, so the engine and the scenarios always come from the same export)
- When you put up a new export while someone is playing, the new Service Worker is installed and waits, and the page being played keeps going with the previous export's engine and scenarios.
  The player sees "A new version is available. Reload to update" and "Reload" at the top of the screen; pressing it autosaves, switches to the new export and reloads
  (closing and opening the game again also switches. The old cache for the same game is deleted when the switch happens). Whether there's a new export is decided by the export time in `project/build.json`,
  checked 30 seconds after starting, when the player comes back to the tab, and every 10 minutes. Exports that don't use a Service Worker (`offline: false` and not encrypted) and exports that are only encrypted
  just show the notice and reload, and until they reload, the scenarios they read come from the new export
- Range requests for audio and video (streaming long BGM) are answered with slices of the cached file. Range requests for assets that aren't cached are fetched from the network as they are, and the whole file is cached in the background
- It isn't included in the export that `lim patch` makes for the comparison

## Updates (desktop versions sold outside Steam)

Steam delivers updates itself, but when you sell on your own site, on BOOTH or elsewhere, the game checks for new versions on its own.

1. Make the files to distribute and the manifest
   ```bash
   lim update-manifest --base-url https://example.com/game/updates/ --pack packs/patch1 --notes-file notes.json
   lim update-manifest --base-url https://example.com/game/updates/ --app windows=dist/windows/…/Game_1.1.0_Setup.exe,mac=dist/Game-mac.zip --page https://example.com/game
   ```
   This creates `update.json` and the files to distribute (packs as `<id>-<version>.zip`, and copies of the game files) in `dist/update/`. Put its contents at the `--base-url` location
2. Write `"build": { "update": { "url": "https://example.com/game/updates/update.json" } }` in `liminalia.json` and export
   (the environment variable `LIMINALIA_UPDATE_URL` takes precedence; `off` leaves it out)

For how the game behaves (how it asks the player and what it shows), see [Updates in player.md](player.md).

- Packs (`--pack`): a project's `packs/<id>/` (exported the same way as `lim pack` first), a folder exported with `lim pack`, or its zip. Whether a pack is newer is decided by `version` in `pack.json`,
  so `version` is required. `requires` (which version of the game it goes into) is `requires` in `pack.json`, or the current `version` if there's none
- The game itself (`--app`): an installer or zip for each OS (`windows`, `mac`, `linux`) (the Mac zip and dmg can be made as described in "Packaging" above). `--page` is the download page (opened when there's no file for the OS).
  The version is `version` in `liminalia.json` (`--version` overrides it)
- Release notes go in `--notes "…"` or `--notes-file` (text, or JSON such as `{"ja": "…", "en": "…"}`; the one in the player's language is shown)
- If `dist/update/update.json` already exists, packs for other game versions that weren't made this time are kept (so you can still deliver fixes to players of older versions). `--fresh` doesn't keep them
- It isn't included in the Steam-connected version (it is with `build.update.steam: true`). The automatic check after export doesn't test it

The manifest looks like this:

```json
{
  "format": "liminalia-update", "formatVersion": 1,
  "app": { "version": "1.1.0", "page": "https://example.com/game", "notes": { "ja": "…", "en": "…" },
           "files": { "windows": { "url": "Game_1.1.0_Setup.exe", "sha256": "…", "size": 123 } } },
  "packs": [ { "id": "patch1", "version": "1.0.1", "requires": "1.0.0", "title": "Fix 1", "url": "patch1-1.0.1.zip", "sha256": "…", "size": 456 } ]
}
```

- URLs can be relative to the manifest. Only https is allowed (`http://localhost` is accepted for local testing). `sha256` is required, and a download that doesn't match isn't used
- Packs are installed in `packs/<id>/` in the save location (because the inside of a Mac app and Program Files can't be modified, due to signatures and permissions). A pack is extracted under a different name and then swapped in,
  so if the process stops partway, the previous one remains. Inside the zip, `pack.json` must be at the top level or inside a single folder, and its `id` must match the manifest
- To update the game itself on Windows, a `.exe` or `.msi` is downloaded and launched, and the game quits (the installer removes the previous version and installs the new one)
- On Mac with a `.zip` (made with `build.mac.zip` or `lim build mac --zip`) and on Linux with a `.tar.gz` (made by `lim build linux`), the game replaces itself
  (`packages/desktop/app-swap.cjs`; the same flow as Studio's updates)
  1. It downloads the file, checks `sha256`, and extracts it into `.<name>.update/` next to the app (on Linux, next to the game folder)
  2. It checks that it's the same game at the expected version (on Mac, `CFBundleIdentifier` and `CFBundleShortVersionString` and `codesign --verify --deep --strict`,
     and if the current app has a Developer ID signature, only a signature from the same Team is accepted. On Linux, the executable's name, and the name and version in `package.json` inside `resources/app.asar`)
  3. The game quits (after the autosave and saving it does before closing), and a small sh script swaps the app and launches it again. The script doesn't delete the previous version; it waits up to 120 seconds for a marker showing that the new version started.
     If the marker appears, it deletes the previous version. If not, it stops the new version, goes back to the previous version and launches it (the script's log is in `liminalia-update-<id>/` in the temporary folder).
     The new version places the marker once the title screen (or the game, for a project without one) appears, so a version that starts but never shows the game is rolled back too
  4. On Linux, the whole folder is replaced, so things that exist only in the old folder (the save data `savedata` next to the executable when `saves.location` is `"portable"`, `resources/packs` the player added, and so on)
     are moved to the new folder (and moved back when reverting to the previous version). The new version is launched with the same arguments as the current game (such as `--no-sandbox` on systems where the sandbox can't be used).
     On Mac, the save data next to the app (`<title> savedata`) is outside the app, so it isn't touched
- When the app can't be replaced (it's in a location that can't be written to, Gatekeeper is running it from a moved location, or the file isn't a `.zip` on a Mac (such as a `.dmg`) or a `.tar.gz` or `.tgz` on Linux), the downloaded file is opened as before.
  If there's no file and only a page, the download page is opened

### Signing the manifest (Ed25519)

So that a fake manifest can't make the game install other files even if the update server (or something along the way) is taken over, you can sign the manifest and put the public key in the game.

1. Make a key pair (only once)
   ```bash
   lim update-key            # creates the private key at ~/.liminalia/update-keys/<project id>.pem and prints the public key (--out changes the location)
   ```
2. Write the printed public key in `liminalia.json` and export. A game with the public key only uses manifests whose signatures verify
   ```json
   "build": { "update": { "url": "https://example.com/game/updates/update.json", "publicKey": "the public key printed by lim update-key (32 bytes in base64)" } }
   ```
3. Pass the private key when you make the manifest (`--sign-key` or the environment variable `LIMINALIA_UPDATE_SIGN_KEY`)
   ```bash
   lim update-manifest --base-url https://example.com/game/updates/ --pack packs/patch1 --sign-key ~/.liminalia/update-keys/my_game.pem
   ```

- The signature is `"signature": { "alg": "ed25519", "value": "…" }` in the manifest. What's signed is the manifest without `signature`, as JSON with its keys sorted by name
  (`canonicalJson` in `packages/desktop/update.cjs`). Changing whitespace or order still verifies, but changing even one value doesn't
- If `build.update.publicKey` is set but no private key is passed, or the private key doesn't pair with that public key, `lim update-manifest` stops
- Keep the private key out of the project folder and version control (`lim update-key` makes it a file that only you can read). To sign in CI, store the private key as a CI secret,
  write it to a file, and pass that to `LIMINALIA_UPDATE_SIGN_KEY`
- To change keys, distribute a version that lists both the old and new public keys in an array (`"publicKey": ["old", "new"]`) through a manifest signed with the old key, and once it has reached players, sign with the new key.
  If you lose the private key, games with its public key can't be made to accept new manifests (players will have to reinstall the game by hand)
- Packs and game files are still checked with `sha256` as before (there's only one signature, on the manifest)

## Distributing the authoring app (Liminalia Studio)

Everything up to here is about exported games. Studio (`packages/studio-desktop`) uses the same signing module (`packages/cli/src/sign`) and the same update format (`liminalia-update`,
`packages/desktop/update.cjs`). The settings are passed not in `liminalia.json` but as environment variables to `npm run studio:package`. If something is missing
or a value can't be used, it stops before building. If nothing is passed, it works as before (ad hoc signing on Mac, no signing on Windows, and no update checks).

### Signing and notarization

| Environment variable | Meaning |
|---|---|
| `LIMINALIA_MAC_SIGN_IDENTITY` | The name or SHA-1 of the Developer ID certificate. Stops if it isn't in the keychain. `-` or empty means ad hoc signing |
| `LIMINALIA_NOTARY_PROFILE` and others | Notarization credentials (the same as in "Mac (Developer ID and notarization)" above: `LIMINALIA_NOTARY_KEY` `_KEY_ID` `_ISSUER`, `LIMINALIA_NOTARY_APPLE_ID` `_PASSWORD` `_TEAM_ID`). Without them, the app is only signed |
| `LIMINALIA_NOTARIZE=0` | Don't notarize even if credentials are available |
| `LIMINALIA_WIN_PFX`, `LIMINALIA_WIN_PFX_PASSWORD` | The Windows PFX (signed with `osslsigncode` on Mac and with `signtool` on Windows) |
| `LIMINALIA_WIN_SIGN_COMMAND` | An external signing command for Windows (`{file}` is replaced with `Liminalia Studio.exe`) |

```bash
LIMINALIA_MAC_SIGN_IDENTITY="Developer ID Application: Example Inc. (ABCDE12345)" LIMINALIA_NOTARY_PROFILE=liminalia-notary \
  npm run studio:package -- mac
```

- On Mac, `@electron/osx-sign` signs from the inside out with the hardened runtime, entitlements and a timestamp. Studio contains many images and fonts,
  so only the executables and native libraries (Mach-O) are signed. Since the app loads the code of project plugins, library validation is turned off in the entitlements
- After notarization passes, the app is stapled, and then the zip and dmg are made (the dmg itself isn't signed; the app inside is stapled). If notarization fails, it stops
- For a notarized app, `liminaliaStudio.notarized` is embedded in `package.json`. The help in a notarized app doesn't show "Opening it for the first time on a Mac".
  On Windows, a signed app (`codeSigned`) doesn't show "Opening it for the first time on Windows"
- On Windows, only `Liminalia Studio.exe` is signed (`esbuild.exe` and the others inside are only run as child processes, so they aren't signed)

### Windows installer

`npm run studio:package -- windows` makes `Liminalia-Studio-<version>-windows-x64-Setup.exe` in addition to the folder and zip (with the same NSIS module as game exports,
`packages/cli/src/installer/nsis.ts`. If makensis is missing, the installer isn't made and the output shows how to install makensis. `LIMINALIA_INSTALLER=0` skips it).

- It installs for the current user only (`%LOCALAPPDATA%\Programs\Liminalia Studio`; no administrator rights are needed, and the app's updater can replace the app itself). The screens are in Japanese and English.
  It creates Start menu and desktop shortcuts and an uninstall entry in Apps & features (key `LiminaliaStudio`). If signing is set up, the installer is signed too
- App updates replace the whole folder, so the swap script (`WINDOWS_SWAP_SCRIPT` in `app-update.ts`) copies `Uninstall.exe` into the new version.
  Uninstalling deletes the installed files plus the items of Electron and the app (`resources`, `locales` and so on, with their contents) (nothing outside the install folder is touched)
- It can be built on a Mac too (`brew install makensis`). makensis on Mac and Linux can't read scripts containing Japanese unless the locale is UTF-8,
  so it's run with `LC_ALL` set to UTF-8 (game exports do the same)
- `.github/workflows/studio-windows.yml` checks on `windows-latest` that the app launches and that silent install and uninstall (`/S`) work, and keeps `Setup.exe` as an artifact (studio-windows-setup, for 7 days)
  (on pushes to main and PRs that change `packages/studio-desktop`, the installer build, or the dependencies, once a week, and manually).
  To build it by hand, run `npm ci` and then `npm run studio:package -- windows` on Windows (get NSIS from https://nsis.sourceforge.io/Download or with `choco install nsis`)

### App updates

Shortly after launch, and from "Check for Updates…" in the menu (the app menu on Mac, Help on Windows), Studio reads `update.json` from the update server. If there's a new version, a small window
shows the version and what changed, and if the user chooses to update, the update proceeds in this order.

1. Download the zip to `userData/updates/` and check its SHA-256 and size (if they don't match, discard it and stop)
2. Extract it into `.liminalia-studio-update/` next to the app, and check that it's the same app at the expected version. On Mac, it must also pass `codesign --verify --deep --strict`,
   and if the current app has a Developer ID signature, only a signature from the same Team is accepted
3. Close the project windows the usual way (finishing any pending saves. If the user cancels closing, the update is canceled too)
4. Run a small swap script (`sh` on Mac, PowerShell on Windows; `userData/updates/swap.*`, logged to `swap.log`) detached, and quit the app.
   The script waits for the app to exit, moves the old app aside, puts the new app in place and launches it. If something fails along the way, it gives the old app back its original name and launches it
5. The script doesn't delete the old app; it waits up to 60 seconds for a marker showing that the new app started (`userData/updates/started`). If it appears, the old app is deleted. If not, the script stops the new app, goes back to the old one and opens it
6. The launched app checks the result of the previous swap and cleans up (if it's the new version, it creates the marker). If the swap failed or the previous version was restored, it tells the user that this is the previous version and where the downloaded file is

`electron-updater` and Squirrel aren't used (so that updates work even for apps without signing or notarization). When the app is in a place that can't be written to (a read-only volume, when Gatekeeper
is running it from a moved location, Program Files and so on), it isn't replaced, and the download location is shown instead. On Windows, the whole folder of the exe is replaced, so if there's even one item directly inside it
that isn't recognizably the app's (one that's neither among Electron's items nor in the list of top-level items in the new zip), the app again isn't replaced, and the reason and the download location are shown.
Updates don't start during an export. If an export starts after the download, the update stops before the project is closed and the user is told (the downloaded file is used next time).

#### Making the update files

The repository is private and GitHub Releases can't be downloaded anonymously, so the update URL is embedded at packaging time. Without it, Studio doesn't check for updates, and the menu has no item for it.
When building in CI, putting it in the variable `LIMINALIA_STUDIO_UPDATE_URL` embeds it ("Release CI" below).

```bash
# 1. Package with the update URL embedded (an environment variable, or "liminaliaStudio": { "updateUrl": "…" } in packages/studio-desktop/package.json; the environment variable comes first)
LIMINALIA_STUDIO_UPDATE_URL=https://example.com/studio/update.json npm run studio:package -- all

# 2. Prepare update.json and the zips in out/<version>/update/ (--notes or --notes-file: a string, or JSON such as { "ja": "…", "en": "…" })
npm run studio:update-manifest -- --notes-file notes.json

# 3. Put the contents of out/<version>/update/ on the update server
```

- The format is `liminalia-update`, the same as in "Updates" above. Mac builds are distributed per CPU, so `app.files` gets the extra keys `mac-arm64` and `mac-x64`
  (`mac` if built with `--universal`). Windows is `windows`. Studio looks for the CPU key first and uses the OS key if there's none. Games don't pass the CPU, so they read `mac` as before
- Zip URLs are written relative to the location of `update.json` (`studio:update-manifest` does this. Absolute URLs are checked the same way)
- Only https is used. For testing, http is allowed only for `http://127.0.0.1` (stricter than games; `localhost` isn't accepted either). Redirects aren't followed automatically, and the same restrictions apply to each hop (up to 5)
- Signing the manifest works the same way as for games ("Signing the manifest" above). Make a key pair with `lim update-key --out <file>` (pass a project folder),
  and run `studio:package` with `LIMINALIA_STUDIO_UPDATE_PUBLIC_KEY=<public key>`; the app then only uses an `update.json` whose signature verifies.
  `studio:update-manifest` signs with `LIMINALIA_STUDIO_UPDATE_SIGN_KEY=<private key .pem>` (and `LIMINALIA_STUDIO_UPDATE_PUBLIC_KEY` to check that the keys pair)
- If `app.files` has no file for this OS and there's an `app.page`, the update window only opens the download page

To test with real packaged apps, run `npx tsx packages/studio-desktop/scripts/update-check.ts [--shots folder] [--keep]` (Mac only).
It makes an app with a lower version and one with a higher version in `out/`, serves them on 127.0.0.1, and goes through the redirect limits, a hash mismatch, a read-only volume, an export in progress, canceling the close, swapping and relaunching, and going back from a version that crashes on launch to the previous one.

### Release CI

When a `v1.2.3` tag is pushed (and when it's run by hand), `.github/workflows/release.yml` builds and signs the authoring app's Mac version (zips and dmgs for Apple Silicon and Intel) and
Windows version (a zip and the installer), makes the update manifest (`update.json`) if the update URL has been decided, builds and checks the npm package (the npm package section of the README;
`lim` installed into an empty folder runs `new`, `check`, `test`, `build browser` and `dev`), and puts them in a draft GitHub Release. Check the draft, then publish it by hand.
The tarballs of the two packages that go to npm (`@liminalia/sdk`, the plugin contract, and `@liminalia/cli`, which provides `lim`) are also put in the distribution repository's Release.
They're published to npm from the public repository (`skyt-a/liminalia-sdk`; see "Publishing to npm" below).

All jobs run on the development Mac's self-hosted runner (label `liminalia-mac`, Apple Silicon, installed in `~/actions-runner-liminalia` as a service that starts at login),
and use neither GitHub's runner minutes nor its artifact storage. Files are passed between jobs in `~/liminalia-release-stage/<run_id>` on that Mac (removed after 14 days).
The Windows version is built from the Mac, so launching on Windows isn't checked (check it with `studio-windows.yml` or on a real machine). Keep that Mac awake when pushing a tag.

1. Set the version with `npm run engine-version -- set <version>` and commit (the root `package.json` is the source, and the authoring app, `lim --version` and the site's download page show this version too.
   If it differs from the tag's version, CI stops. [versioning.md](versioning.md))
2. Create an annotated tag (`git tag -a v1.2.3 -m "What changed"`; the annotation becomes "What's new" in the update window) and push it
3. Check the draft Release and publish it. Publishing it makes `publish-vscode.yml` publish the VS Code extension ("Publishing to the Marketplace and Open VSX" in [vscode.md](vscode.md))
4. Publish to npm ("Publishing to npm" below)
5. Put the update on the update server (run `deploy-studio-update.yml` with the version)

#### Publishing to npm

`.github/workflows/publish-npm.yml` in the public repository `skyt-a/liminalia-sdk` (the source is `scripts/public/publish-npm.yml`, copied by `scripts/public-mirror.mjs`)
publishes to npm with OIDC (trusted publishing). No npm token is used.

- It builds from that repository's source (`node scripts/npm-pack-public.mjs`) and checks that the unpacked contents are the same as the tarballs that `release.yml` built, checked and put
  in the distribution repository before publishing (if anything differs, nothing is published). It adds a provenance statement
- It stages the packages with `npm stage publish`. Review them under Staged Packages on npmjs.com and approve them with 2FA to publish them. sdk and cli have the same version, so approve both together
- A version with `-` (`1.2.3-beta.1`) gets the `next` dist-tag. Versions that are already on npm are skipped

Steps (after publishing the draft Release):

1. Copy into a checkout of the public repository: `node scripts/public-mirror.mjs --repo <checkout> --check` (it also checks, in the copy, that the npm tarballs are the same as the ones built from the source repository)
2. Push the copied commit, then create an annotated tag `v<version>` and push it. Pushing the tag runs `publish-npm.yml` (when running it by hand, enter the version)
3. Check the two packages under Staged Packages on npmjs.com and approve them

In each npm package's settings (Settings → Trusted publishing), set GitHub Actions, `skyt-a`, `liminalia-sdk` and `publish-npm.yml`.
If nothing is published within 2 days of setting it, the setting expires (an npm rule). A package that doesn't exist yet has no settings page, so for a package published for the first time,
stage an earlier version with `npm stage publish` from your own machine to create the package (a placeholder version `0.0.0-stage`), and set it while that version is still staged.
Reject the version you staged by hand only after approving the version that CI published (rejecting it while there's no other version removes the package along with the placeholder; checked on 2026-11-22).
Trusted publishing can't be used from self-hosted runners, so this workflow runs on GitHub's runners (it's a public repository, so it doesn't use the minutes).

Keys come from Secrets (Settings → Secrets and variables → Actions). If one is missing, that signing is skipped and the build continues, and what was skipped is shown in the job summary and annotations.
Incomplete combinations (a certificate without its password, only the notarization key, and so on) stop at that step (`scripts/release.mjs`).

For the first release, enroll in the Apple Developer Program and obtain a Developer ID Application certificate and notarization credentials. Until then, use a manual build with draft creation unchecked. Tags and draft releases require Mac signing and notarization. For unsigned Windows builds leave the Windows certificate, password and `LIMINALIA_RELEASE_REQUIRE_SIGNING` unset. Windows may display a SmartScreen warning. Configuring an update URL for distribution also requires the Ed25519 signing key pair.

| Secret | Contents | If missing |
|---|---|---|
| `LIMINALIA_MAC_CERT_P12`, `LIMINALIA_MAC_CERT_PASSWORD` | The .p12 exported from the Developer ID Application certificate and its private key, in base64 (`base64 -i cert.p12`), and its password. They're imported into a temporary keychain in CI, which is deleted afterward | Ad hoc signing |
| `LIMINALIA_NOTARY_KEY_P8`, `LIMINALIA_NOTARY_KEY_ID`, `LIMINALIA_NOTARY_ISSUER` | The App Store Connect API key used for notarization (the contents of the .p8), the key ID and the Issuer ID | Signed only (not notarized) |
| `LIMINALIA_WIN_PFX_BASE64`, `LIMINALIA_WIN_PFX_PASSWORD` | The Windows code signing certificate (the .pfx in base64) and its password. `signtool` signs `Liminalia Studio.exe` and the installer | Not signed |
| `LIMINALIA_STUDIO_UPDATE_SIGN_KEY_PEM` | The private key for signing the update manifest (the contents of the .pem made with `lim update-key`). Used together with the variable `LIMINALIA_STUDIO_UPDATE_PUBLIC_KEY` | The manifest isn't signed (if only the public key variable is set, it stops) |
| `LIMINALIA_STUDIO_UPDATE_DEPLOY_TOKEN` | The key used by the command that puts the update on the update server (`deploy-studio-update.yml`) | The command runs without a key |

| Variable | Contents |
|---|---|
| `LIMINALIA_STUDIO_UPDATE_URL` | Where the authoring app's updates are hosted (the https URL of `update.json`). It's embedded in the app that's built. Without it, the app doesn't check for updates, and `update.json` isn't made |
| `LIMINALIA_STUDIO_UPDATE_PUBLIC_KEY` | The public key that verifies the update manifest's signature (embedded in the app) |
| `LIMINALIA_MAC_SIGN_IDENTITY` | The name or SHA-1 of the certificate used for signing (without it, the Developer ID Application certificate that was imported is used) |
| `LIMINALIA_RELEASE_REQUIRE_SIGNING` | If `true`, stops when the credentials for Mac signing and notarization or for Windows signing are missing. Set it once you have the keys, so that no unsigned release goes out |
| `LIMINALIA_STUDIO_UPDATE_DEPLOY_COMMAND` | The command (bash) that puts the update on the update server. `$LIMINALIA_STUDIO_UPDATE_DIR` contains `update.json` and the zips |

Where updates are hosted is for a person to decide. Once it's decided, set `LIMINALIA_STUDIO_UPDATE_URL` and put the files there in one of these ways.

- GitHub Releases: they can be downloaded anonymously only if the repository is public. If you set `https://github.com/<repository>/releases/latest/download/update.json`,
  the files are in place as soon as the Release is published (zip URLs are relative to `update.json`, so they point to the zips in the same Release. Up to 5 redirects are followed)
- Another host (Cloudflare R2 and so on): write the command that puts the files there in `LIMINALIA_STUDIO_UPDATE_DEPLOY_COMMAND`. For example (R2; the key is an API token that can write to Workers R2):
  ```bash
  for f in "$LIMINALIA_STUDIO_UPDATE_DIR"/*; do CLOUDFLARE_API_TOKEN="$LIMINALIA_STUDIO_UPDATE_DEPLOY_TOKEN" npx wrangler r2 object put "<bucket>/studio/$(basename "$f")" --file "$f" --remote; done
  ```

Not yet verified: signing and notarization in CI with real certificates (including importing into the temporary keychain), signing with `signtool`, publishing to npm (`publish-npm.yml` in the public repository), and `deploy-studio-update.yml`.
Skipping and stopping when keys are missing, and the version check, are tested by `scripts/test/release.test.mjs`, the npm package by `node scripts/npm-pack.mjs --verify`,
and the npm publishing order, skipping versions that are already there and comparing contents by `scripts/test/npm-publish.test.mjs` and `node scripts/npm-publish.mjs <tarball folder> --version <version> --dry-run`.

### Where problem reports are received

"Help → Report a Problem…" in the authoring app puts what happened, the app version and OS, an excerpt of the frontmost project's settings, and the end of the log into one report,
and before anything is sent, it shows the contents and lets the user choose what to include (the home folder is shown as `~`). Once you've decided where to receive reports (GitHub Issues or Discussions, a form and so on),
write its https URL in `LIMINALIA_STUDIO_REPORT_URL` (or `"liminaliaStudio": { "reportUrl": "…" }` in `packages/studio-desktop/package.json`) when packaging.
`{title}` and `{body}` in the URL are replaced with the title and the contents (Markdown).

```bash
LIMINALIA_STUDIO_REPORT_URL='https://github.com/<owner>/<repository>/issues/new?title={title}&body={body}' npm run studio:package
```

When the contents are too long for the URL (about 6,000 characters), or the URL has no `{body}`, the contents are copied to the clipboard before the page opens, and the user pastes them in.
Without a place to receive reports, "Open the report page" isn't shown, and users pass reports on by copying them or saving them to a file (`.md`).

### What hasn't been verified

Signing and notarization with a real Developer ID certificate, updating a notarized app (including how macOS's App Management treats it in `/Applications`), and swapping on a real Windows machine
can't be verified on the development Mac. Launching on Windows and the swap script (PowerShell) are run on `windows-latest` by `.github/workflows/studio-windows.yml` (once a week when files the app depends on have changed, and manually). Game exports (Mac, Windows, Linux, and Android) and launching the Mac build are checked by running `.github/workflows/platform-builds.yml` manually.

## Patches (differences from a previous export)

`lim patch [project] --base <previous export>` (and "Make a patch…" on Studio's export screen, which does the same) compares something you exported before
(a browser version, a desktop version's folder, a Mac app, or a zip of one of these) with the current project, and makes a pack (a patch) containing only what changed.

- What's compared is the export's content (scenarios, data, characters, translations, assets). The current project is exported as a browser version to a working location for the comparison.
  Packs can also replace characters (cast.json) and translations (lang/)
- If the game itself (the player program, and settings such as ui, extra and items in liminalia.json) has changed, it stops. When you've updated the engine or changed
  settings, distribute the full game again. With `--force` (on the export screen, press the button again), the patch is made from the content only
- The version (`version`) isn't embedded in the program but stored in the export's `project/build.json`, so you can make a patch even after raising the version.
  The pack's `requires` is the previous export's version (so it only goes into that version of the game), and `order` is the time it was made (patches made later take precedence)
- Files you deleted can't be deleted by a patch (they stay in the game; they're listed)
- If the previous export encrypted its content (`build.encrypt`, `build.browser.encrypt`), it's decrypted with the key inside that export (game.json in the app, `lm-sw.js` in the browser version) for the comparison, and the patch is encrypted with the same key
- The zip that's made matches the previous export (a Windows one for the Windows version, a browser one for the browser version; for the Mac version, only the pack folder)
- If the previous export is a test build (`lim build --feedback`), it stops. Add `--allow-test` to make a patch for the test build

What's made in `dist/patches/`:

| Item | How to distribute it |
|---|---|
| `<id>/` | Distribute it through the desktop version's update check with `lim update-manifest --pack dist/patches/<id>` (use this for Mac, because changing the inside of the app breaks its signature) |
| `<id>-windows.zip`, `<id>-linux.zip` (when the previous export was the Windows or Linux version) | Extract it over the game folder (it goes into `resources/packs/<id>/`) |
| `<id>-browser.zip` (when the previous export was the browser version) | Extract it over the place where the browser version is hosted (`packs/<id>/`, and `packs/index.json` with the pack added) |

## Publishing to stores

### Google Play (Android App Bundle)

Google Play accepts Android App Bundles (.aab), not APKs. `lim build android --aab` (or `build.androidAab: true`, or the environment variable `LIMINALIA_AAB`) also makes
`<name>_<datetime>.aab` next to the APK.

```bash
brew install bundletool          # only once (for other OSes, see "Where bundletool is found" below)
LIMINALIA_ANDROID_STORE_PASSWORD=… lim build android --aab
```

```json
"build": { "bundleId": "com.example.game", "android": { "keystore": "/safe/place/upload.jks", "alias": "upload", "storePasswordEnv": "LIMINALIA_ANDROID_STORE_PASSWORD" } }
```

- targetSdk is `build.android.targetSdk` (the default is 36, the minimum Google Play currently requires: from August 31, 2026, new apps and updates must target Android 16 = API 36 or higher).
  Building needs the SDK Platform of that version (from the SDK Manager in Android Studio, or `sdkmanager "platforms;android-36"`. Without it, the export stops, and `lim doctor` tells you too).
  If you only want to try it on your own device, setting `build.android.targetSdk` to a version you have installed lets you export the APK (with a warning), but `--aab` with a targetSdk below the minimum stops
- Gradle isn't used. The same content as the APK has its resources linked again with `aapt2 link --proto-format`, is laid out in bundletool's module form (`manifest/`, `dex/`, `res/`, `assets/`, `resources.pb`),
  is built with `bundletool build-bundle`, signed with `jarsigner`, and checked with `bundletool validate`
- The signing key is `build.android`, the same as for the APK. On Google Play, this becomes the upload key for Play App Signing (Google signs the APKs it delivers).
  Create the key with `keytool -genkeypair -v -keystore upload.jks -alias upload -keyalg RSA -keysize 2048 -validity 10000` and store it outside the project folder.
  Without `build.android`, the bundle is signed with a development key (it can't be uploaded to Play, and you're told so)
- The build number is `build.buildNumber` (raise it every time you upload to Play. The environment variable `LIMINALIA_BUILD_NUMBER` takes precedence, for example to pass a CI run number).
  If it's left out, it's derived from `version` (1.2.3 → 10203). This would give a version whose second or third part is 100 or more (1.0.100 and so on) the same number as another version,
  so in that case the export stops (set the number)
- Where bundletool is found: the environment variable `LIMINALIA_BUNDLETOOL` (`bundletool-all-<version>.jar` or a command) → `bundletool` on the PATH → `~/.liminalia/tools/bundletool*.jar`.
  Download the jar from https://github.com/google/bundletool/releases. If it isn't found, the export stops before building and shows how to install it
- Uploading to the Play Console is done by hand (create the app and upload the .aab to the internal testing track). To check it locally before uploading, use
  `bundletool build-apks --bundle=….aab --output=….apks --local-testing` and `bundletool install-apks --apks=….apks`

### App Store (Archive and export)

```bash
lim build ios --archive                        # makes an Archive and exports it to an .ipa for the App Store (--export app-store is the default)
lim build ios --archive --export ad-hoc        # distributes to registered devices (when you don't use TestFlight). development is for development
LIMINALIA_ASC_KEY=~/keys/AuthKey_XXXX.p8 LIMINALIA_ASC_KEY_ID=XXXX LIMINALIA_ASC_ISSUER=… \
  lim build ios --archive --upload             # uploads to App Store Connect instead of exporting (it appears in TestFlight)
```

The Xcode project, `App.xcarchive` and `export/App.ipa` (and `export/ExportOptions.plist`) are created in `<out>/ios/<name>_<datetime>/`.

- `xcodebuild archive` (`-scheme App -destination generic/platform=iOS`, automatic signing with your team, `-allowProvisioningUpdates`) and `xcodebuild -exportArchive`
- The team is `build.ios.team` → `LIMINALIA_IOS_TEAM` → the team of the "Apple Development" certificate in your keychain (the same as when installing on a device).
  App Store and ad-hoc exports need a team enrolled in the Apple Developer Program (paid) (a free personal team can only do development; the export says so and stops)
- Xcode creates the certificates and distribution signing settings (provisioning) with the account you added in Xcode's Settings → Accounts. Where no account is added, such as in CI,
  have them created with an App Store Connect API key (the environment variables above. Create the key in App Store Connect under Users and Access → Integrations → App Store Connect API.
  If the notarization variables `LIMINALIA_NOTARY_KEY`, `_KEY_ID` and `_ISSUER` are set, the same key is used)
- The method in ExportOptions.plist uses the names from Xcode 15.3 on (`app-store-connect`, `release-testing`, `debugging`) (the older names for earlier versions of Xcode)
- To upload without `--upload`: add `App.ipa` to Transporter (Apple's app on the Mac App Store). After uploading, entering the app information
  and screenshots and submitting for review in App Store Connect are done by hand
- The version is `version` (`CFBundleShortVersionString`) and `build.buildNumber` (`CFBundleVersion`; raise it every time you upload.
  The environment variable `LIMINALIA_BUILD_NUMBER` takes precedence. If it's left out, it's made the same way as for Google Play)

### Steam (SteamPipe)

```json
"build": { "steam": { "appId": 1234560, "depots": { "windows": 1234561, "mac": 1234562, "linux": 1234563 } } }
```

```bash
lim build mac,windows,linux                     # exports the Steam-connected versions (if build.steam is set)
lim publish steam --dry-run                     # only makes the VDF files and prints the commands it would run
lim publish steam --login my_steam_builder      # uploads with steamcmd (steamcmd asks for the password and Steam Guard)
lim publish steam --login my_steam_builder --branch beta --desc "1.2.0 playtest"   # sets the build live on the beta branch after uploading
```

- Create a depot for each OS under SteamPipe → Depots in Steamworks, and write their IDs in `build.steam.depots` (only the OSes listed there are uploaded).
  To upload to the App ID of an edition such as a demo, use `--app-id` and `--depot windows=…,mac=…` (and pass what you exported with `lim build --steam demo` with `--build`)
- If you leave it out, what's uploaded is the newest export in `<out>/<OS>/` (the game folder for Windows and Linux, and the folder containing the app for Mac). You can choose with `--build windows=folder,…`.
  It looks at `game.json` in the export and stops if the export isn't connected to Steam or is for another App ID. It also stops for a test build (`lim build --feedback`; add `--allow-test` to upload it)
- It creates `app_build_<App ID>.vdf` and `depot_build_<depot ID>.vdf` in `<out>/steam/` and runs `steamcmd +login <name> +run_app_build <VDF> +quit`.
  The depots don't include the export check's screenshot (`verify-title.png`) or the packaged zip, dmg and tar.gz files. Logs go to `<out>/steam/output/`
- Without `--branch`, the build isn't set live (set it live on a branch under SteamPipe → Builds in Steamworks). The `default` branch can't be set live from steamcmd, so that stops with an error.
  `--preview` doesn't upload; it only lists what would be uploaded (SteamPipe's Preview)
- You log in yourself. lim doesn't take passwords (`--login` or the environment variable `LIMINALIA_STEAM_LOGIN` is just the account name). It's best to create an account just for uploading builds,
  and give it only permission to edit the app's builds. Once you've logged in, steamcmd may not ask again next time, using the credentials it saved
- steamcmd is `tools/ContentBuilder/builder_osx/steamcmd.sh` in the Steamworks SDK (`builder_linux` on Linux, `builder/steamcmd.exe` on Windows), or
  the steamcmd that Valve distributes. It's looked for in the environment variable `LIMINALIA_STEAMCMD` → `steamcmd` or `steamcmd.sh` on the PATH → `~/Steam/steamcmd.sh` and so on

### itch.io (butler)

```json
"build": { "itch": { "target": "my-name/my-game", "channels": { "browser": "html5" } } }
```

```bash
lim build browser,windows,mac,linux --steam off   # export versions not connected to Steam
lim publish itch --dry-run                         # only show what would be uploaded and the butler commands
lim publish itch                                   # upload everything that has been exported
lim publish itch browser,windows --userversion 1.0.1
```

- `build.itch.target` is the "user/game" part of the game page's URL on itch.io (`https://my-name.itch.io/my-game`). You can also give it with `--target`
- By default, the channels are `html5` for the browser version, `windows` for Windows, `mac` for Mac and `linux` for Linux (itch.io decides the OS from the channel name).
  Change them with `build.itch.channels` or `--channel windows=win-beta`. The version is `version` (change it with `--userversion` or the environment variable `LIMINALIA_VERSION`)
- If you don't choose what to upload, it's `<out>/browser/<id>` for the browser version and the latest export in `<out>/<target>/` for the others. Choose with `--build browser=folder,…`.
  The export check's screenshot and the packaged zip, dmg and tar.gz files aren't uploaded (`butler push --ignore`). Builds connected to Steam and test builds (`lim build --feedback`) stop with an error
  (add `--allow-test` to upload a test build)
- Install butler from https://itchio.itch.io/butler, put it on the PATH, and log in with `butler login` (you can also give its location in the environment variable `LIMINALIA_BUTLER`).
  In CI, put the API key in the environment variable `BUTLER_API_KEY`. lim doesn't take keys. Without butler, it shows how to install it and stops
- For the browser version, after the first upload choose "This file will be played in the browser" on the game's edit page and enter the screen size (the game's `screen` size).
  The encrypted browser version (`build.browser.encrypt`) also plays, since itch.io uses https. butler only sends the differences from the previous version (encrypted assets also stay the same file if their content doesn't change)

### GitHub Pages

The browser version plays when you put the exported folder (`<out>/browser/<id>`) there as it is (it loads files by paths relative to `index.html`, so it also works under `https://<user>.github.io/<repository>/`;
since it's https, the offline Service Worker and encryption work too).

- To put it there by hand, put the contents of the exported folder at the top of the branch that Pages publishes (`gh-pages` and so on)
- To put it there with GitHub Actions, copy the template [templates/ci/liminalia-publish.yml](../templates/ci/liminalia-publish.yml) to `.github/workflows/` in the game's repository.
  When you push a version tag (`v1.0.0` and so on), it exports the browser, Windows and Linux versions, puts the browser version on Pages, and also uploads to itch.io if `BUTLER_API_KEY` is in secrets.
  Set Source under Settings → Pages in the repository to "GitHub Actions"
- The template's `LIMINALIA_ENGINE_REF` has the engine's version tag of the time (`v0.2.0` and so on; [versioning.md](versioning.md)). It can be a commit too (it stops if it's empty).
  Pinning it means the game is always exported with the same engine; when you update the engine, change it here and check before distributing
- When it runs for a version tag, it checks that the tag and `version` in `liminalia.json` match (`v1.0.1` and `1.0.1`) and stops if they don't (so a forgotten version bump isn't shipped)

## Store declarations

What to declare when you publish to stores. The Liminalia engine sends nothing except what you've set a destination for. There are only the following three, and each is either sent after asking the player or written and sent by the player.
None of them carries IDs that identify a device or person, and none is used for advertising or tracking.

| Project setting | What's sent | When |
|---|---|---|
| `build.crashReport.url` | Crash records ("Crash records and source maps" above) | At the next launch after the game stops, when the player answers "Yes" |
| `build.analytics.url` | Play statistics ("Play statistics" above) | After the player agrees to send them |
| `build.feedback.url` | Feedback in test builds (test builds only) | When a tester writes and sends it |

Other than these, the only network traffic is the desktop version's update check (`build.update.url`), store features (achievements, purchases, cloud saves; these follow the store's rules), and whatever the project's plugins do themselves.
If a plugin sends information, you declare that too. For the Android and iOS versions, the export prints a "Store declarations: data collected by …" line.

### Privacy policy

Google Play and the App Store ask for the URL of the game's privacy policy. Write which of the items in the table above you use, where they're sent (your server), how long they're kept, and how to contact you.
If you use none of them, you can write that the game doesn't collect information. Nothing reaches the provider of Liminalia (the site's [privacy policy](https://liminalia.skyta.dev/en/privacy/)).

### Google Play (Data safety)

Answer under "App content → Data safety" in the Play Console.

| What you use | Answer |
|---|---|
| None of them | Doesn't collect or share any data |
| `build.crashReport.url` | Collected: "App info and performance → Crash logs" and "Diagnostics". Not shared, optional (players choose), purpose "App functionality", encrypted in transit (use an https destination) |
| `build.analytics.url` | Collected: "App activity → App interactions". Not shared, optional, purpose "Analytics" |

Neither is tied to the player (no account or device IDs are attached). Make sure the receiving side can respond to deletion requests.

### App Store (App Privacy and PrivacyInfo.xcprivacy)

Answer "App Privacy" in App Store Connect according to what you use, the same as for Google Play (crash records are "Diagnostics → Crash Data" and statistics are "Usage Data → Product Interaction";
both are "Not linked to the user" and "Not used for tracking").

The exported iOS version gets a privacy manifest, `PrivacyInfo.xcprivacy` (`mobile/privacy.ts`). It declares no tracking (`NSPrivacyTracking` is false, and there are no tracking domains),
and lists as collected data only the items in the table above that you use, as collection that isn't linked to a person or used for tracking. APIs that require a reason (UserDefaults, file timestamps and so on) aren't listed,
because the app part of the exported iOS version doesn't use them. When the project's plugins send other information, or you want to use a manifest you wrote yourself, put that file in `build.ios.privacyManifest`.

```json
"build": { "ios": { "privacyManifest": "store/PrivacyInfo.xcprivacy" } }
```

### Age ratings (IARC)

Google Play, the Microsoft Store and others decide age ratings with the IARC questionnaire (Steam uses the mature content declaration on your store page). The answers are about the game's content (violence, sexual content,
language, fear, drugs, gambling), which the engine doesn't decide. The questions that involve the engine can be answered as follows.

| Question | Answer |
|---|---|
| Can players interact with each other, or share things they made? | No (unless the project's plugins add it) |
| Is location shared? | No |
| Can digital goods be bought? | Yes, if you use `build.store.products` |
| Is there unrestricted internet access? | No (`@open-url` opens the page in the device's browser) |

When you release a toned-down edition separately (`contentFilter` in `build.variants`), answer based on that edition's content.

### Steam Deck

What the Steam Deck compatibility review ("Steam Deck Compatibility" in Steamworks) looks at, and how the engine handles it.

| What's checked | How the engine handles it |
|---|---|
| Can it be played with only a gamepad? | Advancing, choices, system screens, and saving and loading can all be done with a gamepad (it can also be bound to Steam Input with `build.steam.input`) |
| Text input | `@text-input` shows Steam's on-screen keyboard (["Steam" in player.md](player.md)) |
| Is text readable at 1280×800? | The screen is scaled up keeping its aspect ratio (a 16:9 game gets bars at the top and bottom). Check with the game's text size that the text and choices aren't too small at 1280×800 (players can raise "Text size" in Settings) |
| Launchers, external accounts | None |
| How it runs | The Linux version (`lim build linux`), or the Windows version through Proton. Check on a real device |

The control hints on the game screen (button names) follow the connected gamepad (players can change them with "Button labels" in Settings).

## Stores and in-app purchases

### Products, and using them from the scenario

Write the products that can be bought in `build.store.products` (the name in the game → the product ID in each store). For now, only one-time purchases (unlocking the full version, additional scenarios and so on) are supported
(consumables and subscriptions aren't).

```json
"build": { "store": { "products": {
  "full": { "ios": "com.example.game.full", "android": "full_unlock", "steam": 1234560, "gog": "1207666" }
} } }
```

```
@if (!system.purchases.full)
  @purchase full
@end
@if (system.purchases.full)
  @jump chapter2
@end
```

- `@purchase <product>` buys it (waiting until the store screen closes). After a purchase, `system.purchases.<product>` becomes `true` and is saved right away as a variable shared by all saves.
  The result ("Purchase complete", "Purchase canceled", "Your purchase is pending" and so on) is shown briefly to the player
- `@restore-purchases` restores purchases (after changing devices, for example. iOS review requires a restore button)
- At launch, and when the player returns to the game (from a store page, for example), ownership is checked with the store again. If the store can't be reached, the result of the previous check is used
- Where there's no store (the browser version, and exports not connected to a store), the game shows "Purchases aren't available here" and does nothing

### iOS (StoreKit 2)

If a product has `ios`, `lim build ios` builds StoreKit 2 code into the app. Create a non-consumable product with the same Product ID in App Store Connect.
- Ownership comes from `Transaction.currentEntitlements` (excluding refunded items), and only transactions whose signatures are verified count as purchases. Restoring uses `AppStore.sync()`
- Purchases awaiting approval (such as Family Sharing's Ask to Buy) are reported as pending, and are applied at the next check once they go through
- To test locally, create a StoreKit Configuration File in Xcode and set it in the scheme under Run → Options → StoreKit Configuration

### Android (Google Play Billing)

Billing on Google Play needs the Play Billing Library (AAR). The export doesn't use Gradle, so get the AARs yourself and list them in `build.store.android.libraries`
(without them, the export warns and builds without billing).

```json
"build": { "store": { "android": { "libraries": ["libs/billing-8.0.0.aar"] } } }
```

- Get the AAR from Google's Maven repository (`com.android.billingclient:billing`), and list all the AARs and JARs it depends on too (see the dependencies in the Maven pom,
  or check with `./gradlew :app:dependencies` in an Android Studio project). It builds with either Play Billing Library 7 or 8
- `classes.jar` and `libs/*.jar` from the AARs are built in, and the permission (`com.android.vending.BILLING`), queries, activity and meta-data are added to AndroidManifest.xml.
  The AARs' resources (`res/`) aren't built in, so libraries that use resources may not work
- Purchases (in the purchased state) are acknowledged (otherwise they're refunded after 3 days). Google Play ties purchases to the account, so restoring is the same as asking again what the player owns
- Create an in-app product with the same product ID in the Play Console. Billing can only be tested in an app installed from the Play Store (from the internal testing track, for example)

### Mobile achievements (Game Center and Google Play Games)

`@achieve` and `@achieve-progress` (`extra.achievements` in `liminalia.json`; counting achievements use `goal`) are sent to Game Center achievements in the iOS version
and to Google Play Games Services v2 achievements in the Android version, just as the desktop version sends them to Steam. Both record achievements unlocked while offline or before signing in,
and send them once sign-in is done. Every launch sends the unlocked achievements and counts again (the store ignores duplicates).

```json
"build": {
  "gameCenter": { "achievements": { "first_star": "com.example.game.first_star" } },
  "playGames": {
    "appId": "1234567890",
    "achievements": { "first_star": "CgkIxxxxxxxxEAIQAQ", "read_all": "CgkIxxxxxxxxEAIQAg" },
    "libraries": ["libs/play-services-games-v2-21.0.0.aar", "libs/play-services-base-18.5.0.aar", "libs/play-services-basement-18.4.0.aar", "libs/play-services-tasks-18.2.0.aar"]
  }
}
```

**iOS (Game Center)**

- If `build.gameCenter` is set, `lim build ios` adds GameKit code and the Game Center entitlements (`App/App.entitlements`) to the app.
  `achievements` maps the game's achievement names → Game Center achievement IDs (if you don't write one, the game's achievement name is used as the ID as is)
- An unlock is sent as 100% complete, and a counting achievement as the ratio "current count / goal" (the percentage is never lowered). The game signs in at launch, and shows the Game Center screen if the player isn't signed in
- What you do: enable Game Center for the app in App Store Connect and create achievements with the same IDs. Enable the Game Center capability for the App ID in your Apple Developer account
  (with Xcode's automatic signing, it's added when you sign with your team). You can also test in the Simulator if you sign in to Game Center

**Android (Google Play Games Services v2)**

- If `build.playGames` is set, `lim build android` adds Play Games code to the app, and `com.google.android.gms.games.APP_ID` to AndroidManifest.xml
  (its value is the resource `game_services_project_id`). The export doesn't use Gradle, so get the libraries (AARs) yourself and list them in `libraries`
  (`com.google.android.gms:play-services-games-v2` from Google's Maven repository and all the dependencies in its pom. You can also look at `./gradlew :app:dependencies` in an Android Studio project)
- The libraries' resources (`res/`) are linked too, and the libraries' `R` classes are generated (to read `google_play_services_version` from `play-services-basement` and so on).
  Libraries that are also in the billing libraries (`build.store.android.libraries`) are built in only once
- `achievements` maps the game's achievement names → Play Console achievement IDs (only the achievements you list are sent). Unlocks are sent with `unlock` and counting achievements with `setSteps(current count)`,
  so make those incremental achievements in the Play Console, with the number of steps equal to `goal`
- The game waits for the automatic sign-in at launch (it doesn't show a sign-in screen, and nothing is sent for players who aren't signed in through Play Games' settings)
- What you do: set up Play Games Services in the Play Console (the project ID is `appId`), create the OAuth consent screen and an Android credential registered with the SHA-1 of the app's signing key,
  and create and publish the achievements. Register tester accounts. Test with an app installed from the Play Store (from the internal testing track, for example)

### Steam DLC

If a product has `steam` (the DLC's App ID), the Steam-connected desktop version checks ownership with `isDlcInstalled`. `@purchase` opens the DLC's store page in the Steam
overlay (whether it was bought is checked again when the player returns to the game). The DLC's content can be delivered as a pack (a depot placed in `Resources/packs/`).

### Steam Workshop

With `build.steam.workshop: true`, the Steam-connected desktop version loads the installed Workshop items the player has subscribed to as packs
(`workshop.getSubscribedItems` and `installInfo` in steamworks.js).
- An item's content is a pack folder exported with `lim pack` (with `pack.json` at the top level or inside a single folder). Its id is `id` in `pack.json` (letters, digits, `_` and `-`;
  if that can't be used, `workshop-<item ID>`). If there's an official pack with the same id (in `packs/` in the save location, or in `Resources/packs/`), that one is used
- Subscriptions that aren't installed yet are requested for download and loaded from the next launch. Items whose `requires` (game version) doesn't match aren't loaded
- Use Steam's tools to make and upload items (SteamCMD from Steamworks, or an uploader your project provides). Liminalia only handles loading them
- Workshop items can be made by people other than the game's creators, so only the pack's content (scenarios, data and assets) is loaded, and plugin code isn't

### Steam Input

`build.steam.input` binds Steam Input actions to game controls. Upload the action definitions (Game Action File) to Steam Input in the Steamworks admin pages.

```json
"build": { "steam": { "appId": 123456, "input": { "actionSet": "InGameControls", "actions": {
  "confirm": "a", "cancel": "b", "menu": "start", "hide_window": "x", "backlog": "y", "skip_hold": "rb", "auto_toggle": "auto", "quick_save": "quick-save"
} } } }
```

- The controls you can bind are gamepad buttons (`a`, `b`, `x`, `y`, `lb`, `rb`, `lt`, `rt`, `select`, `start`, `up`, `down`, `left`, `right`; `advance` is `a` and `back` is `b`) and
  system screen actions (`auto`, `skip`, `quick-save`, `quick-load`, `save`, `load`, `rollback`, `rollforward`, `prev-choice`, `next-choice`, `next-unread`,
  `backlog`, `config`, `flowchart`, `screenshot`, `hide`, `menu`, `title`)
- Buttons behave as on a standard gamepad (`a` confirms and advances, `b` goes back, `start` opens the menu, and `rb` skips while held). Both presses and releases are passed to the game.
  System screen actions happen on press
- `actionSet` defaults to `InGameControls`. The same action set is used for the whole game

### Other stores (GOG Galaxy, Epic Games Store)

GOG Galaxy and Epic Online Services have no official Node.js libraries, so a project plugin plugs in a store module. In an export that isn't connected to Steam,
if you write a CommonJS file in `build.store.desktop.module`, the export puts that file's whole folder into the app's `store/` and loads it at launch
(native libraries (`.node`, `.dll`, `.dylib`) placed in the same folder are kept outside the asar).

```json
"build": { "store": { "desktop": { "module": "plugins/gog-store/store.cjs", "options": { "clientId": "…" } } } }
```

```js
// plugins/gog-store/store.cjs (runs in the desktop version's main process)
module.exports = {
  name: "gog", // the key for this store's IDs in build.store.products
  create(ctx) {
    // ctx.game (title, version), ctx.options (build.store.desktop.options), ctx.log, ctx.dir (this file's folder)
    const galaxy = require("./galaxy-binding.node"); // example: a GOG Galaxy SDK binding you provide
    galaxy.init(ctx.options.clientId);
    return {
      achievement(id) { galaxy.unlockAchievement(id); },            // @achieve
      presence(text) { galaxy.setRichPresence("status", text); },     // @presence (empty clears it)
      async owned(ids) { return ids.filter((id) => galaxy.isDlcInstalled(id)); },
      async buy(id) { galaxy.openStorePage(id); return "opened"; },  // "purchased" | "pending" | "cancelled" | "failed" | "opened"
      async restore(ids) { return this.owned(ids); },
      checkLicense() { return galaxy.isLoggedOn(); },                 // if false, the game tells the player and quits
      shutdown() { galaxy.shutdown(); },
    };
  },
};
```

- Every method is optional (missing ones aren't used). A module can also have `gamepadText(o)` (an on-screen keyboard), `isDeck()`, `packs()` (folders of extra content the store delivers)
  and `licenseMessage` (the text shown when `checkLicense` returns false). If the module can't be loaded, or `create` throws, the game can still be played without the store features
- Exports connected to Steam (`build.steam`) use the Steam code

### DLsite, DMM GAMES and others

DLsite and DMM GAMES work by having the store wrap the game files it receives, or by wrapping the executable with a tool the store provides, and no SDK for games to call is public.
Liminalia only provides hooks for this.
- `build.windows.wrap`: a command that wraps the exported executable (`{file}` is the executable's path. It runs before signing. The environment variable `LIMINALIA_WIN_WRAP_COMMAND` takes precedence)
- `checkLicense()` in the store module: plugs in a license check at launch
- Wrapping changes the executable, so signing (`build.windows.sign`) and the installer come after it. If the store does the wrapping, follow the store's guidance on whether to submit without signing
