# API & CLI

This page lists the public surface as importable today. Signatures are verbatim from the package.

## Site & composition markers: `situ`

The markers are transparent `Annotated` aliases: the checker sees the payload type; the compiler reads the site from the outer name.

| Marker | To a type checker | To the compiler |
|---|---|---|
| `Local[T]` `Url[T]` `Server[T]` `Synced[T]` `Derived[T]` | `T` | the signal's site |
| `Prop[T]` | `T` | parent → child input |
| `Emit[T]` | `Callable[[T], None]` | child → parent event |
| `Provide[T]` / `Inject[T]` | `T` | the hierarchical value channel |

## Where the service comes from

A server mount hands each command and each `context()` call your domain service: a store, a repository, a facade. All three adapters take your own DI the same way, as `resolve`: a function with no argument that returns the service, or an awaitable of it.

- `asgi_app` and `mount_flask` require `resolve` (on Flask it is synchronous, like the rest of a WSGI app).
- `mount_component` and declui's `mount_model` take either `resolve=` or `service_type=`, which looks the type up in the request's [Dishka](https://github.com/reagento/dishka) container. Pass one of the two: a mount given both raises `CompileError`. A `mount_model` given neither is a pure-client mount, with no commands.

situ never closes the service. With `service_type=`, Dishka closes what it opened for the request, so a database session per request belongs there; `situ.infra.di.SessionProvider` is a ready-made one. With `resolve`, the service's lifetime is yours. Return an object that lives as long as the app, such as an in-memory store or a repository holding a session factory. A resource opened per request needs closing in your framework's teardown hooks, such as Flask's `teardown_appcontext`, which svcs uses.

## Mount factories: Litestar (`situ`)

These build on the framework-neutral core ([`situ.mount.core`](#neutral-mount-core-situmountcore)). These names load lazily, so `import situ` pulls in no Litestar until you call one.

```python
mount_static_component(*, path: str, stem: Path, template: str,
                       meta: Mapping[str, str]) -> Router
```

It serves a pure client: `GET /` + `GET /island.js`, with neither DI nor commands.

```python
mount_component(*, path: str, stem: Path, template: str, meta: Mapping[str, str],
                service_type: type[ServiceT] | None = None,          # one of these two:
                resolve: Callable[[], ServiceT | Awaitable[ServiceT]] | None = None,  # see "Where the service comes from"
                facade: Callable[..., object] | None = None,
                context: Callable[..., Awaitable[Mapping[str, object]]],
                components: Context | None = None,
                overrides: Mapping[str, Path] | None = None,
                unified: bool = False,
                live: bool = False,
                hub: Hub | None = None,                          # your own Hub → publish from outside a request
                fallback: str | None = None,                     # region markup when the page render raises
                window_template: str | None = None,
                guard: Guard | None = None,
                identity: Callable[[Request], str] | None = None,
                on_upload: Callable[..., Awaitable[str]] | None = None,
                transition: bool = False,
                check_optionals: bool = False,
                extra_routes: Sequence[ControllerRouterHandler] | None = None,
                exception_handlers: ExceptionHandlersMap | None = None,
                watch: Iterable[Path] = ()) -> Router
```

The server-backed routes: adds `POST /cmd/{name}` (+ `/{arg:int}`), and with `live=True` (or a `hub=`) an SSE `/feed` + `/region`, with `window_template=` a `/window`. The service comes from `service_type=` or `resolve=`, as [Where the service comes from](#where-the-service-comes-from) describes. `facade` optionally wraps it for the handlers, and `context` builds the template data. `guard`, `identity`, `extra_routes` and `exception_handlers` hook the mount into your application, as `mount/factories.py` describes for each one. `window_template` and a `:virtual` binder go together: a component with only one of the two raises `CompileError` at mount. A path id is plain digits on every adapter, so `POST /cmd/toggle/-1` is a 404. The routers these factories build stay out of your app's OpenAPI schema; an `extra_routes` handler that belongs there sets `include_in_schema=True`.

`on_upload(service, upload) -> handle` adds a `POST {path}/upload` route for `:upload` fields: the browser posts the file there, the hook stores it and returns a handle string, and the handle travels with the next command as an ordinary `Local[str]`. `transition=True` cross-fades the region re-render through the View Transitions API, where the browser has it. `check_optionals=True` adds one check to the boot-time template check of a `context()` typed to return a `TypedDict`: an `obj.field` read outside an `{% if obj %}`, where `obj` is typed `X | None`, is a `CompileError`. With `SITU_DEV=1` in the environment, the mount recompiles when a component's files change, shows a compile error in the page, and reloads the browser; `watch` names other files or directories to follow, such as stylesheets.

**Entity mounts.** A parametrized `path` (`/things/{id:int}`) is an entity mount: one compiled island serves one page per entity. The path converters merge into the `view` mapping `context()` receives (`context(service, view)` gets `view["id"]` from the path, stringified, exactly like a query param). The command / island / feed / region URLs bake *relative* (`cmd/…`, `island.js`) so a single island serves all ids, resolved against the entity page URL; a converter named `name` / `arg` (the command routes' own params) raises at mount. A bare-URL request (`/things/1`) 307-redirects to the trailing-slash form so a bookmark still boots a working island. Query-string selection (a `Url` signal) stays the default; the parametrized path is the opt-in entity form (parity with the Flask adapter).

**Fallback** (`fallback=`): markup served in the region when building the page raises: a `context()` that hit a database timeout, a facade bug. The page, the shell and the island still ship with that markup in place of the region. The exception is logged, so one failing region degrades where the mount would otherwise 500 the whole page. An explicit `HTTPException` (a `context()` raising `NotFoundException` for a missing entity) passes through as itself, so a real 404 stays a 404. What `seed()` provides comes from `context()`, so on the fallback path the client signals start from their declared defaults. The markup is **trusted** and injected unescaped, so pass a constant, never user input or an exception's text (the same rule as `head`).

**Live from outside a request** (`hub=`): pass your own `Hub()` (which implies `live`) and hold the handle to publish a "peers re-fetch" ping from a background worker / webhook / domain event: `hub.publish_threadsafe()` hops onto the captured event loop, so a non-loop thread is safe. It is a no-op until a peer subscribes.

```python
mount_tree(*, path: str, root: Path,
           components: Context,
           overrides: Mapping[str, Path] | None = None,
           template: str, meta: Mapping[str, str],
           unified: bool = False) -> Router
```

A pure-client component tree: the root plus resolved children, spliced to one island.

## Mount adapter: Flask (`situ.mount.flask`)

```python
mount_flask(*, path: str, app_factory: Callable[[str], EmittedApp], template: str,
            meta: Mapping[str, str], resolve: Callable[[], object],
            context: Callable[[object, Mapping[str, str]], Awaitable[Mapping[str, object]]],
            facade: Callable[..., object] | None = None,
            guard: Callable[[], Any] | None = None, head: str = "",
            page_render: Callable[[str, Mapping[str, object]], str] | None = None,
            fallback: str | None = None,
            check_optionals: bool = False) -> Blueprint
```

Serves a compiled component on Flask (WSGI): the same four routes as `mount_component`, over a Flask `Blueprint`. `path` may hold Werkzeug converters (`/members/<int:oid>`) for an **entity mount**: converter values are merged into the `view` mapping (stringified, like query params). The island's command/island URLs are compiled *relative* (`cmd/…`, `island.js`) so one island serves all entities, resolved against the page URL; converter names must not shadow `name`/`arg`. `app_factory(cmd_base)` returns the compiled `EmittedApp`; the caller compiles it, so the baked-in command URLs match the mount. `resolve()` supplies the domain service (see [Where the service comes from](#where-the-service-comes-from)), and `context(service, view)` builds the region data. `guard` is a Flask `before_request` callable run before each route on the mount (page + island + commands). Return `None` to allow, a response or `abort(...)` to deny; per-mount auth or an ACL goes here. `head` is trusted HTML injected into the page `<head>`: pass `'<link rel="stylesheet" href="/static/declui.css">'` for declui's scaffold styling (and serve `situ.static_dir()` at `/static`). `page_render` defaults to situ's bundled Jinja; pass `lambda name, ctx: flask.render_template(name, **ctx)` to reuse the app's env + context processors (not bare `render_template`, since the context rides as kwargs). `fallback` is region markup served when building the page raises, as on `mount_component` (an `abort(...)` passes through as itself). Commands run the async core via `asyncio.run`. **CSRF:** a command POST must send the shim's `X-Siting: 1` header (a cross-origin request can't set it without a CORS preflight), so exempt the command routes from form-token CSRF (Flask-WTF: `csrf.exempt(bp)`) and rely on this + a `SameSite` cookie. Ships in `situ[flask]`; importing it pulls in no Litestar. See `examples/flask/`.

## Mount adapter: generic ASGI (`situ.mount.asgi`)

```python
asgi_app(*, app_factory: Callable[[str], EmittedApp], template: str,
         meta: Mapping[str, str], resolve: Callable[[], object | Awaitable[object]],
         context: Callable[[object, Mapping[str, str]], Awaitable[Mapping[str, object]]],
         facade: Callable[..., object] | None = None, head: str = "",
         page_render: Callable[[str, Mapping[str, object]], str] | None = None,
         fallback: str | None = None, check_optionals: bool = False,
         max_body: int = 10 * 1024 * 1024) -> ASGIApp
```

One adapter covers **every ASGI host** (FastAPI, Starlette, Quart, or a bare uvicorn run), built on the ASGI protocol itself, so it imports no web framework (not even Starlette) and adds no dependency. Mount it wherever the host mounts sub-applications: `app.mount("/board", asgi_app(...))`. `resolve()` supplies the domain service, sync or async, as [Where the service comes from](#where-the-service-comes-from) describes; the other arguments match `mount_flask`. Because the mount core is already async, an ASGI host awaits it natively, so there is no `asyncio.run` bridge and none of its loop-affinity limits for async database resources. The four routes resolve against the path remaining after the host's mount prefix. All baked URLs are **relative** (`cmd/…`, `island.js`), so the adapter never needs to know the prefix. A slash-less page request 307-redirects to the trailing-slash form first, since that is what relative URLs resolve against. Entity selection is by query string here, because path converters belong to the host router, which an ASGI sub-app does not see. A `:virtual` or `:upload` component raises at mount, as there is no `/window` or upload route; the Flask adapter refuses both too. `max_body` caps a command's request body in bytes, at 10 MB by default as on Litestar: past it the answer is a 413. A server such as uvicorn sets no limit of its own. A method other than `GET` or `HEAD` on the page or `island.js` is a 405. A repeated query or form key keeps its first value, as on Litestar and Flask.

## Neutral mount core: `situ.mount.core`

The portable mechanics all three adapters wrap, importing no web framework:

- `dispatch_command(app, *, name, arg, form, facade, make_context) -> CommandResult(html, patch) | None`. `None` is a command that cannot run, which the adapter answers with a 404. A `CommandError` the command raises propagates for the adapter to answer.
- `error_body(status, detail=None)`: the JSON error body every adapter answers with; `detail` defaults to the status's standard phrase.

The others are `page_data(app, template, ctx, ...) -> (template_name, context_dict)`, `view_from_query(app, query)`, the compile cache (`compile_mount` / `compile_tree`), the wire helpers (`parse_id_set` / `coerce_int`), `fallback_page(app, template, markup, ...)` (the degraded page a mount's `fallback=` serves; call it from an `except` block, and it logs the active exception), and the live `Hub`. An adapter takes the framework's request, calls these, and wraps the result in that framework's response.

## Component resolution: `situ.Context`

```python
Context.of(mapping: Mapping[str, Path]) -> Context
Context.from_dir(directory: Path, *, aliases: Mapping[str, str] | None = None) -> Context
ctx.merge(other: Context) -> Context
ctx.with_override(tag: str, stem: Path) -> Context
ctx.get(tag) / ctx.tags()
```

A `Context` is immutable and value-hashable, so it works as a cache key. `from_dir` derives `PascalTag` from `snake_case.html` filenames; `aliases` covers the exceptions.

## Compiler: `situ`

```python
load_front_end(stem: Path) -> FrontEnd            # read a .py/.html pair
parse_front_end(template: str, python_src: str) -> FrontEnd
splice_tree(root: FrontEnd, children: dict[str, FrontEnd]) -> FrontEnd
compile_app(front: FrontEnd, cmd_base: str = ...) -> EmittedApp
```

`EmittedApp` has `front`, `page_template`, `region_template`, `island_js`, `local_init`, `url_names`, `set_names`, `routes`, `handler_kinds`, `signal_table`, `context_keys`, `loop_field_reads`, `object_field_reads`, `unguarded_optional_reads`, `looped_names`, `island_loc`, `window_handler`, `path_args` and `binder_kinds`. `path_args` maps each command to the number of path arguments the command's route accepts, 0 or 1. `binder_kinds` is the set of binder kinds the template uses, without the colon (`"text"`, `"upload"`, `"combobox"`), so a mount can tell which routes and which client runtime a page needs. `CompileError` is the one exception type every layer raises.

Paths for wiring: `situ.static_dir()` (the runtime, `_rt.min.js` and the readable `_rt.js`), `situ.templates_dir()` (the default `page.html`). `situ.runtime_url(prefix="/static")` is the runtime's URL with a hash of the file as its query, `/static/_rt.min.js?v=1a2b3c4d`; a mount's page template gets it as `situ_runtime_url`.

## Server data: `situ`

```python
seed(**signals: object) -> dict[str, object]     # in context(): return {"doc": doc, **seed(rows=rows)}
parse_id_set(raw: str) -> list[int]              # a Local[set] JSON array off the wire -> ints
```

`seed()` gives `Local` signals their values from the server: the page starts with them and gets them back after each command, so a server-backed list can live in the browser with no region re-render. See [the wire protocol](../concepts/wire-protocol.md). `parse_id_set` decodes a `Local[set]` sent with a command; malformed input gives an empty or partial list, since the value comes from the client.

## Siting contract: `situ.siting`

`Site` (str-enum: `local` / `url` / `server` / `synced`), the `TRANSPORT` table it indexes, and `SIGNALS_HEADER = "X-Siting-Signals"`. A component's declared signals are modelled by `situ.compiler.frontend.Signal`, one record per name with the signal's site, default and declared type, plus the projections over them (`local_init`, `url_names`, `set_names`, `signal_table`) are pure functions beside it.

## Kit: `situ_ui`

```python
situ_ui.STATIC          # Path to ui.css + widgets.js — serve beside situ.static_dir()
situ_ui.component(name: str) -> Path     # one component's stem
situ_ui.kit() -> Context                 # the whole kit as a resolution Context
situ_ui.css_path() -> Path
```

## declui: `situ.declui`

```python
Field(label=None, label_field=False, hidden=False, secret=False, widget=None,
      control=None, component=None, binds=None,  # widget="custom": inline markup OR a component tag, + the attrs it binds
      search=False, labels=None, badge=False, format=None, source=None,
      required=False, filter=False, link=None, in_=None,
      visible=None, editable=None, valid=None)

mount_model(..., components=None)   # a Context resolving a widget="custom" component= tag

Screen(model: type, zones={}, rules=(), object_editable=None, row_links=())
zones(**named: Sequence[str]) -> Mapping[str, tuple[str, ...]]

Rule(selectors: Mapping[str, Any], properties: Mapping[str, Any])   # the rule cascade
Force(value: str)                                                   # stop a predicate AND-chain
RowLink(label: str, href: str, visible: str | None = None)         # a per-row navigation link
TrackerTheme(...)                                                   # per-slot CSS class overrides

action(func=None, *, label=None, visible=None, message=None, bulk=False)

mount_model(*, path: str, screen: Screen, screens: Sequence[str] = ("form",),
            rows: Sequence[object] = (), choices: Mapping[str, Any] | None = None,
            service_type: type | None = None,           # one of these two makes a server mount:
            resolve: Callable[[], object | Awaitable[object]] | None = None,  # see "Where the service comes from"
            facade: Callable[..., Any] | None = None,
            context: ... | None = None, template: str = "page.html",
            meta: Mapping[str, str] | None = None, theme: TrackerTheme | None = None,
            page_size: int | None = None, after: str | None = None,
            components: Context | None = None,          # resolves a widget="custom" component= tag
            new_link: tuple[str, str] | None = None,    # (label, url): a "New" link in the tracker header
            guard: Guard | None = None) -> Router       # as mount_component's: gates the page, commands, upload

Redirect(url: str)                       # from `situ` — return it from a command to navigate on success
CommandError(status: int, detail: str)   # from `situ` — raise it from a command to answer with a 4xx
explain(screen: Screen, field: str, operation: str) -> str          # trace a field's rule resolution
clamp_offset(offset, total, page_size) -> int  ·  require_total(ctx) -> ctx
read_model(cls: type) -> list[FieldSpec]
generate_form / generate_list / generate_master_detail / generate_server_tracker / generate_table / generate_write_form
```

## Infrastructure: `situ.infra`

`templating.render_string` (the shared Jinja string renderer); behind the `[sqlalchemy]` extra, `infra.db` (an async engine helper) and `infra.di` (a Dishka session provider). `infra.di.SessionProvider` yields one `AsyncSession` per request with no transaction open, and never commits for you: the facade owns the transaction, so wrap a write in `async with session.begin():`. A write left uncommitted rolls back at the end of the request; committing at scope exit would also commit what a failed command had already written.

## CLI: `situ`

Installing situ puts a `situ` command on your PATH. Each subcommand also runs as `python -m situ.<name>`.

```text
situ new NAME [--to DIR] [--server] [--force]
```

Scaffold a component's two sibling files. `situ new Counter --to components` writes `counter.html` + `counter.py` already obeying the rules that fail with no message when broken: every reactive element inside the single `<div data-region>`, and `data-region` first on that div. `--server` also declares a `Server` facade and an `async` command, so a starting file shows both the client and the server side. `--force` overwrites an existing pair.

```text
situ rules [--out PATH] [--check]
```

Generate [the dialect rule reference](dialect-rules.md) from the compiler's own rule table: each operand-type pair, its lowering and the soundness note attached to it. `--check` exits non-zero if the committed page is stale; `make lint` runs it, so the reference cannot drift from the compiler.

## CLI: `situ check`

```text
situ check ROOT [--from-dir DIR]... [--kit]
python -m situ.check ROOT [--from-dir DIR]... [--kit]
```

Two static passes over a component tree, with no server boot, exiting non-zero and listing **every** problem it finds:

1. **Tag resolution.** Each PascalCase `<Tag/>` the tree reaches must resolve.
2. **The column contract.** Each `<th>` must honour the [DataGrid column](../ui/catalog.md) `data-*` contract: the mistakes the kit's runtime *cannot* catch, because a `<th>` it never reads is a `<th>` it cannot reject: a knob on a `<th>` with no `data-field` (silently dropped), a typo'd attribute name (`data-formatt`), an unknown value, or a value on a presence-only knob (`data-pin="false"` **pins** the column, because the engine tests only for the attribute's presence).

`--from-dir` adds a directory context (repeatable); `--kit` includes `situ_ui.kit()`. Run it in your lint loop.

## CLI: `situ.declui explain`

```text
python -m situ.declui explain MODULE:SCREEN FIELD [OPERATION]
```

Traces how one field resolves under the [rule cascade](../declui/rules.md): the field context, its rank-1 `Field`, the matching rank-2 rules in rank order, and the effective result, computed over the `Screen` with no server boot. `OPERATION` defaults to `form`.
