Part of [Architecture](https://docs.mapcairn.com/architecture.md), which is built from [ARCHITECTURE.md](https://github.com/MapCairn/mapcairn/blob/main/ARCHITECTURE.md) in the repository, where it is edited.

The interfaces the app depends on, each with a real adapter, a fake and a contract suite.

Add an interface only where a boundary has at least two implementations. The fake counts as the second implementation. Each port has a real adapter, a fake and a shared contract suite that runs against both, apart from `FeatureSelection`, whose one class is the SDK's store and its fake together, and `FeatureQuery`, which has no adapter in this repository: a host that supplies one runs the contract suite against it.

`MapAdapter` has one real implementation, MapLibre GL JS, and is kept for two reasons. It is the boundary between the ui and the engine, so the ui never imports `maplibre-gl`. It also lets unit tests run the ui against an in-memory fake, with no WebGL. The contract suite runs against the fake and against the real `MapLibreMapAdapter` code, but the adapter there drives a hand-written stand-in for the MapLibre map (`FakeMapLibreMap` in `packages/adapter-maplibre/src/maplibreTestEngine.ts`), not `maplibre-gl` itself, because unit tests have no WebGL. The suite keeps the two adapters in step with each other; it does not prove the stand-in matches MapLibre. The end-to-end tests are what exercise the real engine.

| Port                            | Real adapter                                                                                                                                                                                                                              | Fake                                                                                           |
| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `MapAdapter`                    | MapLibre GL JS (vector and raster styles)                                                                                                                                                                                                 | scripted in-memory map                                                                         |
| `SearchProvider`                | Nominatim                                                                                                                                                                                                                                 | scripted results and errors                                                                    |
| `SuggestionProvider` (optional) | `PhotonSuggestionProvider`, the reference host's one adapter, for the public Photon server; the SDK ships none                                                                                                                            | `FakeSuggestionProvider`, scripted suggestions, errors and holds                               |
| `LocationProvider`              | browser geolocation                                                                                                                                                                                                                       | scripted fixes and errors                                                                      |
| `SettingsStore`                 | `localStorage` with in-memory fallback                                                                                                                                                                                                    | in-memory                                                                                      |
| `DevicePreferences`             | `matchMedia` (reduced motion, fine pointer), `navigator.languages`, and `navigator.onLine` with the window's `online` and `offline` events (`online`, a hint only; the search providers' `isOnline` is fed from it by `createServices()`) | scripted values                                                                                |
| `ClipboardPort`                 | `navigator.clipboard` with a legacy fallback                                                                                                                                                                                              | recording fake                                                                                 |
| `FileSaver`                     | `Blob`, an object URL and a download link                                                                                                                                                                                                 | recording fake                                                                                 |
| `FileOpener` (optional)         | `BrowserFileOpener`: a hidden `<input type="file">`, read with `File.text()`                                                                                                                                                              | `FakeFileOpener`, a scripted picker (choose, cancel, fail)                                     |
| `UrlState`                      | location hash and `history.replaceState`; `link(value)` builds an address without writing it                                                                                                                                              | in-memory                                                                                      |
| `ThemeSource`                   | `matchMedia`                                                                                                                                                                                                                              | scripted system preference                                                                     |
| `MessageCatalogue`              | `createMessageCatalogue` (plain English strings, `Intl.PluralRules` and `Intl.ListFormat`), the SDK's dependency-free default                                                                                                             | `FakeMessageCatalogue`, scripted missing keys and overrides, recording every `t`/`plural` call |
| `LayerCatalogue`                | `createStaticLayerCatalogue` over the host's definitions, validated at start-up and ready on the first render (the reference host); `createRuntimeLayerCatalogue` for a host that loads them with its own function                        | `FakeLayerCatalogue`, scripted with `setLayers` and `setState`                                 |
| `LayerSource`                   | `FetchLayerSource` (`fetch`; feeds go through a shared response cache, an identify never does)                                                                                                                                            | `FakeLayerSource`, scripted per layer id, with its identify scripted apart from its loads      |
| `RoutingProvider` (optional)    | `ValhallaRoutingProvider`, the reference host's one adapter, for a public Valhalla server; the SDK ships none                                                                                                                             | `FakeRoutingProvider`, scripted routes, areas, errors and delays                               |
| `FeatureSelection` (optional)   | `MemoryFeatureSelection` keeps the set in memory; the reference host builds no store, so a host that wants selection supplies one, which may keep the set on a server                                                                     | `MemoryFeatureSelection`, the same class, scripted with `replaceExternally`                    |
| `FeatureQuery` (optional)       | none: the SDK and the reference host ship no query, so a host that offers selection by shape supplies one, which may ask a server                                                                                                         | `FakeFeatureQuery`, scripted with `respondWith`, `failWith` and `hold`                         |

