# `@hamur/devtools`

The devtools of `hamur dev`: a toolbar on every page and a panel at `<app.baseURL>_hamur/devtools/`. They are plain DOM, custom elements and CSS, with no UI library, so they look and work the same with every adapter. Install it as a dev dependency and add it to `modules`; set its options under the `devtools` config key. `hamur init` writes both.

```ts
// hamur.config.ts
import devtools from "@hamur/devtools"

export default defineConfig({
  modules: [devtools],
  devtools: { shortcut: "shift+alt+d", placement: "bottom-center" },
})
```

### `default`

The module, as `defineModule({ meta: { name: "devtools", configKey: "devtools" } })`. Its setup checks `devtools`; in a build, in `hamur typegen` and with `enabled: false` it then returns and registers nothing, so no file of the module reaches `.output/` and `GET <app.baseURL>_hamur/devtools/` answers 404. In `hamur dev` it adds `@hamur/devtools/client` as a client app plugin and the dev handler of `<app.baseURL>_hamur/devtools/`, which answers:

- the panel document at `<app.baseURL>_hamur/devtools/`, with `cache-control: no-store`, `content-security-policy: frame-ancestors 'self'`, `x-frame-options: SAMEORIGIN` and `referrer-policy: no-referrer`; the panel's script is built with `Bun.build` on the first request and kept in memory, and an edit of one of its files builds it again and reloads an open panel. A failed build shows its error in the panel;
- the data routes `<app.baseURL>_hamur/devtools/api/<name>`, JSON with `cache-control: no-store` and `x-content-type-options: nosniff`, an error as `{ "error": "<message>" }`: `api/tabs` answers `{ tabs: [{ name, title, icon, view, module }], apps: [{ name, title, icon, module }] }` (a module tab's `view` as `{ type: "module" }`, its entry kept on the server) in the order `addDevtoolsTab` and `addDevtoolsApp` (`hamur/kit`) were called, `api/overview` answers `{ versions: { hamur, adapter, library, bun }, counts: { pages, serverRoutes, components, imports, modules, appPlugins, serverPlugins } }` for the Overview tab (a version that does not resolve and an unknown server plugin count are `null`); a name the dev handler does not answer goes on to the server process, where a module's door may answer it, and one no door answers is 404 `{ "error": "No devtools data route \"<name>\"" }`;
- the Storage tab's routes, answered by the server process: `GET api/storage/mounts` is `[{ mount, driver }]`; `GET api/storage/keys?mount=<m>&prefix=<p>` is `{ keys, truncated }`, sorted, at most 1000 keys; `api/storage/item?mount=<m>&key=<k>` answers GET `{ type: "json" | "text" | "bytes", value, raw? }` (bytes as hex, `raw` for bytes `setItem` did not write), PUT of the same shape as `application/json` up to 1 MiB, and DELETE 204. An unknown mount is 404 `No storage mount "<m>"`, a missing item 404 `No item "<k>" in storage "<m>"`, a key over 512 characters or holding a control character or a `.` or `..` segment 400 `Invalid storage key "<k>"`. While the tab is open, a write to a listed mount from any code is pushed to it;
- the Assets tab's route: `GET api/assets` is `[{ url, file?, bytes, type, width?, height?, module? }]`, every file of `public/` and every public asset a module added (`addPublicAssets`, `emitPublicAsset`; those carry `module` and are read-only), sorted by path; `type` is `image`, `font`, `text` or `other` by extension, and `width` and `height` are read with `Bun.Image` for a raster image. `POST api/assets` takes `multipart/form-data` with one `file` part and writes `public/<name>`, answering 201 with the file's row (200 when `?overwrite=1` replaced one): a file over 50 MB is 413 `File is over 50 MB` (from `Content-Length`, or once the streamed body passes it), a name holding `..`, `/` or `\` 400 `A file name may not hold .. or a slash`, an empty name, a control character or a leading dot 400; an existing file without `overwrite=1` is 409 `public/<name> exists; send overwrite=1 to replace it`, and a URL a module asset holds 409 `<url> comes from <module>; module assets are read-only`;
- `POST api/rpc/<name>`, which calls the `extendDevtoolsRpc` function `<name>` with the JSON body (an empty body is `undefined`) and answers `{ "result": … }`. Only a registered name is called (else 404 `No devtools RPC "<name>"`); another method answers 405; a body that is not `application/json` or does not parse answers 400 `The body of a devtools RPC call must be JSON`; a body over 1 MiB answers 413; a function that throws answers 500 with its message and logs `[hamur] devtools RPC <name> threw: <message>`; a result `JSON.stringify` cannot write answers 500 `devtools RPC <name> returned a value that is not JSON (<reason>)`. The function gets the body only, never the request's headers or cookies.

A module tab (`view: { type: "module", entry }`) is bundled with the panel and drawn in its content area; an iframe tab shows `src` in a frame.

Every path below `<app.baseURL>_hamur/devtools/`, the panel's socket `/_hamur/reload?devtools=1`, `/_hamur/logs` and `POST /_hamur/overlay` is a dev data route: `hamur dev` answers it only from the same origin (`Origin` absent or the request's own origin, `Sec-Fetch-Site` absent, `same-origin` or `none`; else 403 `Cross-site request to <path> refused`), and only to a local request (a loopback peer, a `localhost` or loopback `Host`, `Sec-Fetch-Site` absent, `same-origin` or `none`, and none of `Forwarded`, `X-Forwarded-For`, `X-Forwarded-Host`, `X-Forwarded-Proto`, `X-Forwarded-Port`, `X-Real-IP`, `CF-Connecting-IP`, `True-Client-IP`, `Via`, `CDN-Loop`) or one that carries the dev token. Else it answers 403 `<path> needs the dev token on this device; open a URL with ?hamur-dev-token=<token> as hamur dev printed it` and logs `[hamur] Refused <path> from <address>: no dev token` once per address.

The dev token is made when `hamur dev` starts and kept across its restarts. When the server listens on a host that is not loopback (`--host`), `hamur dev` prints `[hamur] On another device, open a URL once with ?hamur-dev-token=<token> to use the devtools`. A `GET` of any URL with `?hamur-dev-token=<token>` answers 303 to the same path and query without it and sets the cookie `hamur-dev-<port>` (`HttpOnly`, `SameSite=Strict`, `Secure` over HTTPS), whose value is an HMAC of the port keyed by the token, so it is worth nothing to another app on the same host; a wrong token answers 403 `Wrong dev token`. The runner removes every `hamur-dev-<port>` cookie from every request it passes on, so no loader, server route or log sees one.

Load errors: `devtools.enabled must be a boolean (got "yes")`, `devtools.shortcut must be a key combination such as "shift+alt+d", or false (got "shift+alt")` and `devtools.placement must be one of "bottom-center", "bottom-left", "bottom-right", "top-center", "top-left", "top-right" (got "middle")`.

### `DevtoolsOptions`

| Key         | Type                                                                                              | Default                                                                                                                                                                                                                                                                                |
| ----------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enabled`   | `boolean`                                                                                         | `true`; `false` registers nothing                                                                                                                                                                                                                                                      |
| `shortcut`  | `string \| false`                                                                                 | `"shift+alt+d"`: modifiers `ctrl`, `alt`, `shift`, `meta`, each at most once, joined by `+`, then one key `a`–`z`, `0`–`9` or `f1`–`f12`, case ignored; it opens and closes the panel on the page and closes it inside the panel, except while typing in a field; `false` turns it off |
| `placement` | `"bottom-center" \| "bottom-left" \| "bottom-right" \| "top-center" \| "top-left" \| "top-right"` | `"bottom-center"`: where the toolbar sits; the viewer's own choice in the panel's settings wins                                                                                                                                                                                        |

The panel's settings belong to the viewer, not the repository: hidden tabs, tab order, theme (`system`, `light`, `dark`), scale (0.75 to 1.5), toolbar placement, panel height, `panel` and `pill`, kept in `localStorage` under `hamur:devtools`. `panel` is `{ "dock": "bottom" }` or a floating rectangle `{ x, y, width, height }` in pixels, clamped into the viewport (at least 240 by 120 px). `pill` is `{ x, y }`, the toolbar button's place as fractions of the viewport from 0 to 1, and wins over `placement`. The panel's open state and tab are not settings: they are in `sessionStorage` under `hamur:devtools:view`. A missing or broken value, or a broken field, reads as the default; Reset position in the settings tab drops `panel` and `pill`.

## `@hamur/devtools/client`

The client app plugin the module adds in `hamur dev`; an app never imports it. Once the app has mounted, it appends one `<hamur-devtools>` element to `document.body` (and puts it back when the app replaces the body's children). Everything the element draws is inside its shadow root, so the app's DOM outside the element is unchanged: a button that opens the panel in an `<iframe>` docked at the bottom of the page until you move or resize it, created on the first open and kept while closed, resized from any edge or corner, moved by its header and docked again by a double click on it; the button can be dragged, and the panel can open in its own window. It sets `window.__hamur_devtools.toolbar` to `{ open(tab?), close() }`. Each devtools app (`addDevtoolsApp`) adds a button after the Hamur one: a click imports the app's entry and calls its `init` on a full-viewport canvas in the shadow root, the next click tears it down, and `ctx.setBadge` writes on the button.
