Compare commits

..
Author SHA1 Message Date
German Khokhlov 527068c126 feat(perimeters): colour fire perimeters by age
The Fire Perimeters layer now draws a snapshot of fires and the pieces of
their burned area, each piece coloured by its age at the snapshot's moment
on the WorldFX scale (under 6 h, 6-24 h, 1-3 days, older or unknown).
Containment stays on the card; the legend counts fires by last growth and
shows the source's note.

- One source method, getSnapshot, returning {at, fetchedAt, stale,
  revision, note, fires, pieces}; getSnapshotDetail is removed.
- WFIGS: one piece per polygon, born at poly_PolygonDateTime, else
  poly_DateCurrent; a future time is unknown.
- Outlines are drawn apart from fills, so cut pieces have no line along
  the cut; redraws happen only on a new revision or a change of age band.
- The card ages from `at` and adds "last growth ... ago".
- perimeterOptions: { inciweb: false } creates no InciWeb sources.
- get_fire_perimeters filters by pieces, places fires at their anchor and
  returns last_growth; spot conditions use the anchor.
2026-11-20 19:41:13 +04:00
48 changed files with 1172 additions and 979 deletions

No files matched your search

-3
View File
@@ -205,9 +205,6 @@ AISSTREAM_API_KEY=
# Traffic Flow & Incidents tile requests per MONTH, not per day; no credit card
# required. Get a key at https://my.tomtom.com/keys). SERVER-SIDE ONLY:
# the browser fetches same-origin /api/tomtom/* and never sees the key.
# The key needs a traffic product assigned at my.tomtom.com: either the
# TomTom Maps Traffic API or the Orbis Maps one works (the proxy tries the
# first and falls back to Orbis on HTTP 403).
# Keyless fallback: the traffic layer runs its built-in simulation (white dots,
# hardcoded per-road-class speeds) — no key required for the layer to work.
# TOMTOM_API_KEY=
+2 -2
View File
@@ -43,7 +43,7 @@ How to read this:
| **USGS** | Earthquakes | U.S. public domain | "Data courtesy of the U.S. Geological Survey" |
| **Environment and Climate Change Canada** (MSC GeoMet OGC API) | Air quality (AQHI) — Canadian station observations | [ECCC Data Servers End-use Licence](https://eccc-msc.github.io/open-data/licence/readme_en/) (open, attribution required, no endorsement implied) | "Contains information licensed under the Environment and Climate Change Canada Data Servers End-use Licence" |
| **NASA GIBS** (WMTS tiles + Worldview Snapshots) and **NASA CMR** (granule catalog) | Recent Imagery layer: HLS S30/L30 (Sentinel-2, Landsat 8/9) and VIIRS true-colour tiles draped on the map, per-day thumbnails and PNG exports; the HLS granule catalog (dates, cloud, footprints) for a selected box | U.S. public domain (NASA data); keyless, browser-direct (CORS `*`); no bulk use — one 30-day catalog query per box, tiles bounded to the box, six tile requests in flight | "We acknowledge the use of imagery provided by services from NASA's Global Imagery Browse Services (GIBS), part of NASA's Earth Science Data and Information System (ESDIS)." — [gibs.earthdata.nasa.gov](https://gibs.earthdata.nasa.gov), [HLS](https://lpdaac.usgs.gov/products/hlss30v002/) |
| **NIFC WFIGS** (Wildland Fire Interagency Geospatial Services, ArcGIS feature service) | Fire Perimeters layer: current interagency wildfire incident perimeters, containment, and incident facts | U.S. public domain (interagency wildland-fire data published through the [NIFC Open Data portal](https://data-nifc.opendata.arcgis.com/)); fetched keyless through `/api/fire-perimeters` (5-minute server cache) with `exceededTransferLimit` paging | "Wildfire perimeters: National Interagency Fire Center (WFIGS)" |
| **NIFC WFIGS** (Wildland Fire Interagency Geospatial Services, ArcGIS feature service) | Fire Perimeters layer: current interagency wildfire incident perimeters, containment, and incident facts; perimeters are coloured by when they were mapped (`poly_PolygonDateTime`, else the record's last edit `poly_DateCurrent`, which also moves when only the incident's attributes are edited, so such a fire can look newly grown) | U.S. public domain (interagency wildland-fire data published through the [NIFC Open Data portal](https://data-nifc.opendata.arcgis.com/)); fetched keyless through `/api/fire-perimeters` (5-minute server cache) with `exceededTransferLimit` paging | "Wildfire perimeters: National Interagency Fire Center (WFIGS)" |
| **S2 Underground GhostMaps** (`github.com/s2underground/GhostMaps`) | S2 GhostMaps layer: the current edition of S2's KMZ intel products (Common Intelligence Picture, 30-day kinetic pull, Border Crisis Map, Iran and Yemen products, newest incident drop). Keyless. `/api/ghostmaps` reads the branch head from git's ref advertisement every 15 s (`GHOSTMAPS_POLL_SECONDS`, minimum 5 s), lists the tree through the GitHub REST API only when the head changes (optional `GITHUB_TOKEN`), downloads files by commit-pinned raw URLs into `.gev-cache/ghostmaps/` and pushes new catalogs to browsers over server-sent events | [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) (repository README: "S2 Underground © 2025 by S2A1"); non-commercial, attribution required; files are fetched at runtime, never stored in this repository | "S2 GhostMaps intel products: S2 Underground © by S2A1, CC BY-NC-SA 4.0" — shown in-app |
| **News server** (`GEV_NEWS_ORIGIN`, optional; none by default) | News layer, both sections: the last 24 h of reports from many publishers. Set, the local server forwards the layer's `/api/news/hotspots`, `/feed` and `/outline` GET requests to it and Core reads none of the three sources below. Which providers stand behind its feed is the news server's to state | Each report stays its publisher's: headlines and summaries link to the original article, and pictures are hotlinked from the publisher's site (no referrer), never stored | Per report: publisher name and article link on every card; picture cards name the picture's publisher. The Data attribution popover states that places, categories, severity and English headlines are derived automatically and can be wrong |
| **GDELT 2.0 events and GKG** (`data.gdeltproject.org/gdeltv2/`; no key; used only without a news server) | News layer, Conflicts: the last 24 h of GDELT's 15-minute event exports (`*.export.CSV.zip`, about 100 KB each), read server-side as they appear. Physical violence only (CAMEO roots 18–20); one report per story, copies of one agency story merged; placed at GDELT's location for it (a town the article's words name beats a bare country). Titled by the article's page title from the GKG export of the same quarter hour (`*.gkg.csv.zip`, about 6 MB each) for the newest 3 h, else by the words of the article's address. GDELT's actor coding is never shown. Categories, relevance and severity by bundled rules | [GDELT Terms of Use](https://www.gdeltproject.org/about.html#termsofuse): unrestricted academic, commercial and governmental use, with citation and a link to the GDELT Project. Coded events, page titles and article links only; linked articles keep their publishers' terms | "GDELT Project" with a link to gdeltproject.org in the Data attribution popover; "via GDELT Project", the publisher's domain and the article link on every card |
@@ -281,7 +281,7 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei
- **Radio country coverage (optional).** Set `RADIO_PRIORITY_COUNTRIES=IN,PL` in the local `.env` and restart to include stations beyond the global click charts. The operator may choose up to eight unique ISO alpha-2 country codes; no key is needed. Each country adds one bounded query (at most 200 rows) and reserves up to 40 unique, usable stations inside the existing 750-station catalog. Country seeds precede specialist-tag seeds and global popularity fill; unused slots return to the shared pool. This is a coverage preference, not an exhaustive national directory or a guarantee of stations in every city. Countries with no eligible HTTPS MP3/AAC geolocated stations remain empty. An unset list preserves global selection. Country requests share the directory cache and three-worker pool; failed country queries are reported in coverage without blocking a healthy global refresh. Failed/degraded refreshes back off for one minute, with at most three mirrors per query.
- **Radio Browser.** In every installation, including when `RADIO_PRIORITY_COUNTRIES` is unset, each request tries at most three mirror candidates (later fallback candidates are skipped), and failed or partial catalog refreshes back off for 60 seconds. A cold-start failure therefore continues returning 503 during that delay even if upstream recovers. `/api/radio/stations` discovers official API mirrors, makes bounded and coalesced healthy/geolocated HTTPS-station queries, caches the normalized public-domain directory for 45 minutes, and may serve the last good catalog for up to seven days during an outage. Refreshes must meet minimum accepted-query and station coverage before replacing a warm catalog; broad/specialist responses whose rows all fail the product's health policy do not count as successful queries. Optional priority-country outcomes are advisory: valid, in-limit responses with no eligible stations succeed as empty results, while failed or malformed country queries report unsuccessful coverage without degrading the global catalog. A usable partial cold catalog is explicitly `DEGRADED`, and non-array or empty broad/specialist payloads are rejected atomically. Individual structurally malformed rows are skipped rather than failing the whole query; the response carries their bounded `rejectedStationCount` (at most 10,000), which the client adds to its own rejected rows and reports as degraded coverage without discarding the accepted generation. Every directory and click-count request rejects redirects, validates all resolved addresses as globally routable (including reserved/documentation IPv4 and special/non-global IPv6 exclusions), and pins the TLS connection to a validated address. Only MP3/AAC non-HLS directory rows with public HTTPS stream targets are returned; favicons are intentionally omitted. Pressing play connects one browser audio element directly to the selected broadcaster and calls the directory's click counter through known-ID-only `POST /api/radio/click/:uuid`. GEV never proxies, caches, records, bundles, or redistributes audio. Radio Browser supplies station-level tags, not dependable current-song or upcoming-program metadata, so Radio filtering never claims either. Direct playback exposes the listener's IP address to the broadcaster, whose own stream terms apply.
- **TomTom Traffic.** Optional and BYOK: without `TOMTOM_API_KEY` the traffic layer runs its built-in simulation and no TomTom data (or attribution) appears. With a key, flow vector tiles are fetched through the server-side `/api/tomtom` proxy (from the TomTom Maps Traffic API, or the TomTom Orbis Maps Traffic API when the key is only assigned that product; 120 s cache + a daily tile-budget governor — `TOMTOM_DAILY_TILE_BUDGET`, default 6,000 — sized so a 31-day month stays inside TomTom's 200K monthly free allowance; still a configurable application safety ceiling, not a guarantee; TomTom's [current pricing](https://docs.tomtom.com/pricing/) lists 200K free tile requests per month) and the "Traffic flow data © TomTom" credit is registered in the Data attribution popover the moment live mode activates. TomTom data is served live and cached only transiently (≤120 s TTL under `.gev-cache/`, gitignored) — it is not bundled or redistributed. One 23 KB point-in-time tile snapshot is committed as a decode-test fixture (`src/data/fixtures/`, © TomTom, never served to the app).
- **TomTom Traffic.** Optional and BYOK: without `TOMTOM_API_KEY` the traffic layer runs its built-in simulation and no TomTom data (or attribution) appears. With a key, flow vector tiles are fetched through the server-side `/api/tomtom` proxy (120 s cache + a daily tile-budget governor — `TOMTOM_DAILY_TILE_BUDGET`, default 6,000 — sized so a 31-day month stays inside TomTom's 200K monthly free allowance; still a configurable application safety ceiling, not a guarantee; TomTom's [current pricing](https://docs.tomtom.com/pricing/) lists 200K free tile requests per month) and the "Traffic flow data © TomTom" credit is registered in the Data attribution popover the moment live mode activates. TomTom data is served live and cached only transiently (≤120 s TTL under `.gev-cache/`, gitignored) — it is not bundled or redistributed. One 23 KB point-in-time tile snapshot is committed as a decode-test fixture (`src/data/fixtures/`, © TomTom, never served to the app).
- **Routing (OSRM / FOSSGIS).** `/api/route` proxies the public OSRM instances FOSSGIS e.V. runs for the OpenStreetMap community (car, bike, foot profiles). They are keyless and intended for fair, interactive use — the proxy rate-limits clients (60/min, 200/min total), caps route span and response size, caches each route for 10 minutes, and identifies itself in the User-Agent. Heavy or automated use must run its own OSRM. Routes are computed from OpenStreetMap data (ODbL); the Directions layer and voice routes never redistribute them. A route the router cannot find is reported as such; the Directions layer draws nothing in that case, and voice routes fall back to a clearly labeled straight line.
- **Re:Earth Terrain.** Keyless (no API key). Used two ways: (1) `src/mapStackController.js` swaps in a `Cesium.CesiumTerrainProvider` pointed at Re:Earth's `cesium-mesh/ellipsoid` quantized-mesh endpoint for globe stacks without a Cesium ion token (e.g. OSM), replacing a flat `EllipsoidTerrainProvider`; falls back to the flat provider if the endpoint can't be reached. (2) The server-side `/api/terrain/heights` proxy (disk-cached, serve-stale) resolves per-point ellipsoidal ground height for entity placement. Both are best-effort with a keyless-safe fallback (bundled EGM96 geoid math) if Re:Earth is unreachable.
- **OSRM on the FOSSGIS routing servers.** Keyless (no API key). Every route is requested by a person: clicking A and B in the Directions layer, or a voice "route from A to B". The server-side `/api/route` proxy sends an identifying `User-Agent`, pins the upstream host, accepts 2-12 coordinates, rejects any leg over 600 km or a total over 2,500 km, caps the buffered response at 8 MB, times the upstream out at 12 s, rate-limits per client, caches each route for 10 minutes, and coalesces identical requests that are in flight at the same time. Turn-by-turn maneuvers are asked for only when a caller wants them (`steps=1`), so the callers that do not read them send the smaller request. The "fix the map" link the policy asks for is in the Data attribution popover beside the OpenStreetMap credit.
+1 -1
View File
@@ -441,7 +441,7 @@ Twenty-three layers and map sources. **Twenty-one have a keyless path.** Some of
| ✈️ **Live Flights** | 11,000+ live aircraft + route history | OpenSky + adsb.lol | 🟢 (🟡 optional for more polling credits) |
| 🎖️ **Military Flights** | ADS-B military traffic in amber, emergency broadcasts in red | adsb.lol | 🟢 |
| 📡 **GNSS Integrity** | Regional navigation accuracy scores; anomalies do not confirm interference | adsb.lol, GPSJAM aggregation | 🟢 |
| 🔥 **Fire Perimeters** | Incident boundaries and reported containment | WFIGS / NIFC | 🟢 |
| 🔥 **Fire Perimeters** | Incident boundaries coloured by how recently they were mapped; size, containment and cause on each card | WFIGS / NIFC | 🟢 |
| 🚢 **Live Vessels** | Thousands of ships worldwide | AISStream | 🟡 |
| 🛰️ **Satellites** | About 1,300 objects in six classes (Stations, Imaging, Telecom, Starlink, Probes, Debris) with a toggle and a live count each; Starlink loads its whole shell | CelesTrak | 🟢 |
| 🌍 **Earthquakes** | Global seismic activity, last 24h | USGS | 🟢 |
@@ -1,5 +0,0 @@
- Live traffic works with TomTom keys that are only assigned the Orbis Maps
traffic product: when TomTom refuses the key on the TomTom Maps flow tile
endpoint (HTTP 403), the proxy uses the Orbis one and keeps it. A key both
endpoints refuse now reads "TomTom key rejected" instead of "TomTom upstream
unreachable", and stops spending the daily tile budget on retries (#1809).
+18 -20
View File
@@ -1123,17 +1123,19 @@ Catalog calls check their cancellation signal immediately before executing a
tool. Already-cancelled queries do not start; cancellation after execution starts
continues to follow the existing tool and caller behavior.
Fire-perimeter queries test polygon interiors and holes on continuous unwrapped
longitudes, matching the short-edge convention used for boundary intersections.
An outline crossing ±180° contains nearby boxes and radius areas without also
containing their counterparts near Greenwich. Returned perimeter coordinates
use a circular mean for longitude, including multipart outlines. Incident cards
also use a circular longitude mean over the largest outer ring (excluding its
repeated closing vertex). Their relative-area comparison follows short longitude
edges so a small dateline-crossing part cannot outweigh a larger ordinary part.
Regression coverage lives in `src/tools/area.test.mjs`,
`src/tools/queries/environment.test.mjs` and
`src/layers/perimeters/cards.test.mjs`.
Fire-perimeter queries test the polygon interiors and holes of each fire's
pieces on continuous unwrapped longitudes, matching the short-edge convention
used for boundary intersections: a fire is in the area when one of its pieces
is. An outline crossing ±180° contains nearby boxes and radius areas without
also containing their counterparts near Greenwich. A fire is returned at its
card anchor, which the source gives; for WFIGS it is a circular longitude mean
over the largest outer ring (excluding its repeated closing vertex), with the
relative-area comparison following short longitude edges so a small
dateline-crossing part cannot outweigh a larger ordinary part. Context's
hazard list measures distance to the same anchor. Regression coverage lives in
`src/tools/area.test.mjs`, `src/tools/queries/environment.test.mjs`,
`src/layers/perimeters/cards.test.mjs` and
`src/layers/perimeters/records.test.mjs`.
## Scope display controls
@@ -4027,14 +4029,6 @@ The TomTom `/api/tomtom/*` routes run the shared same-site admission gate before
status, cache or upstream work, refusing cross-site browser requests while
preserving same-origin app requests and non-browser local callers. The browser
layers and their rendering remain in their existing modules.
The proxy asks the TomTom Maps flow endpoint (`traffic/map/4/tile/flow/relative`)
first. On HTTP 403, which TomTom answers when a key is not assigned that
product, it asks the Orbis Maps one (`maps/orbis/traffic/flow/vector/tile`,
`apiVersion=2`) and keeps whichever answered until the key changes or the
process restarts; `flowDecode.js` reads both tile schemas into one segment
shape. When both refuse the key, tiles answer `403 {error:'key_rejected'}`
(shown as "TomTom key rejected"), `/api/tomtom/status` reports
`keyRejected: true`, and upstream is left alone for five minutes.
Past the daily tile budget, or while TomTom fails, the proxy answers with its
last copy of a tile (`x-tomtom-cache: STALE-BUDGET` / `STALE-ERROR`) however old
it is, and every tile carries `x-tomtom-fetched-at`, the proxy fetch time
@@ -6395,7 +6389,11 @@ MLAT-positioned GPS loss, derived-field exclusions and the NIC 0 exception.
anchors, recovery, keyboard and mobile states; emergency repainting is covered
by `scripts/qa-emergency-squawk.mjs`. Both accept `--timeout-ms` for slow boot.
Fire Perimeters uses capped, timed server reads with stale-on-error caching and a per-client limit. A stale snapshot is served for at most 24 hours; the layer row then reads STALE, dated by that snapshot's fetch, and `get_fire_perimeters` returns `stale` and `retrieved_at` with "(data may be stale)" in its summary. Unchanged snapshots retain geometry; link checks cancel on disable or selection change, and the row legend shows reported containment.
Fire Perimeters uses capped, timed server reads with stale-on-error caching and a per-client limit. A stale snapshot is served for at most 24 hours; the layer row then reads STALE, dated by that snapshot's fetch, and `get_fire_perimeters` returns `stale` and `retrieved_at` with "(data may be stale)" in its summary. Link checks cancel on disable or selection change.
Fire Perimeters draws a snapshot of fires and the pieces of their burned area: the source's `getSnapshot({ signal })` answers `{ at, fetchedAt, stale, revision, note, fires, pieces }` (`src/layers/perimeters/records.js`). Each piece is filled and its `outline` drawn as separate draped lines, so a piece cut from a larger area has no line along the cut; a piece whose fire is not listed is dropped. Pieces are coloured by age at `at` (or now) on the WorldFX scale: under 6 hours yellow, 6–24 hours orange, 1–3 days red, older or of unknown birth dark red. The layer redraws only when `revision` changes or a piece moves to another age band. The legend counts fires by `lastGrowthTime` in the same four bands and shows the source's `note` below them; the card keeps its containment accent, ages from `at`, and adds "last growth … ago". A selected fire keeps its card while the snapshot lists it, with or without pieces. A failed read keeps the last picture and the row shows the error. When to read again (a timeline, the camera) is the host's call through the manager's `refreshLayer`. `createApplicationCatalog({ perimeterOptions: { inciweb: false } })` creates no InciWeb sources: the cards carry no links and InciWeb is never asked.
WFIGS keeps one current perimeter per fire, so each of its polygons is one piece, outlined by all its rings, and colour is the age of that perimeter: `poly_PolygonDateTime`, or the record's last edit `poly_DateCurrent` when that is empty (about one fire in seven), which moves with any edit to the record. A time more than 10 minutes ahead of the browser clock counts as unknown. Its `revision` follows fire ids and `poly_DateCurrent`, `at` is always null, and the note reads "Perimeters are simplified to about 100 m.".
The incident card rounds the WFIGS size to whole acres, except under one acre,
where it keeps the reported hundredths: a 0.25-acre fire reads `0.25 ac`, not
+1 -1
View File
@@ -310,7 +310,7 @@ and the development server's internal routes. See SECURITY.md.
| `get_bhote_koshi_flood` | `events` | The 2026 Bhote Koshi flood: evidence trail in story order, flood path and imagery dates (CC BY-NC 4.0) |
| `get_regional_brief` | `regional` | What and where a location is, its weather and recent headlines |
| `get_cyclones` | `cyclones` | Active NHC/CPHC tropical cyclones, optionally in an area |
| `get_fire_perimeters` | `perimeters` | Mapped WFIGS wildfire perimeters in an area, largest first |
| `get_fire_perimeters` | `perimeters` | Mapped WFIGS wildfire perimeters in an area, largest first, with when each last grew |
| `get_terrain_height` | `terrain` | Ground, geoid and ellipsoid heights at up to 20 points |
| `find_military_installations` | `installations` | OpenStreetMap military sites in an area of at most 10° per side |
| `get_map_features` | `features` | Administrative areas, named places or monuments at a location (needs Overpass) |
+2 -1
View File
@@ -467,6 +467,8 @@
"src/layers/perimeters/cards.test.mjs",
"src/layers/perimeters/inciweb.test.mjs",
"src/layers/perimeters/ownership.test.mjs",
"src/app/layers/perimeters.test.mjs",
"src/ui/spotConditions.test.mjs",
"src/layers/droneAirspace/index.js",
"src/layers/droneAirspace/records.js",
"src/layers/droneAirspace/source.js",
@@ -1214,7 +1216,6 @@
"src/sources/militaryTileGeometry.test.mjs",
"src/layers/traffic/surface.test.mjs",
"src/layers/traffic/roadModes.test.mjs",
"src/layers/traffic/flowDecode.test.mjs",
"scripts/qa-traffic-motion.mjs",
"src/layers/traffic/motion.test.mjs",
"scripts/qa-journey-recorder.mjs",
+2
View File
@@ -279,6 +279,7 @@
"src/i18n/marker.js",
"src/sources/httpBody.js",
"src/layers/perimeters/source.js",
"src/layers/perimeters/records.js",
"src/ui/spotConditions.js",
"src/ui/views/panels/SpotConditions.vue",
"src/data/wikidataCities.js",
@@ -8187,6 +8188,7 @@
"src/data/militaryInstallationData.js",
"src/layers/launches/source.js",
"src/layers/perimeters/source.js",
"src/layers/perimeters/records.js",
"src/layers/radio/source.js",
"src/layers/radio/policy.js",
"src/layers/satellites/source.js",
+1
View File
@@ -23,6 +23,7 @@ const API_URL =
'attr_IncidentTypeCategory',
'attr_FireDiscoveryDateTime',
'poly_DateCurrent',
'poly_PolygonDateTime',
'attr_FireCause',
'attr_FireBehaviorGeneral',
'attr_TotalIncidentPersonnel',
+7 -99
View File
@@ -18,18 +18,6 @@ import { admitSameSite } from './common/same-site.js';
* "Traffic flow"). The key comes from TOMTOM_API_KEY server-side only — the
* browser fetches same-origin `/api/tomtom/flow/{z}/{x}/{y}.pbf`.
*
* Orbis fallback: TomTom keys are assigned products, and a key without the
* TomTom Maps traffic product gets 403 on the endpoint above while the same
* key works on the TomTom Orbis Maps one,
* https://api.tomtom.com/maps/orbis/traffic/flow/vector/tile/{z}/{x}/{y}?apiVersion=2
* (same "Traffic flow" layer; `relative_speed` and `road_category` replace
* `traffic_level` and `road_type`, which the client decoder reads either
* way). On 403 the proxy asks the other endpoint and keeps whichever
* answered for the rest of the process. When both refuse the key, tiles
* answer 403 {error:'key_rejected'} and upstream is left alone for
* KEY_REJECTED_TTL_MS, so a rejected key does not spend the daily budget one
* tile at a time. Changing the key clears both.
*
* Cache: memory + disk (.gev-cache/tomtom/), TTL 120 s (traffic is fresh
* data), single-flight per tile, serve-stale-on-failure — the celestrakProxy
* pattern. Cache hits never count against the budget.
@@ -55,7 +43,7 @@ import { admitSameSite } from './common/same-site.js';
* at distinct tiles, spend the TomTom quota and leave the traffic layer on
* 429 budget for the rest of the UTC day.
*
* GET /api/tomtom/status → {hasKey, keyRejected, dailyCount, budget, date}. Keyless mode:
* GET /api/tomtom/status → {hasKey, dailyCount, budget, date}. Keyless mode:
* status reports hasKey:false and the tile endpoint 503s {error:'no_key'}
* without touching upstream — the traffic layer then stays in simulation mode.
*
@@ -71,37 +59,6 @@ export function tomtomProxy() {
const UPSTREAM_TIMEOUT_MS = 15000;
/** Flow tiles are well under 1 MB; this bounds a runaway body, not a budget. */
const TOMTOM_TILE_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
/** How long a key both endpoints refused is left alone before a retry. */
const KEY_REJECTED_TTL_MS = 5 * 60_000;
/** Upstream flow-tile endpoints, in the order a new key is tried. */
const ENDPOINTS = {
legacy: (z, x, y, key) => ({
url:
'https://api.tomtom.com/traffic/map/4/tile/flow/relative/' +
`${z}/${x}/${y}.pbf?key=${encodeURIComponent(key)}`,
}),
orbis: (z, x, y, key) => ({
url:
'https://api.tomtom.com/maps/orbis/traffic/flow/vector/tile/' +
`${z}/${x}/${y}?apiVersion=2`,
headers: { 'TomTom-Api-Key': key },
}),
};
/**
* What is known about the configured key: the endpoint that last served
* it, and until when both endpoints are known to refuse it. Reset when the
* key changes (Provider Settings rewrites process.env at runtime).
* @type {{key:string, endpoint:'legacy'|'orbis', rejectedUntil:number}}
*/
let keyState = { key: '', endpoint: 'legacy', rejectedUntil: 0 };
function currentKeyState() {
const key = process.env.TOMTOM_API_KEY || '';
if (keyState.key !== key)
keyState = { key, endpoint: 'legacy', rejectedUntil: 0 };
return keyState;
}
const isKeyRejected = () => Date.now() < currentKeyState().rejectedUntil;
/** @type {Map<string, {at:number, buf:Buffer}>} tile key `z/x/y` -> cached tile (kept past TTL for serve-stale). */
const mem = new Map();
@@ -192,17 +149,14 @@ export function tomtomProxy() {
mem.set(key, entry);
}
async function fetchEndpoint(name, z, x, y, key) {
const { url, headers } = ENDPOINTS[name](z, x, y, key);
async function fetchUpstream(z, x, y) {
const url =
'https://api.tomtom.com/traffic/map/4/tile/flow/relative/' +
`${z}/${x}/${y}.pbf?key=${encodeURIComponent(process.env.TOMTOM_API_KEY)}`;
recordUpstreamFetch(); // attempts count — upstream bills the request either way
const signal = AbortSignal.timeout(UPSTREAM_TIMEOUT_MS);
const res = await fetch(url, { signal, ...(headers ? { headers } : {}) });
if (!res.ok) {
await res.body?.cancel().catch(() => {});
throw Object.assign(new Error(`HTTP ${res.status}`), {
status: res.status,
});
}
const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const bytes = await readResponseBytesCapped(
res,
TOMTOM_TILE_MAX_RESPONSE_BYTES,
@@ -213,41 +167,6 @@ export function tomtomProxy() {
return buf;
}
/**
* Fetch one tile from the endpoint this key last worked on, asking the
* other one only when TomTom refuses the key (403). Both refusing marks
* the key rejected; any other failure is an ordinary upstream error.
*/
async function fetchUpstream(z, x, y) {
const state = currentKeyState();
const other = state.endpoint === 'legacy' ? 'orbis' : 'legacy';
try {
return await fetchEndpoint(state.endpoint, z, x, y, state.key);
} catch (err) {
if (err?.status !== 403) throw err;
}
try {
const buf = await fetchEndpoint(other, z, x, y, state.key);
if (keyState === state) {
state.endpoint = other;
console.warn(
`[tomtom-proxy] key refused on the ${other === 'orbis' ? 'TomTom Maps' : 'Orbis'} flow endpoint (HTTP 403); using the ${other === 'orbis' ? 'Orbis' : 'TomTom Maps'} one`,
);
}
return buf;
} catch (err) {
if (err?.status !== 403) throw err;
if (keyState === state)
state.rejectedUntil = Date.now() + KEY_REJECTED_TTL_MS;
throw Object.assign(
new Error(
'HTTP 403 on both flow endpoints: check the products assigned to the key and its domain whitelist at https://my.tomtom.com/keys',
),
{ status: 403 },
);
}
}
const installMiddleware = (server) => {
server.middlewares.use('/api/tomtom', async (req, res) => {
// Gate first: a cross-site <img>/fetch must not reach the budget counter.
@@ -285,7 +204,6 @@ export function tomtomProxy() {
const b = currentBudget();
sendJson(200, {
hasKey,
keyRejected: hasKey && isKeyRejected(),
dailyCount: b.count,
budget: dailyBudgetLimit(),
date: b.date,
@@ -324,14 +242,6 @@ export function tomtomProxy() {
return;
}
// TomTom refused the key on both endpoints: asking again per tile
// would only spend the budget. Last-good data still beats nothing.
if (isKeyRejected()) {
if (entry) sendTile(entry, 'STALE-ERROR');
else sendJson(403, { error: 'key_rejected' });
return;
}
// Budget governor: over the soft cap, last-good data beats a dead layer.
if (isTomTomOverBudget(currentBudget(), dailyBudgetLimit())) {
if (entry) {
@@ -367,8 +277,6 @@ export function tomtomProxy() {
sendTile(fresh, 'MISS');
} else if (entry) {
sendTile(entry, 'STALE-ERROR'); // upstream down — stale beats empty
} else if (isKeyRejected()) {
sendJson(403, { error: 'key_rejected' });
} else {
sendJson(502, { error: 'upstream' });
}
+4
View File
@@ -67,6 +67,8 @@ export const APPLICATION_LAYER_METADATA = Object.freeze([
* `placement`, a host-supplied placement provider (../data/placementProvider.js),
* places live aircraft, vessels, transit and trains; without one each layer
* uses its own motion.
* `perimeterOptions: { inciweb: false }` leaves the Fire Perimeters cards
* without InciWeb links, and the layer never asks InciWeb.
*/
export function createApplicationCatalog({
surface,
@@ -75,6 +77,7 @@ export function createApplicationCatalog({
metadata = APPLICATION_LAYER_METADATA,
vesselOptions,
newsOptions,
perimeterOptions,
resolveAsset,
nepalBoundaryResolver,
streetLevelProviders,
@@ -145,6 +148,7 @@ export function createApplicationCatalog({
createApplicationEarthquakes({ source: sources.earthquakes }),
createApplicationAirQuality({ source: sources['air-quality'] }),
createApplicationFirePerimeters({
...perimeterOptions,
source: sources['fire-perimeters'],
}),
createApplicationGnssIntegrity({
+15 -4
View File
@@ -6,8 +6,15 @@ import {
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
/** Wire WFIGS fire perimeters into the application catalog. */
export function createApplicationFirePerimeters(options) {
/**
* Wire fire perimeters into the application catalog. `inciweb: false`
* creates no InciWeb sources, so the cards carry no links and InciWeb is
* never asked.
*/
export function createApplicationFirePerimeters({
inciweb = true,
...options
} = {}) {
return createFirePerimetersLayer({
overlayHost: {
setEntries: overlays.setOverlayEntries,
@@ -15,8 +22,12 @@ export function createApplicationFirePerimeters(options) {
clearSource: overlays.clearOverlaySource,
hitTest: overlays.hitTestWorldOverlay,
},
inciwebSource: createInciwebIndexSource(),
inciwebPublications: createInciwebPublicationSource(),
...(inciweb === false
? {}
: {
inciwebSource: createInciwebIndexSource(),
inciwebPublications: createInciwebPublicationSource(),
}),
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
picking,
...options,
+51
View File
@@ -0,0 +1,51 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createApplicationFirePerimeters } from './perimeters.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
const ring = [
[-108.1, 35.2],
[-108.0, 35.2],
[-108.0, 35.3],
[-108.1, 35.2],
];
const source = {
getSnapshot: async () => ({
at: null,
fetchedAt: null,
stale: false,
revision: 'r',
note: null,
fires: [{ id: 'f', name: 'Fixture', anchor: { lon: -108.05, lat: 35.25 } }],
pieces: [{ fireId: 'f', born: null, polygons: [[ring]], outline: [ring] }],
}),
};
for (const inciweb of [true, false]) {
test(`inciweb: ${inciweb} ${inciweb ? 'asks' : 'never asks'} InciWeb`, async (t) => {
const requested = [];
t.mock.method(globalThis, 'fetch', async (url) => {
requested.push(String(url));
return Response.json([]);
});
const viewer = { scene: { pick: () => null } };
bindFakeDraw(viewer);
const input = fakeInput(viewer);
t.after(() => input.destroy());
const layer = createApplicationFirePerimeters({
source,
inciweb,
inputFor: () => input.input,
});
layer.init(viewer);
layer.enable(viewer);
assert.equal(await layer.update(viewer), true);
await new Promise(setImmediate);
assert.deepEqual(
requested.filter((url) => url.includes('inciweb')),
inciweb ? ['/api/fire-perimeters/inciweb/index'] : [],
);
layer.destroy(viewer);
});
}
-3
View File
@@ -46,9 +46,6 @@ test('hosted account limits and service failures name their own reason', () => {
assert.equal(failure(429, 'budget'), 'TomTom daily budget reached');
assert.equal(failure(503, 'no_key'), 'TomTom key unavailable');
assert.equal(failure(503, null), 'TomTom key unavailable');
// TomTom refused the key itself: not the generic HTTP 403 line.
assert.equal(failure(403, 'key_rejected'), 'TomTom key rejected');
assert.equal(failure(403, null), 'TomTom flow error (HTTP 403)');
assert.equal(
failure(503, 'USAGE_UNAVAILABLE'),
'Traffic service unavailable',
+3 -2
View File
@@ -1110,10 +1110,11 @@ test('the voice TOOL SCHEMA matches the pinned contract — the mission mapping
// Pistes extend the generated layer enums and alias hint; voice geometry
// adds the analyst area scopes and the osm-places layer.
// control_cockpit states the own-layer entry rule (Contacts not required).
assert.equal(block.length, 31372, 'serialized tool schema length drifted');
// Fire Perimeters queries add lastGrowthTime.
assert.equal(block.length, 31387, 'serialized tool schema length drifted');
assert.equal(
crypto.createHash('sha256').update(block).digest('hex'),
'7f593e78c232db972b04441f830b6a60f93916a6e5bc5a68eca7422cd1035508',
'909bc8924e5ad6adf599406d462d325a703d18993176d96498cbb057240a58b6',
'the first-run missions must ride EXISTING tools: no schema edit, no cache bust',
);
const instructions = fs.readFileSync(
+8 -7
View File
@@ -1851,11 +1851,6 @@
"Unnamed incident": "حادث بلا اسم",
"Open {title} on InciWeb": "فتح {title} على InciWeb",
"Perimeter source unavailable": "مصدر محيطات الحرائق غير متاح",
"Not contained or unknown": "بلا احتواء أو غير معروف",
"Under 50% contained": "الاحتواء: أقل من 50%",
"50–99% contained": "الاحتواء: 50–99%",
"Fully contained": "احتواء كامل",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "يبيّن اللون نسبة الاحتواء المُبلَّغ عنها. المحيطات مبسّطة إلى نحو 100 م.",
"Malformed perimeter snapshot": "لقطة المحيطات مشوّهة",
"radio tag|All": "الكل",
"Directory refresh degraded; showing the previous station catalog.": "تحديث الدليل متدهور؛ يُعرض فهرس المحطات السابق.",
@@ -1983,7 +1978,6 @@
"Moving dots colored by live flow": "نقاط متحركة ملوّنة حسب التدفق المباشر",
"Moving dots": "نقاط متحركة",
"TomTom key unavailable": "مفتاح TomTom غير متاح",
"TomTom key rejected": "تم رفض مفتاح TomTom",
"TomTom daily budget reached": "بلغت الحصة اليومية لـ TomTom",
"Monthly traffic allowance used": "تم استهلاك حصة حركة المرور الشهرية",
"Traffic rate limit reached": "تم بلوغ حد طلبات حركة المرور",
@@ -4850,5 +4844,12 @@
"Telemetry reads while the model is on screen": "تُقرأ القياسات أثناء ظهور النموذج على الشاشة",
"Connecting to telemetry…": "جارٍ الاتصال بالقياسات…",
"{seconds} s": "{seconds} ث",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "الألواح والمشعّات وأحد الأطباق تتبع القياسات الحية من ناسا. الطبق الآخر ثابت، والأذرع تتحرك للتوضيح فقط."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "الألواح والمشعّات وأحد الأطباق تتبع القياسات الحية من ناسا. الطبق الآخر ثابت، والأذرع تتحرك للتوضيح فقط.",
"last growth {age} ago": "آخر توسّع قبل {age}",
"New in 6 hours": "جديد خلال آخر 6 ساعات",
"6–24 hours": "6–24 ساعة",
"1–3 days": "1–3 أيام",
"Older or unknown": "أقدم أو غير معروف",
"Colour shows how long ago each area was mapped.": "يبيّن اللون منذ متى رُسمت كل منطقة.",
"Perimeters are simplified to about 100 m.": "المحيطات مبسّطة إلى نحو 100 م."
}
+8 -7
View File
@@ -1733,11 +1733,6 @@
"Unnamed incident": "Unbenannter Einsatz",
"Open {title} on InciWeb": "{title} auf InciWeb öffnen",
"Perimeter source unavailable": "Quelle der Brandgrenzen nicht verfügbar",
"Not contained or unknown": "Nicht eingedämmt oder unbekannt",
"Under 50% contained": "Unter 50 % eingedämmt",
"50–99% contained": "50–99 % eingedämmt",
"Fully contained": "Vollständig eingedämmt",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Die Farbe zeigt die gemeldete Eindämmung. Brandgrenzen sind auf etwa 100 m vereinfacht.",
"Malformed perimeter snapshot": "Fehlerhafter Brandgrenzen-Snapshot",
"radio tag|All": "Alle",
"Directory refresh degraded; showing the previous station catalog.": "Verzeichnisaktualisierung eingeschränkt; der vorherige Senderkatalog wird gezeigt.",
@@ -1860,7 +1855,6 @@
"Moving dots colored by live flow": "Bewegte Punkte nach Live-Verkehrsfluss gefärbt",
"Moving dots": "Bewegte Punkte",
"TomTom key unavailable": "TomTom-Schlüssel nicht verfügbar",
"TomTom key rejected": "TomTom-Schlüssel abgelehnt",
"TomTom daily budget reached": "TomTom-Tagesbudget erreicht",
"Monthly traffic allowance used": "Monatliches Verkehrskontingent aufgebraucht",
"Traffic rate limit reached": "Verkehrs-Anfragelimit erreicht",
@@ -4426,5 +4420,12 @@
"Telemetry reads while the model is on screen": "Telemetrie wird gelesen, solange das Modell zu sehen ist",
"Connecting to telemetry…": "Verbindung zur Telemetrie…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Solarflügel, Radiatoren und eine Antenne folgen der Live-Telemetrie der NASA. Die andere Antenne steht still und die Arme bewegen sich zur Veranschaulichung."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Solarflügel, Radiatoren und eine Antenne folgen der Live-Telemetrie der NASA. Die andere Antenne steht still und die Arme bewegen sich zur Veranschaulichung.",
"last growth {age} ago": "zuletzt gewachsen vor {age}",
"New in 6 hours": "Neu in den letzten 6 Stunden",
"6–24 hours": "6–24 Stunden",
"1–3 days": "1–3 Tage",
"Older or unknown": "Älter oder unbekannt",
"Colour shows how long ago each area was mapped.": "Die Farbe zeigt, wie lange die Kartierung jeder Fläche her ist.",
"Perimeters are simplified to about 100 m.": "Brandgrenzen sind auf etwa 100 m vereinfacht."
}
+8 -7
View File
@@ -1417,11 +1417,6 @@
"Routing unavailable — no response from the routing service": "Rutas no disponibles — sin respuesta del servicio de rutas",
"Routing unavailable": "Rutas no disponibles",
"Fire · FRP {frp} MW": "Incendio · FRP {frp} MW",
"Not contained or unknown": "Sin contener o desconocido",
"Under 50% contained": "Contenido por debajo del 50%",
"50–99% contained": "Contenido al 50–99%",
"Fully contained": "Totalmente contenido",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "El color indica la contención notificada. Los perímetros se simplifican a unos 100 m.",
"MORE DETAIL · 30 m": "MÁS DETALLE · 30 m",
"Sentinel-2 and Landsat via HLS, 30 m, every 2–6 days": "Sentinel‑2 y Landsat vía HLS, 30 m, cada 2–6 días",
"DAILY OVERVIEW · 250 m": "VISTA GENERAL DIARIA · 250 m",
@@ -2463,7 +2458,6 @@
"Military area": "Zona militar",
"SIMULATED — {reason}": "SIMULADO — {reason}",
"TomTom key unavailable": "Clave de TomTom no disponible",
"TomTom key rejected": "Clave de TomTom rechazada",
"TomTom daily budget reached": "Se alcanzó el límite diario de TomTom",
"Monthly traffic allowance used": "Cupo mensual de tráfico agotado",
"Traffic rate limit reached": "Límite de peticiones de tráfico alcanzado",
@@ -4532,5 +4526,12 @@
"Telemetry reads while the model is on screen": "La telemetría se lee mientras el modelo está en pantalla",
"Connecting to telemetry…": "Conectando con la telemetría…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Los paneles, los radiadores y una antena siguen la telemetría en vivo de la NASA. La otra antena permanece quieta y los brazos se mueven a modo de ilustración."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Los paneles, los radiadores y una antena siguen la telemetría en vivo de la NASA. La otra antena permanece quieta y los brazos se mueven a modo de ilustración.",
"last growth {age} ago": "último crecimiento hace {age}",
"New in 6 hours": "Nuevo en las últimas 6 horas",
"6–24 hours": "6–24 horas",
"1–3 days": "1–3 días",
"Older or unknown": "Más antiguo o desconocido",
"Colour shows how long ago each area was mapped.": "El color indica hace cuánto se cartografió cada zona.",
"Perimeters are simplified to about 100 m.": "Los perímetros se simplifican a unos 100 m."
}
+8 -7
View File
@@ -1076,11 +1076,6 @@
"Unnamed incident": "Incident sans nom",
"Open {title} on InciWeb": "Ouvrir {title} sur InciWeb",
"Perimeter source unavailable": "Source des périmètres indisponible",
"Not contained or unknown": "Non circonscrit ou inconnu",
"Under 50% contained": "Circonscrit à moins de 50 %",
"50–99% contained": "Circonscrit à 50–99 %",
"Fully contained": "Entièrement circonscrit",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "La couleur indique la part du périmètre déclarée circonscrite. Les périmètres sont simplifiés à environ 100 m.",
"Malformed perimeter snapshot": "Instantané des périmètres mal formé",
"radio tag|All": "Toutes",
"News": "Actualités",
@@ -1247,7 +1242,6 @@
"Moving dots colored by live flow": "Points mobiles colorés selon le trafic en direct",
"Moving dots": "Points mobiles",
"TomTom key unavailable": "Clé TomTom indisponible",
"TomTom key rejected": "Clé TomTom refusée",
"TomTom daily budget reached": "Quota quotidien TomTom atteint",
"Monthly traffic allowance used": "Quota mensuel de trafic épuisé",
"Traffic rate limit reached": "Limite de requêtes de trafic atteinte",
@@ -4532,5 +4526,12 @@
"Telemetry reads while the model is on screen": "La télémétrie est lue tant que le modèle est à l'écran",
"Connecting to telemetry…": "Connexion à la télémétrie…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Les panneaux, les radiateurs et une antenne suivent la télémétrie en direct de la NASA. L'autre antenne reste immobile et les bras bougent à titre d'illustration."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Les panneaux, les radiateurs et une antenne suivent la télémétrie en direct de la NASA. L'autre antenne reste immobile et les bras bougent à titre d'illustration.",
"last growth {age} ago": "dernière progression il y a {age}",
"New in 6 hours": "Nouveau, moins de 6 heures",
"6–24 hours": "6–24 heures",
"1–3 days": "1–3 jours",
"Older or unknown": "Plus ancien ou inconnu",
"Colour shows how long ago each area was mapped.": "La couleur indique depuis combien de temps chaque zone a été cartographiée.",
"Perimeters are simplified to about 100 m.": "Les périmètres sont simplifiés à environ 100 m."
}
+8 -7
View File
@@ -925,11 +925,6 @@
"Unnamed incident": "אירוע ללא שם",
"Open {title} on InciWeb": "פתיחת {title} ב-InciWeb",
"Perimeter source unavailable": "מקור ההיקף אינו זמין",
"Not contained or unknown": "ללא הכלה או לא ידוע",
"Under 50% contained": "הכלה מתחת ל-50%",
"50–99% contained": "הכלה 50–99%",
"Fully contained": "הכלה מלאה",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "הצבע מציג את ההכלה שדווחה. ההיקפים מפושטים לכ-100 מ׳.",
"Malformed perimeter snapshot": "תמונת מצב היקף פגומה",
"radio tag|All": "הכול",
"News": "חדשות",
@@ -1092,7 +1087,6 @@
"TomTom roads first; OpenStreetMap fills the rest, simulated (needs a TomTom key)": "כבישי TomTom קודם; OpenStreetMap משלים את היתר, מדומים (דורש מפתח TomTom)",
"Hybrid": "היברידי",
"TomTom key unavailable": "מפתח TomTom אינו זמין",
"TomTom key rejected": "מפתח TomTom נדחה",
"TomTom daily budget reached": "תקציב TomTom היומי אזל",
"TomTom upstream unreachable": "שירות TomTom אינו נגיש",
"TomTom flow unavailable": "זרימת TomTom אינה זמינה",
@@ -4532,5 +4526,12 @@
"Telemetry reads while the model is on screen": "הטלמטריה נקראת כל עוד הדגם מוצג על המסך",
"Connecting to telemetry…": "מתחבר לטלמטריה…",
"{seconds} s": "{seconds} שנ׳",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "הלוחות, הרדיאטורים וצלחת אחת עוקבים אחר הטלמטריה החיה של נאס״א. הצלחת השנייה נשארת במקומה והזרועות נעות להמחשה בלבד."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "הלוחות, הרדיאטורים וצלחת אחת עוקבים אחר הטלמטריה החיה של נאס״א. הצלחת השנייה נשארת במקומה והזרועות נעות להמחשה בלבד.",
"last growth {age} ago": "התפשטות אחרונה לפני {age}",
"New in 6 hours": "חדש ב-6 השעות האחרונות",
"6–24 hours": "6–24 שעות",
"1–3 days": "1–3 ימים",
"Older or unknown": "ישן יותר או לא ידוע",
"Colour shows how long ago each area was mapped.": "הצבע מציג לפני כמה זמן מופה כל אזור.",
"Perimeters are simplified to about 100 m.": "ההיקפים מפושטים לכ-100 מ׳."
}
+8 -7
View File
@@ -1076,11 +1076,6 @@
"Unnamed incident": "Incendio senza nome",
"Open {title} on InciWeb": "Apri {title} su InciWeb",
"Perimeter source unavailable": "Fonte dei perimetri non disponibile",
"Not contained or unknown": "Non contenuto o dato non disponibile",
"Under 50% contained": "Contenuto a meno del 50%",
"50–99% contained": "Contenuto al 50–99%",
"Fully contained": "Completamente contenuto",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Il colore indica il contenimento riportato. I perimetri sono semplificati a circa 100 m.",
"Malformed perimeter snapshot": "Snapshot dei perimetri non valido",
"radio tag|All": "Tutti",
"News": "Notizie",
@@ -1247,7 +1242,6 @@
"Moving dots colored by live flow": "Punti in movimento colorati in base al flusso live",
"Moving dots": "Punti in movimento",
"TomTom key unavailable": "Chiave TomTom non disponibile",
"TomTom key rejected": "Chiave TomTom rifiutata",
"TomTom daily budget reached": "Budget giornaliero TomTom esaurito",
"Monthly traffic allowance used": "Quota mensile del traffico esaurita",
"Traffic rate limit reached": "Limite di richieste del traffico raggiunto",
@@ -4532,5 +4526,12 @@
"Telemetry reads while the model is on screen": "La telemetria viene letta finché il modello è sullo schermo",
"Connecting to telemetry…": "Connessione alla telemetria…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Pannelli, radiatori e un'antenna seguono la telemetria in diretta della NASA. L'altra antenna resta ferma e i bracci si muovono a scopo illustrativo."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Pannelli, radiatori e un'antenna seguono la telemetria in diretta della NASA. L'altra antenna resta ferma e i bracci si muovono a scopo illustrativo.",
"last growth {age} ago": "ultima espansione {age} fa",
"New in 6 hours": "Nuovo nelle ultime 6 ore",
"6–24 hours": "6–24 ore",
"1–3 days": "1–3 giorni",
"Older or unknown": "Più vecchio o sconosciuto",
"Colour shows how long ago each area was mapped.": "Il colore indica da quanto tempo ogni area è stata mappata.",
"Perimeters are simplified to about 100 m.": "I perimetri sono semplificati a circa 100 m."
}
+8 -7
View File
@@ -1030,11 +1030,6 @@
"Unnamed incident": "名称未設定の火災",
"Open {title} on InciWeb": "InciWebで{title}を開く",
"Perimeter source unavailable": "延焼範囲のソースを利用できません",
"Not contained or unknown": "封じ込め率0%または不明",
"Under 50% contained": "封じ込め率50%未満",
"50–99% contained": "封じ込め率50–99%",
"Fully contained": "封じ込め率100%",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "色は報告された封じ込め率を示します。延焼範囲の輪郭は約100 mの精度で簡略化されています。",
"Malformed perimeter snapshot": "延焼範囲スナップショットの形式が不正です",
"radio tag|All": "すべて",
"News": "ニュース",
@@ -1201,7 +1196,6 @@
"Moving dots colored by live flow": "ライブの交通流で色分けした移動ドット",
"Moving dots": "移動ドット",
"TomTom key unavailable": "TomTomキーを利用できません",
"TomTom key rejected": "TomTomキーが拒否されました",
"TomTom daily budget reached": "TomTomの1日の上限に達しました",
"Monthly traffic allowance used": "今月の交通情報の上限に達しました",
"Traffic rate limit reached": "交通情報のリクエスト上限に達しました",
@@ -4320,5 +4314,12 @@
"Telemetry reads while the model is on screen": "テレメトリはモデルが画面にある間に読み取られます",
"Connecting to telemetry…": "テレメトリに接続中…",
"{seconds} s": "{seconds} 秒",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽電池パネル、ラジエーター、アンテナの1基はNASAのライブテレメトリに従います。もう1基のアンテナは動かず、アームは説明用にゆっくり動きます。"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽電池パネル、ラジエーター、アンテナの1基はNASAのライブテレメトリに従います。もう1基のアンテナは動かず、アームは説明用にゆっくり動きます。",
"last growth {age} ago": "{age}前に最終拡大",
"New in 6 hours": "6時間以内の新規",
"6–24 hours": "6–24時間",
"1–3 days": "1–3日",
"Older or unknown": "それ以前または不明",
"Colour shows how long ago each area was mapped.": "色は各範囲が地図化されてからの経過時間を示します。",
"Perimeters are simplified to about 100 m.": "延焼範囲の輪郭は約100 mの精度で簡略化されています。"
}
+8 -7
View File
@@ -1074,11 +1074,6 @@
"Unnamed incident": "Sem nome",
"Open {title} on InciWeb": "Abrir {title} no InciWeb",
"Perimeter source unavailable": "Fonte de perímetros indisponível",
"Not contained or unknown": "Não contido ou desconhecido",
"Under 50% contained": "Menos de 50% contido",
"50–99% contained": "50–99% contido",
"Fully contained": "Totalmente contido",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "A cor indica a contenção informada. Os perímetros são simplificados para cerca de 100 m.",
"Malformed perimeter snapshot": "Snapshot de perímetros malformado",
"radio tag|All": "Todas",
"News": "Notícias",
@@ -1245,7 +1240,6 @@
"Moving dots colored by live flow": "Pontos em movimento coloridos pelo fluxo ao vivo",
"Moving dots": "Pontos em movimento",
"TomTom key unavailable": "Chave do TomTom indisponível",
"TomTom key rejected": "Chave do TomTom recusada",
"TomTom daily budget reached": "Limite diário do TomTom atingido",
"Monthly traffic allowance used": "Cota mensal de trânsito esgotada",
"Traffic rate limit reached": "Trânsito: limite de requisições atingido",
@@ -4532,5 +4526,12 @@
"Telemetry reads while the model is on screen": "A telemetria é lida enquanto o modelo está no ecrã",
"Connecting to telemetry…": "A ligar à telemetria…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Painéis, radiadores e uma antena seguem a telemetria ao vivo da NASA. A outra antena fica parada e os braços se movem de forma ilustrativa."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Painéis, radiadores e uma antena seguem a telemetria ao vivo da NASA. A outra antena fica parada e os braços se movem de forma ilustrativa.",
"last growth {age} ago": "último crescimento há {age}",
"New in 6 hours": "Novo nas últimas 6 horas",
"6–24 hours": "6–24 horas",
"1–3 days": "1–3 dias",
"Older or unknown": "Mais antigo ou desconhecido",
"Colour shows how long ago each area was mapped.": "A cor indica há quanto tempo cada área foi mapeada.",
"Perimeters are simplified to about 100 m.": "Os perímetros são simplificados para cerca de 100 m."
}
+8 -7
View File
@@ -1445,11 +1445,6 @@
"Routing unavailable — no response from the routing service": "Построение маршрута недоступно — сервис маршрутизации не отвечает",
"Routing unavailable": "Построение маршрута недоступно",
"Fire · FRP {frp} MW": "Пожар · FRP {frp} МВт",
"Not contained or unknown": "Не локализован или неизвестно",
"Under 50% contained": "Локализован менее чем на 50%",
"50–99% contained": "Локализован на 50–99%",
"Fully contained": "Полностью локализован",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Цвет показывает заявленную степень локализации. Контуры упрощены примерно до 100 м.",
"MORE DETAIL · 30 m": "БОЛЬШЕ ДЕТАЛЕЙ · 30 м",
"Sentinel-2 and Landsat via HLS, 30 m, every 2–6 days": "Sentinel‑2 и Landsat через HLS, 30 м, каждые 2–6 дней",
"DAILY OVERVIEW · 250 m": "ЕЖЕДНЕВНЫЙ ОБЗОР · 250 м",
@@ -2512,7 +2507,6 @@
"Military area": "Военная зона",
"SIMULATED — {reason}": "СИМУЛЯЦИЯ — {reason}",
"TomTom key unavailable": "Ключ TomTom недоступен",
"TomTom key rejected": "Ключ TomTom отклонён",
"TomTom daily budget reached": "Исчерпан дневной лимит TomTom",
"Monthly traffic allowance used": "Месячный лимит данных о трафике исчерпан",
"Traffic rate limit reached": "Достигнут лимит запросов данных о трафике",
@@ -4638,5 +4632,12 @@
"Telemetry reads while the model is on screen": "Телеметрия читается, пока модель на экране",
"Connecting to telemetry…": "Подключение к телеметрии…",
"{seconds} s": "{seconds} с",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панели, радиаторы и одна антенна следуют телеметрии NASA в реальном времени. Вторая антенна неподвижна, а манипуляторы движутся для иллюстрации."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панели, радиаторы и одна антенна следуют телеметрии NASA в реальном времени. Вторая антенна неподвижна, а манипуляторы движутся для иллюстрации.",
"last growth {age} ago": "последний рост {age} назад",
"New in 6 hours": "Новое за 6 часов",
"6–24 hours": "6–24 часа",
"1–3 days": "1–3 дня",
"Older or unknown": "Старше или неизвестно",
"Colour shows how long ago each area was mapped.": "Цвет показывает, как давно нанесён каждый участок.",
"Perimeters are simplified to about 100 m.": "Контуры упрощены примерно до 100 м."
}
+8 -7
View File
@@ -1649,11 +1649,6 @@
"Unnamed incident": "Namnlös händelse",
"Open {title} on InciWeb": "Öppna {title} på InciWeb",
"Perimeter source unavailable": "Källa för brandgränser otillgänglig",
"Not contained or unknown": "Inte under kontroll eller okänt",
"Under 50% contained": "Mindre än 50 % under kontroll",
"50–99% contained": "50–99 % under kontroll",
"Fully contained": "Helt under kontroll",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Färgen visar rapporterad kontrollgrad. Brandgränserna är förenklade till cirka 100 m.",
"Malformed perimeter snapshot": "Felformaterad ögonblicksbild av brandgränser",
"radio tag|All": "Alla",
"Directory refresh degraded; showing the previous station catalog.": "Uppdateringen av katalogen är begränsad; visar den tidigare stationskatalogen.",
@@ -1776,7 +1771,6 @@
"Moving dots colored by live flow": "Rörliga punkter färgade efter trafikflödet live",
"Moving dots": "Rörliga punkter",
"TomTom key unavailable": "TomTom-nyckel otillgänglig",
"TomTom key rejected": "TomTom-nyckeln avvisades",
"TomTom daily budget reached": "TomTom-dagsbudgeten är förbrukad",
"Monthly traffic allowance used": "Månadens trafikkvot är förbrukad",
"Traffic rate limit reached": "Trafiktjänsten har nått gränsen för förfrågningar",
@@ -4426,5 +4420,12 @@
"Telemetry reads while the model is on screen": "Telemetri läses medan modellen syns på skärmen",
"Connecting to telemetry…": "Ansluter till telemetri…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Paneler, radiatorer och en antenn följer NASA:s telemetri i realtid. Den andra antennen står stilla och armarna rör sig som illustration."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Paneler, radiatorer och en antenn följer NASA:s telemetri i realtid. Den andra antennen står stilla och armarna rör sig som illustration.",
"last growth {age} ago": "senaste tillväxt för {age} sedan",
"New in 6 hours": "Nytt de senaste 6 timmarna",
"6–24 hours": "6–24 timmar",
"1–3 days": "1–3 dagar",
"Older or unknown": "Äldre eller okänt",
"Colour shows how long ago each area was mapped.": "Färgen visar hur länge sedan varje område kartlades.",
"Perimeters are simplified to about 100 m.": "Brandgränserna är förenklade till cirka 100 m."
}
+8 -7
View File
@@ -1098,11 +1098,6 @@
"Unnamed incident": "Без назви",
"Open {title} on InciWeb": "Відкрити {title} в InciWeb",
"Perimeter source unavailable": "Джерело контурів пожеж недоступне",
"Not contained or unknown": "Не локалізовано або невідомо",
"Under 50% contained": "Локалізовано менш ніж на 50%",
"50–99% contained": "Локалізовано на 50–99%",
"Fully contained": "Повністю локалізовано",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Колір показує заявлений ступінь локалізації. Контури спрощено приблизно до 100 м.",
"Malformed perimeter snapshot": "Некоректний знімок контурів пожеж",
"radio tag|All": "Усі",
"News": "Новини",
@@ -1269,7 +1264,6 @@
"Moving dots colored by live flow": "Рухомі точки, забарвлені за потоком онлайн",
"Moving dots": "Рухомі точки",
"TomTom key unavailable": "Ключ TomTom недоступний",
"TomTom key rejected": "Ключ TomTom відхилено",
"TomTom daily budget reached": "Вичерпано денний ліміт TomTom",
"Monthly traffic allowance used": "Місячний ліміт даних про дорожній рух вичерпано",
"Traffic rate limit reached": "Перевищено ліміт запитів до сервісу руху",
@@ -4638,5 +4632,12 @@
"Telemetry reads while the model is on screen": "Телеметрія читається, поки модель на екрані",
"Connecting to telemetry…": "Підключення до телеметрії…",
"{seconds} s": "{seconds} с",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панелі, радіатори й одна антена слідують телеметрії NASA в реальному часі. Друга антена нерухома, а маніпулятори рухаються для ілюстрації."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панелі, радіатори й одна антена слідують телеметрії NASA в реальному часі. Друга антена нерухома, а маніпулятори рухаються для ілюстрації.",
"last growth {age} ago": "останнє зростання {age} тому",
"New in 6 hours": "Нове за 6 годин",
"6–24 hours": "6–24 години",
"1–3 days": "1–3 дні",
"Older or unknown": "Старше або невідомо",
"Colour shows how long ago each area was mapped.": "Колір показує, як давно нанесено кожну ділянку.",
"Perimeters are simplified to about 100 m.": "Контури спрощено приблизно до 100 м."
}
+8 -7
View File
@@ -1010,11 +1010,6 @@
"Unnamed incident": "未命名火情",
"Open {title} on InciWeb": "在 InciWeb 上打开 {title}",
"Perimeter source unavailable": "周界数据源不可用",
"Not contained or unknown": "未控制或未知",
"Under 50% contained": "控制低于 50%",
"50–99% contained": "控制 50–99%",
"Fully contained": "已全部控制",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "颜色表示报告的控制比例。周界简化至约 100 m。",
"Malformed perimeter snapshot": "周界快照格式错误",
"radio tag|All": "全部",
"News": "新闻",
@@ -1178,7 +1173,6 @@
"Moving dots colored by live flow": "按实时路况着色的移动圆点",
"Moving dots": "移动圆点",
"TomTom key unavailable": "TomTom 密钥不可用",
"TomTom key rejected": "TomTom 密钥被拒绝",
"TomTom daily budget reached": "已达 TomTom 每日配额",
"Monthly traffic allowance used": "本月交通数据配额已用完",
"Traffic rate limit reached": "已达到交通数据请求频率上限",
@@ -4320,5 +4314,12 @@
"Telemetry reads while the model is on screen": "模型显示在屏幕上时读取遥测",
"Connecting to telemetry…": "正在连接遥测…",
"{seconds} s": "{seconds} 秒",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太阳能板、散热器和一副天线依据 NASA 的实时遥测转动。另一副天线保持不动,机械臂仅作演示性摆动。"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太阳能板、散热器和一副天线依据 NASA 的实时遥测转动。另一副天线保持不动,机械臂仅作演示性摆动。",
"last growth {age} ago": "最近一次扩展于 {age}前",
"New in 6 hours": "6 小时内新增",
"6–24 hours": "6–24 小时",
"1–3 days": "1–3 天",
"Older or unknown": "更早或未知",
"Colour shows how long ago each area was mapped.": "颜色表示各区域测绘至今的时间。",
"Perimeters are simplified to about 100 m.": "周界简化至约 100 m。"
}
+8 -7
View File
@@ -1010,11 +1010,6 @@
"Unnamed incident": "未命名火情",
"Open {title} on InciWeb": "在 InciWeb 上打開 {title}",
"Perimeter source unavailable": "周界數據源不可用",
"Not contained or unknown": "未控制或未知",
"Under 50% contained": "控制低於 50%",
"50–99% contained": "控制 50–99%",
"Fully contained": "已全部控制",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "顏色表示報告的控制比例。周界簡化至約 100 m。",
"Malformed perimeter snapshot": "周界快照格式錯誤",
"radio tag|All": "全部",
"News": "新聞",
@@ -1178,7 +1173,6 @@
"Moving dots colored by live flow": "按實時路況著色的移動圓點",
"Moving dots": "移動圓點",
"TomTom key unavailable": "TomTom 密鑰不可用",
"TomTom key rejected": "TomTom 密鑰被拒絕",
"TomTom daily budget reached": "已達 TomTom 每日配額",
"Monthly traffic allowance used": "本月交通數據配額已用完",
"Traffic rate limit reached": "已達到交通數據請求頻率上限",
@@ -4320,5 +4314,12 @@
"Telemetry reads while the model is on screen": "模型顯示在屏幕上時讀取遙測",
"Connecting to telemetry…": "正在連接遙測…",
"{seconds} s": "{seconds} 秒",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽能板、散熱器和一副天線依據 NASA 的實時遙測轉動。另一副天線保持不動,機械臂僅作演示性擺動。"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽能板、散熱器和一副天線依據 NASA 的實時遙測轉動。另一副天線保持不動,機械臂僅作演示性擺動。",
"last growth {age} ago": "最近一次擴展於 {age}前",
"New in 6 hours": "6 小時內新增",
"6–24 hours": "6–24 小時",
"1–3 days": "1–3 天",
"Older or unknown": "更早或未知",
"Colour shows how long ago each area was mapped.": "顏色表示各區域測繪至今的時間。",
"Perimeters are simplified to about 100 m.": "周界簡化至約 100 m。"
}
+6 -3
View File
@@ -8,13 +8,14 @@ import { buildIncidentCard } from './cards.js';
const now = Date.UTC(2026, 9, 14);
const row = {
stableId: 'x',
id: 'x',
name: 'Lake',
acres: 1200,
containedPct: 40,
state: 'CA',
discoveredTime: now - 2 * 3600e3,
updatedTime: now - 3600e3,
lastGrowthTime: now - 3 * 3600e3,
cause: 'Human',
behavior: 'Moderate',
complexity: 'Type 3 Incident',
@@ -33,6 +34,7 @@ test('en: the fire card keeps its English wording', () => {
'part of North Complex',
'Human cause · Moderate · Type 3 Incident',
'1,500 personnel · Plumas County · $4.2M to date',
'last growth 3h ago',
'discovered 2h ago · updated 1h ago',
'InciWeb ↗ · click card to open',
]);
@@ -44,8 +46,8 @@ for (const locale of ['es', 'ru']) {
setLocale(locale);
try {
assert.notEqual(
t('Fully contained'),
'Fully contained',
t('Older or unknown'),
'Older or unknown',
'legend is translated',
);
const card = buildIncidentCard(row, now, {
@@ -60,6 +62,7 @@ for (const locale of ['es', 'ru']) {
'contained',
'discovered',
'updated',
'last growth',
'part of',
'cause',
'personnel',
+11 -52
View File
@@ -11,55 +11,6 @@ export function containmentAccent(containedPct) {
return '#8bc34a';
}
/** Shoelace area along short longitude edges (degree², relative sizes only). */
function ringArea(ring) {
let sum = 0;
let [x1, y1] = ring[0];
for (let i = 1; i < ring.length; i++) {
let delta = ring[i][0] - ring[i - 1][0];
if (delta > 180) delta -= 360;
else if (delta < -180) delta += 360;
const x2 = x1 + delta;
const y2 = ring[i][1];
sum += x1 * y2 - x2 * y1;
x1 = x2;
y1 = y2;
}
return Math.abs(sum / 2);
}
/**
* Anchor point for the incident card: the vertex mean of the largest polygon's
* outer ring, with circular longitude. Callers own the Cartesian conversion.
* @param {Array<Array<Array<[number, number]>>>} polygons - Normalized rows' polygons.
* @returns {{lon: number, lat: number}}
*/
export function perimeterAnchorDegrees(polygons) {
let best = null;
let bestArea = -1;
for (const rings of polygons) {
const outer = rings[0];
const area = ringArea(outer);
if (area > bestArea) {
bestArea = area;
best = outer;
}
}
// Vertex mean over the closed ring (first == last point dropped): perimeters
// are compact enough that this stays inside or near the polygon.
let sinLon = 0;
let cosLon = 0;
let lat = 0;
const count = best.length - 1;
const toRad = Math.PI / 180;
for (let i = 0; i < count; i++) {
sinLon += Math.sin(best[i][0] * toRad);
cosLon += Math.cos(best[i][0] * toRad);
lat += best[i][1];
}
return { lon: Math.atan2(sinLon, cosLon) / toRad, lat: lat / count };
}
/**
* Compact USD in the UI language: en "$85K / $4.2M / $1.3B", ru "4,2 млн $",
* es "4,2 M$". Null under $1,000.
@@ -149,8 +100,9 @@ function formatAge(deltaMs) {
/**
* Build the overlay-host entry for one selected incident. The caller supplies
* `position` (Cartesian) separately — this model stays JSON-safe for tests.
* @param {Object} row - Normalized perimeter row (see records.js).
* @param {number} nowMs - Current epoch milliseconds.
* @param {Object} row - A snapshot fire (see records.js).
* @param {number} nowMs - The moment shown, epoch milliseconds: the snapshot's
* `at`, or now.
* @param {{link: ?string}} [extras] - Optional InciWeb page for this incident.
* @returns {Object} World-overlay entry without `position`.
*/
@@ -194,6 +146,12 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
if (cost) response.push(t('{cost} to date', { cost }));
}
const growth = formatAge(nowMs - row.lastGrowthTime);
const lastGrowth =
row.lastGrowthTime != null && growth
? t('last growth {age} ago', { age: growth })
: null;
const ages = [];
const discovered = formatAge(nowMs - row.discoveredTime);
if (row.discoveredTime != null && discovered)
@@ -209,6 +167,7 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
);
if (situation.length) details.push(situation.join(' · '));
if (response.length) details.push(response.join(' · '));
if (lastGrowth) details.push(lastGrowth);
if (ages.length) details.push(ages.join(' · '));
if (link) details.push(t('InciWeb ↗ · click card to open'));
@@ -216,7 +175,7 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
name: row.name || t('Unnamed incident'),
});
return {
id: `fire-perimeter-card:${row.stableId}`,
id: `fire-perimeter-card:${row.id}`,
// `selected` picks the paint lane and collision protection; an explicit
// paintLane would override it in the host's lane resolver.
selected: true,
+32 -10
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { perimeterAnchorDegrees, buildIncidentCard } from './cards.js';
import { buildIncidentCard } from './cards.js';
import { perimeterAnchorDegrees } from './records.js';
const square = [
[-108.2, 35.0],
@@ -93,7 +94,7 @@ test('a full incident row renders name, size, containment, and ages', () => {
const now = 1758000000000;
const card = buildIncidentCard(
{
stableId: '2026-NMGNF-000123',
id: '2026-NMGNF-000123',
name: 'Frijoles',
acres: 15956.4,
containedPct: 74,
@@ -101,6 +102,7 @@ test('a full incident row renders name, size, containment, and ages', () => {
category: 'WF',
discoveredTime: now - 36 * 3600000,
updatedTime: now - 2 * 3600000,
lastGrowthTime: now - 5 * 3600000,
cause: 'Natural',
behavior: 'Active',
personnel: 380,
@@ -116,6 +118,7 @@ test('a full incident row renders name, size, containment, and ages', () => {
'15,956 ac · 74% contained · US-NM',
'Natural cause · Active · Type 3 Incident',
'380 personnel · Sandoval County · $4.2M to date',
'last growth 5h ago',
'discovered 1d ago · updated 2h ago',
]);
assert.equal(card.selected, true);
@@ -125,7 +128,7 @@ test('a full incident row renders name, size, containment, and ages', () => {
test('missing attributes degrade to available facts instead of placeholders', () => {
const card = buildIncidentCard(
{
stableId: 'x',
id: 'x',
name: null,
acres: null,
containedPct: null,
@@ -149,7 +152,7 @@ test('missing attributes degrade to available facts instead of placeholders', ()
test('a known InciWeb page adds a link line to the card', () => {
const card = buildIncidentCard(
{
stableId: 'x',
id: 'x',
name: 'Timber',
acres: 25426,
containedPct: 44,
@@ -177,7 +180,7 @@ test('a known InciWeb page adds a link line to the card', () => {
test('the selected card claims the selected paint lane, not the ambient lane', () => {
const card = buildIncidentCard(
{
stableId: 'x',
id: 'x',
name: 'Any',
acres: 1,
containedPct: 1,
@@ -204,7 +207,7 @@ test('the selected card claims the selected paint lane, not the ambient lane', (
test('costs near a unit boundary promote to the larger unit', () => {
const base = {
stableId: 'x',
id: 'x',
name: 'Any',
acres: null,
containedPct: null,
@@ -232,7 +235,7 @@ test('costs near a unit boundary promote to the larger unit', () => {
test('a complex member names its complex on the card', () => {
const card = buildIncidentCard(
{
stableId: 'x',
id: 'x',
name: 'Crosswhite',
acres: 342923,
containedPct: 99,
@@ -256,7 +259,7 @@ test('a complex member names its complex on the card', () => {
test('a card without a link is not interactive', () => {
const card = buildIncidentCard(
{
stableId: 'x',
id: 'x',
name: 'Crosswhite',
acres: 1,
containedPct: 1,
@@ -279,7 +282,7 @@ test('a card without a link is not interactive', () => {
test('partial incident details render only the facts that exist', () => {
const card = buildIncidentCard(
{
stableId: 'x',
id: 'x',
name: 'Whiskey',
acres: 542,
containedPct: 48,
@@ -305,7 +308,7 @@ test('partial incident details render only the facts that exist', () => {
test('a fire under one acre keeps its WFIGS size instead of reading 0 ac', () => {
const row = {
stableId: 'x',
id: 'x',
name: 'Grey',
acres: 0.25,
containedPct: null,
@@ -333,3 +336,22 @@ test('a fire under one acre keeps its WFIGS size instead of reading 0 ac', () =>
'1 ac · containment unknown · US-WA',
);
});
test('ages count from the moment shown, not from the clock', () => {
const at = Date.UTC(2025, 7, 1, 12);
const card = buildIncidentCard(
{
id: 'past',
name: 'Past',
containedPct: 10,
discoveredTime: at - 3 * 86400000,
updatedTime: at - 30 * 60000,
lastGrowthTime: at - 7 * 3600000,
},
at,
);
assert.deepEqual(card.details.slice(-2), [
'last growth 7h ago',
'discovered 3d ago · updated 30m ago',
]);
});
+172 -106
View File
@@ -1,12 +1,6 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf } from '../../render/rendererOf.js';
import { hexColor } from '../../render/color.js';
import {
PERIMETER_OVERLAY_SOURCE_ID,
perimeterAnchorDegrees,
buildIncidentCard,
containmentAccent,
} from './cards.js';
import { PERIMETER_OVERLAY_SOURCE_ID, buildIncidentCard } from './cards.js';
import {
findInciwebLink,
inciwebNodeId,
@@ -14,21 +8,72 @@ import {
} from './inciweb.js';
import { msg, t } from '../../i18n/index.js';
import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
export { normalizeFirePerimeterSnapshot } from './records.js';
export {
normalizeFirePerimeterSnapshot,
firePerimeterSnapshot,
perimeterAnchorDegrees,
} from './records.js';
export { createWfigsPerimeterSource } from './source.js';
export * from './cards.js';
export * from './inciweb.js';
const HOUR_MS = 3600000;
/**
* Fill/line colour for a perimeter by containment progress (same ramp as the
* card accent), as a renderer colour `[r, g, b, a]`.
* Piece colours by age, newest first, as WorldFX draws fire growth: the
* upper bound of each age and its colour (renderer RGB, 0–1). A piece of
* unknown birth is drawn as the oldest.
*/
export function containmentColor(containedPct) {
return hexColor(containmentAccent(containedPct));
export const PERIMETER_AGE_BANDS = Object.freeze(
[
{ upToMs: 6 * HOUR_MS, rgb: [1, 0.78, 0.18], label: msg('New in 6 hours') },
{ upToMs: 24 * HOUR_MS, rgb: [1, 0.45, 0.05], label: msg('6–24 hours') },
{ upToMs: 72 * HOUR_MS, rgb: [0.85, 0.16, 0.05], label: msg('1–3 days') },
{
upToMs: Infinity,
rgb: [0.45, 0.06, 0.04],
label: msg('Older or unknown'),
},
].map((band) => Object.freeze(band)),
);
/**
* The age band of something born (or last grown) at `time`, seen at `atMs`:
* an index into PERIMETER_AGE_BANDS.
*/
export function perimeterAgeBand(time, atMs) {
const last = PERIMETER_AGE_BANDS.length - 1;
if (!Number.isFinite(time)) return last;
const age = atMs - time;
const index = PERIMETER_AGE_BANDS.findIndex(({ upToMs }) => age < upToMs);
return index < 0 ? last : index;
}
const FILL_ALPHA = 0.35;
const LINE_ALPHA = 0.9;
const LINE_WIDTH_PX = 2;
const withAlpha = ([r, g, b], alpha) => [r, g, b, alpha];
const cssColor = (rgb) =>
`#${rgb
.map((v) =>
Math.round(v * 255)
.toString(16)
.padStart(2, '0'),
)
.join('')}`;
const ringDegrees = (ring) => ring.map(([lon, lat]) => ({ lon, lat }));
const validLine = (line, min) =>
Array.isArray(line) &&
line.length >= min &&
line.every(
(point) =>
Array.isArray(point) &&
Number.isFinite(point[0]) &&
Number.isFinite(point[1]),
);
const validAnchor = (anchor) =>
Number.isFinite(anchor?.lon) && Number.isFinite(anchor?.lat);
/**
* The draw sets the perimeters are drawn in start with this; each layer has
@@ -52,8 +97,12 @@ const INCIWEB_INDEX_TTL_MS = 6 * 3600000;
/**
* Own one fire-perimeter display, its refresh lifecycle, and click selection.
*
* Each perimeter is a ground-clamped fill in one renderer draw set and its
* fire line a draped line in another (`drawOf(viewer)`), made at `init`.
* The source's `getSnapshot({signal})` answers fires and the pieces of
* their burned area (records.js `firePerimeterSnapshot`). Each piece is a
* ground-clamped fill in one renderer draw set, coloured by its age at the
* snapshot's `at` (else now), and its outline draped lines in another
* (`drawOf(viewer)`), made at `init`. When to read again (a timeline, the
* camera) is the host's call, through the manager's `refreshLayer`.
* Given a Cesium viewer with no renderer bound, the
* caller loads the package's `./render/cesium/unbound` export first.
*/
@@ -71,12 +120,16 @@ export function createFirePerimetersLayer({
let _viewer = null;
let _request = null;
let _linkRequest = null;
let _snapshotSignature = null;
// What the sets show: the snapshot revision and each piece's age band.
let _drawnKey = null;
let _fills = null;
let _lines = null;
let _setIds = new Set();
let _count = 0;
let _lastUpdate = null;
// The moment the snapshot shows (null: now), and the source's legend note.
let _at = null;
let _note = null;
// The proxy's last snapshot, served while WFIGS is unreachable.
let _stale = false;
let _lastError = null;
@@ -88,8 +141,11 @@ export function createFirePerimetersLayer({
let _inciwebIndex = [];
let _indexFetchedAt = 0;
let _indexFetchInFlight = false;
/** @type {Map<string, {stableId: string, anchor: {lon: number, lat: number}}>} */
const _rowById = new Map();
/** The snapshot's fires by id, each with its card anchor. */
let _fireById = new Map();
/** `<set id>\n<item id>` → the fire that item belongs to. */
const _fireByItem = new Map();
const shownAt = () => _at ?? Date.now();
// Link → currency verdict from the publication check; unknown links are
// absent. Failed checks are not cached so a transient outage retries.
const _linkVerdicts = new Map();
@@ -147,7 +203,7 @@ export function createFirePerimetersLayer({
discoveredTime: row.discoveredTime,
}),
);
if (_selectedId === row.stableId) publishSelectedCard();
if (_selectedId === row.id) publishSelectedCard();
})
.catch(() => {
// Fail closed without caching: no link now, retry on reselection.
@@ -159,7 +215,7 @@ export function createFirePerimetersLayer({
function publishSelectedCard() {
if (!canSelect()) return;
const row = _selectedId ? _rowById.get(_selectedId) : null;
const row = _selectedId ? _fireById.get(_selectedId) : null;
if (!row) {
_selectedId = null;
_selectedLink = null;
@@ -176,7 +232,7 @@ export function createFirePerimetersLayer({
_selectedLink =
candidate && _linkVerdicts.get(candidate) === true ? candidate : null;
const card = {
...buildIncidentCard(row, Date.now(), { link: _selectedLink }),
...buildIncidentCard(row, shownAt(), { link: _selectedLink }),
position: fromDegrees(row.anchor.lon, row.anchor.lat),
};
if (!openExternal) card.interactive = false;
@@ -202,10 +258,8 @@ export function createFirePerimetersLayer({
*/
function pickedIncidentId(hit) {
if (!hit || hit.surface || !_setIds.has(hit.set)) return null;
if (typeof hit.id !== 'string' || !hit.id.startsWith(PICK_PREFIX))
return null;
const incidentId = hit.id.slice(PICK_PREFIX.length).split(':')[0];
return _rowById.has(incidentId) ? incidentId : null;
const incidentId = _fireByItem.get(`${hit.set}\n${hit.id}`);
return incidentId != null && _fireById.has(incidentId) ? incidentId : null;
}
function installClickHandler() {
@@ -254,6 +308,56 @@ export function createFirePerimetersLayer({
});
}
/** Draw `pieces`, each in the colour of its age band. */
function drawPieces(pieces, bands) {
abortLinkVerification();
const nextFills = [];
const nextLines = [];
const counts = new Map();
_fireByItem.clear();
// `fire-perimeter:<fire>:<n>` for fills, `…:<fire>:line:<n>` for lines.
const itemId = (fireId, kind) => {
const key = `${kind}${fireId}`;
const n = counts.get(key) ?? 0;
counts.set(key, n + 1);
const id = `${PICK_PREFIX}${fireId}:${kind}${n}`;
_fireByItem.set(`${kind ? _lines.id : _fills.id}\n${id}`, fireId);
return id;
};
for (const [index, piece] of pieces.entries()) {
const { rgb } = PERIMETER_AGE_BANDS[bands[index]];
// Each exterior keeps its own holes.
for (const rings of Array.isArray(piece.polygons) ? piece.polygons : []) {
if (!Array.isArray(rings) || !rings.every((ring) => validLine(ring, 4)))
continue;
nextFills.push({
id: itemId(piece.fireId, ''),
geometry: { kind: 'polygon', rings: rings.map(ringDegrees) },
fill: withAlpha(rgb, FILL_ALPHA),
height: 'clampGround',
});
}
// The fire line: the piece's outline draped on the ground, apart from
// its fill, so a piece cut from a larger area has no line along the
// cut (lines take ECEF, draw.d.ts `LineItem`).
for (const line of Array.isArray(piece.outline) ? piece.outline : []) {
if (!validLine(line, 2)) continue;
nextLines.push({
id: itemId(piece.fireId, 'line:'),
positions: line.map(([lon, lat]) => fromDegrees(lon, lat)),
widthPx: LINE_WIDTH_PX,
mode: 'draped',
style: { kind: 'solid', color: withAlpha(rgb, LINE_ALPHA) },
});
}
}
_fills.set(nextFills);
_lines.set(nextLines);
console.log(
`[Data:FirePerimeters] Drew ${pieces.length} pieces of ${_fireById.size} fires`,
);
}
function removeClickHandler() {
_clickSubscription?.();
_clickSubscription = null;
@@ -325,80 +429,45 @@ export function createFirePerimetersLayer({
_request = request;
refreshInciwebIndex(request.signal);
try {
// The source contract is getSnapshot; a source that can also say how
// fresh its rows are (the WFIGS proxy) offers getSnapshotDetail.
const snapshot =
typeof source.getSnapshotDetail === 'function'
? await source.getSnapshotDetail({ signal: request.signal })
: { rows: await source.getSnapshot({ signal: request.signal }) };
const snapshot = await source.getSnapshot({ signal: request.signal });
if (request.signal.aborted || _request !== request || !_enabled)
return false;
const { rows } = snapshot;
if (!Array.isArray(snapshot?.fires) || !Array.isArray(snapshot.pieces))
throw new Error(msg('Malformed perimeter snapshot'));
_stale = snapshot.stale === true;
// A stale snapshot is as old as its fetch, not this poll.
const updatedAt =
_stale && Number.isFinite(snapshot.fetchedAt)
? snapshot.fetchedAt
: Date.now();
// Incident facts may change independently of the polygon's source clock.
const signature = JSON.stringify(
rows
.map(({ polygons, ...facts }) => facts)
.sort((a, b) => a.stableId.localeCompare(b.stableId)),
_at = Number.isFinite(snapshot.at) ? snapshot.at : null;
_note = typeof snapshot.note === 'string' ? snapshot.note : null;
// A fire needs an id and the anchor its card stands on; a piece
// needs its fire.
const fires = new Map();
for (const fire of snapshot.fires)
if (typeof fire?.id === 'string' && validAnchor(fire.anchor))
fires.set(fire.id, fire);
const pieces = snapshot.pieces.filter((piece) =>
fires.has(piece?.fireId),
);
if (signature === _snapshotSignature) {
if (_selectedId) publishSelectedCard();
_lastUpdate = updatedAt;
_lastError = null;
return true;
const atMs = shownAt();
const bands = pieces.map((piece) => perimeterAgeBand(piece.born, atMs));
const drawKey =
typeof snapshot.revision === 'string'
? `${snapshot.revision}\n${bands.join('')}`
: null;
_fireById = fires;
if (drawKey === null || drawKey !== _drawnKey) {
drawPieces(pieces, bands);
_drawnKey = drawKey;
}
abortLinkVerification();
const nextFills = [];
const nextLines = [];
_rowById.clear();
for (const row of rows) {
const color = containmentColor(row.containedPct);
for (const [index, rings] of row.polygons.entries()) {
const id = `${PICK_PREFIX}${row.stableId}:${index}`;
// Each exterior keeps its own holes.
nextFills.push({
id,
geometry: { kind: 'polygon', rings: rings.map(ringDegrees) },
fill: withAlpha(color, 0.25),
height: 'clampGround',
});
// The fire line: the exterior ring draped on the ground (lines
// take ECEF, draw.d.ts `LineItem`).
nextLines.push({
id,
positions: rings[0].map(([lon, lat]) => fromDegrees(lon, lat)),
widthPx: 2,
mode: 'draped',
style: { kind: 'solid', color: withAlpha(color, 0.9) },
});
}
// Keep a geometry-free projection: the coordinate arrays would
// otherwise be retained for the layer's lifetime while only the
// anchor is ever read again.
const { polygons, ...facts } = row;
_rowById.set(row.stableId, {
...facts,
anchor: perimeterAnchorDegrees(polygons),
});
}
_fills.set(nextFills);
_lines.set(nextLines);
_snapshotSignature = signature;
// Refresh (or drop) the selected incident's card against the new feed.
// Refresh (or drop) the selected incident's card against the new
// snapshot: its ages move with `at` even when nothing is redrawn.
if (_selectedId) publishSelectedCard();
_count = rows.length;
_count = fires.size;
_lastUpdate = updatedAt;
_lastError = null;
console.log(
`[Data:FirePerimeters] Updated: ${_count} incidents, ${nextFills.length} polygons`,
);
return true;
} catch (e) {
if (request.signal.aborted || _request !== request || !_enabled)
@@ -418,8 +487,11 @@ export function createFirePerimetersLayer({
_request = null;
removeClickHandler();
clearSelection();
_rowById.clear();
_snapshotSignature = null;
_fireById = new Map();
_fireByItem.clear();
_drawnKey = null;
_at = null;
_note = null;
_inciwebIndex = [];
_indexFetchedAt = 0;
_linkVerdicts.clear();
@@ -442,11 +514,11 @@ export function createFirePerimetersLayer({
? Math.max(1, Math.floor(maxCount))
: 2000;
const result = [];
for (const row of _rowById.values()) {
for (const fire of _fireById.values()) {
if (result.length >= limit) break;
const { anchor, stableId, ...facts } = row;
const { anchor, id, ...facts } = fire;
result.push({
id: stableId,
id,
...facts,
lat: anchor.lat,
lon: anchor.lon,
@@ -456,27 +528,21 @@ export function createFirePerimetersLayer({
},
getRowControls() {
const bands = [
{ label: t('Not contained or unknown'), color: containmentAccent(0) },
{ label: t('Under 50% contained'), color: containmentAccent(1) },
{ label: t('50–99% contained'), color: containmentAccent(50) },
{ label: t('Fully contained'), color: containmentAccent(100) },
];
const atMs = shownAt();
const counts = PERIMETER_AGE_BANDS.map(() => 0);
for (const fire of _fireById.values())
counts[perimeterAgeBand(fire.lastGrowthTime, atMs)]++;
return {
chips: [],
legend: bands.map((band, index) => ({
...band,
count: [..._rowById.values()].filter(
(row) => containmentAccent(row.containedPct) === band.color,
).length,
legend: PERIMETER_AGE_BANDS.map((band, index) => ({
label: t(band.label),
color: cssColor(band.rgb),
count: counts[index],
...(index === 0
? {
blurb: t(
'Colour shows reported containment. Perimeters are simplified to about 100 m.',
),
}
? { blurb: t('Colour shows how long ago each area was mapped.') }
: {}),
})),
...(_note ? { info: t(_note) } : {}),
};
},
+262 -106
View File
@@ -1,6 +1,10 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createFirePerimetersLayer } from './index.js';
import {
createFirePerimetersLayer,
perimeterAnchorDegrees,
PERIMETER_AGE_BANDS,
} from './index.js';
import { clickCard } from '../../data/pickRegistry.js';
import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
@@ -97,8 +101,9 @@ const ring = [
[-108.0, 35.3],
[-108.1, 35.2],
];
const row = {
stableId: '2026-NMGNF-000123',
const HOUR = 3600000;
const fire = {
id: '2026-NMGNF-000123',
name: 'Fixture Fire',
acres: 512.5,
containedPct: 40,
@@ -113,58 +118,107 @@ const row = {
costToDate: 4200000,
complexity: 'Type 3 Incident',
complexName: 'ROWE CREEK COMPLEX',
polygons: [[ring]],
lastGrowthTime: 1757950000000,
anchor: perimeterAnchorDegrees([[ring]]),
};
/** One piece of `fireId`'s area: one polygon, outlined by its rings. */
const pieceOf = (fireId, { rings = [ring], born = null, ...rest } = {}) => ({
fireId,
born,
polygons: [rings],
outline: rings,
...rest,
});
/** A source snapshot of `fires`, one piece each unless `pieces` is given. */
function snap(fires, { pieces, ...rest } = {}) {
return {
at: null,
fetchedAt: null,
stale: false,
revision: fires
.map(({ id, updatedTime }) => `${id}@${updatedTime}`)
.sort()
.join('|'),
note: null,
fires,
pieces: pieces ?? fires.map(({ id }) => pieceOf(id)),
...rest,
};
}
const rgba = (band, alpha) => [...PERIMETER_AGE_BANDS[band].rgb, alpha];
test('each perimeter polygon draws as one clamped fill with its draped fire line', async () => {
test('each piece draws as a clamped fill and its outline as draped lines, coloured by age', async () => {
const hole = [
[-108.08, 35.22],
[-108.02, 35.22],
[-108.02, 35.25],
[-108.08, 35.22],
];
const at = Date.UTC(2025, 7, 1, 12);
const other = { ...fire, id: 'other', containedPct: 100 };
const h = harness({
getSnapshot: async () => [
{ ...row, polygons: [[ring, hole]] },
{
...row,
stableId: 'other',
containedPct: 100,
polygons: [[ring], [ring]],
},
],
getSnapshot: async () =>
snap([fire, other], {
at,
pieces: [
pieceOf(fire.id, { rings: [ring, hole], born: at - HOUR }),
// A piece cut from a larger area: no line along the cut.
{
fireId: 'other',
born: at - 30 * HOUR,
polygons: [[ring]],
outline: [ring.slice(0, 3)],
},
pieceOf('other', { born: null }),
],
}),
});
assert.equal(h.fills().show, true);
assert.equal(h.lines().show, true);
assert.equal(await h.layer.update(h.viewer), true);
const ids = [
'fire-perimeter:2026-NMGNF-000123:0',
'fire-perimeter:other:0',
'fire-perimeter:other:1',
];
assert.deepEqual([...h.fills().items.keys()], ids);
assert.deepEqual([...h.lines().items.keys()], ids);
const fill = h.fills().items.get(ids[0]);
assert.deepEqual(
[...h.fills().items.keys()],
[
'fire-perimeter:2026-NMGNF-000123:0',
'fire-perimeter:other:0',
'fire-perimeter:other:1',
],
);
assert.deepEqual(
[...h.lines().items.keys()],
[
'fire-perimeter:2026-NMGNF-000123:line:0',
'fire-perimeter:2026-NMGNF-000123:line:1',
'fire-perimeter:other:line:0',
'fire-perimeter:other:line:1',
],
);
const fill = h.fills().items.get('fire-perimeter:2026-NMGNF-000123:0');
assert.equal(fill.height, 'clampGround');
assert.deepEqual(fill.fill, [1, 122 / 255, 0, 0.25]);
assert.deepEqual(fill.fill, rgba(0, 0.35));
assert.equal(fill.geometry.kind, 'polygon');
assert.equal(fill.geometry.rings.length, 2, 'the hole stays');
assert.deepEqual(fill.geometry.rings[0][1], { lon: -108.0, lat: 35.2 });
const line = h.lines().items.get(ids[0]);
const line = h.lines().items.get('fire-perimeter:2026-NMGNF-000123:line:1');
assert.equal(line.mode, 'draped');
assert.equal(line.widthPx, 2);
assert.deepEqual(line.style, {
kind: 'solid',
color: [1, 122 / 255, 0, 0.9],
});
assert.equal(line.positions.length, ring.length, 'the exterior ring only');
assert.deepEqual(line.style, { kind: 'solid', color: rgba(0, 0.9) });
assert.equal(line.positions.length, hole.length, 'the hole is outlined too');
assert.ok(Number.isFinite(line.positions[0].x), 'lines take ECEF');
assert.deepEqual(h.fills().items.get(ids[1]).fill, [
139 / 255,
195 / 255,
74 / 255,
0.25,
]);
assert.equal(
h.lines().items.get('fire-perimeter:other:line:0').positions.length,
3,
'the outline as given, not the polygon',
);
// Aged at the snapshot's moment, not now: 30 h is 1–3 days; unknown is oldest.
assert.deepEqual(
h.fills().items.get('fire-perimeter:other:0').fill,
rgba(2, 0.35),
);
assert.deepEqual(
h.fills().items.get('fire-perimeter:other:1').fill,
rgba(3, 0.35),
);
assert.equal(h.layer.getStats().count, 2);
h.layer.disable();
assert.equal(h.fills().show, false);
@@ -174,10 +228,23 @@ test('each perimeter polygon draws as one clamped fill with its draped fire line
assert.equal(h.lines(), undefined);
});
test('a piece of a fire the snapshot does not list is dropped', async () => {
const h = harness({
getSnapshot: async () =>
snap([fire], { pieces: [pieceOf(fire.id), pieceOf('ghost')] }),
});
await h.layer.update();
assert.deepEqual(
[...h.fills().items.keys()],
['fire-perimeter:2026-NMGNF-000123:0'],
);
h.layer.destroy();
});
test("a pick selects only an item of the layer's own sets", async () => {
let pickResult = null;
const h = harness(
{ getSnapshot: async () => [row] },
{ getSnapshot: async () => snap([fire]) },
{ pick: () => pickResult },
);
await h.layer.update(h.viewer);
@@ -188,7 +255,10 @@ test("a pick selects only an item of the layer's own sets", async () => {
assert.equal(h.overlay.entries.get('fire-perimeters')?.length ?? 0, 0);
// The fire line picks as its perimeter, as the one entity used to.
pickResult = {
id: { set: h.lines().spec.id, id: 'fire-perimeter:2026-NMGNF-000123:0' },
id: {
set: h.lines().spec.id,
id: 'fire-perimeter:2026-NMGNF-000123:line:0',
},
};
h.clicks.handler({ position: { x: 10, y: 10 } });
assert.equal(h.overlay.entries.get('fire-perimeters').length, 1);
@@ -209,7 +279,7 @@ test('late refresh cannot publish after disable or destroy', async () => {
h.layer[action](h.viewer);
assert.equal(signal.aborted, true);
if (action === 'disable') h.layer.enable(h.viewer);
resolve([row]);
resolve(snap([fire]));
assert.equal(await pending, false);
assert.equal(h.layer.getStats().count, 0);
h.layer.destroy(h.viewer);
@@ -219,7 +289,7 @@ test('late refresh cannot publish after disable or destroy', async () => {
test('clicking a perimeter publishes its incident card; empty space clears it', async () => {
let pickResult = null;
const h = harness(
{ getSnapshot: async () => [row] },
{ getSnapshot: async () => snap([fire]) },
{
pick: () => pickResult,
},
@@ -259,7 +329,7 @@ test("another layer's overlay on top keeps a click off the area", async () => {
let pickResult = null;
let foreignOnTop = false;
const h = harness(
{ getSnapshot: async () => [row] },
{ getSnapshot: async () => snap([fire]) },
{
pick: () => pickResult,
// Unfiltered: the topmost entry of any source.
@@ -292,7 +362,7 @@ test("another layer's overlay on top keeps a click off the area", async () => {
test('disable removes the click handler, pick ownership, and any card', async () => {
const h = harness(
{ getSnapshot: async () => [row] },
{ getSnapshot: async () => snap([fire]) },
{ pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0') },
);
await h.layer.update(h.viewer);
@@ -304,7 +374,7 @@ test('disable removes the click handler, pick ownership, and any card', async ()
});
test('a refresh that drops the selected incident also drops its card', async () => {
let rows = [row];
let rows = snap([fire]);
const h = harness(
{ getSnapshot: async () => rows },
{ pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0') },
@@ -312,11 +382,61 @@ test('a refresh that drops the selected incident also drops its card', async ()
await h.layer.update(h.viewer);
h.clicks.handler({ position: { x: 10, y: 10 } });
assert.equal(h.overlay.entries.get('fire-perimeters').length, 1);
rows = [{ ...row, stableId: 'different' }];
rows = snap([{ ...fire, id: 'different' }]);
await h.layer.update(h.viewer);
assert.equal(h.overlay.entries.get('fire-perimeters')?.length ?? 0, 0);
});
test('a selected fire keeps its card while listed, even with no pieces left', async () => {
let current = snap([fire]);
const h = harness(
{ getSnapshot: async () => current },
{ pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0') },
);
await h.layer.update();
h.clicks.handler({ position: { x: 10, y: 10 } });
current = snap([fire], { pieces: [] });
await h.layer.update();
assert.equal(h.fills().items.size, 0);
const [card] = h.overlay.entries.get('fire-perimeters');
assert.equal(card.id, 'fire-perimeter-card:2026-NMGNF-000123');
assert.equal(h.layer.getStats().count, 1, 'a fire without pieces counts');
assert.equal(
h.layer.getRowControls().legend.reduce((sum, { count }) => sum + count, 0),
1,
);
h.layer.destroy();
});
test('the card ages from the moment the snapshot shows', async () => {
const at = Date.UTC(2025, 7, 1, 12);
const h = harness(
{
getSnapshot: async () =>
snap(
[
{
...fire,
discoveredTime: at - 50 * HOUR,
updatedTime: at - 2 * HOUR,
lastGrowthTime: at - 5 * HOUR,
},
],
{ at },
),
},
{ pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0') },
);
await h.layer.update();
h.clicks.handler({ position: { x: 10, y: 10 } });
const [card] = h.overlay.entries.get('fire-perimeters');
assert.deepEqual(card.details.slice(-2), [
'last growth 5h ago',
'discovered 2d ago · updated 2h ago',
]);
h.layer.destroy();
});
test('a matched incident card carries the InciWeb line and click-through', async () => {
const inciwebIndex = [
{
@@ -328,7 +448,7 @@ test('a matched incident card carries the InciWeb line and click-through', async
let cardHitResult = null;
let foreignOnTop = false;
const h = harness(
{ getSnapshot: async () => [{ ...row, name: 'Fixture' }] },
{ getSnapshot: async () => snap([{ ...fire, name: 'Fixture' }]) },
{
pick: () => null,
inciwebIndex,
@@ -371,7 +491,7 @@ test('a matched incident card carries the InciWeb line and click-through', async
test('a click on a mission label over the incident card never opens its InciWeb page, and keeps the card open', async () => {
let cardHitResult = null;
const h = harness(
{ getSnapshot: async () => [row] },
{ getSnapshot: async () => snap([fire]) },
{
pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0'),
inciwebIndex: [
@@ -409,7 +529,7 @@ test('a click on a mission label over the incident card never opens its InciWeb
test('an unmatched incident renders no InciWeb line and card clicks stay inert', async () => {
let cardHitResult = null;
const h = harness(
{ getSnapshot: async () => [row] },
{ getSnapshot: async () => snap([fire]) },
{
pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0'),
inciwebIndex: [],
@@ -432,7 +552,7 @@ test('an unmatched incident renders no InciWeb line and card clicks stay inert',
test('a complex member resolves to its complex page from the catalog', async () => {
const h = harness(
{ getSnapshot: async () => [row] },
{ getSnapshot: async () => snap([fire]) },
{
pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0'),
inciwebIndex: [
@@ -473,7 +593,7 @@ test('a stale or unverifiable publication yields no link', async () => {
},
]) {
const h = harness(
{ getSnapshot: async () => [row] },
{ getSnapshot: async () => snap([fire]) },
{
pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0'),
inciwebIndex,
@@ -495,17 +615,20 @@ test('a stale or unverifiable publication yields no link', async () => {
});
test('a hanging InciWeb index fetch never blocks the perimeter refresh', async (t) => {
const h = harness({ getSnapshot: async () => [row] }, { inciwebIndex: null });
const h = harness(
{ getSnapshot: async () => snap([fire]) },
{ inciwebIndex: null },
);
// Replace the index source with one that never resolves.
h.layer.destroy(h.viewer);
const hanging = harness({ getSnapshot: async () => [row] });
const hanging = harness({ getSnapshot: async () => snap([fire]) });
hanging.layer.destroy(hanging.viewer);
const viewer = { scene: { pick: () => null } };
bindFakeDraw(viewer);
const input = fakeInput(viewer);
t.after(() => input.destroy());
const layer = createFirePerimetersLayer({
source: { getSnapshot: async () => [row] },
source: { getSnapshot: async () => snap([fire]) },
overlayHost: {
setEntries() {},
setVisible() {},
@@ -537,9 +660,9 @@ test('a hanging InciWeb index fetch never blocks the perimeter refresh', async (
});
test('an InciWeb outage never breaks the perimeter refresh', async (t) => {
const h = harness({ getSnapshot: async () => [row] });
const h = harness({ getSnapshot: async () => snap([fire]) });
const failing = createFirePerimetersLayer({
source: { getSnapshot: async () => [row] },
source: { getSnapshot: async () => snap([fire]) },
overlayHost: {
setEntries() {},
setVisible() {},
@@ -577,7 +700,7 @@ test('an InciWeb outage never breaks the perimeter refresh', async (t) => {
});
test('analyst records expose incident facts without geometry payloads', async () => {
const h = harness({ getSnapshot: async () => [row] });
const h = harness({ getSnapshot: async () => snap([fire]) });
await h.layer.update(h.viewer);
const records = h.layer.getAnalystRecords();
assert.equal(records.length, 1);
@@ -591,95 +714,132 @@ test('analyst records expose incident facts without geometry payloads', async ()
assert.equal(records[0].county, 'Sandoval');
assert.equal(records[0].costToDate, 4200000);
assert.equal(records[0].complexity, 'Type 3 Incident');
assert.equal(records[0].lastGrowthTime, fire.lastGrowthTime);
assert.equal(records[0].id, fire.id);
// Spatial scoping in the analyst engine requires coordinates.
assert.ok(Math.abs(records[0].lat - 35.2333) < 0.01);
assert.ok(Math.abs(records[0].lon - -108.0333) < 0.01);
assert.equal('polygons' in records[0], false);
assert.equal('polygons' in records[0] || 'anchor' in records[0], false);
});
test('unchanged snapshots draw nothing again even if source ordering changes', async () => {
let rows = [row, { ...row, stableId: 'other' }];
const h = harness({ getSnapshot: async () => rows });
await h.layer.update();
test('the layer redraws on a new revision or a change of age band, and only then', async () => {
const at = Date.UTC(2025, 7, 1, 12);
const other = { ...fire, id: 'other' };
let current = snap([fire, other], {
at,
pieces: [pieceOf(fire.id, { born: at - HOUR }), pieceOf('other')],
});
const h = harness({ getSnapshot: async () => current });
const writes = () => [h.fills().writes, h.lines().writes];
assert.deepEqual(writes(), [1, 1]);
rows = [...rows].reverse();
await h.layer.update();
assert.deepEqual(writes(), [1, 1]);
rows = rows.map((value) => ({
...value,
updatedTime: value.updatedTime + 1,
}));
// Same revision, feed reordered, facts changed, still in the same band.
current = {
...current,
at: at + 4 * HOUR,
fires: [{ ...other, containedPct: 100 }, fire],
};
await h.layer.update();
assert.deepEqual(writes(), [1, 1]);
// The new piece turns 6 h old.
current = { ...current, at: at + 6 * HOUR };
await h.layer.update();
assert.deepEqual(writes(), [2, 2]);
rows = rows.map((value) => ({ ...value, containedPct: 100 }));
await h.layer.update();
assert.deepEqual(
writes(),
[3, 3],
'incident facts can change without a new polygon timestamp',
h.fills().items.get('fire-perimeter:2026-NMGNF-000123:0').fill,
rgba(1, 0.35),
);
assert.equal(h.layer.getRowControls().legend[3].count, 2);
rows = [];
current = { ...current, revision: 'changed' };
await h.layer.update();
assert.deepEqual(writes(), [3, 3]);
// A source without a revision is drawn every time.
current = { ...current, revision: undefined };
await h.layer.update();
await h.layer.update();
assert.deepEqual(writes(), [5, 5]);
current = snap([]);
await h.layer.update();
assert.equal(h.fills().items.size, 0);
assert.equal(h.lines().items.size, 0);
h.layer.destroy();
});
test('containment legend uses the existing thresholds, colours and incident counts', async () => {
const values = [null, -1, 0, 0.5, 49.9, 50, 99.9, 100, 101];
test('a failed read keeps the picture and reports the error', async () => {
let fail = false;
const h = harness({
getSnapshot: async () => {
if (fail) throw new Error('WFIGS HTTP 502');
return snap([fire]);
},
});
await h.layer.update();
fail = true;
assert.equal(await h.layer.update(), false);
assert.equal(h.fills().items.size, 1);
assert.equal(h.layer.getStats().error, 'WFIGS HTTP 502');
assert.equal(h.layer.getStats().count, 1);
h.layer.destroy();
});
test('a malformed snapshot is an error, not an empty map', async () => {
const h = harness({ getSnapshot: async () => [fire] });
assert.equal(await h.layer.update(), false);
assert.equal(h.layer.getStats().error, 'Malformed perimeter snapshot');
h.layer.destroy();
});
test('the legend counts fires by their last growth at the moment shown, with the source note', async () => {
const at = Date.UTC(2025, 7, 1, 12);
const ages = [0, 5.9, 6, 23.9, 24, 71.9, 72, null, -1];
const h = harness({
getSnapshot: async () =>
values.map((containedPct, index) => ({
...row,
stableId: String(index),
containedPct,
})),
snap(
ages.map((hours, index) => ({
...fire,
id: String(index),
lastGrowthTime: hours === null ? null : at - hours * HOUR,
})),
{ at, note: 'Perimeters are simplified to about 100 m.' },
),
});
await h.layer.update();
const controls = h.layer.getRowControls();
assert.deepEqual(controls.chips, []);
assert.deepEqual(
controls.legend.map(({ color, count }) => [color, count]),
controls.legend.map(({ label, color, count }) => [label, color, count]),
[
['#ff3b30', 3],
['#ff7a00', 2],
['#ffb300', 2],
['#8bc34a', 2],
['New in 6 hours', '#ffc72e', 3],
['6–24 hours', '#ff730d', 2],
['1–3 days', '#d9290d', 2],
['Older or unknown', '#730f0a', 2],
],
);
assert.ok(
controls.legend.every(
({ label }) => typeof label === 'string' && label.length,
),
);
assert.equal(
controls.legend[0].blurb,
'Colour shows reported containment. Perimeters are simplified to about 100 m.',
'Colour shows how long ago each area was mapped.',
);
assert.equal(controls.info, 'Perimeters are simplified to about 100 m.');
h.layer.destroy();
assert.deepEqual(
h.layer.getRowControls().legend.map(({ count }) => count),
[0, 0, 0, 0],
);
assert.equal(h.layer.getRowControls().info, undefined);
});
for (const action of ['disable', 'destroy', 'selection']) {
test(`incident-link verification aborts on ${action} and ignores late completion`, async () => {
let finish, signal;
let pickId = `fire-perimeter:${row.stableId}:0`;
let pickId = `fire-perimeter:${fire.id}:0`;
const h = harness(
{
getSnapshot: async () => [
row,
{ ...row, stableId: 'other', name: 'Other Fire' },
],
getSnapshot: async () =>
snap([fire, { ...fire, id: 'other', name: 'Other Fire' }]),
},
{
pick: () => perimeterPick(pickId),
inciwebIndex: [
{ incident_id: '123', incident_title: row.name, tau: 'nm' },
{ incident_id: '123', incident_title: fire.name, tau: 'nm' },
],
publication: (_id, options) => {
signal = options.signal;
@@ -698,7 +858,7 @@ for (const action of ['disable', 'destroy', 'selection']) {
} else h.layer[action]();
assert.equal(signal.aborted, true);
const entries = h.overlay.entries.get('fire-perimeters');
finish({ createdMs: row.discoveredTime, changedMs: row.updatedTime });
finish({ createdMs: fire.discoveredTime, changedMs: fire.updatedTime });
await new Promise(setImmediate);
assert.equal(h.overlay.entries.get('fire-perimeters'), entries);
if (action !== 'destroy') h.layer.destroy();
@@ -707,15 +867,12 @@ for (const action of ['disable', 'destroy', 'selection']) {
test('a stale snapshot reads stale, dated by its own fetch, and a fresh one clears it', async () => {
const fetchedAt = Date.now() - 3 * 60 * 60 * 1000;
let snapshot = { rows: [row], stale: true, fetchedAt };
const h = harness({
getSnapshot: async () => snapshot.rows,
getSnapshotDetail: async () => snapshot,
});
let snapshot = snap([fire], { stale: true, fetchedAt });
const h = harness({ getSnapshot: async () => snapshot });
await h.layer.update(h.viewer);
assert.equal(h.layer.getStats().stale, true);
assert.equal(h.layer.getStats().lastUpdate, fetchedAt);
snapshot = { rows: [row], stale: false, fetchedAt: Date.now() };
snapshot = snap([fire], { fetchedAt: Date.now() });
await h.layer.update(h.viewer);
assert.equal(h.layer.getStats().stale, false);
assert.ok(h.layer.getStats().lastUpdate > fetchedAt);
@@ -724,10 +881,9 @@ test('a stale snapshot reads stale, dated by its own fetch, and a fresh one clea
test('a failed refresh after a stale snapshot reads as the failure, not stale', async () => {
let fail = false;
const h = harness({
getSnapshot: async () => [row],
getSnapshotDetail: async () => {
getSnapshot: async () => {
if (fail) throw new Error('WFIGS HTTP 502');
return { rows: [row], stale: true, fetchedAt: Date.now() - 60_000 };
return snap([fire], { stale: true, fetchedAt: Date.now() - 60_000 });
},
});
await h.layer.update(h.viewer);
+113
View File
@@ -1,3 +1,12 @@
/**
* WFIGS perimeters: the proxy's rows (normalizeFirePerimeterSnapshot) and
* the snapshot the layer draws (firePerimeterSnapshot).
*
* A portable export (package.json): no i18n here.
*/
const msg = (text) => text;
/**
* Normalize a WFIGS feed, skipping individually invalid features.
* Only a payload that is not a feature collection at all rejects the whole
@@ -80,6 +89,7 @@ export function normalizeFirePerimeterSnapshot(geojson) {
: null,
discoveredTime: finiteOrNull(properties.attr_FireDiscoveryDateTime),
updatedTime: finiteOrNull(properties.poly_DateCurrent),
polygonTime: finiteOrNull(properties.poly_PolygonDateTime),
cause: textOrNull(properties.attr_FireCause),
behavior: textOrNull(properties.attr_FireBehaviorGeneral),
personnel: finiteOrNull(properties.attr_TotalIncidentPersonnel),
@@ -92,3 +102,106 @@ export function normalizeFirePerimeterSnapshot(geojson) {
}
return rows;
}
/** Shoelace area along short longitude edges (degree², relative sizes only). */
function ringArea(ring) {
let sum = 0;
let [x1, y1] = ring[0];
for (let i = 1; i < ring.length; i++) {
let delta = ring[i][0] - ring[i - 1][0];
if (delta > 180) delta -= 360;
else if (delta < -180) delta += 360;
const x2 = x1 + delta;
const y2 = ring[i][1];
sum += x1 * y2 - x2 * y1;
x1 = x2;
y1 = y2;
}
return Math.abs(sum / 2);
}
/**
* Anchor point for the incident card: the vertex mean of the largest polygon's
* outer ring, with circular longitude. Callers own the Cartesian conversion.
* @param {Array<Array<Array<[number, number]>>>} polygons - Normalized rows' polygons.
* @returns {{lon: number, lat: number}}
*/
export function perimeterAnchorDegrees(polygons) {
let best = null;
let bestArea = -1;
for (const rings of polygons) {
const outer = rings[0];
const area = ringArea(outer);
if (area > bestArea) {
bestArea = area;
best = outer;
}
}
// Vertex mean over the closed ring (first == last point dropped): perimeters
// are compact enough that this stays inside or near the polygon.
let sinLon = 0;
let cosLon = 0;
let lat = 0;
const count = best.length - 1;
const toRad = Math.PI / 180;
for (let i = 0; i < count; i++) {
sinLon += Math.sin(best[i][0] * toRad);
cosLon += Math.cos(best[i][0] * toRad);
lat += best[i][1];
}
return { lon: Math.atan2(sinLon, cosLon) / toRad, lat: lat / count };
}
/** A clock this far ahead of ours is still taken as now, not as the future. */
const CLOCK_SKEW_MS = 10 * 60 * 1000;
/**
* The snapshot the Fire Perimeters layer draws, from the proxy's rows.
*
* WFIGS keeps one perimeter per fire, so each of its polygons is one piece,
* born when the perimeter was mapped (`poly_PolygonDateTime`, else the
* record's last edit `poly_DateCurrent`). A time in the future is unknown.
* @param {object[]} rows - normalizeFirePerimeterSnapshot rows.
* @param {{fetchedAt?: number|null, stale?: boolean, now?: number}} [options]
* @returns {{at: null, fetchedAt: number|null, stale: boolean,
* revision: string, note: string, fires: object[], pieces: object[]}}
*/
export function firePerimeterSnapshot(
rows,
{ fetchedAt = null, stale = false, now = Date.now() } = {},
) {
const fires = [];
const pieces = [];
const versions = [];
for (const row of rows) {
const { stableId, polygons, polygonTime, ...facts } = row;
if (typeof stableId !== 'string' || !Array.isArray(polygons)) continue;
if (!polygons.length) continue;
const mapped = polygonTime ?? facts.updatedTime;
const grown =
Number.isFinite(mapped) && mapped <= now + CLOCK_SKEW_MS ? mapped : null;
fires.push({
...facts,
id: stableId,
lastGrowthTime: grown,
anchor: perimeterAnchorDegrees(polygons),
});
for (const rings of polygons)
pieces.push({
fireId: stableId,
born: grown,
polygons: [rings],
outline: rings,
});
versions.push(`${stableId}@${facts.updatedTime ?? ''}`);
}
return {
at: null,
fetchedAt: Number.isFinite(fetchedAt) ? fetchedAt : null,
stale: stale === true,
revision: versions.sort().join('|'),
note: msg('Perimeters are simplified to about 100 m.'),
fires,
pieces,
};
}
+123 -1
View File
@@ -1,6 +1,9 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { normalizeFirePerimeterSnapshot } from './records.js';
import {
normalizeFirePerimeterSnapshot,
firePerimeterSnapshot,
} from './records.js';
const ring = [
[-108.1, 35.2],
@@ -22,6 +25,7 @@ function feature(overrides = {}) {
attr_IncidentTypeCategory: 'WF',
attr_FireDiscoveryDateTime: 1757900000000,
poly_DateCurrent: 1757950000000,
poly_PolygonDateTime: 1757940000000,
attr_FireCause: 'Natural',
attr_FireBehaviorGeneral: 'Active',
attr_TotalIncidentPersonnel: 380,
@@ -59,6 +63,7 @@ test('a valid snapshot yields one row per incident with polygons preserved', ()
category: 'WF',
discoveredTime: 1757900000000,
updatedTime: 1757950000000,
polygonTime: 1757940000000,
cause: 'Natural',
behavior: 'Active',
personnel: 380,
@@ -90,6 +95,7 @@ test('optional attributes normalize to null rather than leaking undefined', () =
attr_IncidentTypeCategory: null,
attr_FireDiscoveryDateTime: null,
poly_DateCurrent: null,
poly_PolygonDateTime: null,
attr_FireCause: null,
attr_FireBehaviorGeneral: null,
attr_TotalIncidentPersonnel: null,
@@ -110,6 +116,7 @@ test('optional attributes normalize to null rather than leaking undefined', () =
category: rows[0].category,
discoveredTime: rows[0].discoveredTime,
updatedTime: rows[0].updatedTime,
polygonTime: rows[0].polygonTime,
cause: rows[0].cause,
behavior: rows[0].behavior,
personnel: rows[0].personnel,
@@ -126,6 +133,7 @@ test('optional attributes normalize to null rather than leaking undefined', () =
category: null,
discoveredTime: null,
updatedTime: null,
polygonTime: null,
cause: null,
behavior: null,
personnel: null,
@@ -199,3 +207,117 @@ test('a perimeter with no rings is skipped rather than rendered empty', () => {
assert.equal(rows.length, 1);
assert.equal(rows[0].stableId, 'other');
});
const NOW = 1758000000000;
const rowsOf = (...features) => normalizeFirePerimeterSnapshot({ features });
// feature() replaces all properties with the overrides' own: keep the rest.
const fixture = (id, properties) =>
feature({ id, properties: { ...feature().properties, ...properties } });
test('each WFIGS polygon becomes one piece of its fire, born when it was mapped', () => {
const hole = [
[-108.08, 35.22],
[-108.02, 35.22],
[-108.02, 35.25],
[-108.08, 35.22],
];
const snapshot = firePerimeterSnapshot(
rowsOf(
feature({
geometry: { type: 'MultiPolygon', coordinates: [[ring, hole], [ring]] },
}),
),
{ fetchedAt: NOW - 1000, now: NOW },
);
assert.equal(snapshot.at, null);
assert.equal(snapshot.stale, false);
assert.equal(snapshot.fetchedAt, NOW - 1000);
assert.equal(snapshot.note, 'Perimeters are simplified to about 100 m.');
assert.equal(snapshot.fires.length, 1);
const [fire] = snapshot.fires;
assert.equal(fire.id, '2026-NMGNF-000123');
assert.equal(fire.lastGrowthTime, 1757940000000);
assert.equal(fire.containedPct, 40);
assert.equal('stableId' in fire || 'polygons' in fire, false);
assert.ok(Math.abs(fire.anchor.lat - 35.2333) < 0.01);
assert.deepEqual(
snapshot.pieces.map(({ fireId, born, polygons, outline }) => [
fireId,
born,
polygons,
outline,
]),
[
['2026-NMGNF-000123', 1757940000000, [[ring, hole]], [ring, hole]],
['2026-NMGNF-000123', 1757940000000, [[ring]], [ring]],
],
'the outline is every ring, holes included',
);
});
test('a perimeter without its mapping time falls back to the last edit; a future time is unknown', () => {
const [fallback, future, futureEdit, none] = firePerimeterSnapshot(
rowsOf(
fixture(1, { poly_PolygonDateTime: null }),
fixture(2, {
attr_UniqueFireIdentifier: 'future',
poly_PolygonDateTime: NOW + 3600000,
}),
fixture(3, {
attr_UniqueFireIdentifier: 'future-edit',
poly_PolygonDateTime: null,
poly_DateCurrent: NOW + 3600000,
}),
fixture(4, {
attr_UniqueFireIdentifier: 'none',
poly_PolygonDateTime: null,
poly_DateCurrent: null,
}),
),
{ now: NOW },
).fires;
assert.equal(fallback.lastGrowthTime, 1757950000000);
assert.equal(future.lastGrowthTime, null);
assert.equal(futureEdit.lastGrowthTime, null);
assert.equal(none.lastGrowthTime, null);
// A clock a few minutes ahead of ours is not the future.
const skewed = firePerimeterSnapshot(
rowsOf(fixture(1, { poly_PolygonDateTime: NOW + 60000 })),
{ now: NOW },
);
assert.equal(skewed.fires[0].lastGrowthTime, NOW + 60000);
assert.equal(skewed.pieces[0].born, NOW + 60000);
});
test('the revision follows fire ids and update times, not feed order', () => {
const a = feature();
const b = fixture(2, { attr_UniqueFireIdentifier: 'b' });
const revision = (...features) =>
firePerimeterSnapshot(rowsOf(...features), { now: NOW }).revision;
assert.equal(revision(a, b), revision(b, a));
assert.notEqual(
revision(a, b),
revision(
a,
fixture(2, { attr_UniqueFireIdentifier: 'b', poly_DateCurrent: 1 }),
),
);
assert.notEqual(revision(a, b), revision(a));
});
test('the snapshot carries staleness and skips rows it cannot place', () => {
const snapshot = firePerimeterSnapshot(
[
{ stableId: 'empty', polygons: [] },
{ polygons: [[ring]] },
...rowsOf(feature()),
],
{ stale: true, fetchedAt: 'yesterday', now: NOW },
);
assert.equal(snapshot.stale, true);
assert.equal(snapshot.fetchedAt, null);
assert.deepEqual(
snapshot.fires.map(({ id }) => id),
['2026-NMGNF-000123'],
);
});
+25 -29
View File
@@ -1,42 +1,38 @@
import { readResponseJsonCapped } from '../../sources/httpBody.js';
import { firePerimeterSnapshot } from './records.js';
// A portable export (package.json): no i18n here. Failures stay English data;
// the Layers panel shows them translated.
const msg = (text) => text;
/** Request a normalized snapshot through the bounded, same-origin WFIGS proxy. */
/** Request a snapshot through the bounded, same-origin WFIGS proxy. */
export function createWfigsPerimeterSource({
fetchImpl = (...args) => globalThis.fetch(...args),
now = () => Date.now(),
} = {}) {
/**
* The rows with how fresh they are: the proxy answers from its last
* snapshot, marked stale, while WFIGS is unreachable.
* @returns {Promise<{rows: object[], stale: boolean, fetchedAt: number|null}>}
*/
async function getSnapshotDetail({ signal } = {}) {
signal?.throwIfAborted();
const response = await fetchImpl('/api/fire-perimeters', { signal });
if (!response.ok) throw new Error(`WFIGS HTTP ${response.status}`);
const payload = await readResponseJsonCapped(
response,
80 * 1024 * 1024,
signal,
);
signal?.throwIfAborted();
if (!Array.isArray(payload?.rows))
throw new Error(msg('Malformed perimeter snapshot'));
return {
rows: payload.rows,
stale: payload.stale === true,
fetchedAt: Number.isFinite(payload.fetchedAt) ? payload.fetchedAt : null,
};
}
return {
/** The perimeter rows (see getSnapshotDetail for staleness). */
async getSnapshot(options = {}) {
return (await getSnapshotDetail(options)).rows;
/**
* Current perimeters as fires and their pieces (firePerimeterSnapshot).
* The proxy answers from its last snapshot, marked stale, while WFIGS is
* unreachable.
*/
async getSnapshot({ signal } = {}) {
signal?.throwIfAborted();
const response = await fetchImpl('/api/fire-perimeters', { signal });
if (!response.ok) throw new Error(`WFIGS HTTP ${response.status}`);
const payload = await readResponseJsonCapped(
response,
80 * 1024 * 1024,
signal,
);
signal?.throwIfAborted();
if (!Array.isArray(payload?.rows))
throw new Error(msg('Malformed perimeter snapshot'));
return firePerimeterSnapshot(payload.rows, {
fetchedAt: payload.fetchedAt,
stale: payload.stale === true,
now: now(),
});
},
getSnapshotDetail,
};
}
+14 -12
View File
@@ -20,7 +20,7 @@ const validPayload = {
],
};
test('a successful response yields normalized perimeter rows', async () => {
test('a successful response yields the snapshot of fires and pieces', async () => {
let requested;
const source = createWfigsPerimeterSource({
fetchImpl: async (url) => {
@@ -30,9 +30,13 @@ test('a successful response yields normalized perimeter rows', async () => {
});
},
});
const rows = await source.getSnapshot();
assert.equal(rows.length, 1);
assert.equal(rows[0].stableId, '2026-NMGNF-000123');
const snapshot = await source.getSnapshot();
assert.deepEqual(
snapshot.fires.map((fire) => fire.id),
['2026-NMGNF-000123'],
);
assert.deepEqual(snapshot.pieces[0].polygons, [[ring]]);
assert.equal(snapshot.at, null);
assert.equal(requested, '/api/fire-perimeters');
});
@@ -160,22 +164,20 @@ test('a failed refresh serves the last snapshot marked stale for a day, then ref
assert.equal((await ask()).status, 502, 'a day-old snapshot is not served');
});
test('the snapshot detail carries the proxy staleness and fetch time', async () => {
test('the snapshot carries the proxy staleness and fetch time', async () => {
const fetchedAt = Date.UTC(2026, 9, 25, 12);
const source = createWfigsPerimeterSource({
fetchImpl: async () => Response.json({ rows: [], stale: true, fetchedAt }),
});
assert.deepEqual(await source.getSnapshotDetail(), {
rows: [],
stale: true,
fetchedAt,
});
assert.deepEqual(await source.getSnapshot(), []);
const snapshot = await source.getSnapshot();
assert.equal(snapshot.stale, true);
assert.equal(snapshot.fetchedAt, fetchedAt);
assert.deepEqual([snapshot.fires, snapshot.pieces], [[], []]);
});
test('getSnapshot works when taken off its source object', async () => {
const { getSnapshot } = createWfigsPerimeterSource({
fetchImpl: async () => Response.json({ rows: [] }),
});
assert.deepEqual(await getSnapshot(), []);
assert.deepEqual((await getSnapshot()).fires, []);
});
-2
View File
@@ -50,8 +50,6 @@ export function createFlow({ state: layerState, services, parts, source }) {
if (code === 'RATE_LIMITED') return msg('Traffic rate limit reached');
if (status === 503 && code && code !== 'no_key')
return msg('Traffic service unavailable');
// TomTom refused the key on both of its flow endpoints.
if (code === 'key_rejected') return msg('TomTom key rejected');
if (status === 503) return msg('TomTom key unavailable');
if (status === 429) return msg('TomTom daily budget reached');
if (status === 502 || status === 504)
+4 -45
View File
@@ -15,15 +15,6 @@ import { VectorTile } from '@mapbox/vector-tile';
* ratio (1 = free flow). Features with a missing/non-finite `traffic_level`
* are skipped unless `road_closure` is true (closures decode with level 0).
*
* The proxy serves tiles from either TomTom flow endpoint, and they name
* things differently. TomTom Maps (`traffic/map/4`, style `relative`):
* `traffic_level`, `road_type` ("Motorway", "Major road", …) and
* `traffic_road_coverage` (`full` when one line carries both directions).
* TomTom Orbis Maps (`maps/orbis/traffic`, apiVersion 2): `relative_speed`
* (the same ratio), `road_category` (OpenStreetMap-style, with `_link`
* ramps) and one line per travel direction. Orbis features are decoded into
* the TomTom Maps vocabulary, so nothing downstream tells them apart.
*
* Deps: `pbf@5` (PbfReader) + `@mapbox/vector-tile@3` — both tiny and
* tree-shakeable; decoding happens client-side so the proxy stays a dumb
* binary cache.
@@ -32,35 +23,6 @@ import { VectorTile } from '@mapbox/vector-tile';
*/
const FLOW_LAYER_NAME = 'Traffic flow';
/**
* Orbis `road_category` → the TomTom Maps `road_type` and `road_category`
* the traffic layer classifies roads by. A ramp takes its road's class;
* service roads and tracks stay unmapped, as TomTom Maps tiles left
* parking and private roads out of the drivable set.
*/
const ORBIS_ROAD_CATEGORIES = Object.freeze({
motorway: ['Motorway', 'motorway'],
trunk: ['International road', 'trunk'],
primary: ['Major road', 'primary'],
secondary: ['Secondary road', 'secondary'],
tertiary: ['Connecting road', 'tertiary'],
street: ['Local road', 'street'],
});
/** Road class of a feature, in TomTom Maps terms, from either schema. */
function roadClassOf(props) {
if (typeof props.road_type === 'string')
return [props.road_type, props.road_category ?? null];
const category =
typeof props.road_category === 'string'
? props.road_category.replace(/_link$/, '')
: null;
if (category && Object.hasOwn(ORBIS_ROAD_CATEGORIES, category))
return ORBIS_ROAD_CATEGORIES[category];
// Kept as sent, so the drivable filter drops it by category.
return ['', props.road_category ?? null];
}
/** Decode flow geometry; strict mode distinguishes damaged tiles from valid empty coverage. */
export function decodeFlowTile(data, z, x, y, { strict = false } = {}) {
let layer;
@@ -87,15 +49,13 @@ export function decodeFlowTile(data, z, x, y, { strict = false } = {}) {
const props = feature.properties || {};
const closure =
props.road_closure === true || props.road_closure === 'true';
const orbis =
props.traffic_level === undefined && props.road_type === undefined;
const rawLevel = orbis ? props.relative_speed : props.traffic_level;
const rawLevel = props.traffic_level;
const hasLevel = typeof rawLevel === 'number' && Number.isFinite(rawLevel);
// Skip features we can't color — unless closed (closures render dot-free
// regardless of level, so they stay useful without one).
if (!hasLevel && !closure) continue;
const trafficLevel = hasLevel ? Math.min(1, Math.max(0, rawLevel)) : 0;
const [roadType, roadCategory] = roadClassOf(props);
const roadType = typeof props.road_type === 'string' ? props.road_type : '';
const lines =
geometry.type === 'LineString'
@@ -109,11 +69,10 @@ export function decodeFlowTile(data, z, x, y, { strict = false } = {}) {
coords,
trafficLevel,
roadType,
roadCategory,
roadCategory: props.road_category ?? null,
roadSubcategory: props.road_subcategory ?? null,
closure,
// Orbis draws each travel direction as its own line.
coverage: props.traffic_road_coverage ?? (orbis ? 'one_side' : null),
coverage: props.traffic_road_coverage ?? null,
leftHandTraffic:
props.left_hand_traffic === true ||
props.left_hand_traffic === 'true',
-136
View File
@@ -1,136 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { PbfWriter } from 'pbf';
import { decodeFlowTile } from './flowDecode.js';
import { flowSegmentsToRoads, isDrivableFlowSegment } from './roadModes.js';
/**
* One "Traffic flow" layer; each feature is a two-point line carrying the
* given properties (string, number or boolean values).
*/
function flowTile(features) {
const keys = [];
const values = [];
const tags = features.map((props) =>
Object.entries(props).flatMap(([key, value]) => {
if (!keys.includes(key)) keys.push(key);
values.push(value);
return [keys.indexOf(key), values.length - 1];
}),
);
const writer = new PbfWriter();
writer.writeMessage(
3,
(_, layer) => {
layer.writeVarintField(15, 2);
layer.writeStringField(1, 'Traffic flow');
layer.writeVarintField(5, 4096);
for (const key of keys) layer.writeStringField(3, key);
for (const value of values)
layer.writeMessage(
4,
(_, out) => {
if (typeof value === 'string') out.writeStringField(1, value);
else if (typeof value === 'boolean')
out.writeBooleanField(7, value);
else out.writeDoubleField(3, value);
},
null,
);
tags.forEach((featureTags, i) =>
layer.writeMessage(
2,
(_, feature) => {
feature.writeVarintField(3, 2);
feature.writePackedVarint(2, featureTags);
// MoveTo (100, 100 + i), LineTo +200 east.
feature.writePackedVarint(4, [9, 200, 200 + 2 * i, 10, 400, 0]);
},
null,
),
);
},
null,
);
return writer.finish();
}
const decode = (features) => decodeFlowTile(flowTile(features), 12, 935, 1686);
test('TomTom Maps flow features decode as before', () => {
const [segment] = decode([
{
traffic_level: 0.6,
road_type: 'Major road',
road_category: 'primary',
traffic_road_coverage: 'full',
},
]);
assert.equal(segment.trafficLevel, 0.6);
assert.equal(segment.roadType, 'Major road');
assert.equal(segment.roadCategory, 'primary');
assert.equal(segment.coverage, 'full');
// A TomTom Maps line with no coverage tag still reports none.
assert.equal(
decode([{ traffic_level: 1, road_type: 'Motorway' }])[0].coverage,
null,
);
});
test('Orbis flow features decode into the TomTom Maps road vocabulary', () => {
const segments = decode([
{ relative_speed: 0.42, road_category: 'motorway' },
{ relative_speed: 0.9, road_category: 'trunk_link' },
{
relative_speed: 0.7,
road_category: 'street',
road_subcategory: 'residential',
left_hand_traffic: true,
},
{ relative_speed: 1.4, road_category: 'tertiary' },
{ road_category: 'secondary', road_closure: true },
]);
assert.deepEqual(
segments.map((s) => [s.roadType, s.roadCategory, s.trafficLevel]),
[
['Motorway', 'motorway', 0.42],
['International road', 'trunk', 0.9],
['Local road', 'street', 0.7],
['Connecting road', 'tertiary', 1], // clamped like traffic_level
['Secondary road', 'secondary', 0], // closures need no speed
],
);
assert.equal(segments[2].roadSubcategory, 'residential');
assert.equal(segments[2].leftHandTraffic, true);
assert.equal(segments[4].closure, true);
// Orbis draws one line per travel direction.
assert.ok(segments.every((s) => s.coverage === 'one_side'));
assert.ok(segments.every(isDrivableFlowSegment));
assert.deepEqual(
flowSegmentsToRoads(segments).map((road) => [road.type, road.oneway]),
[
['motorway', 1],
['trunk', 1],
['residential', 1],
['tertiary', 1],
['secondary', 1],
],
);
});
test('Orbis service roads, tracks and speedless lines never become traffic', () => {
const segments = decode([
{ relative_speed: 0.5, road_category: 'service' },
{ relative_speed: 0.5, road_category: 'track' },
{ relative_speed: 0.5 },
{ road_category: 'primary' }, // no speed and not closed: nothing to draw
]);
assert.deepEqual(
segments.map((s) => [s.roadType, s.roadCategory]),
[
['', 'service'],
['', 'track'],
['', null],
],
);
assert.equal(segments.filter(isDrivableFlowSegment).length, 0);
});
+16 -6
View File
@@ -2294,7 +2294,7 @@ test('points show only within their display range', () => {
set.dispose();
});
test('the fire perimeters layer draws holed ground fills and draped fire lines on a viewer of its own', async () => {
test('the fire perimeters layer draws holed ground fills and draped outlines on a viewer of its own', async () => {
const { createFirePerimetersLayer } =
await import('../../layers/perimeters/index.js');
const scene = fakeScene();
@@ -2313,9 +2313,19 @@ test('the fire perimeters layer draws holed ground fills and draped fire lines o
];
const layer = createFirePerimetersLayer({
source: {
getSnapshot: async () => [
{ stableId: 'a', containedPct: 0, polygons: [[outer, hole]] },
],
getSnapshot: async () => ({
at: null,
revision: 'r',
fires: [{ id: 'a', containedPct: 0, anchor: { lon: -108, lat: 35.2 } }],
pieces: [
{
fireId: 'a',
born: null,
polygons: [[outer, hole]],
outline: [outer, hole],
},
],
}),
},
});
layer.init(viewer);
@@ -2336,9 +2346,9 @@ test('the fire perimeters layer draws holed ground fills and draped fire lines o
assert.equal(instance.geometry._polygonHierarchy.holes.length, 1);
const [line] = of(Cesium.GroundPolylinePrimitive);
assert.equal(line.classificationType, Cesium.ClassificationType.BOTH);
assert.equal(line.geometryInstances.length, 1, 'the exterior ring only');
assert.equal(line.geometryInstances.length, 2, 'the hole is outlined too');
assert.equal(line.geometryInstances[0].geometry.width, 2);
assert.equal(line.geometryInstances[0].id.id, 'fire-perimeter:a:0');
assert.equal(line.geometryInstances[0].id.id, 'fire-perimeter:a:line:0');
layer.destroy();
assert.equal(scene.added.length, 0);
});
-111
View File
@@ -262,117 +262,6 @@ test('traffic refuses cross-site requests in dev and preview before spending the
}
});
test('traffic falls back to the Orbis flow endpoint when TomTom refuses the key on the TomTom Maps one', async (t) => {
isolate(t, { TOMTOM_API_KEY: 'orbis-only', TOMTOM_DAILY_TILE_BUDGET: '' });
const calls = [];
t.mock.method(globalThis, 'fetch', async (raw, init = {}) => {
const url = new URL(raw);
const orbis = url.pathname.startsWith('/maps/orbis/');
calls.push(orbis ? 'orbis' : 'legacy');
if (orbis) {
assert.match(
url.pathname,
/^\/maps\/orbis\/traffic\/flow\/vector\/tile\/8\/[12]\/1$/,
'no .pbf suffix or flow style on Orbis',
);
assert.equal(url.searchParams.get('apiVersion'), '2');
assert.equal(url.searchParams.get('key'), null);
assert.equal(init.headers['TomTom-Api-Key'], 'orbis-only');
return new Response(new Uint8Array([4, 5, 6]));
}
assert.equal(url.pathname, '/traffic/map/4/tile/flow/relative/8/1/1.pbf');
assert.equal(url.searchParams.get('key'), 'orbis-only');
return Response.json(
{ detailedError: { code: 'Forbidden' } },
{ status: 403 },
);
});
const request = install(tomtomProxy());
const first = await request('/flow/8/1/1.pbf');
assert.equal(first.status, 200);
assert.equal(first.headers['x-tomtom-cache'], 'MISS');
assert.deepEqual([...first.body], [4, 5, 6]);
assert.deepEqual(calls, ['legacy', 'orbis']);
assert.equal(json(await request('/status')).keyRejected, false);
// Both attempts were real upstream requests.
assert.equal(json(await request('/status')).dailyCount, 2);
// The working endpoint is remembered: no second 403 per tile.
calls.length = 0;
process.env.TOMTOM_API_KEY = 'orbis-only';
assert.equal((await request('/flow/8/2/1.pbf')).status, 200);
assert.deepEqual(calls, ['orbis']);
// A new key starts over on the TomTom Maps endpoint.
calls.length = 0;
process.env.TOMTOM_API_KEY = 'another-key';
t.mock.method(globalThis, 'fetch', async (raw) => {
calls.push(
new URL(raw).pathname.startsWith('/maps/orbis/') ? 'orbis' : 'legacy',
);
return new Response(new Uint8Array([7]));
});
assert.equal((await request('/flow/8/3/1.pbf')).status, 200);
assert.deepEqual(calls, ['legacy']);
});
test('traffic names a key both TomTom flow endpoints refuse and stops spending the budget on it', async (t) => {
isolate(t, { TOMTOM_API_KEY: 'refused', TOMTOM_DAILY_TILE_BUDGET: '' });
let now = Date.UTC(2026, 10, 20, 12);
t.mock.method(Date, 'now', () => now);
let calls = 0;
let status = 403;
t.mock.method(globalThis, 'fetch', async () => {
calls++;
return status === 200
? new Response(new Uint8Array([1]))
: new Response('{}', { status });
});
const request = install(tomtomProxy());
assert.equal(json(await request('/status')).keyRejected, false);
const refused = await request('/flow/8/1/1.pbf');
assert.equal(refused.status, 403);
assert.deepEqual(json(refused), { error: 'key_rejected' });
assert.equal(calls, 2, 'one attempt per endpoint');
// Other tiles answer from the verdict, without asking TomTom again.
for (const x of [2, 3, 4])
assert.deepEqual(json(await request(`/flow/8/${x}/1.pbf`)), {
error: 'key_rejected',
});
assert.equal(calls, 2);
const state = json(await request('/status'));
assert.equal(state.hasKey, true);
assert.equal(state.keyRejected, true);
assert.equal(state.dailyCount, 2);
// The verdict expires, so a key fixed at TomTom recovers without a restart.
now += 5 * 60_000 + 1;
status = 200;
assert.equal((await request('/flow/8/1/1.pbf')).status, 200);
assert.equal(json(await request('/status')).keyRejected, false);
// A replaced key is tried at once.
status = 403;
now += 120_001;
assert.equal((await request('/flow/8/5/1.pbf')).status, 403);
process.env.TOMTOM_API_KEY = 'replacement';
status = 200;
assert.equal((await request('/flow/8/6/1.pbf')).status, 200);
});
test('traffic keeps an ordinary upstream failure on one endpoint and reports it as upstream', async (t) => {
isolate(t, { TOMTOM_API_KEY: 'fixture-key', TOMTOM_DAILY_TILE_BUDGET: '' });
const calls = [];
t.mock.method(globalThis, 'fetch', async (raw) => {
calls.push(
new URL(raw).pathname.startsWith('/maps/orbis/') ? 'orbis' : 'legacy',
);
return new Response('', { status: 500 });
});
const request = install(tomtomProxy());
const res = await request('/flow/8/1/1.pbf');
assert.equal(res.status, 502);
assert.deepEqual(json(res), { error: 'upstream' });
assert.deepEqual(calls, ['legacy']);
assert.equal(json(await request('/status')).keyRejected, false);
});
test('traffic middleware answers 502 to an oversized tile without caching it', async (t) => {
isolate(t, { TOMTOM_API_KEY: 'fixture-key', TOMTOM_DAILY_TILE_BUDGET: '' });
const bodies = [];
+23 -34
View File
@@ -248,7 +248,8 @@ export const getFirePerimeters = defineTool({
title: 'Wildfire perimeters',
description:
'Mapped wildfire perimeters from the US WFIGS service in an area, ' +
'largest first, with size, containment, cause and personnel.',
'largest first, with size, containment, cause, personnel and when ' +
'each last grew.',
inputSchema: {
type: 'object',
properties: { area: AREA_SCHEMA, limit: LIMIT_SCHEMA },
@@ -258,19 +259,27 @@ export const getFirePerimeters = defineTool({
requires: ['perimeters'],
async run(args, { services, signal }) {
const area = await resolveArea(args.area, { services, signal });
const snapshot =
typeof services.perimeters.getSnapshotDetail === 'function'
? await services.perimeters.getSnapshotDetail({ signal })
: { rows: await services.perimeters.getSnapshot({ signal }) };
const snapshot = await services.perimeters.getSnapshot({ signal });
// The proxy answers from its last snapshot, marked stale, while WFIGS is
// unreachable.
const stale = snapshot.stale === true;
const rows = snapshot.rows
.filter((fire) => polygonsTouchArea(fire.polygons, area))
.map((fire) => ({ fire, point: polygonCenter(fire.polygons) }))
.filter(({ point }) => point)
.map(({ fire, point }) => ({
id: fire.stableId,
// A fire is in the area when a piece of its burned area is.
const touching = new Set();
for (const piece of snapshot.pieces || [])
if (
!touching.has(piece.fireId) &&
polygonsTouchArea(piece.polygons, area)
)
touching.add(piece.fireId);
const rows = (snapshot.fires || [])
.filter(
(fire) =>
touching.has(fire.id) &&
Number.isFinite(fire.anchor?.lat) &&
Number.isFinite(fire.anchor?.lon),
)
.map((fire) => ({
id: fire.id,
name: fire.name,
acres: round(fire.acres, 0),
contained_pct: fire.containedPct,
@@ -282,8 +291,9 @@ export const getFirePerimeters = defineTool({
personnel: fire.personnel,
discovered: isoTime(fire.discoveredTime),
updated: isoTime(fire.updatedTime),
lat: round(point.lat, 5),
lon: round(point.lon, 5),
last_growth: isoTime(fire.lastGrowthTime),
lat: round(fire.anchor.lat, 5),
lon: round(fire.anchor.lon, 5),
}))
.sort((a, b) => (b.acres ?? 0) - (a.acres ?? 0));
return {
@@ -300,27 +310,6 @@ export const getFirePerimeters = defineTool({
},
});
/** Average outer-ring vertices, using a circular longitude mean at the dateline. */
function polygonCenter(polygons) {
let lat = 0;
let sinLon = 0;
let cosLon = 0;
let count = 0;
const toRad = Math.PI / 180;
for (const polygon of polygons || []) {
for (const [x, y] of polygon?.[0] || []) {
if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
sinLon += Math.sin(x * toRad);
cosLon += Math.cos(x * toRad);
lat += y;
count += 1;
}
}
return count
? { lat: lat / count, lon: Math.atan2(sinLon, cosLon) / toRad }
: null;
}
export const getTerrainHeight = defineTool({
name: 'get_terrain_height',
title: 'Terrain height',
+116 -77
View File
@@ -7,6 +7,7 @@ import {
defineTool,
ToolError,
} from '../index.js';
import { firePerimeterSnapshot } from '../../layers/perimeters/records.js';
const conditions = {
observedAt: '2026-10-01T19:15:00.000Z',
@@ -161,11 +162,12 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
[lon + 0.1, lat],
[lon + 0.1, lat + 0.1],
[lon, lat + 0.1],
[lon, lat],
],
];
const perimeters = {
async getSnapshot() {
return [
return firePerimeterSnapshot([
{
stableId: 'small',
name: 'Small Fire',
@@ -179,6 +181,7 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
personnel: 20,
discoveredTime: Date.UTC(2026, 8, 1),
updatedTime: null,
polygonTime: Date.UTC(2026, 8, 2, 6),
polygons: [ring(-118.5, 35.2)],
},
{
@@ -195,7 +198,7 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
polygons: [ring(-80, 30)],
},
{ stableId: 'empty', name: 'No Outline', acres: 1, polygons: [] },
];
]);
},
};
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
@@ -222,6 +225,7 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
personnel: 20,
discovered: '2026-09-01T00:00:00.000Z',
updated: null,
last_growth: '2026-09-02T06:00:00.000Z',
lat: 35.25,
lon: -118.45,
});
@@ -229,24 +233,25 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
test('fire perimeter queries include dateline interiors and exclude the opposite meridian', async () => {
const perimeters = {
getSnapshot: async () => [
{
stableId: 'dateline',
name: 'Dateline Fire',
acres: 100,
polygons: [
[
getSnapshot: async () =>
firePerimeterSnapshot([
{
stableId: 'dateline',
name: 'Dateline Fire',
acres: 100,
polygons: [
[
[179, -2],
[-179, -2],
[-179, 2],
[179, 2],
[179, -2],
[
[179, -2],
[-179, -2],
[-179, 2],
[179, 2],
[179, -2],
],
],
],
],
},
],
},
]),
};
const catalog = catalogWith({ perimeters });
for (const area of [
@@ -268,45 +273,46 @@ test('fire perimeter queries include dateline interiors and exclude the opposite
test('fire perimeter coordinates stay at the dateline for closed and multipart outlines', async () => {
const perimeters = {
getSnapshot: async () => [
{
stableId: 'closed',
acres: 100,
polygons: [
[
getSnapshot: async () =>
firePerimeterSnapshot([
{
stableId: 'closed',
acres: 100,
polygons: [
[
[179, -2],
[-179, -2],
[-179, 2],
[179, 2],
[179, -2],
[
[179, -2],
[-179, -2],
[-179, 2],
[179, 2],
[179, -2],
],
],
],
],
},
{
stableId: 'multipart',
acres: 50,
polygons: [
[
},
{
stableId: 'multipart',
acres: 50,
polygons: [
[
[179, -1],
[179.5, -1],
[179.5, 1],
[179, 1],
[
[179, -1],
[179.5, -1],
[179.5, 1],
[179, 1],
],
],
[
[
[-179.5, -1],
[-179, -1],
[-179, 1],
[-179.5, 1],
],
],
],
[
[
[-179.5, -1],
[-179, -1],
[-179, 1],
[-179.5, 1],
],
],
],
},
],
},
]),
};
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
area: { bbox: [178, -3, -178, 3] },
@@ -759,23 +765,24 @@ test('brief sections use a named place at its own point', async () => {
test('a fire perimeter enclosing the whole area is found', async () => {
const perimeters = {
getSnapshot: async () => [
{
stableId: 'big',
name: 'Big Fire',
acres: 250000,
polygons: [
[
getSnapshot: async () =>
firePerimeterSnapshot([
{
stableId: 'big',
name: 'Big Fire',
acres: 250000,
polygons: [
[
[-122, 38],
[-120, 38],
[-120, 40],
[-122, 40],
[
[-122, 38],
[-120, 38],
[-120, 40],
[-122, 40],
],
],
],
],
},
],
},
]),
};
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
area: { bbox: [-121.2, 38.9, -120.8, 39.1] },
@@ -883,19 +890,11 @@ test('stale fire perimeters say so, with when they were fetched', async () => {
],
];
const perimeters = {
getSnapshot: async () => [],
getSnapshotDetail: async () => ({
rows: [
{
stableId: 'held',
name: 'Held Fire',
acres: 300,
polygons: [ring],
},
],
stale: true,
fetchedAt,
}),
getSnapshot: async () =>
firePerimeterSnapshot(
[{ stableId: 'held', name: 'Held Fire', acres: 300, polygons: [ring] }],
{ stale: true, fetchedAt },
),
};
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
area: { bbox: [-120, 34, -117, 36] },
@@ -907,3 +906,43 @@ test('stale fire perimeters say so, with when they were fetched', async () => {
assert.equal(result.data.stale, true);
assert.equal(result.data.retrieved_at, new Date(fetchedAt).toISOString());
});
test('a fire is in the area when one of its pieces is', async () => {
const square = (lon, lat) => [
[
[lon, lat],
[lon + 0.1, lat],
[lon + 0.1, lat + 0.1],
[lon, lat],
],
];
const fire = (id, lon, lat) => ({
id,
name: id,
acres: 10,
lastGrowthTime: null,
anchor: { lon, lat },
});
const perimeters = {
getSnapshot: async () => ({
at: null,
stale: false,
fetchedAt: null,
revision: '',
note: null,
fires: [fire('split', -80, 30), fire('unmapped', -118.5, 35.2)],
pieces: [
{ fireId: 'split', born: null, polygons: [square(-80, 30)] },
{ fireId: 'split', born: null, polygons: [square(-118.5, 35.2)] },
],
}),
};
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
area: { bbox: [-120, 34, -117, 36] },
});
assert.deepEqual(
result.data.rows.map(({ id, lat, lon }) => [id, lat, lon]),
[['split', 30, -80]],
'placed at its card anchor; a fire with no pieces is not mapped',
);
});
+4 -16
View File
@@ -92,19 +92,6 @@ export function compassName(deg) {
return COMPASS[Math.round((((deg % 360) + 360) % 360) / 45) % 8];
}
// The middle of a perimeter's first ring, close enough for "how far".
function perimeterMiddle(row) {
const ring = row?.polygons?.[0]?.[0];
if (!Array.isArray(ring) || !ring.length) return null;
let lat = 0;
let lon = 0;
for (const [x, y] of ring) {
lon += x;
lat += y;
}
return { lat: lat / ring.length, lon: lon / ring.length };
}
/** A storm as "Hurricane Melissa": its class in words when the code has them. */
function stormTitle(storm) {
const word = codeWord('classification', storm.classification);
@@ -129,7 +116,7 @@ export async function hazardsNear(
{ fires: withFires = false, force = false } = {},
) {
const here = { lat, lon };
const [quakeRows, stormSnap, perimeterRows, fireSnap] = await Promise.all([
const [quakeRows, stormSnap, perimeterSnap, fireSnap] = await Promise.all([
quakes(force),
storms(force),
perimeters(force),
@@ -171,8 +158,9 @@ export async function hazardsNear(
at,
});
}
for (const fire of Array.isArray(perimeterRows) ? perimeterRows : []) {
const at = perimeterMiddle(fire);
for (const fire of perimeterSnap?.fires || []) {
// The point the fire's card stands on, close enough for "how far".
const at = fire.anchor;
if (!at || !(distanceKm(here, at) <= radiusKm)) continue;
const acres = Number(fire.acres);
add({
+37
View File
@@ -0,0 +1,37 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { hazardsNear } from './spotConditions.js';
test('a wildfire is placed at its card anchor, not its first ring', async (t) => {
// Two polygons: the larger one, far from the first, carries the anchor.
const square = (lon, lat, size) => [
[
[lon, lat],
[lon + size, lat],
[lon + size, lat + size],
[lon, lat + size],
[lon, lat],
],
];
t.mock.method(globalThis, 'fetch', async (url) =>
String(url) === '/api/fire-perimeters'
? Response.json({
rows: [
{
stableId: 'fire',
name: 'Fixture Fire',
acres: 1200,
containedPct: 30,
updatedTime: Date.now() - 3600000,
polygons: [square(-110, 35, 0.01), square(-108, 35, 0.2)],
},
],
})
: new Response('down', { status: 503 }),
);
const near = await hazardsNear(35.1, -107.9, 30, { force: true });
const fires = near.filter(({ kind }) => kind === 'wildfire');
assert.equal(fires.length, 1);
assert.equal(fires[0].title, 'Fixture Fire');
assert.ok(fires[0].distanceKm < 5, `${fires[0].distanceKm} km`);
});
+2 -1
View File
@@ -63,7 +63,8 @@ test('the complete Realtime tool payload pins the manifest-generated layer relea
// The Cyber HUD layout leaves set_hud's layout enum (its sonar is a
// visual style; set_cyber_sonar is excluded above).
// The Space Missions panel adds one panel target.
'09abe70ef3a1fc4320e25cff997dd3b04db7e78ff31b8530e17bbbbb8156b4c6',
// Fire Perimeters queries add lastGrowthTime.
'2be49b7634a7b74b756a68cf80835ee36411e087edb549eb39f1ce7310afe60f',
);
});
+1
View File
@@ -234,6 +234,7 @@ const layers = [
behavior: ['t'],
complexity: ['t'],
discoveredTime: ['ms'],
lastGrowthTime: ['ms'],
},
timeField: 'discoveredTime',
},