{
  "version": 3,
  "sources": ["basemap_download_core.js"],
  "sourcesContent": ["/*\n * static/js/basemap_download_core.js \u2014 Pure tile-URL helpers for the\n * map's basemap download controls (SNOW-521 per-region rework;\n * SNOW-522 re-adds a client-side tile-math port for the custom-area\n * control).\n *\n * Dependency-free IIFE attaching ``self.pwaBasemapDownloadCore`` \u2014 same\n * idiom as ``basemap_cache_core.js`` (frozen export, no side effects).\n * Loaded on the page (window context) BEFORE ``static/js/map.js`` in\n * ``map.html``, unlike ``basemap_cache_core.js`` which is only ever\n * ``importScripts``'d into the service worker \u2014 this module has no SW\n * dependency, so it's a plain deferred ``<script>`` tag.\n *\n * SNOW-521 replaced the viewport-anchored \"Download basemap\" control\n * with per-region download: each region's tile coverage is precomputed\n * server-side (``regions.services.basemap_tiles`` \u2014 see that module's\n * docstring for the stored blob shape) and served over the API, so the\n * per-*region* download does no tile enumeration or byte-estimate\n * arithmetic of its own \u2014 ``rangesToTileURLs`` below still just turns\n * that server-computed data into URLs.\n *\n * SNOW-522 re-introduces the tile-index/byte-estimate arithmetic\n * client-side, deliberately, for the *custom-area* download: a\n * user-drawn bbox (the map panned/zoomed under a fixed framing\n * rectangle) is not precomputable server-side the way a region's fixed\n * boundary is \u2014 there is no stable ID to precompute against, and the\n * live \"up to N MB\" readout has to track every frame of that pan/zoom\n * with no network round-trip. ``lonLatToTile``/``tileRangesForBBox``/\n * ``tileCount``/``centreTile``/``buildBlob`` below are therefore a\n * DELIBERATE re-port of ``apps/regions/services/basemap_tiles.py``'s\n * pure functions of the same names (module docstring there has the full\n * algorithm rationale) \u2014 this is not drift back to a client that forgot\n * the math moved server-side; the two now legitimately coexist for two\n * different download shapes. Kept honest against the Python by a shared\n * golden vector asserted in both ``tests/js/test_basemap_download_core.js``\n * and ``tests/regions/services/test_basemap_tiles.py`` \u2014 see either\n * test's comment for the paired assertion. That shared vector is a\n * convention, not a mechanism: nothing fails the build if the two drift,\n * so treat any change to the Python tile math as also owed here.\n *\n * Coordinate convention: **(lon, lat) order**, matching\n * ``basemap_tiles.py``'s deliberate carve-out from the project's usual\n * (lat, lon) argument order \u2014 see that module's docstring. Kept\n * identical here so a reader porting between the two never has to\n * mentally swap axes.\n *\n * SNOW-583 clips a REGION download to its real boundary plus a margin\n * tile server-side (``apps.regions.services.basemap_tiles.\n * build_region_blob``), so a region's ``z`` entry is no longer always the\n * 4-int rectangle ``[xmin, xmax, ymin, ymax]`` \u2014 it is now\n * ``{\"<y>\": [xmin, xmax]}``, one row span per present row. The\n * CUSTOM-AREA blob ``buildBlob`` (below) produces is UNCHANGED and stays\n * rectangular \u2014 a user-drawn rectangle genuinely is one \u2014 and a response\n * served from the stale window (`max-age=300`,\n * `stale-while-revalidate=86400`, SNOW-902) can still hand back an\n * old-shape rectangle until its revalidation lands. ``zoomRows`` is the\n * one accessor every consumer of a blob's ``z`` routes through so both\n * shapes are handled in exactly one place.\n *\n * Public API \u2014 attached to ``self.pwaBasemapDownloadCore``:\n *\n *   zoomRows(zEntry)\n *     Normalises one zoom level's ``z`` entry \u2014 either shape \u2014 to\n *     ``{\"<y>\": [xmin, xmax]}``. See the SNOW-583 note above; every\n *     function below that walks a blob's tiles goes through this rather\n *     than assuming a rectangle.\n *   tileSources(spec) / tileSourceCount(spec) / tileSourcesKey(spec) /\n *   tileURLs(sources, z, x, y) / sourceScaledMb(mb, spec, count?)\n *     SNOW-843: the tile-source group. A basemap is one or more vector\n *     SOURCES, each with one or more hostnames MapLibre round-robins\n *     between per tile (``urls[(x + y) % urls.length]``) \u2014 so \"the tile\n *     URL\" is a list, not a string, and a download that stored a single\n *     template pinned a fraction of one layer. Every function below that\n *     builds or reads a tile URL routes through these. See ``tileSources``\n *     for the accepted shapes (a legacy template string included). SNOW-868 makes\n *     ``sourceScaledMb`` price a tile PER BASEMAP rather than at one\n *     global worst case, and recompute from the blob's ``count`` when the\n *     caller has it so the documents allowance is not multiplied by the\n *     source count.\n *   basemapKeyForTileSources(spec) / bytesPerTileForBasemap(key) /\n *   bytesPerTileForSources(spec)\n *     SNOW-868: which basemap a resolved tile-source spec belongs to, and\n *     what one of its tiles costs. Resolved from the source template's\n *     HOST rather than the basemap picker \u2014 see\n *     ``basemapKeyForTileSources`` for why that matters. The measurements\n *     behind the figures are in ``BYTES_PER_TILE_BY_BASEMAP``'s comment.\n *   basemapsForGround(ground, activeKey, countriesByKey, extent) /\n *   groundInSwitzerland(bbox, extent) / countriesForBBox(bbox, features) /\n *   recordBasemaps(record) /\n *   recordHoldsBasemaps(record, keys) / basemapSourceCount(key) /\n *   basemapScaledMb(mb, key, count?) /\n *   isFetchableTileTemplate(url) /\n *   tileSourcesFromStyleDocuments(styleJson, tileJsons) /\n *   renderDependencyUrlsFromStyle(styleUrl, styleJson) /\n *   glyphPrefixFromStyle(styleJson)\n *     SNOW-1478: which maps a download over some ground saves (Swisstopo\n *     in Switzerland, whatever is on screen), the maps a stored area holds\n *     (its ``basemaps`` list, or one entry from its legacy fields), and a\n *     map's tile sources and render dependencies from its documents, for\n *     a map that is not on screen.\n *   rangesToTileURLs(spec, blob)\n *     Expands a full basemap_download blob's ``z`` tile-index ranges\n *     (as fetched from ``/api/region-basemap-tiles/?id=...`` OR produced\n *     locally by ``buildBlob`` below) into the full list of tile URLs \u2014\n *     one per tile PER SOURCE, each at the host MapLibre will ask it\n *     from. Returns ``[]`` for an unresolvable ``spec`` or ``blob``, or a\n *     blob with no ``z`` ranges.\n *   lonLatToTile(lon, lat, z)\n *     Web Mercator ``[x, y]`` tile indices for ``(lon, lat)`` at zoom\n *     ``z`` \u2014 mirror of ``basemap_tiles.lon_lat_to_tile``. Not clamped\n *     to the valid ``[0, 2**z - 1]`` range; ``tileRangesForBBox`` clamps\n *     explicitly, matching the Python.\n *   tileRangesForBBox(bbox, minZ, maxZ)\n *     ``{\"<z>\": [xmin, xmax, ymin, ymax]}`` for every zoom in\n *     ``[minZ, maxZ]`` \u2014 mirror of ``basemap_tiles.tile_ranges``, same\n *     clamping.\n *   tileCount(ranges)\n *     Total tile count across every zoom level in ``ranges`` \u2014 mirror of\n *     ``basemap_tiles.tile_count``.\n *   centreTile(bbox, z)\n *     The tile at ``bbox``'s centre point, at zoom ``z`` \u2014 mirror of\n *     ``basemap_tiles.centre_tile``.\n *   buildBlob(bbox, minZ, maxZ, ceilingMb?)\n *     The full blob (``{band, count, mb, over_ceiling, centre_tile, z}``)\n *     \u2014 mirror of ``basemap_tiles.build_blob`` \u2014 produced in the SAME\n *     shape ``rangesToTileURLs`` already consumes, so a\n *     locally-built blob and a server-fetched one are interchangeable.\n *     ``ceilingMb`` is what ``over_ceiling`` is measured against; omitted,\n *     it falls back to ``DOWNLOAD_CEILING_MB``. Every page caller passes\n *     the DEVICE's ceiling (``map_basemap_downloads.js``'s\n *     ``basemapDeviceCeilingMb``) \u2014 see ``deviceCeilingMb`` below.\n *   budgetScaleForBBox(bbox, minZ, maxZ, sourceCount?, ceilingMb?,\n *   bytesPerTile?)\n *     The largest factor in ``[0, 1]`` by which ``bbox`` may be scaled\n *     about its centre while its download still fits under that same\n *     ceiling. Client-only \u2014 it has no ``basemap_tiles.py`` counterpart\n *     and needs none: the server never sizes a framing rectangle. Do NOT\n *     go looking for a Python twin to keep it honest against.\n *   deviceCeilingMb(estimate)\n *     The largest download THIS device may hold \u2014 the real ceiling, and\n *     the exact inverse of ``hasStorageHeadroom``. Client-only for the\n *     obvious reason: the server cannot see a device's storage.\n *   hasStorageHeadroom(estimate, mb)\n *     SNOW-568: whether a download of ``mb`` megabytes fits in the\n *     origin's remaining storage quota, with a safety margin. Client-only,\n *     like ``budgetScaleForBBox`` \u2014 no ``basemap_tiles.py`` counterpart.\n *   MICRO_BAND, WORST_CASE_BYTES_PER_TILE, BYTES_PER_TILE_BY_BASEMAP,\n *   DOWNLOAD_DOCUMENTS_MB, DOWNLOAD_CEILING_MB, STORAGE_HEADROOM_FACTOR\n *     Constants mirroring ``basemap_tiles.py``'s module-level constants\n *     of the same name (see there for the sizing rationale) \u2014 except\n *     ``STORAGE_HEADROOM_FACTOR``, which is client-only.\n *     ``DOWNLOAD_CEILING_MB`` is now only a fallback on this side: the\n *     ceiling a page applies comes from ``deviceCeilingMb``.\n *     ``BYTES_PER_TILE_BY_BASEMAP`` is client-only (SNOW-868) \u2014 the server\n *     has no view of the requester's basemap, exactly as it has none of\n *     the source count.\n *\n * SNOW-586: a third client-only group \u2014 area identity and the standing\n * download-budget arithmetic that replaced the pinned cache's old\n * entry-count FIFO trim (``static/js/sw.js``) with one Cache Storage\n * bucket per downloaded area (``snowdesk-basemap-pinned-<areaId>``) plus\n * a byte budget, so evicting one area can never perforate another's tiles\n * \u2014 see ``docs/decisions/per-area-pinned-basemap-caches.md`` for the full\n * rationale.\n *\n *   DOWNLOAD_BUDGET_MB\n *     The standing budget across every pinned area, in megabytes (500).\n *     Client-only \u2014 unlike ``MICRO_BAND``/``WORST_CASE_BYTES_PER_TILE``/\n *     ``DOWNLOAD_CEILING_MB`` above, this has NO ``basemap_tiles.py``\n *     counterpart and must never gain one: Cache Storage is per-browser,\n *     so a standing on-disk budget is a client concept the server has no\n *     stake in (mirrors ``STORAGE_HEADROOM_FACTOR``'s same carve-out).\n *     Overridable per device via the ``meta:app`` row\n *     ``basemap.budgetMb`` (``static/js/map.js``'s\n *     ``basemapDownloadBudgetBytes``) \u2014 SNOW-588's managed-downloads UI\n *     changes that row, not this constant.\n *   PINNED_CACHE_PREFIX\n *     The Cache Storage name prefix every per-area pinned bucket shares\n *     (``'snowdesk-basemap-pinned-'``) \u2014 mirrors\n *     ``static/js/sw.js``'s ``BASEMAP_PINNED_CACHE_PREFIX`` exactly (the\n *     two can't share a literal across a page/worker boundary, so this is\n *     kept honest by ``tests/js/test_basemap_download_core.js``'s\n *     round-trip assertion against ``pinnedCacheName``).\n *   CUSTOM_AREA_ID\n *     SNOW-586 formalised this as \"the fixed area id for the one\n *     custom-area download\" (``'custom'``). SNOW-635 lets more than one\n *     custom area exist, so this is no longer that \u2014 it is now one\n *     RESERVED legacy id: the area a pre-SNOW-635 device already had\n *     downloaded keeps it (and the ``snowdesk-basemap-pinned-custom``\n *     bucket it names) when ``map.js``'s lazy migration wraps it into the\n *     new ``basemap.customAreas`` array, because Cache Storage has no\n *     rename. Every custom area downloaded since is minted a fresh id by\n *     ``generateCustomAreaId`` below and is never ``CUSTOM_AREA_ID``\n *     itself. Code asking \"is this id a custom area\" must call\n *     ``isCustomAreaId``, never compare against this constant directly.\n *   generateCustomAreaId()\n *     SNOW-635: a fresh id for a NEW custom-area download\n *     (``'custom-' + a random UUID``), minted once per confirmed run so\n *     more than one custom area can be downloaded and kept at once \u2014 a\n *     second download used to collide with the first on this very id.\n *   isCustomAreaId(areaId)\n *     SNOW-635: whether ``areaId`` names a custom-area download \u2014 the\n *     legacy ``CUSTOM_AREA_ID`` or one of the ``generateCustomAreaId``\n *     family. Every caller that used to compare against ``CUSTOM_AREA_ID``\n *     directly to mean \"is this a custom area\" (``manageRows``,\n *     ``evictBasemapAreas``, \u2026) goes through this instead, so the\n *     ``'custom-<uuid>'`` id format stays private to this module.\n *   areaIdForRegion(regionId)\n *     The area id for a region download (``'region-' + regionId``) \u2014\n *     formalises the id a region-download area is keyed under; there was\n *     no such concept before this ticket, region downloads were\n *     identified only by ``region_id`` in the ``basemap.regions`` record.\n *   regionIdForArea(areaId)\n *     The inverse: the region id a region download's area id names, or\n *     ``''`` for any other id. For a bucket a failed run left with no\n *     record (12 Nov 2026), where the id is all that says which region it\n *     was.\n *   pinnedCacheName(areaId)\n *     The Cache Storage name for ``areaId``'s pinned bucket\n *     (``PINNED_CACHE_PREFIX + areaId``).\n *\n * SNOW-856 adds a third group \u2014 the SHARED BASE LAYER, the z0-7 tiles\n * every area on the device reads when the camera is zoomed out past a\n * download's z10 floor. It is not an area: one per BASEMAP, shared by\n * every area under it, and outliving any of them. It gets its own\n * ``base-`` id namespace and therefore its own pinned bucket, which is\n * what lets the worker's read path find it with no change at all.\n *\n *   areaIdForBaseLayer(basemapKey) / isBaseLayerAreaId(areaId) /\n *   baseLayerBasemapKey(areaId)\n *     The ``base-<basemapKey>`` id, its predicate, and its inverse \u2014 the\n *     third namespace beside ``region-`` and ``custom-``. Every surface\n *     that lists or evicts areas has to exclude these. SNOW-863 added the\n *     inverse so a bucket can name its own basemap without the\n *     ``meta:app`` record, which is written later and can be missing.\n *   intersectBBox(a, b)\n *     The overlap of two bboxes, or null.\n *   baseLayerBBox(cameraBBox, styleBounds) / baseLayerBand(basemapKey?) /\n *   baseLayerBlob(\u2026) / baseLayerTileURLs(spec, \u2026)\n *     The base layer's extent, band, blob and tile URLs. The camera bbox\n *     makes the extent sufficient and the style's declared bounds make it\n *     finite \u2014 see ``baseLayerBBox`` for why deriving it from the style\n *     alone breaks on the global default basemap. SNOW-868: the BAND is\n *     per basemap too (``BASE_LAYER_BANDS``), because what it costs to\n *     cover a country is not what it costs to cover the world \u2014 the last\n *     two arguments of ``baseLayerBlob``/``baseLayerTileURLs`` are the\n *     basemap key, and omitting it keeps the default band.\n *   isTileEntryURL(url) / baseLayerStaleEntries(entries, expectedTiles)\n *     SNOW-929: a base-layer bucket now holds the documents that draw its\n *     band as well as the band itself, so the re-banding check has to be\n *     able to tell a tile from a document and judge only the tiles. See\n *     ``baseLayerStaleEntries`` for why folding the documents into the\n *     expected set would let a provider bin a 21 MB band by renaming a\n *     sprite path.\n *   planEviction(areas, incoming, budgetBytes)\n *     Given the areas currently on disk and an incoming run, decides\n *     whether it fits the standing budget and, if not, which areas to\n *     evict (oldest ``savedAt`` first) to make it fit. See its own\n *     docstring for the full contract.\n *\n * SNOW-569 and the tile-grid rework that followed it add a second\n * client-only group \u2014 the geometry a download's on-map progress grid\n * needs (``bboxPolygon``, ``tileBounds``, ``gridZoomFor``,\n * ``tileGridPlan``). Like\n * ``budgetScaleForBBox`` these have no ``basemap_tiles.py`` counterpart\n * and need none: the server never draws anything. They live here rather\n * than in ``map.js`` because they are pure functions of geometry, which\n * makes them unit-testable without a MapLibre instance \u2014 everything in\n * ``map.js`` that touches them is a side effect on a live map.\n *\n *   bboxPolygon(bbox)\n *     A ``bbox`` as a GeoJSON Polygon \u2014 the custom-area download's\n *     equivalent of a region's own boundary.\n *   tileBounds(z, x, y)\n *     The ground one tile covers, as ``[west, south, east, north]`` \u2014\n *     the inverse of ``lonLatToTile``, and the only place the grid's\n *     squares get their geometry.\n *   featureBBox(feature)\n *     SNOW-924: the lon/lat box a Feature covers, moved here from\n *     ``map.js`` (SNOW-811's copy, which is now a one-line adapter for\n *     MapLibre's nested pair). It kept company with two edge-inclusive\n *     predicates until SNOW-953 moved the selection they served to the\n *     server; their rule and its rationale now live in\n *     ``apps/regions/services/area_content.py``.\n *   bboxFromZoomRanges(z) / areaBBox(area)\n *     SNOW-924: the ground an area covers, from its stored record alone.\n *     A custom area is its ``bbox``; a region area has only ``z`` since\n *     SNOW-583, so its rectangle is derived from the tile rows.\n *   forwardContentDays(today, ceiling, onScreen)\n *     SNOW-1312: the days a download takes content for \u2014 today to the\n *     last published day, plus a forward day on screen. Never a past day.\n *   regionSheetURL(template, regionId, day)\n *     SNOW-1312: one region sheet's url, `/partials/region-sheet/<id>/?d=`.\n *   resortSheetURL(template, slug, day)\n *     SNOW-1318: one resort's place sheet url,\n *     `/partials/place-sheet/resort/<slug>/?d=`.\n *   areaContentURLs({regions, weather, resorts, days, weatherDetailTemplate,\n *                    regionSheetTemplate, resortSheetTemplate, ratingsUrl,\n *                    subdivisionsUrl})\n *     SNOW-953: the bulletin pages and weather sheets inside an area, as\n *     urls, over the answer ``/api/area-content/`` gives. It composes\n *     rather than selects \u2014 SNOW-924's rectangle test over every\n *     country's outlines is gone from here. Read its docstring for why a\n *     weather sheet is one url per location, and (SNOW-965) why it is\n *     dated with the download's day when the caller names one. SNOW-1312\n *     adds the region sheets per region and day, and the dated ratings\n *     feed per day; SNOW-1318 a resort's place sheet per resort and day;\n *     SNOW-1379 the problem-terrain feed per day, for an area with\n *     terrain tiles in a terrain country.\n *   areaItemURLs(items, templates, alreadyPlanned)\n *     SNOW-965: the reader's OWN things inside an area, as urls, over the\n *     answer ``/api/area-items/`` gives \u2014 each trip's page and its\n *     ``route.geojson``, and the weather sheet each pin borrows its\n *     forecast from. De-duplicated against what the area-content plan\n *     already holds. SNOW-1313 adds each pin's own place sheet, dated\n *     with the download's day.\n *   tourBoxes(bbox, maxSpan) / tourBoxURL(base, box) / tourPlan(answers,\n *   templates) / reportsInBox(feed, bbox) / withPublicItems(expectation,\n *   extras)\n *     SNOW-1417: an area's SAC tours, from its rectangle cut into boxes\n *     the tours endpoint answers, each tour with its Feature and height\n *     profile urls; the community reports inside the rectangle; and both\n *     onto the expectation a sync stamps, as public fields.\n *   routesInBox(feed, bbox) / resortItems(resorts, template, days)\n *     SNOW-1418: the reader's routes whose line enters the rectangle, and\n *     the resorts the content answer named with their sheet urls \u2014 the\n *     Downloads inventory's routes and resorts rows.\n *   areaItemExpectation(items, templates)\n *     SNOW-1308: the same composition as ``areaItemURLs``, kept per item\n *     with its name \u2014 what a sync stamps onto the area record so the\n *     ``/offline/`` panels can ask, offline, whether each thing is cached.\n *   withProblemTerrain(expectation, urls) / problemTerrainURL(day)\n *     SNOW-1379: the problem-terrain urls a sync warmed, added to the\n *     expectation it stamps, and one day's feed url as map.js asks for it.\n *   stampContentRecord(entry, complete, expectation, nowIso)\n *     SNOW-1308: the one rule every content sync writes back with \u2014\n *     ``contentAt`` / ``contentIncomplete`` (SNOW-932) and the ``items``\n *     expectation.\n *   favouriteSheetURL(template, uuid, day)\n *     SNOW-1313: one saved pin's place-sheet url,\n *     `/partials/place-sheet/favourite/<uuid>/?d=<day>`.\n *   weatherDetailURL(template, shortId, day)\n *     SNOW-965: one weather sheet's url, dated with ``?date=`` when a day\n *     is given \u2014 the exact url the map's sheet asks for on that day.\n *   cachedTilesFromURLs(spec, cachedURLs, zoom)\n *     The tiles a cache actually holds, read back out of its URLs \u2014 the\n *     pure half of the \"cached tiles\" overlay. A tile counts only when\n *     every source holds it (SNOW-843).\n *   gridZoomFor(blob)\n *     Which single zoom level of a download's band to draw the grid at\n *     \u2014 the deepest, so a square is a real tile.\n *   tileGridPlan(spec, blob)\n *     The grid's cells AND the run's tile URLs ordered to fill them one\n *     at a time \u2014 see its docstring for why the ordering is the feature.\n *   blobFullyCached(spec, blob, cached)\n *     SNOW-570, widened by SNOW-583: whether EVERY tile in ``blob``'s own\n *     ``z`` (either shape, via ``zoomRows``) is present in ``cached`` \u2014\n *     \"is this download actually available offline?\". Replaces the old\n *     ``downloadedIds(template, entries, cachedURLs)``/internal\n *     ``_bboxFullyCached`` pair now that the only two callers (the\n *     per-region and custom-area done-probes) each ask about ONE blob at\n *     a time rather than a whole list of regions \u2014 SNOW-583 dropped the\n *     \"Downloaded areas\" overlay's per-region ring (see\n *     ``docs/decisions/region-downloads-clip-custom-areas-dont.md``), the\n *     last caller that needed the list form.\n *   terrainClassTileURLs(template, blob, bounds, minZ, maxZ) /\n *   areaTerrainClassTileURLs(record, template, bounds, minZ, maxZ) /\n *   terrainClassTileCount(blob, bounds, minZ, maxZ) /\n *   terrainClassMb(count) / terrainScaledBytesPerTile(bytesPerTile,\n *   sourceCount, terrain, elevation)\n *     SNOW-1072: the terrain-class tiles the terrain filter paints from,\n *     over the same ground, clipped to the class tileset's own coverage\n *     rectangle and z12-14 band, and what they cost. An OPT-IN tile\n *     family: a download pins them only when its area carries the\n *     ``terrain`` flag. ``TERRAIN_CLASS_BYTES_PER_TILE`` is the per-tile\n *     figure the estimate charges.\n *   elevationTileURLs(template, blob, bounds) / elevationTileCount(blob,\n *   bounds) / elevationMb(count) / areaElevationTileURLs(record, template,\n *   bounds) / elevationAreaBoxes(records, template)\n *     SNOW-1453: the elevation tiles the 3D map draws its terrain from,\n *     pinned with terrain data: the blob's z10-13 rows clipped to the\n *     elevation coverage, plus their z7-9 parents, and what they cost\n *     (``ELEVATION_BYTES_PER_TILE``). ``elevationAreaBoxes`` is the list\n *     of downloaded areas 3D may be drawn in offline: those whose record\n *     carries today's template as its ``elevation`` stamp. Only an area\n *     on ``ELEVATION_BASEMAP_KEY`` (``elevationBasemap``), the basemap 3D\n *     is drawn on, carries them.\n *   missingRenderDependencies(depURLs, cached)\n *     SNOW-844: which of an area's RENDER dependencies \u2014 its style JSON,\n *     each vector source's TileJSON, its sprite JSON+PNG at 1x and 2x \u2014\n *     are absent from ``cached``. The second half of \"is this download\n *     actually available offline?\"; ``blobFullyCached`` above is the\n *     first, and it is deliberately left alone rather than widened. Two\n *     small pure predicates beat one big one here because the two answers\n *     drive DIFFERENT states: complete tiles with a missing sprite is not\n *     the same condition as missing tiles, and the surfaces say so\n *     differently ('incomplete' + repair vs 'idle' + download).\n */\n\n(function () {\n  'use strict';\n\n  // Mirrors apps/regions/services/basemap_tiles.py::MICRO_BAND \u2014 the\n  // custom-area download uses the same zoom band as the region download\n  // (z10-14), so the two produce directly-comparable size estimates.\n  var MICRO_BAND = [10, 14];\n\n  // Mirrors apps/regions/services/basemap_tiles.py::WORST_CASE_BYTES_PER_TILE\n  // \u2014 calibrated against seven real max-size custom-area downloads\n  // (SNOW-631), and re-checked 2026-09-07 against a real 253-tile download\n  // that averaged 34 KB a tile. See that constant's comment for why an\n  // estimate-vs-actual gap of 3x turned out not to be this number.\n  var WORST_CASE_BYTES_PER_TILE = 50 * 1024;\n\n  // SNOW-868: what a tile actually costs, PER BASEMAP. The single figure\n  // above was calibrated on OpenFreeMap and then spent on every style, so\n  // the \"up to N MB\" the UI shows was not an upper bound on swisstopo at\n  // all \u2014 a Ybrig region download reported 59.9 KB a tile against an\n  // estimate priced at 50 KB, and the promise the readout makes is that\n  // the real number comes in UNDER it.\n  //\n  // Measured 2026-09-08 by fetching real tiles, not modelled. The\n  // project's own ``build_region_blob`` expanded all 149 CH regions into\n  // their real 36,511 tile coordinates; 400 of those were sampled at\n  // random and each fetched from swisstopo (both sources) and OpenFreeMap\n  // \u2014 1,200 requests, zero failures, and the true geographic and per-zoom\n  // mix (z10 464, z11 956, z12 2,452, z13 7,412, z14 25,227) rather than a\n  // handful of town-centre tiles, which are the densest in any area.\n  //\n  //   source            mean     p50     p95      max\n  //   openfreemap       25.2 KB  17.1    76.0     186.3\n  //   swisstopo base    48.6 KB  42.9    98.8     190.2\n  //   swisstopo relief  73.1 KB  38.2    236.0    572.3\n  //   swisstopo/source  60.8 KB  40.8    171.0    572.3\n  //\n  // The Ybrig download trace says 59.9 KB per swisstopo tile. The sample\n  // says 60.8. Two independent methods agreeing to 1.5% is what made a\n  // full 4.5 GB download of every region unnecessary.\n  //\n  // What the constant has to bound is a DOWNLOAD's mean, not the fattest\n  // tile: a download averages hundreds of tiles, so only small areas carry\n  // real variance. Bootstrapped from the sample at the real CH region\n  // sizes (min 56 tiles, median 181, max 2,816), the worst-region p99 is\n  // 34.7 KB for OpenFreeMap (at 56 tiles; 30.3 at 181, 26.4 at 2,816) and\n  // 85.5 KB per source for swisstopo (74.1 / 63.9). Each constant below\n  // clears its own p99. That is also why 72 KB was REJECTED for swisstopo\n  // even though it sits well above the 60.8 KB mean \u2014 a small region would\n  // exceed it about 1% of the time, and \"up to\" would be false again.\n  //\n  // OpenFreeMap is deliberately ABSENT from ``BASEMAP_HOST_KEYS`` below\n  // even though it has an entry here: its origin is deployment-dependent\n  // (``OPENFREEMAP_STYLE_URL``, config/settings/base.py, and staging\n  // self-hosts at tiles.snowdesk-data.info \u2014 docs/runbooks/\n  // self-hosted-tiles.md), so there is no host to match on. It resolves\n  // through the fallback instead, and the fallback's 50 KB IS its measured\n  // value. Do not \"complete\" the host table with an origin staging does\n  // not use.\n  var BYTES_PER_TILE_BY_BASEMAP = {\n    // Measured, see above: mean 25.2 KB, worst-region p99 34.7 KB.\n    openfreemap_liberty: 50 * 1024,\n    // Measured, see above: 60.8 KB per source over two sources, worst-region\n    // p99 85.5 KB per source. Charged per source by ``sourceScaledMb``.\n    //\n    // 96 KB clears that p99 by 12%, and the margin is DELIBERATE, not a\n    // rounded measurement: the readout promises an upper bound, and a\n    // re-measurement is free to nudge p99 up a little. Anything that\n    // re-measures should move this constant to keep a comparable margin\n    // rather than shave it to the new p99 \u2014 the test asserts only\n    // ``> 85.5 * 1024``, so eroding the headroom to nothing stays green\n    // right up until the promise is false again.\n    swisstopo_winter: 96 * 1024,\n    // Same tile sources as winter \u2014 the two styles differ only in paint.\n    swisstopo_light: 96 * 1024,\n    // PROVISIONAL. Only CH region geometry exists in the local fixture, so\n    // there was no French region set to run the stratified sample against.\n    // This is a crude four-point sample (weighted mean ~52 KB) scaled by the\n    // same worst-region factor the CH bootstrap produced. Generous rather\n    // than accurate; nothing is blocked by it, because it already sits well\n    // above the measurement. Replace it by re-running the same stratified\n    // method against real FR region geometry, or against a real download\n    // trace.\n    ign_plan: 96 * 1024,\n    // PROVISIONAL, on the same footing as ign_plan: a crude four-point\n    // sample (~85 KB, with a fat z10 tail \u2014 one tile came back at 782 KB)\n    // scaled by the CH worst-region factor. Replace it the same way.\n    basemap_at: 144 * 1024,\n  };\n\n  // SNOW-868: host fragment \u2192 the basemap key whose per-tile figure prices\n  // it. Matched against a tile source's URL TEMPLATE, never against the\n  // picker \u2014 see ``basemapKeyForTileSources`` for why that distinction is\n  // load-bearing. OpenFreeMap is deliberately absent; see the table above.\n  var BASEMAP_HOST_KEYS = [\n    ['.geo.admin.ch', 'swisstopo_winter'],\n    ['data.geopf.fr', 'ign_plan'],\n    ['wien.gv.at', 'basemap_at'],\n  ];\n\n  // Mirrors apps/regions/services/basemap_tiles.py::DOWNLOAD_DOCUMENTS_MB \u2014\n  // the style, sprite, TileJSON and promoted glyphs a run writes into the\n  // bucket beside its tiles, which the estimate used to ignore entirely.\n  // An allowance rather than a prediction: see that constant's comment for\n  // the measured split and for why the glyph half cannot be predicted from\n  // a bbox.\n  var DOWNLOAD_DOCUMENTS_MB = 2;\n\n  // SNOW-1072: what one terrain-class tile costs (the 256 px PNGs the\n  // terrain filter paints from \u2014 tiles.snowdesk-data.info/terrain-class/).\n  // The tileset averages ~88 kB a tile; charged at 88 KiB, which sits just\n  // above that so the \"up to\" figure stays an upper bound. CH-4115\n  // (Martigny\u2013Verbier, 278 km\u00B2) is ~130 class tiles, so ~11 MB. A 204\n  // (no data, or outside z12-14) is a few hundred bytes of headers and is\n  // charged the same \u2014 an estimate that over-reads, never under.\n  var TERRAIN_CLASS_BYTES_PER_TILE = 88 * 1024;\n\n  // SNOW-1453: what one elevation tile costs (the 512 px Terrarium tiles\n  // the 3D map's terrain is drawn from \u2014 tiles.snowdesk-data.info/dem/).\n  // Sampled on 6 Nov 2026: five Alpine points at each of z10-14 came out\n  // at 125-195 KB, a mean of about 155 KB. Charged at 192 KiB, above the\n  // whole sample, so the \"up to\" figure stays an upper bound. A median\n  // Swiss region (181 basemap tiles) needs ~60 of them: ~11.5 MB charged,\n  // ~9 MB real.\n  var ELEVATION_BYTES_PER_TILE = 192 * 1024;\n\n  // SNOW-1453: the zoom band an area's elevation tiles are pinned over,\n  // and the shallowest of the parents added above it. The mesh reads the\n  // elevation about two zooms below the map (map_3d_core.prefetchDemTiles)\n  // and the hillshade one below, so z13 serves the mesh to map z15 and the\n  // shading to z14, the basemap download's own ceiling. The z7-9 parents\n  // are 3-4 tiles, and let MapLibre draw coarse relief past the area's\n  // edge rather than flat ground.\n  var ELEVATION_BAND = [10, 13];\n  var ELEVATION_PARENT_MIN_ZOOM = 7;\n\n  // SNOW-1453 review: the basemap 3D is drawn on. Mirrors\n  // map_view_core.js's BASEMAP_KEY (a test holds the two together): entering\n  // 3D swaps to it, so offline 3D can draw only where an area's download\n  // pinned THAT basemap's tiles and documents. Elevation tiles are pinned,\n  // stamped, priced and expected only for an area downloaded on it.\n  var ELEVATION_BASEMAP_KEY = 'swisstopo_winter';\n\n  // SNOW-1453: how much of a frame's band ``terrainScaledBytesPerTile``\n  // charges an elevation tile against. The elevation band stops one zoom\n  // short of the basemap's z14, and each zoom has about a quarter of the\n  // next one's tiles, so z10-13 is about a quarter of a z10-14 frame's\n  // tiles. Measured on a frame at the ceiling (~1,000 tiles) it is 0.27\n  // with the parents; a third keeps the charge above that, the safe\n  // direction for a ceiling.\n  var ELEVATION_BAND_SHARE = 1 / 3;\n\n  // The FALLBACK ceiling, used only when the device cannot say what it can\n  // hold. The real ceiling is ``deviceCeilingMb`` below: how large one\n  // download may be is a question about the device it lands on, so a\n  // constant is the wrong kind of answer \u2014 it either refuses a download a\n  // phone had room for, or lets one through that it did not.\n  //\n  // Mirrors apps/regions/services/basemap_tiles.py::DOWNLOAD_CEILING_MB,\n  // which is that module's only ceiling: the server has no view of a\n  // device, so the ``over_ceiling`` flag it stores on a region row is\n  // advisory and the client decides for itself.\n  var DOWNLOAD_CEILING_MB = 200;\n\n  // SNOW-856: the zoom band the SHARED BASE LAYER covers. An area\n  // download pins ``MICRO_BAND`` (z10-14) over its own ground; this pins a\n  // shallow band over the whole map, once per basemap, for every area to\n  // share.\n  //\n  // The gap this closes: the map's camera goes down to z4\n  // (``MIN_ZOOM``, static/js/map.js), a download's floor is z10, and\n  // nothing precached a basemap tile at any zoom\n  // (``PRECACHE_URLS = [OFFLINE_FALLBACK, RESET_SCRIPT]``, static/js/sw.js).\n  // So an offline reader who zoomed out fell off the edge of every area\n  // they owned. That was invisible until SNOW-854 closed the\n  // unclassified-cross-origin leak \u2014 before it, those tiles were quietly\n  // fetched over a connection the user had told the app not to spend, and\n  // the map drew.\n  //\n  // **The band is a function of the BASEMAP'S EXTENT, not a global\n  // constant (SNOW-868).** This is the DEFAULT \u2014 what an unknown basemap\n  // gets \u2014 and it is OpenFreeMap's, because a band's cost is set by how\n  // much ground the style covers, and the default basemap covers the\n  // world while the other three cover one country each.\n  //\n  // The history reads like a flip-flop and is not one. SNOW-856 shipped\n  // z0-9, so the base layer would abut ``MICRO_BAND``'s z10 floor with no\n  // gap. SNOW-863 trimmed it to z0-7 for everything, having measured the\n  // default basemap. SNOW-868 measured the OTHER THREE and found the\n  // ruling was right for OpenFreeMap and was never a statement about a\n  // national style. z8+z9 over each basemap's own extent:\n  //\n  //   openfreemap_liberty   33.4 + 88.0 MB  = 121 MB   (140 + 486 tiles,\n  //                                                     Alps-wide)\n  //   swisstopo (both srcs)  1.4 +  3.0 MB  = 4.4 MB   (CH)\n  //   ign_plan               2.1 +  2.3 MB  = 4.4 MB   (FR)\n  //   basemap_at            ~3.2 + ~4.1 MB  = ~7.3 MB  (AT)\n  //\n  // The OpenFreeMap figure independently reproduces the 123 MB the\n  // SNOW-863 comment carried, which is what makes the other three\n  // trustworthy. 121 MB is a quarter of the standing 500 MB budget spent\n  // before a single area is downloaded; 4.4 MB is not a price, it is a\n  // rounding error, and it buys the seam away for every Swiss, French and\n  // Austrian reader.\n  //\n  // **Do not restore the gap for the DEFAULT basemap on tidiness\n  // grounds.** The two-level gap costs nothing the reader can see there:\n  // MapLibre renders the nearest cached ancestor for a tile it does not\n  // hold (``findLoadedParent``), so z8 and z9 draw from the stored z7 tile\n  // \u2014 softer, never blank, which is the whole promise. That same mechanism\n  // is what makes the map draw coarsely outside a download's ground\n  // (SNOW-856's accepted trade), so this is not a new behaviour to reason\n  // about, just the same one over two more levels. Anything below z10 is\n  // context; detail is the area download's job, and 121 MB is not worth\n  // paying to be able to say the numbers touch.\n  //\n  // No ``basemap_tiles.py`` counterpart, and it needs none: the base\n  // layer's extent is the CAMERA's, which is a client-side constraint the\n  // server has no view of.\n  var BASE_LAYER_BAND = [0, 7];\n\n  // SNOW-868: the band per basemap, defaulting to ``BASE_LAYER_BAND``\n  // above for anything not listed. The national styles close the seam\n  // because closing it costs them 4.4 to 7.3 MB; OpenFreeMap is listed\n  // explicitly at the default rather than left implicit, so a reader can\n  // see the ruling was made for it and not merely omitted.\n  var BASE_LAYER_BANDS = {\n    openfreemap_liberty: [0, 7],\n    swisstopo_winter: [0, 9],\n    swisstopo_light: [0, 9],\n    ign_plan: [0, 9],\n    basemap_at: [0, 9],\n  };\n\n  /**\n   * The base layer's zoom band for one basemap (SNOW-868).\n   *\n   * @param {string} [basemapKey] A ``BASEMAP_STYLES`` key. Omitted or\n   *   unknown yields ``BASE_LAYER_BAND``, the default \u2014 the conservative\n   *   direction, since the default is the CHEAPEST band and an unknown\n   *   basemap is one whose extent nothing here has measured.\n   * @returns {number[]} ``[minZ, maxZ]``.\n   */\n  function baseLayerBand(basemapKey) {\n    var band = BASE_LAYER_BANDS[basemapKey];\n    return band || BASE_LAYER_BAND;\n  }\n\n\n  // Kilometres in a degree of latitude. Equirectangular, and deliberately\n  // the same figure `map_drop_zone.js` draws its ring with \u2014 the circle on\n  // screen and the tiles fetched under it have to agree with each other\n  // more than either has to be geodesic.\n  var KM_PER_DEGREE_LAT = 111.32;\n\n  // SNOW-568: the fraction of the origin's REMAINING storage quota a\n  // single download may claim. Client-only \u2014 no basemap_tiles.py twin.\n  // Half leaves room for the shell cache, the passive basemap cache the\n  // user's ordinary browsing keeps filling, IndexedDB, and the mutation\n  // queue, none of which stop growing because a download is in flight.\n  var STORAGE_HEADROOM_FACTOR = 0.5;\n\n  // SNOW-586: the standing budget across every pinned area, in megabytes.\n  // Client-only \u2014 see the module header's \"third client-only group\" note\n  // for why this must never gain a basemap_tiles.py counterpart.\n  // Overridable per device via meta:app's basemap.budgetMb\n  // (static/js/map.js's basemapDownloadBudgetBytes); SNOW-588 changes\n  // that row, not this constant.\n  var DOWNLOAD_BUDGET_MB = 500;\n\n  // SNOW-586: the Cache Storage name prefix every per-area pinned bucket\n  // shares. Mirrored as FOUR separate literals \u2014 this one, static/js/sw.js's\n  // BASEMAP_PINNED_CACHE_PREFIX, static/js/map.js's own\n  // BASEMAP_PINNED_CACHE_PREFIX, and static/js/map_layer_sync_status.js's\n  // PINNED_BASEMAP_CACHE_PREFIX \u2014 because a page script, a worker script,\n  // and this dependency-free core can't share one constant across those\n  // load-context boundaries. tests/js/test_basemap_download_core.js's\n  // round-trip assertion (areaIdForRegion / pinnedCacheName) only checks\n  // THIS module's own internal consistency \u2014 that pinnedCacheName always\n  // returns PINNED_CACHE_PREFIX + areaId \u2014 it does not and cannot compare\n  // against the other three files' copies. Cross-file agreement is a\n  // review discipline, not an enforced mechanism, the same convention\n  // basemap_tiles.py's shared golden vector documents for the Python\u2194JS\n  // tile math (see that module's own comment): a reviewer changing one\n  // copy of this prefix is responsible for checking whether the other\n  // three need the same change.\n  var PINNED_CACHE_PREFIX = 'snowdesk-basemap-pinned-';\n\n  // SNOW-586: originally \"the fixed area id for the one custom-area\n  // download\". SNOW-635 lets more than one exist, so this is now a\n  // RESERVED legacy id only \u2014 the area a pre-SNOW-635 device already had\n  // downloaded keeps it (see this module's header for why: Cache Storage\n  // has no rename). Never mint this for a NEW area (generateCustomAreaId\n  // never returns it) and never compare an id against it directly to mean\n  // \"is this a custom area\" (use isCustomAreaId).\n  var CUSTOM_AREA_ID = 'custom';\n\n  /**\n   * A fresh id for a new custom-area download.\n   *\n   * SNOW-635: every confirmed custom-area download mints its own id rather\n   * than sharing the single ``CUSTOM_AREA_ID`` \u2014 that single id is why a\n   * second download silently replaced the first before this ticket. The\n   * ``crypto.randomUUID`` fallback mirrors ``mutation_queue.js``'s\n   * ``_mintIdempotencyKey`` (and, ultimately, ``db.js``'s ``_randomHex``)\n   * for the rare runtime without it.\n   *\n   * @returns {string}\n   */\n  function generateCustomAreaId() {\n    try {\n      if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n        return 'custom-' + crypto.randomUUID();\n      }\n      var bytes = new Uint8Array(16);\n      crypto.getRandomValues(bytes);\n      var out = '';\n      for (var i = 0; i < bytes.length; i++) {\n        out += bytes[i].toString(16).padStart(2, '0');\n      }\n      return 'custom-' + out;\n    } catch (_e) {\n      // No crypto at all \u2014 a low-entropy but still-unique-enough value so\n      // the download keeps working rather than throwing.\n      return (\n        'custom-' + Date.now().toString(16) + '-' + Math.floor(Math.random() * 1e9).toString(16)\n      );\n    }\n  }\n\n  /**\n   * Whether ``areaId`` names a custom-area download.\n   *\n   * SNOW-635: true for the legacy ``CUSTOM_AREA_ID`` (a pre-SNOW-635\n   * device's one area, migrated in place \u2014 see ``CUSTOM_AREA_ID``'s own\n   * comment) OR any id ``generateCustomAreaId`` mints. Every caller that\n   * used to test ``areaId === CUSTOM_AREA_ID`` to mean \"is this a custom\n   * area\" goes through this instead, so the ``'custom-<uuid>'`` shape\n   * stays private to this module \u2014 mirrors how ``areaIdForRegion``'s\n   * ``'region-'`` prefix is never parsed out of an id elsewhere either.\n   *\n   * @param {string} areaId\n   * @returns {boolean}\n   */\n  function isCustomAreaId(areaId) {\n    return areaId === CUSTOM_AREA_ID || (typeof areaId === 'string' && areaId.indexOf('custom-') === 0);\n  }\n\n  // SNOW-847: the glyph ranges a download pins, for every fontstack the\n  // style declares. A FIXED set, not one derived from the style or probed\n  // against the host \u2014 both alternatives were measured on 2026-09-09 and\n  // neither works:\n  //\n  //   - Derivation from the STYLE is impossible without decoding the\n  //     area's own vector tiles, since a style says which fonts its labels\n  //     use but never which codepoints.\n  //   - Derivation from the HOST is impossible because every one of the\n  //     four basemaps answers HTTP 200 for all 256 ranges. An unpublished\n  //     range is a tiny stub (29-45 bytes; 627 on OpenFreeMap), not a 404,\n  //     so only the BODY SIZE distinguishes \"has glyphs\" from \"has none\" \u2014\n  //     and finding that out costs the whole download. OpenFreeMap's\n  //     ``Noto Sans Regular`` is 33.7 MB across the full space (it carries\n  //     CJK), so \"fetch what the host publishes\" is ~100 MB for that style\n  //     against a 37 MB region download.\n  //\n  // So: the blocks Alpine labels actually draw from, fixed here. Latin-1\n  // through Latin Extended-B and combining diacritics (0-1023), Latin\n  // Extended Additional (7680-7935), and General Punctuation through\n  // Mathematical Operators (8192-8959) \u2014 the last of which is what the\n  // 2026-09-08 staging trace caught missing as\n  // ``Frutiger Neue Condensed Regular/8192-8447``: en dashes, primes,\n  // vulgar fractions and arrows are ordinary furniture on a map, and the\n  // ``0-1023`` set this ticket originally proposed would not have fetched\n  // them.\n  //\n  // Measured cost of this set across EVERY fontstack each style declares:\n  // swisstopo 0.81 MB, IGN 1.49 MB, OpenFreeMap 1.83 MB, basemap.at\n  // 2.11 MB. Against a 37 MB region download that is 2-6%. Widening it to\n  // cover Cyrillic, Greek Extended and the geometric-shape blocks was\n  // costed at 4.12 MB worst case and declined: an Alpine region download\n  // renders Latin-script labels, so those bytes buy coverage nothing on\n  // the page asks for.\n  //\n  // A range a style's fonts do not publish still costs one request and the\n  // stub's few dozen bytes. That is the price of not decoding tiles, and\n  // it is paid once per download.\n  var GLYPH_RANGES = Object.freeze([\n    '0-255',\n    '256-511',\n    '512-767',\n    '768-1023',\n    '7680-7935',\n    '8192-8447',\n    '8448-8703',\n    '8704-8959',\n  ]);\n\n  // MapLibre style-expression operators. An array whose head is one of\n  // these is an EXPRESSION, so its head is an operator name and its tail\n  // holds operands \u2014 never a fontstack. Used by ``collectFontstacks``\n  // below to tell ``[\"Frutiger Neue Regular\"]`` (a fontstack) from\n  // ``[\"get\", \"class\"]`` (a property read whose operand is NOT a font).\n  //\n  // Getting this wrong in either direction is silent: too narrow and real\n  // fontstacks are missed, so those labels ship unlabelled offline \u2014 the\n  // failure this ticket exists to fix. Too wide and property names are\n  // fetched as if they were fonts, which 404s harmlessly but pollutes the\n  // record's deps with URLs no probe can ever satisfy, so the area reads\n  // ``incomplete`` for good.\n  var STYLE_EXPRESSION_OPS = Object.freeze([\n    'array', 'at', 'boolean', 'case', 'coalesce', 'collator', 'concat', 'downcase',\n    'feature-state', 'format', 'geometry-type', 'get', 'has', 'id', 'image', 'in',\n    'index-of', 'interpolate', 'interpolate-hcl', 'interpolate-lab', 'length', 'let',\n    'literal', 'match', 'number', 'number-format', 'object', 'properties',\n    'resolved-locale', 'slice', 'step', 'string', 'to-boolean', 'to-color',\n    'to-number', 'to-string', 'typeof', 'upcase', 'var', 'zoom',\n    'all', 'any', '!', '==', '!=', '<', '<=', '>', '>=',\n  ]);\n\n  /**\n   * Collect font names out of one ``text-font`` value.\n   *\n   * SNOW-847: ``text-font`` is not always a plain array of names. In the\n   * swisstopo winter style two of the five fontstacks appear ONLY inside a\n   * ``[\"match\", [\"get\", \"class\"], \u2026]`` expression, as\n   * ``[\"literal\", [\"Frutiger Neue Condensed Medium\"]]`` \u2014 a scan that reads\n   * only array-valued ``text-font`` misses them, and the towns and lake\n   * elevations they label ship without glyphs.\n   *\n   * The walk is deliberately conservative about what counts as a font:\n   * a ``literal``'s array payload, or a plain all-string array that is not\n   * itself an expression. Anything else is descended into rather than\n   * collected, so operator names and property reads never reach the URL\n   * list.\n   *\n   * @param {*} node A ``text-font`` value or any sub-expression of one.\n   * @param {Set<string>} out Accumulator, mutated in place.\n   * @returns {void}\n   */\n  function collectFontstacks(node, out) {\n    // A BARE string is never a fontstack here. It is a `match` label, or a\n    // `get`'s property name \u2014 collecting it is how an earlier version of\n    // this walk returned `class`, `town` and `lake_elevation` alongside the\n    // real fonts. A fontstack is always an ARRAY of names, whether written\n    // literally or wrapped in `[\"literal\", \u2026]`; the one place a bare string\n    // is accepted is a top-level `text-font`, handled by `styleFontstacks`.\n    if (!Array.isArray(node) || node.length === 0) return;\n    var head = node[0];\n    var i;\n    if (head === 'literal') {\n      for (i = 1; i < node.length; i += 1) {\n        var payload = node[i];\n        if (Array.isArray(payload)) {\n          for (var j = 0; j < payload.length; j += 1) {\n            if (typeof payload[j] === 'string') out.add(payload[j]);\n          }\n        } else if (typeof payload === 'string') {\n          out.add(payload);\n        }\n      }\n      return;\n    }\n    if (typeof head === 'string' && STYLE_EXPRESSION_OPS.indexOf(head) !== -1) {\n      for (i = 1; i < node.length; i += 1) collectFontstacks(node[i], out);\n      return;\n    }\n    var allStrings = true;\n    for (i = 0; i < node.length; i += 1) {\n      if (typeof node[i] !== 'string') {\n        allStrings = false;\n        break;\n      }\n    }\n    if (allStrings) {\n      for (i = 0; i < node.length; i += 1) out.add(node[i]);\n      return;\n    }\n    for (i = 0; i < node.length; i += 1) collectFontstacks(node[i], out);\n  }\n\n  /**\n   * Every fontstack a style's layers can ask for, sorted.\n   *\n   * SNOW-847. Sorted so the URL list a run fetches \u2014 and therefore the\n   * ``deps`` it records \u2014 is stable across runs of the same style, which\n   * is what lets a later probe compare the two by value.\n   *\n   * @param {Object | null | undefined} style A MapLibre style object, as\n   *   ``map.getStyle()`` returns it.\n   * @returns {string[]} Empty for a style with no layers or no labels.\n   */\n  function styleFontstacks(style) {\n    var out = new Set();\n    var layers = style && Array.isArray(style.layers) ? style.layers : [];\n    for (var i = 0; i < layers.length; i += 1) {\n      var layout = layers[i] && layers[i].layout;\n      if (!layout) continue;\n      var textFont = layout['text-font'];\n      if (textFont === undefined || textFont === null) continue;\n      if (typeof textFont === 'string') {\n        // Not valid MapLibre, but a style that ships one would otherwise\n        // lose the font silently. Only accepted at the TOP level \u2014 see\n        // `collectFontstacks` for why a bare string inside an expression is\n        // not a font.\n        out.add(textFont);\n        continue;\n      }\n      collectFontstacks(textFont, out);\n    }\n    return Array.from(out).sort();\n  }\n\n  /**\n   * Every glyph URL a download should pin for ``style``.\n   *\n   * SNOW-847: the cross product of the style's declared fontstacks and\n   * ``GLYPH_RANGES``, substituted into the style's own ``glyphs`` template.\n   * Fed into the run's URL list so glyphs are FETCHED by the download\n   * rather than promoted out of the passive cache \u2014 see ``GLYPH_RANGES``\n   * for why the range set is fixed, and ``sw.js``'s ``_promoteGlyphs`` for\n   * what promotion still covers.\n   *\n   * The fontstack is percent-encoded, matching what MapLibre requests: the\n   * names carry spaces, and a pinned entry keyed on an unencoded URL is one\n   * nothing will ever look up.\n   *\n   * @param {Object | null | undefined} style A MapLibre style object.\n   * @returns {string[]} Empty when the style declares no ``glyphs``\n   *   template or no fontstacks \u2014 both of which mean \"nothing to pin\",\n   *   never \"not yet known\".\n   */\n  function glyphURLs(style) {\n    var urls = [];\n    var template = style && typeof style.glyphs === 'string' ? style.glyphs : '';\n    if (!template) return urls;\n    var stacks = styleFontstacks(style);\n    for (var i = 0; i < stacks.length; i += 1) {\n      var encoded = encodeURIComponent(stacks[i]);\n      for (var j = 0; j < GLYPH_RANGES.length; j += 1) {\n        urls.push(template.replace('{fontstack}', encoded).replace('{range}', GLYPH_RANGES[j]));\n      }\n    }\n    return urls;\n  }\n\n  /**\n   * Every terrain-class tile URL a download should pin for ``blob``.\n   *\n   * SNOW-1072: the terrain filter (SNOW-978) paints from these \u2014 each\n   * pixel carries a height, an aspect octant and a slope band \u2014 so an area\n   * that holds the basemap but not these has a filter, and since SNOW-1073\n   * a slope layer, that goes blank offline. They replaced the swisstopo\n   * slope raster SNOW-692 pinned. The same superset rule as every other tile\n   * family: walk the blob's own row spans (the area's ground, already the\n   * superset of what the map will request there), then drop what the class\n   * tileset itself cannot answer for:\n   *\n   *   - **its coverage rectangle** (``COVERAGE_BOUNDS``,\n   *     terrain_filter_core.js) \u2014 the same rectangle the live layer's\n   *     source declares, so the download never asks for a tile MapLibre\n   *     would not;\n   *   - **its coverage outline** (``coverage``, terrain_filter_core.js's\n   *     ``tileInCoverage``, SNOW-1459) \u2014 the class tiles reach the Alps as\n   *     a polygon, not a box, so a tile inside the rectangle but outside\n   *     the outline is never priced, pinned or expected;\n   *   - **its zoom band** (``MIN_ZOOM``\u2013``MAX_ZOOM``, 12\u201314) \u2014 the origin\n   *     answers 204 outside it, and MapLibre overzooms z14 above, so a\n   *     download band of z10\u201314 pins z12\u201314 here.\n   *\n   * The URL is built exactly as the filter's own fetch builds it\n   * (``tileUrl``, terrain_filter_core.js: three ``replace`` calls on the\n   * same template), because a pinned entry is found by its URL and a\n   * mismatch of one character is a tile nothing ever reads.\n   *\n   * @param {string} template The class tileset's ``{z}/{x}/{y}`` template \u2014\n   *   ``#map[data-terrain-class-tile-url]``.\n   * @param {Object | null | undefined} blob The download blob, for its ``z``\n   *   row spans.\n   * @param {number[] | null | undefined} bounds ``[west, south, east,\n   *   north]`` the tileset covers. Omitted means no clip.\n   * @param {number} minZ Shallowest zoom the tileset publishes, inclusive.\n   * @param {number} maxZ Deepest zoom it publishes, inclusive.\n   * @param {CoveragePredicate | null} [coverage] Whether the tileset covers\n   *   a tile. Omitted, the ``bounds`` test alone decides.\n   * @returns {string[]} Empty when the template, blob or rows are missing.\n   */\n  function terrainClassTileURLs(template, blob, bounds, minZ, maxZ, coverage) {\n    var urls = [];\n    if (!template) return urls;\n    _eachOverlayTile(blob, bounds, minZ, maxZ, coverage, function (z, x, y) {\n      urls.push(_overlayTileURL(template, z, x, y));\n    });\n    return urls;\n  }\n\n  /**\n   * The terrain-class tiles ONE recorded area should hold (SNOW-1138).\n   *\n   * The pure half of ``map_basemap_downloads.js``'s\n   * ``areaTerrainClassTileUrls``, moved here so a page with no map \u2014 the\n   * ``/offline/`` report \u2014 can judge an opted-in area on its class tiles\n   * by the same rule the Manage downloads sheet and the region roundel\n   * apply. What stays map-side is only where the three page-level inputs\n   * come from (the template off ``#map``, the rectangle and band off\n   * ``pwaTerrainFilterCore``); everything that decides WHICH tiles is\n   * here, once.\n   *\n   * Gated on the record's own ``terrain`` flag: an area downloaded without\n   * the opt-in holds no class tiles and is never judged on them. A REGION\n   * record carries the run's own ``z`` row spans; a CUSTOM area carries\n   * ``bbox`` + ``band`` and no ``z``, so its blob is rebuilt through\n   * ``buildBlob``, the same client-side twin that produced it.\n   *\n   * @param {Object | null | undefined} record A ``basemap.regions`` /\n   *   ``basemap.customAreas`` entry, or a row carrying the same fields.\n   * @param {string} template The class tileset's ``{z}/{x}/{y}`` template.\n   * @param {number[] | null | undefined} bounds The tileset's rectangle.\n   * @param {number} minZ Shallowest zoom it publishes, inclusive.\n   * @param {number} maxZ Deepest zoom it publishes, inclusive.\n   * @param {CoveragePredicate | null} [coverage] The tileset's outline\n   *   (SNOW-1459). Omitted, the rectangle alone decides.\n   * @returns {string[]} Empty for an area without terrain data, a missing\n   *   template, or a record with no ground to rebuild.\n   */\n  function areaTerrainClassTileURLs(record, template, bounds, minZ, maxZ, coverage) {\n    if (!record || !record.terrain || !template) return [];\n    if (record.z) {\n      return terrainClassTileURLs(template, { z: record.z }, bounds, minZ, maxZ, coverage);\n    }\n    var band = Array.isArray(record.band) ? record.band : null;\n    if (!record.bbox || !band) return [];\n    return terrainClassTileURLs(\n      template,\n      buildBlob(record.bbox, band[0], band[1]),\n      bounds,\n      minZ,\n      maxZ,\n      coverage,\n    );\n  }\n\n  /**\n   * How many terrain-class tiles ``terrainClassTileURLs`` would list.\n   *\n   * SNOW-1072. The size estimate needs the count, not the URLs, and the\n   * custom-area readout recomputes it on every frame of a pan \u2014 so this\n   * walks the same tiles without building a string for each.\n   *\n   * @param {Object | null | undefined} blob\n   * @param {number[] | null | undefined} bounds\n   * @param {number} minZ\n   * @param {number} maxZ\n   * @param {CoveragePredicate | null} [coverage] The tileset's outline\n   *   (SNOW-1459). Omitted, the rectangle alone decides.\n   * @returns {number}\n   */\n  function terrainClassTileCount(blob, bounds, minZ, maxZ, coverage) {\n    var count = 0;\n    _eachOverlayTile(blob, bounds, minZ, maxZ, coverage, function () {\n      count += 1;\n    });\n    return count;\n  }\n\n  /**\n   * What ``count`` terrain-class tiles cost, in megabytes, rounded up.\n   *\n   * SNOW-1072. Its own figure rather than folded into ``sourceScaledMb``,\n   * because the readout states it on its own line: terrain data is an\n   * opt-in, and the reader deciding whether to take it needs to see what\n   * it adds.\n   *\n   * @param {number} count\n   * @returns {number} 0 for no tiles.\n   */\n  function terrainClassMb(count) {\n    var n = Number(count);\n    if (!Number.isFinite(n) || n <= 0) return 0;\n    return Math.ceil((n * TERRAIN_CLASS_BYTES_PER_TILE) / (1024 * 1024));\n  }\n\n  /**\n   * The per-source tile price ``budgetScaleForBBox`` should size a frame\n   * at, with terrain data included or not.\n   *\n   * SNOW-1072: the frame's ceiling has to hold the class tiles too, or a\n   * frame drawn right up to the ceiling is over it the moment terrain data\n   * is on. The frame model prices every tile in the band, so charging the\n   * class tile against every one of them \u2014 z10 and z11 included, where the\n   * tileset publishes nothing \u2014 over-states the cost. That is the safe\n   * direction for a ceiling: the frame comes out a little smaller than it\n   * strictly had to be, never larger. Divided by the source count because\n   * ``budgetScaleForBBox`` multiplies the figure back by it, and a class\n   * tile is fetched once per cell whatever the basemap.\n   *\n   * SNOW-1453: terrain data carries the elevation tiles too, where the page\n   * pins them (``elevation``). Their share is ``ELEVATION_BAND_SHARE`` of\n   * an elevation tile per frame tile, since the elevation band covers\n   * about a quarter of the frame's tiles; see that constant.\n   *\n   * @param {number} bytesPerTile The basemap's own per-source figure.\n   * @param {number} [sourceCount] Vector sources in the active style.\n   * @param {boolean} [terrain] Whether terrain data is included.\n   * @param {boolean} [elevation] Whether that terrain data includes the\n   *   elevation tiles (the 3D map's DEM template is on the page).\n   * @returns {number}\n   */\n  function terrainScaledBytesPerTile(bytesPerTile, sourceCount, terrain, elevation) {\n    var base =\n      Number.isFinite(bytesPerTile) && bytesPerTile > 0 ? bytesPerTile : WORST_CASE_BYTES_PER_TILE;\n    if (!terrain) return base;\n    var sources = Number.isFinite(sourceCount) && sourceCount > 1 ? sourceCount : 1;\n    var perCell =\n      TERRAIN_CLASS_BYTES_PER_TILE + (elevation ? ELEVATION_BYTES_PER_TILE * ELEVATION_BAND_SHARE : 0);\n    return base + perCell / sources;\n  }\n\n  /**\n   * Call ``visit(z, x, y)`` for every elevation tile an area's blob implies.\n   *\n   * SNOW-1453. The blob's own z10-13 rows (``ELEVATION_BAND``), clipped to\n   * ``bounds`` as the class tiles are, and then every one of their parents\n   * from z9 up to ``ELEVATION_PARENT_MIN_ZOOM``, each once. The parents\n   * come first, shallowest zoom first, so a run cut short still holds the\n   * coarse relief. A parent of a tile inside ``bounds`` is inside it too,\n   * so it needs no clip of its own.\n   *\n   * @param {Object | null | undefined} blob\n   * @param {number[] | null | undefined} bounds Omitted means no clip.\n   * @param {function(number, number, number): void} visit\n   * @returns {void}\n   */\n  function _eachElevationTile(blob, bounds, visit) {\n    var band = [];\n    var parents = [];\n    var seen = new Set();\n    _eachOverlayTile(blob, bounds, ELEVATION_BAND[0], ELEVATION_BAND[1], null, function (z, x, y) {\n      band.push([z, x, y]);\n      for (var pz = ELEVATION_BAND[0] - 1; pz >= ELEVATION_PARENT_MIN_ZOOM; pz -= 1) {\n        var shift = z - pz;\n        var px = Math.floor(x / Math.pow(2, shift));\n        var py = Math.floor(y / Math.pow(2, shift));\n        var key = pz + '/' + px + '/' + py;\n        if (seen.has(key)) continue;\n        seen.add(key);\n        parents.push([pz, px, py]);\n      }\n    });\n    parents.sort(function (a, b) {\n      return a[0] - b[0];\n    });\n    var all = parents.concat(band);\n    for (var i = 0; i < all.length; i += 1) visit(all[i][0], all[i][1], all[i][2]);\n  }\n\n  /**\n   * The elevation tile URLs one download blob implies (SNOW-1453).\n   *\n   * Built exactly as the 3D map's loader builds the URL it asks for\n   * (``map_3d_core.tileUrl``: three ``replace`` calls on the same\n   * template, which ``_overlayTileURL`` repeats character for character),\n   * because a pinned entry is found by its URL.\n   *\n   * @param {string} template The elevation tiles' ``{z}/{x}/{y}`` template \u2014\n   *   ``#map-view-toggle[data-dem-tile-url]``.\n   * @param {Object | null | undefined} blob The download blob, for its rows.\n   * @param {number[] | null | undefined} bounds The elevation coverage\n   *   (terrain_filter_core's ``SWISS_BOUNDS``). Omitted means no clip.\n   * @returns {string[]} Empty without a template or rows.\n   */\n  function elevationTileURLs(template, blob, bounds) {\n    var urls = [];\n    if (!template) return urls;\n    _eachElevationTile(blob, bounds, function (z, x, y) {\n      urls.push(_overlayTileURL(template, z, x, y));\n    });\n    return urls;\n  }\n\n  /**\n   * How many elevation tiles ``elevationTileURLs`` would list (SNOW-1453),\n   * for the size readouts, which recompute on every frame of a pan.\n   *\n   * @param {Object | null | undefined} blob\n   * @param {number[] | null | undefined} bounds\n   * @returns {number}\n   */\n  function elevationTileCount(blob, bounds) {\n    var count = 0;\n    _eachElevationTile(blob, bounds, function () {\n      count += 1;\n    });\n    return count;\n  }\n\n  /**\n   * What ``count`` elevation tiles cost, in megabytes, rounded up\n   * (SNOW-1453). The readouts fold it into the one terrain figure.\n   *\n   * @param {number} count\n   * @returns {number} 0 for no tiles.\n   */\n  function elevationMb(count) {\n    var n = Number(count);\n    if (!Number.isFinite(n) || n <= 0) return 0;\n    return Math.ceil((n * ELEVATION_BYTES_PER_TILE) / (1024 * 1024));\n  }\n\n  /**\n   * Whether an area on ``basemapKey`` carries elevation tiles: only one\n   * downloaded on the basemap 3D is drawn on (SNOW-1453 review).\n   *\n   * @param {string | null | undefined} basemapKey\n   * @returns {boolean}\n   */\n  function elevationBasemap(basemapKey) {\n    return basemapKey === ELEVATION_BASEMAP_KEY;\n  }\n\n  /**\n   * The elevation tiles ONE recorded area should hold (SNOW-1453).\n   *\n   * The twin of ``areaTerrainClassTileURLs``, on the same gate: elevation\n   * rides on the area's ``terrain`` flag, so an area downloaded without\n   * terrain data is never judged on it. Derived from today's template, so\n   * an area downloaded before elevation joined terrain data, or before a\n   * seasonal ``<version>`` bump of the template, reads incomplete until a\n   * sync fetches the tiles.\n   *\n   * @param {Object | null | undefined} record A ``basemap.regions`` /\n   *   ``basemap.customAreas`` entry, or a row carrying the same fields.\n   * @param {string} template The elevation tiles' ``{z}/{x}/{y}`` template.\n   * @param {number[] | null | undefined} bounds The elevation coverage.\n   * Only an area downloaded on the 3D basemap (``ELEVATION_BASEMAP_KEY``)\n   * holds them: 3D cannot draw offline on any other area's tiles, so none\n   * is pinned there, and none is expected.\n   *\n   * @returns {string[]} Empty for an area without terrain data, one on\n   *   another basemap, a missing template, or a record with no ground to\n   *   rebuild.\n   */\n  function areaElevationTileURLs(record, template, bounds) {\n    if (!record || !record.terrain || !template) return [];\n    if (!elevationBasemap(record.basemapKey)) return [];\n    if (record.z) return elevationTileURLs(template, { z: record.z }, bounds);\n    var band = Array.isArray(record.band) ? record.band : null;\n    if (!record.bbox || !band) return [];\n    return elevationTileURLs(template, buildBlob(record.bbox, band[0], band[1]), bounds);\n  }\n\n  /**\n   * The boxes 3D may be drawn in offline: one per downloaded area whose\n   * elevation tiles were fetched under today's template (SNOW-1453).\n   *\n   * A download or a sync that pinned every elevation tile stamps the\n   * record ``elevation: <template>``. Only a stamp equal to ``template``\n   * counts, so a seasonal ``<version>`` bump takes every area out until it\n   * is synced, as its tiles would be missing. The box is ``areaBBox``'s,\n   * from the record alone; nothing here reads the cache.\n   *\n   * @param {Array<Object> | null | undefined} records Downloaded areas\n   *   (``pwaBasemapAreas.downloadedAreas()`` rows, or stored records).\n   * @param {string} template Today's elevation template.\n   * @returns {Array<[number, number, number, number]>}\n   */\n  function elevationAreaBoxes(records, template) {\n    var boxes = [];\n    if (!template || !Array.isArray(records)) return boxes;\n    for (var i = 0; i < records.length; i += 1) {\n      var record = records[i];\n      if (!record || record.elevation !== template) continue;\n      // The 3D view draws on the 3D basemap: an area on another basemap\n      // holds none of its tiles, whatever its stamp says.\n      if (!elevationBasemap(record.basemapKey)) continue;\n      var box = areaBBox(record);\n      if (box) boxes.push(box);\n    }\n    return boxes;\n  }\n\n  /**\n   * Whether a tileset covers one tile \u2014 terrain_filter_core.js's\n   * ``tileInCoverage`` for the class tiles (SNOW-1459).\n   *\n   * @callback CoveragePredicate\n   * @param {number} z\n   * @param {number} x\n   * @param {number} y\n   * @returns {boolean}\n   */\n\n  /**\n   * Call ``visit(z, x, y)`` for every tile in ``blob``'s rows that sits in\n   * ``[minZ, maxZ]``, overlaps ``bounds`` and, where one is given, passes\n   * ``coverage``.\n   *\n   * The walk ``terrainClassTileURLs`` and ``terrainClassTileCount`` share\n   * (SNOW-1072). The class tiles are pinned over the area's OWN ground, so\n   * the walk follows the server-computed rows rather than doing tile maths\n   * of its own, and clips to the rectangle and band the tileset publishes.\n   * SNOW-692's swisstopo slope raster walked it too, until SNOW-1073\n   * removed that layer.\n   *\n   * @param {Object | null | undefined} blob\n   * @param {number[] | null | undefined} bounds Omitted means no clip.\n   * @param {number} minZ Inclusive; ``-Infinity`` for no floor.\n   * @param {number} maxZ Inclusive; a non-number means no ceiling.\n   * @param {CoveragePredicate | null | undefined} coverage Tested after the\n   *   rectangle, which is the cheap prefilter; omitted means no test.\n   * @param {function(number, number, number): void} visit\n   * @returns {void}\n   */\n  function _eachOverlayTile(blob, bounds, minZ, maxZ, coverage, visit) {\n    if (!blob || !blob.z) return;\n    var floor = typeof minZ === 'number' ? minZ : -Infinity;\n    var ceiling = typeof maxZ === 'number' ? maxZ : Infinity;\n    var rect = Array.isArray(bounds) && bounds.length === 4 ? bounds : null;\n    var inside = typeof coverage === 'function' ? coverage : null;\n    var zKeys = Object.keys(blob.z);\n    for (var zi = 0; zi < zKeys.length; zi += 1) {\n      var z = Number(zKeys[zi]);\n      if (!Number.isFinite(z) || z < floor || z > ceiling) continue;\n      var rows = zoomRows(blob.z[zKeys[zi]]);\n      var yKeys = Object.keys(rows);\n      for (var yi = 0; yi < yKeys.length; yi += 1) {\n        var y = Number(yKeys[yi]);\n        var span = rows[yKeys[yi]];\n        for (var x = span[0]; x <= span[1]; x += 1) {\n          if (rect && !_tileIntersectsBBox(z, x, y, rect)) continue;\n          if (inside && !inside(z, x, y)) continue;\n          visit(z, x, y);\n        }\n      }\n    }\n  }\n\n  /**\n   * One overlay tile's URL: the template with ``{z}``/``{x}``/``{y}``\n   * substituted \u2014 the form the terrain filter's live fetch uses.\n   *\n   * @param {string} template\n   * @param {number} z\n   * @param {number} x\n   * @param {number} y\n   * @returns {string}\n   */\n  function _overlayTileURL(template, z, x, y) {\n    return template\n      .replace('{z}', String(z))\n      .replace('{x}', String(x))\n      .replace('{y}', String(y));\n  }\n\n  /**\n   * Whether a tile's ground overlaps ``bbox``.\n   *\n   * SNOW-692. Overlap, not containment: a tile straddling the tileset's\n   * edge carries real data on the inside and has to be fetched. Touching\n   * edges count \u2014 a tile flush against the boundary is one the origin\n   * still answers. The class tiles' outline is a separate test\n   * (``coverage``, SNOW-1459); this is its rectangle prefilter.\n   *\n   * @param {number} z\n   * @param {number} x\n   * @param {number} y\n   * @param {number[]} bbox ``[west, south, east, north]``.\n   * @returns {boolean}\n   */\n  function _tileIntersectsBBox(z, x, y, bbox) {\n    var tile = tileBounds(z, x, y);\n    return tile[0] <= bbox[2] && tile[2] >= bbox[0] && tile[1] <= bbox[3] && tile[3] >= bbox[1];\n  }\n\n  /**\n   * The area id for a region download.\n   *\n   * SNOW-586: formalises \"area\" as the unit a pinned cache bucket and a\n   * budget record are both keyed on \u2014 region downloads previously had no\n   * such id, only a bare ``region_id``.\n   *\n   * @param {string} regionId\n   * @returns {string}\n   */\n  function areaIdForRegion(regionId) {\n    return 'region-' + regionId;\n  }\n\n  /**\n   * The region id ``areaId`` names, or ``''`` when it is not a region's.\n   *\n   * The inverse of ``areaIdForRegion``, kept beside it so the\n   * ``region-<id>`` format is parsed in the one module that writes it. A\n   * download that fails leaves its bucket and no record, and the bucket's\n   * name is then the only thing that says which region it was: the\n   * Downloads sheet reads it to name the row and to complete the download.\n   *\n   * @param {string} areaId\n   * @returns {string}\n   */\n  function regionIdForArea(areaId) {\n    const prefix = 'region-';\n    if (typeof areaId !== 'string' || !areaId.startsWith(prefix)) return '';\n    return areaId.slice(prefix.length);\n  }\n\n  /**\n   * The Cache Storage name for ``areaId``'s pinned bucket.\n   *\n   * @param {string} areaId\n   * @returns {string}\n   */\n  function pinnedCacheName(areaId) {\n    return PINNED_CACHE_PREFIX + areaId;\n  }\n\n  /**\n   * The area id for a basemap's shared base layer (SNOW-856).\n   *\n   * A THIRD id namespace beside ``region-`` and ``custom-``, and the\n   * reason it is one rather than a flag on an existing area: the base\n   * layer is not an area. It is shared by every area on the device, it\n   * covers ground no area asked for, and it must survive the eviction of\n   * the area whose download happened to fetch it. Giving it its own\n   * ``PINNED_CACHE_PREFIX`` bucket buys all of that for free \u2014 the\n   * worker's ``_searchPinnedBuckets`` walks every bucket under the\n   * prefix, so the offline READ path needs no change whatsoever.\n   *\n   * Keyed by basemap rather than being a single global bucket because\n   * the tiles are a specific style's: a device holding areas under both\n   * swisstopo and OpenFreeMap needs both base layers, and neither can\n   * answer for the other.\n   *\n   * @param {string} basemapKey A ``settings.BASEMAP_STYLES`` key.\n   * @returns {string}\n   */\n  function areaIdForBaseLayer(basemapKey) {\n    return 'base-' + basemapKey;\n  }\n\n  /**\n   * Whether ``areaId`` names a base layer rather than a user's area.\n   *\n   * Every surface that lists, sizes, evicts or reconciles \"the areas on\n   * this device\" has to be able to tell the two apart \u2014 a base layer is\n   * real bytes the user is spending, but it is not a download they chose\n   * and must never be offered for deletion or picked as an eviction\n   * candidate. Mirrors ``isCustomAreaId``'s shape so the ``'base-'``\n   * prefix stays private to this module.\n   *\n   * @param {string} areaId\n   * @returns {boolean}\n   */\n  function isBaseLayerAreaId(areaId) {\n    return typeof areaId === 'string' && areaId.indexOf('base-') === 0;\n  }\n\n  /**\n   * The basemap a base-layer area id belongs to (SNOW-863).\n   *\n   * The inverse of ``areaIdForBaseLayer``, and the only sanctioned way to\n   * read a key back out of an id \u2014 the ``'base-'`` prefix stays private to\n   * this module, exactly as ``'region-'`` and ``'custom-'`` do.\n   *\n   * It exists because the BUCKET has to be able to describe itself. A\n   * base layer's ``meta:app`` record is written by the page after the\n   * service worker's warm resolves, so a reader who closes the tab in\n   * between is left with a complete bucket and no record \u2014 and before\n   * this function the only thing that could name that bucket's basemap\n   * was the record that is missing. The result was a row labelled with a\n   * raw bucket id under \"Unknown basemap\", offering to delete the shared\n   * overview map.\n   *\n   * @param {string} areaId\n   * @returns {string} The ``settings.BASEMAP_STYLES`` key, or ``''`` for\n   *   an id that is not a base layer's.\n   */\n  function baseLayerBasemapKey(areaId) {\n    return isBaseLayerAreaId(areaId) ? areaId.slice('base-'.length) : '';\n  }\n\n  /**\n   * The overlap of two ``[minLon, minLat, maxLon, maxLat]`` boxes.\n   *\n   * @param {number[]} a\n   * @param {number[]} b\n   * @returns {number[]|null} ``null`` when they do not overlap, or when\n   *   either is not a well-formed 4-number box.\n   */\n  function intersectBBox(a, b) {\n    const ok = (box) => Array.isArray(box) && box.length === 4 && box.every(Number.isFinite);\n    if (!ok(a)) return null;\n    if (!ok(b)) return a;\n    const out = [\n      Math.max(a[0], b[0]),\n      Math.max(a[1], b[1]),\n      Math.min(a[2], b[2]),\n      Math.min(a[3], b[3]),\n    ];\n    return out[0] < out[2] && out[1] < out[3] ? out : null;\n  }\n\n  /**\n   * The ground a basemap's base layer covers (SNOW-856).\n   *\n   * ``cameraBBox`` is the authority and ``styleBounds`` only ever\n   * narrows it. That order is the whole design:\n   *\n   *   - The CAMERA bbox (``MAX_BOUNDS`` in static/js/map.js \u2014 passed in\n   *     rather than duplicated here, so there is one definition of where\n   *     this map can go) is what makes the layer SUFFICIENT. The reader\n   *     cannot pan outside it, so a layer covering it cannot leave a hole.\n   *   - The STYLE's declared bounds are what make it FINITE. Deriving the\n   *     extent from those alone \u2014 the first design this ticket had \u2014\n   *     works for the three national styles and blows up on the default\n   *     one: OpenFreeMap Liberty is global, and z0-9 worldwide is roughly\n   *     350,000 tiles. Intersecting instead means a global style is\n   *     bounded by the camera and a national one is bounded by its own\n   *     coverage, and neither ever asks a provider for ground it does not\n   *     serve.\n   *\n   * @param {number[]} cameraBBox ``[minLon, minLat, maxLon, maxLat]``.\n   * @param {number[]|null|undefined} styleBounds The source's TileJSON\n   *   ``bounds``, in the same order. Absent or malformed leaves\n   *   ``cameraBBox`` unnarrowed \u2014 a style that declares no coverage is\n   *   claiming all of it, and the camera is still a bound.\n   * @returns {number[]|null} ``null`` when the style covers no part of\n   *   the map's own extent, which is a style nothing here should be\n   *   downloading a base layer for.\n   */\n  function baseLayerBBox(cameraBBox, styleBounds) {\n    return intersectBBox(cameraBBox, styleBounds);\n  }\n\n  /**\n   * The base layer's blob for one basemap (SNOW-856).\n   *\n   * Deliberately ``buildBlob`` rather than a bespoke shape: the result\n   * is then interchangeable with a region's server-computed blob and a\n   * custom area's locally-built one, so ``rangesToTileURLs``,\n   * ``blobFullyCached`` and the byte estimate all work on it unchanged.\n   * A rectangle is also the right shape here \u2014 unlike a region, there is\n   * no boundary to clip to.\n   *\n   * @param {number[]} cameraBBox See ``baseLayerBBox``.\n   * @param {number[]|null|undefined} styleBounds See ``baseLayerBBox``.\n   * @param {string} [basemapKey] SNOW-868: whose band to build. Omitted\n   *   keeps ``BASE_LAYER_BAND``, the default \u2014 see ``baseLayerBand``.\n   * @returns {Object|null} ``null`` when there is no overlap.\n   */\n  function baseLayerBlob(cameraBBox, styleBounds, basemapKey) {\n    const bbox = baseLayerBBox(cameraBBox, styleBounds);\n    if (!bbox) return null;\n    const band = baseLayerBand(basemapKey);\n    return buildBlob(bbox, band[0], band[1]);\n  }\n\n  /**\n   * Every tile URL a basemap's base layer needs (SNOW-856).\n   *\n   * One URL per tile PER SOURCE, each from the host MapLibre will\n   * actually ask that source for \u2014 this goes through ``rangesToTileURLs``\n   * precisely so the ``urls[(x + y) % urls.length]`` rotation is the same\n   * one the area download and the live map both use. A base layer stored\n   * under a host the map never asks is a bucket full of tiles that never\n   * serve, which is the SNOW-843 failure repeated one layer down.\n   *\n   * @param {string | string[][]} spec The style's tile sources.\n   * @param {number[]} cameraBBox See ``baseLayerBBox``.\n   * @param {number[]|null|undefined} styleBounds See ``baseLayerBBox``.\n   * @param {string} [basemapKey] SNOW-868: whose band to build. Omitted\n   *   keeps ``BASE_LAYER_BAND``, the default \u2014 see ``baseLayerBand``.\n   * @returns {string[]}\n   */\n  function baseLayerTileURLs(spec, cameraBBox, styleBounds, basemapKey) {\n    const blob = baseLayerBlob(cameraBBox, styleBounds, basemapKey);\n    return blob ? rangesToTileURLs(spec, blob) : [];\n  }\n\n  // SNOW-929: the tail every tile URL these styles emit has, and that no\n  // document they emit has \u2014 ``/{z}/{x}/{y}.{ext}``, three numeric path\n  // segments and a tile extension.\n  //\n  // Host-independent and path-only on purpose. The hosts rotate\n  // (``tileURLForSource``), OpenFreeMap's tileset path carries a dated\n  // build id that changes under us (``planet/20260906_080001_pt/\u2026``), and\n  // a tile may arrive with a query string or an API key appended \u2014 none of\n  // which this can be allowed to care about. What it must get right is the\n  // NEAR MISSES, which all fail on the numeric triple:\n  //\n  //   /fonts/Noto%20Sans%20Bold/0-255.pbf   glyph range \u2014 ``0-255`` is one\n  //                                         segment, not three, and not a\n  //                                         number\n  //   /sprites/ofm_f384/ofm@2x.png          sprite \u2014 ``ofm@2x`` is not\n  //   /styles/liberty                       style document \u2014 no extension\n  //   /planet, /basemapvectorneu/root.json  TileJSON\n  //\n  // ``.jpg``/``.jpeg`` are here for completeness rather than for a basemap\n  // this project ships: every current style serves ``.pbf``/``.mvt`` vector\n  // tiles, and the natural-earth relief raster is ``.webp`` on our own\n  // origin (snowdesk-tiles transcodes it) and ``.png`` on OpenFreeMap's \u2014\n  // and in any bucket pinned before the switch.\n  const TILE_ENTRY_PATH = /\\/\\d+\\/\\d+\\/\\d+\\.(?:pbf|mvt|png|webp|jpg|jpeg)$/i;\n\n  /**\n   * Whether ``url`` names a TILE rather than one of the documents that\n   * draw it (SNOW-929).\n   *\n   * A pinned bucket holds both since SNOW-929 put the base layer's style,\n   * TileJSON, sprite and glyph ranges in beside its tiles, so any check\n   * over a bucket's contents now has to be able to tell the two apart.\n   * The one that needs it is ``baseLayerStaleEntries`` below \u2014 see there\n   * for what goes wrong if a document is judged as a tile.\n   *\n   * Decided from the PATH alone, so a query string, a fragment or an API\n   * key never changes the answer \u2014 see ``TILE_ENTRY_PATH`` above for the\n   * near misses this has to reject and why each one does.\n   *\n   * @param {string} url A cache entry's url, absolute or relative.\n   * @returns {boolean} ``false`` for a non-string, an unparseable url, or\n   *   anything without the numeric-triple tail \u2014 \"not provably a tile\",\n   *   which every caller reads as \"leave it alone\".\n   */\n  function isTileEntryURL(url) {\n    if (typeof url !== 'string' || !url) return false;\n    try {\n      // A base is supplied so a relative entry still parses to a path;\n      // its host is never read, and an absolute url ignores it outright.\n      return TILE_ENTRY_PATH.test(new URL(url, 'https://snowdesk.info').pathname);\n    } catch (_e) {\n      return false;\n    }\n  }\n\n  /**\n   * Which of a base-layer bucket's ``entries`` are tiles the current band\n   * does not ask for (SNOW-929) \u2014 the pure half of the re-banding check.\n   *\n   * SNOW-863 evicts a base-layer bucket whole when it holds anything\n   * outside the current band's url set, because SNOW-856 shipped z0-9 and\n   * the default band is z0-7: without that migration every device that\n   * ever ran the old band keeps its z8 and z9 tiles for good (they are a\n   * superset, so the missing-url plan is empty and nothing re-warms).\n   * That check lived inline in ``map_basemap_downloads.js`` and judged\n   * EVERY entry.\n   *\n   * SNOW-929 put the documents that draw the band into the same bucket,\n   * which ends that. Folding the document list into the expected set\n   * instead would hand a provider the ability to bin a 21 MB band by\n   * renaming a sprite path or adding a fontstack \u2014 the expected documents\n   * are derived from the LIVE style, so they move whenever the provider\n   * moves them, while the tile set is a pure function of band, camera and\n   * style. So the judgement is tiles only, and a document the current\n   * plan happens not to name is left exactly where it is: it is at worst\n   * a few tens of kilobytes, and it may well be the thing making the\n   * band renderable.\n   *\n   * Pure, exported and given a truth table of its own\n   * (``tests/js/test_basemap_base_layer.js``) rather than staying inline,\n   * because the cost of ``isTileEntryURL`` mis-reading a tile as a\n   * document is silent: SNOW-863's migration would stop firing and the\n   * oversized bucket would sit there with no path out short of a reset.\n   *\n   * @param {string[]} entries The bucket's entry urls, as\n   *   ``cache.keys()`` reports them.\n   * @param {Set<string> | string[]} expectedTiles Every tile url the\n   *   current band asks for, in either shape \u2014 the same contract\n   *   ``blobFullyCached`` and ``missingRenderDependencies`` take.\n   * @returns {string[]} The stale tile entries, in the order given.\n   *   ``[]`` for an empty or unusable bucket (\"there is nothing to throw\n   *   away\") AND for an empty ``expectedTiles``: failing to enumerate the\n   *   band must never read as evidence that everything on disk is stale.\n   */\n  function baseLayerStaleEntries(entries, expectedTiles) {\n    if (!Array.isArray(entries) || entries.length === 0) return [];\n    const wanted = expectedTiles instanceof Set ? expectedTiles : new Set(expectedTiles || []);\n    if (!wanted.size) return [];\n    const stale = [];\n    for (const entry of entries) {\n      if (!isTileEntryURL(entry)) continue;\n      if (wanted.has(entry)) continue;\n      stale.push(entry);\n    }\n    return stale;\n  }\n\n  /**\n   * Decide whether an incoming download fits the standing budget and,\n   * when it doesn't, which areas to evict (oldest first) to make it fit.\n   *\n   * SNOW-586: replaces the old pinned cache's entry-count FIFO trim,\n   * which evicted individual cache ENTRIES with no notion of which\n   * download they belonged to \u2014 perforating whichever area happened to\n   * hold the oldest-inserted tiles. Evicting whole AREAS instead means a\n   * download can only ever be entirely present or entirely gone.\n   *\n   * A re-download of an area already in ``areas`` (``incoming.id``\n   * matches an existing entry) is treated as a REPLACEMENT: that entry's\n   * bytes leave the standing total before the incoming run's bytes are\n   * added back in, so re-downloading an area never counts its own old\n   * copy against itself.\n   *\n   * ``incoming.bytes`` exceeding what the budget has left ONCE the\n   * un-evictable floor is accounted for is refused outright\n   * (``impossible: true``, ``evict: []``) rather than evicting every other\n   * area and still failing \u2014 no amount of eviction could ever make it fit.\n   *\n   * SNOW-856: that floor is the shared base layers. They are counted in\n   * the standing total (real disk) and excluded from the candidate list\n   * (shared, and not the user's to be offered) \u2014 see the inline comment.\n   *\n   * @param {Array<{id: string, bytes: number, savedAt?: string}>} areas\n   *   Areas currently on disk, most fields best-effort (a record with no\n   *   usable ``bytes``/``savedAt`` is treated as ``0``/unset). May include\n   *   ``base-`` entries, which this counts but never evicts.\n   * @param {{id: string, bytes: number}} incoming The run being planned.\n   * @param {number} budgetBytes The standing budget, in bytes.\n   * @returns {{fits: boolean, impossible: boolean, evict: string[],\n   *   projectedBytes: number}} ``fits`` is true only when the incoming run\n   *   already sits under budget with NO eviction needed \u2014 the caller's\n   *   \"run unchanged\" case. ``evict`` lists area ids in the order they\n   *   should be removed; a caller only removing some of them (a\n   *   cancelled confirm, say) doesn't need to know that, since none of\n   *   this function's own state depends on it. ``projectedBytes`` is the\n   *   standing total once the plan runs (or, in the ``impossible`` case,\n   *   the standing total as it stands today, since nothing changes).\n   */\n  function planEviction(areas, incoming, budgetBytes) {\n    const budget = Number(budgetBytes) || 0;\n    const list = Array.isArray(areas) ? areas : [];\n    const incomingId = incoming && incoming.id;\n    const incomingBytes = Number((incoming && incoming.bytes) || 0);\n\n    // The base layers are not in this arithmetic at all \u2014 not as\n    // candidates, and (SNOW-XXX) not as bytes either.\n    //\n    // They were counted, on the reasoning that they are real disk and a\n    // budget ignoring real disk is a lie. What that missed is WHOSE budget\n    // it is. The z0-9 layer is the app's own map data: fetched once per\n    // basemap, shared by every area, never chosen and never removable on\n    // its own. Charging it to the user's download budget spends up to\n    // 100 MB of a 500 MB allowance on something they cannot point at,\n    // cannot delete, and did not ask for \u2014 and on a 200 MB budget it can\n    // make their SECOND download impossible. It is accounted for where the\n    // app's own storage is: the Reset local data summary in account\n    // settings.\n    //\n    // It still goes when the last area under its basemap goes\n    // (`evictBasemapAreas`), which is the only moment nothing needs it.\n    const others = list.filter(\n      (a) => a && a.id !== incomingId && !isBaseLayerAreaId(a.id),\n    );\n    const evictable = others;\n\n    // Nothing un-evictable is left in the total now, so exhausting the\n    // candidate list always leaves exactly the incoming run \u2014 which is the\n    // guarantee this check restores from before SNOW-856.\n    if (incomingBytes > budget) {\n      const standing = others.reduce((sum, a) => sum + (Number(a.bytes) || 0), 0);\n      return { fits: false, impossible: true, evict: [], projectedBytes: standing };\n    }\n\n    let total = others.reduce((sum, a) => sum + (Number(a.bytes) || 0), 0) + incomingBytes;\n\n    if (total <= budget) {\n      return { fits: true, impossible: false, evict: [], projectedBytes: total };\n    }\n\n    // Oldest savedAt first; id is a deterministic tiebreak for equal or\n    // missing timestamps, so a re-run of the same standing set always\n    // proposes the same eviction order.\n    const sorted = evictable.slice().sort((a, b) => {\n      const ta = Date.parse(a.savedAt) || 0;\n      const tb = Date.parse(b.savedAt) || 0;\n      if (ta !== tb) return ta - tb;\n      return String(a.id).localeCompare(String(b.id));\n    });\n    const evict = [];\n    for (const area of sorted) {\n      if (total <= budget) break;\n      total -= Number(area.bytes) || 0;\n      evict.push(area.id);\n    }\n    return { fits: false, impossible: false, evict: evict, projectedBytes: total };\n  }\n\n  /**\n   * Normalise one zoom level's ``z`` entry to ``{\"<y>\": [xmin, xmax]}``,\n   * whichever of the two shapes it arrived in (SNOW-583).\n   *\n   * A full blob's ``z[zoom]`` is one of:\n   *   - a 4-int rectangle ``[xmin, xmax, ymin, ymax]`` \u2014 ``buildBlob``'s\n   *     own shape (the custom-area download, always a rectangle) and\n   *     what a region response served from its stale window can still be\n   *     (SNOW-902) \u2014 expanded here into one identical span per row.\n   *   - an object ``{\"<y>\": [xmin, xmax]}`` \u2014 a clipped region blob's\n   *     shape (``apps.regions.services.basemap_tiles.build_region_blob``),\n   *     taken as given.\n   *\n   * Every consumer of a blob's ``z`` below (``rangesToTileURLs``,\n   * ``tileCount``, ``tileGridPlan``, ``blobFullyCached``) routes through\n   * this rather than assuming either shape directly.\n   *\n   * @param {number[] | Object<string, number[]> | undefined} zEntry\n   * @returns {Object<string, [number, number]>}\n   */\n  function zoomRows(zEntry) {\n    if (!zEntry) return {};\n    if (Array.isArray(zEntry)) {\n      const [xmin, xmax, ymin, ymax] = zEntry;\n      const rows = {};\n      for (let y = ymin; y <= ymax; y++) rows[String(y)] = [xmin, xmax];\n      return rows;\n    }\n    return zEntry;\n  }\n\n  /**\n   * Normalise a tile-source spec to ``string[][]`` \u2014 one entry per vector\n   * source in the style, each holding that source's own URL templates\n   * (SNOW-843).\n   *\n   * A basemap is not one tile URL. A style declares one or more vector\n   * SOURCES (the swisstopo winter style has two: ``ch.swisstopo.relief.vt``\n   * and ``ch.swisstopo.base.vt``), and each source can list SEVERAL URLs\n   * that differ only by hostname, which MapLibre round-robins between per\n   * tile. Everything downstream of here \u2014 the download's URL list, the\n   * cached-tiles overlay, the done-probe \u2014 has to agree with MapLibre about\n   * both, or the tiles land in the cache under keys nothing will ever ask\n   * for. That is exactly the bug this shape exists to close: a download that\n   * pinned ``tiles[0]`` of the FIRST source alone kept a fifth of one of the\n   * two layers, and the map came up blank offline over a full bucket.\n   *\n   * Accepted inputs, so a record written before SNOW-843 still resolves:\n   *\n   *   - a plain string \u2014 one source, one URL: ``[[url]]``;\n   *   - ``string[][]`` \u2014 the current shape, taken as given (empty inner\n   *     lists dropped);\n   *   - ``string[]`` \u2014 read as one single-URL source each, which is what a\n   *     flat list of distinct templates means.\n   *\n   * @param {string | string[] | string[][] | null | undefined} spec\n   * @returns {string[][]} Empty for anything unusable \u2014 every caller\n   *   already treats \"no sources\" as \"nothing to do\".\n   */\n  function tileSources(spec) {\n    if (!spec) return [];\n    if (typeof spec === 'string') return [[spec]];\n    if (!Array.isArray(spec)) return [];\n    const out = [];\n    for (const entry of spec) {\n      if (typeof entry === 'string' && entry) {\n        out.push([entry]);\n      } else if (Array.isArray(entry)) {\n        const urls = entry.filter((url) => typeof url === 'string' && url);\n        if (urls.length) out.push(urls);\n      }\n    }\n    return out;\n  }\n\n  /**\n   * How many vector sources ``spec`` names \u2014 the factor by which one\n   * tile's worth of ground costs more than a single-source style's\n   * (SNOW-843).\n   *\n   * @param {string | string[] | string[][] | null | undefined} spec\n   * @returns {number} ``0`` when nothing resolves.\n   */\n  function tileSourceCount(spec) {\n    return tileSources(spec).length;\n  }\n\n  /**\n   * A stable string identifying ``spec``, for the equality tests that used\n   * to compare two template STRINGS (SNOW-843).\n   *\n   * Several callers ask \"was this area downloaded under the basemap that is\n   * on screen now?\" \u2014 the download record's sources against the live\n   * style's. With a string on both sides that was ``===``; with a nested\n   * array it needs a canonical form, and this is it. A legacy string record\n   * and a live single-source single-URL style still produce the same key, so\n   * an OpenFreeMap area downloaded before this ticket keeps matching.\n   *\n   * @param {string | string[] | string[][] | null | undefined} spec\n   * @returns {string} ``''`` when nothing resolves \u2014 never equal to a real\n   *   key, which is what makes an unresolved style fail the comparison\n   *   rather than accidentally matching everything.\n   */\n  function tileSourcesKey(spec) {\n    const sources = tileSources(spec);\n    if (!sources.length) return '';\n    return JSON.stringify(sources);\n  }\n\n  /**\n   * The URL one source serves tile ``(z, x, y)`` from \u2014 MapLibre's own\n   * choice, not ours (SNOW-843).\n   *\n   * MapLibre picks ``urls[(x + y) % urls.length]`` (``CanonicalTileID.url``\n   * in ``static/js/maplibre-gl.min.js``). A download that stored every tile\n   * under ``urls[0]`` therefore matched only the tiles whose indices happen\n   * to sum to a multiple of ``urls.length`` \u2014 one in five for swisstopo's\n   * five ``vectortilesN.geo.admin.ch`` hosts. Mirroring the selection here\n   * is what makes a pinned tile findable: Cache Storage matches on the whole\n   * URL, so the hostname is part of the key.\n   *\n   * Kept honest by ``tests/js/test_basemap_download_core.js``, which asserts\n   * the rotation against the same worked example the SNOW-843 trace showed.\n   *\n   * @param {string[]} urls One source's URL templates, in style order.\n   * @param {number} z\n   * @param {number} x\n   * @param {number} y\n   * @returns {string}\n   */\n  function tileURLForSource(urls, z, x, y) {\n    const template = urls.length === 1 ? urls[0] : urls[(x + y) % urls.length];\n    return template\n      .replace('{z}', String(z))\n      .replace('{x}', String(x))\n      .replace('{y}', String(y));\n  }\n\n  /**\n   * Every URL one tile needs \u2014 one per source (SNOW-843).\n   *\n   * @param {string[][]} sources Normalised by ``tileSources``.\n   * @param {number} z\n   * @param {number} x\n   * @param {number} y\n   * @returns {string[]}\n   */\n  function tileURLs(sources, z, x, y) {\n    const urls = [];\n    for (const source of sources) urls.push(tileURLForSource(source, z, x, y));\n    return urls;\n  }\n\n  /**\n   * Which basemap's per-tile figure prices ``spec`` (SNOW-868).\n   *\n   * Resolved from the source template's HOST, deliberately, and NOT from\n   * ``activeBasemapKey()``. That function reads the picker's DOM, which\n   * ``map_basemap_picker.js`` updates synchronously on click \u2014 so between\n   * the click and MapLibre finishing ``setStyle()`` it LEADS the render,\n   * while ``activeBasemapTileSources`` still returns the outgoing style's\n   * templates. Its own comment (``map_basemap_downloads.js``) says that\n   * mismatch is harmless precisely because it is display-only and nothing\n   * there feeds a decision. Pricing off it would end that guarantee, and in\n   * that window would apply the incoming basemap's constant to the outgoing\n   * basemap's tiles. Matching the host instead makes the estimate a\n   * function of what will actually be fetched.\n   *\n   * The key returned is a PRICING representative, not an identity. Both\n   * swisstopo styles serve from the same ``vectortilesN.geo.admin.ch``\n   * hosts, so the host cannot tell winter from light \u2014 harmless only\n   * because the table gives both the same figure. Do not read this as\n   * \"which basemap is on screen\"; ``activeBasemapKey`` answers that, and\n   * ``baseLayerBasemapKey`` answers it for a stored area.\n   *\n   * @param {string | string[] | string[][] | null | undefined} spec\n   * @returns {string} ``''`` when no host matches \u2014 including OpenFreeMap,\n   *   whose origin is deployment-dependent (see ``BYTES_PER_TILE_BY_BASEMAP``).\n   */\n  function basemapKeyForTileSources(spec) {\n    const sources = tileSources(spec);\n    for (const source of sources) {\n      for (const url of source) {\n        for (const [fragment, key] of BASEMAP_HOST_KEYS) {\n          if (url.indexOf(fragment) !== -1) return key;\n        }\n      }\n    }\n    return '';\n  }\n\n  /**\n   * What one tile of ``key``'s basemap costs, in bytes (SNOW-868).\n   *\n   * @param {string} key A ``BASEMAP_STYLES`` key.\n   * @returns {number} ``WORST_CASE_BYTES_PER_TILE`` for an unknown key \u2014\n   *   which is also OpenFreeMap's own measured figure, so the default\n   *   basemap is priced correctly by the fallback.\n   */\n  function bytesPerTileForBasemap(key) {\n    const bytes = BYTES_PER_TILE_BY_BASEMAP[key];\n    return Number.isFinite(bytes) ? bytes : WORST_CASE_BYTES_PER_TILE;\n  }\n\n  /**\n   * What one tile costs for the style ``spec`` describes (SNOW-868) \u2014 the\n   * composition of ``basemapKeyForTileSources`` and\n   * ``bytesPerTileForBasemap``, and what the two frame-sizing call sites\n   * pass to ``budgetScaleForBBox``.\n   *\n   * @param {string | string[] | string[][] | null | undefined} spec\n   * @returns {number} Bytes per tile PER SOURCE.\n   */\n  function bytesPerTileForSources(spec) {\n    return bytesPerTileForBasemap(basemapKeyForTileSources(spec));\n  }\n\n  /**\n   * What a blob costs on the basemap ``spec`` describes, in megabytes\n   * (SNOW-843, re-based per basemap by SNOW-868).\n   *\n   * A blob's ``mb`` is computed per TILE at ``WORST_CASE_BYTES_PER_TILE`` \u2014\n   * server-side for a region, ``buildBlob`` for a custom area \u2014 and neither\n   * knows which basemap will be fetched. Two things follow from that, and\n   * this is where both are corrected:\n   *\n   *   - a multi-source style fetches one tile per source per cell, so it\n   *     costs a multiple of the ground (SNOW-843); and\n   *   - a national style's tiles are simply fatter than the default\n   *     basemap's \u2014 60.8 KB against 25.2 measured \u2014 so the same tile count\n   *     costs more (SNOW-868). See ``BYTES_PER_TILE_BY_BASEMAP``.\n   *\n   * Given ``count`` this recomputes from the tile count rather than scaling\n   * ``mb``, because ``mb`` already has ``DOWNLOAD_DOCUMENTS_MB`` folded in\n   * and scaling it would inflate the allowance too \u2014 the pre-SNOW-868 code\n   * charged the documents once PER SOURCE. Every blob carries ``count``\n   * (``{band, count, mb, over_ceiling, centre_tile, z}``, and it is one of\n   * ``basemap_tiles._SUMMARY_KEYS``), so the ``mb``-only path below is a\n   * fallback for a caller holding nothing but the number.\n   *\n   * @param {number} mb The blob's own per-tile estimate.\n   * @param {string | string[] | string[][] | null | undefined} spec\n   * @param {number} [count] The blob's tile count, when the caller has it.\n   * @returns {number} ``mb`` unchanged when the style is UNRESOLVED \u2014 an\n   *   unknown basemap must not inflate an estimate on a guess. Note this is\n   *   an unresolved-spec test, not the single-source one it was before\n   *   SNOW-868: a single-source NATIONAL style (ign_plan, basemap_at) still\n   *   costs more than the fallback and must be priced.\n   */\n  function sourceScaledMb(mb, spec, count) {\n    const sources = tileSourceCount(spec);\n    if (!Number.isFinite(mb) || sources <= 0) return mb;\n    const bytesPerTile = bytesPerTileForSources(spec);\n    const bytesPerMb = 1024 * 1024;\n    if (Number.isFinite(count) && count >= 0) {\n      return Math.ceil((count * sources * bytesPerTile) / bytesPerMb) + DOWNLOAD_DOCUMENTS_MB;\n    }\n    // No count: scale the TILE half of ``mb`` only, then put the documents\n    // allowance back. Exactly a no-op when the fallback figure applies to a\n    // single-source style, which is the arithmetic ``buildBlob`` did.\n    const tileMb = Math.max(0, mb - DOWNLOAD_DOCUMENTS_MB);\n    return (\n      Math.ceil((tileMb * sources * bytesPerTile) / WORST_CASE_BYTES_PER_TILE) +\n      DOWNLOAD_DOCUMENTS_MB\n    );\n  }\n\n  /**\n   * Expand a full basemap_download blob's ``z`` ranges into tile URLs.\n   *\n   * SNOW-843: one URL per tile PER SOURCE, each from the host MapLibre will\n   * ask that source for \u2014 see ``tileSources`` and ``tileURLForSource``.\n   *\n   * @param {string | string[][]} spec The style's tile sources \u2014 a\n   *   ``{z}``/``{x}``/``{y}`` template string (one source, one host) or the\n   *   ``string[][]`` shape ``tileSources`` normalises to.\n   * @param {{z?: Object<string, number[] | Object<string, number[]>>}} blob\n   *   The full blob \u2014 either fetched from\n   *   ``/api/region-basemap-tiles/?id=...`` or built locally by\n   *   ``buildBlob`` (``{band, count, mb, over_ceiling, centre_tile, z}``\n   *   \u2014 see ``regions/services/basemap_tiles.py``'s module docstring).\n   *   Each zoom's ``z[zoom]`` is either shape ``zoomRows`` accepts.\n   * @returns {string[]}\n   */\n  function rangesToTileURLs(spec, blob) {\n    const urls = [];\n    const sources = tileSources(spec);\n    if (!sources.length || !blob || !blob.z) return urls;\n    for (const zKey of Object.keys(blob.z)) {\n      const z = Number(zKey);\n      const rows = zoomRows(blob.z[zKey]);\n      for (const yKey of Object.keys(rows)) {\n        const y = Number(yKey);\n        const [xmin, xmax] = rows[yKey];\n        for (let x = xmin; x <= xmax; x++) {\n          for (const url of tileURLs(sources, z, x, y)) urls.push(url);\n        }\n      }\n    }\n    return urls;\n  }\n\n\n  /**\n   * Web Mercator ``[x, y]`` tile indices for ``(lon, lat)`` at zoom ``z``.\n   *\n   * Deliberate re-port of ``basemap_tiles.lon_lat_to_tile`` \u2014 see the\n   * module header above for why. Not clamped to the valid\n   * ``[0, 2**z - 1]`` range; ``tileRangesForBBox`` clamps explicitly,\n   * matching the Python.\n   *\n   * @param {number} lon Longitude in degrees.\n   * @param {number} lat Latitude in degrees.\n   * @param {number} z Zoom level.\n   * @returns {[number, number]}\n   */\n  function lonLatToTile(lon, lat, z) {\n    const n = Math.pow(2, z);\n    const [wx, wy] = lonLatToWorld(lon, lat);\n    return [Math.floor(wx * n), Math.floor(wy * n)];\n  }\n\n  /**\n   * ``(lon, lat)`` as UNFLOORED Web Mercator world coordinates \u2014 the same\n   * projection ``lonLatToTile`` floors, expressed as fractions of the\n   * whole world in ``[0, 1]`` (x eastward from the antimeridian, y\n   * southward from the north pole). Multiply by ``2**z`` for fractional\n   * tile indices at zoom ``z``.\n   *\n   * Factored out of ``lonLatToTile`` (whose arithmetic it reproduces\n   * operation-for-operation, so the golden vector is unaffected) because\n   * ``budgetScaleForBBox`` below needs the projection WITHOUT the floor:\n   * a rectangle's tile cost has to vary continuously with its size for\n   * the frame to resize smoothly.\n   *\n   * @param {number} lon Longitude in degrees.\n   * @param {number} lat Latitude in degrees.\n   * @returns {[number, number]}\n   */\n  function lonLatToWorld(lon, lat) {\n    const x = (lon + 180.0) / 360.0;\n    const latRad = (lat * Math.PI) / 180.0;\n    const y = (1.0 - Math.log(Math.tan(latRad) + 1.0 / Math.cos(latRad)) / Math.PI) / 2.0;\n    return [x, y];\n  }\n\n  /**\n   * Tile-index ranges covering ``bbox`` for every zoom in ``[minZ, maxZ]``.\n   *\n   * Deliberate re-port of ``basemap_tiles.tile_ranges``.\n   *\n   * @param {[number, number, number, number]} bbox ``[west, south, east,\n   *   north]`` in degrees.\n   * @param {number} minZ Shallowest zoom level (inclusive).\n   * @param {number} maxZ Deepest zoom level (inclusive).\n   * @returns {Object<string, [number, number, number, number]>}\n   *   ``{\"<z>\": [xmin, xmax, ymin, ymax]}`` \u2014 one entry per zoom level,\n   *   with indices clamped to the valid ``[0, 2**z - 1]`` range.\n   */\n  function tileRangesForBBox(bbox, minZ, maxZ) {\n    const [west, south, east, north] = bbox;\n    const ranges = {};\n    for (let z = minZ; z <= maxZ; z++) {\n      const [x0, y0] = lonLatToTile(west, north, z);\n      const [x1, y1] = lonLatToTile(east, south, z);\n      let xmin = Math.min(x0, x1);\n      let xmax = Math.max(x0, x1);\n      let ymin = Math.min(y0, y1);\n      let ymax = Math.max(y0, y1);\n      const maxIndex = Math.pow(2, z) - 1;\n      xmin = Math.max(0, Math.min(xmin, maxIndex));\n      xmax = Math.max(0, Math.min(xmax, maxIndex));\n      ymin = Math.max(0, Math.min(ymin, maxIndex));\n      ymax = Math.max(0, Math.min(ymax, maxIndex));\n      ranges[String(z)] = [xmin, xmax, ymin, ymax];\n    }\n    return ranges;\n  }\n\n  /**\n   * Total tile count across every zoom level in ``ranges``.\n   *\n   * Deliberate re-port of ``basemap_tiles.tile_count`` (rectangle\n   * ranges) \u2014 but, via ``zoomRows``, also correct for a clipped region\n   * blob's row-span ``z`` (SNOW-583's ``row_tile_count`` counterpart),\n   * so one function serves both shapes.\n   *\n   * @param {Object<string, number[] | Object<string, number[]>>} ranges\n   *   The ``{\"<z>\": ...}`` shape returned by ``tileRangesForBBox``, or a\n   *   full blob's ``z``.\n   * @returns {number}\n   */\n  function tileCount(ranges) {\n    let total = 0;\n    for (const key of Object.keys(ranges)) {\n      const rows = zoomRows(ranges[key]);\n      for (const y of Object.keys(rows)) {\n        const [xmin, xmax] = rows[y];\n        total += xmax - xmin + 1;\n      }\n    }\n    return total;\n  }\n\n  /**\n   * The tile at ``bbox``'s centre point, at zoom ``z``. Recorded on a\n   * download's blob as ``centre_tile``; ``map.js``'s ``_probeDone`` reads\n   * it back off the stored record rather than re-deriving a URL for it.\n   *\n   * Deliberate re-port of ``basemap_tiles.centre_tile``.\n   *\n   * @param {[number, number, number, number]} bbox ``[west, south, east,\n   *   north]`` in degrees.\n   * @param {number} z Zoom level \u2014 the download's detail floor\n   *   (``MICRO_BAND[1]``).\n   * @returns {{z: number, x: number, y: number}}\n   */\n  function centreTile(bbox, z) {\n    const [west, south, east, north] = bbox;\n    const centreLon = (west + east) / 2.0;\n    const centreLat = (south + north) / 2.0;\n    const [x, y] = lonLatToTile(centreLon, centreLat, z);\n    return { z: z, x: x, y: y };\n  }\n\n  /**\n   * Build the full download blob for ``bbox`` \u2014 the SAME shape\n   * ``rangesToTileURLs`` consumes, and the same shape\n   * ``/api/region-basemap-tiles/`` serves for a region download.\n   *\n   * Deliberate re-port of ``basemap_tiles.build_blob``.\n   *\n   * @param {[number, number, number, number]} bbox ``[west, south, east,\n   *   north]`` in degrees.\n   * @param {number} minZ The shallowest zoom level (``MICRO_BAND[0]``).\n   * @param {number} maxZ The detail floor (``MICRO_BAND[1]``).\n   * @returns {{band: [number, number], count: number, mb: number,\n   *   over_ceiling: boolean, centre_tile: {z: number, x: number, y:\n   *   number}, z: Object<string, number[]>}}\n   */\n  function buildBlob(bbox, minZ, maxZ, ceilingMb) {\n    const ranges = tileRangesForBBox(bbox, minZ, maxZ);\n    const count = tileCount(ranges);\n    const totalBytes = count * WORST_CASE_BYTES_PER_TILE;\n    // Plus the run's non-tile documents \u2014 see DOWNLOAD_DOCUMENTS_MB. Added\n    // after the round-up so the two terms cannot both round the same\n    // megabyte up.\n    const mb = Math.ceil(totalBytes / (1024 * 1024)) + DOWNLOAD_DOCUMENTS_MB;\n    return {\n      band: [minZ, maxZ],\n      count: count,\n      mb: mb,\n      over_ceiling: mb > resolveCeilingMb(ceilingMb),\n      centre_tile: centreTile(bbox, maxZ),\n      z: ranges,\n    };\n  }\n\n  /**\n   * Build a download blob for a CIRCLE rather than a box (hack mode).\n   *\n   * Same shape as ``buildBlob`` and interchangeable with it everywhere \u2014\n   * the ``z`` map is written as row spans (``{\"<z>\": {\"<y>\": [xmin,\n   * xmax]}}``) instead of a rectangle, which every consumer already\n   * handles: ``zoomRows`` normalises the two, and row spans are how a\n   * REGION download clips its tiles to the region's boundary\n   * (``basemap_tiles.build_region_blob``). This is the same trick against\n   * a shape whose clipping needs no polygon maths.\n   *\n   * Why it is worth doing at all. The drop zone draws a circle, and a\n   * circle is what the user chose; downloading its bounding box fetched a\n   * fifth more tiles than they asked for and \u2014 the part that showed \u2014 drew\n   * a SQUARE on the map afterwards. The downloaded-tiles overlay does not\n   * render the stored bbox: it reads the real cached tiles out of Cache\n   * Storage and draws one square per tile (``map.js``'s\n   * ``refreshDownloadedOverlay``), so the shape on screen is exactly the\n   * shape of what was fetched. Clipping here is therefore the whole fix \u2014\n   * no overlay change, no new geometry to store.\n   *\n   * Per row, the widest part of the circle within that row's latitude band\n   * is at the latitude NEAREST the centre (the band's own edge, or the\n   * centre's latitude for the row containing it). Taking the span there\n   * over-includes a tile whose corner clips the circle, which is the right\n   * direction: a tile the circle touches is a tile the map will ask for.\n   *\n   * Equirectangular, matching ``map_drop_zone.js``'s own circle geometry \u2014\n   * the ring drawn on screen and the tiles fetched under it have to agree\n   * with each other more than either has to be geodesic.\n   *\n   * Client-only, like ``budgetScaleForBBox``: the server never sizes one of\n   * these, and there is no ``basemap_tiles.py`` twin to keep it honest\n   * against.\n   *\n   * @param {number} lat Centre latitude.\n   * @param {number} lon Centre longitude.\n   * @param {number} radiusKm Radius in kilometres.\n   * @param {number} minZ Shallowest zoom (inclusive).\n   * @param {number} maxZ Detail floor (inclusive).\n   * @param {number} [ceilingMb] What ``over_ceiling`` is measured against;\n   *   defaults to ``DOWNLOAD_CEILING_MB``.\n   * @returns {{band: [number, number], count: number, mb: number,\n   *   over_ceiling: boolean, centre_tile: {z: number, x: number, y:\n   *   number}, z: Object<string, Object<string, [number, number]>>}}\n   */\n  function circleBlob(lat, lon, radiusKm, minZ, maxZ, ceilingMb) {\n    const latDelta = radiusKm / KM_PER_DEGREE_LAT;\n    const bbox = [\n      lon - radiusKm / (KM_PER_DEGREE_LAT * Math.cos((lat * Math.PI) / 180)),\n      lat - latDelta,\n      lon + radiusKm / (KM_PER_DEGREE_LAT * Math.cos((lat * Math.PI) / 180)),\n      lat + latDelta,\n    ];\n    const ranges = {};\n    let count = 0;\n    for (let z = minZ; z <= maxZ; z++) {\n      const [, southY] = lonLatToTile(bbox[0], bbox[1], z);\n      const [, northY] = lonLatToTile(bbox[0], bbox[3], z);\n      const rows = {};\n      // Mercator tile y runs southward, so the north edge has the lower y.\n      for (let y = northY; y <= southY; y++) {\n        const [, tileSouth, , tileNorth] = tileBounds(z, 0, y);\n        // The latitude in this row closest to the centre \u2014 where the\n        // circle is at its widest within the row.\n        const nearLat = Math.min(Math.max(lat, tileSouth), tileNorth);\n        const dLatKm = Math.abs(nearLat - lat) * KM_PER_DEGREE_LAT;\n        if (dLatKm > radiusKm) continue;\n        const halfKm = Math.sqrt(radiusKm * radiusKm - dLatKm * dLatKm);\n        const cos = Math.cos((nearLat * Math.PI) / 180);\n        // A row at the pole would divide by ~0; nothing this control is for\n        // goes there, and clamping is cheaper than reasoning about it.\n        const halfLon = halfKm / (KM_PER_DEGREE_LAT * Math.max(cos, 1e-6));\n        const [xmin] = lonLatToTile(lon - halfLon, nearLat, z);\n        const [xmax] = lonLatToTile(lon + halfLon, nearLat, z);\n        rows[String(y)] = [xmin, xmax];\n        count += xmax - xmin + 1;\n      }\n      ranges[String(z)] = rows;\n    }\n    const mb =\n      Math.ceil((count * WORST_CASE_BYTES_PER_TILE) / (1024 * 1024)) + DOWNLOAD_DOCUMENTS_MB;\n    return {\n      band: [minZ, maxZ],\n      count: count,\n      mb: mb,\n      over_ceiling: mb > resolveCeilingMb(ceilingMb),\n      centre_tile: centreTile(bbox, maxZ),\n      z: ranges,\n    };\n  }\n\n  /**\n   * SNOW-1136: the drop-zone blob for a STORED box \u2014 ``circleBlob`` over the\n   * circle ``bbox`` bounds.\n   *\n   * A drop zone's account row carries only its ``bbox`` and ``shape:\n   * 'circle'``; no centre or radius is synced, because the box already\n   * says both. ``map_drop_zone.js`` stores ``circleBBox(centre, radius)``,\n   * which is ``radius / KM_PER_DEGREE_LAT`` degrees either side of the\n   * centre in latitude \u2014 so the centre is the box's midpoint and the\n   * radius is half its north\u2013south extent, in the same equirectangular\n   * arithmetic ``circleBlob`` itself uses. Restoring through this fetches\n   * the same clipped tile set the drop fetched, not the box around it.\n   *\n   * @param {number[]} bbox ``[west, south, east, north]`` in (lon, lat).\n   * @param {number} minZ Shallowest zoom (inclusive).\n   * @param {number} maxZ Detail floor (inclusive).\n   * @param {number} [ceilingMb] As ``circleBlob``.\n   * @returns {ReturnType<typeof circleBlob>}\n   */\n  function circleBlobForBBox(bbox, minZ, maxZ, ceilingMb) {\n    const lat = (bbox[1] + bbox[3]) / 2;\n    const lon = (bbox[0] + bbox[2]) / 2;\n    const radiusKm = ((bbox[3] - bbox[1]) / 2) * KM_PER_DEGREE_LAT;\n    return circleBlob(lat, lon, radiusKm, minZ, maxZ, ceilingMb);\n  }\n\n  /**\n   * The largest factor in ``[0, 1]`` by which ``bbox`` may be scaled\n   * about its centre while a ``[minZ, maxZ]`` download of the result\n   * still fits under ``DOWNLOAD_CEILING_MB``. ``1`` when ``bbox`` already\n   * fits, so a caller can treat \"1\" as \"no cap needed\".\n   *\n   * Why closed-form rather than shrinking until ``buildBlob`` comes in\n   * under the ceiling: ``buildBlob``'s count is a STEP function of the\n   * box, because the tile indices are floored. Two boxes of identical\n   * size sitting a few metres apart on the tile grid can differ by a\n   * whole row and column of tiles, so inverting that count by search\n   * returns a size that depends on where the box is, not just how big it\n   * is \u2014 the framing rectangle then shimmers as the map pans beneath it\n   * and stutters as it zooms (SNOW-566). This models the cost with the\n   * floors removed, which makes the answer a smooth, monotone function of\n   * the box alone.\n   *\n   * The model is a strict UPPER bound on the true count, so the box it\n   * sizes never exceeds the ceiling. Per axis, a span of ``t`` fractional\n   * tiles covers ``floor(a + t) - floor(a) + 1 < t + 2`` whole ones \u2014 so\n   * summing ``(sx*2**z + 2) * (sy*2**z + 2)`` over the band bounds the\n   * blob's count for scale ``s``, and setting that equal to the budget\n   * leaves a quadratic in ``s`` to solve directly. Being an upper bound it\n   * leaves roughly a tile's worth of headroom per axis (a few percent of\n   * the ceiling) unspent, which is the price of a frame that resizes\n   * smoothly \u2014 and cheap against a per-tile byte estimate that is itself\n   * a worst case.\n   *\n   * Scaling is assumed to scale the ground footprint linearly, which is\n   * exact for the un-pitched view this map is used in. Under pitch the\n   * footprint grows faster than the frame does, so the linear model\n   * OVER-states the cost of a shrunken frame \u2014 the answer stays under the\n   * ceiling, it just leaves more headroom.\n   *\n   * @param {[number, number, number, number]} bbox ``[west, south, east,\n   *   north]`` in degrees, at scale 1.\n   * @param {number} minZ Shallowest zoom level (inclusive).\n   * @param {number} maxZ Deepest zoom level (inclusive).\n   * @param {number} [sourceCount] SNOW-843: how many vector sources the\n   *   active style fetches per tile. A two-source style costs twice the\n   *   ground, so the frame it may draw is the one whose HALVED tile budget\n   *   still fits the ceiling. Defaults to 1 \u2014 the single-source case, and\n   *   the shape the golden vector asserts.\n   * @param {number} [ceilingMb] The ceiling to size against; defaults to\n   *   ``DOWNLOAD_CEILING_MB``.\n   * @param {number} [bytesPerTile] SNOW-868: what one tile of the active\n   *   basemap costs, per source \u2014 ``bytesPerTileForSources``. Defaults to\n   *   ``WORST_CASE_BYTES_PER_TILE``, which leaves the golden vector and\n   *   the default basemap untouched.\n   *\n   *   This MUST move in step with ``sourceScaledMb``: sizing the frame at\n   *   50 KB a tile while pricing the same box at 96 KB means the frame the\n   *   control lets you draw is always over the ceiling, and\n   *   ``map_custom_download.js``'s ``confirmBtn.disabled = overCeiling ||\n   *   \u2026`` then latches Download off for good on every national basemap.\n   * @returns {number} A factor in ``(0, 1]``.\n   */\n  function budgetScaleForBBox(bbox, minZ, maxZ, sourceCount, ceilingMb, bytesPerTile) {\n    const [west, south, east, north] = bbox;\n    // Whole tiles, not MB: buildBlob rounds bytes UP to the next MB, so a\n    // count at exactly this budget is the largest that still reports\n    // ``mb <= ceiling``. The documents come off the ceiling first \u2014 they\n    // are fetched whatever the area's size, so they are not part of what\n    // scaling the box can trade away.\n    const sources = Number.isFinite(sourceCount) && sourceCount > 1 ? sourceCount : 1;\n    const tileBudgetMb = Math.max(1, resolveCeilingMb(ceilingMb) - DOWNLOAD_DOCUMENTS_MB);\n    const perTile =\n      Number.isFinite(bytesPerTile) && bytesPerTile > 0 ? bytesPerTile : WORST_CASE_BYTES_PER_TILE;\n    const budget = (tileBudgetMb * 1024 * 1024) / (perTile * sources);\n    // World-fraction spans. Longitude is linear in the projection and\n    // latitude is not, hence the Mercator y difference rather than a\n    // degree one.\n    const spanX = Math.abs(east - west) / 360.0;\n    const spanY = Math.abs(lonLatToWorld(west, south)[1] - lonLatToWorld(west, north)[1]);\n    // Coefficients of the cost quadratic a*s^2 + b*s + c, summed over the\n    // band: a from the two spans together, b from each span against the\n    // per-axis slack, c from the slack alone (the cost of a box small\n    // enough to be a point \u2014 one to four tiles at every level).\n    let a = 0;\n    let b = 0;\n    let c = 0;\n    for (let z = minZ; z <= maxZ; z++) {\n      const n = Math.pow(2, z);\n      a += spanX * n * spanY * n;\n      b += 2 * (spanX * n + spanY * n);\n      c += 4;\n    }\n    if (a + b + c <= budget) return 1;\n    if (a <= 0) {\n      // A degenerate (zero-area) box can only exceed the budget through\n      // its slack term, which no amount of scaling removes.\n      return b > 0 ? Math.max(0, Math.min(1, (budget - c) / b)) : 0;\n    }\n    const scale = (-b + Math.sqrt(b * b + 4 * a * (budget - c))) / (2 * a);\n    return Math.max(0, Math.min(1, scale));\n  }\n\n  /**\n   * SNOW-568: whether a download of ``mb`` megabytes fits in the origin's\n   * remaining storage quota.\n   *\n   * Takes the already-resolved ``navigator.storage.estimate()`` result\n   * rather than calling it, so this stays a pure function of its\n   * arguments (and unit-testable without a Storage API).\n   *\n   * The estimate is deliberately conservative on both sides. ``mb`` is the\n   * download's own worst case (``WORST_CASE_BYTES_PER_TILE`` per tile \u2014\n   * real vector tiles are far smaller), and it is required to fit inside\n   * ``STORAGE_HEADROOM_FACTOR`` of what's left rather than all of it: a\n   * browser starts evicting an origin's storage as it approaches the\n   * quota, and an area download that lands exactly at the limit would be\n   * the first thing evicted. Refusing early costs the user a smaller\n   * frame; not refusing costs them a download that appears to succeed and\n   * is gone by the time they are offline and need it.\n   *\n   * Returns true when the estimate is unusable (Storage API absent, or a\n   * browser reporting no quota) \u2014 an unknown quota must not block a\n   * download that would have worked. The run's own ``QuotaExceededError``\n   * handling is the backstop for that case.\n   *\n   * @param {{quota?: number, usage?: number}|null|undefined} estimate\n   * @param {number} mb Estimated download size in megabytes.\n   * @returns {boolean}\n   */\n  /**\n   * The largest download this device may hold, in megabytes.\n   *\n   * The ceiling, and the answer to \"how big may one download be\": as much\n   * as the device can take. Nothing else about the app has an opinion \u2014\n   * an app-chosen cap either refuses a download a phone had room for, or\n   * waves through one it did not, and only the device knows which.\n   *\n   * This is the exact inverse of ``hasStorageHeadroom`` below, deliberately\n   * so: the largest ``mb`` that function will pass is the number this one\n   * returns, which is what keeps the frame a user is offered and the\n   * pre-flight that accepts it from ever disagreeing. ``STORAGE_HEADROOM_\n   * FACTOR`` is not an app cap in disguise \u2014 it is the margin a browser\n   * needs before it starts evicting the origin, and a download that lands\n   * exactly at the quota is the first thing it takes back.\n   *\n   * Pure, like its inverse: takes the resolved estimate rather than calling\n   * ``navigator.storage.estimate()``.\n   *\n   * Falls back to ``DOWNLOAD_CEILING_MB`` when the device will not say\n   * (no Storage API, or a browser reporting no quota) \u2014 an unknown device\n   * gets the old constant rather than an unbounded download.\n   *\n   * Floored at 1 MB: a device with nothing left yields a ceiling that no\n   * area could ever meet, and every surface that reads this would have to\n   * grow a second empty state to say so. The quota pre-flight refuses that\n   * download on its own, with a message about storage, which is the honest\n   * place for it.\n   *\n   * @param {{quota?: number, usage?: number}|null|undefined} estimate\n   * @returns {number} Megabytes.\n   */\n  function deviceCeilingMb(estimate) {\n    if (!estimate) return DOWNLOAD_CEILING_MB;\n    const quota = Number(estimate.quota);\n    const usage = Number(estimate.usage);\n    if (!Number.isFinite(quota) || quota <= 0) return DOWNLOAD_CEILING_MB;\n    if (!Number.isFinite(usage) || usage < 0) return DOWNLOAD_CEILING_MB;\n    const free = Math.max(0, quota - usage) * STORAGE_HEADROOM_FACTOR;\n    return Math.max(1, Math.floor(free / (1024 * 1024)));\n  }\n\n  /**\n   * Read a caller-supplied ceiling, falling back to the constant.\n   *\n   * One place, so ``buildBlob`` and ``budgetScaleForBBox`` can never\n   * disagree about what a missing, zero or nonsense ceiling means \u2014 the\n   * frame a user is offered and the flag that disables the button are the\n   * same question asked twice.\n   *\n   * @param {number|null|undefined} ceilingMb\n   * @returns {number} Megabytes.\n   */\n  function resolveCeilingMb(ceilingMb) {\n    const mb = Number(ceilingMb);\n    return Number.isFinite(mb) && mb > 0 ? mb : DOWNLOAD_CEILING_MB;\n  }\n\n  function hasStorageHeadroom(estimate, mb) {\n    if (!estimate) return true;\n    const quota = Number(estimate.quota);\n    const usage = Number(estimate.usage);\n    if (!Number.isFinite(quota) || quota <= 0) return true;\n    if (!Number.isFinite(usage) || usage < 0) return true;\n    const needed = Number(mb) * 1024 * 1024;\n    if (!Number.isFinite(needed) || needed <= 0) return true;\n    return needed <= (quota - usage) * STORAGE_HEADROOM_FACTOR;\n  }\n\n\n  /**\n   * ``bbox`` as a GeoJSON Polygon, wound anticlockwise from its\n   * south-west corner and explicitly closed.\n   *\n   * @param {[number, number, number, number]} bbox ``[west, south, east,\n   *   north]`` in degrees.\n   * @returns {{type: string, coordinates: number[][][]}}\n   */\n  function bboxPolygon(bbox) {\n    const [west, south, east, north] = bbox;\n    return {\n      type: 'Polygon',\n      coordinates: [\n        [\n          [west, south],\n          [east, south],\n          [east, north],\n          [west, north],\n          [west, south],\n        ],\n      ],\n    };\n  }\n\n  /**\n   * Which tiles of ``cachedURLs`` belong to ``template``, as ``{z, x, y}``.\n   *\n   * The inverse of the substitution ``rangesToTileURLs`` performs: the\n   * cache stores URLs, and the \"cached tiles\" overlay needs the tile\n   * indices back so it can draw each one's footprint. Reading them out of\n   * the URL is what makes the overlay honest \u2014 it renders what Cache\n   * Storage actually holds, not what a download record claims.\n   *\n   * Matching is per-template, so switching basemap changes the answer:\n   * tiles cached for one basemap's origin are genuinely not cached for\n   * another's.\n   *\n   * The placeholder order is read from each template rather than assumed \u2014\n   * see ``_tileMatcher`` below.\n   *\n   * SNOW-843: a tile counts as cached only when EVERY source holds it. A\n   * two-source style whose relief tiles are down but whose base tiles are\n   * not has nothing usable on that ground, and a square drawn for it would\n   * be the overlay telling the same lie the download record used to.\n   *\n   * @param {string | string[][]} spec The style's tile sources \u2014 a template\n   *   string or the ``string[][]`` shape ``tileSources`` normalises to.\n   * @param {Iterable<string>} cachedURLs URLs present in the cache.\n   * @param {number} [zoom] Keep only tiles at this zoom. Omit for all of\n   *   them \u2014 but note a download spans a whole band, so an unfiltered\n   *   result overlaps itself five deep.\n   * @returns {Array<{z: number, x: number, y: number}>}\n   */\n  function cachedTilesFromURLs(spec, cachedURLs, zoom) {\n    const out = [];\n    const sources = tileSources(spec);\n    if (!sources.length || !cachedURLs) return out;\n    // One matcher per URL of every source; a source whose templates are all\n    // unusable can never be satisfied, so the whole answer is empty \u2014 the\n    // same answer as \"no tiles cached for this basemap\".\n    const matchers = [];\n    for (const source of sources) {\n      const forSource = [];\n      for (const template of source) {\n        const matcher = _tileMatcher(template);\n        if (matcher) forSource.push(matcher);\n      }\n      if (!forSource.length) return out;\n      matchers.push(forSource);\n    }\n    // key -> {tile, sources: Set<number>}: a tile is kept once every source\n    // index has matched it.\n    const seen = new Map();\n    for (const url of cachedURLs) {\n      for (let i = 0; i < matchers.length; i++) {\n        for (const matcher of matchers[i]) {\n          const tile = matcher(url);\n          if (!tile) continue;\n          if (typeof zoom === 'number' && tile.z !== zoom) continue;\n          const key = tile.z + '/' + tile.x + '/' + tile.y;\n          let entry = seen.get(key);\n          if (!entry) {\n            entry = { tile: tile, sources: new Set() };\n            seen.set(key, entry);\n          }\n          entry.sources.add(i);\n        }\n      }\n    }\n    for (const entry of seen.values()) {\n      if (entry.sources.size === matchers.length) out.push(entry.tile);\n    }\n    return out;\n  }\n\n  /**\n   * A function reading ``{z, x, y}`` back out of a URL that ``template``\n   * could have produced, or ``null`` for a template that cannot be turned\n   * into a pattern at all.\n   *\n   * The placeholder ORDER is read from the template rather than assumed.\n   * Most templates are ``{z}/{x}/{y}``, but an ESRI VectorTileServer source\n   * is ``{z}/{y}/{x}`` (see ``map.js``'s style normalisation), and reading\n   * those transposed would draw every square in the wrong place.\n   *\n   * @param {string} template\n   * @returns {(function(string): ({z: number, x: number, y: number}|null))|null}\n   */\n  function _tileMatcher(template) {\n    if (typeof template !== 'string' || !template) return null;\n    const order = [];\n    template.replace(/\\{(z|x|y)\\}/g, (match, key) => {\n      order.push(key);\n      return match;\n    });\n    if (order.length !== 3) return null;\n    const pattern = template\n      .replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n      .replace(/\\\\\\{(z|x|y)\\\\\\}/g, '(\\\\d+)');\n    let re;\n    try {\n      re = new RegExp('^' + pattern + '$');\n    } catch (_e) {\n      return null;\n    }\n    return (url) => {\n      const match = re.exec(url);\n      if (!match) return null;\n      const tile = {};\n      for (let i = 0; i < order.length; i++) tile[order[i]] = Number(match[i + 1]);\n      return tile;\n    };\n  }\n\n  /**\n   * The ``[west, south, east, north]`` bounds of one Web Mercator tile.\n   *\n   * The inverse of ``lonLatToTile``: that floors a projected position to\n   * a tile index, this returns the ground the whole index covers. Round\n   * tripping is therefore one-way-exact \u2014 ``lonLatToTile`` of any point\n   * inside these bounds gives back ``(x, y)``, but the bounds are the\n   * tile's full extent, not the point that produced it.\n   *\n   * Client-only, like the rest of the tile-grid group: the server\n   * enumerates tile INDICES and never needs to know where they sit.\n   *\n   * @param {number} z Zoom level.\n   * @param {number} x Tile x index.\n   * @param {number} y Tile y index.\n   * @returns {[number, number, number, number]} ``[west, south, east,\n   *   north]`` in degrees.\n   */\n  function tileBounds(z, x, y) {\n    const n = Math.pow(2, z);\n    const west = (x / n) * 360.0 - 180.0;\n    const east = ((x + 1) / n) * 360.0 - 180.0;\n    // Mercator y runs southward, so y+1 is the SOUTHERN edge.\n    const north = _mercatorYToLat(y / n);\n    const south = _mercatorYToLat((y + 1) / n);\n    return [west, south, east, north];\n  }\n\n  /**\n   * A Web Mercator world y (``[0, 1]``, southward) back to a latitude.\n   *\n   * The inverse of ``lonLatToWorld``'s y term, factored out because\n   * ``tileBounds`` needs it for both of a tile's horizontal edges.\n   *\n   * @param {number} y World y in ``[0, 1]``.\n   * @returns {number} A latitude in degrees.\n   */\n  function _mercatorYToLat(y) {\n    return (Math.atan(Math.sinh(Math.PI * (1 - 2 * y))) * 180) / Math.PI;\n  }\n\n  /* ------------------------------------------------------------------ *\n   * SNOW-924: what an area's boundary CONTAINS.\n   *\n   * A download stopped at the tiles; everything else a user needs in the\n   * field arrived only if they happened to tap the overlay that draws it.\n   * These five functions answer \"which bulletins and which weather sit\n   * inside this area\", and they are all here rather than in `map.js`\n   * because they are pure functions of geometry \u2014 the same reason\n   * `bboxPolygon` and `tileGridPlan` are.\n   *\n   * THE CONTRACT, and the reason this group looks cruder than it could:\n   * inside the boundary, everything; outside, whatever happens to be\n   * there. Under-fetching is the only defect \u2014 a bulletin the user needed\n   * and does not have. Over-fetching is not: the content half is\n   * kilobytes against a tile half measured in megabytes.\n   *\n   * So the tests below are RECTANGLES, and deliberately so. A rectangle\n   * test can only ever select a SUPERSET of what true geometry would,\n   * which is the correct side to fail on, and it costs no\n   * point-in-polygon, no polygon clipping, no shared-edge or antimeridian\n   * cases. `tests/js/test_basemap_download_core.js` pins the superset\n   * property against real region boundaries; a future reader \"fixing\"\n   * this into exact geometry would be trading a free over-selection for\n   * a class of bug that leaves someone without a bulletin.\n   * ------------------------------------------------------------------ */\n\n  /**\n   * The lon/lat box a GeoJSON Polygon or MultiPolygon covers.\n   *\n   * SNOW-924 moved this out of `map.js`, where it had been since SNOW-811\n   * serving the region popup's fit and `pwaMapFocus.region()`. It is a\n   * pure function of coordinates, so it belongs with the rest of the\n   * geometry group; `map.js` keeps a one-line adapter because MapLibre's\n   * `fitBounds` wants the nested `[[w, s], [e, n]]` pair while everything\n   * here speaks the flat `[west, south, east, north]` this file uses\n   * throughout.\n   *\n   * @param {Object|null} feature A GeoJSON Feature.\n   * @returns {[number, number, number, number]|null} ``null`` for a\n   *   feature with no usable geometry, which every caller reads as\n   *   \"cannot say\" rather than \"empty\".\n   */\n  function featureBBox(feature) {\n    const geometry = feature && feature.geometry;\n    if (!geometry || !Array.isArray(geometry.coordinates)) return null;\n    const rings =\n      geometry.type === 'Polygon'\n        ? geometry.coordinates\n        : geometry.type === 'MultiPolygon'\n          ? geometry.coordinates.flat()\n          : null;\n    if (!rings) return null;\n    let w = Infinity;\n    let s = Infinity;\n    let e = -Infinity;\n    let n = -Infinity;\n    for (const ring of rings) {\n      if (!Array.isArray(ring)) continue;\n      for (const position of ring) {\n        const lon = position && position[0];\n        const lat = position && position[1];\n        if (!Number.isFinite(lon) || !Number.isFinite(lat)) continue;\n        if (lon < w) w = lon;\n        if (lon > e) e = lon;\n        if (lat < s) s = lat;\n        if (lat > n) n = lat;\n      }\n    }\n    return Number.isFinite(w) && Number.isFinite(s) ? [w, s, e, n] : null;\n  }\n\n  /**\n   * The ground a blob's tile ranges cover, as a lon/lat box.\n   *\n   * The way to a rectangle for a REGION area, which stores none: SNOW-583\n   * replaced a region record's `bbox` with `z`, the row spans its tiles\n   * were clipped to, on the reasoning that the region id is the whole\n   * definition. True for re-fetching it; not enough for asking what is\n   * inside it, which is what this ticket needs.\n   *\n   * Reads the DEEPEST zoom present, matching `gridZoomFor`'s choice and\n   * for the same reason \u2014 the finest tiles give the tightest box. Any\n   * zoom would be safe, since they all cover the same ground and a\n   * coarser one only over-states it; deepest is simply the least\n   * over-inclusive answer still on the correct side of the contract.\n   *\n   * Goes through `zoomRows`, as everything walking a blob's `z` must, so\n   * both the rectangle and the clipped row-span shapes work here.\n   *\n   * @param {Object|null} z A blob's ``z`` ranges.\n   * @returns {[number, number, number, number]|null} ``null`` for ranges\n   *   that yield no tiles.\n   */\n  function bboxFromZoomRanges(z) {\n    if (!z || typeof z !== 'object') return null;\n    const zooms = Object.keys(z)\n      .map((key) => parseInt(key, 10))\n      .filter(Number.isFinite);\n    if (zooms.length === 0) return null;\n    const zoom = Math.max(...zooms);\n    const rows = zoomRows(z[String(zoom)] !== undefined ? z[String(zoom)] : z[zoom]);\n    let minX = Infinity;\n    let maxX = -Infinity;\n    let minY = Infinity;\n    let maxY = -Infinity;\n    for (const key of Object.keys(rows || {})) {\n      const y = parseInt(key, 10);\n      const span = rows[key];\n      if (!Number.isFinite(y) || !Array.isArray(span)) continue;\n      if (y < minY) minY = y;\n      if (y > maxY) maxY = y;\n      if (span[0] < minX) minX = span[0];\n      if (span[1] > maxX) maxX = span[1];\n    }\n    if (!Number.isFinite(minX) || !Number.isFinite(minY)) return null;\n    // Mercator y runs southward, so the NORTHERN edge comes from the\n    // smallest y and the southern from the largest.\n    const [west, , , north] = tileBounds(zoom, minX, minY);\n    const [, south, east] = tileBounds(zoom, maxX, maxY);\n    return [west, south, east, north];\n  }\n\n  /**\n   * The rectangle an area covers, from its stored record alone.\n   *\n   * Two area kinds, one answer. A custom or drop-zone area IS its `bbox`;\n   * a region area has only `z`, so it goes through `bboxFromZoomRanges`.\n   * Taking the stored box first matters beyond being cheaper: it is the\n   * box the user actually framed, where the derived one is the tiles that\n   * box happened to land on, which is a hair larger.\n   *\n   * @param {Object|null} area A stored area record, or anything carrying\n   *   a `bbox` or a `z`.\n   * @returns {[number, number, number, number]|null}\n   */\n  function areaBBox(area) {\n    if (!area || typeof area !== 'object') return null;\n    const stored = area.bbox;\n    if (Array.isArray(stored) && stored.length === 4 && stored.every(Number.isFinite)) {\n      return [stored[0], stored[1], stored[2], stored[3]];\n    }\n    return bboxFromZoomRanges(area.z);\n  }\n\n  // SNOW-1312: an ISO date key, the shape every day below is held in.\n  const DATE_KEY_RE = /^\\d{4}-\\d{2}-\\d{2}$/;\n  const MS_PER_DAY = 86400000;\n\n  // SNOW-1312: the one country map.js's boot asks the DATED ratings feed\n  // for (`RATINGS_URL + '?d=' + day + '&country=ch'`, which map.html also\n  // preloads). The other countries paint from their season payloads, which\n  // the download already warms whole. The worker answers the feed on its\n  // exact url, so the warmed url is built in the boot's own parameter order.\n  const BOOT_RATINGS_COUNTRY = 'ch';\n\n  // SNOW-1379: the problem-terrain feed the map paints the day's slopes\n  // from \u2014 map.js's `refreshBulletinTerrainDay` asks for\n  // `/api/problem-terrain/?d=<day>` and nothing else, and the worker\n  // answers it offline on that exact url ('public-json'), so the warmed url\n  // is built the same way, byte for byte.\n  const PROBLEM_TERRAIN_URL = '/api/problem-terrain/';\n\n  // SNOW-1379: the countries the terrain-class tiles cover, by the prefix\n  // of a region id (\"CH-4115\" \u2192 \"CH\"). The same list as `TERRAIN_COUNTRIES`\n  // in map_slopes_notice_core.js and apps/map/problem_terrain.py; held\n  // here rather than imported because this core loads on pages that load\n  // neither.\n  const TERRAIN_COUNTRIES = Object.freeze(['CH']);\n\n  /**\n   * The days a download takes its content for: today and forward only\n   * (SNOW-1312).\n   *\n   * \"You're looking forward out in the field, not back\" (Hugo,\n   * 2026-10-30). Today's bulletin, tomorrow's once it is issued, and any\n   * forecast day the pipeline already holds \u2014 `ceiling` is that last known\n   * day, which the caller reads off the season ratings with\n   * `pwaCalendarCore.latestKnownDate` (SNOW-927) so the evening issue is\n   * picked up the moment it is published. SNOW-953's reach backwards is\n   * gone: a past day is history, and the map no longer saves it.\n   *\n   * The day on screen joins the list only when it is today or later,\n   * because a visitor who scrubbed to a forward day and then downloaded\n   * meant that day; a past day on screen is not saved.\n   *\n   * Shared by the map's download and `/offline/`'s Update, so the two can\n   * never save different days for the same area.\n   *\n   * @param {string} today The server's today, as an ISO key.\n   * @param {string} [ceiling] The latest known day; today when absent,\n   *   malformed or earlier.\n   * @param {string|null} [onScreen] The day the map is showing.\n   * @returns {string[]} ISO keys, oldest first; empty for an unreadable\n   *   `today`.\n   */\n  function forwardContentDays(today, ceiling, onScreen) {\n    if (typeof today !== 'string' || !DATE_KEY_RE.test(today)) return [];\n    const todayMs = Date.parse(today);\n    if (!Number.isFinite(todayMs)) return [];\n    const end =\n      typeof ceiling === 'string' && DATE_KEY_RE.test(ceiling) && ceiling > today\n        ? ceiling\n        : today;\n    const endMs = Date.parse(end);\n    const days = [];\n    for (let ms = todayMs; ms <= endMs; ms += MS_PER_DAY) {\n      days.push(new Date(ms).toISOString().slice(0, 10));\n    }\n    if (\n      typeof onScreen === 'string' &&\n      DATE_KEY_RE.test(onScreen) &&\n      onScreen >= today &&\n      !days.includes(onScreen)\n    ) {\n      days.push(onScreen);\n      days.sort();\n    }\n    return days;\n  }\n\n  /**\n   * One region sheet's url for one day (SNOW-1312).\n   *\n   * The map's own partial, `/partials/region-sheet/<id>/?d=<day>`, as\n   * `map_region_sheet.js` asks for it: the id LOWERCASED (the view 301s\n   * any other case) and `d` first. The sheet may add `r=` after it \u2014 the\n   * reports cache-buster, SNOW-1295 \u2014 which the worker ignores when it\n   * keys the entry, so the url warmed here is the key the offline read\n   * looks up whatever `r` the sheet sends.\n   *\n   * @param {string} template A url carrying ``XX-0000``, as `#map`'s\n   *   `data-region-sheet-url` does.\n   * @param {string} regionId The region's EAWS id.\n   * @param {string} day An ISO date key.\n   * @returns {string}\n   */\n  function regionSheetURL(template, regionId, day) {\n    return (\n      template.replace('XX-0000', encodeURIComponent(String(regionId).toLowerCase())) +\n      '?d=' +\n      encodeURIComponent(day)\n    );\n  }\n\n  /**\n   * One resort's place-sheet url for one day (SNOW-1318).\n   *\n   * The map's own request, as `map_place_sheet.js` makes it: the slug in\n   * place of the template's ``__SLUG__``, then `?d=<day>`. The worker\n   * keeps the sheet under its path and `d` ('public-partial'), the key the\n   * offline read looks up.\n   *\n   * @param {string} template A url carrying ``__SLUG__``, as `#map`'s\n   *   `data-resort-sheet-url` does.\n   * @param {string} slug The resort's slug.\n   * @param {string} day An ISO date key.\n   * @returns {string}\n   */\n  function resortSheetURL(template, slug, day) {\n    return (\n      template.replace('__SLUG__', encodeURIComponent(String(slug))) +\n      '?d=' +\n      encodeURIComponent(day)\n    );\n  }\n\n  /**\n   * The urls for what an area's boundary contains, from the server's answer.\n   *\n   * SNOW-953 replaced `areaContentPlan`, which made the SELECTION here \u2014\n   * walking `regions.geojson`'s features and testing each one's bounding\n   * box against the area's. Doing that meant loading every country's\n   * outlines first and awaiting them (SNOW-931), which is 764 KB over the\n   * wire to discover roughly 55 KB of pages, on the thin connection the\n   * whole feature exists to serve. `/api/area-content/` answers the same\n   * question from the boundaries it already holds, in one small request,\n   * and the failure mode SNOW-931 closed cannot recur \u2014 there is no\n   * \"which countries are loaded\" state left for the answer to depend on.\n   *\n   * What stays here is the url composition, which is a client concern:\n   * the day window comes from the caller (`forwardContentDays`: today to\n   * the last published day, SNOW-1312), and the templates come from the\n   * page's dataset.\n   *\n   * A bulletin URL is `/<region_id>/<slug>/<date>/`. The id is LOWERCASED\n   * because `bulletin_detail` is wrapped in `@lowercase_region_id` and\n   * 301s a mixed-case one \u2014 a redirect the service worker would cache as\n   * the entry for a URL nothing ever requests again.\n   *\n   * SNOW-1312: and, per region and day, the map's region sheet\n   * (`regionSheetURL`) \u2014 the body the sheet shows when a downloaded\n   * region is tapped offline \u2014 and, per day, the dated ratings feed the\n   * map boots its colours from (`?d=<day>&country=ch`). Each is a url\n   * the run warms and tallies, so a sheet or a feed that fails to land\n   * counts against the download exactly as a bulletin page does.\n   *\n   * SNOW-1318: and, per resort and day, the resort's place sheet\n   * (`resortSheetURL`) \u2014 what a resort tapped offline opens. Tallied the\n   * same way, so a resort sheet that fails to warm makes the download\n   * short.\n   *\n   * SNOW-1379: and, per day, the problem-terrain feed the map paints the\n   * day's slopes from (`/api/problem-terrain/?d=<day>`) \u2014 only for an area\n   * downloaded WITH terrain tiles (`options.terrain`) whose regions\n   * include one in a terrain country (`TERRAIN_COUNTRIES`, read off the\n   * region ids the endpoint answered with). Without the tiles there is\n   * nothing for the feed to paint on, and outside those countries the\n   * feed describes no slope of the area's.\n   *\n   * A weather sheet is ONE URL per location, not one per day: a forward\n   * `?date=` opens the same week as today's \u2014 today's row and the rows\n   * after it (SNOW-1337) \u2014 and the day picker selects among them\n   * client-side \u2014 see\n   * `docs/decisions/weather-day-picker-is-a-selector-not-navigation.md`.\n   * Fetching a URL per day would cache the same week seven times.\n   *\n   * SNOW-965: that one URL carries `?date=<weatherDay>` when the caller\n   * names the day \u2014 today \u2014 because it is the URL the map's weather\n   * sheet asks for (`map_weather_detail.js` always sends the map's day),\n   * and the service worker serves a sheet offline on an EXACT match\n   * only. An undated entry would be today's sheet stored under a key\n   * nothing ever reads. See `weatherDetailURL`.\n   *\n   * @param {Object} options\n   * @param {Array<{id?: string, slug?: string}>} [options.regions] The\n   *   endpoint's `regions` list. Absent or empty yields no bulletins.\n   * @param {Array<{short_id?: string}>} [options.weather] The endpoint's\n   *   `weather` list.\n   * @param {Array<{slug?: string}>} [options.resorts] SNOW-1318: the\n   *   endpoint's `resorts` list.\n   * @param {string[]} [options.days] Date keys to take a bulletin for,\n   *   supplied by the caller from `forwardContentDays`, never from a\n   *   clock in here.\n   * @param {string} [options.weatherDetailTemplate] A URL carrying\n   *   ``__SHORTID__``, as `#map`'s `data-weather-detail-url` does.\n   * @param {string} [options.weatherDay] SNOW-965: the ISO day each sheet\n   *   is taken for \u2014 today. Omitted, the sheets are undated.\n   * @param {string} [options.regionSheetTemplate] SNOW-1312: a url\n   *   carrying ``XX-0000``, as `#map`'s `data-region-sheet-url` does.\n   *   Omitted, no region sheets.\n   * @param {string} [options.resortSheetTemplate] SNOW-1318: a url\n   *   carrying ``__SLUG__``, as `#map`'s `data-resort-sheet-url` does.\n   *   Omitted, no resort sheets.\n   * @param {string} [options.ratingsUrl] SNOW-1312: the ratings feed's\n   *   base url (`/api/ratings/`). Omitted, no dated ratings.\n   * @param {string} [options.subdivisionsUrl] SNOW-1529: the sub-level\n   *   feed's base url (`/api/rating-subdivisions/`), dated per day like the\n   *   ratings, which the map's boot asks for beside them. Omitted, none.\n   * @param {boolean} [options.terrain] SNOW-1379: whether the area was\n   *   downloaded with terrain tiles (the area record's `terrain`). Omitted\n   *   or false, no problem-terrain feed.\n   * @returns {{bulletinUrls: string[], weatherDetailUrls: string[],\n   *   regionSheetUrls: string[], resortSheetUrls: string[],\n   *   ratingsUrls: string[], subdivisionsUrls: string[],\n   *   problemTerrainUrls: string[]}} Each list\n   *   deduplicated and stable in the server's order, so a run's URL list\n   *   is reproducible. The sheet, ratings and problem-terrain lists are\n   *   empty without days.\n   */\n  function areaContentURLs(options) {\n    const opts = options || {};\n    const out = {\n      bulletinUrls: [],\n      weatherDetailUrls: [],\n      regionSheetUrls: [],\n      resortSheetUrls: [],\n      ratingsUrls: [],\n      subdivisionsUrls: [],\n      problemTerrainUrls: [],\n    };\n\n    const days = Array.isArray(opts.days) ? Array.from(new Set(opts.days.filter(Boolean))) : [];\n    const sheetTemplate = opts.regionSheetTemplate || '';\n    const seenRegion = new Set();\n    let inTerrainCountry = false;\n    for (const region of opts.regions || []) {\n      const regionId = region && region.id;\n      const slug = region && region.slug;\n      if (!regionId || !slug) continue;\n      // Deduplicated on the LOWERCASED id: the url is lowercase, so two\n      // spellings of one region would otherwise name one url twice.\n      const key = String(regionId).toLowerCase();\n      if (seenRegion.has(key)) continue;\n      seenRegion.add(key);\n      if (TERRAIN_COUNTRIES.includes(key.split('-')[0].toUpperCase())) inTerrainCountry = true;\n      for (const day of days) {\n        out.bulletinUrls.push('/' + key + '/' + slug + '/' + day + '/');\n        if (sheetTemplate) out.regionSheetUrls.push(regionSheetURL(sheetTemplate, key, day));\n      }\n    }\n\n    const resortTemplate = opts.resortSheetTemplate || '';\n    if (resortTemplate) {\n      const seenResort = new Set();\n      for (const resort of opts.resorts || []) {\n        const slug = resort && resort.slug;\n        if (!slug || seenResort.has(slug)) continue;\n        seenResort.add(slug);\n        for (const day of days) out.resortSheetUrls.push(resortSheetURL(resortTemplate, slug, day));\n      }\n    }\n\n    if (opts.ratingsUrl) {\n      for (const day of days) {\n        out.ratingsUrls.push(\n          opts.ratingsUrl + '?d=' + encodeURIComponent(day) + '&country=' + BOOT_RATINGS_COUNTRY,\n        );\n      }\n    }\n\n    if (opts.subdivisionsUrl) {\n      for (const day of days) {\n        out.subdivisionsUrls.push(\n          opts.subdivisionsUrl + '?d=' + encodeURIComponent(day) + '&country=' + BOOT_RATINGS_COUNTRY,\n        );\n      }\n    }\n\n    if (opts.terrain && inTerrainCountry) {\n      for (const day of days) out.problemTerrainUrls.push(problemTerrainURL(day));\n    }\n\n    const template = opts.weatherDetailTemplate;\n    if (template) {\n      const seenLocation = new Set();\n      for (const point of opts.weather || []) {\n        const shortId = point && point.short_id;\n        if (!shortId || seenLocation.has(shortId)) continue;\n        seenLocation.add(shortId);\n        out.weatherDetailUrls.push(weatherDetailURL(template, shortId, opts.weatherDay));\n      }\n    }\n\n    return out;\n  }\n\n  /**\n   * The problem-terrain feed's url for one day (SNOW-1379).\n   *\n   * The url map.js's `refreshBulletinTerrainDay` fetches \u2014\n   * `/api/problem-terrain/?d=<day>`, `d` alone \u2014 so the copy a download\n   * warms is the one the worker finds offline.\n   *\n   * @param {string} day An ISO date key.\n   * @returns {string}\n   */\n  function problemTerrainURL(day) {\n    return PROBLEM_TERRAIN_URL + '?d=' + encodeURIComponent(day);\n  }\n\n  /**\n   * One location's weather-sheet URL, dated when a day is given (SNOW-965).\n   *\n   * The map's weather sheet always asks with the map's day\n   * (`map_weather_detail.js`), and the service worker answers a sheet\n   * offline only on an exact match \u2014 an undated sheet names no day of its\n   * own (\"Today\" is relative), so serving it for another day would be a\n   * stale forecast claiming to be today's. Dating the warmed URL with the\n   * day it is warmed on makes it the URL the map reads on that day.\n   *\n   * @param {string} template A URL carrying ``__SHORTID__``.\n   * @param {string} shortId The location's short id.\n   * @param {string} [day] An ISO date key, or nothing for an undated URL.\n   * @returns {string}\n   */\n  function weatherDetailURL(template, shortId, day) {\n    const url = template.replace('__SHORTID__', shortId);\n    return day ? url + '?date=' + encodeURIComponent(day) : url;\n  }\n\n  // SNOW-1313: the placeholder `#map`'s `data-favourite-sheet-url` carries\n  // (`_map_embed.html` reverses the route with the nil uuid), the same one\n  // `map_place_sheet.js` replaces.\n  const NIL_UUID = '00000000-0000-0000-0000-000000000000';\n\n  /**\n   * One saved pin's place-sheet url for one day (SNOW-1313).\n   *\n   * The map's own request, as `map_place_sheet.js` makes it: the uuid in\n   * place of the template's nil uuid, then `?d=<day>`. The worker keeps\n   * the sheet under its path and `d` ('private-partial'), so the day is\n   * required \u2014 an undated url could never be found offline, and gives\n   * ``null``.\n   *\n   * @param {string} template A url carrying the nil uuid, as `#map`'s\n   *   `data-favourite-sheet-url` does.\n   * @param {string} uuid The pin's uuid.\n   * @param {string} [day] An ISO date key.\n   * @returns {?string}\n   */\n  function favouriteSheetURL(template, uuid, day) {\n    if (!template || !uuid || !day || template.indexOf(NIL_UUID) === -1) return null;\n    return template.replace(NIL_UUID, encodeURIComponent(uuid)) + '?d=' + encodeURIComponent(day);\n  }\n\n  /**\n   * The urls for the reader's own things inside an area (SNOW-965).\n   *\n   * Composes over `/api/area-items/`'s answer, as `areaContentURLs` does\n   * over `/api/area-content/`'s: each trip's page and its `route.geojson`,\n   * then the weather sheet each pin borrows its forecast from \u2014 which can\n   * sit outside the area, and is the reason this exists. The trip page is\n   * page HTML, so the worker stamps it with the principal its body names;\n   * the route is principal-stamped JSON (`'private-json'` in\n   * `basemap_cache_core.js`); the sheet is public.\n   *\n   * SNOW-1313: and each pin's own place sheet, for the day the weather\n   * sheet is taken for \u2014 the sheet a pin tapped offline opens, whose\n   * \"Full forecast\" opens that borrowed weather sheet. It is the reader's\n   * own HTML, stamped by the worker with the principal the answer names\n   * ('private-partial'). A pin's sheet is asked for whether or not it\n   * borrows a forecast.\n   *\n   * A missing template drops its group rather than the whole answer: a\n   * page that cannot compose a trip's page can still carry its route.\n   *\n   * @param {{trips?: Array<{uuid?: string}>,\n   *   pins?: Array<{uuid?: string, forecast?: {short_id?: string}|null}>}|null} items The\n   *   endpoint's answer.\n   * @param {{tripPage?: string, tripRoute?: string, weatherDetail?: string,\n   *   weatherDay?: string, favouriteSheet?: string}} templates ``__UUID__``\n   *   templates for the two trip urls, the ``__SHORTID__`` weather\n   *   template, the day each sheet is taken for, and (SNOW-1313) the\n   *   nil-uuid place-sheet template.\n   * @param {Iterable<string>} [alreadyPlanned] Urls the area-content plan\n   *   already holds; none of them is repeated.\n   * @returns {string[]} Deduplicated, in the answer's order.\n   */\n  function areaItemURLs(items, templates, alreadyPlanned) {\n    const seen = new Set(alreadyPlanned || []);\n    const out = [];\n    // SNOW-1308: composed per item by `areaItemExpectation`, so the urls a\n    // download fetches and the urls the `/offline/` panels expect to find\n    // are one composition and cannot drift.\n    const expected = areaItemExpectation(items, templates);\n    for (const item of expected.trips.concat(expected.pins)) {\n      for (const url of item.urls) {\n        if (seen.has(url)) continue;\n        seen.add(url);\n        out.push(url);\n      }\n    }\n    return out;\n  }\n\n  /**\n   * The reader's own things inside an area, each by name with its urls\n   * (SNOW-1308).\n   *\n   * The same composition `areaItemURLs` flattens \u2014 a trip's page then its\n   * `route.geojson`; a pin's own place sheet then the weather sheet it\n   * borrows \u2014 kept per item, so a sync can STAMP it onto the area record\n   * and the `/offline/` panels can later ask, by name, whether each one is\n   * in Cache Storage. `/api/area-items/` is never cached, so without the\n   * stamp the page could not know offline what it should expect.\n   *\n   * @param {{trips?: Array<{uuid?: string, name?: string}>,\n   *   pins?: Array<{uuid?: string, name?: string,\n   *   forecast?: {short_id?: string}|null}>}|null} items The endpoint's\n   *   answer.\n   * @param {{tripPage?: string, tripRoute?: string, weatherDetail?: string,\n   *   weatherDay?: string, favouriteSheet?: string}} templates As\n   *   `areaItemURLs`.\n   * @returns {{trips: Array<{uuid: string, name: string, urls: string[]}>,\n   *   pins: Array<{uuid: string, name: string, urls: string[]}>}} In the\n   *   answer's order; an item with no uuid is dropped. A missing template\n   *   drops that url, never the item.\n   */\n  function areaItemExpectation(items, templates) {\n    const tpl = templates || {};\n    const name = (item) => (item && typeof item.name === 'string' ? item.name : '');\n    const trips = [];\n    for (const trip of (items && Array.isArray(items.trips) && items.trips) || []) {\n      const uuid = trip && trip.uuid;\n      if (!uuid) continue;\n      const urls = [];\n      if (tpl.tripPage) urls.push(tpl.tripPage.replace('__UUID__', uuid));\n      if (tpl.tripRoute) urls.push(tpl.tripRoute.replace('__UUID__', uuid));\n      trips.push({ uuid: uuid, name: name(trip), urls: urls });\n    }\n    const pins = [];\n    for (const pin of (items && Array.isArray(items.pins) && items.pins) || []) {\n      const uuid = pin && pin.uuid;\n      if (!uuid) continue;\n      const urls = [];\n      // SNOW-1313: the pin's own sheet, then the forecast it borrows.\n      const sheet = favouriteSheetURL(tpl.favouriteSheet || '', uuid, tpl.weatherDay);\n      if (sheet) urls.push(sheet);\n      const shortId = pin.forecast && pin.forecast.short_id;\n      if (tpl.weatherDetail && shortId) {\n        urls.push(weatherDetailURL(tpl.weatherDetail, shortId, tpl.weatherDay));\n      }\n      pins.push({ uuid: uuid, name: name(pin), urls: urls });\n    }\n    return { trips: trips, pins: pins };\n  }\n\n  /**\n   * Whose names an expectation is (SNOW-1308).\n   *\n   * `/api/area-items/` names its viewer in `X-Snowdesk-Principal`\n   * (`attest_principal`), and that \u2014 not the page's render-time\n   * `pwa-user-id` \u2014 is whose trips and pins it listed: a sign-in in\n   * another tab leaves a page's meta stale while its cookie answers for\n   * the new account. The names are attributed only when the answer's\n   * account IS the page's; a missing header (anonymous) or a mismatch\n   * stamps no principal, which the `/offline/` panels read as unknown and\n   * name nothing. Never attributed to the wrong account.\n   *\n   * @param {{trips: Array<Object>, pins: Array<Object>}|null} expectation\n   *   From `areaItemExpectation`.\n   * @param {string|null|undefined} attested The answer's\n   *   `X-Snowdesk-Principal`.\n   * @param {string|null|undefined} pagePrincipal The page's `pwa-user-id`.\n   * @returns {{trips: Array<Object>, pins: Array<Object>, principal: string}|null}\n   */\n  function attestedExpectation(expectation, attested, pagePrincipal) {\n    if (!expectation) return null;\n    const agreed = !!attested && attested === pagePrincipal;\n    return Object.assign({}, expectation, { principal: agreed ? String(attested) : '' });\n  }\n\n  /**\n   * An expectation with the problem-terrain urls a sync warmed (SNOW-1379).\n   *\n   * The `/offline/` panel's Conditions stage counts the area's saved\n   * problem-terrain days, and like the reader's own things it cannot ask\n   * offline what it should expect \u2014 so the urls ride the expectation a\n   * sync stamps (`stampContentRecord`). Unlike those things they are\n   * public and every reader's, so a signed-out sync, which has no things\n   * to stamp, still carries them: a null expectation becomes one holding\n   * the urls alone.\n   *\n   * @param {Object|null} expectation From `attestedExpectation`, or null.\n   * @param {string[]|null|undefined} urls The plan's `problemTerrainUrls`.\n   * @returns {Object} A new expectation.\n   */\n  function withProblemTerrain(expectation, urls) {\n    return Object.assign({}, expectation || {}, {\n      problemTerrain: Array.isArray(urls) ? urls.slice() : [],\n    });\n  }\n\n  // SNOW-1417: the widest rectangle `/api/ski-tours.geojson` answers, in\n  // degrees each way (`SKI_NETWORK_MAX_SPAN_DEG` in apps/map/api.py).\n  const SKI_TOURS_MAX_SPAN_DEG = 0.5;\n\n  /**\n   * Round to the metre-ish precision a tour box is written in, so the url\n   * a download warms and the url the map asks offline are one string.\n   *\n   * @param {number} value\n   * @returns {number}\n   */\n  function round3(value) {\n    return Math.round(value * 1000) / 1000;\n  }\n\n  /**\n   * An area's rectangle cut into boxes the SAC tours endpoint answers\n   * (SNOW-1417).\n   *\n   * The endpoint refuses a box wider than `maxSpan` either way, and an\n   * area can be wider than that. So the rectangle, rounded outward to\n   * three places, is cut into equal columns and rows, each comfortably\n   * under the cap even after its edges are rounded. Neighbouring boxes\n   * share an edge, and the endpoint answers every tour that touches a box,\n   * so a tour on a seam is in both answers (de-duplicated by uuid in\n   * `tourPlan`).\n   *\n   * @param {number[]|null|undefined} bbox `[west, south, east, north]`.\n   * @param {number} [maxSpan] Defaults to the endpoint's cap.\n   * @returns {Array<[number, number, number, number]>} West-to-east, then\n   *   south-to-north. Empty for an unreadable rectangle.\n   */\n  function tourBoxes(bbox, maxSpan) {\n    if (!Array.isArray(bbox) || bbox.length !== 4 || !bbox.every(Number.isFinite)) return [];\n    const cap = Number.isFinite(maxSpan) ? Number(maxSpan) : SKI_TOURS_MAX_SPAN_DEG;\n    const west = Math.floor(bbox[0] * 1000) / 1000;\n    const south = Math.floor(bbox[1] * 1000) / 1000;\n    const east = Math.ceil(bbox[2] * 1000) / 1000;\n    const north = Math.ceil(bbox[3] * 1000) / 1000;\n    if (!(east > west) || !(north > south)) return [];\n    // Two thousandths of slack, so rounding an edge can never push a box\n    // past the cap.\n    const usable = Math.max(cap - 0.002, 0.001);\n    const cols = Math.ceil(round3(east - west) / usable);\n    const rows = Math.ceil(round3(north - south) / usable);\n    const edges = (from, to, n) => {\n      const out = [];\n      for (let i = 0; i <= n; i += 1) out.push(i === n ? to : round3(from + ((to - from) * i) / n));\n      return out;\n    };\n    const xs = edges(west, east, cols);\n    const ys = edges(south, north, rows);\n    /** @type {Array<[number, number, number, number]>} */\n    const boxes = [];\n    for (let r = 0; r < rows; r += 1) {\n      for (let c = 0; c < cols; c += 1) boxes.push([xs[c], ys[r], xs[c + 1], ys[r + 1]]);\n    }\n    return boxes;\n  }\n\n  /**\n   * One SAC tours box's url, as ski_tours.js asks for it (SNOW-1417).\n   *\n   * @param {string} base `/api/ski-tours.geojson`.\n   * @param {number[]} box\n   * @returns {string}\n   */\n  function tourBoxURL(base, box) {\n    return base + '?bbox=' + box.join(',');\n  }\n\n  /**\n   * The SAC tours inside an area, from the answers to its boxes\n   * (SNOW-1417).\n   *\n   * Each tour once, by uuid, in first-seen order, with its name and the\n   * two urls a tap and the route panel ask for: its Feature and its\n   * height profile. An answer that is missing, malformed or says\n   * `truncated` makes the plan short, so the area is never stamped\n   * complete over a partial set of tours.\n   *\n   * @param {Array<any>} answers One per box, null where the fetch failed.\n   * @param {{feature?: string, terrain?: string}} templates Each with\n   *   `__UUID__`.\n   * @returns {{tours: Array<{uuid: string, name: string, urls: string[]}>,\n   *   short: boolean}}\n   */\n  function tourPlan(answers, templates) {\n    const tpl = templates || {};\n    let short = false;\n    const seen = new Set();\n    const tours = [];\n    for (const answer of answers || []) {\n      if (!answer || !Array.isArray(answer.features) || answer.truncated) {\n        short = true;\n        if (!answer || !Array.isArray(answer.features)) continue;\n      }\n      for (const feature of answer.features) {\n        const props = (feature && feature.properties) || {};\n        if (props.kind !== 'tour' || !props.uuid || seen.has(props.uuid)) continue;\n        seen.add(props.uuid);\n        const uuid = String(props.uuid);\n        const urls = [];\n        if (tpl.feature) urls.push(tpl.feature.replace('__UUID__', encodeURIComponent(uuid)));\n        if (tpl.terrain) urls.push(tpl.terrain.replace('__UUID__', encodeURIComponent(uuid)));\n        tours.push({ uuid: uuid, name: typeof props.name === 'string' ? props.name : '', urls: urls });\n      }\n    }\n    return { tours: tours, short: short };\n  }\n\n  /**\n   * The community reports inside an area's rectangle (SNOW-1417).\n   *\n   * Edge-inclusive, as the rest of an area's content is chosen by its\n   * crude rectangle. The id is the report's `submission`; the newest is\n   * the latest `observed_at` among them.\n   *\n   * @param {any} feed The `/api/community-reports.geojson` answer.\n   * @param {number[]|null|undefined} bbox\n   * @returns {{ids: string[], newestAt: string|null}|null} Null for an\n   *   unreadable feed or rectangle.\n   */\n  function reportsInBox(feed, bbox) {\n    if (!feed || !Array.isArray(feed.features)) return null;\n    if (!Array.isArray(bbox) || bbox.length !== 4 || !bbox.every(Number.isFinite)) return null;\n    const ids = [];\n    let newest = null;\n    let newestMs = -Infinity;\n    for (const feature of feed.features) {\n      const coords = feature && feature.geometry && feature.geometry.coordinates;\n      const props = (feature && feature.properties) || {};\n      if (!Array.isArray(coords) || !props.submission) continue;\n      const [lon, lat] = coords;\n      if (!(lon >= bbox[0] && lon <= bbox[2] && lat >= bbox[1] && lat <= bbox[3])) continue;\n      ids.push(String(props.submission));\n      const ms = typeof props.observed_at === 'string' ? Date.parse(props.observed_at) : NaN;\n      if (Number.isFinite(ms) && ms > newestMs) {\n        newestMs = ms;\n        newest = props.observed_at;\n      }\n    }\n    return { ids: ids, newestAt: newest };\n  }\n\n  /**\n   * The reader's routes whose line enters an area's rectangle (SNOW-1418).\n   *\n   * From the routes overlay feed a sync already fetches. A route counts\n   * when any vertex of its line is inside the rectangle, edge-inclusive,\n   * as the reports and the rest of an area's content are chosen.\n   *\n   * @param {any} feed The routes feed (`/routes/geojson`).\n   * @param {number[]|null|undefined} bbox\n   * @returns {Array<{uuid: string}>|null} Null for an unreadable feed or\n   *   rectangle.\n   */\n  function routesInBox(feed, bbox) {\n    if (!feed || !Array.isArray(feed.features)) return null;\n    if (!Array.isArray(bbox) || bbox.length !== 4 || !bbox.every(Number.isFinite)) return null;\n    const isPoint = (point) =>\n      Array.isArray(point) && Number.isFinite(point[0]) && Number.isFinite(point[1]);\n    // Liang\u2013Barsky: whether the segment a\u2192b has any part inside the\n    // rectangle, so a route that only passes through a small area (no\n    // vertex inside it) still counts. A one-point line is a = b.\n    const crosses = (a, b) => {\n      const dx = b[0] - a[0];\n      const dy = b[1] - a[1];\n      let lo = 0;\n      let hi = 1;\n      const edges = [\n        [-dx, a[0] - bbox[0]],\n        [dx, bbox[2] - a[0]],\n        [-dy, a[1] - bbox[1]],\n        [dy, bbox[3] - a[1]],\n      ];\n      for (const [p, q] of edges) {\n        if (p === 0) {\n          if (q < 0) return false;\n          continue;\n        }\n        const t = q / p;\n        if (p < 0) lo = Math.max(lo, t);\n        else hi = Math.min(hi, t);\n        if (lo > hi) return false;\n      }\n      return true;\n    };\n    const enters = (line) => {\n      if (!Array.isArray(line)) return false;\n      const points = line.filter(isPoint);\n      if (points.length === 1) return crosses(points[0], points[0]);\n      for (let i = 1; i < points.length; i += 1) {\n        if (crosses(points[i - 1], points[i])) return true;\n      }\n      return false;\n    };\n    const routes = [];\n    const seen = new Set();\n    for (const feature of feed.features) {\n      const geometry = feature && feature.geometry;\n      const uuid = feature && feature.properties && feature.properties.uuid;\n      if (!geometry || !uuid || seen.has(String(uuid))) continue;\n      const lines =\n        geometry.type === 'MultiLineString'\n          ? geometry.coordinates\n          : geometry.type === 'LineString'\n            ? [geometry.coordinates]\n            : [];\n      if (!Array.isArray(lines)) continue;\n      if (lines.some(enters)) {\n        seen.add(String(uuid));\n        routes.push({ uuid: String(uuid) });\n      }\n    }\n    return routes;\n  }\n\n  /**\n   * The resorts an area's content answer names, each with the place-sheet\n   * urls its plan saves (SNOW-1418), for the stamp's `items.resorts`.\n   *\n   * @param {Array<{slug?: string}>|null|undefined} resorts The endpoint's\n   *   `resorts` list.\n   * @param {string} template A url carrying ``__SLUG__``, as `#map`'s\n   *   `data-resort-sheet-url` does; empty gives each resort no urls.\n   * @param {string[]} days The plan's days.\n   * @returns {Array<{slug: string, urls: string[]}>|null} Null when the\n   *   answer named no list.\n   */\n  function resortItems(resorts, template, days) {\n    if (!Array.isArray(resorts)) return null;\n    const out = [];\n    const seen = new Set();\n    for (const resort of resorts) {\n      const slug = resort && resort.slug;\n      if (!slug || seen.has(slug)) continue;\n      seen.add(slug);\n      const urls = template ? (days || []).map((day) => resortSheetURL(template, slug, day)) : [];\n      out.push({ slug: String(slug), urls: urls });\n    }\n    return out;\n  }\n\n  /**\n   * An expectation with an area's public things on it (SNOW-1417): its SAC\n   * tours and the community reports inside it.\n   *\n   * Like the problem-terrain urls (`withProblemTerrain`) these are every\n   * reader's, so a signed-out sync carries them too. A field that was not\n   * read this time (`undefined`) is left off, so the stamp keeps whatever\n   * the record held for it.\n   *\n   * @param {Object|null} expectation\n   * @param {{tours?: Array<Object>, tourBoxes?: string[],\n   *   resorts?: Array<Object>,\n   *   reports?: {ids: string[], newestAt: string|null}|null,\n   *   reportsAt?: string}} extras\n   * @returns {Object} A new expectation.\n   */\n  function withPublicItems(expectation, extras) {\n    const out = Object.assign({}, expectation || {});\n    const e = extras || {};\n    if (Array.isArray(e.tours)) out.tours = e.tours.slice();\n    if (Array.isArray(e.tourBoxes)) out.tourBoxes = e.tourBoxes.slice();\n    // SNOW-1418: the resorts inside it, with their sheets.\n    if (Array.isArray(e.resorts)) out.resorts = e.resorts.slice();\n    if (e.reports) {\n      out.reports = e.reports.ids.map((id) => ({ id: id }));\n      out.reportsNewestAt = e.reports.newestAt || null;\n      out.reportsAt = e.reportsAt || null;\n    }\n    return out;\n  }\n\n  // SNOW-1417: the public fields an expectation may carry, stamped onto\n  // `items` beside the reader's own things and kept when a sync did not\n  // read them.\n  const PUBLIC_ITEM_FIELDS = [\n    'problemTerrain',\n    'tours',\n    'tourBoxes',\n    'resorts',\n    'reports',\n    'reportsAt',\n    'reportsNewestAt',\n  ];\n\n  /**\n   * One area record after a content sync \u2014 the ONE stamping rule\n   * (SNOW-1308).\n   *\n   * Every writer of a content outcome goes through this: the map's region\n   * roundel (`_stampRegionContent`), the map's Manage downloads sheet\n   * (`_stampAreaContent`) and `/offline/`'s Sync now (`stampAreaContent`).\n   * The rule is SNOW-932's: success SETS `contentAt` and DELETES\n   * `contentIncomplete`; failure sets `contentIncomplete` and leaves\n   * `contentAt` alone. SNOW-1308 adds the third field: a successful sync\n   * that asked `/api/area-items/` stamps what it expects of the reader's\n   * own things (`areaItemExpectation`) as `items`. A sync that did not ask\n   * (signed out) or fell short leaves `items` as it was.\n   *\n   * The expectation carries the SYNCING session's principal\n   * (`expectation.principal`, the `pwa-user-id` the caller read), stamped\n   * as `items.principal`. It is not the area's own `principal`: an area\n   * one account downloaded can be synced by another signed in on the same\n   * device, and the names written are the syncing account's. The\n   * `/offline/` panels show them only to that account (SNOW-1308 review).\n   *\n   * SNOW-1379: an expectation carrying `problemTerrain`\n   * (`withProblemTerrain`) stamps it as `items.problemTerrain` \u2014 with the\n   * things when there are some, and on its own (keeping whatever things\n   * the record already held) when a signed-out sync had none to stamp.\n   *\n   * Synchronous, because every caller runs it inside a `readModifyWrite`\n   * mutator, which must not await.\n   *\n   * @param {Object} entry The stored record.\n   * @param {boolean} complete Whether the content half landed in full.\n   * @param {{trips?: Array<Object>, pins?: Array<Object>,\n   *   routes?: Array<Object>, principal?: string,\n   *   problemTerrain?: string[]}|null} [expectation]\n   *   With the syncing session's principal.\n   * @param {string} [nowIso] The stamp; the clock when absent.\n   * @returns {Object} A new record.\n   */\n  function stampContentRecord(entry, complete, expectation, nowIso) {\n    if (!complete) return Object.assign({}, entry, { contentIncomplete: true });\n    const next = Object.assign({}, entry);\n    // Deleted rather than set false: absence is the one representation of\n    // \"nothing wrong\" every reader shares.\n    delete next.contentIncomplete;\n    next.contentAt = nowIso || new Date().toISOString();\n    // SNOW-1417: every public field this sync read, and only those.\n    /** @type {Object<string, any>} */\n    const publicFields = {};\n    for (const field of PUBLIC_ITEM_FIELDS) {\n      if (expectation && expectation[field] !== undefined) publicFields[field] = expectation[field];\n    }\n    if (expectation && Array.isArray(expectation.trips) && Array.isArray(expectation.pins)) {\n      // The reader's things replace the old ones whole; a public field this\n      // sync did not read keeps the record's.\n      const kept = {};\n      for (const field of PUBLIC_ITEM_FIELDS) {\n        if (next.items && next.items[field] !== undefined) kept[field] = next.items[field];\n      }\n      next.items = Object.assign(\n        kept,\n        {\n          trips: expectation.trips,\n          pins: expectation.pins,\n          principal: typeof expectation.principal === 'string' ? expectation.principal : null,\n        },\n        // SNOW-1418: the reader's routes in the area, beside their trips\n        // and pins and under the same principal. A sync that did not read\n        // the routes feed writes none, rather than another account's.\n        Array.isArray(expectation.routes) ? { routes: expectation.routes } : {},\n        publicFields,\n      );\n    } else if (Object.keys(publicFields).length > 0) {\n      next.items = Object.assign({}, next.items || {}, publicFields);\n    }\n    return next;\n  }\n\n  /**\n   * The zoom level to draw a download's progress grid at: the deepest in\n   * the blob.\n   *\n   * The download spans a whole band (z10-14 \u2014 see ``MICRO_BAND``) and\n   * every level covers the SAME ground, so the grid has to pick one zoom\n   * or it would paint the same area five times over. It picks the band's\n   * detail floor, which makes each square a REAL tile \u2014 the finest unit\n   * the run actually fetches (~1.7 km across in the Alps at z14), and\n   * mostly one tile per square.\n   *\n   * Deepest rather than a \"give me at least N squares\" rule: cell count\n   * quadruples per level, so any such threshold lands on a different\n   * level for different-sized areas \u2014 a big region drew 27 km blocks\n   * while a small one drew 3 km ones, which read as an inconsistent\n   * animation rather than a scale. Deepest is both the finest grid\n   * available and the only choice that needs no tuning constant.\n   *\n   * @param {{z?: Object<string, number[]>}} blob A full download blob.\n   * @returns {number | null} A zoom level, or ``null`` for a blob with no\n   *   ranges to draw.\n   */\n  function gridZoomFor(blob) {\n    if (!blob || !blob.z) return null;\n    const zooms = Object.keys(blob.z)\n      .map(Number)\n      .filter((z) => Number.isFinite(z));\n    if (!zooms.length) return null;\n    return Math.max.apply(null, zooms);\n  }\n\n  /**\n   * The grid cell a tile belongs to, in cell-index space at ``gridZ``.\n   *\n   * A tile deeper than the grid sits inside exactly one cell, found by\n   * shifting its indices right. A tile SHALLOWER than the grid (every\n   * level above the band's floor, which is where the grid is drawn) spans\n   * many cells; it is assigned to the north-westmost one it covers, so\n   * every tile lands in exactly one cell and the per-cell totals sum to\n   * the run's tile count.\n   *\n   * That assignment is deliberately not \"the cells this tile covers\".\n   * The grid is a progress indicator, not a coverage map \u2014 one tile\n   * completing several cells would let squares light up for ground whose\n   * own detail tiles have not been fetched yet.\n   *\n   * ``gridRows`` clamps the result into the grid's own footprint. A\n   * coarse tile starts WEST and NORTH of the area it was fetched for (its\n   * indices floor to a wider grid), so its north-westmost fine cell can\n   * fall outside the rows the grid draws \u2014 which showed up as a lattice\n   * of stray squares scattered off the edge of the download area, over\n   * ground the run does not cover. Clamping folds those onto the edge\n   * cell the tile actually overlaps.\n   *\n   * SNOW-583: a clipped region blob's grid rows are no longer necessarily\n   * CONTIGUOUS in y (a concave boundary can leave a gap between two\n   * present rows), so the old single clamp \u2014 bound ``cx``/``cy`` each\n   * independently into the grid zoom's own rectangle \u2014 could land a cell\n   * on a row that has no tiles at all. The clamp is therefore two steps,\n   * row first: ``cy`` snaps to the nearest row ``gridRows`` actually has,\n   * THEN ``cx`` clamps into that row's own ``[xmin, xmax]`` span. For a\n   * rectangular grid (every row present, one shared span) this reduces to\n   * exactly the old single clamp \u2014 the ``buildBlob``/custom-area path is\n   * untouched in substance, only in shape of the arithmetic.\n   *\n   * @param {number} z The tile's zoom level.\n   * @param {number} x The tile's x index.\n   * @param {number} y The tile's y index.\n   * @param {number} gridZ The grid's zoom level.\n   * @param {Object<string, [number, number]>} gridRows The grid zoom's own\n   *   ``{\"<y>\": [xmin, xmax]}`` rows (``zoomRows(blob.z[gridZ])``).\n   * @returns {[number, number]} ``[cellX, cellY]``.\n   */\n  function _cellForTile(z, x, y, gridZ, gridRows) {\n    const shift = z - gridZ;\n    let cx;\n    let cy;\n    if (shift >= 0) {\n      const step = Math.pow(2, shift);\n      cx = Math.floor(x / step);\n      cy = Math.floor(y / step);\n    } else {\n      const scale = Math.pow(2, -shift);\n      cx = x * scale;\n      cy = y * scale;\n    }\n    cy = _nearestRow(cy, gridRows);\n    const [xmin, xmax] = gridRows[String(cy)];\n    cx = Math.max(xmin, Math.min(cx, xmax));\n    return [cx, cy];\n  }\n\n  /**\n   * The row (``y``) in ``gridRows`` closest to ``cy`` \u2014 exact when ``cy``\n   * is itself present, otherwise the nearest neighbour. Ties (equidistant\n   * above and below) resolve to the smaller ``y``, i.e. the row further\n   * NORTH \u2014 an arbitrary but deterministic choice; a boundary narrow\n   * enough to produce one is already a rare, single-row sliver.\n   *\n   * @param {number} cy A candidate row index, possibly absent from\n   *   ``gridRows``.\n   * @param {Object<string, [number, number]>} gridRows The grid zoom's\n   *   own rows.\n   * @returns {number} A row index guaranteed present in ``gridRows``.\n   */\n  function _nearestRow(cy, gridRows) {\n    let best = null;\n    let bestDistance = Infinity;\n    for (const key of Object.keys(gridRows)) {\n      const y = Number(key);\n      const distance = Math.abs(y - cy);\n      if (distance < bestDistance || (distance === bestDistance && y < best)) {\n        best = y;\n        bestDistance = distance;\n      }\n    }\n    return best;\n  }\n\n  /**\n   * Plan a download as a grid of cells plus the tile URLs that fill them.\n   *\n   * Returns the URL list to hand to the service worker AND the squares\n   * the map draws, with the two tied together: ``urls[i]`` belongs to\n   * ``cells[cellOfURL[i]]``, and a cell is complete once all ``total`` of\n   * its tiles have settled.\n   *\n   * **The URLs come back grouped by cell**, which is the whole point.\n   * ``rangesToTileURLs`` emits them zoom-major, so a run works through\n   * every z10 tile, then every z11, and so on \u2014 five passes over the same\n   * ground, with no cell finishing until the last pass reaches it.\n   * Grouping instead means a cell's tiles are fetched consecutively and\n   * the square lights up when they land, so the grid fills in cell by\n   * cell. The SET of URLs is identical either way, so ordering costs the\n   * download nothing; it is purely what makes the progress legible.\n   *\n   * Cells are ordered **bottom-up in a boustrophedon**: rows from the\n   * south northwards, and each row runs the opposite way to the one below\n   * it \u2014 west to east, then east to west, and so on. That matches the\n   * download roundel, which fills from its bottom edge upwards; the map\n   * and the icon are two readouts of one run, so they fill in the same\n   * direction.\n   *\n   * Alternating rather than restarting every row at the west edge because\n   * a plain raster scan jumps the length of the area at each row end,\n   * which reads as a repeating wipe. Serpentine keeps consecutive cells\n   * adjacent, so the filled area grows like something pouring in.\n   *\n   * Note rows are ordered by DESCENDING cell y: Web Mercator tile y\n   * increases southward, so the southernmost row is the highest y and has\n   * to come first. Deterministic, so a re-run of the same area fills in\n   * the same order.\n   *\n   * SNOW-843: a cell's ``total`` counts one tile PER SOURCE, and the URL\n   * list carries them all, so the grid fills as the ground is actually\n   * covered rather than reporting a two-source area complete at half.\n   *\n   * @param {string | string[][]} spec The style's tile sources \u2014 a template\n   *   string or the ``string[][]`` shape ``tileSources`` normalises to.\n   * @param {{z?: Object<string, number[] | Object<string, number[]>>}} blob\n   *   A full download blob \u2014 fetched from\n   *   ``/api/region-basemap-tiles/?id=...`` (rectangle or clipped row\n   *   spans \u2014 either shape, via ``zoomRows``) or built by ``buildBlob``\n   *   (always a rectangle).\n   * @returns {{gridZ: number, cells: Array<{x: number, y: number, bbox:\n   *   [number, number, number, number], total: number}>, urls: string[],\n   *   cellOfURL: number[]} | null} ``null`` when there is nothing to draw.\n   */\n  function tileGridPlan(spec, blob) {\n    const gridZ = gridZoomFor(blob);\n    const sources = tileSources(spec);\n    if (!sources.length || gridZ === null) return null;\n\n    // Bucket every tile in the blob by the cell it lands in, keyed on the\n    // cell's own indices so the two loops below agree on identity.\n    const gridRows = zoomRows(blob.z[String(gridZ)]);\n    const buckets = new Map();\n    for (const key of Object.keys(blob.z)) {\n      const z = Number(key);\n      if (!Number.isFinite(z)) continue;\n      const rows = zoomRows(blob.z[key]);\n      for (const rowKey of Object.keys(rows)) {\n        const y = Number(rowKey);\n        const [xmin, xmax] = rows[rowKey];\n        for (let x = xmin; x <= xmax; x++) {\n          const [cx, cy] = _cellForTile(z, x, y, gridZ, gridRows);\n          const cellKey = cx + ':' + cy;\n          let bucket = buckets.get(cellKey);\n          if (!bucket) {\n            bucket = { x: cx, y: cy, tiles: [] };\n            buckets.set(cellKey, bucket);\n          }\n          bucket.tiles.push([z, x, y]);\n        }\n      }\n    }\n    if (!buckets.size) return null;\n\n    // Group into rows, then walk them south to north, reversing every\n    // other row so the sweep never jumps back across the area.\n    const byRow = new Map();\n    for (const bucket of buckets.values()) {\n      if (!byRow.has(bucket.y)) byRow.set(bucket.y, []);\n      byRow.get(bucket.y).push(bucket);\n    }\n    // Descending y: the southernmost row is the highest tile index.\n    const rowKeys = Array.from(byRow.keys()).sort((a, b) => b - a);\n    const ordered = [];\n    rowKeys.forEach((y, rowIndex) => {\n      const row = byRow.get(y).sort((a, b) => a.x - b.x);\n      if (rowIndex % 2 === 1) row.reverse();\n      for (const bucket of row) ordered.push(bucket);\n    });\n    const cells = [];\n    const urls = [];\n    const cellOfURL = [];\n    ordered.forEach((bucket, index) => {\n      for (const [z, x, y] of bucket.tiles) {\n        // SNOW-843: one URL per SOURCE, all attributed to the same cell \u2014\n        // a square is a patch of ground, and the ground is not covered\n        // until every layer over it is down.\n        for (const url of tileURLs(sources, z, x, y)) {\n          urls.push(url);\n          cellOfURL.push(index);\n        }\n      }\n      cells.push({\n        x: bucket.x,\n        y: bucket.y,\n        bbox: tileBounds(gridZ, bucket.x, bucket.y),\n        total: bucket.tiles.length * sources.length,\n      });\n    });\n    return { gridZ: gridZ, cells: cells, urls: urls, cellOfURL: cellOfURL };\n  }\n\n  /**\n   * Whether EVERY tile in ``blob``'s own ``z`` is present in ``cached`` \u2014\n   * \"is this download actually available offline?\" (SNOW-570; widened by\n   * SNOW-583 from a bbox rectangle to whatever tile set the blob itself\n   * carries, via ``zoomRows`` \u2014 a clipped region blob is checked against\n   * exactly the tiles its download fetched, not a bbox super-set of them).\n   *\n   * Deliberately not the centre-tile proxy an earlier version of the\n   * roundel's own done-probe used. That proxy is fair only for a question\n   * that only ever asks about a download the user made AS THAT DOWNLOAD:\n   * the centre tile is then a witness that that particular run completed.\n   * It is NOT fair when two download shapes write to one pinned cache over\n   * the same zoom band with the same URL template, so their tiles are\n   * indistinguishable strings \u2014 a custom-area download whose frame merely\n   * crosses a region's centre caches that region's centre tile, and a\n   * centre-tile probe would then read the whole region as downloaded on\n   * the strength of one tile it never covered (and would equally MISS a\n   * region almost entirely covered whose centre falls outside the frame).\n   *\n   * Full coverage is the honest question and it is nearly free: the caller\n   * has already paid for the answer with one ``cache.keys()`` pass, and\n   * every tile after the first is a Set lookup. A download is at most a\n   * few hundred tiles across the micro band, so the whole check costs\n   * single-digit milliseconds \u2014 which is why this checks all of them\n   * rather than sampling. It is also the RIGHT answer whoever cached the\n   * tiles: an area wholly inside a larger download genuinely is available\n   * offline, and should say so.\n   *\n   * @param {string | string[][]} spec The ACTIVE basemap's tile sources \u2014\n   *   which is what makes the answer per-basemap. A template string or the\n   *   ``string[][]`` shape ``tileSources`` normalises to.\n   * @param {{z?: Object<string, number[] | Object<string, number[]>>}} blob\n   *   A full download blob \u2014 fetched from\n   *   ``/api/region-basemap-tiles/?id=...`` or built locally by\n   *   ``buildBlob`` (custom area).\n   * @param {Set<string> | string[]} cached The pinned cache's URLs.\n   * @returns {boolean} ``false`` for a falsy template or blob (or one with\n   *   no ``z``), and for an empty tile set \u2014 \"nothing is cached\" must\n   *   never read as \"all of nothing is cached, so yes\".\n   */\n  function blobFullyCached(spec, blob, cached) {\n    const sources = tileSources(spec);\n    if (!sources.length || !blob || !blob.z) return false;\n    const cachedSet = cached instanceof Set ? cached : new Set(cached || []);\n    let seen = 0;\n    for (const zKey of Object.keys(blob.z)) {\n      const z = Number(zKey);\n      const rows = zoomRows(blob.z[zKey]);\n      for (const yKey of Object.keys(rows)) {\n        const y = Number(yKey);\n        const [xmin, xmax] = rows[yKey];\n        for (let x = xmin; x <= xmax; x++) {\n          // SNOW-843: every source, at the host MapLibre will ask for it.\n          // One layer of a multi-source style being present is not the area\n          // being available offline.\n          for (const url of tileURLs(sources, z, x, y)) {\n            if (!cachedSet.has(url)) return false;\n            seen++;\n          }\n        }\n      }\n    }\n    return seen > 0;\n  }\n\n  /**\n   * Which of ``depURLs`` are NOT in ``cached`` \u2014 an area's missing render\n   * dependencies (SNOW-844).\n   *\n   * ``blobFullyCached`` above answers \"are the tiles here?\", and until\n   * this ticket that was the ONLY question any surface asked about a\n   * downloaded area. It is not the question. A pinned area renders offline\n   * only if its bucket also holds the style JSON, the TileJSON document\n   * each vector source is declared by (SNOW-843 \u2014 without it MapLibre\n   * cannot learn a single tile URL, so a perfect tile set is unreachable),\n   * and the sprite JSON+PNG at 1x and 2x. A download fetches all four; it\n   * is the VERIFICATION that was tile-only, which is why an area\n   * downloaded before SNOW-843 \u2014 one that never fetched its TileJSON at\n   * all \u2014 still reads ``done`` today.\n   *\n   * Returns the missing URLs rather than a boolean because the caller\n   * repairs from them: ``basemap_download_runner.js``'s ``repair`` warms\n   * exactly this list into the area's own bucket, and warming the whole\n   * dependency list instead would re-fetch documents already on disk.\n   *\n   * Glyph ranges are deliberately NOT dependencies here. MapLibre requests\n   * only the unicode ranges its labels use, so the honest list is not\n   * derivable without re-deriving MapLibre's own glyph logic \u2014 SNOW-742\n   * PROMOTES whatever was already cached instead, which means the set in\n   * the bucket is legitimately partial and any check over it would report\n   * a permanent, unrepairable failure. Pinning the ranges an area actually\n   * needs is SNOW-847's job; see this ticket's decision doc.\n   *\n   * @param {string[]} depURLs The area's dependency URLs \u2014 from its own\n   *   stored record, or derived live from the active style\n   *   (``activeBasemapRenderDependencyURLs``, map_basemap_downloads.js).\n   * @param {Set<string> | string[]} cached The pinned cache's URLs, in\n   *   either shape \u2014 same contract as ``blobFullyCached``'s own argument.\n   * @returns {string[]} The subset of ``depURLs`` that is absent, in the\n   *   order given, deduplicated. ``[]`` for an empty or unusable\n   *   ``depURLs`` \u2014 \"nothing was claimed\", which callers read as UNKNOWN\n   *   and must never paint as a fault; see the three-row resolution rule\n   *   in docs/decisions/a-downloaded-area-is-verified-by-what-it-renders.md.\n   */\n  function missingRenderDependencies(depURLs, cached) {\n    if (!Array.isArray(depURLs) || depURLs.length === 0) return [];\n    var cachedSet = cached instanceof Set ? cached : new Set(cached || []);\n    var missing = [];\n    var seen = new Set();\n    for (var i = 0; i < depURLs.length; i += 1) {\n      var url = depURLs[i];\n      if (typeof url !== 'string' || !url) continue;\n      if (seen.has(url)) continue;\n      seen.add(url);\n      if (!cachedSet.has(url)) missing.push(url);\n    }\n    return missing;\n  }\n\n  /* ------------------------------------------------------------------ *\n   * SNOW-1583: what a downloaded area holds, part by part.\n   *\n   * A run is counted part by part. `map` is the map \u2014 the basemap's area\n   * tiles, the shared base layer below them and the documents they draw\n   * with (style, TileJSON, sprite, glyphs) \u2014 and every other key is \"the\n   * rest\". `areaOutcome` turns the counts into the one of three answers\n   * the Downloads sheet's dot shows. It replaced SNOW-649's\n   * `downloadSucceeded`, and SNOW-932's `contentOutcome` as the amber\n   * predicate, which judged the whole run as one, so one missing tour\n   * marked a fully saved map Incomplete.\n   * docs/decisions/the-map-decides-whether-an-area-works-offline.md has\n   * the why.\n   * ------------------------------------------------------------------ */\n\n  /**\n   * Every part of a download, the map first. The keys are the ones\n   * `offline_journey_core.js`'s `inventoryFor` lists.\n   */\n  var AREA_PARTS = Object.freeze([\n    'map',\n    // SNOW-1583 review: the shared base layer below z10, counted apart\n    // from the area's own tiles so a sync that cannot plan it (another\n    // basemap on screen) keeps what the last top-up left. It is the map:\n    // `areaOutcome` reads a failure here as the map's, and the inventory\n    // shows it in the map's row.\n    'base',\n    'swiss',\n    'terrain',\n    'boundaries',\n    'bulletin',\n    'weather',\n    'resorts',\n    'tours',\n    'routes',\n    'trips',\n    'places',\n    'reports',\n  ]);\n\n  /** The failure kinds a retry can mend (`pwaDownloadRunLogCore.failureKind`). */\n  var RETRYABLE_KINDS = Object.freeze(['connection', 'server', 'stopped']);\n\n  /**\n   * One part's count, read defensively: a negative, absent or non-number\n   * count is zero.\n   *\n   * @param {*} part\n   * @param {'ok'|'failed'} field\n   * @returns {number}\n   */\n  function partCount(part, field) {\n    var value = part && typeof part === 'object' ? part[field] : 0;\n    return typeof value === 'number' && value > 0 ? value : 0;\n  }\n\n  /**\n   * SNOW-1583: what a run, or a record's parts, means for the area.\n   *\n   *   - `complete` \u2014 no part has a failure.\n   *   - `usable` \u2014 the map has no failure and some other part does, the\n   *     Swiss map included: a missing Swiss map is not the map.\n   *   - `unusable` \u2014 the map has a failure, or nothing of it landed. The\n   *     base layer (`base`) is the map: a failure there is the map's.\n   *\n   * A map with nothing fetched is unusable rather than complete: a\n   * vacuous run (no tile sources, no worker) must never claim the area is\n   * downloaded \u2014 the clause `downloadSucceeded`'s `ok > 0` carried.\n   *\n   * @param {Object<string, {ok?: number, failed?: number}>|null|undefined} parts\n   * @returns {'complete'|'usable'|'unusable'}\n   */\n  function areaOutcome(parts) {\n    if (!parts || typeof parts !== 'object') return 'unusable';\n    var map = parts.map;\n    if (partCount(map, 'failed') > 0 || partCount(parts.base, 'failed') > 0 || partCount(map, 'ok') === 0) {\n      return 'unusable';\n    }\n    var keys = Object.keys(parts);\n    for (var i = 0; i < keys.length; i += 1) {\n      if (partCount(parts[keys[i]], 'failed') > 0) return 'usable';\n    }\n    return 'complete';\n  }\n\n  /**\n   * SNOW-1583: whether a fetch landed whole \u2014 something landed and no\n   * part has a failure. What a repair (a handful of documents, or one\n   * content delta) is judged by, where there is no map part to weigh.\n   *\n   * @param {Object<string, {ok?: number, failed?: number}>|null|undefined} parts\n   * @returns {boolean}\n   */\n  function fetchLanded(parts) {\n    if (!parts || typeof parts !== 'object') return false;\n    var ok = 0;\n    var keys = Object.keys(parts);\n    for (var i = 0; i < keys.length; i += 1) {\n      if (partCount(parts[keys[i]], 'failed') > 0) return false;\n      ok += partCount(parts[keys[i]], 'ok');\n    }\n    return ok > 0;\n  }\n\n  /**\n   * SNOW-1583: whether retrying can mend any of these failures \u2014 no\n   * connection, a temporary server error (5xx, 429), or a download the\n   * device stopped part way. A 403, 404 or 410 never is, and neither is\n   * full storage.\n   *\n   * @param {Array<string|{kind?: string}>|null|undefined} failures Kinds,\n   *   or failures carrying one.\n   * @returns {boolean}\n   */\n  function retryableFrom(failures) {\n    if (!Array.isArray(failures)) return false;\n    return failures.some(function (failure) {\n      var kind = typeof failure === 'string' ? failure : failure && failure.kind;\n      return RETRYABLE_KINDS.indexOf(String(kind || '')) !== -1;\n    });\n  }\n\n  /**\n   * SNOW-1583: one run's parts laid over a record's.\n   *\n   * Only the parts the run fetched change: each one's `failed` becomes\n   * what this run still could not fetch, and its `ok` adds what it did.\n   * Every other part is the record's, as it was.\n   *\n   * @param {Object|null|undefined} prior The record's `parts`.\n   * @param {Object|null|undefined} run The run's `parts`.\n   * @returns {Object<string, {ok: number, failed: number}>}\n   */\n  function mergeParts(prior, run) {\n    var out = {};\n    var before = prior && typeof prior === 'object' ? prior : {};\n    var now = run && typeof run === 'object' ? run : {};\n    Object.keys(before).forEach(function (key) {\n      out[key] = { ok: partCount(before[key], 'ok'), failed: partCount(before[key], 'failed') };\n    });\n    Object.keys(now).forEach(function (key) {\n      var had = out[key] || { ok: 0, failed: 0 };\n      out[key] = { ok: had.ok + partCount(now[key], 'ok'), failed: partCount(now[key], 'failed') };\n    });\n    return out;\n  }\n\n  /**\n   * SNOW-1583: a record's outcome \u2014 the one it stores, or, for a record\n   * written before `outcome` existed (an older cached shell writes them\n   * still, mid-rollout), the one its other fields and the probes already\n   * taken imply:\n   *\n   *   | A legacy record with                                | Is read as |\n   *   |-----------------------------------------------------|------------|\n   *   | probes that find a render dependency or tiles gone  | unusable   |\n   *   | `contentIncomplete`, missing terrain or Swiss map   | usable     |\n   *   | everything present                                  | complete   |\n   *   | no record at all (an orphaned pinned bucket)        | unusable   |\n   *\n   * `probes` are what the caller has read: `depsMissing` (the sheet's\n   * `markIncompleteRows`, over the map's own documents), `partsMissing`\n   * (the same, over another part's), `tilesHeld` (a tile reading, null\n   * unread), `terrainMissing` and `swissMissing`. The record's own `verified` map\n   * answer stands in for a tile probe the caller did not take. With\n   * nothing read at all, a legacy record has no outcome (null): the\n   * honest answer for an area nothing has checked.\n   *\n   * The probes are evidence of what the device holds NOW, so they speak\n   * for a record with an `outcome` too: a probe that finds the map short\n   * makes any record unusable, and a Swiss map or terrain still to add\n   * makes a complete one usable.\n   *\n   * @param {Object|null|undefined} record\n   * @param {{depsMissing?: boolean, tilesHeld?: (boolean|null),\n   *   terrainMissing?: boolean, swissMissing?: boolean, partsMissing?: boolean}} [probes]\n   * @returns {'complete'|'usable'|'unusable'|null}\n   */\n  function recordOutcome(record, probes) {\n    if (!record || typeof record !== 'object') return 'unusable';\n    var p = probes || {};\n    // A probe's evidence outranks what was stored: a map the device has\n    // since lost part of does not draw, whatever the run that saved it\n    // found, and a Swiss map or terrain still to add is still missing.\n    if (p.depsMissing === true || p.tilesHeld === false) return 'unusable';\n    // SNOW-1583 review: and a part's documents the bucket lacks \u2014 the\n    // Swiss map's, the terrain's \u2014 leave the map drawing: amber.\n    var addition = p.terrainMissing === true || p.swissMissing === true || p.partsMissing === true;\n    var stored = record.outcome;\n    if (stored === 'complete' || stored === 'usable' || stored === 'unusable') {\n      return stored === 'complete' && addition ? 'usable' : stored;\n    }\n    var verified = record.verified && typeof record.verified === 'object' ? record.verified : {};\n    if (verified.map === 'no' && verified.reason !== 'terrain') return 'unusable';\n    if (record.contentIncomplete || addition) return 'usable';\n    if (p.tilesHeld === true || verified.map === 'yes') return 'complete';\n    return null;\n  }\n\n\n  /**\n   * SNOW-932: read a run's CONTENT tally into the two facts a record's\n   * content stamp keeps \u2014 `contentAt` (fetched in full) and\n   * `contentIncomplete` (fell short).\n   *\n   * SNOW-1583: no longer the amber-roundel predicate \u2014 what an area holds\n   * is `areaOutcome`'s, part by part. This is the stamp rule alone: an\n   * older cached shell still reads `contentAt` and `contentIncomplete`\n   * mid-rollout, and the sheet's legacy reading does too.\n   *\n   * It is not a negation because of the third state. A run with nothing\n   * to fetch \u2014 an area whose boundary contains no bulletins, or a shell\n   * whose deps bundle predates the content phase \u2014 is neither complete nor\n   * incomplete. It has nothing to say, and it must record NEITHER field.\n   *\n   * `short` is SNOW-931's channel, opened by SNOW-932. A plan assembled\n   * while a planning request could not be read is missing urls it should\n   * have listed, so its tally can read a clean `ok === total` over a list\n   * that was never whole.\n   *\n   * @param {{ok?: number, total?: number, short?: boolean} | null |\n   *   undefined} content The run's content tally, from `finish`'s extras.\n   * @returns {{complete: boolean, incomplete: boolean}} Both false for a\n   *   run with nothing to fetch and a whole plan. Never both true.\n   */\n  function contentOutcome(content) {\n    var total = (content && content.total) || 0;\n    var ok = (content && content.ok) || 0;\n    var short = !!(content && content.short);\n    return {\n      complete: !short && total > 0 && ok === total,\n      incomplete: short || (total > 0 && ok < total),\n    };\n  }\n\n  /* ------------------------------------------------------------------ *\n   * SNOW-1478: which maps a download saves, and from what.\n   *\n   * Until SNOW-1478 a download saved the map on screen and nothing else,\n   * so an area saved on OpenFreeMap and then viewed on Swisstopo drew only\n   * what browsing had left behind (Hugo, airplane mode, 8 Nov 2026). See\n   * docs/decisions/swiss-downloads-save-the-swisstopo-map.md.\n   * ------------------------------------------------------------------ */\n\n  /** The map a download outside Switzerland saves when the one on screen does not cover it. */\n  var FALLBACK_BASEMAP_KEY = 'openfreemap_liberty';\n\n  /** The countries Swisstopo's own data covers (``swisstopo_extent.js``). */\n  var SWISS_COUNTRIES = Object.freeze(['ch', 'li']);\n\n  /** Points per side when a box is placed against Switzerland, corners included. */\n  var GROUND_SAMPLES = 5;\n\n  /**\n   * Even-odd: whether ``[x, y]`` is inside one ring.\n   *\n   * @param {Array} ring\n   * @param {number} x\n   * @param {number} y\n   * @returns {boolean}\n   */\n  function inRing(ring, x, y) {\n    var inside = false;\n    for (var i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) {\n      var xi = ring[i][0];\n      var yi = ring[i][1];\n      var xj = ring[j][0];\n      var yj = ring[j][1];\n      if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;\n    }\n    return inside;\n  }\n\n  /**\n   * Whether ``[x, y]`` is inside polygons whose first ring is the outer\n   * one and whose others are holes (``swisstopo_extent.js``'s shape).\n   *\n   * @param {Array} polygons\n   * @param {number} x\n   * @param {number} y\n   * @returns {boolean}\n   */\n  function inPolygons(polygons, x, y) {\n    return polygons.some(function (polygon) {\n      if (!inRing(polygon[0], x, y)) return false;\n      return !polygon.slice(1).some(function (hole) {\n        return inRing(hole, x, y);\n      });\n    });\n  }\n\n  /**\n   * Where a box of ground sits against Switzerland.\n   *\n   * Sampled on a five-by-five grid, corners included. A box with no\n   * sample inside is still ``cross`` when a vertex of the border falls\n   * inside it: a small box over a bend in the border.\n   *\n   * @param {number[] | null | undefined} bbox ``[west, south, east, north]``.\n   * @param {Array | null | undefined} extent ``pwaSwisstopoExtent.EXTENT``.\n   * @returns {'inside' | 'outside' | 'cross' | null} Null for a box or an\n   *   extent it cannot read.\n   */\n  function groundInSwitzerland(bbox, extent) {\n    if (!Array.isArray(bbox) || bbox.length !== 4 || !bbox.every(Number.isFinite)) return null;\n    if (!Array.isArray(extent) || extent.length === 0) return null;\n    var west = bbox[0];\n    var south = bbox[1];\n    var east = bbox[2];\n    var north = bbox[3];\n    var inside = 0;\n    var total = 0;\n    for (var i = 0; i < GROUND_SAMPLES; i += 1) {\n      for (var j = 0; j < GROUND_SAMPLES; j += 1) {\n        var x = west + ((east - west) * i) / (GROUND_SAMPLES - 1);\n        var y = south + ((north - south) * j) / (GROUND_SAMPLES - 1);\n        total += 1;\n        if (inPolygons(extent, x, y)) inside += 1;\n      }\n    }\n    if (inside === total) return 'inside';\n    if (inside > 0) return 'cross';\n    var vertexInside = extent.some(function (polygon) {\n      return polygon[0].some(function (point) {\n        return point[0] >= west && point[0] <= east && point[1] >= south && point[1] <= north;\n      });\n    });\n    return vertexInside ? 'cross' : 'outside';\n  }\n\n  /**\n   * The map a download saves over ground outside Switzerland: the one on\n   * screen when it covers every foreign country the ground touches,\n   * OpenFreeMap otherwise.\n   *\n   * @param {string | null | undefined} activeKey\n   * @param {string[]} countries The ground's countries beyond Switzerland,\n   *   lower case. Empty when they are not known, and then OpenFreeMap,\n   *   which draws everywhere, is the only safe answer.\n   * @param {Object<string, string[]> | null | undefined} countriesByKey\n   * @returns {string}\n   */\n  function foreignBasemapKey(activeKey, countries, countriesByKey) {\n    if (!activeKey || activeKey === ELEVATION_BASEMAP_KEY) return FALLBACK_BASEMAP_KEY;\n    if (!countries.length) return FALLBACK_BASEMAP_KEY;\n    var covered = (countriesByKey && countriesByKey[activeKey]) || [];\n    var all = countries.every(function (code) {\n      return covered.indexOf(code) >= 0;\n    });\n    return all ? activeKey : FALLBACK_BASEMAP_KEY;\n  }\n\n  /**\n   * The countries of the region features a box overlaps, lower case. Each\n   * feature is judged by its own bounding box, so a box near a border may\n   * name a neighbour it only nearly touches; that errs towards\n   * OpenFreeMap, which draws everywhere (``foreignBasemapKey``).\n   *\n   * @param {number[] | null | undefined} bbox ``[west, south, east, north]``.\n   * @param {Array<Object> | null | undefined} features GeoJSON features\n   *   carrying ``properties.country``.\n   * @returns {string[]} Empty when the box is unusable or nothing meets it.\n   */\n  function countriesForBBox(bbox, features) {\n    if (!Array.isArray(bbox) || bbox.length !== 4 || !Array.isArray(features)) return [];\n    var found = [];\n    features.forEach(function (feature) {\n      var country = feature && feature.properties && feature.properties.country;\n      if (typeof country !== 'string' || !country) return;\n      var box = featureBBox(feature);\n      if (!box) return;\n      var meets = box[0] <= bbox[2] && box[2] >= bbox[0] && box[1] <= bbox[3] && box[3] >= bbox[1];\n      var code = country.toLowerCase();\n      if (meets && found.indexOf(code) < 0) found.push(code);\n    });\n    return found;\n  }\n\n  /**\n   * The maps a download over this ground saves, primary first.\n   *\n   * Ground in Switzerland saves Swisstopo (``ELEVATION_BASEMAP_KEY``),\n   * whatever is on screen. Ground outside it saves the map on screen when\n   * that map covers its country, and OpenFreeMap otherwise (Hugo, 9 Nov\n   * 2026). Ground across the border saves both, Swisstopo first. A region\n   * names its country, which settles it; a drawn area or drop zone names a\n   * box, placed against ``extent``, and the countries of the regions it\n   * overlaps (``countries``). A box whose foreign countries are not known\n   * saves OpenFreeMap there. Ground that cannot be placed saves the\n   * map on screen, the behaviour before SNOW-1478.\n   *\n   * @param {{country?: string | null, bbox?: number[] | null, countries?: string[] | null} | null} ground\n   * @param {string | null | undefined} activeKey The map on screen.\n   * @param {Object<string, string[]> | null | undefined} countriesByKey\n   *   Each map's countries, lower case (``BASEMAP_COUNTRIES``).\n   * @param {Array | null | undefined} extent ``pwaSwisstopoExtent.EXTENT``.\n   * @returns {string[]} Never empty.\n   */\n  function basemapsForGround(ground, activeKey, countriesByKey, extent) {\n    var country =\n      ground && typeof ground.country === 'string' && ground.country\n        ? ground.country.toLowerCase()\n        : null;\n    var listed = country\n      ? [country]\n      : ground && Array.isArray(ground.countries)\n        ? ground.countries\n        : [];\n    var foreign = listed\n      .filter(function (code) {\n        return typeof code === 'string' && code;\n      })\n      .map(function (code) {\n        return code.toLowerCase();\n      })\n      .filter(function (code, index, all) {\n        return SWISS_COUNTRIES.indexOf(code) < 0 && all.indexOf(code) === index;\n      });\n    var place;\n    if (country) place = SWISS_COUNTRIES.indexOf(country) >= 0 ? 'inside' : 'outside';\n    else place = groundInSwitzerland(ground ? ground.bbox : null, extent);\n    if (place === 'inside') return [ELEVATION_BASEMAP_KEY];\n    if (place === 'cross') {\n      return [ELEVATION_BASEMAP_KEY, foreignBasemapKey(activeKey, foreign, countriesByKey)];\n    }\n    if (place === 'outside') return [foreignBasemapKey(activeKey, foreign, countriesByKey)];\n    return [activeKey || FALLBACK_BASEMAP_KEY];\n  }\n\n  /**\n   * The maps one stored area holds, primary first: its ``basemaps`` list\n   * where a download since SNOW-1478 wrote one, otherwise one entry read\n   * from its top-level ``basemapKey``, ``template`` and ``deps``. Nothing\n   * is migrated in place; every reader that judges completeness asks this.\n   *\n   * @param {Object | null | undefined} record A ``basemap.regions`` /\n   *   ``basemap.customAreas`` entry, or a row normalised from one.\n   * @returns {Array<{key: string | null, template: *, deps: string[]}>}\n   *   Empty for a record that names no map and no template.\n   */\n  function recordBasemaps(record) {\n    if (!record || typeof record !== 'object') return [];\n    if (Array.isArray(record.basemaps) && record.basemaps.length > 0) {\n      return record.basemaps\n        .filter(function (entry) {\n          return entry && typeof entry === 'object';\n        })\n        .map(function (entry) {\n          return {\n            key: typeof entry.key === 'string' && entry.key ? entry.key : null,\n            template: entry.template || null,\n            deps: Array.isArray(entry.deps) ? entry.deps : [],\n          };\n        });\n    }\n    var key = typeof record.basemapKey === 'string' && record.basemapKey ? record.basemapKey : null;\n    if (!key && !record.template) return [];\n    return [\n      {\n        key: key,\n        template: record.template || null,\n        deps: Array.isArray(record.deps) ? record.deps : [],\n      },\n    ];\n  }\n\n  /**\n   * How many vector sources each basemap's style declares, for pricing a\n   * map that is not on screen (the live style counts its own). Swisstopo's\n   * two styles declare relief and base; every other basemap one.\n   */\n  var BASEMAP_SOURCE_COUNTS = Object.freeze({ swisstopo_winter: 2, swisstopo_light: 2 });\n\n  /**\n   * @param {string | null | undefined} key\n   * @returns {number}\n   */\n  function basemapSourceCount(key) {\n    return (key && BASEMAP_SOURCE_COUNTS[key]) || 1;\n  }\n\n  /**\n   * ``sourceScaledMb`` for a basemap named by key rather than by a live\n   * spec: its declared source count at its own per-tile figure.\n   *\n   * @param {number} mb\n   * @param {string | null | undefined} key\n   * @param {number} [count]\n   * @returns {number}\n   */\n  function basemapScaledMb(mb, key, count) {\n    if (!Number.isFinite(mb)) return mb;\n    var sources = basemapSourceCount(key);\n    var bytesPerTile = bytesPerTileForBasemap(key);\n    var bytesPerMb = 1024 * 1024;\n    if (Number.isFinite(count) && count >= 0) {\n      return Math.ceil((count * sources * bytesPerTile) / bytesPerMb) + DOWNLOAD_DOCUMENTS_MB;\n    }\n    var tileMb = Math.max(0, mb - DOWNLOAD_DOCUMENTS_MB);\n    return (\n      Math.ceil((tileMb * sources * bytesPerTile) / WORST_CASE_BYTES_PER_TILE) +\n      DOWNLOAD_DOCUMENTS_MB\n    );\n  }\n\n  /**\n   * Whether a stored area holds every map in ``keys``.\n   *\n   * @param {Object | null | undefined} record\n   * @param {string[]} keys\n   * @returns {boolean}\n   */\n  function recordHoldsBasemaps(record, keys) {\n    var held = recordBasemaps(record).map(function (entry) {\n      return entry.key;\n    });\n    return (keys || []).every(function (key) {\n      return held.indexOf(key) >= 0;\n    });\n  }\n\n  /**\n   * Whether the service worker can fetch a tile template: an http(s) URL,\n   * or one relative to the page. A page-side MapLibre protocol\n   * (SNOW-1460's ``osmclip://``) is drawn by the map alone, and a fetch of\n   * it fails on the scheme, so a download must never list it.\n   *\n   * @param {*} url\n   * @returns {boolean}\n   */\n  function isFetchableTileTemplate(url) {\n    if (typeof url !== 'string' || !url) return false;\n    var scheme = /^([a-z][a-z0-9+.-]*):/i.exec(url);\n    if (!scheme) return true;\n    var name = scheme[1].toLowerCase();\n    return name === 'http' || name === 'https';\n  }\n\n  /**\n   * A basemap's tile sources, from its style document and the TileJSON\n   * each vector source's ``url`` names \u2014 the shape\n   * ``activeBasemapTileSources`` reads off a live map, for a map that is\n   * not on screen. A source with inline ``tiles`` keeps them, as MapLibre\n   * does.\n   *\n   * @param {Object | null | undefined} styleJson\n   * @param {Object<string, Object> | null | undefined} tileJsons By source id.\n   * @returns {string[][] | null} Null for a style with no vector source\n   *   this can resolve.\n   */\n  function tileSourcesFromStyleDocuments(styleJson, tileJsons) {\n    if (!styleJson || typeof styleJson !== 'object' || !styleJson.sources) return null;\n    var sources = [];\n    Object.keys(styleJson.sources).forEach(function (id) {\n      var source = styleJson.sources[id];\n      if (!source || source.type !== 'vector') return;\n      var doc = tileJsons && tileJsons[id];\n      var tiles = Array.isArray(source.tiles)\n        ? source.tiles\n        : doc && Array.isArray(doc.tiles)\n          ? doc.tiles\n          : null;\n      var urls = (tiles || []).filter(isFetchableTileTemplate);\n      if (urls.length) sources.push(urls);\n    });\n    return sources.length ? sources : null;\n  }\n\n  /**\n   * Every render dependency of a basemap from its documents \u2014 the list\n   * ``activeBasemapRenderDependencyURLs`` reads off a live map: the style\n   * document's own URL, its sprite JSON and PNG at 1x and 2x, each vector\n   * source's TileJSON, and the glyph ranges (``glyphURLs``). Relative URLs\n   * resolve against the style's own.\n   *\n   * @param {string} styleUrl Where ``styleJson`` was fetched from.\n   * @param {Object | null | undefined} styleJson\n   * @returns {string[]} Empty for a style it cannot read, which every\n   *   caller reads as UNKNOWN.\n   */\n  function renderDependencyUrlsFromStyle(styleUrl, styleJson) {\n    if (!styleUrl || !styleJson || typeof styleJson !== 'object') return [];\n    var resolve = function (url) {\n      try {\n        return new URL(url, styleUrl).toString();\n      } catch (_err) {\n        return null;\n      }\n    };\n    var urls = [styleUrl];\n    var sprite = styleJson.sprite;\n    var bases = Array.isArray(sprite)\n      ? sprite.map(function (s) {\n          return s && s.url;\n        })\n      : [sprite];\n    bases.forEach(function (base) {\n      if (typeof base !== 'string' || !base) return;\n      var absolute = resolve(base);\n      if (!absolute) return;\n      urls.push(absolute + '.json', absolute + '.png', absolute + '@2x.json', absolute + '@2x.png');\n    });\n    Object.keys(styleJson.sources || {}).forEach(function (id) {\n      var source = styleJson.sources[id];\n      if (!source || source.type !== 'vector' || typeof source.url !== 'string') return;\n      var absolute = resolve(source.url);\n      if (absolute) urls.push(absolute);\n    });\n    return urls.concat(glyphURLs(styleJson));\n  }\n\n  /**\n   * The prefix every glyph request for a style shares \u2014 its ``glyphs``\n   * template cut at the first placeholder; ``''`` when it has none.\n   *\n   * @param {Object | null | undefined} styleJson\n   * @returns {string}\n   */\n  function glyphPrefixFromStyle(styleJson) {\n    var glyphs = styleJson && styleJson.glyphs;\n    if (typeof glyphs !== 'string') return '';\n    var brace = glyphs.indexOf('{');\n    return brace > 0 ? glyphs.slice(0, brace) : '';\n  }\n\n  self.pwaBasemapDownloadCore = Object.freeze({\n    // SNOW-1583: what a downloaded area holds, part by part.\n    AREA_PARTS: AREA_PARTS,\n    areaOutcome: areaOutcome,\n    contentOutcome: contentOutcome,\n    fetchLanded: fetchLanded,\n    retryableFrom: retryableFrom,\n    mergeParts: mergeParts,\n    recordOutcome: recordOutcome,\n    zoomRows: zoomRows,\n    tileSources: tileSources,\n    tileSourceCount: tileSourceCount,\n    tileSourcesKey: tileSourcesKey,\n    tileURLs: tileURLs,\n    basemapKeyForTileSources: basemapKeyForTileSources,\n    bytesPerTileForBasemap: bytesPerTileForBasemap,\n    bytesPerTileForSources: bytesPerTileForSources,\n    sourceScaledMb: sourceScaledMb,\n    rangesToTileURLs: rangesToTileURLs,\n    lonLatToTile: lonLatToTile,\n    tileRangesForBBox: tileRangesForBBox,\n    tileCount: tileCount,\n    centreTile: centreTile,\n    buildBlob: buildBlob,\n    circleBlob: circleBlob,\n    circleBlobForBBox: circleBlobForBBox,\n    budgetScaleForBBox: budgetScaleForBBox,\n    hasStorageHeadroom: hasStorageHeadroom,\n    deviceCeilingMb: deviceCeilingMb,\n    bboxPolygon: bboxPolygon,\n    tileBounds: tileBounds,\n    featureBBox: featureBBox,\n    bboxFromZoomRanges: bboxFromZoomRanges,\n    areaBBox: areaBBox,\n    areaContentURLs: areaContentURLs,\n    resortSheetURL: resortSheetURL,\n    forwardContentDays: forwardContentDays,\n    regionSheetURL: regionSheetURL,\n    areaItemURLs: areaItemURLs,\n    areaItemExpectation: areaItemExpectation,\n    attestedExpectation: attestedExpectation,\n    withProblemTerrain: withProblemTerrain,\n    // SNOW-1417: SAC tours and community reports in an area.\n    tourBoxes: tourBoxes,\n    tourBoxURL: tourBoxURL,\n    tourPlan: tourPlan,\n    reportsInBox: reportsInBox,\n    routesInBox: routesInBox,\n    resortItems: resortItems,\n    withPublicItems: withPublicItems,\n    problemTerrainURL: problemTerrainURL,\n    stampContentRecord: stampContentRecord,\n    favouriteSheetURL: favouriteSheetURL,\n    weatherDetailURL: weatherDetailURL,\n    cachedTilesFromURLs: cachedTilesFromURLs,\n    gridZoomFor: gridZoomFor,\n    tileGridPlan: tileGridPlan,\n    blobFullyCached: blobFullyCached,\n    missingRenderDependencies: missingRenderDependencies,\n    styleFontstacks: styleFontstacks,\n    glyphURLs: glyphURLs,\n    terrainClassTileURLs: terrainClassTileURLs,\n    areaTerrainClassTileURLs: areaTerrainClassTileURLs,\n    terrainClassTileCount: terrainClassTileCount,\n    terrainClassMb: terrainClassMb,\n    terrainScaledBytesPerTile: terrainScaledBytesPerTile,\n    elevationTileURLs: elevationTileURLs,\n    elevationTileCount: elevationTileCount,\n    elevationMb: elevationMb,\n    areaElevationTileURLs: areaElevationTileURLs,\n    elevationAreaBoxes: elevationAreaBoxes,\n    areaIdForRegion: areaIdForRegion,\n    regionIdForArea: regionIdForArea,\n    generateCustomAreaId: generateCustomAreaId,\n    isCustomAreaId: isCustomAreaId,\n    areaIdForBaseLayer: areaIdForBaseLayer,\n    isBaseLayerAreaId: isBaseLayerAreaId,\n    baseLayerBasemapKey: baseLayerBasemapKey,\n    intersectBBox: intersectBBox,\n    baseLayerBBox: baseLayerBBox,\n    baseLayerBand: baseLayerBand,\n    baseLayerBlob: baseLayerBlob,\n    baseLayerTileURLs: baseLayerTileURLs,\n    isTileEntryURL: isTileEntryURL,\n    baseLayerStaleEntries: baseLayerStaleEntries,\n    pinnedCacheName: pinnedCacheName,\n    planEviction: planEviction,\n    MICRO_BAND: MICRO_BAND,\n    BASE_LAYER_BAND: BASE_LAYER_BAND,\n    BASE_LAYER_BANDS: BASE_LAYER_BANDS,\n    WORST_CASE_BYTES_PER_TILE: WORST_CASE_BYTES_PER_TILE,\n    BYTES_PER_TILE_BY_BASEMAP: BYTES_PER_TILE_BY_BASEMAP,\n    DOWNLOAD_CEILING_MB: DOWNLOAD_CEILING_MB,\n    DOWNLOAD_DOCUMENTS_MB: DOWNLOAD_DOCUMENTS_MB,\n    TERRAIN_CLASS_BYTES_PER_TILE: TERRAIN_CLASS_BYTES_PER_TILE,\n    ELEVATION_BYTES_PER_TILE: ELEVATION_BYTES_PER_TILE,\n    ELEVATION_BAND: ELEVATION_BAND,\n    ELEVATION_PARENT_MIN_ZOOM: ELEVATION_PARENT_MIN_ZOOM,\n    ELEVATION_BASEMAP_KEY: ELEVATION_BASEMAP_KEY,\n    elevationBasemap: elevationBasemap,\n    // SNOW-1478: which maps a download saves, and from what.\n    FALLBACK_BASEMAP_KEY: FALLBACK_BASEMAP_KEY,\n    SWISS_COUNTRIES: SWISS_COUNTRIES,\n    groundInSwitzerland: groundInSwitzerland,\n    basemapsForGround: basemapsForGround,\n    countriesForBBox: countriesForBBox,\n    recordBasemaps: recordBasemaps,\n    recordHoldsBasemaps: recordHoldsBasemaps,\n    basemapSourceCount: basemapSourceCount,\n    basemapScaledMb: basemapScaledMb,\n    isFetchableTileTemplate: isFetchableTileTemplate,\n    tileSourcesFromStyleDocuments: tileSourcesFromStyleDocuments,\n    renderDependencyUrlsFromStyle: renderDependencyUrlsFromStyle,\n    glyphPrefixFromStyle: glyphPrefixFromStyle,\n    STORAGE_HEADROOM_FACTOR: STORAGE_HEADROOM_FACTOR,\n    DOWNLOAD_BUDGET_MB: DOWNLOAD_BUDGET_MB,\n    PINNED_CACHE_PREFIX: PINNED_CACHE_PREFIX,\n    CUSTOM_AREA_ID: CUSTOM_AREA_ID,\n    GLYPH_RANGES: GLYPH_RANGES,\n  });\n})();\n"],
  "mappings": "CA+YC,UAAY,CACX,aAKA,IAAIA,GAAa,CAAC,GAAI,EAAE,EAOpBC,EAA4B,GAAK,KA6CjCC,GAA4B,CAE9B,oBAAqB,GAAK,KAW1B,iBAAkB,GAAK,KAEvB,gBAAiB,GAAK,KAStB,SAAU,GAAK,KAIf,WAAY,IAAM,IACpB,EAMIC,GAAoB,CACtB,CAAC,gBAAiB,kBAAkB,EACpC,CAAC,gBAAiB,UAAU,EAC5B,CAAC,aAAc,YAAY,CAC7B,EAQIC,EAAwB,EASxBC,EAA+B,GAAK,KASpCC,EAA2B,IAAM,KASjCC,EAAiB,CAAC,GAAI,EAAE,EACxBC,GAA4B,EAO5BC,EAAwB,mBASxBC,GAAuB,EAAI,EAY3BC,EAAsB,IAyDtBC,GAAkB,CAAC,EAAG,CAAC,EAOvBC,GAAmB,CACrB,oBAAqB,CAAC,EAAG,CAA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AAuBP,EACvB,6BAA8BC,EAC9B,yBAA0BC,EAC1B,eAAgBC,EAChB,0BAA2BC,GAC3B,sBAAuBC,EACvB,iBAAkB8E,EAElB,qBAAsB4U,EACtB,gBAAiBC,GACjB,oBAAqBU,GACrB,kBAAmBc,GACnB,iBAAkBL,GAClB,eAAgBU,GAChB,oBAAqBI,GACrB,mBAAoBF,GACpB,gBAAiBC,GACjB,wBAAyBG,GACzB,8BAA+BE,GAC/B,8BAA+BK,GAC/B,qBAAsBM,GACtB,wBAAyBlc,EACzB,mBAAoBC,GACpB,oBAAqBC,GACrB,eAAgBC,GAChB,aAAcO,CAChB,CAAC,CACH,GAAG",
  "names": ["MICRO_BAND", "WORST_CASE_BYTES_PER_TILE", "BYTES_PER_TILE_BY_BASEMAP", "BASEMAP_HOST_KEYS", "DOWNLOAD_DOCUMENTS_MB", "TERRAIN_CLASS_BYTES_PER_TILE", "ELEVATION_BYTES_PER_TILE", "ELEVATION_BAND", "ELEVATION_PARENT_MIN_ZOOM", "ELEVATION_BASEMAP_KEY", "ELEVATION_BAND_SHARE", "DOWNLOAD_CEILING_MB", "BASE_LAYER_BAND", "BASE_LAYER_BANDS", "baseLayerBand", "basemapKey", "band", "KM_PER_DEGREE_LAT", "STORAGE_HEADROOM_FACTOR", "DOWNLOAD_BUDGET_MB", "PINNED_CACHE_PREFIX", "CUSTOM_AREA_ID", "generateCustomAreaId", "bytes", "out", "i", "isCustomAreaId", "areaId", "GLYPH_RANGES", "STYLE_EXPRESSION_OPS", "collectFontstacks", "node", "head", "payload", "j", "allStrings", "styleFontstacks", "style", "layers", "layout", "textFont", "glyphURLs", "urls", "template", "stacks", "encoded", "terrainClassTileURLs", "blob", "bounds", "minZ", "maxZ", "coverage", "_eachOverlayTile", "z", "x", "y", "_overlayTileURL", "areaTerrainClassTileURLs", "record", "buildBlob", "terrainClassTileCount", "count", "terrainClassMb", "n", "terrainScaledBytesPerTile", "bytesPerTile", "sourceCount", "terrain", "elevation", "base", "sources", "perCell", "_eachElevationTile", "visit", "parents", "seen", "pz", "shift", "px", "py", "key", "a", "b", "all", "elevationTileURLs", "elevationTileCount", "elevationMb", "elevationBasemap", "areaElevationTileURLs", "elevationAreaBoxes", "records", "boxes", "box", "areaBBox", "floor", "ceiling", "rect", "inside", "zKeys", "zi", "rows", "zoomRows", "yKeys", "yi", "span", "_tileIntersectsBBox", "bbox", "tile", "tileBounds", "areaIdForRegion", "regionId", "regionIdForArea", "prefix", "pinnedCacheName", "areaIdForBaseLayer", "isBaseLayerAreaId", "baseLayerBasemapKey", "intersectBBox", "ok", "baseLayerBBox", "cameraBBox", "styleBounds", "baseLayerBlob", "baseLayerTileURLs", "spec", "rangesToTileURLs", "TILE_ENTRY_PATH", "isTileEntryURL", "url", "baseLayerStaleEntries", "entries", "expectedTiles", "wanted", "stale", "entry", "planEviction", "areas", "incoming", "budgetBytes", "budget", "list", "incomingId", "incomingBytes", "others", "evictable", "standing", "sum", "total", "sorted", "ta", "tb", "evict", "area", "zEntry", "xmin", "xmax", "ymin", "ymax", "tileSources", "tileSourceCount", "tileSourcesKey", "tileURLForSource", "tileURLs", "source", "basemapKeyForTileSources", "fragment", "bytesPerTileForBasemap", "bytesPerTileForSources", "sourceScaledMb", "mb", "bytesPerMb", "tileMb", "zKey", "yKey", "lonLatToTile", "lon", "lat", "wx", "wy", "lonLatToWorld", "latRad", "tileRangesForBBox", "west", "south", "east", "north", "ranges", "x0", "y0", "x1", "y1", "maxIndex", "tileCount", "centreTile", "centreLon", "centreLat", "ceilingMb", "totalBytes", "resolveCeilingMb", "circleBlob", "radiusKm", "latDelta", "southY", "northY", "tileSouth", "tileNorth", "nearLat", "dLatKm", "halfKm", "cos", "halfLon", "circleBlobForBBox", "budgetScaleForBBox", "tileBudgetMb", "perTile", "spanX", "spanY", "c", "scale", "deviceCeilingMb", "estimate", "quota", "usage", "free", "hasStorageHeadroom", "needed", "bboxPolygon", "cachedTilesFromURLs", "cachedURLs", "zoom", "matchers", "forSource", "matcher", "_tileMatcher", "order", "match", "pattern", "re", "_mercatorYToLat", "featureBBox", "feature", "geometry", "rings", "w", "s", "e", "ring", "position", "bboxFromZoomRanges", "zooms", "minX", "maxX", "minY", "maxY", "stored", "DATE_KEY_RE", "MS_PER_DAY", "BOOT_RATINGS_COUNTRY", "PROBLEM_TERRAIN_URL", "TERRAIN_COUNTRIES", "forwardContentDays", "today", "onScreen", "todayMs", "end", "endMs", "days", "ms", "regionSheetURL", "day", "resortSheetURL", "slug", "areaContentURLs", "options", "opts", "sheetTemplate", "seenRegion", "inTerrainCountry", "region", "resortTemplate", "seenResort", "resort", "problemTerrainURL", "seenLocation", "point", "shortId", "weatherDetailURL", "NIL_UUID", "favouriteSheetURL", "uuid", "areaItemURLs", "items", "templates", "alreadyPlanned", "expected", "areaItemExpectation", "item", "tpl", "name", "trips", "trip", "pins", "pin", "sheet", "attestedExpectation", "expectation", "attested", "pagePrincipal", "withProblemTerrain", "SKI_TOURS_MAX_SPAN_DEG", "round3", "value", "tourBoxes", "maxSpan", "cap", "usable", "cols", "edges", "from", "to", "xs", "ys", "r", "tourBoxURL", "tourPlan", "answers", "short", "tours", "answer", "props", "reportsInBox", "feed", "ids", "newest", "newestMs", "coords", "routesInBox", "isPoint", "crosses", "dx", "dy", "lo", "hi", "p", "q", "t", "enters", "line", "points", "routes", "lines", "resortItems", "resorts", "withPublicItems", "extras", "id", "PUBLIC_ITEM_FIELDS", "stampContentRecord", "complete", "nowIso", "next", "publicFields", "field", "kept", "gridZoomFor", "_cellForTile", "gridZ", "gridRows", "cx", "cy", "step", "_nearestRow", "best", "bestDistance", "distance", "tileGridPlan", "buckets", "rowKey", "cellKey", "bucket", "byRow", "rowKeys", "ordered", "rowIndex", "row", "cells", "cellOfURL", "index", "blobFullyCached", "cached", "cachedSet", "missingRenderDependencies", "depURLs", "missing", "AREA_PARTS", "RETRYABLE_KINDS", "partCount", "part", "areaOutcome", "parts", "map", "keys", "fetchLanded", "retryableFrom", "failures", "failure", "kind", "mergeParts", "prior", "run", "before", "now", "had", "recordOutcome", "probes", "addition", "verified", "contentOutcome", "content", "FALLBACK_BASEMAP_KEY", "SWISS_COUNTRIES", "GROUND_SAMPLES", "inRing", "xi", "xj", "yj", "inPolygons", "polygons", "polygon", "hole", "groundInSwitzerland", "extent", "vertexInside", "foreignBasemapKey", "activeKey", "countries", "countriesByKey", "covered", "code", "countriesForBBox", "features", "found", "country", "meets", "basemapsForGround", "ground", "listed", "foreign", "place", "recordBasemaps", "BASEMAP_SOURCE_COUNTS", "basemapSourceCount", "basemapScaledMb", "recordHoldsBasemaps", "held", "isFetchableTileTemplate", "scheme", "tileSourcesFromStyleDocuments", "styleJson", "tileJsons", "doc", "tiles", "renderDependencyUrlsFromStyle", "styleUrl", "resolve", "sprite", "bases", "absolute", "glyphPrefixFromStyle", "glyphs", "brace"]
}