The settings keys are `mapcairn:<name>`.

**The message catalogue.** `MessageCatalogue` (`packages/core/src/ports/messages.ts`) is how every piece of user-facing text is looked up: a flat `MessageKey` union, a `MessageParams` type giving each key's placeholders, and `t(key, params)`, `plural(key, params)` and `list(items, type)` on the catalogue itself. `createMessageCatalogue(language, catalogue, fallback)` builds the dependency-free default from a plain `Record<MessageKey, string>`, substituting `{name}` placeholders and falling back to `fallback`'s value with one `console.warn` per missing key per instance. It accepts an optional fourth argument, `{ layerTemplates, fallbackLanguage, numberingSystem, direction, isolateParameters }`, for host-keyed layer text, the fallback record's BCP 47 language (`fallbackLanguage` defaults to `en-GB`) and an `Intl` numbering system such as `latn` for numbers and days; the catalogue exposes it as `numberingSystem` (and `FakeMessageCatalogue` takes the same option), and `formatLocale(catalogue)` gives the tag with it applied, which numbers and days use in place of `language` (lists and plural selection keep the plain language). A malformed numbering system is ignored with one `console.warn`. `isolateParameters` wraps each text parameter, and each item `list` joins, in a first-strong isolate (`isolate()` in `packages/core/src/messages/isolate.ts`, which first removes any isolate control the value holds) so a name or a coordinate cannot reorder a right-to-left sentence. It defaults to on when `direction` is `"rtl"`, and `direction` defaults to what `languageDirection` reads from the tag; the web host passes the direction of its offered `LanguageOption`. Numbers are never wrapped. Left unset, numbers and days follow the language's own `Intl` defaults, calendar included, and coordinates stay ASCII either way. Plural values use the existing `one|other` form or category-keyed forms such as `one{…} few{…} other{…}`; `Intl.PluralRules` for the selected value's language selects the form, so a missing value uses the fallback language's categories. Number and day placeholders use `formatLocale(catalogue)` (the active language plus its numbering system), and list placeholders use the active language. `plural` substitutes a plain active value just as `t` does, and a count can be supplied even for a key without an English count placeholder. A host may wire a message-format library of its own behind the same interface. `EN_GB_CATALOGUE` (`packages/core/src/messages/en-GB.ts`) is the SDK's shipped English catalogue, and a lint test in `packages/core/src/lint` checks its keys, placeholders and plural categories. Components read the active catalogue with `useMessages()` and call `t`/`plural` instead of writing copy inline. What the interface says is on the catalogue: the Settings panel, the chrome (map tools, scale and readout, credits, sheet), the panels, the tools (search, pin, measure, draw, directions, locate and the tour), the Layers section with its cards, list, key and time control, the host's app shell, banners and error page, the text core's pure helpers return (announcements, descriptions, units, durations, errors), the keyboard help, and the readable text of the basemap and layer definitions (see "Definition text" below). The privacy page (`PrivacyPage.tsx`) is catalogue text too, in the `privacy.*` keys: a placeholder in a paragraph stands for a link or `<code>` span the page supplies through `MessageParts`, and its English text stays in step with the English-only `PRIVACY.md`. The browser tab title follows the language: a route exports a `handle` naming the catalogue key of its page name (`PageTitleHandle`), and `DocumentTitle` sets `document.title` from it in the browser. The deliberate exceptions are the developer design guide (built only in development and test builds), the WebMCP tool text, the SEO metadata the server renders (the English page titles, the descriptions and other tags that crawlers and link previews read, `robots.txt`, `sitemap.xml` and `llms.txt`) and programmer errors (a thrown `Error`, a `console` line), which are for developers and crawlers and stay in English. Nothing in the repository is translated, and only text the host app shows is. Credits and licence names are legal text, and provider names stay as supplied. Layer feature templates use plain strings by default; host-keyed translations are taken from `MessageCatalogue.layerTemplates` only when they preserve the source field and formatter placeholders. A missing entry falls back silently, while an invalid supplied translation warns once per key per catalogue instance before falling back to the source text. Vector-tile labels remain property-only. `SkipLink` and `StatusMessage` fall back to the SDK's English when there is no `ServicesProvider` above them (`useOptionalMessages`), and the server-rendered `ChromeSkeleton` takes its words as props, built from the host's default-language catalogue by `chromeSkeletonCopy`, because it uses no hook.

