# Liminalia Studio

## The game's aspect ratio

The preview, the separate window, full screen, the timeline preview, the game settings preview, command samples, thumbnails and the images on flowchart cards follow the aspect ratio of `screen` in `liminalia.json` (`work-screen.ts`, `work-screen.css`; `work-aspect`, `work-portrait`, `--work-aspect` and `--work-ratio` are written on html; nothing is written for 16:9 games).

- For portrait games, the preview is limited to 56% of the screen height (72% when enlarged) so it doesn't get too tall in the right panel, and is centered
- The separate window opens 1280 wide for landscape, and for portrait at 720×1280 shrunk to fit within 90% of the screen height
- Flowchart cards keep their size (decided by the layout), keep the image height and make the width match the game's aspect ratio
- Thumbnail images and flowchart images crop the middle of the background (`ui.backgroundFocus` isn't used; the preview and screenshots use it)
- Asset guesses: for portrait games, 16:9 images are taken as backgrounds too, besides images with the game's aspect ratio

## Principles

- The single source of truth is the `.lim` text. The screens only read and draw it, and every write goes through `PUT /file` (the write API)
- If the content on disk changed after it was loaded, it isn't saved (409 and the current content are returned). Old content never overwrites new content.
  The parts of `liminalia.json` that the client replaces with its loaded copy (the game settings `ui`, extras `extra`, the basics and export items) and translations (`lang/<language>.json`)
  are also saved with the hash from when they were loaded (for `liminalia.json`, the hash of that part written as JSON), and if they changed, 409 returns the current content (`PartRead`, `PartWrite`).
  The client merges them as it does scripts (`part-sync.ts`, `model/merge-json.ts`; items are compared one by one, changes that don't overlap are both taken in, and when the same item was changed to different values,
  you choose in the merge panel; after merging and saving, it tells you and reloads the panel). Just opening doesn't save
- The content of `liminalia.json` and translations before saving is also kept, by the same rules as the change history, in `.liminalia/history/@config/` and `.liminalia/history/@lang/<language>/` (there is no panel to restore them from the screen)
- The content before each save (the change history) is kept with a date and time in `<project>/.liminalia/history/<file>/`. Automatic saving saves every time typing pauses for 1 second, so recent entries are kept in detail and older ones are thinned more coarsely
  (`server/versions.ts`: the newest 5 as they are, one per minute up to 10 minutes ago, one per hour up to 24 hours ago, and one per day before that, keeping the last one in each interval;
  up to 50 entries and 16 MB per file in total; beyond that, the oldest are deleted, and the newest is always kept). Project data (`@data`) is kept by the same rules.
  Saving writes to a temporary file and then replaces the original (so stopping partway never leaves a half-written file)
- No build output for the preview is made in the project. Read-only APIs (GET, `POST /check`) write nothing. The all-routes test (`POST /coverage`, `POST /coverage/stream`) saves its result only in Studio's data, `.liminalia/coverage.json`.
  Only exports the writer asked for (screenshots in `exports/shots`, performance measurements in `exports/profile`, translations, and recording scripts in `exports/…`) are saved in `exports/`
- Projects made by importing (with `import.tyrano` in `liminalia.json`) have `importManaged: true`. Edits are overwritten by the next `lim import`

## Endpoints

All of them are under `/__liminalia/studio/api`. Files are paths relative to the script folder, without the extension (`start`, `part1/chapter2`).

| API | Returns |
|---|---|
| `GET /project` | Project information, the list of files (line counts, hashes, labels), speakers, characters, command specs, and the asset list (below) |
| `GET /file?file=` | The content and hash (the first 16 characters of SHA-256) |
| `PUT /file` | Saves `{ file, text, baseHash, check? }`. If baseHash differs from the disk, 409 (with the current content). For a new file, baseHash is null. After saving, it checks the whole project once and returns the whole result (`check`, the same as `POST /check`) and that file's part (`diagnostics`). With `check: false`, it doesn't check (for saving several times in a row, such as replacing, and then calling `POST /check` once at the end). `liminalia.json` is reloaded only when its text changes |
| `POST /search` | `SearchRequest` (`{ query, regex?, body?, kana?, caseSensitive?, open? }`) → `SearchResult` (for each matching file, the hash and the lines, matched ranges and regular expression groups; up to 5,000 lines). An unreadable regular expression returns 400 |
| `GET /history?file=` / `GET /history/item?file=&id=` | The list of the change history (newest first), and the content of an entry |
| `POST /check` | The same check as `lim check` (including checking that assets exist). Each diagnostic has its category, with counts per category |
| `POST /coverage` | The same as `lim coverage`: the all-routes test run without a screen, and the diagnostics from running (the body `{ runs }` sets the most runs per file; 8 by default, stopping early when every way of choosing has been tried). Saves the result (`hashes` are the file hashes at the time of the run) in `.liminalia/coverage.json` |
| `POST /coverage/stream` / `GET /coverage` | The same, sending `CoverageEvent`s one line at a time with progress after each run (`progress`, and `done` at the end; closing the request stops it) / the saved result (null if none) |
| `GET /reviews` / `POST /reviews` | Review comments (`ReviewList`: the threads and the name attached to comments) / takes a `ReviewAction` (`create`, `reply`, `edit`, `resolve`, `delete`, `anchor`; `create` and `anchor` also take `end`, the last line of a range; `edit` only for comments whose author name matches the current name), rewrites `reviews/` and returns the list |
| `POST /reviews/import` / `GET /reviews/shot?path=` | Imports feedback from a test build as comments (`{ files: { name, data }[] }`, where data is the content of a `.liminalia-feedback.json` or a list of them; returns `FeedbackImportResult`) / the screenshot attached to feedback (only inside `reviews/shots/`) |
| `GET /stats` / `POST /stats/ignore` / `POST /stats/unignore` | Character counts, spelling variant candidates and excluded groups (`TextReport`, the same tally as `lim stats`) / adds the group `{ id }` to `stats.variants.ignore` / removes it |
| `POST /reload` | Reloads a project changed outside Studio. `ReloadResult` (`{ ok: false, restart }` if the settings or plugins changed) |
| `GET /data?name=` | Project data (.json in `paths.data`). `DataText` (used by plugin screens) |
| `PUT /data` | `DataWriteRequest` → 200 `{ ok: true, hash }`, 409 `{ ok: false, current }`. The change history is in `.liminalia/history/@data/` |
| `POST /asset?kind=&path=[&overwrite=1]` | Adds an asset (the request body is the file itself; only images, sounds, videos, subtitles, fonts and shaders; the extensions are the same table export uses for what goes into the game, `MEDIA_EXTENSIONS` in `@liminalia/lang`). The background, sprite and image folders accept only images, BGM, sound effects and voices only sounds, and videos only videos and subtitles; otherwise 400 with the allowed extensions. Other, and folders the project added, accept anything. The same name returns 409 |
| `GET /voices` | The voice file and status for each line of dialogue (`VoiceList`, the same rules as `lim voice-script`), and the hash of each file |
| `GET /assets/list` / `GET /assets/usage` | The files in each asset folder (with sizes; for images, also `width` and `height` if they can be read) and the folders inside / where assets are used (`"kind/path"` → script lines, characters, project settings) |
| `POST /assets/rename` | Renames with `{ kind, from, to }` (folders too). Also rewrites the script lines that refer to it (through the write API, kept in the history) and the characters, and returns the references that couldn't be rewritten |
| `GET /trash` | The contents of the trash (`TrashEntry[]`, newest first: what (kind and path, up to 20), when it was moved, and the total count) |
| `POST /assets/trash` / `POST /assets/restore` / `POST /assets/folder` | Moves to `.liminalia/trash/<id>/` (up to `TRASH_KEEP` entries) / restores with `{ id }` (409 if the destination is taken) / makes a folder |
| `POST /assets/samples` | Copies the template's sample assets (CC0) into the asset folders (files with the same name aren't copied) → `{ added, skipped }` (`"kind/path"`) |
| `POST /assets/requests` / `GET /assets/requests.csv` | Writes the asset request list (missing assets, variants and voices) to `exports/asset-requests.csv` → `{ path, count }` / that CSV (English headings with `?lang=en`) |
| `POST /assets/trash-many` | Moves an `AssetTrashManyRequest` (`{ items: [{ kind, path }] }`, files only) to the trash under one id. If any is missing, nothing moves |
| `POST /files/create` / `duplicate` / `rename` / `trash` | Creates a script file (`{ file, text? }`), duplicates, renames (`{ from, to }`; jump targets, history and entry too), moves to the trash (`{ file }`; restore with `/assets/restore`) |
| `POST /scenes/move` | `SceneMoveRequest` (`{ file, labels, to }`; labels are scenes placed consecutively in the file) → `SceneMoveResult` (the rename result plus `created`, whether a file was created, and `joins`, the lines added to keep the flow). Creates `to` if it doesn't exist. Non-consecutive scenes, the top of the file, and the same name at the destination return 400 or 409 |
| `POST /labels/rename` | `{ file, from, to }` → `LabelRenameResult` (the rewritten files, the number of lines, the places in liminalia.json, `entry` (applied after a restart), the languages whose translation keys were replaced, and `left`, the references that couldn't be rewritten). Invalid names return 400, and duplicates within the same file 409 |
| `GET /settings` / `POST /settings` | Reads the basics (including `check` for the check and `format` for formatting) and export items and their hash / saves `{ settings, baseHash }` (200 `{ ok: true, hash, restart }`, 409 `{ ok: false, current }`) |
| `POST /check/severity` | Writes the severity for a code to `check.severity` in liminalia.json with `{ code, level }` (removes it if `level` is null; "Don't show this kind" is `off`) |
| `GET /scenes` / `POST /scenes` | Scene info (`scenes` in liminalia.json) / saves the info of one scene with `{ key, info: { pov, date, place } }` (empty strings are removed, and other fields are kept; 404 for a scene that doesn't exist) |
| `POST /script-export` | Exports the script for proofreading to `exports/script/` with `{ format: "text" \| "html" }` and opens the folder (`{ folder, files, lines }`) |
| `GET /extra` / `POST /extra` | Reads the extras lists (`extra` in liminalia.json) and their hash / saves `{ extra, baseHash }` (removed if empty; 409 as for `/settings`) |
| `GET /i18n` / `GET /i18n/file?lang=` / `PUT /i18n/file` / `POST /i18n/languages` | Languages, translation progress and the hash of the language list / the translations synced to the current script, the script locations and the file hash (null if none) / saves translations with `{ lang, file, baseHash }` (409 returns the current translations) / saves the playable languages with `{ languages, baseHash }` (409 returns the current list; the client applies the same change to the current list and saves again) |
| `GET /plugins` / `POST /plugins` | `{ plugins, hash }` (the project's plugins, their contents and the hash of the list) / saves the plugin list with `{ plugins, baseHash }` (400 if one can't be found; 409 returns the current list, and the client applies the same change and saves again; takes effect after a restart) |
| `POST /plugins/create` | `{ name, parts }` → `{ spec }`. Creates a plugin with a sample in `plugins/<name>` and adds it (409 if it exists) |
| `POST /plugins/update` | `{ spec, name?, description? }`. Rewrites the package.json of a plugin inside the project folder |
| `POST /plugins/reveal` | `{ spec }`. Opens the folder of a plugin inside the project folder in the OS file browser |
| `GET /ui` / `POST /ui` | Reads the game settings (`ui` in liminalia.json) and their hash / saves `{ ui, baseHash }` (400 if the shape is wrong; removed if empty; 409 as for `/settings`) |
| `GET /command-defaults` / `POST /command-defaults` | Reads / saves the command defaults (`commandDefaults` in liminalia.json) (unknown commands or parameters and type errors return 400; removed if empty) |
| `GET /ui/themes` / `POST /ui/theme` | The list of available themes (the bundled ones and the project's `themes/<id>/theme.json`) / applies the theme `{ id }` (copies its assets to `assets/image/themes/<id>/`, saves `ui` and returns it; applying a portrait-only theme to a landscape game is refused with 400) |
| `GET /screens/rules` | The rules for screens that can be built from a template (`ScreenTemplateRules`; whatever starts the dev server passes it with `setScreenTemplateRules`; `null` if not) |
| `GET /screens/files?screen=` / `PUT /screens/file` | The screen's template and screen JS, whether it is registered, and the plugin that replaces it first (`ScreenFiles`) / `{ screen, kind, text, before }` writes the whole template or screen JS (409 if it changed after it was read) |
| `POST /screens/copy` / `POST /screens/script` / `POST /screens/reset` / `GET /screens/diff?screen=` | The same as `lim screens copy`, `js`, `reset` and `diff` (`@liminalia/project/screen-copy`). Writes return an `undo` entry for ⌘Z |
| `GET /screens` | The list of built-in screens (`ScreenInfo[]`: name, owning package, whether Game screens can open it, the content it provides, why it can't be opened, and the hooks for the four tiers in the table in screens.md). Studio doesn't load the player side, so whatever starts the dev server (`packages/web/vite.config.ts`, the mobile version's Service Worker) passes it with `setScreenTable` |
| `POST /ui/theme/save` / `POST /ui/theme/trash` | `{ name, overwrite? }` saves the current look to `themes/<id>/theme.json` (`ThemeSaveResult`; the same name returns 409; for portrait games, `orientation: "portrait"` is written too) / `{ id }` moves a project theme to the trash (restore with `/assets/restore`; bundled themes return 400) |
| `GET /variables` / `POST /variables/set` / `POST /variables/rename` | The list of variables (initial values, and the lines that read and assign them) / sets or removes an initial value / renames |
| `POST /macros/rename` | `{ from, to, file? }` → `MacroRenameResult` (the files rewritten, the number of lines, and whether keys of `commandDefaults` were rewritten). An invalid name is 400, and 409 if a macro with that name already exists. When the `@define` of `from` is in two or more files, `file` chooses one (409 without it, 404 if that file doesn't have it) |
| `GET /cast/lines?speaker=` | `SpeakerLine[]` (the dialogue of the given speakers, in file name order and line order) |
| `GET /cast/backups` / `GET /cast/backups/item?id=` | The change history of cast.json (newest first; `HistoryEntry`) / the content of one entry (`current` gives the current cast.json) |
| `GET /undo/state` / `POST /undo/apply` | The state of the record (`undo`) of an action that moved files (`applied`, `undone`, `changed`, `gone`) / undoes or redoes with `{ id, to: "undone" \| "applied" }` (`server/file-undo.ts`) |
| `GET /cast/usage` / `POST /cast/rename` | The number of script lines per character ID, the number of lines of dialogue per speaker name, and the number of lines that specify each variant (`variants`) / renames with `{ kind: "cast" \| "speaker", from, to }`, rewriting the script references and cast.json (with `speakerToo: true`, the display name with the same name as the character ID changes too, as one action) |
| `GET /studio-state` / `PUT /studio-state` | Studio's data (the shared part `STUDIO_SHARED_KEYS` in `.liminalia/shared.json`, the rest in `.liminalia/studio.json`: face crops `faces`, positions of scenes moved on the flowchart `mapPositions`, parts panel favorites `favorites`, bookmarks `bookmarks`, the character goal and daily counts `textGoal` and `textDaily`, breakpoints `breakpoints`, character notes `castNotes`) / replaces the whole thing with `{ state }` (items with the wrong shape are dropped). Nothing is saved to the game data |
| `GET /map/cast` | Scene (flowchart id) → the people who speak in that scene (in the order written; for the flowchart's character filter; `sceneSpeakers` in `model/map-filter.ts`) |
| `GET /sweep?file=[&from=&to=]` | The state of each line of that file as in the real game (below). from and to narrow the range of lines (the states of command lines are narrowed too, and the screen states are limited to those used in the range and renumbered) |
| `POST /shot` | `ShotRequest` (`{ file, line, show, cast? }`; show is the `stage-show` or `stage-still` requested from the preview) → `ShotResult` (`{ path, width, height }`). Captures the preview's screen at the game's size and saves it in `exports/shots`. Without Chromium, `CHROMIUM_MISSING_STATUS` (424) |
| `GET /shots/file?name=` | A PNG directly under `exports/shots` (for "Download" in the browser) |
| `POST /shot/play` | `{ start?, skip?, title?, lang? }` → PNG. As with `lim shot`, captures the click wait of the page skip pages after start (`[N]` in `lim trace`; when skip is 1 or less, it also stops at choices and screens waiting for input before the first page), or the title screen, at the game's size and returns it (in the language `lang`, if given; `lim shot --lang`) (not saved to a file; the `screenshot` of the AI's MCP; [mcp.md](../mcp.md)) |
| `GET /server` | `{ root, pid }`. Answers without waiting for the project to load. The AI's MCP uses it to check the dev server in `.liminalia/studio-server.json` |
| `POST /profile` | `ProfileRequest` (`{ target?, pages? }`) → sends `ProfileEvent`s one line at a time (`application/x-ndjson`; each line is a `StreamLine`): `progress` as it advances, and `done` at the end (the `ProfileReport` and the folder it was saved in). Closing the request stops the measurement |
| `POST /regress` / `GET /regress/file?kind=&name=` | `{ update?, threshold? }` → sends `RegressEvent`s one line at a time (`progress`, and at the end `done` with the `RegressResult`) / the `baseline`, `current` and `diff` images in `.liminalia/regress` |
| `POST /voice-lock` | Locks the numbers of numbered voices, and returns `VoiceLockResult` (the saved file, the number of lines, the breakdown of carried-over and added numbers, and lines whose numbers split) |
| `GET /sweep/stage?file=` | The data for the duration bars. Returns, for the whole file, the background, BGM (file, volume, loop), looping sound effects (per channel) and sprites (name, variant, sprite set, position, flip) at each line (identical states are merged into one, and lines point to its number) |

The write APIs accept only requests from the same origin. The dev server watches the script folder and `cast.json`, and sends outside changes (other editors, AIs, imports)
through the Vite WebSocket custom event `liminalia:studio` (`file-changed`, `file-added`, `file-removed`, `cast-changed`).
It doesn't send them for the client's own writes. It also watches the asset folders and sends `assets-changed` when files are added or removed (once for a run of additions).
Large responses (16 KB or more) are returned gzipped if the request accepts it.

The asset list (`ProjectInfo.assets`) is the paths relative to each asset folder (`bgimage`, `fgimage`, `image`, `bgm`, `sound`, `video`, and
the folders the command specs list as places to look) (in name order; names starting with `.` are left out).

Check categories (`category` of each item in `CheckResult.diagnostics`, and `counts`): `syntax` (syntax errors), `command` (commands and parameters),
`cast` (characters, sprite sets, variants, standing positions, the shape of cast.json), `target` (jump target files and labels), `asset` (missing assets),
`plugin` (diagnostics returned by a plugin's `check`, and exceptions thrown by `check`; [plugins.md](../plugins.md#命令commands)).
