From 015bf25a799782f5287199278c6b50d4bebf2252 Mon Sep 17 00:00:00 2001 From: Renzo Will Date: Fri, 16 Oct 2026 06:08:45 +1000 Subject: [PATCH] feat(transit): add Cairns and Adelaide Metro; mode hints for TransLink MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - translink-cairns: TransLink CNS vehicle positions (keyless, CC BY 4.0, same open-data page as SEQ). - adelaide-metro: Adelaide Metro GTFS-R vehicle positions (keyless, CC BY 4.0 per the data.sa.gov.au catalogue). Its gateway negotiates on Accept and returns base64 protobuf as JSON for the proxy's default list, so the feed asks for application/x-google-protobuf. - TransLink route ids now resolve rail (station-pair codes), the Gold Coast light rail (L1) and ferries (F*, SMBI); buses, Brisbane Metro and the SHUT rail-replacement bus stay on the bus default. Adelaide trains, trams and the SeaLink ferry resolve from its static route list. Both rule sets checked against the operators' routes.txt. - Credits: "Translink, Department of Transport and Main Roads" and "Adelaide Metro – Department for Infrastructure and Transport, South Australia", each with its CC BY 4.0 link (generated per feed by transitFeedCredit). DATA_SOURCES rows follow the transit row style. Co-Authored-By: Claude Opus 5.5 (1M context) --- DATA_SOURCES.md | 5 +- scripts/format-scope.json | 1 + src/data/transitFeeds.js | 97 ++++++++++++++++- src/data/transitFeedsAustralia.test.mjs | 139 ++++++++++++++++++++++++ 4 files changed, 239 insertions(+), 3 deletions(-) create mode 100644 src/data/transitFeedsAustralia.test.mjs diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index a4035f1754..62dc3d6c81 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -85,7 +85,8 @@ How to read this: | **Metro Transit** (Metropolitan Council) | Transit layer live vehicles, Minneapolis–St Paul | Metro Transit / Metropolitan Council open realtime vehicle data, used for the live view; published for developer use and not against their use. | Attribution to Metro Transit / Metropolitan Council (courtesy text) | | **OVapi / Stichting OpenGeo** | Transit layer live vehicles, Netherlands | OVapi / Stichting OpenGeo open realtime vehicle data, used for the live view; published for developer use and not against their use. The client sends a User-Agent and conditional requests. | Attribution to OVapi / Stichting OpenGeo (courtesy text) | | **Entur** (api.entur.io) | Transit layer live vehicles, Norway | Entur open realtime vehicle data, used for the live view; published for developer use and not against their use. The client sends the `ET-Client-Name` identifying header. | Attribution to Entur (courtesy text) | -| **TransLink** (Queensland Government) | Transit layer live vehicles, South East Queensland | TransLink / Queensland Government open realtime vehicle data, used for the live view; published for developer use and not against their use. | Attribution to TransLink / Queensland Government (courtesy text) | +| **TransLink** (Queensland Government) | Transit layer live vehicles, South East Queensland and Cairns | TransLink / Queensland Government open realtime vehicle data, used for the live view; published for developer use and not against their use. | Attribution to Translink, Department of Transport and Main Roads (courtesy text) | +| **Adelaide Metro** (gtfs.adelaidemetro.com.au) | Transit layer live vehicles, Adelaide | Adelaide Metro / Department for Infrastructure and Transport (South Australia) open realtime vehicle data, used for the live view; published for developer use and not against their use. | Attribution to Adelaide Metro – Department for Infrastructure and Transport, South Australia (courtesy text) | | **HSL** (realtime.hsl.fi) | Transit layer live vehicles, Helsinki | HSL (Helsinki Region Transport) open realtime vehicle data, used for the live view; published for developer use and not against their use. | Attribution to HSL (Helsinki Region Transport) (courtesy text) | | **TTC** (bustime.ttc.ca) | Transit layer live vehicles, Toronto — surface vehicles (buses and streetcars) only | Toronto Transit Commission BusTime open realtime vehicle data, published through City of Toronto Open Data and used for the live view. The subway publishes no vehicle positions, so Lines 1/2/4 are absent rather than inferred. | Attribution to Toronto Transit Commission — City of Toronto Open Data, under the Open Government Licence – Toronto | | **MiWay** (miapp.ca) | Transit layer live vehicles, Mississauga ON | MiWay open realtime vehicle data, published by the City of Mississauga under its Open Data Terms of Use, used for the live view. The licence is revocable and asks that the Terms of Use link travel with the data. | Attribution to MiWay — City of Mississauga Open Data, linked to the Terms of Use | @@ -179,7 +180,7 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei - **City of Toronto RESCU cameras.** Keyless. The camera list is the City's public `tmcearthcameras.json` on `opendata.toronto.ca` (dataset "Traffic Cameras", Transportation Services), served as JSONP and unwrapped with an anchored pattern. This is the municipal network the Ontario 511 pack does not carry: downtown arterials plus the Gardiner, DVP, Allen and Lake Shore. The list publishes no frame URL, so frame URLs are BUILT from the documented `CameraImages/loc####.jpg` convention and a strictly-digits camera number, pinning the frame proxy to the portal origin by construction; the list fetch refuses redirects and bounds the body it buffers. Frames are fetched at request time and never stored or redistributed. The dataset publishes no camera facing: the `D1`-`D4` fields are the directions of the *comparison* images (static reference stills captured in 2016 under a different path), not a bearing for the live pan-tilt-zoom frame, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. A camera that is temporarily out of service still answers 200 with a byte-identical "Image Unavailable" placeholder rather than an error (about 6% of the network at any moment), so such a camera reads as healthy; the frame it shows is the agency's, not a synthesized one. The licence requires the attribution statement above. Disable with `CCTV_TORONTO_ENABLED=0`. - **Autostrada del Brennero (A22) webcams.** Keyless. The camera list is one request to the Open Data Hub tourism API (`tourism.api.opendatahub.com/v1/WebcamInfo?source=a22`), run by NOI Techpark in South Tyrol, which republishes Autobrennero's own list of 13 motorway webcams with coordinates and kilometre markers. Frames are the operator's stills on `www.autobrennero.it/WebCamImg/km.jpg`, refreshed about once a minute, and only the exact image for each camera's kilometre is registered. The feed names no bearing, so headings use the id-hash fallback at low confidence. The road climbs from about 20 m in the Po valley to about 1,370 m at the Brenner Pass, so each camera's ground elevation comes from a per-kilometre table sampled from the Copernicus GLO-90 DEM (via Open-Meteo's elevation API); a camera not in the table uses a 200 m prior. The Open Data Hub tags every record CC0 (`ClosedData: false`, Autobrennero as licence holder), but that tag is the aggregator's metadata and Autobrennero publishes no terms of its own for the images, so they are credited to the operator as a courtesy and are not redistributed. Frames are fetched at request time and never stored. Disable with `CCTV_A22_ENABLED=0`. - **Camera frame content.** Public camera frames can contain people, vehicles and license plates, and the camera layer does nothing with them beyond putting them on the map. A successful upstream response is relayed as the provider served it: nothing in the camera pipeline blurs, redacts, enhances or restores it, and nothing there runs face, plate or object detection or otherwise recognises or classifies what is in the picture. (The ALPR layer described below maps where plate-reader cameras are, from locations contributors tagged in OpenStreetMap; it reads nothing from any camera frame.) When an upstream has no frame for a camera, what you see instead is a Google Street View still or the app's own placeholder card; the panel's source badge names which of them you are looking at, and a refresh that fails after a frame has arrived leaves the last good picture on screen rather than replacing it. The browser resamples each frame for display: onto a fixed 1920x1080 surface for the camera's projection plane in the scene, and onto a 192x108 canvas for the small ambient card. That scaling is the only change made to the picture, and the only pixels the camera layer reads back are a 64x36 downscale hashed to tell whether the picture has changed. Live streams are piped through; the still path reads the image into memory to pass it on — TxDOT wraps its JPEG in a JSON envelope, which is decoded there — and no frame is written to disk (the disk cache, `.gev-cache/`, holds feed JSON for other layers and never camera imagery). Outside that pipeline, the voice assistant is the one feature that sends imagery anywhere: when it answers a question about what is in view it may attach a downscaled screenshot of the rendered scene — including any camera plane on screen — to the request it sends to the voice model. Frames are fetched only from server-registered camera URLs — a client cannot hand the proxy a URL (see [SECURITY.md](SECURITY.md)). What the app does stays inside the line README draws: no named-person search, no face recognition, no tracking individuals. -- **Transit (GTFS-Realtime).** The proxy requests only registered operator feeds, validates redirects, bounds responses, and uses conditional requests, short snapshot caching and failure backoff. All sixteen registered regions are live-enabled; each can be disabled independently. Vehicles use delayed playback between reports, with report age and waiting states shown separately. Session-local selected trails are available for every feed. MBTA additionally retains up to 15 minutes of recently observed positions in the running proxy, so available history can survive a browser reload; server restart clears it. History reads never fetch upstream, and other feeds have no proxy retention. Nothing is archived to disk or collected in the background. Operator text credits are included as a courtesy and do not imply endorsement. Heights are aligned to work with Google 3D tiles; subway markers are shown at street level because these feeds do not supply depth. The TTC feed is BusTime, the surface system: it carries buses and streetcars and no subway at all. About four in ten of its vehicles report no route at all (unassigned or deadheading), and those are shown with the feed default rather than a route-established mode. It sends no ETag or Last-Modified, so its conditional requests fall through to the ordinary snapshot cache. Three Golden Horseshoe neighbours run alongside it — MiWay, Hamilton HSR and Durham Region Transit — each bus-only and each polled only near its own region. Durham Region Transit publishes no bearing on any vehicle, so those sprites take their heading from observed movement like any other feed that omits it. Guelph, Kingston and Barrie extend the same pattern eastward and north. Hamilton, Guelph, Burlington and YRT publish route ids that are not the number on the vehicle, so those entries carry a route-name table taken from each operator’s own published GTFS; any id missing from a table renders unchanged rather than blank. A label is never invented: YRT runs a route `9101` that appears nowhere in its published routes, so it stays as the feed sends it. Burlington’s is the one that cannot be shortcut: `351` is route 1 while `3510` is route 10, so the table is a real join rather than a trimmed prefix. GO Transit / Metrolinx is deliberately absent: its REALTIME feed requires an API key issued by manual review, which the keyless admission rule excludes (its static schedule download is keyless, but carries no vehicle positions). Barrie and YRT/Viva each invite acceptance of their licence through a form, and each licence also states that using the data is itself acceptance; this deployment relies on that clause, which is recorded in both entries. Grand River Transit in Waterloo is absent for a different reason: it answers, but its feed header was months stale and it publishes no per-vehicle timestamps, so it would render vehicles that look live and are not. Ottawa’s OC Transpo falls to the same keyless admission rule as GO Transit — its realtime feed requires an API key. London Transit and Thunder Bay Transit publish vehicle positions over plain HTTP with no HTTPS endpoint available. Every other Ontario system — Brampton, Oakville, Niagara, Milton, Windsor, Greater Sudbury, UP Express and a dozen smaller operators — publishes static GTFS schedules only, with no realtime vehicle positions to register. Between the nine included and these exclusions, every Ontario realtime vehicle-position feed catalogued in the Mobility Database is accounted for. +- **Transit (GTFS-Realtime).** The proxy requests only registered operator feeds, validates redirects, bounds responses, and uses conditional requests, short snapshot caching and failure backoff. All eighteen registered regions are live-enabled; each can be disabled independently. The Australian feeds (TransLink South East Queensland and Cairns, Adelaide Metro) are keyless and published under CC BY 4.0; the passage each rests on is quoted in `terms` in `src/data/transitFeeds.js`. Vehicles use delayed playback between reports, with report age and waiting states shown separately. Session-local selected trails are available for every feed. MBTA additionally retains up to 15 minutes of recently observed positions in the running proxy, so available history can survive a browser reload; server restart clears it. History reads never fetch upstream, and other feeds have no proxy retention. Nothing is archived to disk or collected in the background. Operator text credits are included as a courtesy and do not imply endorsement. Heights are aligned to work with Google 3D tiles; subway markers are shown at street level because these feeds do not supply depth. The TTC feed is BusTime, the surface system: it carries buses and streetcars and no subway at all. About four in ten of its vehicles report no route at all (unassigned or deadheading), and those are shown with the feed default rather than a route-established mode. It sends no ETag or Last-Modified, so its conditional requests fall through to the ordinary snapshot cache. Three Golden Horseshoe neighbours run alongside it — MiWay, Hamilton HSR and Durham Region Transit — each bus-only and each polled only near its own region. Durham Region Transit publishes no bearing on any vehicle, so those sprites take their heading from observed movement like any other feed that omits it. Guelph, Kingston and Barrie extend the same pattern eastward and north. Hamilton, Guelph, Burlington and YRT publish route ids that are not the number on the vehicle, so those entries carry a route-name table taken from each operator’s own published GTFS; any id missing from a table renders unchanged rather than blank. A label is never invented: YRT runs a route `9101` that appears nowhere in its published routes, so it stays as the feed sends it. Burlington’s is the one that cannot be shortcut: `351` is route 1 while `3510` is route 10, so the table is a real join rather than a trimmed prefix. GO Transit / Metrolinx is deliberately absent: its REALTIME feed requires an API key issued by manual review, which the keyless admission rule excludes (its static schedule download is keyless, but carries no vehicle positions). Barrie and YRT/Viva each invite acceptance of their licence through a form, and each licence also states that using the data is itself acceptance; this deployment relies on that clause, which is recorded in both entries. Grand River Transit in Waterloo is absent for a different reason: it answers, but its feed header was months stale and it publishes no per-vehicle timestamps, so it would render vehicles that look live and are not. Ottawa’s OC Transpo falls to the same keyless admission rule as GO Transit — its realtime feed requires an API key. London Transit and Thunder Bay Transit publish vehicle positions over plain HTTP with no HTTPS endpoint available. Every other Ontario system — Brampton, Oakville, Niagara, Milton, Windsor, Greater Sudbury, UP Express and a dozen smaller operators — publishes static GTFS schedules only, with no realtime vehicle positions to register. Between the nine included and these exclusions, every Ontario realtime vehicle-position feed catalogued in the Mobility Database is accounted for. - **Radio Browser.** `/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; schema-valid responses whose rows all fail the product's health policy do not count as successful queries. A usable partial cold catalog is explicitly `DEGRADED`, and non-array or empty successful 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 (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. diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 2d1593a0e7..bcc35dd31f 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -766,6 +766,7 @@ "server/providers/transitHistory.test.mjs", "src/data/transitFeeds.js", "src/data/transitFeeds.test.mjs", + "src/data/transitFeedsAustralia.test.mjs", "src/data/transitProxy.js", "src/data/transitProxy.test.mjs", "src/data/gtfsRealtime.js", diff --git a/src/data/transitFeeds.js b/src/data/transitFeeds.js index b8476a6ee8..bcbf213e5c 100644 --- a/src/data/transitFeeds.js +++ b/src/data/transitFeeds.js @@ -376,6 +376,54 @@ function burlingtonRouteLabel(routeId) { return BURLINGTON_ROUTE_NAMES[routeId] || routeId; } +/** + * TransLink (Queensland) route ids are `-`. Rail lines are two + * two-letter station codes (`BRBN`, `SHCL`), ferries are `F` plus the + * Southern Moreton Bay Islands service `SMBI`, and the Gold Coast light rail + * is `L1`. `SHUT` is the rail-replacement bus. Everything else is a bus, left + * to the feed default so movement plausibility treats it as a guess. + * @param {string|null} routeId + * @returns {string} + */ +function translinkRouteMode(routeId) { + if (!routeId) return 'unknown'; + const route = routeId.replace(/-\d+$/, ''); + if (/^F\d+$/.test(route) || route === 'SMBI') return 'ferry'; + if (route === 'L1') return 'tram'; + if (/^[A-Z]{4}$/.test(route) && route !== 'SHUT') return 'rail'; + return 'unknown'; +} + +/** Adelaide Metro train and tram route ids, from its static routes.txt. */ +const ADELAIDE_RAIL_ROUTES = new Set([ + 'BEL', + 'FLNDRS', + 'GAW', + 'GAWC', + 'GRNG', + 'NOAR', + 'OSBORN', + 'OUTHA', + 'PTDOCK', + 'SALIS', + 'SEAFRD', +]); +const ADELAIDE_TRAM_ROUTES = new Set(['BTANIC', 'FESTVL', 'GLNELG']); + +/** + * Adelaide Metro route ids are the line codes; all-letter bus routes exist + * (`INDSTA`), so trains and trams are listed rather than pattern-matched. + * @param {string|null} routeId + * @returns {string} + */ +function adelaideMetroRouteMode(routeId) { + if (!routeId) return 'unknown'; + if (ADELAIDE_RAIL_ROUTES.has(routeId)) return 'rail'; + if (ADELAIDE_TRAM_ROUTES.has(routeId)) return 'tram'; + if (routeId === 'SEALNK') return 'ferry'; + return 'unknown'; +} + /** * Registry of feeds. Order is presentation order in the stats/credit text. * `loadRadiusKm` is the distance from `center` inside which the feed is polled. @@ -522,7 +570,7 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([ url: 'https://gtfsrt.api.translink.com.au/api/realtime/seq/VehiclePositions', license: 'CC BY 4.0', licenseUrl: 'https://translink.com.au/about-translink/open-data', - attribution: 'TransLink — Queensland Government (CC BY 4.0)', + attribution: 'Translink, Department of Transport and Main Roads', defaultEnabled: true, terms: Object.freeze({ quote: @@ -530,6 +578,53 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([ note: 'No key, no stated rate limit, no caching rule. Logos and network imagery need separate approval, so the credit is text only.', }), defaultMode: 'bus', + routeMode: translinkRouteMode, + }), + Object.freeze({ + id: 'translink-cairns', + name: 'TransLink', + operator: 'TransLink (Queensland Government)', + region: 'Cairns, Australia', + center: Object.freeze({ lat: -16.9186, lon: 145.7781 }), + loadRadiusKm: 60, + url: 'https://gtfsrt.api.translink.com.au/api/realtime/CNS/VehiclePositions', + license: 'CC BY 4.0', + licenseUrl: 'https://translink.com.au/about-translink/open-data', + attribution: 'Translink, Department of Transport and Main Roads', + defaultEnabled: true, + terms: Object.freeze({ + quote: + 'Our data is licensed under a Creative Commons Attribution 4.0 International License. Authentication is not required to use the feed.', + note: 'The same open-data page lists Cairns (CNS) vehicle positions beside South East Queensland; same terms, text-only credit.', + }), + defaultMode: 'bus', + routeMode: translinkRouteMode, + }), + Object.freeze({ + id: 'adelaide-metro', + name: 'Adelaide Metro', + operator: + 'Adelaide Metro (Department for Infrastructure and Transport, South Australia)', + region: 'Adelaide, Australia', + center: Object.freeze({ lat: -34.9285, lon: 138.6007 }), + loadRadiusKm: 80, + url: 'https://gtfs.adelaidemetro.com.au/v1/realtime/vehicle_positions', + // The gateway negotiates on Accept: the proxy's default list gets + // application/json carrying base64 protobuf; its own type gets raw bytes. + headers: Object.freeze({ Accept: 'application/x-google-protobuf' }), + license: 'CC BY 4.0', + licenseUrl: + 'https://data.sa.gov.au/data/dataset/adelaide-metro-real-time-passenger-information', + attribution: + 'Adelaide Metro – Department for Infrastructure and Transport, South Australia', + defaultEnabled: true, + terms: Object.freeze({ + quote: + 'Adelaide Metro provides Real-Time information in SIRI and GTFS-R format', + note: 'Quoted from the data.sa.gov.au catalogue entry "Adelaide Metro Real-Time Passenger Information", published by the Department for Infrastructure and Transport under Creative Commons Attribution 4.0. The feed needs no key (its API description declares no security scheme) and is marked BETA, subject to change. adelaidemetro.com.au refuses automated readers (HTTP 403).', + }), + defaultMode: 'bus', + routeMode: adelaideMetroRouteMode, }), Object.freeze({ id: 'ttc-toronto', diff --git a/src/data/transitFeedsAustralia.test.mjs b/src/data/transitFeedsAustralia.test.mjs new file mode 100644 index 0000000000..decf32baca --- /dev/null +++ b/src/data/transitFeedsAustralia.test.mjs @@ -0,0 +1,139 @@ +import { readFileSync } from 'node:fs'; +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { transitFeedCredit } from './dataCredits.js'; +import { transitUpstreamHeaders } from './transitProxy.js'; +import { + getTransitFeed, + publicTransitCatalog, + transitFeedsInRange, + transitModeFor, + transitModeResolved, +} from './transitFeeds.js'; + +// Route ids below are as published in the live feeds and the operators' +// static routes.txt (checked 16 Oct 2026). + +test('Australian feeds are keyless, routable and cover their own city only', () => { + const seq = getTransitFeed('translink-seq'); + const cairns = getTransitFeed('translink-cairns'); + const adelaide = getTransitFeed('adelaide-metro'); + assert.equal( + cairns.url, + 'https://gtfsrt.api.translink.com.au/api/realtime/CNS/VehiclePositions', + ); + assert.equal( + adelaide.url, + 'https://gtfs.adelaidemetro.com.au/v1/realtime/vehicle_positions', + ); + for (const feed of [seq, cairns]) { + assert.equal(feed.headers, undefined, `${feed.id} needs no extra header`); + } + for (const feed of [seq, cairns, adelaide]) { + assert.equal(feed.license, 'CC BY 4.0'); + } + const ids = (lat, lon) => transitFeedsInRange(lat, lon).map((f) => f.id); + assert.deepEqual(ids(-27.4698, 153.0251), ['translink-seq']); + assert.deepEqual(ids(-16.9186, 145.7781), ['translink-cairns']); + assert.deepEqual(ids(-34.9285, 138.6007), ['adelaide-metro']); + assert.deepEqual(ids(-37.8136, 144.9631), [], 'Melbourne has no feed'); +}); + +test('Adelaide is asked for its own protobuf type, or its gateway answers base64 JSON', () => { + // Offered the default Accept list (application/x-protobuf, ..., */*), the + // Adelaide Metro gateway replies application/json carrying the protobuf as + // base64, which the decoder rejects. Its own media type gets raw protobuf. + const adelaide = getTransitFeed('adelaide-metro'); + assert.deepEqual(Object.keys(adelaide.headers), ['Accept']); + const headers = transitUpstreamHeaders(adelaide); + assert.equal(headers.Accept, 'application/x-google-protobuf'); + assert.equal(headers['Accept-Encoding'], 'gzip'); + assert.match(headers['User-Agent'], /gods-eye-view/); +}); + +test('TransLink route ids resolve rail, light rail and ferries; buses stay a default', () => { + const seq = getTransitFeed('translink-seq'); + const cases = [ + ['BRBN-5187', 'rail'], + ['SHCL-5187', 'rail'], + ['RPIP-5201', 'rail'], + ['L1-5029', 'tram'], + ['F1-4055', 'ferry'], + ['F23-4055', 'ferry'], + ['F50-4430', 'ferry'], + ['SMBI-3779', 'ferry'], + ]; + for (const [routeId, mode] of cases) { + assert.equal(transitModeFor(seq, routeId), mode, routeId); + assert.equal(transitModeResolved(seq, routeId), true, routeId); + } + // Buses, Brisbane Metro and the rail-replacement shuttle are buses by the + // feed default, so movement plausibility does not treat them as known. + for (const routeId of ['600', '250-5169', 'M1-4949', 'SHUT-5213', null]) { + assert.equal(transitModeFor(seq, routeId), 'bus', String(routeId)); + assert.equal(transitModeResolved(seq, routeId), false, String(routeId)); + } + const cairns = getTransitFeed('translink-cairns'); + assert.equal(transitModeFor(cairns, 'C111-5061'), 'bus'); + assert.equal(transitModeResolved(cairns, 'C111-5061'), false); +}); + +test('Adelaide Metro route ids resolve trains, trams and the SeaLink ferry', () => { + const adelaide = getTransitFeed('adelaide-metro'); + const cases = [ + ['BEL', 'rail'], + ['GAWC', 'rail'], + ['OUTHA', 'rail'], + ['SEAFRD', 'rail'], + ['PTDOCK', 'rail'], + ['BTANIC', 'tram'], + ['GLNELG', 'tram'], + ['FESTVL', 'tram'], + ['SEALNK', 'ferry'], + ]; + for (const [routeId, mode] of cases) { + assert.equal(transitModeFor(adelaide, routeId), mode, routeId); + assert.equal(transitModeResolved(adelaide, routeId), true, routeId); + } + // All-letter bus routes exist (INDSTA/INDSTB), so letters alone are not rail. + for (const routeId of ['100', 'G10', 'H33C', 'INDSTA', 'T721', null]) { + assert.equal(transitModeFor(adelaide, routeId), 'bus', String(routeId)); + assert.equal( + transitModeResolved(adelaide, routeId), + false, + String(routeId), + ); + } +}); + +test('Australian feeds credit the operator and department as text', () => { + const credit = (id) => + transitFeedCredit(publicTransitCatalog().find((feed) => feed.id === id)) + .html; + for (const id of ['translink-seq', 'translink-cairns']) { + assert.match( + credit(id), + /^Transit \(Translink, Department of Transport and Main Roads\): ]*>CC BY 4\.0<\/a>$/, + ); + } + assert.match( + credit('adelaide-metro'), + /^Transit \(Adelaide Metro – Department for Infrastructure and Transport, South Australia\): ]*>CC BY 4\.0<\/a>$/, + ); +}); + +test('DATA_SOURCES documents the Australian feeds in the transit row style', () => { + const rows = readFileSync( + new URL('../../DATA_SOURCES.md', import.meta.url), + 'utf8', + ).split('\n'); + const translink = rows.find((line) => line.startsWith('| **TransLink**')); + assert.match(translink, /South East Queensland and Cairns/); + const adelaide = rows.find((line) => line.startsWith('| **Adelaide Metro**')); + assert.ok(adelaide, 'Adelaide Metro row exists'); + for (const row of [translink, adelaide]) { + assert.match(row, /open realtime vehicle data/); + assert.match(row, /published for developer use and not against their use/); + assert.doesNotMatch(row, /licen[cs]e|CC BY|terms/i); + } +});