**Catalogue checks.** `checkMessageCatalogue` checks a host's catalogue against the English catalogue, and `npm run catalogue:check` reports missing and unchanged values; the reference host uses the checker in its Afrikaans catalogue tests. `checkDefinitionTexts` does the same for a host's own `HostText` keys: it walks any definitions generically (skipping only the positions typed as a `LayerTemplate`, such as a card's `title`) and reports each key a catalogue's `definitionTexts` lacks or holds blank, and each entry nothing uses.

**The language setting.** `Settings.language` is a BCP 47 tag, or `null` for "follow the browser", kept on the device with the other settings and never in a shared link. A host offers languages as a `LanguageCatalogue` (`packages/core/src/messages/languageCatalogue.ts`): plain data with `languages` (each a `tag` and a `label` written in that language), `defaultLanguage` and `load(tag)`, which returns a `MessageCatalogue` or a promise for one, so a host can lazy-load every language but its default. It is built with `createLanguageCatalogue` and passed as the optional `Services.languages`; like `BasemapCatalogue` it has one shape and no second implementation, so it has no fake and no contract suite, and `portRegistry` lists it under `DATA_SERVICE_NAMES`. `resolveLanguage(choice, offered, browserLanguages, fallback)` (core, a pure function beside `resolveTheme`) picks the offered `choice`, else the first of the browser's languages (`DevicePreferences.get().languages`) that the host offers, by exact tag and then by language subtag (`af-ZA` gets an offered `af`, `en-ZA` an offered `en-GB`), else the default. `ServicesProvider` mounts an `ActiveMessagesProvider` that holds the active catalogue in state for the whole tree and that `useMessages()` reads: it starts on `Services.messages`, so the first client render matches the server's, resolves the language when the setting or the browser's languages change, and calls `load`. While a lazy load is pending the previous catalogue stays, a load that finishes after another language was asked for is dropped, and a load that fails keeps the previous catalogue and warns, then is tried again the next time the setting or the browser's languages resolve, even to the same tag (a load in flight or finished is not repeated). The provider also keeps the failed tag and whether it is being loaded again in a second context, read with `useLanguageLoad()` (`failed`, `retrying` and `retry`; `undefined` without `Services.languages`), and `retry` asks for the failed language again whatever the setting is, which the settings-change retry cannot do when the person chooses the language that already failed. The failed state clears when a load succeeds or another language is asked for. Without `Services.languages` the catalogue is always `Services.messages`. The host's root error page runs outside `ServicesProvider`, because the boundary replaces the root route, so `useErrorPageMessages` (`packages/web/src/app/`) does the same job on its own: it renders English first (the server cannot read storage), then asks `resolveDeviceLanguage` (`packages/web/src/composition/storedLanguage.ts`, which reads the stored language and the browser's languages through the settings and device-preference adapters, neither of which throws, and calls `resolveLanguage`), loads the language through `loadLanguage`, and sets `<html lang>`; a blocked store, a garbled value or a failed load leaves English. The Settings panel shows a "Language" `SegmentedControl` (Automatic, then each offered language by its own name, each marked with `lang`) only when the host offers more than one language. `<html lang>` follows the language in use: the server renders the host's default (it reads neither `Accept-Language` nor a cookie, so a cached page does not vary by language, and a returning visitor who chose another language sees one render of the default first), the inline theme script sets it before paint from the stored tag when the host offers it (so its hash in `public/_headers` and `constants/securityHeaders.ts` covers it), and the app layout (`routes/app.tsx`) keeps it in step afterwards. The reference host builds its catalogue in `packages/web/src/i18n/hostLanguages.ts` from `OFFERED_LANGUAGE_OPTIONS` (`i18n/offeredLanguageOptions.ts`), which lists English and Afrikaans, adding each language's build-time direction to make `OFFERED_LANGUAGES`; its Afrikaans `MessageKey` catalogue (`i18n/af.ts`) loads on demand.

