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.

MapLibre GL JS is the only map engine, and the ui never imports it. The adapter and the engine styles are in `packages/adapter-maplibre`, whose entry module exports `createMapLibreMapAdapter`, its options type `MapLibreMapAdapterOptions` and `TILE_LAYER_SLOW_MS`, and nothing else, so the class, the loader and the test options can change; its built declarations do not import `maplibre-gl`. The host imports it in `createServices()` only. `MapView` takes an adapter factory (`() => MapAdapter`) from the services, mounts one adapter in a host element and wires events to the rest of the ui. Changing basemap calls `setBasemap` on that adapter. It avoids `transformStyle` because a swap with it set waits for the current style, so a failed swap could not put the last basemap back. The adapter builds an inline raster style for a `raster` source and loads the style URL for a `vector` source. For a `hybrid` source it loads the label style and, in its `style.load` handler, before data layers, keeps only the line and symbol layers that draw from one of `labelSourceLayers`, less those in `labelOmitLayers`, so no area of the style (land, water, buildings, road areas) covers the imagery, and removes any source only the removed layers used. It then adds the imagery as a raster source capped at `maxTileZoom` and a layer under the rest, so MapLibre enlarges the deepest real level instead of asking for more, and under that a background layer in the basemap's `swatch` colour, so a dark basemap is not pale before its imagery draws. If that fails, a pending mount or swap fails with it, so a swap puts the last basemap back. No code names a basemap. `MapLibreMapAdapter.ts` keeps the map and the lifecycle (`mount`, `destroy`, the pending style load and `style.load`) and holds one module for each other job: the camera (`camera.ts`), the flat or globe placement of overlay marks (`overlayPlacement.ts`), the options of the map on screen (`engineMap.ts`), the engine loader (`engineLoader.ts`, which is the only adapter module that imports `maplibre-gl` at run time), and the modules named below for style, data layers, edit handles, image export and failures. The factory `createMapLibreMapAdapter` takes one option, `loadWorkerUrl`, a function that resolves to the URL of the engine's worker as the host serves it. The adapter does not import the worker: Vite's `?worker&url` query lives in the host's `packages/web/src/adapters/maplibre/workerUrl.ts`, which adds the policy's cache key to the URL and which `createServices()` passes in, so the package holds nothing that only Vite understands. `loadEngine` calls it when the first map mounts, before it calls the engine's `setWorkerUrl`; a rejected loader fails the mount as `load-failed` and is asked again on the next one. The timing options the tests use (`workerFailureGraceMs`, `imageTilesWaitMs`, `tileLayerSlowMs`) are a second constructor argument that the factory does not take, and `TILE_LAYER_SLOW_MS` is the only constant `MapLibreMapAdapter.ts` re-exports, which the entry module exports in turn, for `e2eTimers.test.ts`. The style code is in `basemapStyle.ts`, as functions of the map and a basemap that hold no state: `styleFor`, `composeHybrid` and `applyZoomLimits`. The adapter calls them when it draws a basemap and in its `style.load` handler.