Each `LanguageOption` may override its direction. Otherwise `languageDirection` reads the locale's text information, falling back to `ltr` for an invalid tag or unavailable information. The reference host resolves its offered directions in the Vite configuration, so the server and client use the same build-time values. It renders `<html dir>` for the default language alongside `lang`; the theme bootstrap embeds the offered tags and directions, and the app layout and error page update both attributes when messages load. The fixed English product page restores `ltr`. A host changing the bootstrap's inputs updates both CSP hashes.

**Messages from pure helpers.** The pure helpers that used to return English (everything in `announce.ts` and `draw/describe.ts`, `describeDistance`, `describeArea`, `describeDuration`, the routing error text, `describeSlotStart` and the rest of the date words) now return a `Message`: a `key` and its `params`, built with `message(key, params)`. A text placeholder may hold another `Message` (a distance inside "Total distance {distance}"), and `formatMessage(catalogue, message)` formats the inner ones first, then calls `plural` when the parameters include a numeric count and `t` otherwise. A function that can say one of several things returns a union of keyed messages, and `joinMessages` and `appendMessages` put several into one by nesting them in `common.followedBy`. The same holds for the rest of the text core produces: `formatDuration` ("1 h 5 min"), `travelModeLabel` and `describeStop` return messages; the fault in WKT text a person typed or opened is a `Message` on `GeometryError.description` (its `message` stays English, for logs) and reaches an import refusal as its `detail`; the default name of a shape ("Polygon 1") comes from `shapeLabel(kind, serial, catalogue)`, which a host-built reducer (`createDrawReducer(catalogue)`) uses while the plain `drawReducer` names in English; and `FormatContext` (what a layer card or list template formatter such as `relative` is given) carries the `catalogue`, as `shapeClasses`, `shapeEvaluator`, `evaluateShapeStyle` and `legendFor` take one to word an interval ("10 to 99 per km²"). `shapeAppearances` gives how each class is drawn with no words, for a map engine. The catalogue formats the parameters for its own language: a number with `Intl.NumberFormat`, a `Date` as a UTC day in words, a list of strings with `Intl.ListFormat`. Nothing in core branches on a language. `formatNumber(value, locale, options)` and `formatZoom` take the catalogue's `formatLocale(catalogue)`. `formatDistance`, `formatArea` and `computeScaleBar` take the catalogue itself and write a reading through `units.reading` (`{number} {symbol}`, so a language sets the order and the spacing) with the `units.symbol.*` key of the unit, so Afrikaans can write "myl" for a mile; the scale bar's line keeps its fixed maximum width whatever the label. `formatLatitude` and `formatLongitude` take the hemisphere letters (`hemispheresFor(catalogue)` reads them from the four `format.hemisphere*` keys), so Afrikaans can say N, S, O and W. The digits of a coordinate keep a dot in every language, so a label still reads back through `parseCoordinates`, which takes the same `hemispheresFor(catalogue)` letters as an optional second argument and reads them as well as N, S, E and W (so Afrikaans "26.20410° S, 28.04730° O" reads back). Before it reads, `normaliseCoordinateText` rewrites other scripts' digits, minus signs and separators as ASCII and `withDecimalCommas` reads a decimal comma in two layouts; the rules are in "Search by place name or coordinates" in `sites/docs/docs/guides/using-the-reference-site.md`. A third optional argument, `coordinateWordsFor(catalogue)`, adds the whole words of the `format.word*` keys (north, south, east, west, degree, minute, second, each a word or several separated by a space), so "26.2041 suid, 28.0473 oos" reads in Afrikaans; the English words are always read and win over a clashing word. `coordinateSearchResult` passes both. `formatLatLng`, the value that is copied, is unchanged. "UTC" stays in every language: `format.utcTime` and `format.utcRange` carry it, and only the word that joins the time to the day is the catalogue's to change.

**Definition text.** The words a person reads in a definition are a `DefinitionText` (`MessageKey | string | HostText`): a layer's `name`, `description`, `group`, `disclaimer` and `emptyText`, a control's `label` and `description`, a segmented option's `label`, the labels of a style's classes, size stops and heatmap words, a sort's `label`, the card's link label, the detail source's `label` and `dataCost`, a tile layer's legend labels, a `BasemapDefinition`'s `name`, and the keyboard help lines (`MAP_KEY_HELP`, `DRAW_KEY_HELP`, a host's `keyHelp`). `resolveText(catalogue, text)` (core) is the one resolver: when `text` is a key of the English catalogue (a runtime check, so an unknown dotted string passes through) it returns the catalogue's value; when it is a `HostText` (`{ key, text }`, a host's own key with its source text) it returns `MessageCatalogue.definitionTexts[key]` when the catalogue has an own, non-blank entry and the source `text` otherwise, warning once per key for each catalogue about a blank one; and anything else comes back unchanged, so a third-party definition that writes plain strings keeps working. A plain string is never taken for a host key: a host opts in by writing the object. `HostText` keys stay out of the typed `MessageKey` union, and the keys of `definitionTexts` are separate from the keys of `layerTemplates`. `validateLayerDefinition` accepts a `HostText` wherever it accepts a `DefinitionText` and requires a non-empty `key` and `text`, but `attribution` text stays plain. Nothing branches on an id. Each place that shows a definition resolves it: `legendFor`, `shapeClasses` and `featureTitle` take the catalogue, the map reads the rest with `useResolveText()`, and a pure helper that builds an announcement from a layer's name passes `textOrMessage(name)`, a `Message` (or a `HostText`, as a `MessagePart`) the live region formats in the active language (a list placeholder may hold such messages, as `announce.layersDidNotAnswer` does). The reference host's own definitions use keys: `basemap.<id>.name` and `layer.<id>.…` in one block at the end of `MessageKey`, with the exact former English in `EN_GB_CATALOGUE`. One definition, Earth at night, writes its `name` and `description` as host text instead (`{ key, text }`, with the English as the source `text`); `afDefinitionTexts.ts` translates them and `host-text.spec.ts` checks them in Afrikaans in the browser, with the source text as the fallback in a language that has no entry. Card titles and lines, list secondary lines, feed-shape labels, and range and interval units are `LayerTemplate`s: a plain string stays as written, or `{ key, text }` names a host catalogue entry and keeps the source `text` as a fallback. `MessageCatalogue.layerTemplates` carries those entries outside typed `MessageKey`; a translation is used only when it has the same field and formatter placeholders as the source, in any order. Vector-tile labels remain one plain property name for the map engine, and credits are legal text. The host's layer order is fixed at start-up from the English words, so it does not follow the language. A tour step (`TourStep`) and the welcome and ending copy of `TourCard` are `DefinitionText` as well, and the step announcement reuses the card's `tools.tour.progress` message.