- **Zoom** is normalised to the 256 px tile convention (OpenStreetMap tile numbering). MapLibre counts 512 px tiles, so the engine zoom is the normalised zoom minus one. That offset is one constant, converted only inside the adapter. For the 256 px raster style, the tile level equals the normalised zoom. The URL, the saved view, the scale bar, the zoom level in the readout and the tests use the normalised value only.
- **Overlays** (pin, measure line, accuracy circle, the open card's ring) are drawn once, in a single overlay layer positioned with `adapter.project` and hidden with `adapter.isVisible` when they are on the far side of a globe. The pin, the measure line, drawn shapes, handles and directions stops are placed through `placePoint` and `placePath` in core (`packages/core/src/globe`), described under Flat or globe.
- **Data layers** are the exception, because hundreds of points or a tiled image belong in the engine. `setFeatureLayer` draws points whose colour, size and shape the ui has already worked out, `setTileLayer` draws raster or WMS tiles (`{bbox-epsg-3857}` is filled by MapLibre), requests no tile wholly outside the definition's optional `bounds` (`[west, south, east, north]`, west less than east; a tile that straddles an edge is still drawn whole), and changes opacity in place, `setShapeLayer` draws an affected area, and `removeLayer` removes any of them. They stack tiles, then shapes, then points, above the basemap, may be set before mount, and are drawn again after every `style.load`, because a full style swap drops them. Points are symbols whose images are rasterised in `markerImages.ts`, so squares and triangles carry meaning beside colour. A tap within a fingertip of a point emits `featureTap` before `click`. The planning code is in `dataLayerPlan.ts`, as functions that hold no state and change nothing in the engine (`planDataLayer`, `basemapFont`): each turns a kept layer into the source, the engine layers and the ids a tap can land on. The label font is read through a function the adapter passes in, at the moment a plan needs it. `DataLayerStore` in `dataLayerStore.ts` keeps the layers, adds the marker and pattern images, and draws, erases and orders what the plans describe. The adapter holds one and stays the owner of the map and of when its style is ready. The store's interface is `set`, `setTiles` (which only changes opacity when the tiles are the same), `remove`, `restore` (every kept layer again, then one ordering, called from `style.load`), `styleChanged` (forgets the label font read from the old style), `hitsAt` and `tapAt`. It draws only on the map the adapter hands it through `readyMap`, tells the adapter through `changed` that a layer was set or removed, and reports a tile layer's source being drawn or erased through `TileSourceRegistry`, a hook that `TileLayerTraffic` in `tileLayerTraffic.ts` implements with the tile layers' counters (see "Failures"). It imports only types from `maplibre-gl`.
- **Styled shapes, vector tiles and heatmaps.** `setStyledShapes` draws polygons or lines whose look (colour, opacity, hatching, dash and width) the ui has already worked out per shape, and optional label text. `setVectorLayer` draws vector tiles whose features the ui never sees, so the port carries a rule (`fixed`, `category` or `steps` over one property) that the adapter compiles to engine expressions, with a zoom window for the layer and for each source layer. `setHeatmapLayer` draws point density from loaded points or from a vector source layer. Layer windows are normalised zoom, converted inside the adapter; a source's `minzoom` and `maxzoom` are tile levels and are passed through. One data layer owns several engine layers (a fill, a hatching layer, outlines per dash, labels), and the adapter keeps their ids so it erases and orders them as a unit. Hatching is a data-driven `fill-pattern` over images rasterised in `patternImages.ts`; dashes cannot be data-driven, so there is one engine layer per dash style, filtered by value. Labels need glyphs, so they are drawn only when the basemap's style has a glyph source and a literal font stack; a raster basemap has neither, and the list, card and legend carry the words there. Stacking, lowest first: tiles, vector tiles, styled shapes, affected areas, heatmaps, points.
- **Hits and bounds.** `featuresAt(point)` lists every tappable feature under a pixel, topmost first and once each (points and lines within a fingertip, polygons exactly), and `featureTap` carries the topmost one together with that list in `hits`. `getBounds()` is the box the map shows. Vector tile features and heatmaps are not tappable, and neither are the pixels of a raster tile layer: a tap on one is asked of the layer's `identify` service through `LayerSource.identify`, not through the engine.
- **Image export.** `toImage(options)` returns a PNG blob. The adapter hands the work to `MapImageExporter` in `imageExport.ts`, which keeps only the queue of requested exports (below) and reads seven things from the adapter through `MapImageExportHost`: the mounted map (none before `mount` or after `destroy`), whether a basemap swap is pending, the overlay placement on a given map, the size and view of the map on screen, a signal that aborts when the adapter is destroyed, a style version that changes with the basemap, data layers (a tile layer included, unless only its opacity changed) and projection, and a way to open a render map (below). The exporter asks the host again after each wait, so a swap or a `destroy` that happens during an export is seen.
- **Image export, step by step.** The exporter does not set `preserveDrawingBuffer`, which would cost every frame; it repaints, copies the canvas inside the engine's `render` event, where the buffer is valid, draws the credit text along the bottom edge, and encodes it. With no `size`, `pixelRatio` or `view` it copies the map on screen, requests nothing, and goes on with what has loaded if a tile is stuck for `IMAGE_WAIT_MS`. It fails with a `MapEngineError` of reason `export-failed` (including a browser that blocks reading the canvas, an adapter that is not mounted or is destroyed during the export, and a basemap swap that is still loading or starts before the pixels are copied).
- **Image export, a requested size and view.** `size` (the map's size in CSS pixels, defaulting to the map on screen), `pixelRatio` (image pixels for each CSS pixel, defaulting to 1 so the result does not depend on the device) and `view` (a `bounds` box, or a `center` and normalised `zoom`; always north-up, defaulting to where the map on screen looks) are drawn on a render map: a second MapLibre map the adapter builds (`RenderMapOpener` in `renderMapOpener.ts`) from `getStyle()` of the map on screen, in a hidden, attached container of the requested size (sized through the style object, which the production Content Security Policy allows). MapLibre sizes its canvas as `round(ratio * floor(width))` from the container, so `planRequestedImage` rounds the CSS size to whole pixels first, and the default size is the host's `clientWidth` and `clientHeight`, not the fractional bounding box. The map on screen is only read, so it is not resized or moved and emits no event, and the URL hash does not change. The render map has the same sources and layers and adds no source or origin of its own, but it is a separate map with its own caches: it fetches again the style's tile descriptions, sprite sheets and glyph ranges and the tiles of its view, unless the browser's HTTP cache has them, from the providers the map on screen already uses. The request volume is that of one more map at the requested view; nothing new is sent to anyone, so the privacy position is unchanged. `getStyle()` leaves out the images added with `addImage`, so the adapter copies its own marker and pattern images (names with the `mapcairn-marker:` or `mapcairn-pattern:` prefix) and sets the app's projection after `style.load`. It has no interaction, no fade (`fadeDuration: 0`) and a `maxCanvasSize` of `MAX_IMAGE_SIDE_PX`, since MapLibre would otherwise lower the ratio of a canvas over its default 4096 px. After the new map is built, a box view is checked by comparing the map's `getBounds()` with the box (`coversBounds`, within `FIT_TOLERANCE_DEGREES`, 0.0001): MapLibre keeps its default camera when it cannot fit a box and keeps the camera inside what the projection allows, so a box in a tall, narrow container, or below the basemap's lowest zoom, comes back cropped, and that is refused as `invalid` ("The view cannot be framed at this size.") instead of saving the wrong place. A box on a globe is refused as `invalid` for now (`refuseBoxOnGlobe` in core, called by the fake and the adapter): the fit runs on the flat camera before `style.load` sets the projection, and on a sphere a box can lie beyond what is shown, so no check made at that point can promise the framing; a centre and zoom is drawn on either. When a request names only a size or pixel ratio, the view on screen is used with its latitude clamped to the Web Mercator limit (a globe can look beyond it) and its longitude wrapped. A box across the antimeridian is given in the short form that `boundsOfPoints` returns (the west inside -180 to 180, the east past 180) and the render map is fitted to it as it is: after a fit the engine's `getBounds()` holds the box in the same unwrapped longitudes, so `coversBounds` compares them directly. The long form (the west beyond the east) is refused as `invalid`. What is still refused: a west outside -180 to 180 (so the `getBounds()` of a world-wide view, which reaches beyond -180 or 180, is not an acceptable `bounds`) and an east more than 360 degrees past the west. A very wide box that passes these can still come back `invalid` ("The view cannot be framed at this size.") from the framing check, because the engine may have to crop it; the real engine was probed only for boxes up to 20 degrees wide. The exporter waits for the render map's `idle` event, which a map over a sparse tile layer would never fire (a 404 tile asks for no frame), so the adapter paints it every `TILE_SETTLE_NUDGE_MS` until it does. Unlike the map on screen, which gives up painting when a tile never answers (see "Tile layers that find no tiles"), the render map is painted until it goes idle or the export finishes or times out and removes it. It then copies the canvas as above and removes the map and the container on every path, including `destroy()`, which stops a wait for tiles at once with the not-mounted error. Requested images are drawn one at a time: each waits for the ones asked for before it, so only one extra WebGL context and canvas exist at a time, and a failure does not hold up the next. The queue has no cap and a caller cannot cancel an export in it yet. The size and view are read when an export is asked for and the style when its turn comes, so the adapter counts changes to the basemap, data layers and projection (`styleVersion`, read when queued and again at the turn): an export that waited while one changed fails with `export-failed` ("The map changed while the image was waiting.") instead of mixing the new style with the old view and credits. A `destroy()` while the pixels are being copied waits for the 3 second frame timer. Credits and marks are drawn at `pixelRatio` image pixels to a CSS pixel, and marks are placed with the render map's own camera. A request is checked first by `planRequestedImage` in core, which the fake and the adapter both call, before any engine work. A size or ratio that is not a finite number above zero, a view that cannot be drawn (a latitude beyond the Web Mercator limit, a longitude beyond -180 to 180 for a centre or a box's west, or a box whose south is not below its north, whose west is not below its east, or whose east is more than 360 degrees past its west), or an image of under one pixel, is a `MapImageExportError` of kind `invalid`. An image over `MAX_IMAGE_SIDE_PX` on a side or `MAX_IMAGE_PIXELS` in all, counted in image pixels, is `too-large`, and so is a canvas the device could not make at the size asked for. Tiles that have not loaded after `IMAGE_TILES_WAIT_MS` (15 seconds) are `timed-out`. `MapImageExportError` extends `MapEngineError` with reason `export-failed`, so a caller that handles only that still works. Known limits: a second map that cannot start (the likeliest cause is memory pressure, on iOS especially) is an `export-failed` error with no `kind`; a tile that errors (a 404, a 429, a blocked response) still lets the map settle, so the image is saved with a gap and no error, as on screen; and a basemap swap is refused only while it is still loading when the pixels are copied (or when a queued export starts), so one that starts and finishes during the tile wait is not noticed and the image shows the basemap the map had when the export started. The Save image button passes none of these options and is unchanged.
- **Image export, drawn shapes.** Overlays the ui draws itself (the pin, the measure line, the open card's ring) are not in the image, except marks the caller passes as `drawing` (positions, two hex colours): the exporter places them with the same `placePath` and `placePoint` as the overlay (curves, copy of the world and horizon) and strokes them over the copy with a halo, so drawn shapes are saved as they were seen. The scale bar, legend and title are not drawn into an image yet.
- **Edit handles.** `setEditHandles` gives the adapter the points the person may press and drag (id, position, kind: vertex, midpoint or radius). The ui draws them in the overlay; the adapter only owns the gesture, because only the engine can stop a press from also panning the map. The gesture code is `EditHandleController` in `editHandles.ts`: the adapter holds one, forwards the engine's pointer events to it, and gives it the overlay placement and two callbacks for `handleDrag` and `handleHover`; it holds the handles, the press in progress, the hover and the dropped click, and keeps no state outside the instance. Handles are placed with `placePoint`, as the overlay draws them, so a handle beyond the horizon of a globe cannot be pressed and one just across the antimeridian is pressed where it shows. A press within reach of a handle (12 px for a mouse, 22 px for a finger, the nearest wins, chosen by `pressHandle` in core so both adapters agree) calls `preventDefault` on MapLibre's `mousedown` or one-finger `touchstart`, is reported as `handleDrag` (`start`, then `move` once the pointer leaves the click tolerance, then `end`, with `moved` false for a tap), and its `click` is dropped. `handleHover` reports the handle under a mouse. Handles live on the controller, not in the style, so they survive a basemap swap, and `MapView` cancels a pending long-press when a press starts on one.
- **Flat or globe.** `Settings.projection` (`"flat"`, the default, or `"globe"`) is the one setting for the map's shape. It reaches the adapter as data: `MapMountOptions.projection` on mount, and `setProjection(projection)` when it changes. The adapter calls the engine's `setProjection` (`mercator` or `globe`) after every `style.load`, so a first mount and every basemap swap keep it, and the app's setting always wins over a style's own `projection` (VersaTiles Colorful asks for a globe). No code branches on a basemap id. Zoom stays the normalised 256 px convention, the address hash is unchanged, and the camera stays north-up with no pitch, so a globe is a different drawing of the same view. `isVisible(latlng)` is the engine's own horizon test (`transform.isLocationOccluded`) and is always true on a flat map; on a globe `project` still returns a pixel for a place on the far side, so every overlay checks `isVisible` and leaves out a pin, vertex or handle beyond the horizon.
  - _Cost of the switch._ Measured in Chromium with a 4x CPU throttle and software GL, the first switch from flat to globe on a page is one long task of about 165 ms on the world view (about 235 ms with a measure line and the population layer on), almost all of it the engine's first globe frame: building the globe shader programs and drawing the globe's tiles. The adapter asks the engine for the shape once per change (never again on `style.load` unless a style was loading), the React render, the overlay placement and `setProjection` itself are each well under 50 ms, and a second switch on the same page has no long task, so there is nothing of the app's to defer. Switching back to flat takes 50 to 145 ms. A shorter first switch would need a visible busy state or a shader warm-up, which this document does not describe because neither is built.
  - _Placing marks._ `placePoint` and `placePath` (core, `globe/placement.ts`) take a `MapPlacement` (the shape, the view, `project` and `isVisible`). The engine's `project` places a longitude on the copy of the world it names (190 is one world east of -170) and MapLibre wraps nothing, so a point is drawn on the copy nearest the view centre and every segment of a path goes the short way, across the antimeridian when that is shorter. Positions are only unwrapped for drawing; stored, exported and linked positions keep their own longitudes, and the adapter brings `unproject` and event positions into [-180, 180). A polygon's area is measured with its edges taken the short way too.
  - _Curves._ On a globe each segment is cut along its great circle (`densifyAlongGreatCircles`), the path the measured distance runs along, into pieces short enough to stay within `GLOBE_CHORD_TOLERANCE_PX` (0.5 px) of the arc: a chord of angle θ on a globe of radius R pixels strays at most Rθ²/8, so the step is √(8 · 0.5 / R), with R from `globeRadiusPixels` (MapLibre's `getGlobeRadiusPixels`: 256 · 2^zoom / 2π / cos(centre latitude) in the normalised zoom). That is about 18 degrees at zoom 0, 2.2 at zoom 6 and 0.28 at zoom 12, with at most `MAX_GREAT_CIRCLE_STEPS` (1,024) pieces a segment. A piece that goes over the horizon gains a point where it does (12 halvings), so a line stops at the edge of the disc, and `visibleRuns` splits a path into the parts in sight, wrapping round a ring's closing edge. A closed shape is filled only while all of its outline is in sight. Edge midpoint handles sit on the great circle on a globe (`editHandlesFor(…, projection)`), and picking a shape (`pickShape`) uses the same placement. A flat map draws straight segments, as before. Data layers and the directions route are drawn by the engine and are not curved by the app.
  - _Space around the globe._ MapLibre clears the canvas around the sphere to transparent and draws no atmosphere unless a style has a `sky` (none of the site's do), so the space is the map region's own background. `MapView` renders `data-projection` on the host from its first render, and on a globe the host and the engine container (`packages/adapter-maplibre/src/styles.css.ts`) take the `mapGlobeSpace` token instead of `mapBackground`; a flat map is unchanged. Before the app mounts, the inline theme script also reads the stored map shape (`PROJECTION_STORAGE_KEY`) and marks the root with `data-map-shape="globe"`, and the server-rendered placeholder takes the same token under that mark, so a globe started in either theme does not flash the pale ground first. The script's hash in `public/_headers` and `constants/securityHeaders.ts` changed with it.
  - _Scale._ MapLibre sizes the globe so a feature at the view centre is as large as on the flat map, so the scale bar, which reads the centre, is the same on both. The sphere has one scale, so on a globe `metresPerPixel(lat)` returns the centre's resolution for any latitude (`mapMetresPerPixel`), which sizes the accuracy circle of a fix away from the centre correctly; between normalised zoom 12 and 13, where the engine blends into the flat map, the two differ by under one percent.
- **Engine CSS** lives in one file, `packages/adapter-maplibre/src/styles.css.ts`. It styles MapLibre only, scopes its rules under the host's `data-map-host` attribute (and `data-projection`), both of which `MapView` sets, hides MapLibre's own controls, replaces fonts and focus rings, and sets the map background from the tokens. `MapLibreMapAdapter.ts` imports it, so it is compiled into `@mapcairn/adapter-maplibre/styles.css`, which a host outside this repository imports once. The reference host resolves the package's source and gets the rules through its own vanilla-extract plugin when `createServices.ts` imports the factory, so it does not import the stylesheet. `MapView.test.tsx` checks the two attributes where they are set, and `basemap.spec.ts` checks in a browser that the engine container has the map background and that no engine control shows, which fails if the styles stop reaching the page.
- **Loading** is lazy. The MapLibre module imports `maplibre-gl` dynamically the first time the map mounts. The adapter reports `loading` while the style, or the style of a requested basemap, is loading, and while the basemap's own sources are not all in (any source whose id does not start with `mapcairn:`, read from the engine's style when it loads, and each asked `isSourceLoaded` on every source event, error and frame while the map is busy, so a tile answered with a 404, which fires no event, still ends it; a style with no source of its own is in once the engine goes idle). It reports `load` and settles a waiting mount at the moment they are all in, rather than waiting for the engine's own `load` and `idle`, which wait for every source, data layers included; `idle` clears the same state as a final safety. A data layer's tiles never hold `loading`, because a tile that never answers keeps the engine from going idle for good and would leave the map region `aria-busy` for as long. A feed layer reports its own status, and a tile layer reports `tileLayerSlow` when none of its tiles has loaded for `TILE_LAYER_SLOW_MS` and `tileLayerUnavailable` when the map settles with none loaded (see "Tile layers that find no tiles"). The first does not wait for the engine to go idle, which a tile that never answers prevents, so `loading` is not the place to show a layer's tiles.
- **User zoom.** The adapter emits `userZoom` only for zoom gestures the engine handles (wheel, pinch, double-click), which MapLibre marks with the input event. `MapView` adds the zoom keys and exposes both as `onUserZoom`, so the app announces the settled level after every zoom the person makes and never after one made in code.
- **Failures.** The code is in `failureDetection.ts`: `FailureDetection` classifies the engine's `error` events and owns the counters and timers described here, in `basemapTiles.ts` (the basemap's tiles), `tileLayerTraffic.ts` (each tile layer's), `workerFailureCheck.ts` (the worker grace check) and `repaintUntilIdle.ts` (the painting that lets a map settle). It tells the adapter what it found through a small set of reports (`tileError`, `basemapUnavailable`, `fatalError` and the three tile layer reports), and asks the adapter's lifecycle only for the pending mount or swap and to reject it, so the adapter stays the owner of that lifecycle. The busy state is `BasemapLoadState` in `basemapLoadState.ts`. Tile and source failures are `tileError`, and the map keeps working: one tile error is never fatal. The adapter counts the tiles of the basemap's own sources (any source whose id does not start with `mapcairn:`, so data layers do not count; for a hybrid basemap only the imagery, because its labels can load while the imagery is down) from the moment its style loads. If some have failed and none has loaded when the map goes idle, it reports `basemapUnavailable` with that basemap (the one whose style loaded, captured then, because the report can come before the mount has resolved: MapLibre fires `load` and the first `idle` in one render), at most once per style load; an expired certificate or a host that is down looks like this. Once any tile of the basemap has loaded, nothing more is reported for that style, because later failures look the same as a patchy connection or a few missing tiles, and leaving a basemap the person can already see would be worse than the general tile error. `MapView` passes the report on as `onBasemapUnavailable(basemap)`, and the host (`useBasemapChoice.unavailableNow`) marks the basemap unavailable for five minutes (`useBasemapAvailability`), goes back to the previous basemap or the default (never one already marked), and says so; with nothing left it stays and only says so. A basemap the person chose in this session was saved when its style loaded, so the choice saved before it is put back; a saved or linked basemap the person did not just choose is not rewritten by an outage, only by going back or dismissing the message, which saves the basemap the map went back to. A source-less error before the pending style document has loaded (`style.load`) is that document failing, and rejects the mount or basemap swap; a sprite or glyph failure comes after it and is a `tileError`. A failed swap puts the last basemap that loaded back, so the map keeps working: `MapView` reports it through `onBasemapError`, not as an engine error, and the app saves a basemap choice only once it has loaded, then shows "That basemap could not be loaded." with "Use previous basemap". A start that fails to load a basemap other than the default (a saved or linked one whose provider is down) falls back the same way: `useMapEngine` mounts again when a different basemap is asked for after such a failure, the host (`useBasemapChoice.mountFailed`) asks for the default and shows the same banner, and going back saves the default so the next start no longer asks for the failed one. A failure of the default itself, or without WebGL, is not about the basemap and keeps its own message. MapLibre reports every worker `error` event with one message, whether the worker never started or threw while running, so after load the adapter waits up to five seconds: if the map goes idle or has everything loaded, it is a `tileError`; otherwise `fatalError` (reason `stopped`), and the app shows "The map stopped working" with Reload, as an alert. A worker error during the first load rejects the mount. A missing WebGL2 context is recognised by MapLibre's exported `GPUInitializationError`.
- **Tile layers that find no tiles.** A raster tile data layer is judged by its own tiles, and its failures are not the general `tileError`. From the moment `setTileLayer` draws its source (a new `tiles` template, or a basemap swap drawing it again; an opacity change redraws nothing and counts on), the adapter counts the tiles of that source it asks for (`sourcedataloading`), gives up on (`sourcedataabort`) and loads (`sourcedata`). While a tile of the layer has been asked for and not answered, and none has loaded, the adapter also starts a wait of `TILE_LAYER_SLOW_MS` (10 seconds) from the first tile asked for; later tiles do not restart it. When it ends with a tile still outstanding, the adapter emits `tileLayerSlow` with the same layer id and `tiles` template, once for that drawing and never once any tile of the layer has loaded; it does not wait for `idle`, so a provider that never answers is reported. The figure is a judgement, not a measurement: long enough that a provider that is merely slow to render a tile is not flagged, and shorter than `TILE_SETTLE_GIVE_UP_MS`, which is counted from the last tile asked for and so never ends before it. The painting goes on meanwhile, so a tile answered late with a 404 can still turn the report into `tileLayerUnavailable`; a layer that has both reported slow first. The option `tileLayerSlowMs` overrides the wait in a test. When the map goes idle with tiles asked for and none loaded, it emits `tileLayerUnavailable` with the layer id and the `tiles` template it was drawn from, once for that drawing, and never once any tile of the layer has loaded. A provider that has no tile for what was asked (NASA GIBS for a half hour it has not published answers each with a 404 that carries open CORS headers) raises no engine `error`, so a count of failures could not see it; and because that 404 fires no event and asks for no new frame, the map is never painted again and never reports `idle`, so while tile layer tiles load the adapter paints the map every `TILE_SETTLE_NUDGE_MS` until it does. A tile of the basemap's own sources being asked for while the map is busy starts the same painting, so a basemap tile answered with a 404 is seen to be in; it stops at `idle`, or when the basemap is in and no tile layer has a tile outstanding, so a basemap tile that never answers does not keep the map painting. A tile that never answers keeps the engine from going idle however often the map is painted, and the counts cannot tell it from a 404, so the painting also stops 30 seconds (`TILE_SETTLE_GIVE_UP_MS`) after the last tile of a tile layer or the basemap was asked for, and starts again when one is asked for later. A layer whose only tile never answers is therefore never reported as unavailable (that report waits for `idle`), but it is reported as slow, and a 404 that arrives later than that after the last request is not seen until the next pan or zoom. An `error` event for a tile layer's source (a failed request, a blocked CORS response) is counted the same way and no longer raises the general `tileError`, so the "Check your connection" banner is left to the basemap and the other sources. A tile layer whose tiles partly load, or fail after some loaded, therefore says nothing. `MapDataLayers` passes the slow report to `useDataLayers.reportTilesSlow(id, tiles)`, which ignores it unless `tiles` is still the layer's current URL and the layer is on, then keeps the layer's status as `tiles-slow` until its tiles change, it is turned off, a tile loads or the layer is reported unavailable, and announces "Rainfall: Still waiting for imagery. The provider may be slow or not answering." once, politely and with `keep`, because the person turned the layer on and would otherwise see nothing. It passes the unavailable report to `useDataLayers.reportTilesUnavailable(id, tiles)`, which ignores it unless `tiles` is still the layer's current URL, then keeps the layer's status as `tiles-unavailable` until its tiles change (a control that is in the URL), it is turned off or a tile loads later, and announces it once, politely. After a transient failure (offline, a server error, a rate limit) the tiles can load on a later pan or zoom: the first tile of a layer that has reported (slow, unavailable or both) loads, and the adapter emits `tileLayerRecovered` with the same layer id and `tiles` template, once for each drawing that reported and never for a layer that has not reported. `MapDataLayers` passes it to `useDataLayers.reportTilesRecovered(id, tiles)`, which ignores it unless the layer is showing the slow or unavailable status for those tiles, then clears the status and announces "Rainfall: imagery is showing again." once, politely. A date or time control that changes the tiles still clears the status and restarts counting, so a recovery for the old tiles is ignored. Once tiles of a drawing have loaded, the layer says nothing more for it (the existing rule for a layer whose tiles fail after some loaded). The adapter counts afresh, and so can report and recover again, whenever the layer is drawn again: new `tiles`, or a redraw with the same tiles such as a basemap swap. A redraw with the same tiles keeps a report (slow or unavailable) that had loaded no tile, because the ui still shows it, so the first tile after the redraw ends it; an opacity-only `setTileLayer` draws nothing again and changes nothing. If the adapter reports the same tiles again after a recovery, the hook shows the status and announces it again, and the next recovery clears it. There is no Try again action: the control is the way to ask for another time, and panning or zooming asks for new tiles.
- **Referrer for layer tiles.** The engine makes the tile requests, so the adapter gives its maps (the one on screen and an export's render map) a `transformRequest`, `DataLayerTileRequests` in `dataLayerTileRequests.ts`. The data layer store registers the tile URL template of every source it draws that requests tiles (raster and vector, whatever the provider) and drops it when the layer is erased. A request whose URL matches a registered template gets `referrerPolicy: "no-referrer"`, so a layer's provider never learns which site the visitor is on; every other request, the basemap's included, is left to the page's `Referrer-Policy`, because a basemap provider may ask for the site's origin. A placeholder stands for text without `/`, `?`, `&` or `#`, so a layer's template never matches a basemap URL that differs in path. The policy holds only while MapLibre loads raster tiles with `fetch`, so neither map sets `refreshExpiredTiles: false`, which would load them through an image element that has no referrer policy (a test pins it). Nothing in it names a provider or a layer.
- **No WebGL** means no map. There is no fallback basemap. The app shows a plain message in place of the map ("MapCairn needs WebGL to draw the map.") with advice to try a different browser or turn on hardware acceleration. `MapUnavailable` draws it inside the map region, so the region and the skip link still work, and announces it once, assertively, through the shared announcer rather than being a live region itself. It has no Retry, because mounting again would fail the same way.
