diff --git a/README.md b/README.md index 02f0a5991..346491c10 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Road domain, v0.1: their readings. Congestion is computed from a self-derived free-flow baseline (85th percentile), with native reference speeds where a feed ships one and OSM `maxspeed` as a day-one proxy. See [docs/speed-coverage.md](docs/speed-coverage.md). -- **Emitters:** a paged record API, GeoJSON, JSON-LD, TraFF, DATEX II, Valhalla exclusions, and an SSE stream — +- **Emitters:** a paged record API, GeoJSON, JSON-LD, TraFF, CIFS (XML & JSON), DATEX II, Valhalla exclusions, and an SSE stream — all public, rate-limited, and bbox-filterable. - **Graph binding:** road situations, and effects with a location of their own, are bound to the directed OSM segment spine (`way_id:f|b` spans with confidence); see [docs/graph-binding.md](docs/graph-binding.md). @@ -89,14 +89,14 @@ packages/ reusable libraries (Apache-2.0 unless noted) facilities, maritime, vehicles, weather core/ canonical model, severity, freshness, read helpers, DB schema/migrations (./server) ingest-framework/ feed descriptors, credentials, guarded fetch, catalogue resolvers, licences, domain plugins - roads/ road parsers (DATEX II / Open511 / WZDx and more), the roads domain, TMC location tables + roads/ road parsers (DATEX II / Open511 / WZDx / CIFS and more), the roads domain, TMC location tables bind/ event → segment resolver + evaluation corpus parking/ fuel/ charging/ cameras/ hazards/ weather/ vehicles/ border/ each domain's parsers and its ingest domain datex2/ DATEX II decoding shared by the domains (XML, publications, value decoders) ocpi/ OCPI wire types, decoders and dialects openlr/ OpenLR binary decode + resolver client - publishers/ outbound emitters (GeoJSON, JSON-LD, TraFF, DATEX II, SSE, Valhalla) + publishers/ outbound emitters (GeoJSON, JSON-LD, TraFF, CIFS, DATEX II, SSE, Valhalla) storage/ the source catalogue and the record writer (AGPL-3.0) contrib-core/ the signed, portable crowd report and sub-claim format federation/ instance identity: Ed25519 keys, the actor document, the pinned peers registry diff --git a/docs/cifs.md b/docs/cifs.md new file mode 100644 index 000000000..20c0ba717 --- /dev/null +++ b/docs/cifs.md @@ -0,0 +1,38 @@ +# CIFS v2 ingest and export + +OpenConditions implements the **Closure and Incident Feed Specification (CIFS v2)** published by Google/Waze in both directions: inbound parsing (`format: "cifs"` in `@openconditions/roads`, XML and JSON) and outbound publishing (`situationsToCifsXml` and `situationsToCifsJson` in `@openconditions/publishers`, exposed at `GET /cifs.xml` and `GET /cifs.json`). + +## Schema and crosswalk + +The official XML Schema (`https://www.gstatic.com/road-incidents/cifsv2.xsd`) is pinned by SHA-256 in `packages/conformance/src/standards/cifs-v2.ts` and validated at test time with `xmllint-wasm`. Every CIFS `type` and `subtype` is declared in `packages/model-roads/src/vocabularies/cifs.ts` and mapped in `packages/model-roads/src/crosswalk/cifs.ts`. + +Inbound parsing validates `(type, subtype)` pairs before classification so mismatched pairs (such as `HAZARD` with `ROAD_CLOSED_EVENT`) fail closed. `CHIT_CHAT` is accounted as `terminal` rather than published as a road condition. Two documented subtypes absent from `cifsv2.xsd` (`HAZARD_ON_ROAD_EMERGENCY_VEHICLE` and `POLICE_WITH_MOBILE_CAMERA`) are accepted inbound and never written outbound. Outbound export never writes deprecated top-level `CONSTRUCTION` (it emits `HAZARD` / `HAZARD_ON_ROAD_CONSTRUCTION` instead) or `CHIT_CHAT`. + +## Inbound parsing and snapshot authority + +`parseCifsSnapshot` reads both CIFS XML (``) and CIFS JSON (`{ "incidents": [...] }`, supporting both flat incident objects and wrapped `{ "incident": { ... } }` entries) as well as legacy nested `location` objects. Contradictory values between flat location fields and a nested `location` object fail closed. + +Because Waze partner feeds do not uniformly guarantee complete-world snapshot semantics, `format: "cifs"` always parses through the accounted snapshot path (`reconcileRoadSnapshots`) with `situationsComplete: false` by default and a bounded retrieval TTL (`freshness.expiresAt`). The format declares `reparseUnchanged: true` so conditional `304 Not Modified` responses replay the held payload and advance `freshness.expiresAt` on healthy feeds, while failed or malformed polls leave existing records untouched. Malformed records, wrong roots, explicit failure envelopes (`error`, `errors`, `success: false`, `ok: false`, HTTP error status), and conflicting duplicate IDs fail the poll rather than withdrawing valid predecessors. A catalogue source may declare `snapshot: { completeness: "complete" }` only after qualifying its withdrawal contract. + +Inbound semantic rules: + +- `ROAD_CLOSED` and `ROAD_CLOSED_*` retain their cause classification (`roadworks.works.construction`, `public_event.event`, `road_hazard.hazard`, or `closure.closure.full`) and explicitly set `roadState: "closed"`, producing a `closure` effect. Closures without an explicit usable `starttime` set `validity.status: "unknown"`, and single-point, circular, zero-length, or >20 km `ROAD_CLOSED` geometries attach a non-temporal `invalid_value` issue so they remain `normalization: "partial"` and never enter routing. +- Bare `CONSTRUCTION` and `HAZARD_ON_ROAD_CONSTRUCTION` remain works alerts unless backed by valid lane evidence. +- On a `LineString`, `ONE_DIRECTION` and omitted `direction` map to `{ value: "positive", basis: "geometry" }`. On a `Point`, `ONE_DIRECTION` maps to `{ value: "positive", basis: "unknown", text: "ONE_DIRECTION" }` so graph binding treats it as `unplaced` instead of widening to both directions. Duplicate or non-scalar direction/location/timing fields fail closed rather than collapsing to absent. +- Partial lane data (`` and ``) is validated as single-direction linear evidence only. Zero-based `order` (`0..99`) is normalized to 1-based lane indices, non-traffic lane types (anything other than `LANE`) are excluded from traffic lane counts, count and roadside conflicts between `` and `` are flagged as partial evidence, and partial lane data never synthesizes `all_lanes_closed`. +- `` / JSON `reference` maps to `provenance.informationSource` while `provenance.attribution` stays catalogue-owned. `` is preserved in `externalIds` under `cifs:parent_event` alongside `cifs:incident`. +- Inverted `starttime > endtime`, unparseable or malformed bounds, malformed or equal-endpoint schedule windows, schedules without a resolvable timezone, and recurring windows that cross a DST transition set `validity.status: "unknown"` with a matching temporal issue so the record never defaults to 24/7 active or drifts by an hour across DST. + +## Outbound export (`GET /cifs.xml` and `GET /cifs.json`) + +`GET /cifs.xml` and `GET /cifs.json` return one **complete public point-in-time CIFS v2 feed** from a single repeatable-read read-only database snapshot, sharing the exact same projection. Neither endpoint accepts `cursor`, `limit`, `simplify`, `from`, or `to` (400); use `at` (and optional `horizonDays`) for point-in-time reads. Both endpoints always use the public scope even when an operator bearer token is sent, and enforce a maximum of **20,000 candidate situations** and **32 MiB of UTF-8 serialized output** (answering 413 JSON with `Cache-Control: no-store` if either bound is exceeded). `X-Data-License` names the licences of the public selection. + +Outbound safety and geometry policy: + +- **Never fabricate geometry.** Coordinates are rounded to 6 decimal places first; distinctness, non-circularity (rejecting closed rings where first and last vertices coincide for 3+ vertices), and Haversine length are validated on the serialized coordinates. +- **`ROAD_CLOSED` requires strong evidence:** a complete, active or confirmed-scheduled (`actionStatus` not `rejected` or `requested`), mandatory, road-wide (no `laneScope`) `closure` effect with scope in `road`, `carriageway`, `ramp`, `bridge`, or `tunnel`, an explicit `validity.start` timestamp (never defaulted from mutable poll or update timestamps), and a non-circular `LineString` of length > 0 m and ≤ 20,000 m. `lane_restriction` effects (including `all_lanes_closed`) and bare `closure` classifications never synthesize `ROAD_CLOSED`. +- **Single-point incidents:** single-point closures are always withheld. Non-closure single-point alerts (`ACCIDENT`, `HAZARD`, `JAM`, `POLICE`) are exported with `BOTH_DIRECTIONS` only when the canonical situation carries explicit bilateral evidence (`direction.value === "both"`). Single-point alerts with absent or non-bilateral direction are withheld rather than widened. +- **Line direction:** absent direction or `direction.value === "both"` writes `BOTH_DIRECTIONS`. `basis: "geometry"` writes `ONE_DIRECTION` (reversing coordinates when `value === "negative"`). Compass, bearing, Alert-C, and unknown directions are withheld with `unrepresentable_direction`. +- **Timing and schedules:** `unknown`, `ended`, `cancelled`, and `suspended` root lifecycles are withheld. Recurring `periods` are exported as `` (strictly in `cifsv2.xsd` sequence order: `everyday` or `monday`..`sunday`) only when `scheduleTimezone` matches the geometry timezone, no `exceptions` / `exceptDate` / `byMonth` / `byMonthDay` / `repeatCount` or narrower date sub-bounds are present, windows are same-day minute-aligned with authoritative `duration` matching any `endTime`, and the window does not cross a DST transition. Note that Waze defaults omitted `endtime` on closures to 14 days from `starttime`. +- **Lanes and splitting:** `` is attached only on `ONE_DIRECTION` non-closure incidents with a complete contiguous `1..N` traffic lane list whose statuses are `open` or `closed` and whose counts reconcile with declared `lanesTotal`, `lanesClosed`, `lanesRestricted`, `lanesOperational`, and `vehicleImpact`. Partial counts never fabricate `` for ``. Effects with their own geometry, effective validity (including `periods`), or direction split into separate incidents; overlapping effective windows (intersecting recurring schedules) at the same location and direction with conflicting lane restrictions (including `all_lanes_open`) are withheld with `conflicting_effects`. +- **Timestamps, sanitization, and identity:** `xs:dateTime` values are formatted as second-resolution UTC clamped to `0001-01-01T00:00:00Z` through `9999-12-31T23:59:59Z`. Text fields pass through XML 1.0 character sanitization before enforcing `cifsv2.xsd` minimum Unicode code-point lengths (`@id` ≥ 3, `` ≥ 2, `` ≥ 1). Preserved `cifs:parent_event` external IDs (≥ 3 code points) are emitted as `` / `parent_event`. Feed-wide incident ID uniqueness is enforced across root and split records after sanitization. diff --git a/docs/model.md b/docs/model.md index f6853c2c5..9859278f0 100644 --- a/docs/model.md +++ b/docs/model.md @@ -859,82 +859,82 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin ### Vocabularies -| vocabulary | extensible | values | -| ------------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `access_mode` | no | `bulk`, `on_demand` | -| `action_status` | no | `requested`, `approved`, `being_implemented`, `implemented`, `rejected`, `termination_requested`, `being_terminated` | -| `admin_geocode_scheme` | yes | `iso3166-2`, `nuts`, `fips`, `same`, `ugc`, `ars`, `insee`, `padd`, `warncellid`, `emma_id`, `sgc`, `eccc_clc`, `cisorp`, `fips10_4` | -| `aggregation` | no | `instantaneous`, `mean`, `median`, `min`, `max`, `sum`, `p85`, `typical` | -| `amenity` | yes | `hotel`, `motel`, `overnight_accommodation`, `shop`, `kiosk`, `food_shopping`, `supermarket`, `mall`, `cafe`, `restaurant`, `self_service_restaurant`, `motorway_restaurant`, `spare_parts_shop`, `petrol_station`, `charging_station`, `vehicle_maintenance`, `tyre_repair`, `truck_repair`, `truck_wash`, `car_wash`, `car_rental`, `pharmacy`, `medical_facility`, `first_aid`, `defibrillator`, `police`, `tourist_information`, `information_point`, `bike_sharing`, `bike_parking`, `docstop`, `laundry`, `leisure`, `sport`, `recreation_area`, `nature`, `museum`, `playground`, `picnic_facilities`, `toilets`, `shower`, `wifi`, `internet_terminal`, `public_phone`, `cash_machine`, `payment_machine`, `vending_machine`, `safe_deposit`, `luggage_locker`, `elevator`, `fresh_water`, `power_outlet`, `waste_disposal`, `refuse_bin`, `dumping_station`, `fire_extinguisher`, `fire_hydrant`, `toll_terminal`, `bus_stop`, `tram_stop`, `taxi_stand`, `metro_station`, `train_station`, `public_transport_hub`, `airport`, `parking`, `carpool_parking`, `compressed_air`, `parcel_pickup`, `baby_changing`, `bar`, `takeaway`, `bottled_gas`, `heating_oil`, `lamp_oil`, `fuel_additives` | -| `border_wait_status` | no | `no_delay`, `delay`, `closed`, `unknown` | -| `camera_status` | no | `online`, `offline`, `stale`, `unknown` | -| `cap_category` | no | `geo`, `met`, `safety`, `security`, `rescue`, `fire`, `health`, `env`, `transport`, `infra`, `cbrne`, `other` | -| `cap_certainty` | no | `observed`, `likely`, `possible`, `unlikely`, `unknown` | -| `cap_msg_type` | no | `alert`, `update`, `cancel`, `ack`, `error` | -| `cap_response_type` | no | `shelter`, `evacuate`, `prepare`, `execute`, `avoid`, `monitor`, `assess`, `all_clear`, `none` | -| `cap_scope` | no | `public`, `restricted`, `private` | -| `cap_severity` | no | `extreme`, `severe`, `moderate`, `minor`, `unknown` | -| `cap_status` | no | `actual`, `exercise`, `system`, `test`, `draft` | -| `cap_urgency` | no | `immediate`, `expected`, `future`, `past`, `unknown` | -| `carriageway` | no | `main`, `entry`, `exit`, `ramp`, `connector`, `service`, `collector`, `parallel` | -| `cause` | yes | `accident`, `breakdown`, `debris`, `spill`, `fire`, `police_activity`, `animal`, `congestion`, `hazard`, `weather`, `roadworks`, `maintenance`, `construction`, `public_event`, `security`, `infrastructure_failure`, `equipment_failure`, `flooding`, `landslide`, `avalanche`, `wildfire`, `strike`, `demonstration`, `medical_emergency`, `obstruction`, `abnormal_load`, `military`, `customs`, `unknown`, `other` | -| `certainty` | no | `observed`, `likely`, `possible`, `unlikely`, `unknown` | -| `chain_level` | no | `none`, `R1`, `R2`, `R3` | -| `charging_site_status` | no | `available`, `partially_available`, `full`, `out_of_service`, `closed`, `unknown` | -| `compliance` | no | `mandatory`, `advisory`, `unknown` | -| `connector_standard` | yes | `CHADEMO`, `CHAOJI`, `DOMESTIC_A`, `DOMESTIC_B`, `DOMESTIC_C`, `DOMESTIC_D`, `DOMESTIC_E`, `DOMESTIC_F`, `DOMESTIC_G`, `DOMESTIC_H`, `DOMESTIC_I`, `DOMESTIC_J`, `DOMESTIC_K`, `DOMESTIC_L`, `DOMESTIC_M`, `DOMESTIC_N`, `DOMESTIC_O`, `GBT_AC`, `GBT_DC`, `IEC_60309_2_single_16`, `IEC_60309_2_three_16`, `IEC_60309_2_three_32`, `IEC_60309_2_three_64`, `IEC_62196_T1`, `IEC_62196_T1_COMBO`, `IEC_62196_T2`, `IEC_62196_T2_COMBO`, `IEC_62196_T3A`, `IEC_62196_T3C`, `NEMA_5_20`, `NEMA_6_30`, `NEMA_6_50`, `NEMA_10_30`, `NEMA_10_50`, `NEMA_14_30`, `NEMA_14_50`, `PANTOGRAPH_BOTTOM_UP`, `PANTOGRAPH_TOP_DOWN`, `TESLA_R`, `TESLA_S`, `SAE_J3400`, `MCS`, `UNKNOWN` | -| `delay_band` | no | `negligible`, `up_to_ten_minutes`, `between_ten_minutes_and_thirty_minutes`, `between_thirty_minutes_and_one_hour`, `between_one_hour_and_three_hours`, `between_three_hours_and_six_hours`, `longer_than_six_hours` | -| `delay_type` | no | `delays`, `delays_of_uncertain_duration`, `long_delays`, `very_long_delays` | -| `device_status` | no | `ok`, `warning`, `error`, `offline`, `unknown` | -| `dimension` | no | `height`, `width`, `length`, `gross_weight`, `laden_weight`, `axle_load`, `axle_count`, `trailer_count` | -| `direction_basis` | no | `road_reference`, `alert_c`, `openlr`, `geometry`, `bearing`, `compass`, `text`, `unknown` | -| `direction_loop` | no | `inner`, `outer` | -| `direction_value` | no | `positive`, `negative`, `both`, `unknown` | -| `emission_scheme` | yes | `euro`, `de_plakette`, `crit_air`, `ulez` | -| `ended_reason` | no | `source_ended`, `withdrawn_from_feed`, `expired`, `superseded`, `cancelled`, `stale` | -| `evidence_state` | no | `self_reported`, `corroborated`, `externally_resolved`, `negated`, `expired` | -| `evse_status` | no | `available`, `charging`, `occupied`, `reserved`, `blocked`, `out_of_order`, `inoperative`, `planned`, `removed`, `unknown` | -| `extent` | no | `point`, `linear`, `area`, `network`, `none` | -| `external_id_scheme` | yes | `ocpi:location`, `ocpi:evse`, `ocpi:connector`, `oicp:evse`, `emi3:evse`, `datex:site`, `datex:situation`, `datex:record`, `datex:parking`, `datex:vms`, `datex:refill_point`, `wzdx:road_event`, `wzdx:device`, `open511`, `tpims:site`, `nbi:structure`, `fra:crossing`, `cbp:port`, `cbsa:office`, `osm:node`, `osm:way`, `osm:relation`, `gers`, `wikidata`, `tmc`, `cap`, `gtfs:stop`, `gtfs:route`, `ifopt`, `ocm`, `bnetza`, `cpo`, `provider`, `siren`, `afdc`, `netex:line`, `netex:stop_place`, `irwin`, `nwcg:unique_fire_id`, `usgs:event`, `jma:event`, `jma:message`, `jma:warning`, `geonet:event`, `gdacs:event`, `glide`, `gvp:volcano` | -| `facility_open_status` | no | `open`, `closed`, `restricted`, `unknown` | -| `feature_trait` | yes | `field_device`, `weather_sensing`, `operated_site` | -| `ferry_status` | no | `on_schedule`, `delayed`, `cancelled`, `suspended`, `running`, `unknown` | -| `fuel_grade` | yes | `e5`, `e10`, `sp98`, `e85`, `diesel`, `diesel_premium`, `hvo100`, `b7`, `b10`, `b100`, `lpg`, `cng`, `lng`, `h2_350`, `h2_700`, `adblue`, `ethanol`, `kerosene`, `e25`, `renewable_petrol`, `agricultural_diesel`, `methanol`, `ammonia`, `e5_premium`, `sp98_e10`, `cng_bio`, `lng_bio`, `sp100`, `b20`, `b30` | -| `fusion_tier` | no | `authoritative`, `operator`, `aggregator`, `community`, `crowd_externally_resolved`, `crowd_corroborated`, `crowd_self_reported` | -| `fuzziness` | no | `exact`, `low_res`, `medium_res`, `end_unknown`, `start_unknown`, `extent_unknown` | -| `geometry_origin` | no | `source`, `site_table`, `tmc_table`, `openlr_decoded`, `osm`, `crowd_device`, `derived`, `none` | -| `grant_state` | no | `yes`, `no`, `unknown` | -| `ical_day` | no | `MO`, `TU`, `WE`, `TH`, `FR`, `SA`, `SU` | -| `information_source_type` | no | `automobile_club_patrol`, `camera_observation`, `freight_vehicle_operator`, `induction_loop_monitoring_station`, `infrared_monitoring_station`, `microwave_monitoring_station`, `mobile_telephone_caller`, `non_police_emergency_service_patrol`, `other_information`, `other_official_vehicle`, `police_patrol`, `private_breakdown_service`, `public_and_private_utilities`, `registered_motorist_observer`, `road_authorities`, `road_operator_patrol`, `roadside_telephone_caller`, `spotter_aircraft`, `traffic_monitoring_station`, `transit_operator`, `vehicle_probe_measurement`, `video_processing_monitoring_station` | -| `issue_code` | yes | `unsupported_type`, `unsupported_unit`, `unsupported_operator`, `invalid_value`, `invalid_window`, `unsupported_schedule`, `unsupported_status`, `unknown_vehicle`, `compound_condition`, `conflicting_direction`, `unresolved_lane`, `value_not_published` | -| `lane_type` | no | `general`, `hov`, `bus`, `bicycle`, `shoulder`, `hard_shoulder`, `emergency`, `turn`, `exit`, `entrance`, `median`, `center_turn`, `ramp`, `parking`, `sidewalk` | -| `lifecycle` | no | `planned`, `under_construction`, `operational`, `temporarily_closed`, `decommissioned`, `unknown` | -| `los` | no | `free_flow`, `slow`, `heavy`, `queuing`, `stationary`, `blocked`, `unknown` | -| `normalization` | no | `complete`, `partial`, `unsupported` | -| `origin` | no | `feed`, `crowd`, `federation`, `derived` | -| `parking_security` | no | `social_control`, `security_staff`, `external_security`, `cctv`, `dog`, `guard_24h`, `lighting`, `flood_light`, `fences`, `separated_area`, `none` | -| `parking_status` | no | `open`, `closed`, `full`, `almost_full`, `spaces_available`, `closed_abnormally`, `unknown` | -| `pass_status` | no | `open`, `closed`, `restricted`, `chains_required`, `unknown` | -| `payment_method` | no | `cash`, `credit_card`, `debit_card`, `card`, `contactless`, `app`, `rfid`, `sms`, `membership`, `direct_debit`, `prepaid_card`, `free`, `other` | -| `precipitation_type` | no | `none`, `rain`, `snow`, `sleet`, `hail`, `drizzle`, `freezing_rain` | -| `privacy_class` | no | `authoritative`, `aggregate`, `k_anon`, `dp_noised`, `crowd_pseudonym` | -| `record_class` | no | `feature`, `situation`, `observation`, `offer` | -| `relation` | no | `part_of`, `monitors`, `controls`, `serves`, `group`, `next_occurrence`, `first_occurrence`, `related_work_zone`, `caused_by`, `detour_for`, `supersedes`, `update_of`, `cancels`, `related` | -| `result_type` | no | `quantity`, `count`, `boolean`, `category`, `text`, `vector`, `money`, `structured`, `unknown`, `not_applicable` | -| `road_class` | no | `motorway`, `trunk`, `primary`, `secondary`, `tertiary`, `local`, `service`, `other` | -| `road_designation_scheme` | yes | `us_interstate`, `us_route`, `us_state_route`, `de_bab`, `de_bundesstrasse`, `e_road`, `national` | -| `severity` | no | `none`, `minor`, `moderate`, `major`, `critical`, `unknown` | -| `source_format` | yes | `crowd`, `derived`, `datex2`, `geojson`, `json`, `csv`, `overpass`, `autobahn`, `bcn-trams`, `bcn-trams-csv`, `bonn`, `cars`, `cars-signs`, `caltrans-cms`, `datex2-elaborated`, `datex2-locations`, `datex2-measured`, `datex2-sites`, `digitraffic`, `digitraffic-traffic-measurement`, `fdt`, `fintraffic-stations`, `fintraffic-tms`, `flatjson`, `france-comptage-csv`, `gddkia`, `geojson-flow`, `hk-detector-csv`, `hk-td`, `ibi511`, `ibi511-conditions`, `informo`, `lta`, `lta-speedbands`, `miv`, `miv-config`, `nyc-dot`, `ohgo`, `ohgo-events`, `open511`, `trafikverket`, `trafikverket-flow`, `vic-disruptions`, `wa-webeoc`, `webtris`, `webtris-sites`, `wzdx`, `windy`, `tfl`, `nps`, `tripcheck`, `cars-cctv`, `quebec-cameras`, `digitraffic-weather`, `eccc-swob`, `dwd-cdc-10min`, `smhi-metobs`, `fmi-weather`, `iowa-avl`, `parkapi-v3`, `datex2-light`, `db-bahnpark`, `rdw`, `sbb`, `opendatahub`, `hdb`, `taipei`, `utmc`, `tfnsw`, `vegvesen-parkreg`, `ocpi`, `oicp`, `bnetza`, `irve`, `afdc`, `nobil`, `eipa`, `cynap`, `chargy`, `evroam`, `geofa`, `keco`, `tdx`, `ocm`, `pun`, `tankerkoenig`, `econtrol`, `prix-carburants`, `minetur`, `cbp-bwt`, `cbsa-bwt`, `granica-html`, `jma-xml`, `nsw-rfs`, `cap`, `nws`, `meteoalarm`, `firms`, `slstr-frp`, `wfigs`, `effis`, `hms`, `usgs`, `geonet`, `eonet`, `gdacs` | -| `source_tier` | no | `authoritative`, `operator`, `aggregator`, `community` | -| `surface_state` | no | `dry`, `damp`, `wet`, `frost`, `ice`, `black_ice`, `snow`, `packed_snow`, `slush`, `standing_water`, `flooded`, `chemically_wet`, `unknown` | -| `temporality` | no | `static`, `scheduled`, `live`, `forecast` | -| `tombstone_reason` | no | `expired`, `withdrawn`, `superseded`, `cancelled`, `rights_revoked`, `rejected` | -| `trend` | no | `rising`, `falling`, `steady`, `filling`, `clearing` | -| `validity_status` | no | `planned`, `active`, `suspended`, `ended`, `cancelled`, `unknown` | -| `vehicle_class` | no | `motor_vehicle`, `car`, `van`, `truck`, `hgv`, `bus`, `coach`, `motorcycle`, `moped`, `bicycle`, `pedestrian`, `trailer`, `caravan`, `agricultural`, `emergency`, `taxi`, `oversize`, `abnormal_load` | -| `vehicle_fuel` | no | `electric`, `hydrogen`, `lpg`, `cng`, `lng`, `diesel`, `petrol`, `hybrid` | -| `vehicle_usage` | no | `emergency_services`, `public_transport`, `taxi`, `delivery`, `local_access`, `residents`, `permit_holders`, `military`, `agricultural`, `car_sharing` | -| `vms_working_status` | no | `in_service`, `out_of_service`, `fault`, `blank`, `unknown` | +| vocabulary | extensible | values | +| ------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `access_mode` | no | `bulk`, `on_demand` | +| `action_status` | no | `requested`, `approved`, `being_implemented`, `implemented`, `rejected`, `termination_requested`, `being_terminated` | +| `admin_geocode_scheme` | yes | `iso3166-2`, `nuts`, `fips`, `same`, `ugc`, `ars`, `insee`, `padd`, `warncellid`, `emma_id`, `sgc`, `eccc_clc`, `cisorp`, `fips10_4` | +| `aggregation` | no | `instantaneous`, `mean`, `median`, `min`, `max`, `sum`, `p85`, `typical` | +| `amenity` | yes | `hotel`, `motel`, `overnight_accommodation`, `shop`, `kiosk`, `food_shopping`, `supermarket`, `mall`, `cafe`, `restaurant`, `self_service_restaurant`, `motorway_restaurant`, `spare_parts_shop`, `petrol_station`, `charging_station`, `vehicle_maintenance`, `tyre_repair`, `truck_repair`, `truck_wash`, `car_wash`, `car_rental`, `pharmacy`, `medical_facility`, `first_aid`, `defibrillator`, `police`, `tourist_information`, `information_point`, `bike_sharing`, `bike_parking`, `docstop`, `laundry`, `leisure`, `sport`, `recreation_area`, `nature`, `museum`, `playground`, `picnic_facilities`, `toilets`, `shower`, `wifi`, `internet_terminal`, `public_phone`, `cash_machine`, `payment_machine`, `vending_machine`, `safe_deposit`, `luggage_locker`, `elevator`, `fresh_water`, `power_outlet`, `waste_disposal`, `refuse_bin`, `dumping_station`, `fire_extinguisher`, `fire_hydrant`, `toll_terminal`, `bus_stop`, `tram_stop`, `taxi_stand`, `metro_station`, `train_station`, `public_transport_hub`, `airport`, `parking`, `carpool_parking`, `compressed_air`, `parcel_pickup`, `baby_changing`, `bar`, `takeaway`, `bottled_gas`, `heating_oil`, `lamp_oil`, `fuel_additives` | +| `border_wait_status` | no | `no_delay`, `delay`, `closed`, `unknown` | +| `camera_status` | no | `online`, `offline`, `stale`, `unknown` | +| `cap_category` | no | `geo`, `met`, `safety`, `security`, `rescue`, `fire`, `health`, `env`, `transport`, `infra`, `cbrne`, `other` | +| `cap_certainty` | no | `observed`, `likely`, `possible`, `unlikely`, `unknown` | +| `cap_msg_type` | no | `alert`, `update`, `cancel`, `ack`, `error` | +| `cap_response_type` | no | `shelter`, `evacuate`, `prepare`, `execute`, `avoid`, `monitor`, `assess`, `all_clear`, `none` | +| `cap_scope` | no | `public`, `restricted`, `private` | +| `cap_severity` | no | `extreme`, `severe`, `moderate`, `minor`, `unknown` | +| `cap_status` | no | `actual`, `exercise`, `system`, `test`, `draft` | +| `cap_urgency` | no | `immediate`, `expected`, `future`, `past`, `unknown` | +| `carriageway` | no | `main`, `entry`, `exit`, `ramp`, `connector`, `service`, `collector`, `parallel` | +| `cause` | yes | `accident`, `breakdown`, `debris`, `spill`, `fire`, `police_activity`, `animal`, `congestion`, `hazard`, `weather`, `roadworks`, `maintenance`, `construction`, `public_event`, `security`, `infrastructure_failure`, `equipment_failure`, `flooding`, `landslide`, `avalanche`, `wildfire`, `strike`, `demonstration`, `medical_emergency`, `obstruction`, `abnormal_load`, `military`, `customs`, `unknown`, `other` | +| `certainty` | no | `observed`, `likely`, `possible`, `unlikely`, `unknown` | +| `chain_level` | no | `none`, `R1`, `R2`, `R3` | +| `charging_site_status` | no | `available`, `partially_available`, `full`, `out_of_service`, `closed`, `unknown` | +| `compliance` | no | `mandatory`, `advisory`, `unknown` | +| `connector_standard` | yes | `CHADEMO`, `CHAOJI`, `DOMESTIC_A`, `DOMESTIC_B`, `DOMESTIC_C`, `DOMESTIC_D`, `DOMESTIC_E`, `DOMESTIC_F`, `DOMESTIC_G`, `DOMESTIC_H`, `DOMESTIC_I`, `DOMESTIC_J`, `DOMESTIC_K`, `DOMESTIC_L`, `DOMESTIC_M`, `DOMESTIC_N`, `DOMESTIC_O`, `GBT_AC`, `GBT_DC`, `IEC_60309_2_single_16`, `IEC_60309_2_three_16`, `IEC_60309_2_three_32`, `IEC_60309_2_three_64`, `IEC_62196_T1`, `IEC_62196_T1_COMBO`, `IEC_62196_T2`, `IEC_62196_T2_COMBO`, `IEC_62196_T3A`, `IEC_62196_T3C`, `NEMA_5_20`, `NEMA_6_30`, `NEMA_6_50`, `NEMA_10_30`, `NEMA_10_50`, `NEMA_14_30`, `NEMA_14_50`, `PANTOGRAPH_BOTTOM_UP`, `PANTOGRAPH_TOP_DOWN`, `TESLA_R`, `TESLA_S`, `SAE_J3400`, `MCS`, `UNKNOWN` | +| `delay_band` | no | `negligible`, `up_to_ten_minutes`, `between_ten_minutes_and_thirty_minutes`, `between_thirty_minutes_and_one_hour`, `between_one_hour_and_three_hours`, `between_three_hours_and_six_hours`, `longer_than_six_hours` | +| `delay_type` | no | `delays`, `delays_of_uncertain_duration`, `long_delays`, `very_long_delays` | +| `device_status` | no | `ok`, `warning`, `error`, `offline`, `unknown` | +| `dimension` | no | `height`, `width`, `length`, `gross_weight`, `laden_weight`, `axle_load`, `axle_count`, `trailer_count` | +| `direction_basis` | no | `road_reference`, `alert_c`, `openlr`, `geometry`, `bearing`, `compass`, `text`, `unknown` | +| `direction_loop` | no | `inner`, `outer` | +| `direction_value` | no | `positive`, `negative`, `both`, `unknown` | +| `emission_scheme` | yes | `euro`, `de_plakette`, `crit_air`, `ulez` | +| `ended_reason` | no | `source_ended`, `withdrawn_from_feed`, `expired`, `superseded`, `cancelled`, `stale` | +| `evidence_state` | no | `self_reported`, `corroborated`, `externally_resolved`, `negated`, `expired` | +| `evse_status` | no | `available`, `charging`, `occupied`, `reserved`, `blocked`, `out_of_order`, `inoperative`, `planned`, `removed`, `unknown` | +| `extent` | no | `point`, `linear`, `area`, `network`, `none` | +| `external_id_scheme` | yes | `ocpi:location`, `ocpi:evse`, `ocpi:connector`, `oicp:evse`, `emi3:evse`, `datex:site`, `datex:situation`, `datex:record`, `datex:parking`, `datex:vms`, `datex:refill_point`, `wzdx:road_event`, `wzdx:device`, `open511`, `tpims:site`, `nbi:structure`, `fra:crossing`, `cbp:port`, `cbsa:office`, `osm:node`, `osm:way`, `osm:relation`, `gers`, `wikidata`, `tmc`, `cap`, `gtfs:stop`, `gtfs:route`, `ifopt`, `ocm`, `bnetza`, `cpo`, `provider`, `cifs:incident`, `cifs:parent_event`, `siren`, `afdc`, `netex:line`, `netex:stop_place`, `irwin`, `nwcg:unique_fire_id`, `usgs:event`, `jma:event`, `jma:message`, `jma:warning`, `geonet:event`, `gdacs:event`, `glide`, `gvp:volcano` | +| `facility_open_status` | no | `open`, `closed`, `restricted`, `unknown` | +| `feature_trait` | yes | `field_device`, `weather_sensing`, `operated_site` | +| `ferry_status` | no | `on_schedule`, `delayed`, `cancelled`, `suspended`, `running`, `unknown` | +| `fuel_grade` | yes | `e5`, `e10`, `sp98`, `e85`, `diesel`, `diesel_premium`, `hvo100`, `b7`, `b10`, `b100`, `lpg`, `cng`, `lng`, `h2_350`, `h2_700`, `adblue`, `ethanol`, `kerosene`, `e25`, `renewable_petrol`, `agricultural_diesel`, `methanol`, `ammonia`, `e5_premium`, `sp98_e10`, `cng_bio`, `lng_bio`, `sp100`, `b20`, `b30` | +| `fusion_tier` | no | `authoritative`, `operator`, `aggregator`, `community`, `crowd_externally_resolved`, `crowd_corroborated`, `crowd_self_reported` | +| `fuzziness` | no | `exact`, `low_res`, `medium_res`, `end_unknown`, `start_unknown`, `extent_unknown` | +| `geometry_origin` | no | `source`, `site_table`, `tmc_table`, `openlr_decoded`, `osm`, `crowd_device`, `derived`, `none` | +| `grant_state` | no | `yes`, `no`, `unknown` | +| `ical_day` | no | `MO`, `TU`, `WE`, `TH`, `FR`, `SA`, `SU` | +| `information_source_type` | no | `automobile_club_patrol`, `camera_observation`, `freight_vehicle_operator`, `induction_loop_monitoring_station`, `infrared_monitoring_station`, `microwave_monitoring_station`, `mobile_telephone_caller`, `non_police_emergency_service_patrol`, `other_information`, `other_official_vehicle`, `police_patrol`, `private_breakdown_service`, `public_and_private_utilities`, `registered_motorist_observer`, `road_authorities`, `road_operator_patrol`, `roadside_telephone_caller`, `spotter_aircraft`, `traffic_monitoring_station`, `transit_operator`, `vehicle_probe_measurement`, `video_processing_monitoring_station` | +| `issue_code` | yes | `unsupported_type`, `unsupported_unit`, `unsupported_operator`, `invalid_value`, `invalid_window`, `unsupported_schedule`, `unsupported_status`, `unknown_vehicle`, `compound_condition`, `conflicting_direction`, `unresolved_lane`, `value_not_published` | +| `lane_type` | no | `general`, `hov`, `bus`, `bicycle`, `shoulder`, `hard_shoulder`, `emergency`, `turn`, `exit`, `entrance`, `median`, `center_turn`, `ramp`, `parking`, `sidewalk` | +| `lifecycle` | no | `planned`, `under_construction`, `operational`, `temporarily_closed`, `decommissioned`, `unknown` | +| `los` | no | `free_flow`, `slow`, `heavy`, `queuing`, `stationary`, `blocked`, `unknown` | +| `normalization` | no | `complete`, `partial`, `unsupported` | +| `origin` | no | `feed`, `crowd`, `federation`, `derived` | +| `parking_security` | no | `social_control`, `security_staff`, `external_security`, `cctv`, `dog`, `guard_24h`, `lighting`, `flood_light`, `fences`, `separated_area`, `none` | +| `parking_status` | no | `open`, `closed`, `full`, `almost_full`, `spaces_available`, `closed_abnormally`, `unknown` | +| `pass_status` | no | `open`, `closed`, `restricted`, `chains_required`, `unknown` | +| `payment_method` | no | `cash`, `credit_card`, `debit_card`, `card`, `contactless`, `app`, `rfid`, `sms`, `membership`, `direct_debit`, `prepaid_card`, `free`, `other` | +| `precipitation_type` | no | `none`, `rain`, `snow`, `sleet`, `hail`, `drizzle`, `freezing_rain` | +| `privacy_class` | no | `authoritative`, `aggregate`, `k_anon`, `dp_noised`, `crowd_pseudonym` | +| `record_class` | no | `feature`, `situation`, `observation`, `offer` | +| `relation` | no | `part_of`, `monitors`, `controls`, `serves`, `group`, `next_occurrence`, `first_occurrence`, `related_work_zone`, `caused_by`, `detour_for`, `supersedes`, `update_of`, `cancels`, `related` | +| `result_type` | no | `quantity`, `count`, `boolean`, `category`, `text`, `vector`, `money`, `structured`, `unknown`, `not_applicable` | +| `road_class` | no | `motorway`, `trunk`, `primary`, `secondary`, `tertiary`, `local`, `service`, `other` | +| `road_designation_scheme` | yes | `us_interstate`, `us_route`, `us_state_route`, `de_bab`, `de_bundesstrasse`, `e_road`, `national` | +| `severity` | no | `none`, `minor`, `moderate`, `major`, `critical`, `unknown` | +| `source_format` | yes | `crowd`, `derived`, `datex2`, `geojson`, `json`, `csv`, `overpass`, `autobahn`, `bcn-trams`, `bcn-trams-csv`, `bonn`, `cars`, `cars-signs`, `caltrans-cms`, `cifs`, `datex2-elaborated`, `datex2-locations`, `datex2-measured`, `datex2-sites`, `digitraffic`, `digitraffic-traffic-measurement`, `fdt`, `fintraffic-stations`, `fintraffic-tms`, `flatjson`, `france-comptage-csv`, `gddkia`, `geojson-flow`, `hk-detector-csv`, `hk-td`, `ibi511`, `ibi511-conditions`, `informo`, `lta`, `lta-speedbands`, `miv`, `miv-config`, `nyc-dot`, `ohgo`, `ohgo-events`, `open511`, `trafikverket`, `trafikverket-flow`, `vic-disruptions`, `wa-webeoc`, `webtris`, `webtris-sites`, `wzdx`, `windy`, `tfl`, `nps`, `tripcheck`, `cars-cctv`, `quebec-cameras`, `digitraffic-weather`, `eccc-swob`, `dwd-cdc-10min`, `smhi-metobs`, `fmi-weather`, `iowa-avl`, `parkapi-v3`, `datex2-light`, `db-bahnpark`, `rdw`, `sbb`, `opendatahub`, `hdb`, `taipei`, `utmc`, `tfnsw`, `vegvesen-parkreg`, `ocpi`, `oicp`, `bnetza`, `irve`, `afdc`, `nobil`, `eipa`, `cynap`, `chargy`, `evroam`, `geofa`, `keco`, `tdx`, `ocm`, `pun`, `tankerkoenig`, `econtrol`, `prix-carburants`, `minetur`, `cbp-bwt`, `cbsa-bwt`, `granica-html`, `jma-xml`, `nsw-rfs`, `cap`, `nws`, `meteoalarm`, `firms`, `slstr-frp`, `wfigs`, `effis`, `hms`, `usgs`, `geonet`, `eonet`, `gdacs` | +| `source_tier` | no | `authoritative`, `operator`, `aggregator`, `community` | +| `surface_state` | no | `dry`, `damp`, `wet`, `frost`, `ice`, `black_ice`, `snow`, `packed_snow`, `slush`, `standing_water`, `flooded`, `chemically_wet`, `unknown` | +| `temporality` | no | `static`, `scheduled`, `live`, `forecast` | +| `tombstone_reason` | no | `expired`, `withdrawn`, `superseded`, `cancelled`, `rights_revoked`, `rejected` | +| `trend` | no | `rising`, `falling`, `steady`, `filling`, `clearing` | +| `validity_status` | no | `planned`, `active`, `suspended`, `ended`, `cancelled`, `unknown` | +| `vehicle_class` | no | `motor_vehicle`, `car`, `van`, `truck`, `hgv`, `bus`, `coach`, `motorcycle`, `moped`, `bicycle`, `pedestrian`, `trailer`, `caravan`, `agricultural`, `emergency`, `taxi`, `oversize`, `abnormal_load` | +| `vehicle_fuel` | no | `electric`, `hydrogen`, `lpg`, `cng`, `lng`, `diesel`, `petrol`, `hybrid` | +| `vehicle_usage` | no | `emergency_services`, `public_transport`, `taxi`, `delivery`, `local_access`, `residents`, `permit_holders`, `military`, `agricultural`, `car_sharing` | +| `vms_working_status` | no | `in_service`, `out_of_service`, `fault`, `blank`, `unknown` | ### Situation kinds @@ -1159,6 +1159,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `incident.accident` | datex2_v2 | Accident, GeneralObstruction:airCrash, GeneralObstruction:unprotectedAccidentArea | | `incident.accident` | open511 | INCIDENT, ACCIDENT | | `incident.accident` | ibi511 | accidentsAndIncidents | +| `incident.accident` | cifs | ACCIDENT, ACCIDENT_MAJOR, ACCIDENT_MINOR | | `incident.accident` | traff | INCIDENT_ACCIDENT | | `incident.accident` | gtfs_rt | ACCIDENT | | `incident.accident` | road511 | incident/accident | @@ -1185,6 +1186,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `incident.breakdown.stuck_vehicle` | datex2_v2 | VehicleObstruction:vehicleStuck, VehicleObstruction:vehicleStuckUnderBridge | | `incident.obstruction.animal` | datex2_v3 | AnimalPresenceObstruction | | `incident.obstruction.animal` | datex2_v2 | AnimalPresenceObstruction | +| `incident.obstruction.animal` | cifs | HAZARD_ON_ROAD_ROAD_KILL | | `incident.obstruction.animal` | traff | HAZARD_ANIMALS_ON_ROAD | | `incident.obstruction.animal` | road511 | hazard/animal | | `incident.obstruction.people_on_road` | datex2_v3 | DisturbanceActivity:sightseersObstructingAccess, GeneralObstruction:childrenOnRoadway, GeneralObstruction:cyclistsOnRoadway, GeneralObstruction:peopleOnRoadway | @@ -1193,6 +1195,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `incident.obstruction` | datex2_v3 | EnvironmentalObstruction, GeneralObstruction | | `incident.obstruction` | datex2_v2 | EnvironmentalObstruction, GeneralObstruction | | `incident.obstruction` | open511 | OBSTRUCTION | +| `incident.obstruction` | cifs | HAZARD_ON_ROAD | | `incident.obstruction` | traff | HAZARD_OBSTRUCTION | | `incident.obstruction` | gtfs_rt | OTHER_CAUSE | | `incident.obstruction` | road511 | hazard/debris | @@ -1216,9 +1219,11 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `incident.obstruction.debris` | datex2_v2 | GeneralObstruction:debris, GeneralObstruction:snowAndIceDebris | | `incident.obstruction.object` | datex2_v3 | GeneralObstruction:objectOnTheRoad, GeneralObstruction:objectsFallingFromMovingVehicle, GeneralObstruction:shedLoad | | `incident.obstruction.object` | datex2_v2 | GeneralObstruction:objectOnTheRoad, GeneralObstruction:objectsFallingFromMovingVehicle, GeneralObstruction:shedLoad | +| `incident.obstruction.object` | cifs | HAZARD_ON_ROAD_OBJECT | | `incident.obstruction.object` | traff | HAZARD_OBJECT_ON_ROAD | | `incident.obstruction.pothole` | datex2_v3 | GeneralObstruction:severeFrostDamagedRoadway, InfrastructureDamageObstruction:damagedRoadSurface | | `incident.obstruction.pothole` | datex2_v2 | GeneralObstruction:severeFrostDamagedRoadway, InfrastructureDamageObstruction:damagedRoadSurface | +| `incident.obstruction.pothole` | cifs | HAZARD_ON_ROAD_POT_HOLE | | `incident.obstruction.spill` | datex2_v3 | GeneralObstruction:spillageOccurringFromMovingVehicle, GeneralObstruction:spillageOnTheRoad | | `incident.obstruction.spill` | datex2_v2 | GeneralObstruction:spillageOccurringFromMovingVehicle, GeneralObstruction:spillageOnTheRoad | | `incident.obstruction.spill` | open511 | SPILL | @@ -1226,6 +1231,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `incident.obstruction.spill` | road511 | hazard/spill | | `incident.breakdown.disabled_vehicle` | datex2_v3 | RoadsideAssistance:vehicleRepair, RoadsideAssistance:vehicleRecovery, VehicleObstruction:brokenDownVehicle, VehicleObstruction:damagedVehicle, VehicleObstruction:vehicleInDifficulty | | `incident.breakdown.disabled_vehicle` | datex2_v2 | RoadsideAssistance:vehicleRepair, RoadsideAssistance:vehicleRecovery, VehicleObstruction:brokenDownVehicle, VehicleObstruction:damagedVehicle, VehicleObstruction:vehicleInDifficulty, VehicleObstruction:brokenDownBus, VehicleObstruction:brokenDownHeavyLorry | +| `incident.breakdown.disabled_vehicle` | cifs | HAZARD_ON_ROAD_CAR_STOPPED, HAZARD_ON_SHOULDER_CAR_STOPPED | | `incident.breakdown` | datex2_v3 | VehicleObstruction | | `incident.breakdown` | datex2_v2 | VehicleObstruction | | `incident.breakdown` | traff | INCIDENT_BROKEN_DOWN_VEHICLE | @@ -1241,6 +1247,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `incident.vehicle_hazard.slow_vehicle` | traff | HAZARD_SLOW_VEHICLE | | `incident.vehicle_hazard.emergency_vehicle` | datex2_v3 | VehicleObstruction:emergencyVehicle, VehicleObstruction:highSpeedEmergencyVehicle | | `incident.vehicle_hazard.emergency_vehicle` | datex2_v2 | VehicleObstruction:emergencyVehicle, VehicleObstruction:highSpeedEmergencyVehicle | +| `incident.vehicle_hazard.emergency_vehicle` | cifs | HAZARD_ON_ROAD_EMERGENCY_VEHICLE | | `incident.vehicle_hazard.emergency_vehicle` | traff | HAZARD_EMERGENCY_VEHICLE | | `incident.vehicle_hazard.high_speed_chase` | datex2_v3 | VehicleObstruction:highSpeedChase | | `incident.vehicle_hazard.high_speed_chase` | datex2_v2 | GeneralObstruction:highSpeedChase | @@ -1288,6 +1295,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `roadworks.works.construction` | datex2_v2 | ConstructionWorks | | `roadworks.works.construction` | wzdx | work-zone:roadway-relocation, work-zone:roadway-creation | | `roadworks.works.construction` | open511 | ROAD_CONSTRUCTION | +| `roadworks.works.construction` | cifs | HAZARD_ON_ROAD_CONSTRUCTION, ROAD_CLOSED_CONSTRUCTION | | `roadworks.works.construction` | traff | CONSTRUCTION_CONSTRUCTION_WORK | | `roadworks.works.blasting` | datex2_v3 | ConstructionWorks:blastingWork | | `roadworks.works.blasting` | datex2_v2 | ConstructionWorks:blastingWork | @@ -1300,6 +1308,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `roadworks.works` | wzdx | work-zone | | `roadworks.works` | open511 | CONSTRUCTION | | `roadworks.works` | ibi511 | roadwork | +| `roadworks.works` | cifs | CONSTRUCTION | | `roadworks.works` | traff | CONSTRUCTION_ROADWORKS | | `roadworks.works` | gtfs_rt | CONSTRUCTION | | `roadworks.works` | road511 | construction/roadwork | @@ -1362,12 +1371,14 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `closure.closure.seasonal` | road511 | closure/seasonal_closure | | `closure.closure.lane` | datex2_v3 | RoadOrCarriagewayOrLaneManagement:doNotUseSpecifiedLanesOrCarriageways, RoadOrCarriagewayOrLaneManagement:laneClosures, RoadOrCarriagewayOrLaneManagement:singleAlternateLineTraffic | | `closure.closure.lane` | datex2_v2 | RoadOrCarriagewayOrLaneManagement:doNotUseSpecifiedLanesOrCarriageways, RoadOrCarriagewayOrLaneManagement:laneClosures, RoadOrCarriagewayOrLaneManagement:singleAlternateLineTraffic | +| `closure.closure.lane` | cifs | HAZARD_ON_ROAD_LANE_CLOSED | | `closure.closure.lane` | traff | RESTRICTION_LANE_CLOSED | | `closure.closure.lane` | road511 | closure/lane_closure | | `closure.closure.night` | datex2_v3 | RoadOrCarriagewayOrLaneManagement:overnightClosures | | `closure.closure.night` | datex2_v2 | RoadOrCarriagewayOrLaneManagement:overnightClosures | | `closure.closure.full` | datex2_v3 | RoadOrCarriagewayOrLaneManagement:roadClosed | | `closure.closure.full` | datex2_v2 | RoadOrCarriagewayOrLaneManagement:roadClosed | +| `closure.closure.full` | cifs | ROAD_CLOSED | | `closure.closure.tunnel` | traff | RESTRICTION_CLOSED | | `restriction.access.no_overtaking` | datex2_v3 | GeneralInstructionOrMessageToRoadUsers:noOvertaking | | `restriction.access.no_overtaking` | datex2_v2 | GeneralInstructionOrMessageToRoadUsers:noOvertaking | @@ -1425,6 +1436,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `weather_condition.weather` | datex2_v3 | PoorEnvironmentConditions | | `weather_condition.weather` | datex2_v2 | PoorEnvironmentConditions | | `weather_condition.weather` | open511 | WEATHER_CONDITION | +| `weather_condition.weather` | cifs | HAZARD_WEATHER | | `weather_condition.weather` | traff | HAZARD_HAZARDOUS_CONDITIONS | | `weather_condition.weather` | gtfs_rt | WEATHER | | `weather_condition.weather` | road511 | weather | @@ -1437,6 +1449,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `weather_condition.weather.dust` | traff | WEATHER_BLOWING_DUST | | `weather_condition.weather.snow` | datex2_v3 | PoorEnvironmentConditions:blowingSnow, PoorEnvironmentConditions:heavySnowfall, PoorEnvironmentConditions:rainChangingToSnow, PoorEnvironmentConditions:sleet, PoorEnvironmentConditions:snowfall | | `weather_condition.weather.snow` | datex2_v2 | PoorEnvironmentConditions:blowingSnow, PoorEnvironmentConditions:heavySnowfall, PoorEnvironmentConditions:rainChangingToSnow, PoorEnvironmentConditions:sleet, PoorEnvironmentConditions:snowfall | +| `weather_condition.weather.snow` | cifs | HAZARD_WEATHER_HEAVY_SNOW | | `weather_condition.weather.snow` | traff | WEATHER_SNOWFALL | | `weather_condition.weather.snow` | road511 | weather/snow | | `weather_condition.weather.high_wind` | datex2_v3 | PoorEnvironmentConditions:crosswinds, PoorEnvironmentConditions:gales, PoorEnvironmentConditions:gustyWinds, PoorEnvironmentConditions:strongGustsOfWind, PoorEnvironmentConditions:strongWinds, PoorEnvironmentConditions:veryStrongGustsOfWind | @@ -1447,9 +1460,11 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `weather_condition.weather.hail` | datex2_v3 | PoorEnvironmentConditions:damagingHail, PoorEnvironmentConditions:hail | | `weather_condition.weather.hail` | datex2_v2 | PoorEnvironmentConditions:damagingHail, PoorEnvironmentConditions:hail | | `weather_condition.weather.hail` | open511 | HAIL | +| `weather_condition.weather.hail` | cifs | HAZARD_WEATHER_HAIL | | `weather_condition.weather.hail` | traff | WEATHER_HAIL | | `weather_condition.weather.fog` | datex2_v3 | PoorEnvironmentConditions:denseFog, PoorEnvironmentConditions:fog, PoorEnvironmentConditions:freezingFog, PoorEnvironmentConditions:moderateFog, PoorEnvironmentConditions:patchyFog | | `weather_condition.weather.fog` | datex2_v2 | PoorEnvironmentConditions:denseFog, PoorEnvironmentConditions:fog, PoorEnvironmentConditions:freezingFog, PoorEnvironmentConditions:moderateFog, PoorEnvironmentConditions:patchyFog | +| `weather_condition.weather.fog` | cifs | HAZARD_WEATHER_FOG | | `weather_condition.weather.fog` | traff | WEATHER_FOG | | `weather_condition.weather.fog` | road511 | weather/fog | | `weather_condition.weather.extreme_cold` | datex2_v3 | PoorEnvironmentConditions:extremeCold | @@ -1457,6 +1472,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `weather_condition.weather.extreme_cold` | traff | WEATHER_EXTREME_COLD | | `weather_condition.weather.extreme_heat` | datex2_v3 | PoorEnvironmentConditions:extremeHeat | | `weather_condition.weather.extreme_heat` | datex2_v2 | PoorEnvironmentConditions:extremeHeat | +| `weather_condition.weather.extreme_heat` | cifs | HAZARD_WEATHER_HEAT_WAVE | | `weather_condition.weather.extreme_heat` | traff | WEATHER_EXTREME_HEAT | | `weather_condition.weather.ice` | datex2_v3 | PoorEnvironmentConditions:frost, PoorEnvironmentConditions:heavyFrost | | `weather_condition.weather.ice` | datex2_v2 | PoorEnvironmentConditions:frost, PoorEnvironmentConditions:heavyFrost | @@ -1465,9 +1481,11 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `weather_condition.weather.heavy_rain` | datex2_v3 | PoorEnvironmentConditions:heavyRain | | `weather_condition.weather.heavy_rain` | datex2_v2 | PoorEnvironmentConditions:heavyRain | | `weather_condition.weather.heavy_rain` | open511 | HEAVY_DOWNPOUR | +| `weather_condition.weather.heavy_rain` | cifs | HAZARD_WEATHER_HEAVY_RAIN, HAZARD_WEATHER_MONSOON | | `weather_condition.weather.heavy_rain` | traff | WEATHER_HEAVY_RAIN | | `weather_condition.weather.storm` | datex2_v3 | PoorEnvironmentConditions:hurricaneForceWinds, PoorEnvironmentConditions:stormForceWinds, PoorEnvironmentConditions:tornadoes | | `weather_condition.weather.storm` | datex2_v2 | PoorEnvironmentConditions:hurricaneForceWinds, PoorEnvironmentConditions:stormForceWinds, PoorEnvironmentConditions:tornadoes | +| `weather_condition.weather.storm` | cifs | HAZARD_WEATHER_HURRICANE, HAZARD_WEATHER_TORNADO | | `weather_condition.weather.storm` | traff | WEATHER_STORM | | `weather_condition.weather.low_sun` | datex2_v3 | PoorEnvironmentConditions:lowSunGlare | | `weather_condition.weather.low_sun` | datex2_v2 | PoorEnvironmentConditions:lowSunGlare | @@ -1486,6 +1504,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `weather_condition.weather.thunderstorm` | datex2_v2 | PoorEnvironmentConditions:thunderstorms | | `weather_condition.weather.thunderstorm` | open511 | THUNDERSTORM | | `weather_condition.weather.thunderstorm` | traff | WEATHER_THUNDERSTORM | +| `weather_condition.weather.freezing_rain` | cifs | HAZARD_WEATHER_FREEZING_RAIN | | `weather_condition.weather.freezing_rain` | traff | HAZARD_FREEZING_RAIN | | `weather_condition.weather.black_ice` | traff | HAZARD_BLACK_ICE | | `road_condition.driving_condition` | datex2_v3 | Conditions | @@ -1518,6 +1537,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `road_condition.surface.oil` | datex2_v3 | NonWeatherRelatedRoadConditions:dieselOnRoad, NonWeatherRelatedRoadConditions:oilOnRoad, NonWeatherRelatedRoadConditions:petrolOnRoad | | `road_condition.surface.oil` | datex2_v2 | NonWeatherRelatedRoadConditions:dieselOnRoad, NonWeatherRelatedRoadConditions:oilOnRoad, NonWeatherRelatedRoadConditions:petrolOnRoad | | `road_condition.surface.oil` | open511 | OIL_ON_ROADWAY | +| `road_condition.surface.oil` | cifs | HAZARD_ON_ROAD_OIL | | `road_condition.surface.oil` | traff | HAZARD_OIL_ON_ROAD | | `road_condition.surface.leaves` | datex2_v3 | NonWeatherRelatedRoadConditions:leavesOnRoad | | `road_condition.surface.leaves` | datex2_v2 | NonWeatherRelatedRoadConditions:leavesOnRoad | @@ -1539,6 +1559,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `road_condition.surface.icy` | datex2_v3 | WeatherRelatedRoadConditions:blackIce, WeatherRelatedRoadConditions:freezingOfWetRoads, WeatherRelatedRoadConditions:freezingPavements, WeatherRelatedRoadConditions:freezingRain, WeatherRelatedRoadConditions:glaze, WeatherRelatedRoadConditions:ice, WeatherRelatedRoadConditions:iceBuildUp, WeatherRelatedRoadConditions:iceWithWheelBarTracks, WeatherRelatedRoadConditions:icyPatches, WeatherRelatedRoadConditions:wetAndIcyRoad, WeatherRelatedRoadConditions:wetIcyPavement | | `road_condition.surface.icy` | datex2_v2 | WeatherRelatedRoadConditions:blackIce, WeatherRelatedRoadConditions:freezingOfWetRoads, WeatherRelatedRoadConditions:freezingPavements, WeatherRelatedRoadConditions:freezingRain, WeatherRelatedRoadConditions:ice, WeatherRelatedRoadConditions:iceBuildUp, WeatherRelatedRoadConditions:iceWithWheelBarTracks, WeatherRelatedRoadConditions:icyPatches, WeatherRelatedRoadConditions:wetAndIcyRoad, WeatherRelatedRoadConditions:wetIcyPavement | | `road_condition.surface.icy` | open511 | PARTLY_ICY, ICE_COVERED | +| `road_condition.surface.icy` | cifs | HAZARD_ON_ROAD_ICE | | `road_condition.surface.icy` | traff | HAZARD_ICE | | `road_condition.surface.icy` | road511 | road_condition/icy | | `road_condition.surface.snow_covered` | datex2_v3 | WeatherRelatedRoadConditions:deepSnow, WeatherRelatedRoadConditions:freshSnow, WeatherRelatedRoadConditions:looseSnow, WeatherRelatedRoadConditions:packedSnow, WeatherRelatedRoadConditions:snow, WeatherRelatedRoadConditions:snowDrifts, WeatherRelatedRoadConditions:snowOnPavement, WeatherRelatedRoadConditions:snowOnTheRoad | @@ -1572,17 +1593,20 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `road_hazard.hazard.ice_fall` | datex2_v2 | EnvironmentalObstruction:fallingIce, EnvironmentalObstruction:fallingLightIceOrSnow | | `road_hazard.hazard.flooding` | datex2_v3 | EnvironmentalObstruction:flashFloods, EnvironmentalObstruction:flooding, EnvironmentalObstruction:sewerOverflow, PoorEnvironmentConditions:nearbyFlooding | | `road_hazard.hazard.flooding` | datex2_v2 | EnvironmentalObstruction:flashFloods, EnvironmentalObstruction:flooding, EnvironmentalObstruction:sewerOverflow | +| `road_hazard.hazard.flooding` | cifs | HAZARD_WEATHER_FLOOD | | `road_hazard.hazard.flooding` | traff | HAZARD_FLOODING | | `road_hazard.hazard.flooding` | road511 | weather/flooding | | `road_hazard.hazard.wildfire_near_road` | datex2_v3 | EnvironmentalObstruction:forestFire, PoorEnvironmentConditions:nearbyFire | | `road_hazard.hazard.wildfire_near_road` | datex2_v2 | EnvironmentalObstruction:forestFire | | `road_hazard.hazard.wildfire_near_road` | traff | HAZARD_FOREST_FIRE | | `road_hazard.hazard` | open511 | HAZARD | +| `road_hazard.hazard` | cifs | HAZARD, HAZARD_ON_SHOULDER, ROAD_CLOSED_HAZARD | | `road_hazard.hazard` | traff | HAZARD_HAZARDOUS_CONDITIONS | | `road_hazard.hazard` | gtfs_rt | WEATHER | | `road_hazard.hazard` | road511 | hazard | -| `road_hazard.hazard.high_water` | traff | HAZARD_FLOODING | +| `road_hazard.hazard.wildlife` | cifs | HAZARD_ON_SHOULDER_ANIMALS | | `road_hazard.hazard.wildlife` | traff | HAZARD_LARGE_ANIMALS_ON_ROAD | +| `road_hazard.hazard.high_water` | traff | HAZARD_FLOODING | | `public_event.event.demonstration` | datex2_v3 | DisturbanceActivity:blockadeOrBarrier, DisturbanceActivity:demonstration, DisturbanceActivity:filterBlockade, DisturbanceActivity:goSlowOperation, DisturbanceActivity:march, DisturbanceActivity:strike | | `public_event.event.demonstration` | datex2_v2 | DisturbanceActivity:blockadeOrBarrier, DisturbanceActivity:demonstration, DisturbanceActivity:filterBlockade, DisturbanceActivity:goSlowOperation, DisturbanceActivity:march, DisturbanceActivity:strike | | `public_event.event.demonstration` | traff | ACTIVITY_DEMONSTRATION | @@ -1591,6 +1615,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `public_event.event` | datex2_v2 | DisturbanceActivity:crowd, PublicEvent | | `public_event.event` | open511 | SPECIAL_EVENT | | `public_event.event` | ibi511 | specialEvents | +| `public_event.event` | cifs | ROAD_CLOSED_EVENT | | `public_event.event` | traff | ACTIVITY_EVENT | | `public_event.event` | gtfs_rt | OTHER_CAUSE | | `public_event.event` | road511 | special_event | @@ -1632,6 +1657,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `authority.operation` | road511 | incident/police_activity | | `authority.operation.police_activity` | datex2_v3 | AuthorityOperation:accidentInvestigationWork, AuthorityOperation:juridicalReconstruction, AuthorityOperation:policeInvestigation | | `authority.operation.police_activity` | datex2_v2 | AuthorityOperation:accidentInvestigationWork, AuthorityOperation:juridicalReconstruction, AuthorityOperation:policeInvestigation | +| `authority.operation.police_activity` | cifs | POLICE, POLICE_VISIBLE, POLICE_HIDING | | `authority.operation.police_activity` | traff | AUTHORITY_INVESTIGATION | | `authority.operation.customs` | datex2_v3 | AuthorityOperation:customsOperation | | `authority.operation.customs` | datex2_v2 | AuthorityOperation:customsOperation | @@ -1641,6 +1667,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `authority.operation.vehicle_inspection` | datex2_v2 | AuthorityOperation:roadOperatorCheckPoint, AuthorityOperation:vehicleInspectionCheckPoint | | `authority.operation.enforcement` | datex2_v3 | AuthorityOperation:snowChainOnBoardOrSnowTyresMountedCheck, AuthorityOperation:snowChainOrSnowTyresMountedCheck, SpeedManagement:policeSpeedChecksInOperation | | `authority.operation.enforcement` | datex2_v2 | SpeedManagement:policeSpeedChecksInOperation | +| `authority.operation.enforcement` | cifs | POLICE_WITH_MOBILE_CAMERA | | `authority.operation.enforcement` | traff | AUTHORITY_SPEED_CHECKS | | `authority.operation.survey` | datex2_v3 | AuthorityOperation:survey | | `authority.operation.survey` | datex2_v2 | AuthorityOperation:survey | @@ -1656,6 +1683,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `authority.operation.military_convoy` | traff | HAZARD_MILITARY_CONVOY | | `equipment_fault.fault` | datex2_v3 | EquipmentOrSystemFault, RoadOperatorServiceDisruption | | `equipment_fault.fault` | datex2_v2 | EquipmentOrSystemFault, RoadOperatorServiceDisruption | +| `equipment_fault.fault` | cifs | HAZARD_ON_SHOULDER_MISSING_SIGN | | `equipment_fault.fault` | gtfs_rt | TECHNICAL_PROBLEM | | `equipment_fault.fault` | road511 | advisory | | `equipment_fault.fault.emergency_phone` | datex2_v3 | RoadOperatorServiceDisruption:emergencyTelephoneNumberOutOfService | @@ -1664,6 +1692,7 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `equipment_fault.fault.communications` | datex2_v3 | RoadOperatorServiceDisruption:informationServiceTelephoneNumberOutOfService | | `equipment_fault.fault.communications` | datex2_v2 | RoadOperatorServiceDisruption:informationServiceTelephoneNumberOutOfService | | `equipment_fault.fault.traffic_signal` | open511 | SIGNAL_LIGHT_FAILURE | +| `equipment_fault.fault.traffic_signal` | cifs | HAZARD_ON_ROAD_TRAFFIC_LIGHT_FAULT | | `equipment_fault.fault.traffic_signal` | traff | EQUIPMENT_STATUS_TRAFFIC_LIGHTS_NOT_WORKING | | `equipment_fault.fault.level_crossing` | traff | EQUIPMENT_STATUS_LEVEL_CROSSING_NOT_WORKING | | `equipment_fault.fault.toll_system` | traff | EQUIPMENT_STATUS_AUTOMATIC_TOLL_SYSTEM_NOT_WORKING | @@ -1700,19 +1729,24 @@ Kernel version `1.2`; modules: `kernel`, `roads`, `weather`, `vehicles`, `parkin | `pass_status.pass` | gtfs_rt | WEATHER | | `congestion.congestion` | datex2_v3 | AbnormalTraffic | | `congestion.congestion` | datex2_v2 | AbnormalTraffic | +| `congestion.congestion` | cifs | JAM | | `congestion.congestion` | traff | CONGESTION_TRAFFIC_CONGESTION | | `congestion.congestion` | gtfs_rt | OTHER_CAUSE | | `congestion.congestion.stationary` | datex2_v3 | AbnormalTraffic:stationaryTraffic | | `congestion.congestion.stationary` | datex2_v2 | AbnormalTraffic:stationaryTraffic | +| `congestion.congestion.stationary` | cifs | JAM_STAND_STILL_TRAFFIC | | `congestion.congestion.stationary` | traff | CONGESTION_STATIONARY_TRAFFIC | | `congestion.congestion.queuing` | datex2_v3 | AbnormalTraffic:queuingTraffic | | `congestion.congestion.queuing` | datex2_v2 | AbnormalTraffic:queuingTraffic | +| `congestion.congestion.queuing` | cifs | JAM_HEAVY_TRAFFIC | | `congestion.congestion.queuing` | traff | CONGESTION_QUEUE | | `congestion.congestion.slow` | datex2_v3 | AbnormalTraffic:slowTraffic | | `congestion.congestion.slow` | datex2_v2 | AbnormalTraffic:slowTraffic | +| `congestion.congestion.slow` | cifs | JAM_LIGHT_TRAFFIC | | `congestion.congestion.slow` | traff | CONGESTION_SLOW_TRAFFIC | | `congestion.congestion.heavy` | datex2_v3 | AbnormalTraffic:heavyTraffic | | `congestion.congestion.heavy` | datex2_v2 | AbnormalTraffic:heavyTraffic | +| `congestion.congestion.heavy` | cifs | JAM_MODERATE_TRAFFIC | | `congestion.congestion.heavy` | traff | CONGESTION_HEAVY_TRAFFIC | | `congestion.congestion.stop_and_go` | traff | CONGESTION_QUEUE | | `other.other` | datex2_v3 | GeneralInstructionOrMessageToRoadUsers, GeneralNetworkManagement, GenericSituationRecord, RoadOrCarriagewayOrLaneManagement, ServiceDisruption, SpeedManagement:doNotSlowdownUnnecessarily, TransitInformation | diff --git a/docs/speed-coverage.md b/docs/speed-coverage.md index cee8ba705..d14be0162 100644 --- a/docs/speed-coverage.md +++ b/docs/speed-coverage.md @@ -76,10 +76,7 @@ OHGO). DATEX II models this correctly as-is: `loc:PointLocation` is a valid DATEX II v3 location type for a point sensor, so no linear geometry is needed and the emitter never fabricates one by buffering a point into a segment (see `docs/datex-conformance.md` for what full SRTI conformance still requires). -**CIFS** (Waze/Google) is not built yet and does expect a linear polyline plus -a direction; how a point-sensor reading should project into a CIFS `line` is -an open design question left to whenever CIFS is actually implemented — it -must not silently invent geometry either. +**CIFS** (Waze/Google) is implemented in `@openconditions/roads` and `@openconditions/publishers` (see [`docs/cifs.md`](./cifs.md)). The CIFS emitter never fabricates linear geometry from a point sensor: point-only alerts are exported only when they carry explicit bilateral direction (`direction.value === "both"`), and directional or unstated point-sensor congestion is withheld until linear geometry is available. ## Excluded / deferred diff --git a/feeds/schema/roads.schema.json b/feeds/schema/roads.schema.json index fae61a8f9..5003eebd6 100644 --- a/feeds/schema/roads.schema.json +++ b/feeds/schema/roads.schema.json @@ -67,6 +67,7 @@ "caltrans-cms", "cars", "cars-signs", + "cifs", "datex2", "datex2-elaborated", "datex2-measured", diff --git a/packages/conformance/src/standards/cifs-v2.ts b/packages/conformance/src/standards/cifs-v2.ts new file mode 100644 index 000000000..f0731b2a5 --- /dev/null +++ b/packages/conformance/src/standards/cifs-v2.ts @@ -0,0 +1,26 @@ +import type { PinnedSet } from "../pinned.js"; + +/** + * Waze / Google Closure and Incident Feed Specification (CIFS) v2 XML schema: + * https://www.gstatic.com/road-incidents/cifsv2.xsd, referenced from + * https://developers.google.com/waze/data-feed/feed-setup. Retrieved 2026-11-26. + * The schema carries no inline open-source licence header, so it is fetched + * pinned by SHA-256 rather than vendored into this repository. + * + * The schema declares its enumerations as anonymous simple types inside their + * elements (`type`, `subtype`, `direction`, `roadside`, `status`), with no + * targetNamespace. + */ +export const CIFS_V2: PinnedSet = { + id: "cifs-v2", + files: [ + { + name: "cifsv2.xsd", + url: "https://www.gstatic.com/road-incidents/cifsv2.xsd", + sha256: "a82ffb2cd92610a739bc55c9ab4b270e66e74cb546a9f5e59a34ce9af45e0f6b", + }, + ], +}; + +/** The root schema of a CIFS v2 `incidents` document. */ +export const CIFS_SCHEMA = "cifsv2.xsd"; diff --git a/packages/model-registry/schemas/effect/access@1.json b/packages/model-registry/schemas/effect/access@1.json index 07312d08f..49030d6d9 100644 --- a/packages/model-registry/schemas/effect/access@1.json +++ b/packages/model-registry/schemas/effect/access@1.json @@ -1535,6 +1535,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", diff --git a/packages/model-registry/schemas/effect/advisory@1.json b/packages/model-registry/schemas/effect/advisory@1.json index c18ee886c..12f3501f7 100644 --- a/packages/model-registry/schemas/effect/advisory@1.json +++ b/packages/model-registry/schemas/effect/advisory@1.json @@ -1511,6 +1511,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", diff --git a/packages/model-registry/schemas/effect/closure@1.json b/packages/model-registry/schemas/effect/closure@1.json index 1a8f557ba..840670d0c 100644 --- a/packages/model-registry/schemas/effect/closure@1.json +++ b/packages/model-registry/schemas/effect/closure@1.json @@ -1523,6 +1523,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", diff --git a/packages/model-registry/schemas/effect/contraflow@1.json b/packages/model-registry/schemas/effect/contraflow@1.json index 400666089..ba7b2821b 100644 --- a/packages/model-registry/schemas/effect/contraflow@1.json +++ b/packages/model-registry/schemas/effect/contraflow@1.json @@ -1507,6 +1507,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", diff --git a/packages/model-registry/schemas/effect/delay@1.json b/packages/model-registry/schemas/effect/delay@1.json index 615b8f7dc..f099a85a0 100644 --- a/packages/model-registry/schemas/effect/delay@1.json +++ b/packages/model-registry/schemas/effect/delay@1.json @@ -1551,6 +1551,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", diff --git a/packages/model-registry/schemas/effect/detour@1.json b/packages/model-registry/schemas/effect/detour@1.json index dfc82606a..cc4902a99 100644 --- a/packages/model-registry/schemas/effect/detour@1.json +++ b/packages/model-registry/schemas/effect/detour@1.json @@ -1523,6 +1523,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", diff --git a/packages/model-registry/schemas/effect/dimension_limit@1.json b/packages/model-registry/schemas/effect/dimension_limit@1.json index 0e11950dc..811734e6d 100644 --- a/packages/model-registry/schemas/effect/dimension_limit@1.json +++ b/packages/model-registry/schemas/effect/dimension_limit@1.json @@ -1541,6 +1541,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", diff --git a/packages/model-registry/schemas/effect/hazmat@1.json b/packages/model-registry/schemas/effect/hazmat@1.json index 9fc8735dc..eb2752d04 100644 --- a/packages/model-registry/schemas/effect/hazmat@1.json +++ b/packages/model-registry/schemas/effect/hazmat@1.json @@ -1532,6 +1532,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", diff --git a/packages/model-registry/schemas/effect/lane_restriction@1.json b/packages/model-registry/schemas/effect/lane_restriction@1.json index 656e65f36..ffb250a42 100644 --- a/packages/model-registry/schemas/effect/lane_restriction@1.json +++ b/packages/model-registry/schemas/effect/lane_restriction@1.json @@ -1598,6 +1598,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", diff --git a/packages/model-registry/schemas/effect/speed_limit@1.json b/packages/model-registry/schemas/effect/speed_limit@1.json index aa615f90d..a41013493 100644 --- a/packages/model-registry/schemas/effect/speed_limit@1.json +++ b/packages/model-registry/schemas/effect/speed_limit@1.json @@ -1517,6 +1517,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", diff --git a/packages/model-registry/schemas/effect/unsupported@1.json b/packages/model-registry/schemas/effect/unsupported@1.json index 5eb294dd0..db0119926 100644 --- a/packages/model-registry/schemas/effect/unsupported@1.json +++ b/packages/model-registry/schemas/effect/unsupported@1.json @@ -1510,6 +1510,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", diff --git a/packages/model-registry/schemas/feature/blackspot@1.json b/packages/model-registry/schemas/feature/blackspot@1.json index 875c78294..5473642bf 100644 --- a/packages/model-registry/schemas/feature/blackspot@1.json +++ b/packages/model-registry/schemas/feature/blackspot@1.json @@ -665,6 +665,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2168,6 +2170,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/border_crossing@1.json b/packages/model-registry/schemas/feature/border_crossing@1.json index bbd2b0942..b4eb3ed03 100644 --- a/packages/model-registry/schemas/feature/border_crossing@1.json +++ b/packages/model-registry/schemas/feature/border_crossing@1.json @@ -938,6 +938,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2441,6 +2443,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/camera@1.json b/packages/model-registry/schemas/feature/camera@1.json index efa802a13..4e806c9fb 100644 --- a/packages/model-registry/schemas/feature/camera@1.json +++ b/packages/model-registry/schemas/feature/camera@1.json @@ -837,6 +837,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2340,6 +2342,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/chain_control_zone@1.json b/packages/model-registry/schemas/feature/chain_control_zone@1.json index 4c65d0e58..209dc6348 100644 --- a/packages/model-registry/schemas/feature/chain_control_zone@1.json +++ b/packages/model-registry/schemas/feature/chain_control_zone@1.json @@ -583,6 +583,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2086,6 +2088,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/charging_site@1.json b/packages/model-registry/schemas/feature/charging_site@1.json index 9e5bb845d..ad06d53df 100644 --- a/packages/model-registry/schemas/feature/charging_site@1.json +++ b/packages/model-registry/schemas/feature/charging_site@1.json @@ -1679,6 +1679,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -3182,6 +3184,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/emergency_phone@1.json b/packages/model-registry/schemas/feature/emergency_phone@1.json index 0ecb5c2e7..299de9cf3 100644 --- a/packages/model-registry/schemas/feature/emergency_phone@1.json +++ b/packages/model-registry/schemas/feature/emergency_phone@1.json @@ -583,6 +583,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2086,6 +2088,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/ferry_route@1.json b/packages/model-registry/schemas/feature/ferry_route@1.json index 47a249e22..689093b25 100644 --- a/packages/model-registry/schemas/feature/ferry_route@1.json +++ b/packages/model-registry/schemas/feature/ferry_route@1.json @@ -822,6 +822,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2325,6 +2327,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/ferry_terminal@1.json b/packages/model-registry/schemas/feature/ferry_terminal@1.json index 3796010f1..25e82ff52 100644 --- a/packages/model-registry/schemas/feature/ferry_terminal@1.json +++ b/packages/model-registry/schemas/feature/ferry_terminal@1.json @@ -588,6 +588,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2091,6 +2093,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/fuel_station@1.json b/packages/model-registry/schemas/feature/fuel_station@1.json index 98bd78f4e..48760bc07 100644 --- a/packages/model-registry/schemas/feature/fuel_station@1.json +++ b/packages/model-registry/schemas/feature/fuel_station@1.json @@ -859,6 +859,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2362,6 +2364,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/lane_control_gantry@1.json b/packages/model-registry/schemas/feature/lane_control_gantry@1.json index 7cc1f5540..77d4beb60 100644 --- a/packages/model-registry/schemas/feature/lane_control_gantry@1.json +++ b/packages/model-registry/schemas/feature/lane_control_gantry@1.json @@ -583,6 +583,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2086,6 +2088,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/measurement_site@1.json b/packages/model-registry/schemas/feature/measurement_site@1.json index 769da7f7e..369844c33 100644 --- a/packages/model-registry/schemas/feature/measurement_site@1.json +++ b/packages/model-registry/schemas/feature/measurement_site@1.json @@ -849,6 +849,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2352,6 +2354,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/mountain_pass@1.json b/packages/model-registry/schemas/feature/mountain_pass@1.json index da1f48794..4613b10ab 100644 --- a/packages/model-registry/schemas/feature/mountain_pass@1.json +++ b/packages/model-registry/schemas/feature/mountain_pass@1.json @@ -674,6 +674,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2177,6 +2179,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/parking_site@1.json b/packages/model-registry/schemas/feature/parking_site@1.json index fefbc36a5..e5a55afb8 100644 --- a/packages/model-registry/schemas/feature/parking_site@1.json +++ b/packages/model-registry/schemas/feature/parking_site@1.json @@ -1692,6 +1692,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -3195,6 +3197,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/rail_crossing@1.json b/packages/model-registry/schemas/feature/rail_crossing@1.json index d3db15d2a..1924dbe41 100644 --- a/packages/model-registry/schemas/feature/rail_crossing@1.json +++ b/packages/model-registry/schemas/feature/rail_crossing@1.json @@ -633,6 +633,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2136,6 +2138,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/rest_area@1.json b/packages/model-registry/schemas/feature/rest_area@1.json index 72ab8c91a..1f083c998 100644 --- a/packages/model-registry/schemas/feature/rest_area@1.json +++ b/packages/model-registry/schemas/feature/rest_area@1.json @@ -619,6 +619,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2122,6 +2124,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/service_vehicle@1.json b/packages/model-registry/schemas/feature/service_vehicle@1.json index b12e49054..fb3b4872f 100644 --- a/packages/model-registry/schemas/feature/service_vehicle@1.json +++ b/packages/model-registry/schemas/feature/service_vehicle@1.json @@ -614,6 +614,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2117,6 +2119,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/structure@1.json b/packages/model-registry/schemas/feature/structure@1.json index 665a872f0..87d1e2225 100644 --- a/packages/model-registry/schemas/feature/structure@1.json +++ b/packages/model-registry/schemas/feature/structure@1.json @@ -855,6 +855,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2358,6 +2360,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/toll_point@1.json b/packages/model-registry/schemas/feature/toll_point@1.json index 4266615d0..e9cd6a631 100644 --- a/packages/model-registry/schemas/feature/toll_point@1.json +++ b/packages/model-registry/schemas/feature/toll_point@1.json @@ -883,6 +883,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2386,6 +2388,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/toll_section@1.json b/packages/model-registry/schemas/feature/toll_section@1.json index be72110a1..276f72ada 100644 --- a/packages/model-registry/schemas/feature/toll_section@1.json +++ b/packages/model-registry/schemas/feature/toll_section@1.json @@ -872,6 +872,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2375,6 +2377,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/travel_time_route@1.json b/packages/model-registry/schemas/feature/travel_time_route@1.json index be4c11dc4..c241fd3cd 100644 --- a/packages/model-registry/schemas/feature/travel_time_route@1.json +++ b/packages/model-registry/schemas/feature/travel_time_route@1.json @@ -633,6 +633,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2136,6 +2138,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/vms@1.json b/packages/model-registry/schemas/feature/vms@1.json index 0c25a2627..c8f3f15d1 100644 --- a/packages/model-registry/schemas/feature/vms@1.json +++ b/packages/model-registry/schemas/feature/vms@1.json @@ -824,6 +824,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2327,6 +2329,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/weather_station@1.json b/packages/model-registry/schemas/feature/weather_station@1.json index 1d39d1916..5878d4a19 100644 --- a/packages/model-registry/schemas/feature/weather_station@1.json +++ b/packages/model-registry/schemas/feature/weather_station@1.json @@ -825,6 +825,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2328,6 +2330,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/feature/weigh_station@1.json b/packages/model-registry/schemas/feature/weigh_station@1.json index e02d1e67e..64ac44bb7 100644 --- a/packages/model-registry/schemas/feature/weigh_station@1.json +++ b/packages/model-registry/schemas/feature/weigh_station@1.json @@ -645,6 +645,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2148,6 +2150,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/kernel@1.json b/packages/model-registry/schemas/kernel@1.json index 4b619920e..aa8b2fd42 100644 --- a/packages/model-registry/schemas/kernel@1.json +++ b/packages/model-registry/schemas/kernel@1.json @@ -919,6 +919,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2217,6 +2219,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/border.wait@1.json b/packages/model-registry/schemas/observation/border.wait@1.json index f34e41a73..5f2647ec8 100644 --- a/packages/model-registry/schemas/observation/border.wait@1.json +++ b/packages/model-registry/schemas/observation/border.wait@1.json @@ -491,6 +491,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1994,6 +1996,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/camera.image@1.json b/packages/model-registry/schemas/observation/camera.image@1.json index 77168a06b..fd0fc1fed 100644 --- a/packages/model-registry/schemas/observation/camera.image@1.json +++ b/packages/model-registry/schemas/observation/camera.image@1.json @@ -531,6 +531,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2034,6 +2036,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/charging.connector_status@1.json b/packages/model-registry/schemas/observation/charging.connector_status@1.json index ade271eab..23a0606ef 100644 --- a/packages/model-registry/schemas/observation/charging.connector_status@1.json +++ b/packages/model-registry/schemas/observation/charging.connector_status@1.json @@ -461,6 +461,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1964,6 +1966,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/charging.evse_status@1.json b/packages/model-registry/schemas/observation/charging.evse_status@1.json index fc780698f..49fcc5464 100644 --- a/packages/model-registry/schemas/observation/charging.evse_status@1.json +++ b/packages/model-registry/schemas/observation/charging.evse_status@1.json @@ -461,6 +461,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1964,6 +1966,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/charging.site_status@1.json b/packages/model-registry/schemas/observation/charging.site_status@1.json index 7bde3a6d3..1d0137050 100644 --- a/packages/model-registry/schemas/observation/charging.site_status@1.json +++ b/packages/model-registry/schemas/observation/charging.site_status@1.json @@ -457,6 +457,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1960,6 +1962,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/charging.waiting_time@1.json b/packages/model-registry/schemas/observation/charging.waiting_time@1.json index 8dec7d75c..3618da17c 100644 --- a/packages/model-registry/schemas/observation/charging.waiting_time@1.json +++ b/packages/model-registry/schemas/observation/charging.waiting_time@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/device.status@1.json b/packages/model-registry/schemas/observation/device.status@1.json index 24e479a2c..c83107ddb 100644 --- a/packages/model-registry/schemas/observation/device.status@1.json +++ b/packages/model-registry/schemas/observation/device.status@1.json @@ -456,6 +456,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1959,6 +1961,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/facility.open_status@1.json b/packages/model-registry/schemas/observation/facility.open_status@1.json index b7e558859..4dd171f2e 100644 --- a/packages/model-registry/schemas/observation/facility.open_status@1.json +++ b/packages/model-registry/schemas/observation/facility.open_status@1.json @@ -455,6 +455,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1958,6 +1960,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/ferry.status@1.json b/packages/model-registry/schemas/observation/ferry.status@1.json index c26ea69cc..016649c91 100644 --- a/packages/model-registry/schemas/observation/ferry.status@1.json +++ b/packages/model-registry/schemas/observation/ferry.status@1.json @@ -465,6 +465,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1968,6 +1970,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/ferry.vehicle_space@1.json b/packages/model-registry/schemas/observation/ferry.vehicle_space@1.json index 2a54e9b1d..ee333c23d 100644 --- a/packages/model-registry/schemas/observation/ferry.vehicle_space@1.json +++ b/packages/model-registry/schemas/observation/ferry.vehicle_space@1.json @@ -458,6 +458,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1961,6 +1963,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/fire.frp@1.json b/packages/model-registry/schemas/observation/fire.frp@1.json index 70608ff17..0d837df16 100644 --- a/packages/model-registry/schemas/observation/fire.frp@1.json +++ b/packages/model-registry/schemas/observation/fire.frp@1.json @@ -444,6 +444,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1947,6 +1949,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/fuel.price@1.json b/packages/model-registry/schemas/observation/fuel.price@1.json index cdf0ccb2e..5b8f7caee 100644 --- a/packages/model-registry/schemas/observation/fuel.price@1.json +++ b/packages/model-registry/schemas/observation/fuel.price@1.json @@ -514,6 +514,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2017,6 +2019,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/fuel.price_cap@1.json b/packages/model-registry/schemas/observation/fuel.price_cap@1.json index 02399fd82..7f75bb13b 100644 --- a/packages/model-registry/schemas/observation/fuel.price_cap@1.json +++ b/packages/model-registry/schemas/observation/fuel.price_cap@1.json @@ -492,6 +492,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1995,6 +1997,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/fuel.product_available@1.json b/packages/model-registry/schemas/observation/fuel.product_available@1.json index aa2c96d86..e6b69140f 100644 --- a/packages/model-registry/schemas/observation/fuel.product_available@1.json +++ b/packages/model-registry/schemas/observation/fuel.product_available@1.json @@ -444,6 +444,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1947,6 +1949,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/parking.available@1.json b/packages/model-registry/schemas/observation/parking.available@1.json index 1a5189987..9d8742726 100644 --- a/packages/model-registry/schemas/observation/parking.available@1.json +++ b/packages/model-registry/schemas/observation/parking.available@1.json @@ -446,6 +446,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1949,6 +1951,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/parking.occupancy_pct@1.json b/packages/model-registry/schemas/observation/parking.occupancy_pct@1.json index 23fed6269..edfb637d5 100644 --- a/packages/model-registry/schemas/observation/parking.occupancy_pct@1.json +++ b/packages/model-registry/schemas/observation/parking.occupancy_pct@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/parking.occupied@1.json b/packages/model-registry/schemas/observation/parking.occupied@1.json index 91c31b9dc..866ffe4cd 100644 --- a/packages/model-registry/schemas/observation/parking.occupied@1.json +++ b/packages/model-registry/schemas/observation/parking.occupied@1.json @@ -446,6 +446,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1949,6 +1951,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/parking.status@1.json b/packages/model-registry/schemas/observation/parking.status@1.json index 2fda5c848..9bd10b88e 100644 --- a/packages/model-registry/schemas/observation/parking.status@1.json +++ b/packages/model-registry/schemas/observation/parking.status@1.json @@ -458,6 +458,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1961,6 +1963,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/parking.trend@1.json b/packages/model-registry/schemas/observation/parking.trend@1.json index d040a6676..d650f0bbd 100644 --- a/packages/model-registry/schemas/observation/parking.trend@1.json +++ b/packages/model-registry/schemas/observation/parking.trend@1.json @@ -456,6 +456,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1959,6 +1961,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/pass.status@1.json b/packages/model-registry/schemas/observation/pass.status@1.json index bf737ca09..38b414359 100644 --- a/packages/model-registry/schemas/observation/pass.status@1.json +++ b/packages/model-registry/schemas/observation/pass.status@1.json @@ -472,6 +472,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1975,6 +1977,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/road.condition_forecast@1.json b/packages/model-registry/schemas/observation/road.condition_forecast@1.json index 5f07a810a..a810e1ad8 100644 --- a/packages/model-registry/schemas/observation/road.condition_forecast@1.json +++ b/packages/model-registry/schemas/observation/road.condition_forecast@1.json @@ -519,6 +519,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2022,6 +2024,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/road.freezing_point@1.json b/packages/model-registry/schemas/observation/road.freezing_point@1.json index 914b23a11..f7b63ecc5 100644 --- a/packages/model-registry/schemas/observation/road.freezing_point@1.json +++ b/packages/model-registry/schemas/observation/road.freezing_point@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/road.friction@1.json b/packages/model-registry/schemas/observation/road.friction@1.json index f7e506d9d..83fd69c76 100644 --- a/packages/model-registry/schemas/observation/road.friction@1.json +++ b/packages/model-registry/schemas/observation/road.friction@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/road.ice_thickness@1.json b/packages/model-registry/schemas/observation/road.ice_thickness@1.json index 631547d2f..2aa20837d 100644 --- a/packages/model-registry/schemas/observation/road.ice_thickness@1.json +++ b/packages/model-registry/schemas/observation/road.ice_thickness@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/road.salt_amount@1.json b/packages/model-registry/schemas/observation/road.salt_amount@1.json index a0cce1776..c87c20020 100644 --- a/packages/model-registry/schemas/observation/road.salt_amount@1.json +++ b/packages/model-registry/schemas/observation/road.salt_amount@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/road.salt_concentration@1.json b/packages/model-registry/schemas/observation/road.salt_concentration@1.json index 0322faf34..c64bedd88 100644 --- a/packages/model-registry/schemas/observation/road.salt_concentration@1.json +++ b/packages/model-registry/schemas/observation/road.salt_concentration@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/road.snow_depth@1.json b/packages/model-registry/schemas/observation/road.snow_depth@1.json index 26785be31..d7c94c5fc 100644 --- a/packages/model-registry/schemas/observation/road.snow_depth@1.json +++ b/packages/model-registry/schemas/observation/road.snow_depth@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/road.subsurface_temperature@1.json b/packages/model-registry/schemas/observation/road.subsurface_temperature@1.json index 9b21ad226..a3b241d62 100644 --- a/packages/model-registry/schemas/observation/road.subsurface_temperature@1.json +++ b/packages/model-registry/schemas/observation/road.subsurface_temperature@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/road.surface_state@1.json b/packages/model-registry/schemas/observation/road.surface_state@1.json index d89c980b8..6a213bc2f 100644 --- a/packages/model-registry/schemas/observation/road.surface_state@1.json +++ b/packages/model-registry/schemas/observation/road.surface_state@1.json @@ -528,6 +528,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2031,6 +2033,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/road.surface_temperature@1.json b/packages/model-registry/schemas/observation/road.surface_temperature@1.json index 9842159cf..f798f1453 100644 --- a/packages/model-registry/schemas/observation/road.surface_temperature@1.json +++ b/packages/model-registry/schemas/observation/road.surface_temperature@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/road.water_film@1.json b/packages/model-registry/schemas/observation/road.water_film@1.json index caf9be3f9..4ac4485e6 100644 --- a/packages/model-registry/schemas/observation/road.water_film@1.json +++ b/packages/model-registry/schemas/observation/road.water_film@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/toll.price@1.json b/packages/model-registry/schemas/observation/toll.price@1.json index 9e0bd0790..107504bbe 100644 --- a/packages/model-registry/schemas/observation/toll.price@1.json +++ b/packages/model-registry/schemas/observation/toll.price@1.json @@ -483,6 +483,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1986,6 +1988,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/traffic.los@1.json b/packages/model-registry/schemas/observation/traffic.los@1.json index bb9d0862f..64167f32a 100644 --- a/packages/model-registry/schemas/observation/traffic.los@1.json +++ b/packages/model-registry/schemas/observation/traffic.los@1.json @@ -522,6 +522,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2025,6 +2027,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/traffic.occupancy@1.json b/packages/model-registry/schemas/observation/traffic.occupancy@1.json index 032e5b3d2..f39a84598 100644 --- a/packages/model-registry/schemas/observation/traffic.occupancy@1.json +++ b/packages/model-registry/schemas/observation/traffic.occupancy@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/traffic.speed@1.json b/packages/model-registry/schemas/observation/traffic.speed@1.json index c09e28953..49011007d 100644 --- a/packages/model-registry/schemas/observation/traffic.speed@1.json +++ b/packages/model-registry/schemas/observation/traffic.speed@1.json @@ -517,6 +517,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2020,6 +2022,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/traffic.travel_time@1.json b/packages/model-registry/schemas/observation/traffic.travel_time@1.json index 437d0cb10..ba4d426f3 100644 --- a/packages/model-registry/schemas/observation/traffic.travel_time@1.json +++ b/packages/model-registry/schemas/observation/traffic.travel_time@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/traffic.vehicle_class_speed@1.json b/packages/model-registry/schemas/observation/traffic.vehicle_class_speed@1.json index bd32886ae..4a7ba3c6d 100644 --- a/packages/model-registry/schemas/observation/traffic.vehicle_class_speed@1.json +++ b/packages/model-registry/schemas/observation/traffic.vehicle_class_speed@1.json @@ -475,6 +475,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1978,6 +1980,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/traffic.volume@1.json b/packages/model-registry/schemas/observation/traffic.volume@1.json index ca5c6f390..4403b3863 100644 --- a/packages/model-registry/schemas/observation/traffic.volume@1.json +++ b/packages/model-registry/schemas/observation/traffic.volume@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/vehicle.position@1.json b/packages/model-registry/schemas/observation/vehicle.position@1.json index 0b2242c4c..f2213fcae 100644 --- a/packages/model-registry/schemas/observation/vehicle.position@1.json +++ b/packages/model-registry/schemas/observation/vehicle.position@1.json @@ -645,6 +645,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2148,6 +2150,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/vms.display@1.json b/packages/model-registry/schemas/observation/vms.display@1.json index c6d546db1..424d16367 100644 --- a/packages/model-registry/schemas/observation/vms.display@1.json +++ b/packages/model-registry/schemas/observation/vms.display@1.json @@ -622,6 +622,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2125,6 +2127,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/weather.air_temperature@1.json b/packages/model-registry/schemas/observation/weather.air_temperature@1.json index 1d166c49e..f9dbbf97c 100644 --- a/packages/model-registry/schemas/observation/weather.air_temperature@1.json +++ b/packages/model-registry/schemas/observation/weather.air_temperature@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/weather.dew_point@1.json b/packages/model-registry/schemas/observation/weather.dew_point@1.json index 6dbc4d087..75cdf7aea 100644 --- a/packages/model-registry/schemas/observation/weather.dew_point@1.json +++ b/packages/model-registry/schemas/observation/weather.dew_point@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/weather.humidity@1.json b/packages/model-registry/schemas/observation/weather.humidity@1.json index 3c7d29938..bd6396c55 100644 --- a/packages/model-registry/schemas/observation/weather.humidity@1.json +++ b/packages/model-registry/schemas/observation/weather.humidity@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/weather.precipitation_amount@1.json b/packages/model-registry/schemas/observation/weather.precipitation_amount@1.json index e21e2ee79..8adf1f6e0 100644 --- a/packages/model-registry/schemas/observation/weather.precipitation_amount@1.json +++ b/packages/model-registry/schemas/observation/weather.precipitation_amount@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/weather.precipitation_rate@1.json b/packages/model-registry/schemas/observation/weather.precipitation_rate@1.json index 53641807d..a5ac1fb42 100644 --- a/packages/model-registry/schemas/observation/weather.precipitation_rate@1.json +++ b/packages/model-registry/schemas/observation/weather.precipitation_rate@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/weather.precipitation_type@1.json b/packages/model-registry/schemas/observation/weather.precipitation_type@1.json index 1fd063c48..efad5006f 100644 --- a/packages/model-registry/schemas/observation/weather.precipitation_type@1.json +++ b/packages/model-registry/schemas/observation/weather.precipitation_type@1.json @@ -458,6 +458,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1961,6 +1963,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/weather.visibility@1.json b/packages/model-registry/schemas/observation/weather.visibility@1.json index 9345aaf69..308cf2eab 100644 --- a/packages/model-registry/schemas/observation/weather.visibility@1.json +++ b/packages/model-registry/schemas/observation/weather.visibility@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/weather.wind_direction@1.json b/packages/model-registry/schemas/observation/weather.wind_direction@1.json index 022a6362e..66eb6c9f7 100644 --- a/packages/model-registry/schemas/observation/weather.wind_direction@1.json +++ b/packages/model-registry/schemas/observation/weather.wind_direction@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/weather.wind_gust@1.json b/packages/model-registry/schemas/observation/weather.wind_gust@1.json index 0c4f93f31..c86d89970 100644 --- a/packages/model-registry/schemas/observation/weather.wind_gust@1.json +++ b/packages/model-registry/schemas/observation/weather.wind_gust@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/weather.wind_speed@1.json b/packages/model-registry/schemas/observation/weather.wind_speed@1.json index ecd852905..05791ac15 100644 --- a/packages/model-registry/schemas/observation/weather.wind_speed@1.json +++ b/packages/model-registry/schemas/observation/weather.wind_speed@1.json @@ -453,6 +453,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1956,6 +1958,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/observation/winter.chain_level@1.json b/packages/model-registry/schemas/observation/winter.chain_level@1.json index a4586147c..0ebaaabe4 100644 --- a/packages/model-registry/schemas/observation/winter.chain_level@1.json +++ b/packages/model-registry/schemas/observation/winter.chain_level@1.json @@ -455,6 +455,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1958,6 +1960,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/offer/energy_tariff@1.json b/packages/model-registry/schemas/offer/energy_tariff@1.json index a8fcbf376..050836032 100644 --- a/packages/model-registry/schemas/offer/energy_tariff@1.json +++ b/packages/model-registry/schemas/offer/energy_tariff@1.json @@ -474,6 +474,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1977,6 +1979,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/offer/fare@1.json b/packages/model-registry/schemas/offer/fare@1.json index a56e66413..7cce4caf0 100644 --- a/packages/model-registry/schemas/offer/fare@1.json +++ b/packages/model-registry/schemas/offer/fare@1.json @@ -474,6 +474,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1977,6 +1979,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/offer/parking_rate@1.json b/packages/model-registry/schemas/offer/parking_rate@1.json index c10c35552..88af11b31 100644 --- a/packages/model-registry/schemas/offer/parking_rate@1.json +++ b/packages/model-registry/schemas/offer/parking_rate@1.json @@ -474,6 +474,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1977,6 +1979,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/offer/toll@1.json b/packages/model-registry/schemas/offer/toll@1.json index ed6ef71a1..c4b1b2182 100644 --- a/packages/model-registry/schemas/offer/toll@1.json +++ b/packages/model-registry/schemas/offer/toll@1.json @@ -474,6 +474,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1977,6 +1979,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/alert@1.json b/packages/model-registry/schemas/situation/alert@1.json index e93cfeb6b..386b60f6f 100644 --- a/packages/model-registry/schemas/situation/alert@1.json +++ b/packages/model-registry/schemas/situation/alert@1.json @@ -1072,6 +1072,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2575,6 +2577,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/authority@1.json b/packages/model-registry/schemas/situation/authority@1.json index a7d0dba73..83c55994f 100644 --- a/packages/model-registry/schemas/situation/authority@1.json +++ b/packages/model-registry/schemas/situation/authority@1.json @@ -418,6 +418,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1921,6 +1923,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/closure@1.json b/packages/model-registry/schemas/situation/closure@1.json index 9941f6b35..320da1d46 100644 --- a/packages/model-registry/schemas/situation/closure@1.json +++ b/packages/model-registry/schemas/situation/closure@1.json @@ -418,6 +418,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1921,6 +1923,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/congestion@1.json b/packages/model-registry/schemas/situation/congestion@1.json index 49311e5ff..cd47c3598 100644 --- a/packages/model-registry/schemas/situation/congestion@1.json +++ b/packages/model-registry/schemas/situation/congestion@1.json @@ -443,6 +443,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1946,6 +1948,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/equipment_fault@1.json b/packages/model-registry/schemas/situation/equipment_fault@1.json index 0e88880b0..5e4aff4ab 100644 --- a/packages/model-registry/schemas/situation/equipment_fault@1.json +++ b/packages/model-registry/schemas/situation/equipment_fault@1.json @@ -421,6 +421,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1924,6 +1926,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/incident@1.json b/packages/model-registry/schemas/situation/incident@1.json index ab55919ce..11b4f51b9 100644 --- a/packages/model-registry/schemas/situation/incident@1.json +++ b/packages/model-registry/schemas/situation/incident@1.json @@ -462,6 +462,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1965,6 +1967,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/natural_hazard@1.json b/packages/model-registry/schemas/situation/natural_hazard@1.json index 200fb6376..2b96e647f 100644 --- a/packages/model-registry/schemas/situation/natural_hazard@1.json +++ b/packages/model-registry/schemas/situation/natural_hazard@1.json @@ -892,6 +892,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2395,6 +2397,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/other@1.json b/packages/model-registry/schemas/situation/other@1.json index dcc16ca64..7a2483ec9 100644 --- a/packages/model-registry/schemas/situation/other@1.json +++ b/packages/model-registry/schemas/situation/other@1.json @@ -418,6 +418,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1921,6 +1923,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/pass_status@1.json b/packages/model-registry/schemas/situation/pass_status@1.json index 7414da410..474da38f6 100644 --- a/packages/model-registry/schemas/situation/pass_status@1.json +++ b/packages/model-registry/schemas/situation/pass_status@1.json @@ -424,6 +424,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1927,6 +1929,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/public_event@1.json b/packages/model-registry/schemas/situation/public_event@1.json index 323bdf5be..980f902c3 100644 --- a/packages/model-registry/schemas/situation/public_event@1.json +++ b/packages/model-registry/schemas/situation/public_event@1.json @@ -426,6 +426,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1929,6 +1931,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/restriction@1.json b/packages/model-registry/schemas/situation/restriction@1.json index 029b77569..33e66b62b 100644 --- a/packages/model-registry/schemas/situation/restriction@1.json +++ b/packages/model-registry/schemas/situation/restriction@1.json @@ -446,6 +446,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1949,6 +1951,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/road_condition@1.json b/packages/model-registry/schemas/situation/road_condition@1.json index 08b526927..409db0d32 100644 --- a/packages/model-registry/schemas/situation/road_condition@1.json +++ b/packages/model-registry/schemas/situation/road_condition@1.json @@ -468,6 +468,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1971,6 +1973,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/road_hazard@1.json b/packages/model-registry/schemas/situation/road_hazard@1.json index 25629bdf9..b16a2fe06 100644 --- a/packages/model-registry/schemas/situation/road_hazard@1.json +++ b/packages/model-registry/schemas/situation/road_hazard@1.json @@ -427,6 +427,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1930,6 +1932,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/roadworks@1.json b/packages/model-registry/schemas/situation/roadworks@1.json index 59576cfc3..6a373781c 100644 --- a/packages/model-registry/schemas/situation/roadworks@1.json +++ b/packages/model-registry/schemas/situation/roadworks@1.json @@ -571,6 +571,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -2074,6 +2076,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/security@1.json b/packages/model-registry/schemas/situation/security@1.json index fe02f148d..ce9c5e8ec 100644 --- a/packages/model-registry/schemas/situation/security@1.json +++ b/packages/model-registry/schemas/situation/security@1.json @@ -418,6 +418,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1921,6 +1923,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/weather_condition@1.json b/packages/model-registry/schemas/situation/weather_condition@1.json index f2f47db56..3499ca1ae 100644 --- a/packages/model-registry/schemas/situation/weather_condition@1.json +++ b/packages/model-registry/schemas/situation/weather_condition@1.json @@ -439,6 +439,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1942,6 +1944,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-registry/schemas/situation/winter_operation@1.json b/packages/model-registry/schemas/situation/winter_operation@1.json index 05a781637..3e4789e63 100644 --- a/packages/model-registry/schemas/situation/winter_operation@1.json +++ b/packages/model-registry/schemas/situation/winter_operation@1.json @@ -427,6 +427,8 @@ "bnetza", "cpo", "provider", + "cifs:incident", + "cifs:parent_event", "siren", "afdc", "netex:line", @@ -1930,6 +1932,7 @@ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", diff --git a/packages/model-roads/src/__tests__/coverage.test.ts b/packages/model-roads/src/__tests__/coverage.test.ts index 283a2f062..1676c097e 100644 --- a/packages/model-roads/src/__tests__/coverage.test.ts +++ b/packages/model-roads/src/__tests__/coverage.test.ts @@ -12,6 +12,7 @@ import { } from "@openconditions/model"; import { describe, expect, it } from "vitest"; import { CAUSE_NATURES } from "../cause-natures.js"; +import { CIFS_INCIDENTS, CIFS_SITUATIONS, isValidCifsPair } from "../crosswalk/cifs.js"; import { DATEX2_CAUSES, DATEX2_CERTAINTIES, @@ -65,6 +66,7 @@ import { WORKER_PRESENCE_METHODS, } from "../kinds.js"; import { roadsModule } from "../module.js"; +import { CIFS_SUBTYPES, CIFS_TYPES, CIFS_XSD_SUBTYPES } from "../vocabularies/cifs.js"; import { DATEX2_V2, DATEX2_V3 } from "../vocabularies/datex2.js"; import { GTFS_RT } from "../vocabularies/gtfs-rt.js"; import { IBI511 } from "../vocabularies/ibi511.js"; @@ -195,12 +197,18 @@ describe("source crosswalk coverage", () => { expect(sorted(Object.keys(IBI511_SITUATIONS))).toEqual(sorted(IBI511.eventTypes)); }); + it("maps every CIFS type and subtype", () => { + expect(sorted(Object.keys(CIFS_SITUATIONS))).toEqual(sorted([...CIFS_TYPES, ...CIFS_SUBTYPES])); + expect(CIFS_SITUATIONS.CHIT_CHAT).toBeNull(); + }); + it("maps only to registered classifications and values", () => { for (const table of [ DATEX2_SITUATIONS, WZDX_SITUATIONS, OPEN511_SITUATIONS, IBI511_SITUATIONS, + CIFS_SITUATIONS, DIGITRAFFIC_SITUATIONS, LTA_SITUATIONS, GDDKIA_SITUATIONS, @@ -354,4 +362,21 @@ describe("emitter crosswalk coverage", () => { for (const cause of Object.values(GTFS_RT_CAUSE_VALUES)) expect(GTFS_RT.causes).toContain(cause); }); + + it("gives every registered type an XSD-valid CIFS incident code or an explicit null", () => { + for (const type of registeredTypes) expect(Object.keys(CIFS_INCIDENTS), type).toContain(type); + for (const [code, target] of Object.entries(CIFS_INCIDENTS)) { + expect(isRegistered(code), code).toBe(true); + if (target === null) continue; + expect(CIFS_TYPES as readonly string[], code).toContain(target.type); + expect(target.type, code).not.toBe("CONSTRUCTION"); + expect(target.type, code).not.toBe("CHIT_CHAT"); + if (target.subtype !== undefined) { + expect(CIFS_XSD_SUBTYPES as readonly string[], code).toContain(target.subtype); + } + expect(isValidCifsPair(target.type, target.subtype), code).toBe(true); + const back = CIFS_SITUATIONS[target.subtype ?? target.type]; + expect(back, `${code} → ${target.subtype ?? target.type}`).not.toBeNull(); + } + }); }); diff --git a/packages/model-roads/src/classify.ts b/packages/model-roads/src/classify.ts index 0056e69c1..5ba61d1cc 100644 --- a/packages/model-roads/src/classify.ts +++ b/packages/model-roads/src/classify.ts @@ -1,5 +1,6 @@ import { type MappingTarget, parseSituationCode, type SituationClass } from "@openconditions/model"; import { CAUSE_NATURES } from "./cause-natures.js"; +import { isValidCifsPair } from "./crosswalk/cifs.js"; import { AUTOBAHN_SITUATIONS, CARS_SITUATIONS, @@ -116,6 +117,18 @@ export function ibi511Classification(eventType: string): RoadClassification | un return lookup(["ibi511"], [eventType]); } +/** + * A CIFS incident's classification from its `type` and optional `subtype`. + * Validates that `(type, subtype)` is a legal pairing before lookup, returning + * `undefined` for unknown types, mismatched pairs, or `CHIT_CHAT`. + */ +export function cifsClassification(type: string, subtype?: string): RoadClassification | undefined { + const t = type.trim(); + const s = subtype?.trim() || undefined; + if (!isValidCifsPair(t, s)) return undefined; + return lookup(["cifs"], s !== undefined ? [s, t] : [t]); +} + /** * The classification a `kind.type[.subtype]` code names, when the roads * situation kinds register it; undefined for anything else. diff --git a/packages/model-roads/src/crosswalk/cifs.ts b/packages/model-roads/src/crosswalk/cifs.ts new file mode 100644 index 000000000..783d46575 --- /dev/null +++ b/packages/model-roads/src/crosswalk/cifs.ts @@ -0,0 +1,195 @@ +import { + CIFS_SUBTYPES_BY_TYPE, + type CifsSubtype, + type CifsType, + type CifsXsdSubtype, +} from "../vocabularies/cifs.js"; + +/** + * CIFS `type` and `subtype` → roads situation classification. Every CIFS + * subtype is globally unique across types and disjoint from the 7 top-level + * types, so all 45 non-empty codes share one ingest mapping table. Callers + * validate the `(type, subtype)` pair with {@link isValidCifsPair} before + * lookup so mismatches such as `HAZARD` + `ROAD_CLOSED_EVENT` are rejected. + * + * `ROAD_CLOSED_*` records carry their cause classification here while the CIFS + * parser separately sets `roadState: "closed"` so they gain a `closure` effect. + * `CHIT_CHAT` is not a road condition and maps to `null`. + */ +export const CIFS_SITUATIONS: Readonly> = { + ACCIDENT: "incident.accident", + ACCIDENT_MAJOR: "incident.accident", + ACCIDENT_MINOR: "incident.accident", + + CONSTRUCTION: "roadworks.works", + + HAZARD: "road_hazard.hazard", + HAZARD_ON_ROAD: "incident.obstruction", + HAZARD_ON_ROAD_CAR_STOPPED: "incident.breakdown.disabled_vehicle", + HAZARD_ON_ROAD_CONSTRUCTION: "roadworks.works.construction", + HAZARD_ON_ROAD_EMERGENCY_VEHICLE: "incident.vehicle_hazard.emergency_vehicle", + HAZARD_ON_ROAD_ICE: "road_condition.surface.icy", + HAZARD_ON_ROAD_LANE_CLOSED: "closure.closure.lane", + HAZARD_ON_ROAD_OBJECT: "incident.obstruction.object", + HAZARD_ON_ROAD_OIL: "road_condition.surface.oil", + HAZARD_ON_ROAD_POT_HOLE: "incident.obstruction.pothole", + HAZARD_ON_ROAD_ROAD_KILL: "incident.obstruction.animal", + HAZARD_ON_ROAD_TRAFFIC_LIGHT_FAULT: "equipment_fault.fault.traffic_signal", + + HAZARD_ON_SHOULDER: "road_hazard.hazard", + HAZARD_ON_SHOULDER_ANIMALS: "road_hazard.hazard.wildlife", + HAZARD_ON_SHOULDER_CAR_STOPPED: "incident.breakdown.disabled_vehicle", + HAZARD_ON_SHOULDER_MISSING_SIGN: "equipment_fault.fault", + + HAZARD_WEATHER: "weather_condition.weather", + HAZARD_WEATHER_FLOOD: "road_hazard.hazard.flooding", + HAZARD_WEATHER_FOG: "weather_condition.weather.fog", + HAZARD_WEATHER_FREEZING_RAIN: "weather_condition.weather.freezing_rain", + HAZARD_WEATHER_HAIL: "weather_condition.weather.hail", + HAZARD_WEATHER_HEAT_WAVE: "weather_condition.weather.extreme_heat", + HAZARD_WEATHER_HEAVY_RAIN: "weather_condition.weather.heavy_rain", + HAZARD_WEATHER_HEAVY_SNOW: "weather_condition.weather.snow", + HAZARD_WEATHER_HURRICANE: "weather_condition.weather.storm", + HAZARD_WEATHER_MONSOON: "weather_condition.weather.heavy_rain", + HAZARD_WEATHER_TORNADO: "weather_condition.weather.storm", + + JAM: "congestion.congestion", + JAM_LIGHT_TRAFFIC: "congestion.congestion.slow", + JAM_MODERATE_TRAFFIC: "congestion.congestion.heavy", + JAM_HEAVY_TRAFFIC: "congestion.congestion.queuing", + JAM_STAND_STILL_TRAFFIC: "congestion.congestion.stationary", + + ROAD_CLOSED: "closure.closure.full", + ROAD_CLOSED_CONSTRUCTION: "roadworks.works.construction", + ROAD_CLOSED_EVENT: "public_event.event", + ROAD_CLOSED_HAZARD: "road_hazard.hazard", + + POLICE: "authority.operation.police_activity", + POLICE_VISIBLE: "authority.operation.police_activity", + POLICE_HIDING: "authority.operation.police_activity", + POLICE_WITH_MOBILE_CAMERA: "authority.operation.enforcement", + + CHIT_CHAT: null, +}; + +/** Outbound CIFS `(type, subtype)` pair, restricted to `cifsv2.xsd` values. */ +export interface CifsIncidentCode { + type: Exclude; + subtype?: CifsXsdSubtype; +} + +/** + * Roads classification → outbound CIFS non-closure incident code. + * + * This table is explicit export policy rather than a reverse lookup of + * {@link CIFS_SITUATIONS}: it never writes deprecated top-level `CONSTRUCTION`, + * `CHIT_CHAT`, or doc-only subtypes absent from `cifsv2.xsd`. Every registered + * `kind.type` has an entry or an explicit `null`. Full road closures are + * driven by verified `closure` effects in the emitter rather than by nature + * alone, so `closure.closure` and `pass_status.pass` map to `null` here. + */ +export const CIFS_INCIDENTS: Readonly> = { + "incident.accident": { type: "ACCIDENT" }, + "incident.breakdown": { type: "HAZARD", subtype: "HAZARD_ON_ROAD_CAR_STOPPED" }, + "incident.vehicle_hazard": { type: "HAZARD", subtype: "HAZARD_ON_ROAD" }, + "incident.obstruction": { type: "HAZARD", subtype: "HAZARD_ON_ROAD" }, + "incident.obstruction.object": { type: "HAZARD", subtype: "HAZARD_ON_ROAD_OBJECT" }, + "incident.obstruction.animal": { type: "HAZARD", subtype: "HAZARD_ON_ROAD_ROAD_KILL" }, + "incident.obstruction.pothole": { type: "HAZARD", subtype: "HAZARD_ON_ROAD_POT_HOLE" }, + "incident.obstruction.stranded_vehicle": { + type: "HAZARD", + subtype: "HAZARD_ON_ROAD_CAR_STOPPED", + }, + "incident.fire": { type: "HAZARD", subtype: "HAZARD_ON_ROAD" }, + + "roadworks.works": { type: "HAZARD", subtype: "HAZARD_ON_ROAD_CONSTRUCTION" }, + + "closure.closure": null, + "restriction.dimension": null, + "restriction.access": null, + "restriction.speed": null, + "restriction.seasonal_load": null, + "winter_operation.chain_control": null, + + "weather_condition.weather": { type: "HAZARD", subtype: "HAZARD_WEATHER" }, + "weather_condition.weather.fog": { type: "HAZARD", subtype: "HAZARD_WEATHER_FOG" }, + "weather_condition.weather.freezing_rain": { + type: "HAZARD", + subtype: "HAZARD_WEATHER_FREEZING_RAIN", + }, + "weather_condition.weather.hail": { type: "HAZARD", subtype: "HAZARD_WEATHER_HAIL" }, + "weather_condition.weather.extreme_heat": { + type: "HAZARD", + subtype: "HAZARD_WEATHER_HEAT_WAVE", + }, + "weather_condition.weather.heavy_rain": { + type: "HAZARD", + subtype: "HAZARD_WEATHER_HEAVY_RAIN", + }, + "weather_condition.weather.snow": { type: "HAZARD", subtype: "HAZARD_WEATHER_HEAVY_SNOW" }, + "weather_condition.weather.blizzard": { type: "HAZARD", subtype: "HAZARD_WEATHER_HEAVY_SNOW" }, + "weather_condition.weather.storm": { type: "HAZARD", subtype: "HAZARD_WEATHER" }, + "weather_condition.weather.ice": { type: "HAZARD", subtype: "HAZARD_ON_ROAD_ICE" }, + "weather_condition.weather.black_ice": { type: "HAZARD", subtype: "HAZARD_ON_ROAD_ICE" }, + + "road_condition.surface": { type: "HAZARD", subtype: "HAZARD_ON_ROAD" }, + "road_condition.surface.icy": { type: "HAZARD", subtype: "HAZARD_ON_ROAD_ICE" }, + "road_condition.surface.oil": { type: "HAZARD", subtype: "HAZARD_ON_ROAD_OIL" }, + "road_condition.surface.standing_water": { type: "HAZARD", subtype: "HAZARD_WEATHER_FLOOD" }, + "road_condition.driving_condition": { type: "HAZARD", subtype: "HAZARD_ON_ROAD" }, + + "road_hazard.hazard": { type: "HAZARD", subtype: "HAZARD_ON_ROAD" }, + "road_hazard.hazard.flooding": { type: "HAZARD", subtype: "HAZARD_WEATHER_FLOOD" }, + "road_hazard.hazard.high_water": { type: "HAZARD", subtype: "HAZARD_WEATHER_FLOOD" }, + "road_hazard.hazard.wildlife": { type: "HAZARD", subtype: "HAZARD_ON_SHOULDER_ANIMALS" }, + + "public_event.event": null, + + "authority.operation": null, + "authority.operation.police_activity": { type: "POLICE" }, + "authority.operation.police_checkpoint": { type: "POLICE" }, + + "equipment_fault.fault": null, + "equipment_fault.fault.traffic_signal": { + type: "HAZARD", + subtype: "HAZARD_ON_ROAD_TRAFFIC_LIGHT_FAULT", + }, + + "security.incident": null, + "pass_status.pass": null, + + "congestion.congestion": { type: "JAM" }, + "congestion.congestion.slow": { type: "JAM", subtype: "JAM_LIGHT_TRAFFIC" }, + "congestion.congestion.heavy": { type: "JAM", subtype: "JAM_MODERATE_TRAFFIC" }, + "congestion.congestion.queuing": { type: "JAM", subtype: "JAM_HEAVY_TRAFFIC" }, + "congestion.congestion.stop_and_go": { type: "JAM", subtype: "JAM_HEAVY_TRAFFIC" }, + "congestion.congestion.stationary": { type: "JAM", subtype: "JAM_STAND_STILL_TRAFFIC" }, + + "other.other": null, +}; + +/** Whether `type` is a known CIFS `type` token. */ +export function isCifsType(value: string): value is CifsType { + return Object.hasOwn(CIFS_SUBTYPES_BY_TYPE, value); +} + +/** Whether `(type, subtype)` is a legal pairing in Waze's CIFS specification. */ +export function isValidCifsPair(type: string, subtype: string | undefined): boolean { + if (!isCifsType(type)) return false; + if (subtype === undefined || subtype === "") return true; + return (CIFS_SUBTYPES_BY_TYPE[type] as readonly string[]).includes(subtype); +} + +/** Outbound CIFS incident code for a situation classification (subtype first, then type). */ +export function cifsIncidentCodeOf(c: { + kind: string; + type: string; + subtype?: string; +}): CifsIncidentCode | null { + if (c.subtype !== undefined) { + const key = `${c.kind}.${c.type}.${c.subtype}`; + if (Object.hasOwn(CIFS_INCIDENTS, key)) return CIFS_INCIDENTS[key] ?? null; + } + const base = `${c.kind}.${c.type}`; + return Object.hasOwn(CIFS_INCIDENTS, base) ? (CIFS_INCIDENTS[base] ?? null) : null; +} diff --git a/packages/model-roads/src/index.ts b/packages/model-roads/src/index.ts index c4cc6c14b..1e61375eb 100644 --- a/packages/model-roads/src/index.ts +++ b/packages/model-roads/src/index.ts @@ -1,5 +1,6 @@ export * from "./cause-natures.js"; export * from "./classify.js"; +export * from "./crosswalk/cifs.js"; export * from "./crosswalk/datex2.js"; export * from "./crosswalk/emitters.js"; export * from "./crosswalk/ibi511.js"; @@ -17,6 +18,7 @@ export * from "./severity.js"; export * from "./structure-restrictions.js"; export * from "./tolls.js"; export * from "./travel-time.js"; +export * from "./vocabularies/cifs.js"; export * from "./vocabularies/datex2.js"; export * from "./vocabularies/datex2-infrastructure.js"; export * from "./vocabularies/gtfs-rt.js"; diff --git a/packages/model-roads/src/module.ts b/packages/model-roads/src/module.ts index 14d2e8ae7..6c5921b92 100644 --- a/packages/model-roads/src/module.ts +++ b/packages/model-roads/src/module.ts @@ -12,6 +12,7 @@ import { withPropertyCrosswalks, withSituationCrosswalks, } from "@openconditions/model"; +import { CIFS_SITUATIONS } from "./crosswalk/cifs.js"; import { DATEX2_CAUSES, DATEX2_CERTAINTIES, @@ -83,6 +84,7 @@ export const ROADS_SOURCE_FORMATS = [ "cars", "cars-signs", "caltrans-cms", + "cifs", "datex2-elaborated", "datex2-locations", "datex2-measured", @@ -169,6 +171,7 @@ const situationKinds = withSituationCrosswalks( { target: "wzdx", table: WZDX_SITUATIONS }, { target: "open511", table: OPEN511_SITUATIONS }, { target: "ibi511", table: IBI511_SITUATIONS }, + { target: "cifs", table: CIFS_SITUATIONS }, ], [ { target: "traff", table: TRAFF_EVENTS }, @@ -237,6 +240,10 @@ export const roadsModule: RegistryModule = { }), extendVocabulary({ vocabulary: "source_format", values: ROADS_SOURCE_FORMATS }), extendVocabulary({ vocabulary: "source_format", values: CAMERA_SOURCE_FORMATS }), + extendVocabulary({ + vocabulary: "external_id_scheme", + values: ["cifs:incident", "cifs:parent_event"], + }), ...situationKinds, cameraStatusVocabulary, vmsWorkingStatusVocabulary, diff --git a/packages/model-roads/src/vocabularies/cifs.ts b/packages/model-roads/src/vocabularies/cifs.ts new file mode 100644 index 000000000..3c3a59beb --- /dev/null +++ b/packages/model-roads/src/vocabularies/cifs.ts @@ -0,0 +1,147 @@ +/** + * Waze / Google Closure and Incident Feed Specification (CIFS) v2 vocabulary, + * from `https://www.gstatic.com/road-incidents/cifsv2.xsd` and + * `https://developers.google.com/waze/data-feed/cifs-specification`. + * + * The XSD enumerations are held directly against the pinned schema in + * `@openconditions/roads`'s `cifs-conformance.test.ts`. Two subtypes published + * in the web documentation (`HAZARD_ON_ROAD_EMERGENCY_VEHICLE` and + * `POLICE_WITH_MOBILE_CAMERA`) are absent from `cifsv2.xsd`: inbound parsing + * accepts them, while outbound emission writes only XSD-valid subtypes. + */ + +export const CIFS_TYPES = [ + "ACCIDENT", + "CONSTRUCTION", + "HAZARD", + "ROAD_CLOSED", + "POLICE", + "CHIT_CHAT", + "JAM", +] as const; + +export type CifsType = (typeof CIFS_TYPES)[number]; + +/** The 36 non-empty subtypes enumerated by `cifsv2.xsd`. */ +export const CIFS_XSD_SUBTYPES = [ + "ACCIDENT_MAJOR", + "ACCIDENT_MINOR", + "HAZARD_ON_ROAD", + "HAZARD_ON_ROAD_CAR_STOPPED", + "HAZARD_ON_ROAD_CONSTRUCTION", + "HAZARD_ON_ROAD_ICE", + "HAZARD_ON_ROAD_LANE_CLOSED", + "HAZARD_ON_ROAD_OBJECT", + "HAZARD_ON_ROAD_OIL", + "HAZARD_ON_ROAD_POT_HOLE", + "HAZARD_ON_ROAD_ROAD_KILL", + "HAZARD_ON_ROAD_TRAFFIC_LIGHT_FAULT", + "HAZARD_ON_SHOULDER", + "HAZARD_ON_SHOULDER_ANIMALS", + "HAZARD_ON_SHOULDER_CAR_STOPPED", + "HAZARD_ON_SHOULDER_MISSING_SIGN", + "HAZARD_WEATHER", + "HAZARD_WEATHER_FLOOD", + "HAZARD_WEATHER_FOG", + "HAZARD_WEATHER_FREEZING_RAIN", + "HAZARD_WEATHER_HAIL", + "HAZARD_WEATHER_HEAT_WAVE", + "HAZARD_WEATHER_HEAVY_RAIN", + "HAZARD_WEATHER_HEAVY_SNOW", + "HAZARD_WEATHER_HURRICANE", + "HAZARD_WEATHER_MONSOON", + "HAZARD_WEATHER_TORNADO", + "JAM_HEAVY_TRAFFIC", + "JAM_LIGHT_TRAFFIC", + "JAM_MODERATE_TRAFFIC", + "JAM_STAND_STILL_TRAFFIC", + "ROAD_CLOSED_CONSTRUCTION", + "ROAD_CLOSED_EVENT", + "ROAD_CLOSED_HAZARD", + "POLICE_VISIBLE", + "POLICE_HIDING", +] as const; + +export type CifsXsdSubtype = (typeof CIFS_XSD_SUBTYPES)[number]; + +/** Subtypes documented on Google Developers but omitted from `cifsv2.xsd`. */ +export const CIFS_DOC_ONLY_SUBTYPES = [ + "HAZARD_ON_ROAD_EMERGENCY_VEHICLE", + "POLICE_WITH_MOBILE_CAMERA", +] as const; + +export type CifsDocOnlySubtype = (typeof CIFS_DOC_ONLY_SUBTYPES)[number]; + +/** Every non-empty CIFS subtype accepted on inbound parsing (38 values). */ +export const CIFS_SUBTYPES = [...CIFS_XSD_SUBTYPES, ...CIFS_DOC_ONLY_SUBTYPES] as const; +export type CifsSubtype = (typeof CIFS_SUBTYPES)[number]; + +export const CIFS_DIRECTIONS = ["ONE_DIRECTION", "BOTH_DIRECTIONS"] as const; +export type CifsDirection = (typeof CIFS_DIRECTIONS)[number]; + +export const CIFS_ROADSIDES = ["LEFT", "MIDDLE", "RIGHT"] as const; +export type CifsRoadside = (typeof CIFS_ROADSIDES)[number]; + +export const CIFS_LANE_STATUSES = [ + "OPEN_LANE", + "OPEN", + "OPENED", + "CLOSED_LANE", + "CLOSE", + "CLOSED", +] as const; +export type CifsLaneStatus = (typeof CIFS_LANE_STATUSES)[number]; + +/** Legal `(type, subtype)` pairings per Waze's CIFS specification. */ +export const CIFS_SUBTYPES_BY_TYPE: Readonly> = { + ACCIDENT: ["ACCIDENT_MAJOR", "ACCIDENT_MINOR"], + CONSTRUCTION: [], + HAZARD: [ + "HAZARD_ON_ROAD", + "HAZARD_ON_ROAD_CAR_STOPPED", + "HAZARD_ON_ROAD_CONSTRUCTION", + "HAZARD_ON_ROAD_EMERGENCY_VEHICLE", + "HAZARD_ON_ROAD_ICE", + "HAZARD_ON_ROAD_LANE_CLOSED", + "HAZARD_ON_ROAD_OBJECT", + "HAZARD_ON_ROAD_OIL", + "HAZARD_ON_ROAD_POT_HOLE", + "HAZARD_ON_ROAD_ROAD_KILL", + "HAZARD_ON_ROAD_TRAFFIC_LIGHT_FAULT", + "HAZARD_ON_SHOULDER", + "HAZARD_ON_SHOULDER_ANIMALS", + "HAZARD_ON_SHOULDER_CAR_STOPPED", + "HAZARD_ON_SHOULDER_MISSING_SIGN", + "HAZARD_WEATHER", + "HAZARD_WEATHER_FLOOD", + "HAZARD_WEATHER_FOG", + "HAZARD_WEATHER_FREEZING_RAIN", + "HAZARD_WEATHER_HAIL", + "HAZARD_WEATHER_HEAT_WAVE", + "HAZARD_WEATHER_HEAVY_RAIN", + "HAZARD_WEATHER_HEAVY_SNOW", + "HAZARD_WEATHER_HURRICANE", + "HAZARD_WEATHER_MONSOON", + "HAZARD_WEATHER_TORNADO", + ], + ROAD_CLOSED: ["ROAD_CLOSED_CONSTRUCTION", "ROAD_CLOSED_EVENT", "ROAD_CLOSED_HAZARD"], + POLICE: ["POLICE_VISIBLE", "POLICE_HIDING", "POLICE_WITH_MOBILE_CAMERA"], + CHIT_CHAT: [], + JAM: [ + "JAM_LIGHT_TRAFFIC", + "JAM_MODERATE_TRAFFIC", + "JAM_HEAVY_TRAFFIC", + "JAM_STAND_STILL_TRAFFIC", + ], +}; + +export const CIFS = { + types: CIFS_TYPES, + xsdSubtypes: CIFS_XSD_SUBTYPES, + docOnlySubtypes: CIFS_DOC_ONLY_SUBTYPES, + subtypes: CIFS_SUBTYPES, + directions: CIFS_DIRECTIONS, + roadsides: CIFS_ROADSIDES, + laneStatuses: CIFS_LANE_STATUSES, + subtypesByType: CIFS_SUBTYPES_BY_TYPE, +} as const; diff --git a/packages/model/src/registry/define.ts b/packages/model/src/registry/define.ts index 8a413239d..f53f39e1e 100644 --- a/packages/model/src/registry/define.ts +++ b/packages/model/src/registry/define.ts @@ -17,6 +17,7 @@ export type MappingTarget = | "wzdx" | "open511" | "ibi511" + | "cifs" | "alert_c" | "traff" | "gtfs_rt" @@ -43,6 +44,7 @@ export const INGEST_MAPPING_TARGETS: readonly MappingTarget[] = [ "wzdx", "open511", "ibi511", + "cifs", "ocpi", "oicp", "parkapi", diff --git a/packages/publishers/src/__tests__/cifs-roundtrip.test.ts b/packages/publishers/src/__tests__/cifs-roundtrip.test.ts new file mode 100644 index 000000000..83a6be816 --- /dev/null +++ b/packages/publishers/src/__tests__/cifs-roundtrip.test.ts @@ -0,0 +1,160 @@ +import { readFileSync } from "node:fs"; +import { pinnedOrUnavailable, type SchemaFile, xsdErrors } from "@openconditions/conformance"; +import { CIFS_SCHEMA, CIFS_V2 } from "@openconditions/conformance/standards/cifs-v2"; +import { buildRegistry, kernelModule, sealRecord } from "@openconditions/model"; +import { roadsModule } from "@openconditions/model-roads"; +import { parseCifs, type SourceDescriptor, situationDrafts } from "@openconditions/roads"; +import { beforeAll, describe, expect, it } from "vitest"; +import { situationsToCifsJson, situationsToCifsXml } from "../situation-cifs.js"; + +const registry = buildRegistry([kernelModule, roadsModule]); + +const SRC: SourceDescriptor = { + id: "de-mobidata-bw-cifs", + attribution: "MobiData BW", + country: "DE", + license: "DL-DE-BY-2.0", +}; + +const AT = new Date("2026-09-01T10:00:00Z"); + +function toSealedSituations(raw: string): Record[] { + const events = parseCifs(raw, SRC); + return situationDrafts(events, { source: SRC, fetchedAt: AT.toISOString() }).map((draft) => { + const sealed = sealRecord(registry, draft, { + instanceId: "test.local", + revision: 1, + recordedAt: AT.toISOString(), + }); + expect(sealed.ok, sealed.ok ? "" : JSON.stringify(sealed.issues)).toBe(true); + return sealed.ok ? (sealed.value as Record) : draft; + }); +} + +describe("CIFS round-trip", () => { + let schemas: SchemaFile[] = []; + let unavailable: string | undefined; + + beforeAll(async () => { + const pinned = await pinnedOrUnavailable(CIFS_V2); + if ("files" in pinned) schemas = pinned.files; + else unavailable = pinned.unavailable; + }, 60_000); + + it("round-trips MobiData BW fixture through XML and JSON while preserving semantics", async () => { + const raw = readFileSync( + new URL("../../../roads/src/__tests__/fixtures/cifs/mobidata-bw.json", import.meta.url), + "utf8", + ); + const pass1 = toSealedSituations(raw); + expect(pass1).toHaveLength(2); + + const xml = situationsToCifsXml(pass1, AT, { timestamp: AT.toISOString() }); + const json = situationsToCifsJson(pass1, AT, { timestamp: AT.toISOString() }); + + if (!unavailable) { + expect(await xsdErrors(xml, schemas, CIFS_SCHEMA, "mobidata-roundtrip.xml")).toEqual([]); + } + + const fromXml = toSealedSituations(xml); + const fromJson = toSealedSituations(JSON.stringify(json)); + + expect(fromXml).toHaveLength(2); + expect(fromJson).toHaveLength(2); + + for (const pass2 of [fromXml, fromJson]) { + // Record 0: CONSTRUCTION → HAZARD_ON_ROAD_CONSTRUCTION (still roadworks, no closure effect) + expect(pass2[0]!["kind"]).toBe("roadworks"); + expect(pass2[0]!["effects"]).toEqual([]); + expect((pass2[0]!["location"] as Record)["direction"]).toEqual({ + value: "positive", + basis: "geometry", + }); + + // Record 1: ROAD_CLOSED_CONSTRUCTION → ROAD_CLOSED_CONSTRUCTION (roadworks + complete road closure) + expect(pass2[1]!["kind"]).toBe("roadworks"); + expect(pass2[1]!["subtype"]).toBe("construction"); + expect(pass2[1]!["effects"]).toEqual([ + expect.objectContaining({ kind: "closure", scope: "road", normalization: "complete" }), + ]); + expect((pass2[1]!["location"] as Record)["direction"]).toEqual({ + value: "both", + basis: "text", + text: "BOTH_DIRECTIONS", + }); + } + }); + + it("round-trips lanes, schedules, and bilateral single-point alerts losslessly", async () => { + const inputXml = ` + + + + 2026-09-01T09:30:00Z + + ops-1 + Regional Traffic + + HAZARD + HAZARD_ON_ROAD_LANE_CLOSED + Left lane closed + B10 Stuttgart + 48.780000 9.180000 48.790000 9.190000 + ONE_DIRECTION + + 1LANECLOSED + 2LANEOPEN + + 2026-09-01T08:00:00Z + 2026-09-30T18:00:00Z + + 08:00-12:00 + 08:00-12:00 + + + + ACCIDENT + ACCIDENT_MAJOR + Major crash + A8 Karlsruhe + 48.990000 8.400000 + BOTH_DIRECTIONS + +`; + + const pass1 = toSealedSituations(inputXml); + const outXml = situationsToCifsXml(pass1, AT, { timestamp: AT.toISOString() }); + if (!unavailable) { + expect(await xsdErrors(outXml, schemas, CIFS_SCHEMA, "rt-rich.xml")).toEqual([]); + } + const pass2 = toSealedSituations(outXml); + expect(pass2).toHaveLength(2); + expect(pass2[0]!["externalIds"]).toContainEqual({ + scheme: "cifs:parent_event", + id: "event-2026", + }); + expect((pass2[0]!["effects"] as unknown[])[0]).toMatchObject({ + kind: "lane_restriction", + lanes: [ + { index: 1, status: "closed" }, + { index: 2, status: "open" }, + ], + }); + expect((pass2[0]!["validity"] as { periods?: unknown[] }).periods).toEqual([ + expect.objectContaining({ + byDay: ["MO", "FR"], + startTime: "08:00", + endTime: "12:00", + duration: "PT4H", + scheduleTimezone: "Europe/Berlin", + }), + ]); + expect(pass2[1]!["kind"]).toBe("incident"); + expect(pass2[1]!["type"]).toBe("accident"); + expect((pass2[1]!["severity"] as Record)["label"]).toBe("major"); + expect((pass2[1]!["location"] as Record)["geometry"]).toEqual({ + type: "Point", + coordinates: [8.4, 48.99], + }); + }); +}); diff --git a/packages/publishers/src/__tests__/export-fuzz.test.ts b/packages/publishers/src/__tests__/export-fuzz.test.ts index 51c0474d7..7661385c8 100644 --- a/packages/publishers/src/__tests__/export-fuzz.test.ts +++ b/packages/publishers/src/__tests__/export-fuzz.test.ts @@ -9,6 +9,7 @@ import { xmlCharProblems, xsdErrors, } from "@openconditions/conformance"; +import { CIFS_SCHEMA, CIFS_V2 } from "@openconditions/conformance/standards/cifs-v2"; import { DATEX2_V3, MESSAGE_CONTAINER_SCHEMA, @@ -22,6 +23,7 @@ import type { ExportDiagnostic } from "../export-diagnostics.js"; import { featuresToGeoJSON, featuresToJsonLd } from "../feature-geojson.js"; import { type ArchivableRecord, publishedRecords, recordArchiveBuffer } from "../record-archive.js"; import { segmentConditionsToJson } from "../segment-conditions.js"; +import { situationsToCifsJson, situationsToCifsXml } from "../situation-cifs.js"; import { situationsToDatex } from "../situation-datex.js"; import { situationsToGeoJSON, situationsToJsonLd } from "../situation-geojson.js"; import { situationsToTraff } from "../situation-traff.js"; @@ -102,6 +104,37 @@ describe("situationsToDatex over random situations", () => { ); }); +describe("situationsToCifs over random situations", () => { + let schemas: SchemaFile[] = []; + let unavailable: string | undefined; + + beforeAll(async () => { + const pinned = await pinnedOrUnavailable(CIFS_V2); + if ("files" in pinned) schemas = pinned.files; + else unavailable = pinned.unavailable; + }, 120_000); + + it( + "writes well-formed XML the CIFS v2 XSD accepts and matching JSON with valid diagnostics", + async ({ skip }) => { + if (unavailable) skip(unavailable); + await fc.assert( + fc.asyncProperty(batch, async (situations) => { + const diagnostics: ExportDiagnostic[] = []; + const xml = situationsToCifsXml(situations, AT, INFO, (d) => diagnostics.push(d)); + const json = situationsToCifsJson(situations, AT, INFO); + expect(xmlProblems(xml)).toEqual([]); + expect(diagnosticProblems(diagnostics)).toEqual([]); + expect(Array.isArray(json.incidents)).toBe(true); + expect(await xsdErrors(xml, schemas, CIFS_SCHEMA, "fuzz-cifs.xml")).toEqual([]); + }), + fuzzParameters(25), + ); + }, + fuzzTimeout(20_000), + ); +}); + /** TraFF 0.8 coordinates: signed decimal degrees, latitude then longitude. */ const TRAFF_COORDINATES = /^[+-]\d+(?:\.\d+)? [+-]\d+(?:\.\d+)?$/; /** TraFF timestamps, to the second, in UTC. */ diff --git a/packages/publishers/src/__tests__/situation-cifs-schema.test.ts b/packages/publishers/src/__tests__/situation-cifs-schema.test.ts new file mode 100644 index 000000000..3338a26a7 --- /dev/null +++ b/packages/publishers/src/__tests__/situation-cifs-schema.test.ts @@ -0,0 +1,185 @@ +import { pinnedOrUnavailable, type SchemaFile, xsdErrors } from "@openconditions/conformance"; +import { CIFS_SCHEMA, CIFS_V2 } from "@openconditions/conformance/standards/cifs-v2"; +import { CIFS_INCIDENTS } from "@openconditions/model-roads"; +import { beforeAll, describe, expect, it } from "vitest"; +import { situationsToCifsXml } from "../situation-cifs.js"; + +type Rec = Record; + +const AT = new Date("2026-09-06T10:00:00Z"); +const INFO = { timestamp: "2026-09-06T10:00:00Z" }; + +const LINE = { + type: "LineString", + coordinates: [ + [9.18, 48.78], + [9.19, 48.79], + ], +}; + +const ROAD = { name: [{ lang: "de", text: "B10 Stuttgart" }] }; + +const effect = (id: string, kind: string, fields: Rec = {}): Rec => ({ + id, + kind, + v: 1, + applicability: { kind: "all" }, + compliance: "mandatory", + normalization: "complete", + ...fields, +}); + +function situation(id: string, over: Rec = {}): Rec { + return { + id: `oc:situation:test:${id}`, + class: "situation", + kind: "roadworks", + type: "works", + temporality: "live", + certainty: "observed", + severity: { label: "moderate", source: "derived" }, + description: [{ lang: "en", text: "Disruption on B10" }], + validity: { status: "active", start: "2026-09-06T08:00:00Z", end: "2026-09-07T08:00:00Z" }, + effects: [], + location: { + geometry: LINE, + roads: [ROAD], + direction: { value: "positive", basis: "geometry" }, + }, + provenance: { sourceUpdatedAt: "2026-09-06T09:00:00Z" }, + freshness: { fetchedAt: "2026-09-06T09:30:00Z" }, + ...over, + }; +} + +const everyMappedNature = Object.entries(CIFS_INCIDENTS) + .filter(([, code]) => code !== null) + .map(([key]) => { + const [kind, type, subtype] = key.split("."); + return situation(key, { kind, type, ...(subtype ? { subtype } : {}) }); + }); + +const variants: Rec[] = [ + situation("road-closed-construction", { + kind: "roadworks", + type: "works", + subtype: "construction", + effects: [effect("c1", "closure", { scope: "road" })], + }), + situation("road-closed-event", { + kind: "public_event", + type: "event", + effects: [effect("c1", "closure", { scope: "road" })], + }), + situation("road-closed-hazard", { + kind: "road_hazard", + type: "hazard", + effects: [effect("c1", "closure", { scope: "road" })], + }), + situation("road-closed-plain", { + kind: "closure", + type: "closure", + subtype: "full", + effects: [effect("c1", "closure", { scope: "road" })], + }), + situation("lanes-and-source-and-schedule", { + provenance: { + sourceUpdatedAt: "2026-09-06T09:00:00Z", + informationSource: { + id: "mobidata-bw", + name: [{ lang: "de", text: "MobiData BW" }], + }, + }, + validity: { + status: "active", + start: "2026-09-01T00:00:00+02:00", + end: "2026-09-30T23:59:00+02:00", + periods: [ + { + repeatFrequency: "P1W", + byDay: ["MO", "TH", "FR"], + startTime: "09:00", + duration: "PT2H", + scheduleTimezone: "Europe/Berlin", + }, + { + repeatFrequency: "P1W", + byDay: ["SU"], + startTime: "10:00", + duration: "PT4H", + scheduleTimezone: "Europe/Berlin", + }, + ], + }, + effects: [ + effect("l1", "lane_restriction", { + vehicleImpact: "some_lanes_closed", + lanes: [ + { index: 1, status: "closed" }, + { index: 2, status: "open" }, + ], + }), + ], + }), + situation("everyday-schedule", { + validity: { + status: "active", + start: "2026-09-01T00:00:00+02:00", + end: "2026-09-30T23:59:00+02:00", + periods: [ + { + repeatFrequency: "P1D", + startTime: "07:00", + duration: "PT3H", + scheduleTimezone: "Europe/Berlin", + }, + ], + }, + }), + situation("bilateral-point-accident", { + kind: "incident", + type: "accident", + severity: { label: "critical", source: "derived" }, + location: { + geometry: { type: "Point", coordinates: [9.18, 48.78] }, + roads: [ROAD], + direction: { value: "both", basis: "text", text: "BOTH_DIRECTIONS" }, + }, + }), + situation("control-chars-and-clamped-times", { + description: [{ lang: "en", text: "Bad\u0000control\u0007chars" }], + location: { + geometry: LINE, + roads: [{ name: [{ lang: "en", text: "A\u000010" }] }], + }, + validity: { + status: "active", + start: "0000-01-01T00:00:00Z", + end: "9999-12-31T23:59:59-05:00", + }, + }), +]; + +describe("CIFS v2 XML schema conformance", () => { + let schemas: SchemaFile[] = []; + let unavailable: string | undefined; + + beforeAll(async () => { + const pinned = await pinnedOrUnavailable(CIFS_V2); + if ("files" in pinned) schemas = pinned.files; + else unavailable = pinned.unavailable; + }, 60_000); + + it("validates every mapped classification and variant against cifsv2.xsd", async ({ skip }) => { + if (unavailable) skip(unavailable); + const xml = situationsToCifsXml([...everyMappedNature, ...variants], AT, INFO); + expect(xml).toContain(" { + if (unavailable) skip(unavailable); + const xml = situationsToCifsXml([], AT, INFO); + expect(await xsdErrors(xml, schemas, CIFS_SCHEMA, "cifs-empty.xml")).toEqual([]); + }); +}); diff --git a/packages/publishers/src/__tests__/situation-cifs.test.ts b/packages/publishers/src/__tests__/situation-cifs.test.ts new file mode 100644 index 000000000..efb25e5bf --- /dev/null +++ b/packages/publishers/src/__tests__/situation-cifs.test.ts @@ -0,0 +1,785 @@ +import { describe, expect, it } from "vitest"; +import type { ExportDiagnostic } from "../export-diagnostics.js"; +import { cifsIncidentsOf, situationsToCifsJson, situationsToCifsXml } from "../situation-cifs.js"; + +type Rec = Record; + +const AT = new Date("2026-09-06T10:00:00Z"); + +const LINE = { + type: "LineString", + coordinates: [ + [9.18, 48.78], + [9.19, 48.79], + ], +}; + +const ROAD = { name: [{ lang: "de", text: "B10" }] }; + +const effect = (id: string, kind: string, fields: Rec = {}): Rec => ({ + id, + kind, + v: 1, + applicability: { kind: "all" }, + compliance: "mandatory", + normalization: "complete", + ...fields, +}); + +function situation(id: string, over: Rec = {}): Rec { + return { + id: `oc:situation:test:${id}`, + class: "situation", + kind: "roadworks", + type: "works", + temporality: "live", + certainty: "observed", + severity: { label: "moderate", source: "derived" }, + description: [{ lang: "en", text: "Roadworks on B10" }], + validity: { status: "active", start: "2026-09-06T08:00:00Z", end: "2026-09-07T08:00:00Z" }, + effects: [], + location: { + geometry: LINE, + roads: [ROAD], + direction: { value: "positive", basis: "geometry" }, + }, + provenance: { sourceUpdatedAt: "2026-09-06T09:00:00Z" }, + freshness: { fetchedAt: "2026-09-06T09:30:00Z" }, + ...over, + }; +} + +describe("CIFS outbound emitter", () => { + it("emits ROAD_CLOSED only for complete road-scoped closures with explicit validity.start", () => { + const valid = situation("closure-ok", { + kind: "roadworks", + type: "works", + subtype: "construction", + effects: [effect("c1", "closure", { scope: "road" })], + }); + const [inc] = cifsIncidentsOf(valid, AT); + expect(inc).toMatchObject({ + id: "oc:situation:test:closure-ok", + type: "ROAD_CLOSED", + subtype: "ROAD_CLOSED_CONSTRUCTION", + direction: "ONE_DIRECTION", + starttime: "2026-09-06T08:00:00Z", + endtime: "2026-09-07T08:00:00Z", + }); + + // Missing validity.start withholds ROAD_CLOSED (never falls back to sourceUpdatedAt/fetchedAt) + const noStartDiags: ExportDiagnostic[] = []; + expect( + cifsIncidentsOf( + situation("closure-nostart", { + effects: [effect("c1", "closure", { scope: "road" })], + validity: { status: "active", end: "2026-09-07T08:00:00Z" }, + }), + AT, + (d) => noStartDiags.push(d), + ), + ).toEqual([]); + expect(noStartDiags).toContainEqual( + expect.objectContaining({ code: "unsupported_timing", path: "/validity/start" }), + ); + + // Sidewalk closure is not a ROAD_CLOSED + const sidewalkDiags: ExportDiagnostic[] = []; + const sidewalk = situation("sidewalk", { + kind: "closure", + type: "closure", + effects: [effect("c1", "closure", { scope: "sidewalk" })], + }); + expect(cifsIncidentsOf(sidewalk, AT, (d) => sidewalkDiags.push(d))).toEqual([]); + expect(sidewalkDiags).toContainEqual( + expect.objectContaining({ code: "unsupported_effect", path: "/effects/0/scope" }), + ); + + // all_lanes_closed lane_restriction does NOT synthesize ROAD_CLOSED + const allLanes = situation("all-lanes", { + kind: "closure", + type: "closure", + effects: [effect("l1", "lane_restriction", { vehicleImpact: "all_lanes_closed" })], + }); + const [laneInc] = cifsIncidentsOf(allLanes, AT); + expect(laneInc?.type).toBe("HAZARD"); + expect(laneInc?.subtype).toBe("HAZARD_ON_ROAD_LANE_CLOSED"); + }); + + it("handles geometry directionality: reverses negative geometry lines and enforces bilateral-only single points", () => { + const reversed = situation("neg-line", { + location: { + geometry: LINE, + roads: [ROAD], + direction: { value: "negative", basis: "geometry" }, + }, + }); + const [revInc] = cifsIncidentsOf(reversed, AT); + expect(revInc?.direction).toBe("ONE_DIRECTION"); + expect(revInc?.polyline).toBe("48.790000 9.190000 48.780000 9.180000"); + + // Compass direction withheld + const compassDiags: ExportDiagnostic[] = []; + expect( + cifsIncidentsOf( + situation("compass", { + location: { + geometry: LINE, + roads: [ROAD], + direction: { value: "unknown", basis: "compass", compass: "N" }, + }, + }), + AT, + (d) => compassDiags.push(d), + ), + ).toEqual([]); + expect(compassDiags).toContainEqual( + expect.objectContaining({ code: "unrepresentable_direction" }), + ); + + // Single-point alert with explicit bilateral direction succeeds + const bilateralPoint = situation("pt-both", { + kind: "incident", + type: "accident", + severity: { label: "major", source: "derived" }, + location: { + geometry: { type: "Point", coordinates: [9.18, 48.78] }, + roads: [ROAD], + direction: { value: "both", basis: "text", text: "BOTH_DIRECTIONS" }, + }, + }); + const [ptInc] = cifsIncidentsOf(bilateralPoint, AT); + expect(ptInc).toMatchObject({ + type: "ACCIDENT", + subtype: "ACCIDENT_MAJOR", + polyline: "48.780000 9.180000", + direction: "BOTH_DIRECTIONS", + }); + + // Single-point alert with absent or non-both direction is withheld + expect( + cifsIncidentsOf( + situation("pt-nodir", { + kind: "incident", + type: "accident", + location: { geometry: { type: "Point", coordinates: [9.18, 48.78] }, roads: [ROAD] }, + }), + AT, + ), + ).toEqual([]); + + // Single-point closure is ALWAYS withheld even with bilateral direction + expect( + cifsIncidentsOf( + situation("pt-closure", { + effects: [effect("c1", "closure", { scope: "road" })], + location: { + geometry: { type: "Point", coordinates: [9.18, 48.78] }, + roads: [ROAD], + direction: { value: "both", basis: "text", text: "BOTH_DIRECTIONS" }, + }, + }), + AT, + ), + ).toEqual([]); + }); + + it("rejects circular, zero-length/rounded-collapsed, and >20 km closure polylines", () => { + // Circular polyline (first === last with >= 3 points) + expect( + cifsIncidentsOf( + situation("circular", { + location: { + geometry: { + type: "LineString", + coordinates: [ + [9.18, 48.78], + [9.19, 48.79], + [9.18, 48.78], + ], + }, + roads: [ROAD], + }, + }), + AT, + ), + ).toEqual([]); + + // Two vertices that collapse after 6-decimal rounding + expect( + cifsIncidentsOf( + situation("collapsed", { + location: { + geometry: { + type: "LineString", + coordinates: [ + [9.1800001, 48.7800001], + [9.1800002, 48.7800002], + ], + }, + roads: [ROAD], + }, + }), + AT, + ), + ).toEqual([]); + + // >20 km closure withheld, while non-closure alert is allowed + const longLine = { + type: "LineString", + coordinates: [ + [9.0, 48.0], + [9.0, 48.3], // ~33 km + ], + }; + expect( + cifsIncidentsOf( + situation("long-closure", { + effects: [effect("c1", "closure", { scope: "road" })], + location: { geometry: longLine, roads: [ROAD] }, + }), + AT, + ), + ).toEqual([]); + expect( + cifsIncidentsOf( + situation("long-alert", { + location: { geometry: longLine, roads: [ROAD] }, + }), + AT, + ), + ).toHaveLength(1); + }); + + it("exports schedules honoring authoritative duration and rejecting unsupported rules/timezones/suspended status", () => { + // Valid weekday schedule in matching geometry timezone (Europe/Berlin) + const scheduled = situation("sched-ok", { + validity: { + status: "active", + start: "2026-09-01T00:00:00+02:00", + end: "2026-09-30T23:59:00+02:00", + periods: [ + { + repeatFrequency: "P1W", + byDay: ["MO", "WE"], + startTime: "08:00", + duration: "PT4H", + scheduleTimezone: "Europe/Berlin", + }, + ], + }, + }); + const [inc] = cifsIncidentsOf(scheduled, AT); + expect(inc?.schedule).toEqual({ monday: "08:00-12:00", wednesday: "08:00-12:00" }); + + // Suspended status withheld + const suspDiags: ExportDiagnostic[] = []; + expect( + cifsIncidentsOf( + situation("suspended", { + validity: { status: "suspended", start: "2026-09-06T08:00:00Z" }, + }), + AT, + (d) => suspDiags.push(d), + ), + ).toEqual([]); + expect(suspDiags).toContainEqual( + expect.objectContaining({ code: "unsupported_timing", path: "/validity/status" }), + ); + + // Wrong timezone rejected + expect( + cifsIncidentsOf( + situation("wrong-tz", { + validity: { + status: "active", + start: "2026-09-01T00:00:00Z", + periods: [ + { + repeatFrequency: "P1D", + startTime: "08:00", + duration: "PT2H", + scheduleTimezone: "America/New_York", + }, + ], + }, + }), + AT, + ), + ).toEqual([]); + + // Duration vs endTime disagreement rejected + expect( + cifsIncidentsOf( + situation("dur-mismatch", { + validity: { + status: "active", + start: "2026-09-01T00:00:00+02:00", + periods: [ + { + repeatFrequency: "P1D", + startTime: "08:00", + endTime: "11:00", + duration: "PT2H", + scheduleTimezone: "Europe/Berlin", + }, + ], + }, + }), + AT, + ), + ).toEqual([]); + + // Overnight schedule rejected + expect( + cifsIncidentsOf( + situation("overnight", { + validity: { + status: "active", + start: "2026-09-01T00:00:00+02:00", + periods: [ + { + repeatFrequency: "P1D", + startTime: "22:00", + duration: "PT7H", + scheduleTimezone: "Europe/Berlin", + }, + ], + }, + }), + AT, + ), + ).toEqual([]); + }); + + it("exports complete contiguous lanes on ONE_DIRECTION non-closures and splits/withholds conflicting effects", () => { + const withLanes = situation("lanes-ok", { + effects: [ + effect("l1", "lane_restriction", { + vehicleImpact: "some_lanes_closed", + lanesTotal: 2, + lanesClosed: 1, + lanes: [ + { index: 1, status: "closed" }, + { index: 2, status: "open" }, + ], + }), + ], + }); + const [inc] = cifsIncidentsOf(withLanes, AT); + expect(inc?.lanes).toEqual([ + { order: 1, type: "LANE", status: "CLOSED" }, + { order: 2, type: "LANE", status: "OPEN" }, + ]); + + // Conflicting lane restrictions in overlapping windows are withheld + const conflictDiags: ExportDiagnostic[] = []; + const conflicting = situation("lanes-conflict", { + effects: [ + effect("l1", "lane_restriction", { + vehicleImpact: "some_lanes_closed", + lanes: [ + { index: 1, status: "closed" }, + { index: 2, status: "open" }, + ], + validity: { + status: "active", + start: "2026-09-06T08:00:00Z", + end: "2026-09-06T12:00:00Z", + }, + }), + effect("l2", "lane_restriction", { + vehicleImpact: "some_lanes_closed", + lanes: [ + { index: 1, status: "open" }, + { index: 2, status: "closed" }, + ], + validity: { + status: "active", + start: "2026-09-06T09:00:00Z", + end: "2026-09-06T13:00:00Z", + }, + }), + ], + }); + const conflictOut = cifsIncidentsOf(conflicting, AT, (d) => conflictDiags.push(d)); + // Split lane effects overlap and conflict, so neither split lane message is emitted + expect(conflictOut.filter((i) => i.lanes !== undefined)).toEqual([]); + expect(conflictDiags).toContainEqual(expect.objectContaining({ code: "conflicting_effects" })); + + // XML and JSON share identical incident projection + const json = situationsToCifsJson([withLanes], AT, { timestamp: "2026-09-06T10:00:00Z" }); + const xml = situationsToCifsXml([withLanes], AT, { timestamp: "2026-09-06T10:00:00Z" }); + expect(json.incidents).toHaveLength(1); + expect(xml).toContain('timestamp="2026-09-06T10:00:00Z"'); + expect(xml).toContain("HAZARD"); + expect(xml).toContain("1"); + }); + + it("refuses ROAD_CLOSED for rejected future actions, lane-scoped closures, and advisory closures", () => { + const rejectedFuture = situation("rejected-future", { + kind: "closure", + type: "closure", + validity: { status: "active", start: "2026-09-07T08:00:00Z", end: "2026-09-08T08:00:00Z" }, + effects: [effect("c1", "closure", { scope: "road", actionStatus: "rejected" })], + }); + expect(cifsIncidentsOf(rejectedFuture, AT)).toEqual([]); + + const laneScoped = situation("lane-scoped-closure", { + kind: "closure", + type: "closure", + effects: [ + effect("c1", "closure", { + scope: "road", + laneScope: [{ index: 1 }], + }), + ], + }); + expect(cifsIncidentsOf(laneScoped, AT)).toEqual([]); + + const advisory = situation("advisory-closure", { + kind: "closure", + type: "closure", + effects: [effect("c1", "closure", { scope: "road", compliance: "advisory" })], + }); + expect(cifsIncidentsOf(advisory, AT)).toEqual([]); + }); + + it("reconciles outbound lane counts, checks all_lanes_open conflicts, and allows non-overlapping day schedules", () => { + // Partial lane list (2 items) on an effect declaring 4 lanesTotal / 2 lanesClosed omits + const partialLanesDiags: ExportDiagnostic[] = []; + const partialLanes = situation("partial-lanes", { + effects: [ + effect("l1", "lane_restriction", { + vehicleImpact: "some_lanes_closed", + lanesTotal: 4, + lanesClosed: 2, + lanes: [ + { index: 1, status: "closed" }, + { index: 2, status: "open" }, + ], + }), + ], + }); + const [partialInc] = cifsIncidentsOf(partialLanes, AT, (d) => partialLanesDiags.push(d)); + expect(partialInc?.lanes).toBeUndefined(); + expect(partialLanesDiags).toContainEqual( + expect.objectContaining({ code: "field_not_exported" }), + ); + + // Overlapping all_lanes_open conflicts with closed-lane bucket at same place & direction + const openVsClosedDiags: ExportDiagnostic[] = []; + const openVsClosed = situation("open-vs-closed", { + kind: "closure", + type: "closure", + subtype: "lane", + effects: [ + effect("l1", "lane_restriction", { + vehicleImpact: "some_lanes_closed", + lanes: [ + { index: 1, status: "closed" }, + { index: 2, status: "open" }, + ], + validity: { + status: "active", + start: "2026-09-06T08:00:00Z", + end: "2026-09-06T12:00:00Z", + }, + }), + effect("l2", "lane_restriction", { + vehicleImpact: "all_lanes_open", + validity: { + status: "active", + start: "2026-09-06T09:00:00Z", + end: "2026-09-06T13:00:00Z", + }, + }), + ], + }); + expect(cifsIncidentsOf(openVsClosed, AT, (d) => openVsClosedDiags.push(d))).toEqual([]); + expect(openVsClosedDiags).toContainEqual( + expect.objectContaining({ code: "conflicting_effects" }), + ); + + // Disjoint Monday vs Tuesday lane layouts with overlapping outer dates are compatible + const monVsTue = situation("mon-vs-tue", { + kind: "closure", + type: "closure", + subtype: "lane", + validity: { + status: "active", + start: "2026-09-01T00:00:00+02:00", + end: "2026-09-30T23:59:00+02:00", + }, + effects: [ + effect("l-mon", "lane_restriction", { + vehicleImpact: "some_lanes_closed", + lanes: [ + { index: 1, status: "closed" }, + { index: 2, status: "open" }, + ], + validity: { + status: "active", + start: "2026-09-01T00:00:00+02:00", + end: "2026-09-30T23:59:00+02:00", + periods: [ + { + repeatFrequency: "P1W", + byDay: ["MO"], + startTime: "08:00", + duration: "PT4H", + scheduleTimezone: "Europe/Berlin", + }, + ], + }, + }), + effect("l-tue", "lane_restriction", { + vehicleImpact: "some_lanes_closed", + lanes: [ + { index: 1, status: "open" }, + { index: 2, status: "closed" }, + ], + validity: { + status: "active", + start: "2026-09-01T00:00:00+02:00", + end: "2026-09-30T23:59:00+02:00", + periods: [ + { + repeatFrequency: "P1W", + byDay: ["TU"], + startTime: "08:00", + duration: "PT4H", + scheduleTimezone: "Europe/Berlin", + }, + ], + }, + }), + ], + }); + const monTueOut = cifsIncidentsOf(monVsTue, AT); + expect(monTueOut).toHaveLength(2); + expect(monTueOut.map((i) => i.schedule)).toEqual([ + { monday: "08:00-12:00" }, + { tuesday: "08:00-12:00" }, + ]); + }); + + it("withholds DST-crossing schedules, enforces code-point lengths, disambiguates split IDs, emits parent_event, and avoids over-specific codes", () => { + // Spring & autumn DST-crossing schedules withheld + for (const [id, start, end] of [ + ["spring-dst", "2026-03-28T00:00:00+01:00", "2026-03-30T23:59:00+02:00"], + ["autumn-dst", "2026-10-24T00:00:00+02:00", "2026-10-26T23:59:00+01:00"], + ] as const) { + const dstSit = situation(id, { + validity: { + status: "active", + start, + end, + periods: [ + { + repeatFrequency: "P1W", + byDay: ["SU"], + startTime: "01:00", + duration: "PT3H", + scheduleTimezone: "Europe/Berlin", + }, + ], + }, + }); + expect(cifsIncidentsOf(dstSit, new Date(start))).toEqual([]); + } + + // Single supplementary Unicode character street has length 2 in UTF-16 but 1 code point → withheld + const emojiStreet = situation("emoji-street", { + location: { + geometry: LINE, + roads: [{ name: [{ lang: "und", text: "🚧" }] }], + direction: { value: "positive", basis: "geometry" }, + }, + }); + expect(cifsIncidentsOf(emojiStreet, AT)).toEqual([]); + + // Split ID colliding with another situation's root ID is disambiguated across the feed + const sitA = situation("A", { + effects: [ + effect("part", "lane_restriction", { + vehicleImpact: "some_lanes_closed", + validity: { + status: "active", + start: "2026-09-06T09:00:00Z", + end: "2026-09-06T12:00:00Z", + }, + }), + ], + }); + const sitAPart = situation("A#part"); + const feed = situationsToCifsJson([sitA, sitAPart], AT); + expect(feed.incidents.length).toBeGreaterThanOrEqual(3); + expect(new Set(feed.incidents.map((i) => i.id)).size).toBe(feed.incidents.length); + + // Preserved cifs:parent_event is emitted in JSON and XML + const withParent = situation("with-parent", { + externalIds: [{ scheme: "cifs:parent_event", id: "marathon-2026" }], + }); + const [parentJson] = situationsToCifsJson([withParent], AT).incidents; + expect(parentJson?.parent_event).toEqual({ id: "marathon-2026" }); + expect(situationsToCifsXml([withParent], AT)).toContain(''); + + // Non-over-specific crosswalk codes + const [storm] = cifsIncidentsOf( + situation("storm", { kind: "weather_condition", type: "weather", subtype: "storm" }), + AT, + ); + expect(storm).toMatchObject({ type: "HAZARD", subtype: "HAZARD_WEATHER" }); + const [obstruction] = cifsIncidentsOf( + situation("obstruction", { kind: "incident", type: "obstruction" }), + AT, + ); + expect(obstruction).toMatchObject({ type: "HAZARD", subtype: "HAZARD_ON_ROAD" }); + const [obj] = cifsIncidentsOf( + situation("object", { kind: "incident", type: "obstruction", subtype: "object" }), + AT, + ); + expect(obj).toMatchObject({ type: "HAZARD", subtype: "HAZARD_ON_ROAD_OBJECT" }); + }); + + it("enforces strict lane consistency, intersects bounded weekly occurrences, and keeps IDs XML-safe and poll-stable", () => { + // all_lanes_closed with mixed open/closed lanes emits neither HAZARD_ON_ROAD_LANE_CLOSED nor + const mixedAllClosed = situation("mixed-all-closed", { + kind: "closure", + type: "closure", + subtype: "lane", + effects: [ + effect("l1", "lane_restriction", { + vehicleImpact: "all_lanes_closed", + lanes: [ + { index: 1, status: "closed" }, + { index: 2, status: "open" }, + ], + }), + ], + }); + expect(cifsIncidentsOf(mixedAllClosed, AT)).toEqual([]); + + // all_lanes_open_shift_left does not emit HAZARD_ON_ROAD_LANE_CLOSED + const shiftLeft = situation("shift-left", { + kind: "closure", + type: "closure", + subtype: "lane", + effects: [effect("l1", "lane_restriction", { vehicleImpact: "all_lanes_open_shift_left" })], + }); + expect(cifsIncidentsOf(shiftLeft, AT)).toEqual([]); + + // lanesRestricted: 0 with a closed lane does not emit HAZARD_ON_ROAD_LANE_CLOSED or + const zeroRestricted = situation("zero-restricted", { + kind: "closure", + type: "closure", + subtype: "lane", + effects: [ + effect("l1", "lane_restriction", { + vehicleImpact: "some_lanes_closed", + lanesRestricted: 0, + lanes: [ + { index: 1, status: "closed" }, + { index: 2, status: "open" }, + ], + }), + ], + }); + expect(cifsIncidentsOf(zeroRestricted, AT)).toEqual([]); + + // Two Monday-only schedules in Europe/Berlin whose outer bounds overlap only on Wed-Thu + // have zero overlapping occurrences and must both be emitted + const disjointMondays = situation("disjoint-mondays", { + kind: "closure", + type: "closure", + subtype: "lane", + validity: { + status: "active", + start: "2026-09-07T00:00:00+02:00", + end: "2026-09-14T23:59:00+02:00", + }, + effects: [ + effect("mon-1", "lane_restriction", { + vehicleImpact: "some_lanes_closed", + lanes: [ + { index: 1, status: "closed" }, + { index: 2, status: "open" }, + ], + validity: { + status: "active", + start: "2026-09-07T00:00:00+02:00", + end: "2026-09-10T23:59:00+02:00", + periods: [ + { + repeatFrequency: "P1W", + byDay: ["MO"], + startTime: "08:00", + duration: "PT4H", + scheduleTimezone: "Europe/Berlin", + }, + ], + }, + }), + effect("mon-2", "lane_restriction", { + vehicleImpact: "some_lanes_closed", + lanes: [ + { index: 1, status: "open" }, + { index: 2, status: "closed" }, + ], + validity: { + status: "active", + start: "2026-09-09T00:00:00+02:00", + end: "2026-09-14T23:59:00+02:00", + periods: [ + { + repeatFrequency: "P1W", + byDay: ["MO"], + startTime: "08:00", + duration: "PT4H", + scheduleTimezone: "Europe/Berlin", + }, + ], + }, + }), + ], + }); + const disjointOut = cifsIncidentsOf(disjointMondays, new Date("2026-09-07T09:00:00+02:00")); + expect(disjointOut).toHaveLength(2); + + // Tab vs space in situation IDs remain distinct after XML attribute normalization + const tabSit = situation("abc\tdef"); + const spaceSit = situation("abc def"); + const wsFeed = situationsToCifsJson([tabSit, spaceSit], AT); + const wsXml = situationsToCifsXml([tabSit, spaceSit], AT); + expect(wsFeed.incidents.map((i) => i.id)).toEqual([ + "oc:situation:test:abc%09def", + "oc:situation:test:abc def", + ]); + expect(wsXml).toContain('id="oc:situation:test:abc%09def"'); + expect(wsXml).toContain('id="oc:situation:test:abc def"'); + + // Split ID of "sitA" is stable whether or not another situation with raw id "sitA#part" is present + const sitA = situation("sitA", { + effects: [ + effect("part", "lane_restriction", { + vehicleImpact: "some_lanes_closed", + validity: { + status: "active", + start: "2026-09-06T09:00:00Z", + end: "2026-09-06T12:00:00Z", + }, + }), + ], + }); + const sitAPart = situation("sitA#part"); + const soloIds = situationsToCifsJson([sitA], AT).incidents.map((i) => i.id); + const pairIds = situationsToCifsJson([sitA, sitAPart], AT).incidents.map((i) => i.id); + expect(soloIds).toEqual(["oc:situation:test:sitA", "oc:situation:test:sitA#part"]); + expect(pairIds).toEqual([ + "oc:situation:test:sitA", + "oc:situation:test:sitA#part", + "oc:situation:test:sitA%23part", + ]); + }); +}); diff --git a/packages/publishers/src/export-diagnostics.ts b/packages/publishers/src/export-diagnostics.ts index e2770c25d..f2b2cc27c 100644 --- a/packages/publishers/src/export-diagnostics.ts +++ b/packages/publishers/src/export-diagnostics.ts @@ -95,7 +95,7 @@ export class ProjectionDiagnostics { * and one that can state which vehicles an effect applies to, which * (`states.vehicles`). */ blocked( - format: "traff" | "datex", + format: "traff" | "datex" | "cifs", states: { timing?: (validity: Validity, effect?: Effect) => boolean; place?: (location: Rec) => boolean; @@ -112,7 +112,7 @@ export class ProjectionDiagnostics { } if ( (path === "/validity" && ["unknown", "ended", "cancelled"].includes(validity.status)) || - (format === "traff" && validity.status === "suspended") + ((format === "traff" || format === "cifs") && validity.status === "suspended") ) fields.push("status"); for (const field of fields) { diff --git a/packages/publishers/src/index.ts b/packages/publishers/src/index.ts index 60903592a..f8752c1f2 100644 --- a/packages/publishers/src/index.ts +++ b/packages/publishers/src/index.ts @@ -3,6 +3,7 @@ export * from "./feature-geojson.js"; export * from "./record-archive.js"; export * from "./segment-conditions.js"; export * from "./segments.js"; +export * from "./situation-cifs.js"; export * from "./situation-datex.js"; export * from "./situation-geojson.js"; export * from "./situation-traff.js"; diff --git a/packages/publishers/src/situation-cifs.ts b/packages/publishers/src/situation-cifs.ts new file mode 100644 index 000000000..fc4a64ced --- /dev/null +++ b/packages/publishers/src/situation-cifs.ts @@ -0,0 +1,1480 @@ +import { createHash } from "node:crypto"; +import { haversineMeters, scheduleTimezoneForGeometry } from "@openconditions/core"; +import { + type DirectionRef, + type Effect, + effectValidity, + type Geometry, + localDateInZone, + type Schedule, + type Validity, + zonedWallClockToInstant, +} from "@openconditions/model"; +import { + type CifsIncidentCode, + type CifsType, + type CifsXsdSubtype, + cifsIncidentCodeOf, +} from "@openconditions/model-roads"; +import { scheduleWindowCrossesDst } from "@openconditions/roads"; +import { type ExportDiagnosticSink, ProjectionDiagnostics } from "./export-diagnostics.js"; +import { + definesManagementNature, + omittedPath, + type ProjectionEffect, + projectionEffects, + projectionStateAt, +} from "./export-validity.js"; +import { buildXmlDocument, xmlChars } from "./xml.js"; + +type Rec = Record; + +/** + * CIFS (Closure and Incident Feed Specification v2) outbound emitter for both + * XML (``) and JSON (`{ timestamp, incidents }`). + * + * Emits only XSD-valid `cifsv2.xsd` values: never writes deprecated + * `CONSTRUCTION`, `CHIT_CHAT`, or doc-only subtypes. Full `ROAD_CLOSED` + * incidents require a complete, active or confirmed-scheduled, mandatory, + * road-wide (non-lane-scoped) `closure` effect, an explicit `validity.start` + * timestamp, and a non-circular `LineString` of length > 0 m and ≤ 20,000 m on + * the serialized 6-decimal coordinates. Single-point alerts are exported only + * for non-closure incidents with explicit bilateral direction + * (`direction.value === "both"`). + */ + +export interface CifsLane { + order: number; + type: "LANE"; + status: "OPEN" | "CLOSED"; +} + +export interface CifsSchedule { + everyday?: string; + monday?: string; + tuesday?: string; + wednesday?: string; + thursday?: string; + friday?: string; + saturday?: string; + sunday?: string; +} + +export interface CifsSource { + reference: string; + name?: string; + url?: string; +} + +export interface CifsParentEvent { + id: string; +} + +export interface CifsIncident { + id: string; + parent_event?: CifsParentEvent; + creationtime?: string; + updatetime?: string; + source?: CifsSource; + type: Exclude; + subtype?: CifsXsdSubtype; + description: string; + street: string; + polyline: string; + direction: "ONE_DIRECTION" | "BOTH_DIRECTIONS"; + lanes?: CifsLane[]; + starttime?: string; + endtime?: string; + schedule?: CifsSchedule; +} + +export interface CifsFeed { + timestamp?: string; + incidents: CifsIncident[]; +} + +/** + * `xs:dateTime` in XML Schema 1.0 (as enforced by `xmllint-wasm`) rejects year + * `0000`, so timestamps clamp to `[0001-01-01T00:00:00Z, 9999-12-31T23:59:59Z]`. + */ +const FIRST_WIRE_TIME = Date.parse("0001-01-01T00:00:00Z"); +const LAST_WIRE_TIME = Date.parse("9999-12-31T23:59:59Z"); + +/** Maximum road closure polyline length Waze accepts (20 km). */ +const MAX_CLOSURE_METERS = 20_000; + +/** Closure scopes representing motor-vehicle road closures representable as CIFS ROAD_CLOSED. */ +const ROAD_CLOSURE_SCOPES = new Set(["road", "carriageway", "ramp", "bridge", "tunnel"]); + +/** Action statuses that are not confirmed and must never be exported even when scheduled. */ +const UNCONFIRMED_SCHEDULED_ACTIONS = new Set(["rejected", "requested"]); + +const SCHEDULE_DAY_KEYS = [ + ["MO", "monday"], + ["TU", "tuesday"], + ["WE", "wednesday"], + ["TH", "thursday"], + ["FR", "friday"], + ["SA", "saturday"], + ["SU", "sunday"], +] as const; + +const ALL_ICAL_DAYS = SCHEDULE_DAY_KEYS.map(([code]) => code); + +const FALLBACK_DESCRIPTIONS: Readonly> = { + ROAD_CLOSED: "Road closed", + ROAD_CLOSED_CONSTRUCTION: "Road closed due to construction", + ROAD_CLOSED_EVENT: "Road closed due to event", + ROAD_CLOSED_HAZARD: "Road closed due to hazard", + ACCIDENT: "Accident", + ACCIDENT_MAJOR: "Major accident", + ACCIDENT_MINOR: "Minor accident", + HAZARD: "Road hazard", + HAZARD_ON_ROAD_CONSTRUCTION: "Roadworks", + HAZARD_ON_ROAD_LANE_CLOSED: "Lane closed", + JAM: "Traffic jam", + POLICE: "Police activity", +}; + +/** Unicode scalar value (code-point) length matching XML Schema `xs:minLength`. */ +function codePointLength(value: string): number { + let count = 0; + for (const _ of value) count++; + return count; +} + +function shortHash(value: string): string { + return createHash("sha256").update(value).digest("hex").slice(0, 12); +} + +function wireTime(value: string): string { + const ms = Date.parse(value); + const clamped = Number.isFinite(ms) + ? Math.min(Math.max(ms, FIRST_WIRE_TIME), LAST_WIRE_TIME) + : FIRST_WIRE_TIME; + return new Date(clamped).toISOString().replace(/\.\d{3}Z$/, "Z"); +} + +function cleanText(value: unknown): string | undefined { + if (typeof value !== "string") return undefined; + const cleaned = xmlChars(value).trim(); + return cleaned.length > 0 ? cleaned : undefined; +} + +/** + * Encodes an incident ID segment so root IDs (no `#`) and split IDs (`root#effect`) + * occupy disjoint, poll-stable namespaces and XML 1.0 §3.3.3 attribute whitespace + * normalization (`\t`, `\n`, `\r` → space) cannot collapse distinct IDs. + */ +function encodeIdPart(value: string): string { + return xmlChars(value) + .trim() + .replace(/%/g, "%25") + .replace(/#/g, "%23") + .replace(/\t/g, "%09") + .replace(/\n/g, "%0A") + .replace(/\r/g, "%0D"); +} + +const firstText = (value: unknown): string | undefined => + cleanText((value as { text?: string }[] | undefined)?.[0]?.text); + +function fmtCoord(n: number): string { + const s = n.toFixed(6); + return s === "-0.000000" ? "0.000000" : s; +} + +function canonicalJson(value: unknown): string { + const sort = (v: unknown): unknown => { + if (Array.isArray(v)) return v.map(sort); + if (v !== null && typeof v === "object") { + return Object.fromEntries( + Object.entries(v as Rec) + .sort(([a], [b]) => a.localeCompare(b)) + .map(([k, item]) => [k, sort(item)]), + ); + } + return v; + }; + return JSON.stringify(sort(value)); +} + +function validityKey(v: Validity): string { + const start = v.start !== undefined ? Date.parse(v.start) : null; + const end = v.end !== undefined ? Date.parse(v.end) : null; + return canonicalJson({ + start: Number.isFinite(start) ? start : null, + end: Number.isFinite(end) ? end : null, + periods: v.periods ?? null, + exceptions: v.exceptions ?? null, + }); +} + +function directionKey(d: DirectionRef | undefined): string { + return canonicalJson(d ?? null); +} + +const hasOwnPlace = (effect: Effect): boolean => + (effect.location as { geometry?: unknown } | undefined)?.geometry != null; + +function effectiveLocationOf(situation: Rec, effect?: Effect): Rec { + const base = situation["location"] as Rec; + if (!effect || !hasOwnPlace(effect)) return base; + return { ...base, ...(effect.location as Rec) }; +} + +function effectiveDirectionOf(situation: Rec, effect?: Effect): DirectionRef | undefined { + if (effect?.direction !== undefined) return effect.direction; + if (effect?.location?.direction !== undefined) return effect.location.direction; + return (situation["location"] as Rec | undefined)?.["direction"] as DirectionRef | undefined; +} + +function parseHhMmExact(value: string | undefined): number | undefined { + if (value === undefined) return undefined; + const m = /^(\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(value.trim()); + if (!m) return undefined; + const h = Number(m[1]); + const min = Number(m[2]); + const sec = m[3] !== undefined ? Number(m[3]) : 0; + if (sec !== 0 || h < 0 || h > 23 || min < 0 || min > 59) return undefined; + return h * 60 + min; +} + +function parseDurationMinutes(value: string | undefined): number | undefined { + if (value === undefined) return undefined; + const m = /^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/.exec(value.trim()); + if (!m) return undefined; + const days = m[1] ? Number(m[1]) : 0; + const hours = m[2] ? Number(m[2]) : 0; + const minutes = m[3] ? Number(m[3]) : 0; + const seconds = m[4] ? Number(m[4]) : 0; + if (seconds !== 0) return undefined; + const total = days * 1440 + hours * 60 + minutes; + return total > 0 ? total : undefined; +} + +function fmtHhMm(totalMinutes: number): string { + const h = Math.floor(totalMinutes / 60); + const m = totalMinutes % 60; + return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`; +} + +/** + * Converts a model {@link Validity}'s recurring `periods` into a CIFS + * ``, or returns `"unsupported"` when the recurrence cannot be + * represented faithfully without widening, DST drift, or timezone mismatch. + */ +function cifsScheduleOf( + validity: Validity, + geometry: Geometry | null | undefined, +): CifsSchedule | undefined | "unsupported" { + if (validity.exceptions?.length) return "unsupported"; + const periods = validity.periods; + if (!periods || periods.length === 0) return undefined; + + const geoTz = scheduleTimezoneForGeometry(geometry); + if (!geoTz) return "unsupported"; + + const overallStartDate = + validity.start !== undefined && Number.isFinite(Date.parse(validity.start)) + ? localDateInZone(new Date(validity.start), geoTz) + : undefined; + const overallEndDate = + validity.end !== undefined && Number.isFinite(Date.parse(validity.end)) + ? localDateInZone(new Date(validity.end), geoTz) + : undefined; + + const byDay = new Map>(); + for (const code of ALL_ICAL_DAYS) byDay.set(code, new Set()); + + for (const s of periods as Schedule[]) { + if (s.scheduleTimezone !== geoTz) return "unsupported"; + if ( + s.exceptDate?.length || + s.byMonth?.length || + s.byMonthDay?.length || + s.repeatCount !== undefined + ) { + return "unsupported"; + } + if ( + s.repeatFrequency !== undefined && + s.repeatFrequency !== "P1D" && + s.repeatFrequency !== "P1W" + ) { + return "unsupported"; + } + // Reject sub-period date bounds narrower than the overall validity dates. + if ( + s.startDate !== undefined && + (overallStartDate === undefined || s.startDate > overallStartDate) + ) { + return "unsupported"; + } + if (s.endDate !== undefined && (overallEndDate === undefined || s.endDate < overallEndDate)) { + return "unsupported"; + } + + const startMins = parseHhMmExact(s.startTime); + if (startMins === undefined) return "unsupported"; + + const durMins = s.duration !== undefined ? parseDurationMinutes(s.duration) : undefined; + if (s.duration !== undefined && durMins === undefined) return "unsupported"; + + const endTimeMins = s.endTime !== undefined ? parseHhMmExact(s.endTime) : undefined; + if (s.endTime !== undefined && endTimeMins === undefined) return "unsupported"; + + let endMins: number; + if (durMins !== undefined) { + // `duration` is authoritative in OpenConditions' Schedule contract. + endMins = startMins + durMins; + if (endTimeMins !== undefined && endTimeMins !== endMins) return "unsupported"; + } else if (endTimeMins !== undefined) { + endMins = endTimeMins; + } else { + return "unsupported"; + } + + // Reject overnight, equal-endpoint, or >= 24:00 windows that CIFS cannot express cleanly. + if (endMins <= startMins || endMins >= 24 * 60) return "unsupported"; + + const days = s.byDay && s.byDay.length > 0 ? s.byDay : ALL_ICAL_DAYS; + // Reject windows that cross a DST transition where fixed duration diverges from wall-clock endpoints. + if (scheduleWindowCrossesDst(geoTz, startMins, endMins, days, validity.start, validity.end)) { + return "unsupported"; + } + + const windowText = `${fmtHhMm(startMins)}-${fmtHhMm(endMins)}`; + for (const d of days) { + const bucket = byDay.get(d); + if (!bucket) return "unsupported"; + bucket.add(windowText); + } + } + + const dayStrings = SCHEDULE_DAY_KEYS.map(([code, key]) => { + const entries = [...byDay.get(code)!].sort(); + return [key, entries.length > 0 ? entries.join(",") : undefined] as const; + }); + + const nonEmpty = dayStrings.filter(([, text]) => text !== undefined); + if (nonEmpty.length === 0) return "unsupported"; + + const first = dayStrings[0]![1]; + if (first !== undefined && dayStrings.every(([, text]) => text === first)) { + return { everyday: first }; + } + + // Emit strictly in cifsv2.xsd order: monday..sunday. + const out: CifsSchedule = {}; + for (const [key, text] of dayStrings) { + if (text !== undefined) out[key] = text; + } + return out; +} + +interface SerializedGeometry { + polyline: string; + direction: "ONE_DIRECTION" | "BOTH_DIRECTIONS"; +} + +function serializeGeometryAndDirection( + geometry: Geometry | null | undefined, + direction: DirectionRef | undefined, + isClosure: boolean, + diagnostics: ProjectionDiagnostics, + locationPath: string, + directionPath: string, + effect?: Effect, + emitDiagnostics = true, +): SerializedGeometry | undefined { + const report = ( + code: Parameters[0], + path: string, + message: string, + ) => { + if (emitDiagnostics) diagnostics.emit(code, "message", "withheld", path, message, effect); + }; + + if (!geometry) { + report( + "missing_geometry", + `${locationPath}/geometry`, + "This CIFS message is withheld: no usable geometry is available.", + ); + return undefined; + } + + if (geometry.type === "LineString") { + let dir: "ONE_DIRECTION" | "BOTH_DIRECTIONS"; + let reverse = false; + if (direction === undefined || direction.value === "both") { + dir = "BOTH_DIRECTIONS"; + } else if (direction.basis === "geometry" && direction.value === "positive") { + dir = "ONE_DIRECTION"; + } else if (direction.basis === "geometry" && direction.value === "negative") { + dir = "ONE_DIRECTION"; + reverse = true; + } else { + report( + "unrepresentable_direction", + directionPath, + "This CIFS message is withheld: CIFS cannot infer travel order from this direction.", + ); + return undefined; + } + + const rawCoords = reverse ? [...geometry.coordinates].reverse() : geometry.coordinates; + const serialized: Array<{ latStr: string; lonStr: string; lat: number; lon: number }> = []; + for (const pos of rawCoords) { + const lon = pos[0]; + const lat = pos[1]; + if (typeof lon !== "number" || typeof lat !== "number") continue; + if (!Number.isFinite(lon) || !Number.isFinite(lat)) continue; + if (lat < -90 || lat > 90 || lon < -180 || lon > 180) continue; + const latStr = fmtCoord(lat); + const lonStr = fmtCoord(lon); + const prev = serialized.at(-1); + if (prev !== undefined && prev.latStr === latStr && prev.lonStr === lonStr) continue; + serialized.push({ latStr, lonStr, lat: Number(latStr), lon: Number(lonStr) }); + } + + if (serialized.length < 2) { + report( + "missing_geometry", + `${locationPath}/geometry`, + "This CIFS message is withheld: line collapses to fewer than two distinct vertices at 6-decimal precision.", + ); + return undefined; + } + + // Reject circular polylines (first serialized vertex === last serialized vertex for ≥ 3 vertices). + const first = serialized[0]!; + const last = serialized.at(-1)!; + if (serialized.length >= 3 && first.latStr === last.latStr && first.lonStr === last.lonStr) { + report( + "missing_geometry", + `${locationPath}/geometry`, + "This CIFS message is withheld: circular polylines are not accepted by CIFS.", + ); + return undefined; + } + + let lengthMeters = 0; + for (let i = 1; i < serialized.length; i++) { + const a = serialized[i - 1]!; + const b = serialized[i]!; + lengthMeters += haversineMeters([a.lon, a.lat], [b.lon, b.lat]); + } + if (!(lengthMeters > 0)) { + report( + "missing_geometry", + `${locationPath}/geometry`, + "This CIFS message is withheld: serialized line has zero length.", + ); + return undefined; + } + if (isClosure && lengthMeters > MAX_CLOSURE_METERS) { + report( + "missing_geometry", + `${locationPath}/geometry`, + "This CIFS closure is withheld: polyline exceeds CIFS 20 km closure length limit.", + ); + return undefined; + } + + return { + polyline: serialized.map((p) => `${p.latStr} ${p.lonStr}`).join(" "), + direction: dir, + }; + } + + if (geometry.type === "Point") { + if (isClosure) { + report( + "missing_geometry", + `${locationPath}/geometry`, + "This CIFS ROAD_CLOSED message is withheld: road closures require a LineString.", + ); + return undefined; + } + // Single-point alerts are exported only with explicit bilateral evidence so + // unstated or one-way points are never widened to BOTH_DIRECTIONS. + if (direction?.value !== "both") { + report( + direction !== undefined ? "unrepresentable_direction" : "missing_geometry", + direction !== undefined ? directionPath : `${locationPath}/geometry`, + "This single-point CIFS alert is withheld: single-point alerts require explicit bilateral direction.", + ); + return undefined; + } + const [lon, lat] = geometry.coordinates; + if ( + typeof lon !== "number" || + typeof lat !== "number" || + !Number.isFinite(lon) || + !Number.isFinite(lat) || + lat < -90 || + lat > 90 || + lon < -180 || + lon > 180 + ) { + report( + "missing_geometry", + `${locationPath}/geometry`, + "This CIFS message is withheld: point coordinates are out of range.", + ); + return undefined; + } + return { + polyline: `${fmtCoord(lat)} ${fmtCoord(lon)}`, + direction: "BOTH_DIRECTIONS", + }; + } + + report( + "missing_geometry", + `${locationPath}/geometry`, + `This CIFS message is withheld: ${geometry.type} geometry cannot be represented as a CIFS polyline.`, + ); + return undefined; +} + +function closureSubtypeOf(situation: Rec): CifsXsdSubtype | undefined { + const kind = String(situation["kind"] ?? ""); + if (kind === "roadworks") return "ROAD_CLOSED_CONSTRUCTION"; + if (kind === "public_event") return "ROAD_CLOSED_EVENT"; + if (kind === "road_hazard" || kind === "weather_condition" || kind === "road_condition") { + return "ROAD_CLOSED_HAZARD"; + } + return undefined; +} + +function refineAccidentCode(situation: Rec, code: CifsIncidentCode): CifsIncidentCode { + if (code.type !== "ACCIDENT" || code.subtype !== undefined) return code; + const label = (situation["severity"] as { label?: string } | undefined)?.label; + if (label === "major" || label === "critical") { + return { type: "ACCIDENT", subtype: "ACCIDENT_MAJOR" }; + } + if (label === "minor") { + return { type: "ACCIDENT", subtype: "ACCIDENT_MINOR" }; + } + return code; +} + +function isPartialClosureVehicleImpact( + impact: Extract["vehicleImpact"], +): boolean { + return ( + impact === "some_lanes_closed" || + impact === "some_lanes_closed_merge_left" || + impact === "some_lanes_closed_merge_right" || + impact === "some_lanes_closed_split" + ); +} + +/** + * Whether a `lane_restriction` effect carries affirmative, internally consistent + * evidence that at least one lane is closed (eligible for + * `HAZARD_ON_ROAD_LANE_CLOSED`). Rejects `all_lanes_open*` shifts, traffic + * control impacts, and contradictory lane counts/lists. + */ +function isAffirmativeLaneClosure(effect: Extract): boolean { + if (effect.lanesClosed === 0 || effect.lanesRestricted === 0) return false; + if ( + effect.lanesClosed !== undefined && + effect.lanesRestricted !== undefined && + effect.lanesRestricted < effect.lanesClosed + ) { + return false; + } + const raw = effect.lanes; + let closedInList = 0; + let openInList = 0; + if (raw && raw.length > 0) { + for (const lane of raw) { + if (lane.status === "closed") closedInList++; + else if (lane.status === "open") openInList++; + } + if (effect.lanesClosed !== undefined && closedInList > effect.lanesClosed) return false; + if (effect.lanesRestricted !== undefined && closedInList > effect.lanesRestricted) { + return false; + } + if (effect.lanesTotal !== undefined && raw.length === effect.lanesTotal && closedInList === 0) { + return false; + } + } + if (effect.vehicleImpact === "all_lanes_closed") { + if (openInList > 0) return false; + if (effect.lanesOperational !== undefined && effect.lanesOperational > 0) return false; + if ( + effect.lanesTotal !== undefined && + effect.lanesClosed !== undefined && + effect.lanesClosed < effect.lanesTotal + ) { + return false; + } + return true; + } + if (isPartialClosureVehicleImpact(effect.vehicleImpact)) { + return true; + } + if (effect.vehicleImpact === "unknown") { + return (effect.lanesClosed ?? 0) > 0 || closedInList > 0; + } + return false; +} + +/** + * Extracts a full, contiguous `1..N` CIFS `` layout only when the lane + * array is complete, traffic-eligible, partial (both closed and open lanes), + * and consistent with every declared lane count and `vehicleImpact` on the effect. + */ +function extractCompleteLanes( + effect: Extract, +): CifsLane[] | undefined { + if (!isPartialClosureVehicleImpact(effect.vehicleImpact) && effect.vehicleImpact !== "unknown") { + return undefined; + } + const raw = effect.lanes; + if (!raw || raw.length === 0) return undefined; + const sorted = [...raw].sort((a, b) => a.index - b.index); + const out: CifsLane[] = []; + let closedCount = 0; + for (let i = 0; i < sorted.length; i++) { + const lane = sorted[i]!; + if (lane.index !== i + 1 || lane.index > 99) return undefined; + if (lane.status !== "open" && lane.status !== "closed") return undefined; + if (lane.type !== undefined && lane.type !== "general") return undefined; + if (lane.status === "closed") closedCount++; + out.push({ + order: lane.index, + type: "LANE", + status: lane.status === "closed" ? "CLOSED" : "OPEN", + }); + } + const openCount = out.length - closedCount; + // CIFS is only valid for partial closures (at least one closed and one open lane). + if (closedCount === 0 || closedCount === out.length) return undefined; + // Reconcile against declared counts so a partial or contradictory array is never emitted. + if (effect.lanesTotal !== undefined && effect.lanesTotal !== out.length) return undefined; + if (effect.lanesClosed !== undefined && effect.lanesClosed !== closedCount) return undefined; + if (effect.lanesRestricted !== undefined && effect.lanesRestricted !== closedCount) { + return undefined; + } + if (effect.lanesOperational !== undefined && effect.lanesOperational !== openCount) { + return undefined; + } + return out; +} + +function effectSemantics(effect: Effect, validity: Validity): string { + const { id: _id, sourceRecordRef: _ref, source: _source, ...fields } = effect; + return canonicalJson({ ...fields, validity: effectValidity(effect, validity) }); +} + +function laneStatementSignature(effect: Extract): string { + return canonicalJson({ + vehicleImpact: effect.vehicleImpact, + lanesTotal: effect.lanesTotal ?? null, + lanesClosed: effect.lanesClosed ?? null, + lanesRestricted: effect.lanesRestricted ?? null, + lanesOperational: effect.lanesOperational ?? null, + lanes: effect.lanes ?? null, + }); +} + +function sourceOf(situation: Rec): CifsSource | undefined { + const prov = situation["provenance"] as Rec | undefined; + const info = prov?.["informationSource"] as + | { id?: string; name?: { text?: string }[] } + | undefined; + if (!info) return undefined; + const name = firstText(info.name); + const reference = cleanText(info.id) ?? name; + if (!reference || codePointLength(reference) < 1) return undefined; + return { + reference, + ...(name !== undefined && codePointLength(name) >= 1 ? { name } : {}), + }; +} + +function parentEventOf(situation: Rec): CifsParentEvent | undefined { + const externalIds = situation["externalIds"] as + | Array<{ scheme?: string; id?: string }> + | undefined; + if (!Array.isArray(externalIds)) return undefined; + for (const ext of externalIds) { + if (ext?.scheme !== "cifs:parent_event") continue; + const cleaned = cleanText(ext.id); + if (cleaned !== undefined && codePointLength(cleaned) >= 3) { + return { id: cleaned }; + } + } + return undefined; +} + +function streetOf(location: Rec): string | undefined { + const roads = location["roads"] as Rec[] | undefined; + if (!roads || roads.length === 0) return undefined; + for (const road of roads) { + const name = firstText(road["name"]); + if (name !== undefined && codePointLength(name) >= 2) return name; + const ref = cleanText(road["ref"]); + if (ref !== undefined && codePointLength(ref) >= 2) return ref; + } + return undefined; +} + +function descriptionOf(situation: Rec, code: CifsIncidentCode): string { + const desc = firstText(situation["description"]) ?? firstText(situation["headline"]); + if (desc !== undefined && codePointLength(desc) >= 1) return desc; + return ( + FALLBACK_DESCRIPTIONS[code.subtype ?? code.type] ?? + FALLBACK_DESCRIPTIONS[code.type] ?? + code.type + ); +} + +interface CandidateBucket { + isMain: boolean; + rawId: string; + splitEffectId?: string; + location: Rec; + locationPath: string; + direction: DirectionRef | undefined; + directionPath: string; + validity: Validity; + validityPath: string; + effects: ProjectionEffect[]; + anchorEffect?: Effect; +} + +interface LaneWindowClaim { + bucketIndex: number; + polyline: string; + direction: "ONE_DIRECTION" | "BOTH_DIRECTIONS"; + validity: Validity; + schedule: CifsSchedule | undefined; + tz: string | undefined; + signature: string; +} + +interface BuiltCandidate { + bucketIndex: number; + incident: CifsIncident; + bucket: CandidateBucket; +} + +function addLocalDays(dateStr: string, delta: number): string { + const d = new Date(`${dateStr}T00:00:00Z`); + d.setUTCDate(d.getUTCDate() + delta); + return d.toISOString().slice(0, 10); +} + +function mondayZeroDay(dateStr: string): number { + const utcDay = new Date(`${dateStr}T00:00:00Z`).getUTCDay(); + return (utcDay + 6) % 7; +} + +function parseScheduleMinutes(text: string): Array<[number, number]> { + const out: Array<[number, number]> = []; + for (const part of text.split(",")) { + const m = /^(\d{2}):(\d{2})-(\d{2}):(\d{2})$/.exec(part.trim()); + if (!m) continue; + out.push([Number(m[1]) * 60 + Number(m[2]), Number(m[3]) * 60 + Number(m[4])]); + } + return out; +} + +function scheduleByDayIntervals( + schedule: CifsSchedule | undefined, +): Array> { + if (!schedule) { + return Array.from({ length: 7 }, () => [[0, 24 * 60]]); + } + if (schedule.everyday !== undefined) { + const wins = parseScheduleMinutes(schedule.everyday); + return Array.from({ length: 7 }, () => wins); + } + return SCHEDULE_DAY_KEYS.map(([, key]) => { + const text = schedule[key]; + return text !== undefined ? parseScheduleMinutes(text) : []; + }); +} + +function effectiveWindowsOverlap( + aValidity: Validity, + aSchedule: CifsSchedule | undefined, + aTz: string | undefined, + bValidity: Validity, + bSchedule: CifsSchedule | undefined, + bTz: string | undefined, +): boolean { + const aStart = aValidity.start !== undefined ? Date.parse(aValidity.start) : -Infinity; + const aEnd = aValidity.end !== undefined ? Date.parse(aValidity.end) : Infinity; + const bStart = bValidity.start !== undefined ? Date.parse(bValidity.start) : -Infinity; + const bEnd = bValidity.end !== undefined ? Date.parse(bValidity.end) : Infinity; + const overlapStart = Math.max(aStart, bStart); + const overlapEnd = Math.min(aEnd, bEnd); + if (!(overlapStart < overlapEnd)) return false; + if (!aSchedule && !bSchedule) return true; + + const aDays = scheduleByDayIntervals(aSchedule); + const bDays = scheduleByDayIntervals(bSchedule); + const tz = aTz ?? bTz; + // When the shared outer validity spans at most 14 days, intersect actual + // localized occurrences clipped to [overlapStart, overlapEnd) so two weekly + // schedules whose outer bounds overlap only on non-matching weekdays are not + // falsely flagged as conflicting. + if ( + tz !== undefined && + Number.isFinite(overlapStart) && + Number.isFinite(overlapEnd) && + overlapEnd - overlapStart <= 14 * 86_400_000 + ) { + const firstDay = addLocalDays(localDateInZone(new Date(overlapStart), tz), -1); + const lastDay = localDateInZone(new Date(overlapEnd - 1), tz); + const occurrencesFor = (days: Array>): Array<[number, number]> => { + const out: Array<[number, number]> = []; + for (let day = firstDay; day <= lastDay; day = addLocalDays(day, 1)) { + const dow = mondayZeroDay(day); + for (const [s, e] of days[dow]!) { + const startWall = `${fmtHhMm(s)}:00`; + const endDay = e >= 24 * 60 ? addLocalDays(day, 1) : day; + const endWall = e >= 24 * 60 ? "00:00:00" : `${fmtHhMm(e)}:00`; + const t0 = zonedWallClockToInstant(tz, `${day}T${startWall}`)?.getTime(); + const t1 = zonedWallClockToInstant(tz, `${endDay}T${endWall}`)?.getTime(); + if (t0 === undefined || t1 === undefined) return [[overlapStart, overlapEnd]]; + const c0 = Math.max(t0, overlapStart); + const c1 = Math.min(t1, overlapEnd); + if (c0 < c1) out.push([c0, c1]); + } + } + return out; + }; + const aOcc = occurrencesFor(aDays); + const bOcc = occurrencesFor(bDays); + for (const [as, ae] of aOcc) { + for (const [bs, be] of bOcc) { + if (as < be && bs < ae) return true; + } + } + return false; + } + + for (let d = 0; d < 7; d++) { + for (const [as, ae] of aDays[d]!) { + for (const [bs, be] of bDays[d]!) { + if (as < be && bs < ae) return true; + } + } + } + return false; +} + +interface InternalIncidentResult { + incident: CifsIncident; + isSplit: boolean; + rawSituationId: string; + splitEffectId?: string; +} + +function cifsIncidentsInternal( + situation: Rec, + at: Date, + report?: ExportDiagnosticSink, +): InternalIncidentResult[] { + const diagnostics = new ProjectionDiagnostics(situation, report); + const blocked = diagnostics.blocked("cifs", { + timing: (validity, effect) => { + const loc = effectiveLocationOf(situation, effect); + const geom = loc["geometry"] as Geometry | null | undefined; + return cifsScheduleOf(validity, geom) !== "unsupported"; + }, + }); + if (blocked) return []; + + const rootValidity = situation["validity"] as Validity; + const rootValidityKey = validityKey(rootValidity); + const rootLocation = situation["location"] as Rec; + const rootDirection = rootLocation["direction"] as DirectionRef | undefined; + const rootDirectionKey = directionKey(rootDirection); + const allEffects = projectionEffects(situation); + + const mainEffects: ProjectionEffect[] = []; + const splitMap = new Map(); + + for (const ctx of allEffects) { + const ownPlace = hasOwnPlace(ctx.effect); + const effDir = effectiveDirectionOf(situation, ctx.effect); + const effDirKey = directionKey(effDir); + const effValKey = validityKey(ctx.validity); + if (!ownPlace && effValKey === rootValidityKey && effDirKey === rootDirectionKey) { + mainEffects.push(ctx); + } else { + const placeKey = ownPlace ? canonicalJson(ctx.effect.location) : "__root__"; + const key = `${placeKey}|${effValKey}|${effDirKey}`; + const list = splitMap.get(key) ?? []; + list.push(ctx); + splitMap.set(key, list); + } + } + + const rawSituationId = String(situation["id"]); + const encodedSituationId = encodeIdPart(rawSituationId); + const buckets: CandidateBucket[] = [ + { + isMain: true, + rawId: encodedSituationId, + location: rootLocation, + locationPath: "/location", + direction: rootDirection, + directionPath: "/location/direction", + validity: rootValidity, + validityPath: "/validity", + effects: mainEffects, + }, + ]; + + const splitGroups = [...splitMap.values()]; + for (const group of splitGroups) { + group.sort((a, b) => a.effect.id.localeCompare(b.effect.id)); + } + splitGroups.sort((a, b) => a[0]!.effect.id.localeCompare(b[0]!.effect.id)); + + for (const group of splitGroups) { + const first = group[0]!; + const ownPlace = hasOwnPlace(first.effect); + const effPath = diagnostics.effectPath(first.effect); + const directionPath = + first.effect.direction !== undefined + ? `${effPath}/direction` + : first.effect.location?.direction !== undefined + ? `${effPath}/location/direction` + : "/location/direction"; + const encodedEffectId = encodeIdPart(first.effect.id); + buckets.push({ + isMain: false, + rawId: + encodedSituationId.length > 0 && encodedEffectId.length > 0 + ? `${encodedSituationId}#${encodedEffectId}` + : "", + splitEffectId: first.effect.id, + location: effectiveLocationOf(situation, first.effect), + locationPath: ownPlace ? `${effPath}/location` : "/location", + direction: effectiveDirectionOf(situation, first.effect), + directionPath, + validity: first.validity, + validityPath: first.validityPath, + effects: group, + anchorEffect: first.effect, + }); + } + + const natureCode = cifsIncidentCodeOf({ + kind: String(situation["kind"] ?? ""), + type: String(situation["type"] ?? ""), + ...(typeof situation["subtype"] === "string" ? { subtype: situation["subtype"] } : {}), + }); + const managementOwned = allEffects.some(({ effect }) => + definesManagementNature(situation, effect), + ); + const parentEvent = parentEventOf(situation); + + const built: BuiltCandidate[] = []; + const laneClaims: LaneWindowClaim[] = []; + + for (const [bucketIndex, bucket] of buckets.entries()) { + const active: ProjectionEffect[] = []; + for (const ctx of bucket.effects) { + const projected = projectionStateAt(ctx, at, false); + const effPath = diagnostics.effectPath(ctx.effect); + if (projected.state === "ended" || projected.state === "unknown") { + diagnostics.emit( + projected.state === "ended" ? "effect_ended" : "effect_time_unknown", + "effect", + "omitted", + omittedPath(ctx, projected, effPath), + `This effect is not exported at the evaluation instant: ${projected.state}.`, + ctx.effect, + ); + continue; + } + // Guard scheduled actions too: rejected or unapproved/requested actions must never export. + if ( + projected.state === "scheduled" && + ctx.effect.actionStatus !== undefined && + UNCONFIRMED_SCHEDULED_ACTIONS.has(ctx.effect.actionStatus) + ) { + diagnostics.emit( + "effect_time_unknown", + "effect", + "omitted", + `${effPath}/actionStatus`, + `This scheduled effect is not exported: actionStatus is ${ctx.effect.actionStatus}.`, + ctx.effect, + ); + continue; + } + active.push(ctx); + } + + const closures = active.filter( + (c): c is ProjectionEffect & { effect: Extract } => + c.effect.kind === "closure", + ); + const roadClosures: typeof closures = []; + for (const c of closures) { + const effPath = diagnostics.effectPath(c.effect); + if (!ROAD_CLOSURE_SCOPES.has(c.effect.scope)) { + diagnostics.emit( + "unsupported_effect", + "effect", + "omitted", + `${effPath}/scope`, + `CIFS ROAD_CLOSED does not represent closure scope "${c.effect.scope}".`, + c.effect, + ); + continue; + } + if (c.effect.compliance !== "mandatory") { + diagnostics.emit( + "unsupported_effect", + "effect", + "omitted", + `${effPath}/compliance`, + `CIFS ROAD_CLOSED requires mandatory compliance; "${c.effect.compliance}" closures are not exported as full road closures.`, + c.effect, + ); + continue; + } + if (c.effect.laneScope && c.effect.laneScope.length > 0) { + diagnostics.emit( + "unsupported_effect", + "effect", + "omitted", + `${effPath}/laneScope`, + "CIFS ROAD_CLOSED applies to the full roadway and cannot represent a lane-scoped closure.", + c.effect, + ); + continue; + } + if ( + c.effect.normalization !== "complete" || + c.effect.applicability.kind !== "all" || + (c.effect.applicability.except?.length ?? 0) > 0 + ) { + diagnostics.emit( + "unsupported_effect", + "effect", + "omitted", + effPath, + "CIFS ROAD_CLOSED requires complete all-vehicle closure evidence.", + c.effect, + ); + continue; + } + roadClosures.push(c); + } + + const laneEffects = active.filter( + (c): c is ProjectionEffect & { effect: Extract } => + c.effect.kind === "lane_restriction", + ); + + // Report other unsupported active effects in the bucket. + for (const c of active) { + if (c.effect.kind !== "closure" && c.effect.kind !== "lane_restriction") { + diagnostics.emit( + "unsupported_effect", + "effect", + "omitted", + `${diagnostics.effectPath(c.effect)}/kind`, + `This ${c.effect.kind} effect has no CIFS representation.`, + c.effect, + ); + } + } + + // Detect conflicting distinct lane_restriction effects in the same bucket (including all_lanes_open). + if (laneEffects.length > 1) { + const distinct = new Set(laneEffects.map((c) => effectSemantics(c.effect, c.validity))); + if (distinct.size > 1) { + for (const c of laneEffects) { + diagnostics.emit( + "conflicting_effects", + "message", + "withheld", + diagnostics.effectPath(c.effect), + "This CIFS message is withheld: conflicting lane restrictions cannot be collapsed safely.", + c.effect, + ); + } + continue; + } + } + + // Record every bucket's lane claim (including all_lanes_open) for cross-bucket overlap checks. + const bucketGeometry = bucket.location["geometry"] as Geometry | null | undefined; + const bucketSchedule = cifsScheduleOf(bucket.validity, bucketGeometry); + if (laneEffects.length > 0 && bucketSchedule !== "unsupported") { + const probeGeom = serializeGeometryAndDirection( + bucketGeometry, + bucket.direction, + false, + diagnostics, + bucket.locationPath, + bucket.directionPath, + bucket.anchorEffect, + false, + ); + if (probeGeom) { + laneClaims.push({ + bucketIndex, + polyline: probeGeom.polyline, + direction: probeGeom.direction, + validity: bucket.validity, + schedule: bucketSchedule, + tz: scheduleTimezoneForGeometry(bucketGeometry) ?? undefined, + signature: laneStatementSignature(laneEffects[0]!.effect), + }); + } + } + + let code: CifsIncidentCode | undefined; + let isClosure = false; + let attachLanesEffect: Extract | undefined; + + if (roadClosures.length > 0) { + isClosure = true; + const subtype = closureSubtypeOf(situation); + code = { type: "ROAD_CLOSED", ...(subtype !== undefined ? { subtype } : {}) }; + for (const c of laneEffects) { + diagnostics.emit( + "field_not_exported", + "field", + "omitted", + diagnostics.effectPath(c.effect), + "CIFS forbids partial lane data on ROAD_CLOSED incidents.", + c.effect, + ); + } + } else { + const closingLanes = laneEffects.find((c) => isAffirmativeLaneClosure(c.effect)); + if (bucket.isMain) { + if (natureCode !== null && !managementOwned) { + code = refineAccidentCode(situation, natureCode); + } else if (closingLanes !== undefined) { + code = { type: "HAZARD", subtype: "HAZARD_ON_ROAD_LANE_CLOSED" }; + } else if (natureCode === null && !managementOwned) { + diagnostics.emit( + "unsupported_nature", + "field", + "omitted", + "/type", + "This situation classification has no CIFS incident mapping.", + ); + } + } else if (closingLanes !== undefined) { + code = { type: "HAZARD", subtype: "HAZARD_ON_ROAD_LANE_CLOSED" }; + } + attachLanesEffect = closingLanes?.effect; + } + + if (!code) continue; + + // ROAD_CLOSED requires an explicit validity.start (never invent from mutable poll times). + if (isClosure && bucket.validity.start === undefined) { + diagnostics.emit( + "unsupported_timing", + "message", + "withheld", + `${bucket.validityPath}/start`, + "This CIFS ROAD_CLOSED message is withheld: road closures require an explicit validity.start.", + bucket.anchorEffect, + ); + continue; + } + + const sanitizedId = bucket.rawId; + if (sanitizedId.length === 0 || codePointLength(sanitizedId) < 3) { + diagnostics.emit( + "field_not_exported", + "message", + "withheld", + "/id", + "This CIFS message is withheld: incident id must be at least 3 code points after XML sanitization.", + bucket.anchorEffect, + ); + continue; + } + + const street = streetOf(bucket.location); + if (!street) { + diagnostics.emit( + "field_not_exported", + "message", + "withheld", + `${bucket.locationPath}/roads`, + "This CIFS message is withheld: CIFS requires a street name or road ref of at least 2 code points.", + bucket.anchorEffect, + ); + continue; + } + + if (bucketSchedule === "unsupported") { + diagnostics.emit( + "unsupported_timing", + "message", + "withheld", + `${bucket.validityPath}/periods`, + "This CIFS message is withheld: schedule cannot be represented faithfully in CIFS.", + bucket.anchorEffect, + ); + continue; + } + + const serialized = serializeGeometryAndDirection( + bucketGeometry, + bucket.direction, + isClosure, + diagnostics, + bucket.locationPath, + bucket.directionPath, + bucket.anchorEffect, + ); + if (!serialized) continue; + + let lanes: CifsLane[] | undefined; + if (!isClosure && attachLanesEffect !== undefined) { + const completeLanes = + serialized.direction === "ONE_DIRECTION" + ? extractCompleteLanes(attachLanesEffect) + : undefined; + if (completeLanes !== undefined) { + lanes = completeLanes; + } else { + diagnostics.emit( + "field_not_exported", + "field", + "omitted", + diagnostics.effectPath(attachLanesEffect), + "Partial lane counts, inconsistent totals, or bidirectional/non-contiguous lane data cannot be exported as CIFS without fabricating roadside.", + attachLanesEffect, + ); + } + } + + const provenance = situation["provenance"] as Rec | undefined; + const sourceUpdatedAt = + typeof provenance?.["sourceUpdatedAt"] === "string" + ? wireTime(provenance["sourceUpdatedAt"]) + : undefined; + const source = sourceOf(situation); + + const incident: CifsIncident = { + id: sanitizedId, + ...(parentEvent !== undefined ? { parent_event: parentEvent } : {}), + ...(sourceUpdatedAt !== undefined ? { updatetime: sourceUpdatedAt } : {}), + ...(source !== undefined ? { source } : {}), + type: code.type, + ...(code.subtype !== undefined ? { subtype: code.subtype } : {}), + description: descriptionOf(situation, code), + street, + polyline: serialized.polyline, + direction: serialized.direction, + ...(lanes !== undefined ? { lanes } : {}), + ...(bucket.validity.start !== undefined + ? { starttime: wireTime(bucket.validity.start) } + : {}), + ...(bucket.validity.end !== undefined ? { endtime: wireTime(bucket.validity.end) } : {}), + ...(bucketSchedule !== undefined ? { schedule: bucketSchedule } : {}), + }; + + built.push({ bucketIndex, incident, bucket }); + } + + // Withhold conflicting lane claims (including all_lanes_open) across overlapping + // effective windows (intersecting recurring schedules) at the same place & direction. + const conflictedBuckets = new Set(); + for (let i = 0; i < laneClaims.length; i++) { + for (let j = i + 1; j < laneClaims.length; j++) { + const a = laneClaims[i]!; + const b = laneClaims[j]!; + if (a.signature === b.signature) continue; + if ( + a.polyline === b.polyline && + a.direction === b.direction && + effectiveWindowsOverlap(a.validity, a.schedule, a.tz, b.validity, b.schedule, b.tz) + ) { + conflictedBuckets.add(a.bucketIndex); + conflictedBuckets.add(b.bucketIndex); + } + } + } + + const out: InternalIncidentResult[] = []; + for (const item of built) { + if (conflictedBuckets.has(item.bucketIndex)) { + diagnostics.emit( + "conflicting_effects", + "message", + "withheld", + item.bucket.anchorEffect ? diagnostics.effectPath(item.bucket.anchorEffect) : "/effects", + "This CIFS message is withheld: overlapping effective windows at the same location and direction state conflicting lane restrictions.", + item.bucket.anchorEffect, + ); + continue; + } + out.push({ + incident: item.incident, + isSplit: !item.bucket.isMain, + rawSituationId, + ...(item.bucket.splitEffectId !== undefined + ? { splitEffectId: item.bucket.splitEffectId } + : {}), + }); + } + + return out; +} + +/** + * Projects one canonical situation into zero or more CIFS v2 incidents at `at`. + * Withholds situations or messages whose timing, geometry, direction, vehicle + * scope, or lane restrictions cannot be represented faithfully in CIFS. + */ +export function cifsIncidentsOf( + situation: Rec, + at: Date, + report?: ExportDiagnosticSink, +): CifsIncident[] { + return cifsIncidentsInternal(situation, at, report).map((r) => r.incident); +} + +function disambiguateFeedIds(results: InternalIncidentResult[]): CifsIncident[] { + const rootIdCounts = new Map(); + for (const r of results) { + if (!r.isSplit) { + rootIdCounts.set(r.incident.id, (rootIdCounts.get(r.incident.id) ?? 0) + 1); + } + } + + const used = new Set(); + const out: CifsIncident[] = []; + for (const r of results) { + let id = r.incident.id; + const collidesWithRoot = r.isSplit && rootIdCounts.has(id); + const collidesWithUsed = used.has(id); + const duplicateRoot = !r.isSplit && (rootIdCounts.get(id) ?? 0) > 1; + if (collidesWithRoot || collidesWithUsed || duplicateRoot) { + const seed = r.isSplit + ? `split\0${r.rawSituationId}\0${r.splitEffectId ?? ""}` + : `root\0${r.rawSituationId}`; + let suffix = shortHash(seed); + let candidate = `${id}~${suffix}`; + let n = 1; + while (used.has(candidate) || (r.isSplit && rootIdCounts.has(candidate))) { + suffix = shortHash(`${seed}\0${n++}`); + candidate = `${id}~${suffix}`; + } + id = candidate; + } + used.add(id); + out.push(id === r.incident.id ? r.incident : { ...r.incident, id }); + } + return out; +} + +function scheduleToXml(schedule: CifsSchedule): Record { + // Preserve strict cifsv2.xsd element order. + const out: Record = {}; + if (schedule.everyday !== undefined) out["everyday"] = schedule.everyday; + if (schedule.monday !== undefined) out["monday"] = schedule.monday; + if (schedule.tuesday !== undefined) out["tuesday"] = schedule.tuesday; + if (schedule.wednesday !== undefined) out["wednesday"] = schedule.wednesday; + if (schedule.thursday !== undefined) out["thursday"] = schedule.thursday; + if (schedule.friday !== undefined) out["friday"] = schedule.friday; + if (schedule.saturday !== undefined) out["saturday"] = schedule.saturday; + if (schedule.sunday !== undefined) out["sunday"] = schedule.sunday; + return out; +} + +function incidentToXml(incident: CifsIncident): Record { + return { + "@_id": incident.id, + ...(incident.parent_event !== undefined + ? { parent_event: { "@_id": incident.parent_event.id } } + : {}), + ...(incident.creationtime !== undefined ? { creationtime: incident.creationtime } : {}), + ...(incident.updatetime !== undefined ? { updatetime: incident.updatetime } : {}), + ...(incident.source !== undefined + ? { + source: { + reference: incident.source.reference, + ...(incident.source.name !== undefined ? { name: incident.source.name } : {}), + ...(incident.source.url !== undefined ? { url: incident.source.url } : {}), + }, + } + : {}), + type: incident.type, + ...(incident.subtype !== undefined ? { subtype: incident.subtype } : {}), + description: incident.description, + street: incident.street, + polyline: incident.polyline, + direction: incident.direction, + ...(incident.lanes !== undefined + ? { + lanes: { + lane: incident.lanes.map((l) => ({ + order: l.order, + type: l.type, + status: l.status, + })), + }, + } + : {}), + ...(incident.starttime !== undefined ? { starttime: incident.starttime } : {}), + ...(incident.endtime !== undefined ? { endtime: incident.endtime } : {}), + ...(incident.schedule !== undefined ? { schedule: scheduleToXml(incident.schedule) } : {}), + }; +} + +/** + * Projects situations to a CIFS v2 JSON feed (`{ timestamp?, incidents }`), + * evaluated at `at`. Shares the exact same projection as {@link situationsToCifsXml} + * and guarantees feed-wide incident ID uniqueness after XML sanitization. + */ +export function situationsToCifsJson( + situations: readonly Rec[], + at: Date = new Date(), + info?: { timestamp?: string }, + report?: ExportDiagnosticSink, +): CifsFeed { + const raw = situations.flatMap((situation) => cifsIncidentsInternal(situation, at, report)); + const incidents = disambiguateFeedIds(raw); + const timestamp = info?.timestamp !== undefined ? wireTime(info.timestamp) : undefined; + return { + ...(timestamp !== undefined ? { timestamp } : {}), + incidents, + }; +} + +/** + * Projects situations to a CIFS v2 XML `` document conforming to + * `cifsv2.xsd`, evaluated at `at`. + */ +export function situationsToCifsXml( + situations: readonly Rec[], + at: Date = new Date(), + info?: { timestamp?: string }, + report?: ExportDiagnosticSink, +): string { + const feed = situationsToCifsJson(situations, at, info, report); + const root: Record = { + ...(feed.timestamp !== undefined ? { "@_timestamp": feed.timestamp } : {}), + ...(feed.incidents.length > 0 ? { incident: feed.incidents.map(incidentToXml) } : {}), + }; + return buildXmlDocument({ incidents: root }); +} diff --git a/packages/roads/src/__tests__/cifs-conformance.test.ts b/packages/roads/src/__tests__/cifs-conformance.test.ts new file mode 100644 index 000000000..48a335871 --- /dev/null +++ b/packages/roads/src/__tests__/cifs-conformance.test.ts @@ -0,0 +1,56 @@ +import { pinnedOrUnavailable, type SchemaFile, xsdEnumerations } from "@openconditions/conformance"; +import { CIFS_SCHEMA, CIFS_V2 } from "@openconditions/conformance/standards/cifs-v2"; +import { + CIFS_DIRECTIONS, + CIFS_LANE_STATUSES, + CIFS_ROADSIDES, + CIFS_TYPES, + CIFS_XSD_SUBTYPES, +} from "@openconditions/model-roads"; +import { beforeAll, describe, expect, it } from "vitest"; + +/** + * Holds OpenConditions' CIFS vocabulary declarations against the official + * Google/Waze `cifsv2.xsd` schema pinned by SHA-256. + */ +describe("CIFS v2 schema conformance", () => { + let schemas: SchemaFile[] | undefined; + let unavailable: string | undefined; + + beforeAll(async () => { + const result = await pinnedOrUnavailable(CIFS_V2); + if ("files" in result) schemas = result.files; + else unavailable = result.unavailable; + }, 60_000); + + it("matches every enumeration declared in cifsv2.xsd", () => { + if (unavailable) { + console.warn(unavailable); + return; + } + const xsd = schemas!.find((f) => f.fileName === CIFS_SCHEMA)!.contents; + const enums = xsdEnumerations(schemas!); + + // Inline anonymous simpleTypes under elements in cifsv2.xsd are extracted by + // regex or xsdEnumerations; check element-scoped enumerations directly from XSD. + const elementEnum = (elementName: string): string[] => { + const re = new RegExp( + `]*>([\\s\\S]*?)`, + ); + const match = re.exec(xsd); + expect(match, `element ${elementName} enumeration`).not.toBeNull(); + return [...match![1]!.matchAll(/ m[1]!); + }; + + expect(enums).toBeDefined(); + expect(elementEnum("type").sort()).toEqual([...CIFS_TYPES].sort()); + expect( + elementEnum("subtype") + .filter((v) => v !== "") + .sort(), + ).toEqual([...CIFS_XSD_SUBTYPES].sort()); + expect(elementEnum("direction").sort()).toEqual([...CIFS_DIRECTIONS].sort()); + expect(elementEnum("roadside").sort()).toEqual([...CIFS_ROADSIDES].sort()); + expect(elementEnum("status").sort()).toEqual([...CIFS_LANE_STATUSES].sort()); + }); +}); diff --git a/packages/roads/src/__tests__/cifs.test.ts b/packages/roads/src/__tests__/cifs.test.ts new file mode 100644 index 000000000..22c36c178 --- /dev/null +++ b/packages/roads/src/__tests__/cifs.test.ts @@ -0,0 +1,823 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { buildRegistry, type Effect, kernelModule, sealRecord } from "@openconditions/model"; +import { roadsModule } from "@openconditions/model-roads"; +import { describe, expect, it } from "vitest"; +import { travelDirectionOf } from "../bind/direction.js"; +import { parseCifs, parseCifsSnapshot } from "../cifs.js"; +import { parseEvents } from "../parse.js"; +import { situationDrafts } from "../situation/assemble.js"; +import type { SourceDescriptor } from "../types.js"; +import { roadFeed } from "./helpers/road-feed.js"; + +const registry = buildRegistry([kernelModule, roadsModule]); + +const SRC: SourceDescriptor = { + id: "de-mobidata-bw-cifs", + attribution: "MobiData BW", + country: "DE", + license: "DL-DE-BY-2.0", + licenseUrl: "https://www.govdata.de/dl-de/by-2-0", +}; + +const FIXTURE = (name: string) => + readFileSync(join(import.meta.dirname, "fixtures", "cifs", name), "utf8"); + +function sealDrafts( + input: string, + src: SourceDescriptor = SRC, + fetchedAt = "2026-09-01T10:00:00Z", +) { + const report = parseCifsSnapshot(input, src); + expect(report.errors).toEqual([]); + const events = parseCifs(input, src); + const drafts = situationDrafts(events, { source: src, records: report.records, fetchedAt }); + return drafts.map((draft) => { + const sealed = sealRecord(registry, draft, { + instanceId: "test.local", + revision: 1, + recordedAt: fetchedAt, + }); + expect(sealed.ok, sealed.ok ? "" : JSON.stringify(sealed.issues)).toBe(true); + return sealed.ok ? (sealed.value as Record) : draft; + }); +} + +describe("CIFS inbound parser", () => { + it("parses real MobiData BW CIFS JSON fixture into sealed situations", () => { + const raw = FIXTURE("mobidata-bw.json"); + const records = sealDrafts(raw); + expect(records).toHaveLength(2); + + const works = records[0]!; + expect(works["kind"]).toBe("roadworks"); + expect(works["type"]).toBe("works"); + expect(works["effects"]).toEqual([]); // Bare CONSTRUCTION is a works alert, not a closure + expect((works["location"] as Record)["direction"]).toEqual({ + value: "positive", + basis: "geometry", + }); + expect(works["externalIds"]).toContainEqual({ + scheme: "cifs:incident", + id: "105025184-105025186-105025189-105025193.001", + }); + const worksProv = works["provenance"] as Record; + expect(worksProv["informationSource"]).toEqual({ id: "MobiData BW" }); + expect(worksProv["attribution"]).toMatchObject({ + provider: "MobiData BW", + license: "DL-DE-BY-2.0", + }); + + const closure = records[1]!; + expect(closure["kind"]).toBe("roadworks"); + expect(closure["type"]).toBe("works"); + expect(closure["subtype"]).toBe("construction"); + const closureEffects = closure["effects"] as Effect[]; + expect(closureEffects).toHaveLength(1); + expect(closureEffects[0]).toMatchObject({ + kind: "closure", + scope: "road", + normalization: "complete", + applicability: { kind: "all" }, + }); + expect((closure["location"] as Record)["direction"]).toEqual({ + value: "both", + basis: "text", + text: "BOTH_DIRECTIONS", + }); + }); + + it("parses flat XML incidents with source, parent_event, schedule, lanes, and deduplicated vertices", () => { + const xml = ` + + + + 2026-09-01T08:00:00Z + 2026-09-01T09:30:00Z + + city-ops + City Traffic Center + https://traffic.example.org + + HAZARD + HAZARD_ON_ROAD_LANE_CLOSED + Left lane closed for repairs + Main Street + 48.100000 11.500000 48.100000 11.500000 48.105000 11.510000 + + + 0 + LANE + CLOSED_LANE + + + 1 + LANE + OPEN_LANE + + + 2 + SHOULDER + CLOSED + + + 2026-09-01T09:00:00+02:00 + 2026-09-10T18:00:00+02:00 + + 08:00-10:00 + 08:00-10:00,14:00-16:00 + + +`; + + const [rec] = sealDrafts(xml); + expect(rec!["kind"]).toBe("closure"); + expect(rec!["subtype"]).toBe("lane"); + expect(rec!["headline"]).toBeUndefined(); + expect(rec!["description"]).toEqual([{ lang: "und", text: "Left lane closed for repairs" }]); + expect(rec!["externalIds"]).toEqual([ + { scheme: "cifs:incident", id: "xml-inc-1" }, + { scheme: "cifs:parent_event", id: "event-marathon-2026" }, + ]); + const prov = rec!["provenance"] as Record; + expect(prov["sourceUpdatedAt"]).toBe("2026-09-01T09:30:00.000Z"); + expect(prov["informationSource"]).toEqual({ + id: "city-ops", + name: [{ lang: "und", text: "City Traffic Center" }], + }); + // Consecutive duplicate coordinate collapsed to 2 vertices, omitted direction on line → positive/geometry + const loc = rec!["location"] as Record; + expect(loc["geometry"]).toEqual({ + type: "LineString", + coordinates: [ + [11.5, 48.1], + [11.51, 48.105], + ], + }); + expect(loc["direction"]).toEqual({ value: "positive", basis: "geometry" }); + expect(travelDirectionOf(loc["direction"] as Record)).toEqual({ + kind: "along", + }); + + // 0-based order shifted to 1-based; SHOULDER filtered out → 2 traffic lanes, 1 closed + const [eff] = rec!["effects"] as Effect[]; + expect(eff).toMatchObject({ + kind: "lane_restriction", + normalization: "complete", + vehicleImpact: "some_lanes_closed", + lanesTotal: 2, + lanesClosed: 1, + lanes: [ + { index: 1, status: "closed" }, + { index: 2, status: "open" }, + ], + }); + + // Everyday merged with Monday: 08:00-10:00 daily + 14:00-16:00 Monday + const validity = rec!["validity"] as { periods?: Array> }; + expect(validity.periods).toHaveLength(2); + expect(validity.periods).toContainEqual( + expect.objectContaining({ + repeatFrequency: "P1D", + startTime: "08:00", + endTime: "10:00", + duration: "PT2H", + scheduleTimezone: "Europe/Berlin", + }), + ); + expect(validity.periods).toContainEqual( + expect.objectContaining({ + repeatFrequency: "P1W", + byDay: ["MO"], + startTime: "14:00", + endTime: "16:00", + duration: "PT2H", + scheduleTimezone: "Europe/Berlin", + }), + ); + }); + + it("supports wrapped JSON incidents and maps ACCIDENT_MAJOR/MINOR severity", () => { + const json = JSON.stringify({ + incidents: [ + { + incident: { + id: "acc-major-1", + type: "ACCIDENT", + subtype: "ACCIDENT_MAJOR", + description: "Multi-car crash", + street: "I-95", + polyline: "40.7128 -74.0060", + direction: "BOTH_DIRECTIONS", + }, + }, + { + id: "acc-minor-1", + type: "ACCIDENT", + subtype: "ACCIDENT_MINOR", + description: "Fender bender", + street: "I-95", + polyline: "40.7128 -74.0060", + direction: "ONE_DIRECTION", + }, + ], + }); + + const records = sealDrafts(json); + expect(records).toHaveLength(2); + expect(records[0]!["severity"]).toMatchObject({ label: "major", source: "derived" }); + expect(records[1]!["severity"]).toMatchObject({ label: "minor", source: "derived" }); + // Single-point ONE_DIRECTION preserves unplaced single-direction constraint + const dir = (records[1]!["location"] as Record)["direction"] as Record< + string, + unknown + >; + expect(dir).toEqual({ value: "positive", basis: "unknown", text: "ONE_DIRECTION" }); + expect(travelDirectionOf(dir)).toEqual({ kind: "unplaced" }); + }); + + it("retains point-only ROAD_CLOSED as partial non-routing evidence", () => { + const json = JSON.stringify({ + incidents: [ + { + id: "point-closure-1", + type: "ROAD_CLOSED", + subtype: "ROAD_CLOSED_EVENT", + description: "Parade", + street: "Broadway", + polyline: "40.7580 -73.9855", + direction: "BOTH_DIRECTIONS", + starttime: "2026-09-01T08:00:00Z", + }, + ], + }); + + const [rec] = sealDrafts(json); + expect(rec!["kind"]).toBe("public_event"); + const [eff] = rec!["effects"] as Effect[]; + expect(eff).toMatchObject({ + kind: "closure", + normalization: "partial", + issues: [expect.objectContaining({ code: "invalid_value", sourcePath: "polyline" })], + }); + }); + + it("handles lane_impact and flags conflicting/invalid partial lane data without synthesizing all_lanes_closed", () => { + const json = JSON.stringify({ + incidents: [ + { + id: "impact-ok", + type: "HAZARD", + subtype: "HAZARD_ON_ROAD_CONSTRUCTION", + description: "Right lane closed", + street: "B10", + polyline: "48.7800 9.1800 48.7850 9.1850", + direction: "ONE_DIRECTION", + lane_impact: { total_closed_lanes: 1, roadside: "RIGHT" }, + }, + { + id: "lanes-all-closed", + type: "HAZARD", + subtype: "HAZARD_ON_ROAD_LANE_CLOSED", + description: "All listed lanes closed", + street: "B10", + polyline: "48.7800 9.1800 48.7850 9.1850", + direction: "ONE_DIRECTION", + lanes: [ + { order: 1, type: "LANE", status: "CLOSED" }, + { order: 2, type: "LANE", status: "CLOSED" }, + ], + }, + { + id: "lanes-conflict", + type: "HAZARD", + subtype: "HAZARD_ON_ROAD_LANE_CLOSED", + description: "Conflicting lane impact", + street: "B10", + polyline: "48.7800 9.1800 48.7850 9.1850", + direction: "ONE_DIRECTION", + lanes: [ + { order: 1, type: "LANE", status: "CLOSED" }, + { order: 2, type: "LANE", status: "OPEN" }, + ], + lane_impact: { total_closed_lanes: 2, roadside: "LEFT" }, + }, + { + id: "lanes-both-dirs", + type: "HAZARD", + subtype: "HAZARD_ON_ROAD_LANE_CLOSED", + description: "Both directions with lanes", + street: "B10", + polyline: "48.7800 9.1800 48.7850 9.1850", + direction: "BOTH_DIRECTIONS", + lanes: [ + { order: 1, type: "LANE", status: "CLOSED" }, + { order: 2, type: "LANE", status: "OPEN" }, + ], + }, + ], + }); + + const records = sealDrafts(json); + expect(records).toHaveLength(4); + expect((records[0]!["effects"] as Effect[])[0]).toMatchObject({ + kind: "lane_restriction", + normalization: "complete", + vehicleImpact: "some_lanes_closed", + lanesClosed: 1, + }); + expect((records[1]!["effects"] as Effect[])[0]).toMatchObject({ + kind: "lane_restriction", + normalization: "partial", + vehicleImpact: "unknown", + }); + expect((records[2]!["effects"] as Effect[])[0]).toMatchObject({ + kind: "lane_restriction", + normalization: "partial", + vehicleImpact: "unknown", + }); + expect((records[3]!["effects"] as Effect[])[0]).toMatchObject({ + kind: "lane_restriction", + normalization: "partial", + vehicleImpact: "unknown", + }); + }); + + it("marks inverted starttime/endtime and malformed schedules as validity.status = unknown", () => { + const json = JSON.stringify({ + incidents: [ + { + id: "inverted-window", + type: "ACCIDENT", + description: "Crash", + street: "A8", + polyline: "48.70 9.20 48.71 9.21", + starttime: "2026-09-05T10:00:00Z", + endtime: "2026-09-01T10:00:00Z", + }, + { + id: "equal-schedule", + type: "ROAD_CLOSED", + description: "Closure with bad schedule", + street: "A8", + polyline: "48.70 9.20 48.71 9.21", + starttime: "2026-09-01T10:00:00Z", + schedule: { monday: "09:00-09:00" }, + }, + ], + }); + + const records = sealDrafts(json); + const inverted = records.find( + (r) => r["id"] === "oc:situation:de-mobidata-bw-cifs:inverted-window", + )!; + const badSched = records.find( + (r) => r["id"] === "oc:situation:de-mobidata-bw-cifs:equal-schedule", + )!; + expect((inverted["validity"] as Record)["status"]).toBe("unknown"); + expect((badSched["validity"] as Record)["status"]).toBe("unknown"); + const [eff] = badSched["effects"] as Effect[]; + expect(eff!.issues).toContainEqual( + expect.objectContaining({ code: "unsupported_schedule", sourcePath: "schedule.monday" }), + ); + }); + + it("accounts CHIT_CHAT as terminal and missing polyline as unlocatable", () => { + const json = JSON.stringify({ + incidents: [ + { + id: "chat-1", + type: "CHIT_CHAT", + description: "Hello", + street: "A1", + polyline: "48.0 9.0", + }, + { id: "noloc-1", type: "ACCIDENT", description: "Crash", street: "A1" }, + ], + }); + const report = parseCifsSnapshot(json, SRC); + expect(report.errors).toEqual([]); + expect(report.inputCount).toBe(2); + expect(report.records.map((r) => [r.id, r.disposition])).toEqual([ + ["de-mobidata-bw-cifs:chat-1", "terminal"], + ["de-mobidata-bw-cifs:noloc-1", "unlocatable"], + ]); + }); + + it("rejects wrong roots, error envelopes, subtype mismatches, contradictory location, and mixed wrappers", () => { + expect(() => parseCifsSnapshot("", SRC)).toThrow(//); + expect(() => parseCifsSnapshot("down", SRC)).toThrow( + /unexpected XML child/, + ); + expect(() => + parseCifsSnapshot(JSON.stringify({ error: "unauthorized", incidents: [] }), SRC), + ).toThrow(/error envelope/); + expect(() => parseCifsSnapshot("[]", SRC)).toThrow(/unrecognized payload/); + + // Valid empty feeds return 0 records and 0 errors + expect(parseCifsSnapshot("", SRC)).toEqual({ + inputCount: 0, + records: [], + errors: [], + }); + expect(parseCifsSnapshot(JSON.stringify({ incidents: [] }), SRC)).toEqual({ + inputCount: 0, + records: [], + errors: [], + }); + + // Subtype mismatch, contradictory flat vs legacy location, mixed wrapper + const bad = JSON.stringify({ + incidents: [ + { + id: "mismatch-1", + type: "HAZARD", + subtype: "ROAD_CLOSED_EVENT", + description: "Bad pair", + street: "Main St", + polyline: "48.0 9.0 48.1 9.1", + }, + { + id: "conflict-loc", + type: "ACCIDENT", + description: "Conflict", + street: "Main St", + polyline: "48.0 9.0 48.1 9.1", + location: { street: "Other St", polyline: "48.0 9.0 48.1 9.1" }, + }, + { + incident: { id: "mixed-1", type: "ACCIDENT" }, + extra: true, + }, + ], + }); + const report = parseCifsSnapshot(bad, SRC); + expect(report.errors.map((e) => e.code)).toEqual([ + "invalid_subtype_pair", + "conflicting_location", + "invalid_record", + ]); + expect(() => parseCifs(bad, SRC)).toThrow(/snapshot parse error/); + }); + + it("defaults parseEvents to situationsComplete = false with bounded freshness and fails closed on mixed/conflicting polls", () => { + const feed = roadFeed({ + id: "de-mobidata-bw-cifs", + region: "de", + format: "cifs", + freshnessWindowSec: 600, + }); + const fetchedAt = "2026-09-01T10:00:00.000Z"; + const okOut = parseEvents(feed, [Buffer.from(FIXTURE("mobidata-bw.json"))], { fetchedAt }); + expect(okOut.situationsComplete).toBe(false); + expect(okOut.situations).toHaveLength(2); + expect(okOut.records?.inputCount).toBe(2); + expect(okOut.records?.accepted).toBe(2); + expect((okOut.situations[0]!["freshness"] as Record)["expiresAt"]).toBe( + "2026-09-01T10:10:00.000Z", + ); + + // Qualified complete snapshot sets situationsComplete = true + const completeFeed = roadFeed({ + id: "de-mobidata-bw-cifs", + region: "de", + format: "cifs", + snapshot: { completeness: "complete" }, + }); + const completeOut = parseEvents(completeFeed, [Buffer.from("")], { fetchedAt }); + expect(completeOut.situationsComplete).toBe(true); + expect(completeOut.situations).toEqual([]); + expect(completeOut.records?.inputCount).toBe(0); + + // Mixed valid + malformed poll fails closed instead of partially withdrawing + const mixed = JSON.stringify({ + incidents: [ + { + id: "ok-1", + type: "ACCIDENT", + description: "Crash", + street: "A1", + polyline: "48.0 9.0 48.1 9.1", + }, + { + id: "bad-1", + type: "NO_SUCH_TYPE", + description: "Bad", + street: "A1", + polyline: "48.0 9.0 48.1 9.1", + }, + ], + }); + expect(() => parseEvents(feed, [Buffer.from(mixed)], { fetchedAt })).toThrow(/unknown_type/); + + // Conflicting duplicate IDs across payloads fail closed + const a = JSON.stringify({ + incidents: [ + { + id: "dup-1", + type: "ACCIDENT", + description: "Version A", + street: "A1", + polyline: "48.0 9.0 48.1 9.1", + }, + ], + }); + const b = JSON.stringify({ + incidents: [ + { + id: "dup-1", + type: "ACCIDENT", + description: "Version B", + street: "A1", + polyline: "48.0 9.0 48.1 9.1", + }, + ], + }); + expect(() => parseEvents(feed, [Buffer.from(a), Buffer.from(b)], { fetchedAt })).toThrow( + /snapshot version conflict/, + ); + }); + + it("rejects duplicate XML tags, failure envelopes, and malformed JSON timing fields", () => { + // Explicit failure envelopes must never authorize an empty snapshot + expect(() => parseCifsSnapshot(JSON.stringify({ success: false, incidents: [] }), SRC)).toThrow( + /error envelope/, + ); + expect(() => parseCifsSnapshot(JSON.stringify({ ok: false, incidents: [] }), SRC)).toThrow( + /error envelope/, + ); + expect(() => + parseCifsSnapshot(JSON.stringify({ status: "error", incidents: [] }), SRC), + ).toThrow(/error envelope/); + + // Duplicate XML elements fail closed rather than collapsing to omitted direction + const dupDirXml = ` + + + ROAD_CLOSED + Closed + Main St + 48.78 9.18 48.79 9.19 + ONE_DIRECTION + BOTH_DIRECTIONS + 2026-09-01T08:00:00Z + +`; + const dupReport = parseCifsSnapshot(dupDirXml, SRC); + expect(dupReport.errors).toContainEqual(expect.objectContaining({ code: "invalid_direction" })); + + // Numeric JSON endtime does not silently become an open-ended active closure + const numEnd = JSON.stringify({ + incidents: [ + { + id: "num-end", + type: "ROAD_CLOSED", + description: "Closed", + street: "Main St", + polyline: "48.78 9.18 48.79 9.19", + starttime: "2026-09-01T08:00:00Z", + endtime: 1788260000, + }, + ], + }); + const [rec] = sealDrafts(numEnd); + expect((rec!["validity"] as Record)["status"]).toBe("unknown"); + }); + + it("keeps ROAD_CLOSED without starttime or with circular/>20km polyline non-routing", () => { + const json = JSON.stringify({ + incidents: [ + { + id: "closure-no-start", + type: "ROAD_CLOSED", + description: "Missing start", + street: "A8", + polyline: "48.78 9.18 48.79 9.19", + }, + { + id: "closure-circular", + type: "ROAD_CLOSED", + description: "Loop", + street: "A8", + polyline: "48.78 9.18 48.79 9.19 48.78 9.18", + starttime: "2026-09-01T08:00:00Z", + }, + { + id: "closure-too-long", + type: "ROAD_CLOSED", + description: "Over 20km", + street: "A8", + polyline: "48.00 9.00 48.30 9.00", + starttime: "2026-09-01T08:00:00Z", + }, + ], + }); + const records = sealDrafts(json); + const byId = (local: string) => + records.find((r) => r["id"] === `oc:situation:de-mobidata-bw-cifs:${local}`)!; + expect((byId("closure-no-start")["validity"] as Record)["status"]).toBe( + "unknown", + ); + expect((byId("closure-circular")["effects"] as Effect[])[0]).toMatchObject({ + kind: "closure", + normalization: "partial", + }); + expect((byId("closure-too-long")["effects"] as Effect[])[0]).toMatchObject({ + kind: "closure", + normalization: "partial", + }); + }); + + it("flags roadside conflicts between lanes and lane_impact, preserves source+reference, and rejects DST-crossing schedules", () => { + const json = JSON.stringify({ + incidents: [ + { + id: "roadside-conflict", + type: "HAZARD", + subtype: "HAZARD_ON_ROAD_LANE_CLOSED", + description: "Left lane closed but impact says RIGHT", + street: "B10", + polyline: "48.78 9.18 48.79 9.19", + direction: "ONE_DIRECTION", + source: { name: "City Ops" }, + reference: "ops-ref-1", + lanes: [ + { order: 1, type: "LANE", status: "CLOSED" }, + { order: 2, type: "LANE", status: "OPEN" }, + ], + lane_impact: { total_closed_lanes: 1, roadside: "RIGHT" }, + }, + { + id: "dst-spring", + type: "ROAD_CLOSED", + description: "Spring DST crossing", + street: "B10", + polyline: "48.78 9.18 48.79 9.19", + starttime: "2026-03-28T00:00:00+01:00", + endtime: "2026-03-30T23:59:00+02:00", + schedule: { sunday: "01:00-04:00" }, + }, + { + id: "dst-autumn", + type: "ROAD_CLOSED", + description: "Autumn DST crossing", + street: "B10", + polyline: "48.78 9.18 48.79 9.19", + starttime: "2026-10-24T00:00:00+02:00", + endtime: "2026-10-26T23:59:00+01:00", + schedule: { sunday: "01:00-04:00" }, + }, + { + id: "dst-safe-daytime", + type: "ROAD_CLOSED", + description: "Daytime schedule across spring DST", + street: "B10", + polyline: "48.78 9.18 48.79 9.19", + starttime: "2026-03-28T00:00:00+01:00", + endtime: "2026-03-30T23:59:00+02:00", + schedule: { sunday: "08:00-12:00" }, + }, + ], + }); + const records = sealDrafts(json); + const byId = (local: string) => + records.find((r) => r["id"] === `oc:situation:de-mobidata-bw-cifs:${local}`)!; + + // Conflicting roadside downgraded to partial/unknown, while source.name + top-level reference both survived + expect((byId("roadside-conflict")["effects"] as Effect[])[0]).toMatchObject({ + kind: "lane_restriction", + normalization: "partial", + vehicleImpact: "unknown", + }); + expect( + (byId("roadside-conflict")["provenance"] as Record)["informationSource"], + ).toEqual({ + id: "ops-ref-1", + name: [{ lang: "und", text: "City Ops" }], + }); + + // Spring & autumn DST-crossing windows become validity.status = unknown; daytime window stays active + expect((byId("dst-spring")["validity"] as Record)["status"]).toBe("unknown"); + expect((byId("dst-autumn")["validity"] as Record)["status"]).toBe("unknown"); + expect((byId("dst-safe-daytime")["validity"] as Record)["status"]).toBe( + "active", + ); + }); + + it("handles string error status envelopes, explicit JSON nulls, empty XML lanes, overnight/end-only DST, and duplicate XML source", () => { + // String HTTP error status envelope must fail closed + expect(() => parseCifsSnapshot(JSON.stringify({ status: "503", incidents: [] }), SRC)).toThrow( + /error envelope/, + ); + expect(() => + parseCifsSnapshot(JSON.stringify({ statusCode: "400", incidents: [] }), SRC), + ).toThrow(/error envelope/); + + // Explicit JSON null on endtime leaves closure validity.status = unknown; null direction is rejected + const nullFieldsJson = JSON.stringify({ + incidents: [ + { + id: "null-endtime", + type: "ROAD_CLOSED", + description: "Closed", + street: "B10", + polyline: "48.78 9.18 48.79 9.19", + starttime: "2026-09-01T08:00:00Z", + endtime: null, + }, + { + id: "null-direction", + type: "ROAD_CLOSED", + description: "Closed", + street: "B10", + polyline: "48.78 9.18 48.79 9.19", + starttime: "2026-09-01T08:00:00Z", + direction: null, + }, + ], + }); + const nullReport = parseCifsSnapshot(nullFieldsJson, SRC); + expect(nullReport.errors).toContainEqual( + expect.objectContaining({ id: `${SRC.id}:null-direction`, code: "invalid_direction" }), + ); + const nullEndRec = nullReport.records.find( + (r) => r.disposition === "accepted" && r.event?.id === `${SRC.id}:null-endtime`, + ); + expect(nullEndRec?.event?.situation?.validityStatus).toBe("unknown"); + + // Empty XML inside is detected as malformed instead of dropped + const emptyLaneXml = ` + + + HAZARD + HAZARD_ON_ROAD_LANE_CLOSED + Lane closed + B10 + 48.78 9.18 48.79 9.19 + ONE_DIRECTION + + + 1LANECLOSED + + +`; + const [emptyLaneRec] = sealDrafts(emptyLaneXml); + expect((emptyLaneRec!["effects"] as Effect[])[0]).toMatchObject({ + kind: "lane_restriction", + normalization: "partial", + vehicleImpact: "unknown", + }); + + // Duplicate XML elements fail closed rather than silently dropping provenance + const dupSourceXml = ` + + + ref-1Org A + ref-2Org B + ACCIDENT + Crash + B10 + 48.78 9.18 48.79 9.19 + +`; + const dupSourceReport = parseCifsSnapshot(dupSourceXml, SRC); + expect(dupSourceReport.errors).toContainEqual( + expect.objectContaining({ id: `${SRC.id}:dup-source`, code: "invalid_source" }), + ); + + // Overnight Saturday 23:00-04:00 starting the evening before Sunday spring DST + // when validStart is Sunday 00:00+01:00 still crosses DST, and end-only 2025 bounds are scanned + const dstEdgeJson = JSON.stringify({ + incidents: [ + { + id: "dst-overnight-sat", + type: "ROAD_CLOSED", + description: "Overnight across spring DST", + street: "B10", + polyline: "48.78 9.18 48.79 9.19", + starttime: "2026-03-29T00:00:00+01:00", + endtime: "2026-03-30T00:00:00+02:00", + schedule: { saturday: "23:00-04:00" }, + }, + { + id: "dst-end-only-2025", + type: "HAZARD", + description: "End-only 2025 schedule", + street: "B10", + polyline: "48.78 9.18 48.79 9.19", + endtime: "2025-12-31T23:59:00+01:00", + schedule: { sunday: "01:00-04:00" }, + }, + ], + }); + const dstEdgeRecs = sealDrafts(dstEdgeJson); + const byId = (local: string) => + dstEdgeRecs.find((r) => r["id"] === `oc:situation:${SRC.id}:${local}`)!; + expect((byId("dst-overnight-sat")["validity"] as Record)["status"]).toBe( + "unknown", + ); + expect((byId("dst-end-only-2025")["validity"] as Record)["status"]).toBe( + "unknown", + ); + }); +}); diff --git a/packages/roads/src/__tests__/domain.test.ts b/packages/roads/src/__tests__/domain.test.ts index 46b2e9555..4f93398c1 100644 --- a/packages/roads/src/__tests__/domain.test.ts +++ b/packages/roads/src/__tests__/domain.test.ts @@ -55,6 +55,7 @@ describe("roads formats", () => { [ "autobahn", "cars", + "cifs", "datex2", "digitraffic", "flatjson", diff --git a/packages/roads/src/__tests__/fixtures/cifs/mobidata-bw.json b/packages/roads/src/__tests__/fixtures/cifs/mobidata-bw.json new file mode 100644 index 000000000..f31e03ef8 --- /dev/null +++ b/packages/roads/src/__tests__/fixtures/cifs/mobidata-bw.json @@ -0,0 +1,33 @@ +{ + "timestamp": "2026-11-26T20:00:00.000Z", + "incidents": [ + { + "id": "105025184-105025186-105025189-105025193.001", + "type": "CONSTRUCTION", + "subtype": "", + "description": "Bauphase 1", + "reference": "MobiData BW", + "location": { + "polyline": "48.002535 7.808793 48.002159 7.809804 48.001200 7.812280 47.999522 7.816695", + "street": "B31a Umkirch-Freiburg", + "direction": "ONE_DIRECTION" + }, + "starttime": "2026-08-24T00:00:00.000+02:00", + "endtime": "2027-07-02T23:59:00.000+02:00" + }, + { + "id": "80747046-80747048-80747051-80747216-sperrung.001", + "type": "ROAD_CLOSED", + "subtype": "ROAD_CLOSED_CONSTRUCTION", + "description": "B311 Ausbau Mengen-Rulfingen - Mengen", + "reference": "MobiData BW", + "location": { + "polyline": "48.032693 9.298790 48.033512 9.299247 48.036359 9.302873 48.041292 9.315211", + "street": "B311 Krauchenwies-Mengen", + "direction": "BOTH_DIRECTIONS" + }, + "starttime": "2027-03-01T00:00:00.000+01:00", + "endtime": "2027-12-03T23:59:00.000+01:00" + } + ] +} diff --git a/packages/roads/src/__tests__/skip-metrics-conformance.test.ts b/packages/roads/src/__tests__/skip-metrics-conformance.test.ts index 126e76373..742685b42 100644 --- a/packages/roads/src/__tests__/skip-metrics-conformance.test.ts +++ b/packages/roads/src/__tests__/skip-metrics-conformance.test.ts @@ -90,6 +90,10 @@ const GEOMETRYLESS_SAMPLE: Record = { "ohgo-events": JSON.stringify({ Results: [{ id: "no-geo", description: "x" }] }), "vic-disruptions": JSON.stringify({ disruptions: [{ id: "no-geo", name: "x" }] }), + + cifs: JSON.stringify({ + incidents: [{ id: "no-geo", type: "ACCIDENT", description: "x", street: "Main St" }], + }), }; /** diff --git a/packages/roads/src/cifs.ts b/packages/roads/src/cifs.ts new file mode 100644 index 000000000..c5f4250a2 --- /dev/null +++ b/packages/roads/src/cifs.ts @@ -0,0 +1,1447 @@ +import { haversineMeters, scheduleTimezoneForGeometry, toIsoTimestamp } from "@openconditions/core"; +import { getXmlAttribute, isXmlObject, parseXmlDocument, xmlText } from "@openconditions/datex2"; +import { recordSkipped } from "@openconditions/ingest-framework"; +import { + type DirectionRef, + type InformationSource, + Iso8601, + type Issue, + localDateInZone, + localTimeInZone, + type Schedule, + zonedWallClockToInstant, +} from "@openconditions/model"; +import { + CIFS_LANE_STATUSES, + CIFS_ROADSIDES, + cifsClassification, + isCifsType, + isValidCifsPair, +} from "@openconditions/model-roads"; +import type { LaneStatus, RoadEvent } from "./model.js"; +import { buildLocalSchedule, type LocalSchedule, withTimezone } from "./schedule.js"; +import { coarseOf } from "./situation/classes.js"; +import { text, usableGeometry } from "./situation/location.js"; +import { + canonicalSnapshotValue, + type RoadSnapshotReport, + reconcileRoadSnapshots, +} from "./snapshot.js"; +import type { SourceDescriptor } from "./types.js"; + +/** + * Parser for Waze / Google CIFS (Closure and Incident Feed Specification v2) + * feeds in both XML (``) and JSON (`{ "incidents": [...] }`) wire + * formats. + * + * Every input record is accounted for through {@link parseCifsSnapshot}: + * structural, identity, envelope, type/subtype-pair, coordinate, malformed- + * field, and flat-vs-legacy location conflicts fail closed in `report.errors` + * so a partial or corrupted poll can never be mistaken for an empty feed. + * `CHIT_CHAT` records are non-road-condition chatter and are accounted as + * `terminal`. + */ + +const SCHEDULE_DAYS = [ + ["monday", "MO"], + ["tuesday", "TU"], + ["wednesday", "WE"], + ["thursday", "TH"], + ["friday", "FR"], + ["saturday", "SA"], + ["sunday", "SU"], +] as const; + +const ALL_ICAL_DAYS = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"] as const; +const ICAL_BY_UTC_DAY = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"] as const; +const KNOWN_SCHEDULE_KEYS = new Set(["everyday", ...SCHEDULE_DAYS.map(([name]) => name)]); + +const OPEN_LANE_STATUSES = new Set(["OPEN_LANE", "OPEN", "OPENED"]); +const CLOSED_LANE_STATUSES = new Set(["CLOSED_LANE", "CLOSE", "CLOSED"]); +const KNOWN_LANE_STATUSES = new Set(CIFS_LANE_STATUSES); +const KNOWN_ROADSIDES = new Set(CIFS_ROADSIDES); + +/** Maximum road closure polyline length Waze accepts (20 km). */ +const MAX_CLOSURE_METERS = 20_000; +const DAY_MS = 86_400_000; + +const XML_ARRAY_TAGS = new Set([ + "incident", + "lane", + "everyday", + ...SCHEDULE_DAYS.map(([name]) => name), +]); + +type PlainObject = Record; + +type FieldRead = + | { state: "absent" } + | { state: "ok"; value: string } + | { state: "malformed"; raw: unknown }; + +function isPlainObject(value: unknown): value is PlainObject { + return ( + typeof value === "object" && + value !== null && + !Array.isArray(value) && + (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null) + ); +} + +function str(value: unknown): string | undefined { + if (typeof value !== "string") return undefined; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : undefined; +} + +/** + * Strictly distinguishes absent, valid scalar text, and malformed fields + * (explicit JSON `null`, arrays such as duplicate XML tags, numbers, booleans, + * or nested objects). + */ +function readScalarField(node: PlainObject, key: string, format: "xml" | "json"): FieldRead { + if (!Object.hasOwn(node, key)) return { state: "absent" }; + const raw = node[key]; + if (raw === undefined) return { state: "absent" }; + if (raw === null) return { state: "malformed", raw: null }; + if (typeof raw === "string") { + const trimmed = raw.trim(); + return trimmed.length > 0 ? { state: "ok", value: trimmed } : { state: "absent" }; + } + if (format === "xml" && isXmlObject(raw)) { + const childKeys = Object.keys(raw).filter((k) => !k.startsWith("@_") && k !== "#text"); + if (childKeys.length > 0) return { state: "malformed", raw }; + const t = raw["#text"]; + if (t === undefined || t === null) return { state: "absent" }; + if (typeof t === "string") { + const trimmed = t.trim(); + return trimmed.length > 0 ? { state: "ok", value: trimmed } : { state: "absent" }; + } + return { state: "malformed", raw }; + } + return { state: "malformed", raw }; +} + +function normalizeSpace(value: string): string { + return value.trim().replace(/\s+/g, " "); +} + +function parseStrictNumber(token: string): number | undefined { + if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(token)) return undefined; + const n = Number(token); + return Number.isFinite(n) ? n : undefined; +} + +function parseIntInRange(value: unknown, min: number, max: number): number | undefined { + if (typeof value === "number") { + return Number.isSafeInteger(value) && value >= min && value <= max ? value : undefined; + } + if (typeof value === "string") { + const trimmed = value.trim(); + if (!/^\d+$/.test(trimmed)) return undefined; + const n = Number(trimmed); + return Number.isSafeInteger(n) && n >= min && n <= max ? n : undefined; + } + return undefined; +} + +type TimestampRead = + | { state: "absent" } + | { state: "ok"; value: string; raw: string } + | { state: "invalid"; raw: string }; + +function parseTimestampField(field: FieldRead, timeZone: string | undefined): TimestampRead { + if (field.state === "absent") return { state: "absent" }; + if (field.state === "malformed") return { state: "invalid", raw: String(field.raw) }; + const iso = toIsoTimestamp(field.value, timeZone); + if (iso !== undefined && Iso8601.safeParse(iso).success) { + return { state: "ok", value: iso, raw: field.value }; + } + return { state: "invalid", raw: field.value }; +} + +type PolylineResult = + | { kind: "empty" } + | { kind: "invalid" } + | { + kind: "ok"; + geometry: + | { type: "Point"; coordinates: [number, number] } + | { type: "LineString"; coordinates: [number, number][] }; + }; + +function parsePolyline(raw: string | undefined): PolylineResult { + if (raw === undefined) return { kind: "empty" }; + const tokens = raw.trim().split(/\s+/).filter(Boolean); + if (tokens.length === 0) return { kind: "empty" }; + if (tokens.length < 2 || tokens.length % 2 !== 0) return { kind: "invalid" }; + + const coords: [number, number][] = []; + for (let i = 0; i < tokens.length; i += 2) { + const lat = parseStrictNumber(tokens[i]!); + const lon = parseStrictNumber(tokens[i + 1]!); + if (lat === undefined || lon === undefined) return { kind: "invalid" }; + if (lat < -90 || lat > 90 || lon < -180 || lon > 180) return { kind: "invalid" }; + const prev = coords.at(-1); + if (prev !== undefined && prev[0] === lon && prev[1] === lat) continue; + coords.push([lon, lat]); + } + if (coords.length === 0) return { kind: "invalid" }; + const candidate = + coords.length === 1 + ? ({ type: "Point", coordinates: coords[0]! } as const) + : ({ type: "LineString", coordinates: coords } as const); + const valid = usableGeometry(candidate); + if (!valid || (valid.type !== "Point" && valid.type !== "LineString")) { + return { kind: "invalid" }; + } + return { kind: "ok", geometry: candidate }; +} + +function addLocalDays(date: string, delta: number): string { + return new Date(Date.parse(`${date}T00:00:00Z`) + delta * DAY_MS).toISOString().slice(0, 10); +} + +function fmtHhMm(totalMinutes: number): string { + const h = Math.floor(totalMinutes / 60); + const m = totalMinutes % 60; + return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`; +} + +const DST_TRANSITION_DAYS_CACHE = new Map(); + +function localMidnightInstant(tz: string, date: string): number | null { + return zonedWallClockToInstant(tz, `${date}T00:00:00`)?.getTime() ?? null; +} + +function utcOffsetMinutesAt(tz: string, date: string): number | null { + const t = localMidnightInstant(tz, date); + if (t === null) return null; + const naive = Date.parse(`${date}T00:00:00Z`); + return Math.round((naive - t) / 60_000); +} + +/** + * Local calendar dates in `year` on which `tz` changes UTC offset (DST spring/ + * autumn transitions). Cached per `(tz, year)`. + */ +function dstTransitionDays(tz: string, year: number): string[] { + const cacheKey = `${tz}|${year}`; + const cached = DST_TRANSITION_DAYS_CACHE.get(cacheKey); + if (cached !== undefined) return cached; + + const days: string[] = []; + for (let month = 1; month <= 12; month++) { + const start = `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}-01`; + const nextYear = month === 12 ? year + 1 : year; + const nextMonth = month === 12 ? 1 : month + 1; + const end = `${String(nextYear).padStart(4, "0")}-${String(nextMonth).padStart(2, "0")}-01`; + const oStart = utcOffsetMinutesAt(tz, start); + const oEnd = utcOffsetMinutesAt(tz, end); + if (oStart === null || oEnd === null || oStart === oEnd) continue; + + // Binary search for the transition day inside [start, end). + let lo = 0; + let hi = Math.round( + (Date.parse(`${end}T00:00:00Z`) - Date.parse(`${start}T00:00:00Z`)) / DAY_MS, + ); + while (hi - lo > 1) { + const mid = (lo + hi) >> 1; + const oMid = utcOffsetMinutesAt(tz, addLocalDays(start, mid)); + if (oMid === oStart) lo = mid; + else hi = mid; + } + days.push(addLocalDays(start, lo)); + } + DST_TRANSITION_DAYS_CACHE.set(cacheKey, days); + return days; +} + +function isAmbiguousLocalInstant(tz: string, instantMs: number): boolean { + const wall = localTimeInZone(new Date(instantMs), tz); + const date = localDateInZone(new Date(instantMs), tz); + for (const delta of [-3_600_000, 3_600_000, -1_800_000, 1_800_000]) { + const probe = new Date(instantMs + delta); + if (localDateInZone(probe, tz) === date && localTimeInZone(probe, tz) === wall) { + return true; + } + } + return false; +} + +/** + * Whether a recurring local wall-clock window `[startMins, endMins)` on `days` + * crosses, starts inside, or ends inside a DST transition in `tz` within + * `[validStartIso, validEndIso]` (or across a representative year when either + * bound is absent). Fixed-duration `Schedule` evaluation cannot match wall- + * clock endpoints across such a transition without drifting by an hour. + */ +export function scheduleWindowCrossesDst( + tz: string, + startMins: number, + endMins: number, + days: readonly string[], + validStartIso?: string, + validEndIso?: string, +): boolean { + const daySet = new Set(days); + const startMs = validStartIso !== undefined ? Date.parse(validStartIso) : Number.NaN; + const endMs = validEndIso !== undefined ? Date.parse(validEndIso) : Number.NaN; + const hasStart = Number.isFinite(startMs); + const hasEnd = Number.isFinite(endMs); + + if (hasStart && hasEnd && startMs >= endMs) return false; + + const startDate = hasStart ? localDateInZone(new Date(startMs), tz) : undefined; + const endDate = hasEnd ? localDateInZone(new Date(endMs), tz) : undefined; + + const overnight = endMins <= startMins; + const nominalMins = overnight ? 24 * 60 - startMins + endMins : endMins - startMins; + const startWall = `${fmtHhMm(startMins)}:00`; + const endWall = endMins < 24 * 60 ? `${fmtHhMm(endMins)}:00` : "00:00:00"; + + let baseYear: number; + let lastYear: number; + if (startDate !== undefined && endDate !== undefined) { + baseYear = Number(startDate.slice(0, 4)) - (overnight ? 1 : 0); + lastYear = Math.min(Number(endDate.slice(0, 4)), baseYear + 7); + } else if (startDate !== undefined) { + baseYear = Number(startDate.slice(0, 4)) - (overnight ? 1 : 0); + lastYear = baseYear + 6; + } else if (endDate !== undefined) { + lastYear = Number(endDate.slice(0, 4)); + baseYear = lastYear - 6; + } else { + baseYear = 2026; + lastYear = 2032; + } + + for (let year = baseYear; year <= lastYear; year++) { + for (const transDay of dstTransitionDays(tz, year)) { + const candidates = overnight ? [addLocalDays(transDay, -1), transDay] : [transDay]; + for (const occDay of candidates) { + const dow = ICAL_BY_UTC_DAY[new Date(`${occDay}T00:00:00Z`).getUTCDay()]!; + if (!daySet.has(dow)) continue; + + const tStart = zonedWallClockToInstant(tz, `${occDay}T${startWall}`); + const endOccDay = overnight || endMins === 24 * 60 ? addLocalDays(occDay, 1) : occDay; + const tEnd = zonedWallClockToInstant(tz, `${endOccDay}T${endWall}`); + if (tStart === null || tEnd === null) { + if (startDate !== undefined && endOccDay < startDate) continue; + if (endDate !== undefined && occDay > endDate) continue; + return true; + } + + // Check overlap against actual [startMs, endMs) instants so overnight + // occurrences starting the evening before validStartIso are included. + const effEndMs = Math.max(tEnd.getTime(), tStart.getTime() + nominalMins * 60_000); + if (hasStart && effEndMs <= startMs) continue; + if (hasEnd && tStart.getTime() >= endMs) continue; + + // Spring-forward gap: wall clock shifted past the non-existent hour. + if (localTimeInZone(tStart, tz) !== startWall) return true; + if (localTimeInZone(tEnd, tz) !== endWall) return true; + + // Elapsed duration diverges from nominal wall-clock span across DST. + if (Math.round((tEnd.getTime() - tStart.getTime()) / 60_000) !== nominalMins) return true; + + // Autumn fold: start or end falls on a repeated local hour. + if (isAmbiguousLocalInstant(tz, tStart.getTime())) return true; + if (isAmbiguousLocalInstant(tz, tEnd.getTime())) return true; + } + } + } + return false; +} + +interface ParsedWindow { + key: string; + startMins: number; + endMins: number; + startTime: string; + endTime?: string; + duration: string; +} + +function isoDurationMinutes(totalMinutes: number): string { + const h = Math.floor(totalMinutes / 60); + const m = totalMinutes % 60; + return `PT${h ? `${h}H` : ""}${m ? `${m}M` : ""}`; +} + +function parseScheduleWindow(segment: string): ParsedWindow | undefined { + const match = /^(\d{1,2}):(\d{2})-(\d{1,2}):(\d{2})$/.exec(segment.trim()); + if (!match) return undefined; + const sh = Number(match[1]); + const sm = Number(match[2]); + const eh = Number(match[3]); + const em = Number(match[4]); + if (sh < 0 || sh > 23 || sm < 0 || sm > 59) return undefined; + if (!((eh >= 0 && eh <= 23 && em >= 0 && em <= 59) || (eh === 24 && em === 0))) { + return undefined; + } + const startMins = sh * 60 + sm; + const endMins = eh * 60 + em; + // Equal endpoints (e.g. 09:00-09:00) are ambiguous/malformed rather than 24h. + if (startMins === endMins) return undefined; + const span = endMins > startMins ? endMins - startMins : 24 * 60 - startMins + endMins; + const startTime = `${String(sh).padStart(2, "0")}:${String(sm).padStart(2, "0")}`; + const endTime = + eh === 24 ? undefined : `${String(eh).padStart(2, "0")}:${String(em).padStart(2, "0")}`; + return { + key: `${startTime}|${endTime ?? "24:00"}|${span}`, + startMins, + endMins, + startTime, + ...(endTime !== undefined ? { endTime } : {}), + duration: isoDurationMinutes(span), + }; +} + +function extractScheduleStrings(value: unknown): string[] | undefined { + if (typeof value === "string") return [value]; + if (Array.isArray(value)) { + const out: string[] = []; + for (const entry of value) { + const textValue = typeof entry === "string" ? entry : xmlText(entry); + if (textValue === undefined) return undefined; + out.push(textValue); + } + return out; + } + const textValue = xmlText(value); + return textValue !== undefined ? [textValue] : undefined; +} + +function parseSchedule( + node: PlainObject, + timeZone: string | null, + validFrom?: string, + validTo?: string, +): { present: false } | { present: true; schedules?: Schedule[]; issue?: Issue } { + if (!Object.hasOwn(node, "schedule") || node["schedule"] === undefined) return { present: false }; + const rawSchedule = node["schedule"]; + if (rawSchedule === null) { + return { + present: true, + issue: { + code: "unsupported_schedule", + sourcePath: "schedule", + sourceText: "null schedule", + }, + }; + } + if (rawSchedule === "") { + return { + present: true, + issue: { + code: "unsupported_schedule", + sourcePath: "schedule", + sourceText: "empty schedule element", + }, + }; + } + if (!isPlainObject(rawSchedule)) { + return { + present: true, + issue: { + code: "unsupported_schedule", + sourcePath: "schedule", + sourceText: "malformed schedule", + }, + }; + } + + const keys = Object.keys(rawSchedule).filter((k) => !k.startsWith("@_")); + if (keys.length === 0) { + return { + present: true, + issue: { + code: "unsupported_schedule", + sourcePath: "schedule", + sourceText: "empty schedule", + }, + }; + } + for (const key of keys) { + if (!KNOWN_SCHEDULE_KEYS.has(key)) { + return { + present: true, + issue: { + code: "unsupported_schedule", + sourcePath: `schedule.${key}`, + sourceText: key, + }, + }; + } + } + + const windowsByKey = new Map(); + const daysByWindow = new Map>(); + + const addForDays = ( + rawValue: unknown, + days: readonly string[], + sourceKey: string, + ): Issue | undefined => { + const strings = extractScheduleStrings(rawValue); + if (!strings || strings.length === 0) { + return { + code: "unsupported_schedule", + sourcePath: `schedule.${sourceKey}`, + sourceText: "malformed schedule entry", + }; + } + for (const s of strings) { + const trimmed = s.trim(); + if (!trimmed) { + return { + code: "unsupported_schedule", + sourcePath: `schedule.${sourceKey}`, + sourceText: "empty schedule window", + }; + } + // cifsv2.xsd pattern allows an optional trailing comma after a valid window. + const normalized = trimmed.endsWith(",") ? trimmed.slice(0, -1) : trimmed; + const parts = normalized.split(","); + if (parts.length === 0) { + return { + code: "unsupported_schedule", + sourcePath: `schedule.${sourceKey}`, + sourceText: trimmed, + }; + } + for (const part of parts) { + const parsed = parseScheduleWindow(part); + if (!parsed) { + return { + code: "unsupported_schedule", + sourcePath: `schedule.${sourceKey}`, + sourceText: trimmed, + }; + } + windowsByKey.set(parsed.key, parsed); + let set = daysByWindow.get(parsed.key); + if (!set) { + set = new Set(); + daysByWindow.set(parsed.key, set); + } + for (const day of days) set.add(day); + } + } + return undefined; + }; + + if (Object.hasOwn(rawSchedule, "everyday")) { + const issue = addForDays(rawSchedule["everyday"], ALL_ICAL_DAYS, "everyday"); + if (issue) return { present: true, issue }; + } + for (const [dayName, icalDay] of SCHEDULE_DAYS) { + if (Object.hasOwn(rawSchedule, dayName)) { + const issue = addForDays(rawSchedule[dayName], [icalDay], dayName); + if (issue) return { present: true, issue }; + } + } + + if (windowsByKey.size === 0) { + return { + present: true, + issue: { + code: "unsupported_schedule", + sourcePath: "schedule", + sourceText: "empty schedule", + }, + }; + } + if (!timeZone) { + return { + present: true, + issue: { + code: "unsupported_schedule", + sourcePath: "schedule", + sourceText: "unable to resolve schedule timezone", + }, + }; + } + + const localSchedules: LocalSchedule[] = []; + for (const [key, win] of windowsByKey) { + const daySet = daysByWindow.get(key)!; + const orderedDays = ALL_ICAL_DAYS.filter((d) => daySet.has(d)); + // A wall-clock schedule crossing a DST transition cannot be faithfully + // evaluated via fixed elapsed duration without drifting by an hour. + if ( + scheduleWindowCrossesDst( + timeZone, + win.startMins, + win.endMins, + orderedDays, + validFrom, + validTo, + ) + ) { + return { + present: true, + issue: { + code: "unsupported_schedule", + sourcePath: "schedule", + sourceText: `${win.startTime}-${win.endTime ?? "24:00"} crosses DST transition in ${timeZone}`, + }, + }; + } + const allDays = orderedDays.length === ALL_ICAL_DAYS.length; + const built = buildLocalSchedule({ + startTime: win.startTime, + ...(win.endTime !== undefined ? { endTime: win.endTime } : {}), + ...(!allDays ? { byDay: orderedDays } : {}), + }); + // Keep exact duration (including 24h windows where endTime is omitted). + built.duration = win.duration; + localSchedules.push(built); + } + const stamped = withTimezone(localSchedules, timeZone); + if (!stamped) { + return { + present: true, + issue: { + code: "unsupported_schedule", + sourcePath: "schedule", + sourceText: "unable to stamp schedule timezone", + }, + }; + } + return { present: true, schedules: stamped }; +} + +interface NormalizedLane { + order: number; + type: string; + status: "open" | "closed"; +} + +interface ParsedLaneData { + lanesAffected?: RoadEvent["lanesAffected"]; + issues: Issue[]; +} + +function roadsideMatchesLanes(roadside: string, trafficLanes: readonly NormalizedLane[]): boolean { + const n = trafficLanes.length; + const closedPos: number[] = []; + for (let i = 0; i < n; i++) { + if (trafficLanes[i]!.status === "closed") closedPos.push(i); + } + if (closedPos.length === 0) return true; + const count = closedPos.length; + if (roadside === "LEFT") { + return count < n && closedPos.every((pos, idx) => pos === idx); + } + if (roadside === "RIGHT") { + return count < n && closedPos.every((pos, idx) => pos === n - count + idx); + } + if (roadside === "MIDDLE") { + return closedPos[0]! > 0 && closedPos.at(-1)! < n - 1; + } + return false; +} + +function parseLanesField( + node: PlainObject, + incidentType: string, + isSingleDirectionLine: boolean, + format: "xml" | "json", +): ParsedLaneData { + const hasLanes = Object.hasOwn(node, "lanes") && node["lanes"] !== undefined; + const hasImpact = Object.hasOwn(node, "lane_impact") && node["lane_impact"] !== undefined; + if (!hasLanes && !hasImpact) return { issues: [] }; + const rawLanes = node["lanes"]; + const rawLaneImpact = node["lane_impact"]; + + const issueOf = (sourcePath: string, sourceText: string): ParsedLaneData => ({ + ...(incidentType !== "ROAD_CLOSED" ? { lanesAffected: { vehicleImpact: "unknown" } } : {}), + issues: [{ code: "invalid_value", sourcePath, sourceText }], + }); + + if (incidentType === "ROAD_CLOSED") { + return issueOf( + hasLanes ? "lanes" : "lane_impact", + "partial lane data is not valid on ROAD_CLOSED", + ); + } + if (!isSingleDirectionLine) { + return issueOf( + hasLanes ? "lanes" : "lane_impact", + "partial lane data requires a single-direction line", + ); + } + + let parsedLanes: NormalizedLane[] | undefined; + if (hasLanes) { + let rawItems: unknown[]; + if (format === "xml") { + if (!isXmlObject(rawLanes)) { + return issueOf("lanes", "malformed lanes element"); + } + const extraKeys = Object.keys(rawLanes).filter((k) => !k.startsWith("@_") && k !== "lane"); + if (extraKeys.length > 0) { + return issueOf(`lanes.${extraKeys[0]}`, "unexpected child element in lanes"); + } + const laneProp = rawLanes["lane"]; + // Keep every raw entry (including empty ) so malformed items are never dropped. + rawItems = laneProp === undefined ? [] : Array.isArray(laneProp) ? laneProp : [laneProp]; + } else if (Array.isArray(rawLanes)) { + rawItems = rawLanes; + } else if (isPlainObject(rawLanes) && Array.isArray(rawLanes["lane"])) { + rawItems = rawLanes["lane"]; + } else { + return issueOf("lanes", "malformed lanes field"); + } + if (rawItems.length === 0) return issueOf("lanes", "empty lanes list"); + + const seenOrders = new Set(); + const items: NormalizedLane[] = []; + for (const [i, entry] of rawItems.entries()) { + if (!isPlainObject(entry)) { + return issueOf(`lanes[${i}]`, "malformed lane entry"); + } + const orderField = + format === "xml" + ? readScalarField(entry, "order", format) + : entry["order"] === undefined || entry["order"] === null + ? { state: "absent" as const } + : typeof entry["order"] === "number" || typeof entry["order"] === "string" + ? { state: "ok" as const, value: entry["order"] } + : { state: "malformed" as const, raw: entry["order"] }; + const typeField = readScalarField(entry, "type", format); + const statusField = readScalarField(entry, "status", format); + + const order = + orderField.state === "ok" ? parseIntInRange(orderField.value, 0, 99) : undefined; + if (order === undefined) return issueOf(`lanes[${i}].order`, String(entry["order"] ?? "")); + if (seenOrders.has(order)) { + return issueOf(`lanes[${i}].order`, `duplicate lane order ${order}`); + } + seenOrders.add(order); + if (typeField.state !== "ok") + return issueOf(`lanes[${i}].type`, "invalid or missing lane type"); + if (statusField.state !== "ok" || !KNOWN_LANE_STATUSES.has(statusField.value)) { + return issueOf( + `lanes[${i}].status`, + statusField.state === "ok" ? statusField.value : "invalid or missing lane status", + ); + } + const status: "open" | "closed" = CLOSED_LANE_STATUSES.has(statusField.value) + ? "closed" + : OPEN_LANE_STATUSES.has(statusField.value) + ? "open" + : "closed"; + items.push({ order, type: typeField.value, status }); + } + items.sort((a, b) => a.order - b.order); + parsedLanes = items; + } + + let parsedImpact: { totalClosedLanes: number; roadside: string } | undefined; + if (hasImpact) { + if (!isPlainObject(rawLaneImpact)) { + return issueOf("lane_impact", "malformed lane_impact"); + } + const closedField = + format === "xml" + ? readScalarField(rawLaneImpact, "total_closed_lanes", format) + : rawLaneImpact["total_closed_lanes"] === undefined || + rawLaneImpact["total_closed_lanes"] === null + ? { state: "absent" as const } + : typeof rawLaneImpact["total_closed_lanes"] === "number" || + typeof rawLaneImpact["total_closed_lanes"] === "string" + ? { state: "ok" as const, value: rawLaneImpact["total_closed_lanes"] } + : { state: "malformed" as const, raw: rawLaneImpact["total_closed_lanes"] }; + const roadsideField = readScalarField(rawLaneImpact, "roadside", format); + const totalClosedLanes = + closedField.state === "ok" ? parseIntInRange(closedField.value, 0, 99) : undefined; + if (totalClosedLanes === undefined) { + return issueOf( + "lane_impact.total_closed_lanes", + String(rawLaneImpact["total_closed_lanes"] ?? ""), + ); + } + if (roadsideField.state !== "ok" || !KNOWN_ROADSIDES.has(roadsideField.value)) { + return issueOf( + "lane_impact.roadside", + roadsideField.state === "ok" ? roadsideField.value : "invalid or missing roadside", + ); + } + parsedImpact = { totalClosedLanes, roadside: roadsideField.value }; + } + + if (parsedLanes !== undefined) { + // Only traffic lanes ("LANE" per cifsv2.xsd) determine traffic lane counts. + const trafficLanes = parsedLanes.filter((l) => l.type.toUpperCase() === "LANE"); + if (trafficLanes.length === 0) { + return issueOf("lanes", "no traffic lanes (type=LANE) in lanes list"); + } + const offset = parsedLanes[0]!.order === 0 ? 1 : 0; + const closedCount = trafficLanes.filter((l) => l.status === "closed").length; + if (parsedImpact !== undefined) { + if (parsedImpact.totalClosedLanes !== closedCount) { + return issueOf( + "lane_impact.total_closed_lanes", + `lane_impact (${parsedImpact.totalClosedLanes}) conflicts with lanes (${closedCount})`, + ); + } + if (!roadsideMatchesLanes(parsedImpact.roadside, trafficLanes)) { + return issueOf( + "lane_impact.roadside", + `lane_impact roadside ${parsedImpact.roadside} conflicts with closed lane positions`, + ); + } + } + const lanes: LaneStatus[] = trafficLanes.map((l) => ({ + index: l.order + offset, + status: l.status, + })); + // Never synthesize all_lanes_closed from partial lane data on a non-ROAD_CLOSED incident. + if (closedCount === trafficLanes.length) { + return { + lanesAffected: { + total: trafficLanes.length, + closed: closedCount, + lanes, + vehicleImpact: "unknown", + }, + issues: [ + { + code: "invalid_value", + sourcePath: "lanes", + sourceText: "all listed traffic lanes closed on non-ROAD_CLOSED incident", + }, + ], + }; + } + return { + lanesAffected: { + total: trafficLanes.length, + closed: closedCount, + lanes, + vehicleImpact: closedCount > 0 ? "some-lanes-closed" : "all-lanes-open", + }, + issues: [], + }; + } + + // Only lane_impact present: total lane count is unknown, so never derive all_lanes_closed. + const closed = parsedImpact!.totalClosedLanes; + return { + lanesAffected: { + closed, + vehicleImpact: closed > 0 ? "some-lanes-closed" : "all-lanes-open", + }, + issues: [], + }; +} + +function parseInformationSource( + node: PlainObject, + format: "xml" | "json", +): { ok: true; value?: InformationSource } | { ok: false } { + let nestedRef: string | undefined; + let name: string | undefined; + if (Object.hasOwn(node, "source") && node["source"] !== undefined) { + const rawSource = node["source"]; + if (rawSource === null || (format === "json" && rawSource === "")) return { ok: false }; + if (rawSource !== "") { + // Reject duplicate XML arrays and non-object shapes instead of erasing provenance. + if (!isPlainObject(rawSource)) return { ok: false }; + const refField = readScalarField(rawSource, "reference", format); + const nameField = readScalarField(rawSource, "name", format); + if (refField.state === "malformed" || nameField.state === "malformed") return { ok: false }; + if (refField.state === "ok") nestedRef = refField.value; + if (nameField.state === "ok") name = nameField.value; + } + } + + let topRef: string | undefined; + if (format === "json") { + const topRefField = readScalarField(node, "reference", format); + if (topRefField.state === "malformed") return { ok: false }; + if (topRefField.state === "ok") topRef = topRefField.value; + } + + if (nestedRef !== undefined && topRef !== undefined && nestedRef !== topRef) { + return { ok: false }; + } + const ref = nestedRef ?? topRef; + const out: InformationSource = {}; + if (ref !== undefined) out.id = ref; + if (name !== undefined) out.name = [{ lang: "und", text: name }]; + return { ok: true, ...(Object.keys(out).length > 0 ? { value: out } : {}) }; +} + +function parseParentEventId(node: PlainObject, format: "xml" | "json"): FieldRead { + if (!Object.hasOwn(node, "parent_event")) return { state: "absent" }; + const raw = node["parent_event"]; + if (raw === undefined) return { state: "absent" }; + if (raw === null) return { state: "malformed", raw: null }; + if (format === "xml") { + if (!isXmlObject(raw)) return { state: "malformed", raw }; + const id = str(getXmlAttribute(raw, "id")); + return id ? { state: "ok", value: id } : { state: "malformed", raw }; + } + if (typeof raw === "string") { + const id = str(raw); + return id ? { state: "ok", value: id } : { state: "absent" }; + } + if (isPlainObject(raw)) { + const idField = readScalarField(raw, "id", format); + return idField.state === "ok" ? idField : { state: "malformed", raw }; + } + return { state: "malformed", raw }; +} + +function mergeLocationField( + flatField: FieldRead, + nestedField: FieldRead, + normalize?: (value: string) => string, +): { ok: true; value?: string } | { ok: false; code: "invalid" | "conflict" } { + if (flatField.state === "malformed" || nestedField.state === "malformed") { + return { ok: false, code: "invalid" }; + } + const flatValue = flatField.state === "ok" ? flatField.value : undefined; + const nestedValue = nestedField.state === "ok" ? nestedField.value : undefined; + if (flatValue !== undefined && nestedValue !== undefined) { + const a = normalize ? normalize(flatValue) : flatValue; + const b = normalize ? normalize(nestedValue) : nestedValue; + if (a !== b) return { ok: false, code: "conflict" }; + return { ok: true, value: flatValue }; + } + return { ok: true, value: flatValue ?? nestedValue }; +} + +function isHttpErrorStatus(value: unknown): boolean { + if (typeof value === "number") return Number.isFinite(value) && value >= 400; + if (typeof value === "string") { + const trimmed = value.trim(); + if (/^\d+$/.test(trimmed)) return Number(trimmed) >= 400; + return ["error", "failed", "failure"].includes(trimmed.toLowerCase()); + } + return false; +} + +function isJsonFailureEnvelope(doc: PlainObject): boolean { + if (Object.hasOwn(doc, "error") && doc["error"] != null) return true; + if (Object.hasOwn(doc, "errors") && doc["errors"] != null) return true; + if (doc["success"] === false || doc["ok"] === false) return true; + if (isHttpErrorStatus(doc["status"]) || isHttpErrorStatus(doc["statusCode"])) return true; + return false; +} + +function extractRawIncidents(input: string | Buffer): { + format: "xml" | "json"; + incidents: unknown[]; +} { + const raw = (Buffer.isBuffer(input) ? input.toString("utf8") : input) + .replace(/^\uFEFF/, "") + .trimStart(); + + if (raw.startsWith("{")) { + let doc: unknown; + try { + doc = JSON.parse(raw); + } catch (error) { + throw new Error(`cifs: invalid JSON document (${(error as Error).message})`); + } + if (!isPlainObject(doc)) { + throw new Error("cifs: expected JSON object root"); + } + if (isJsonFailureEnvelope(doc)) { + throw new Error("cifs: JSON error envelope rejected"); + } + if (!Array.isArray(doc["incidents"])) { + throw new Error("cifs: expected JSON object with an incidents array"); + } + return { format: "json", incidents: doc["incidents"] }; + } + + if (raw.startsWith("<")) { + const doc = parseXmlDocument(raw, { + ignoreAttributes: false, + removeNSPrefix: true, + validate: true, + isArray: (name) => XML_ARRAY_TAGS.has(name), + }); + const rootKeys = Object.keys(doc).filter((k) => k !== "?xml"); + if (rootKeys.length !== 1 || rootKeys[0] !== "incidents") { + throw new Error("cifs: expected XML root element"); + } + const root = doc["incidents"]; + if (root === "" || root === null || root === undefined) { + return { format: "xml", incidents: [] }; + } + if (!isXmlObject(root)) { + throw new Error("cifs: invalid XML root element"); + } + const unexpectedChildren = Object.keys(root).filter( + (k) => !k.startsWith("@_") && k !== "incident", + ); + if (unexpectedChildren.length > 0) { + throw new Error( + `cifs: unexpected XML child element under : ${unexpectedChildren[0]}`, + ); + } + const rawList = root["incident"]; + if (rawList === undefined || rawList === null) { + return { format: "xml", incidents: [] }; + } + return { format: "xml", incidents: Array.isArray(rawList) ? rawList : [rawList] }; + } + + throw new Error("cifs: unrecognized payload (expected XML or JSON object)"); +} + +function closureLineIssue(coords: readonly [number, number][]): Issue | undefined { + if (coords.length < 2) { + return { + code: "invalid_value", + sourcePath: "polyline", + sourceText: "closure polyline has fewer than two vertices", + }; + } + const first = coords[0]!; + const last = coords.at(-1)!; + if (coords.length >= 3 && first[0] === last[0] && first[1] === last[1]) { + return { + code: "invalid_value", + sourcePath: "polyline", + sourceText: "circular closure polyline", + }; + } + let lengthMeters = 0; + for (let i = 1; i < coords.length; i++) { + lengthMeters += haversineMeters(coords[i - 1]!, coords[i]!); + } + if (!(lengthMeters > 0) || lengthMeters > MAX_CLOSURE_METERS) { + return { + code: "invalid_value", + sourcePath: "polyline", + sourceText: + lengthMeters > MAX_CLOSURE_METERS + ? "closure polyline exceeds 20 km" + : "closure polyline has zero length", + }; + } + return undefined; +} + +/** + * Pure CIFS v2 snapshot reader supporting both XML and JSON encodings. + * Accounts for every input incident so callers can reconcile across partitions + * and reject partial or contradictory snapshots. + */ +export function parseCifsSnapshot( + input: string | Buffer, + src: SourceDescriptor, +): RoadSnapshotReport { + const { format, incidents } = extractRawIncidents(input); + const report: RoadSnapshotReport = { inputCount: incidents.length, records: [], errors: [] }; + const now = new Date().toISOString(); + + for (const [index, rawItem] of incidents.entries()) { + const sourcePath = `incidents[${index}]`; + let node: PlainObject; + if (format === "json") { + if (!isPlainObject(rawItem)) { + report.errors.push({ code: "invalid_record", id: null, sourcePath }); + continue; + } + if (Object.hasOwn(rawItem, "incident")) { + if (Object.keys(rawItem).length !== 1 || !isPlainObject(rawItem["incident"])) { + report.errors.push({ code: "invalid_record", id: null, sourcePath }); + continue; + } + node = rawItem["incident"]; + } else { + node = rawItem; + } + } else { + if (!isXmlObject(rawItem)) { + report.errors.push({ code: "invalid_record", id: null, sourcePath }); + continue; + } + node = rawItem; + } + + const idField: FieldRead = + format === "xml" + ? (() => { + const rawAttr = node["@_id"]; + if (rawAttr === undefined || rawAttr === null) return { state: "absent" }; + if (typeof rawAttr !== "string") return { state: "malformed", raw: rawAttr }; + const t = rawAttr.trim(); + return t.length > 0 ? { state: "ok", value: t } : { state: "absent" }; + })() + : readScalarField(node, "id", format); + if (idField.state !== "ok") { + report.errors.push({ code: "invalid_identity", id: null, sourcePath }); + continue; + } + const localId = idField.value; + const id = `${src.id}:${localId}`; + + const createdField = readScalarField(node, "creationtime", format); + const updatedField = readScalarField(node, "updatetime", format); + if (createdField.state === "malformed" || updatedField.state === "malformed") { + report.errors.push({ + code: "invalid_timestamp", + id, + sourcePath: `${sourcePath}.${updatedField.state === "malformed" ? "updatetime" : "creationtime"}`, + }); + continue; + } + const created = parseTimestampField(createdField, src.timeZone); + const updated = parseTimestampField(updatedField, src.timeZone); + const sourceUpdatedAt = + (updated.state === "ok" ? updated.value : undefined) ?? + (created.state === "ok" ? created.value : undefined); + + const base = { + id, + version: null, + versionTime: sourceUpdatedAt ?? null, + fingerprint: canonicalSnapshotValue(node), + }; + + const typeField = readScalarField(node, "type", format); + const subtypeField = readScalarField(node, "subtype", format); + if (typeField.state !== "ok" || !isCifsType(typeField.value)) { + report.errors.push({ code: "unknown_type", id, sourcePath: `${sourcePath}.type` }); + continue; + } + if (subtypeField.state === "malformed") { + report.errors.push({ + code: "invalid_subtype_pair", + id, + sourcePath: `${sourcePath}.subtype`, + }); + continue; + } + const rawType = typeField.value; + const rawSubtype = subtypeField.state === "ok" ? subtypeField.value : undefined; + if (rawSubtype !== undefined && !isValidCifsPair(rawType, rawSubtype)) { + report.errors.push({ + code: "invalid_subtype_pair", + id, + sourcePath: `${sourcePath}.subtype`, + }); + continue; + } + + if (rawType === "CHIT_CHAT") { + report.records.push({ ...base, disposition: "terminal" }); + continue; + } + + const classification = cifsClassification(rawType, rawSubtype); + if (!classification) { + report.errors.push({ code: "unknown_type", id, sourcePath: `${sourcePath}.type` }); + continue; + } + + const rawLocation = node["location"]; + let legacyLocation: PlainObject | undefined; + if (Object.hasOwn(node, "location") && rawLocation !== undefined && rawLocation !== "") { + if (!isPlainObject(rawLocation)) { + report.errors.push({ + code: "invalid_location", + id, + sourcePath: `${sourcePath}.location`, + }); + continue; + } + legacyLocation = rawLocation; + } + + const streetMerged = mergeLocationField( + readScalarField(node, "street", format), + legacyLocation ? readScalarField(legacyLocation, "street", format) : { state: "absent" }, + ); + const polylineMerged = mergeLocationField( + readScalarField(node, "polyline", format), + legacyLocation ? readScalarField(legacyLocation, "polyline", format) : { state: "absent" }, + normalizeSpace, + ); + const directionMerged = mergeLocationField( + readScalarField(node, "direction", format), + legacyLocation ? readScalarField(legacyLocation, "direction", format) : { state: "absent" }, + ); + const locDescMerged = mergeLocationField( + readScalarField(node, "location_description", format), + legacyLocation + ? readScalarField(legacyLocation, "location_description", format) + : { state: "absent" }, + ); + if (!streetMerged.ok) { + report.errors.push({ + code: streetMerged.code === "conflict" ? "conflicting_location" : "invalid_location", + id, + sourcePath: `${sourcePath}.street`, + }); + continue; + } + if (!polylineMerged.ok) { + report.errors.push({ + code: polylineMerged.code === "conflict" ? "conflicting_location" : "invalid_geometry", + id, + sourcePath: `${sourcePath}.polyline`, + }); + continue; + } + if (!directionMerged.ok) { + report.errors.push({ + code: directionMerged.code === "conflict" ? "conflicting_location" : "invalid_direction", + id, + sourcePath: `${sourcePath}.direction`, + }); + continue; + } + if (!locDescMerged.ok) { + report.errors.push({ + code: locDescMerged.code === "conflict" ? "conflicting_location" : "invalid_location", + id, + sourcePath: `${sourcePath}.location_description`, + }); + continue; + } + + const rawDirection = directionMerged.value; + if ( + rawDirection !== undefined && + rawDirection !== "ONE_DIRECTION" && + rawDirection !== "BOTH_DIRECTIONS" + ) { + report.errors.push({ + code: "invalid_direction", + id, + sourcePath: `${sourcePath}.direction`, + }); + continue; + } + + const descriptionField = readScalarField(node, "description", format); + if (descriptionField.state === "malformed") { + report.errors.push({ + code: "invalid_record", + id, + sourcePath: `${sourcePath}.description`, + }); + continue; + } + const sourceParsed = parseInformationSource(node, format); + if (!sourceParsed.ok) { + report.errors.push({ + code: "invalid_source", + id, + sourcePath: `${sourcePath}.source`, + }); + continue; + } + const parentEventField = parseParentEventId(node, format); + if (parentEventField.state === "malformed") { + report.errors.push({ + code: "invalid_record", + id, + sourcePath: `${sourcePath}.parent_event`, + }); + continue; + } + + const poly = parsePolyline(polylineMerged.value); + if (poly.kind === "empty") { + recordSkipped(src.id, "no_geometry", 1); + report.records.push({ ...base, disposition: "unlocatable" }); + continue; + } + if (poly.kind === "invalid") { + report.errors.push({ + code: "invalid_geometry", + id, + sourcePath: `${sourcePath}.polyline`, + }); + continue; + } + const geometry = poly.geometry; + + let directionRef: DirectionRef; + if (rawDirection === "BOTH_DIRECTIONS") { + directionRef = { value: "both", basis: "text", text: "BOTH_DIRECTIONS" }; + } else if (geometry.type === "LineString") { + // Per Waze CIFS spec, an ordered polyline with ONE_DIRECTION or omitted + // direction affects one direction in coordinate order. + directionRef = { value: "positive", basis: "geometry" }; + } else if (rawDirection === "ONE_DIRECTION") { + // Preserve single-direction constraint on a point without widening to both ways. + directionRef = { value: "positive", basis: "unknown", text: "ONE_DIRECTION" }; + } else { + directionRef = { value: "unknown", basis: "unknown" }; + } + + const startParsed = parseTimestampField( + readScalarField(node, "starttime", format), + src.timeZone, + ); + const endParsed = parseTimestampField(readScalarField(node, "endtime", format), src.timeZone); + + let validityStatus: "unknown" | undefined; + let statusIssue: Issue | undefined; + const effectIssues: Issue[] = []; + + const recordTimingIssue = (issue: Issue) => { + validityStatus = "unknown"; + if (!statusIssue) statusIssue = issue; + else effectIssues.push(issue); + }; + + if (startParsed.state === "invalid") { + recordTimingIssue({ + code: "invalid_window", + sourcePath: "starttime", + sourceText: startParsed.raw, + }); + } + if (endParsed.state === "invalid") { + recordTimingIssue({ + code: "invalid_window", + sourcePath: "endtime", + sourceText: endParsed.raw, + }); + } + const validFrom = startParsed.state === "ok" ? startParsed.value : undefined; + let validTo = endParsed.state === "ok" ? endParsed.value : undefined; + if ( + validFrom !== undefined && + validTo !== undefined && + Date.parse(validTo) < Date.parse(validFrom) + ) { + recordTimingIssue({ + code: "invalid_window", + sourcePath: "endtime", + sourceText: `${validFrom}..${validTo}`, + }); + validTo = undefined; + } + + const isClosure = rawType === "ROAD_CLOSED"; + if (isClosure && validFrom === undefined && startParsed.state === "absent") { + // Waze requires starttime for closures; never route an unbounded closure without one. + recordTimingIssue({ + code: "invalid_window", + sourcePath: "starttime", + sourceText: "missing starttime on ROAD_CLOSED", + }); + } + + const scheduleTz = src.timeZone ?? scheduleTimezoneForGeometry(geometry); + const scheduleResult = parseSchedule(node, scheduleTz, validFrom, validTo); + let schedule: Schedule[] | undefined; + if (scheduleResult.present) { + if (scheduleResult.issue) { + recordTimingIssue(scheduleResult.issue); + } else { + schedule = scheduleResult.schedules; + } + } + + if (isClosure) { + if (geometry.type === "Point") { + // Retain single-point closures as evidence while withholding them from routing. + effectIssues.push({ + code: "invalid_value", + sourcePath: "polyline", + sourceText: "single-point closure", + }); + } else { + const lineIssue = closureLineIssue(geometry.coordinates); + if (lineIssue) effectIssues.push(lineIssue); + } + } + + const isSingleDirectionLine = + geometry.type === "LineString" && rawDirection !== "BOTH_DIRECTIONS"; + const laneData = parseLanesField(node, rawType, isSingleDirectionLine, format); + effectIssues.push(...laneData.issues); + + const description = descriptionField.state === "ok" ? descriptionField.value : undefined; + const street = streetMerged.value; + const locDesc = locDescMerged.value; + const informationSource = sourceParsed.value; + const parentEventId = parentEventField.state === "ok" ? parentEventField.value : undefined; + + const severity: RoadEvent["severity"] = + rawSubtype === "ACCIDENT_MAJOR" + ? "high" + : rawSubtype === "ACCIDENT_MINOR" + ? "low" + : "unknown"; + const severitySource: RoadEvent["severitySource"] = + rawSubtype === "ACCIDENT_MAJOR" || rawSubtype === "ACCIDENT_MINOR" ? "assessed" : "derived"; + + const comments = locDesc + ? [{ type: "public" as const, text: [{ lang: "und", text: locDesc }] }] + : undefined; + + const event: RoadEvent = { + id, + source: src.id, + sourceFormat: "cifs", + domain: "roads", + kind: "event", + ...coarseOf(classification), + subtype: rawSubtype ?? rawType, + severity, + severitySource, + status: "active", + geometry, + directionRef, + roads: street ? [{ name: street }] : [], + headline: description ?? street ?? rawSubtype ?? rawType, + ...(description !== undefined ? { description } : {}), + ...(validFrom !== undefined ? { validFrom } : {}), + ...(validTo !== undefined ? { validTo } : {}), + ...(schedule !== undefined ? { schedule } : {}), + ...(isClosure ? { roadState: "closed" as const } : {}), + ...(laneData.lanesAffected !== undefined ? { lanesAffected: laneData.lanesAffected } : {}), + situation: { + classification, + headlineFromSource: false, + ...(description !== undefined ? { description: text(description) } : {}), + ...(comments !== undefined ? { comments } : {}), + ...(sourceUpdatedAt !== undefined ? { sourceUpdatedAt } : {}), + ...(informationSource !== undefined ? { informationSource } : {}), + ...(parentEventId !== undefined + ? { externalIds: [{ scheme: "cifs:parent_event", id: parentEventId }] } + : {}), + ...(validityStatus !== undefined ? { validityStatus } : {}), + ...(statusIssue !== undefined ? { statusIssue } : {}), + ...(effectIssues.length > 0 ? { effectIssues } : {}), + }, + sourceRaw: node, + origin: { + kind: "feed", + attribution: { provider: src.attribution, license: src.license, url: src.licenseUrl }, + }, + dataUpdatedAt: sourceUpdatedAt ?? now, + fetchedAt: now, + isStale: false, + }; + + report.records.push({ ...base, disposition: "accepted", event }); + } + + return report; +} + +/** + * Convenience parser returning reconciled CIFS {@link RoadEvent} records. + * Unknown identities, malformed records, and conflicting duplicates throw. + */ +export function parseCifs(input: string | Buffer, src: SourceDescriptor): RoadEvent[] { + return reconcileRoadSnapshots([parseCifsSnapshot(input, src)]).observations as RoadEvent[]; +} diff --git a/packages/roads/src/domain.ts b/packages/roads/src/domain.ts index 71c961c85..3c625e2d8 100644 --- a/packages/roads/src/domain.ts +++ b/packages/roads/src/domain.ts @@ -44,12 +44,16 @@ export type RoadReferenceDecoder = (typeof ROAD_REFERENCE_DECODERS)[number]; const MAIN: EndpointRole = { required: true }; -function situations(id: SituationFormatCode): FeedFormat { +function situations( + id: SituationFormatCode, + extra: Partial, "reparseUnchanged" | "transactionalRoles">> = {}, +): FeedFormat { return { id, kind: "situations", products: ["events", "conditions"], endpoints: { main: MAIN }, + ...extra, parse: (feed, payloads, ctx) => parseEvents(feed, payloads["main"] ?? [], { fetchedAt: ctx.fetchedAt }), }; @@ -174,6 +178,10 @@ const FORMATS: FeedFormat[] = [ situations("ohgo-events"), situations("vic-disruptions"), situations("wa-webeoc"), + // Partial-snapshot CIFS drafts carry a retrieval TTL (freshness.expiresAt); + // HTTP 304 must replay the last accepted payload so revalidated records renew + // expiry, and transactionalRoles prevents a rejected poll from poisoning it. + situations("cifs", { reparseUnchanged: true, transactionalRoles: true }), measurements( "datex2-measured", { required: false, decoders: ["datex2-sites", "france-comptage-csv"] }, diff --git a/packages/roads/src/index.ts b/packages/roads/src/index.ts index 89ead7b7c..2432de1ff 100644 --- a/packages/roads/src/index.ts +++ b/packages/roads/src/index.ts @@ -3,6 +3,7 @@ export * from "./bind/index.js"; export * from "./cars.js"; export * from "./cars-signs.js"; export * from "./catalog/index.js"; +export * from "./cifs.js"; export * from "./datex.js"; export * from "./datex-restrictions.js"; export * from "./dedupe.js"; diff --git a/packages/roads/src/parse.ts b/packages/roads/src/parse.ts index 3f2f39fd8..3856a5cd6 100644 --- a/packages/roads/src/parse.ts +++ b/packages/roads/src/parse.ts @@ -5,6 +5,7 @@ import { } from "@openconditions/ingest-framework"; import { parseAutobahn } from "./autobahn.js"; import { parseCars, parseCarsSnapshot } from "./cars.js"; +import { parseCifs, parseCifsSnapshot } from "./cifs.js"; import { parseDatexSituations, parseDatexSnapshot } from "./datex.js"; import { parseDigitraffic, parseDigitrafficSnapshot } from "./digitraffic.js"; import type { RoadFeed } from "./feed-schema.js"; @@ -59,6 +60,7 @@ const SITUATION_PARSERS = { "ohgo-events": parseOhgoEvents as SituationParser, "vic-disruptions": parseVicDisruptions as SituationParser, "wa-webeoc": parseWaWebeoc, + cifs: parseCifs, } satisfies Record; /** Every situation format; the wire formats `SITUATION_PARSERS` reads. */ @@ -88,8 +90,16 @@ const SNAPSHOT_REPORTERS: Record< datex2: parseDatexSnapshot, cars: parseCarsSnapshot, "wa-webeoc": parseWaWebeocSnapshot, + cifs: parseCifsSnapshot, }; +/** + * Formats that always reconcile through {@link SNAPSHOT_REPORTERS} and default + * to `situationsComplete: false` with bounded freshness until a catalogue source + * explicitly qualifies `snapshot: { completeness: "complete" }`. + */ +const ACCOUNTED_PARTIAL_FORMATS = new Set(["wa-webeoc", "cifs"]); + /** * One poll of a roads event feed as situation drafts. Every payload of the * poll is one snapshot: the assembler folds records across all of them. A @@ -108,16 +118,18 @@ export function parseEvents( opts.fetchedAt !== undefined ? new Date(opts.fetchedAt) : undefined, ); const at = opts.fetchedAt !== undefined ? { fetchedAt: opts.fetchedAt } : {}; + const accountedPartial = ACCOUNTED_PARTIAL_FORMATS.has(feed.format); const reporter = - (feed.snapshot?.completeness === "complete" || feed.format === "wa-webeoc") && + (feed.snapshot?.completeness === "complete" || accountedPartial) && Object.hasOwn(SNAPSHOT_REPORTERS, feed.format) ? SNAPSHOT_REPORTERS[feed.format] : undefined; const out = emptyParseOutput(); - // Received-row accounting cannot qualify disappearance. WA must retain - // absent predecessors until the source's refresh/identity/withdrawal gate - // is deliberately qualified by a complete-snapshot declaration. - if (feed.format === "wa-webeoc") { + // Received-row accounting alone cannot qualify disappearance. Formats in + // ACCOUNTED_PARTIAL_FORMATS retain absent predecessors until the source's + // refresh/identity/withdrawal gate is deliberately qualified by a + // complete-snapshot declaration. + if (accountedPartial) { out.situationsComplete = feed.snapshot?.completeness === "complete"; } if (reporter === undefined) { @@ -144,7 +156,7 @@ export function parseEvents( members, ...at, }); - if (feed.format === "wa-webeoc") { + if (accountedPartial && (feed.format === "wa-webeoc" || out.situationsComplete !== true)) { // Partial-source retention must not keep a vanished incident public forever. // This is an operator retrieval TTL, not an inferred publisher timestamp. for (const draft of out.situations) { diff --git a/packages/roads/src/situation/assemble.ts b/packages/roads/src/situation/assemble.ts index 0f0ea9111..3615c5dd3 100644 --- a/packages/roads/src/situation/assemble.ts +++ b/packages/roads/src/situation/assemble.ts @@ -81,6 +81,7 @@ const EXTERNAL_ID_SCHEME: Record = { "datex2-measured": "datex:record", wzdx: "wzdx:road_event", open511: "open511", + cifs: "cifs:incident", }; /** diff --git a/services/ingest/README.md b/services/ingest/README.md index 8b0d571b9..7b8a4ced2 100644 --- a/services/ingest/README.md +++ b/services/ingest/README.md @@ -20,7 +20,7 @@ a breaking change gets a new path, and the old one keeps its contract (see [the public API](../../README.md#public-api)): - situations: `/situations` (JSON, `.geojson`, `.jsonld`), `/situations/{id}`, - `/traff.xml`, `/datex2/situations.xml`, and the `/stream` of server-sent events; + `/traff.xml`, `/cifs.xml`, `/cifs.json`, `/datex2/situations.xml`, and the `/stream` of server-sent events; - features: `/features` (JSON, `.geojson`, `.jsonld`; `canonical=1` for the canonical view, `expand=components` for components) and `/features/{id}`; - offers: `/offers` and `/offers/{id}`; @@ -47,7 +47,7 @@ bearer one included, reads in the public scope, and the service logs response is `Cache-Control: private, no-store`. The speed surface (`/segments.geojson`, `/segments/speed.csv`) withholds, in the public scope, a speed any restricted source contributed to. The emitters -(`/situations.geojson`, `/situations.jsonld`, `/traff.xml`, +(`/situations.geojson`, `/situations.jsonld`, `/traff.xml`, `/cifs.xml`, `/cifs.json`, `/datex2/situations.xml`, `/stream`, `/features.geojson`, `/features.jsonld`) are public feeds and always read in the public scope. A crowd reporter's key is stripped in every scope. What each route reads is in diff --git a/services/ingest/openapi.json b/services/ingest/openapi.json index e0a33c1dd..a5f4353c5 100644 --- a/services/ingest/openapi.json +++ b/services/ingest/openapi.json @@ -856,6 +856,328 @@ } } }, + "/cifs.xml": { + "get": { + "operationId": "listSituationsCifsXml", + "summary": "A complete public point-in-time CIFS v2 XML feed (`cifsv2.xsd`) from one database snapshot, not paged. No cursor, limit, simplify or historical from/to parameters. At most 20,000 candidate situations and 32 MiB of UTF-8 XML; narrow bbox, source or time filters on 413. Road closures require a complete, mandatory, confirmed, road-wide closure effect, explicit validity.start and a non-circular line up to 20 km; single-point alerts require explicit bilateral direction.", + "parameters": [ + { + "name": "bbox", + "in": "query", + "required": false, + "schema": { + "type": "string", + "description": "west,south,east,north in WGS84 degrees" + }, + "description": "west,south,east,north in WGS84 degrees" + }, + { + "name": "kind", + "in": "query", + "required": false, + "schema": { + "description": "comma-separated kind codes", + "type": "string" + }, + "description": "comma-separated kind codes" + }, + { + "name": "excludeKind", + "in": "query", + "required": false, + "schema": { + "description": "comma-separated kind codes left out", + "type": "string" + }, + "description": "comma-separated kind codes left out" + }, + { + "name": "type", + "in": "query", + "required": false, + "schema": { + "description": "comma-separated type codes", + "type": "string" + }, + "description": "comma-separated type codes" + }, + { + "name": "domain", + "in": "query", + "required": false, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "source", + "in": "query", + "required": false, + "schema": { + "description": "comma-separated source ids", + "type": "string" + }, + "description": "comma-separated source ids" + }, + { + "name": "origin", + "in": "query", + "required": false, + "schema": { + "description": "comma-separated origins: feed, crowd, federation, derived", + "type": "string" + }, + "description": "comma-separated origins: feed, crowd, federation, derived" + }, + { + "name": "minSeverity", + "in": "query", + "required": false, + "schema": { + "type": "string", + "enum": ["minor", "moderate", "major", "critical"] + } + }, + { + "name": "at", + "in": "query", + "required": false, + "schema": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$", + "description": "the instant situations are current at" + }, + "description": "the instant situations are current at" + }, + { + "name": "horizonDays", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 0, + "maximum": 366, + "description": "only situations starting within this many days after `at`" + }, + "description": "only situations starting within this many days after `at`" + }, + { + "name": "dedupe", + "in": "query", + "required": false, + "schema": { + "type": "string", + "enum": ["0", "1"], + "description": "1 conservatively folds compatible reports across the complete feed; unknown or incomplete reports remain separate" + }, + "description": "1 conservatively folds compatible reports across the complete feed; unknown or incomplete reports remain separate" + }, + { + "name": "subtype", + "in": "query", + "required": false, + "schema": { + "description": "comma-separated subtype codes", + "type": "string" + }, + "description": "comma-separated subtype codes" + } + ], + "security": [{}], + "responses": { + "200": { + "description": "OK", + "content": { + "application/xml": {} + } + }, + "400": { + "description": "Invalid request" + }, + "401": { + "description": "A bearer token other than the configured operator token (with none configured, a bearer token reads in public scope)", + "content": { + "application/json": {} + } + }, + "413": { + "description": "More than 20,000 candidate situations or 32 MiB of XML; narrow bbox, source or time filters", + "content": { + "application/json": {} + } + }, + "429": { + "description": "The client's rate limit is spent; `Retry-After` says when to retry", + "content": { + "application/json": {} + } + } + } + } + }, + "/cifs.json": { + "get": { + "operationId": "listSituationsCifsJson", + "summary": "A complete public point-in-time CIFS v2 JSON feed from one database snapshot, not paged, sharing the exact projection of `/cifs.xml`. No cursor, limit, simplify or historical from/to parameters. At most 20,000 candidate situations and 32 MiB of UTF-8 JSON; narrow bbox, source or time filters on 413.", + "parameters": [ + { + "name": "bbox", + "in": "query", + "required": false, + "schema": { + "type": "string", + "description": "west,south,east,north in WGS84 degrees" + }, + "description": "west,south,east,north in WGS84 degrees" + }, + { + "name": "kind", + "in": "query", + "required": false, + "schema": { + "description": "comma-separated kind codes", + "type": "string" + }, + "description": "comma-separated kind codes" + }, + { + "name": "excludeKind", + "in": "query", + "required": false, + "schema": { + "description": "comma-separated kind codes left out", + "type": "string" + }, + "description": "comma-separated kind codes left out" + }, + { + "name": "type", + "in": "query", + "required": false, + "schema": { + "description": "comma-separated type codes", + "type": "string" + }, + "description": "comma-separated type codes" + }, + { + "name": "domain", + "in": "query", + "required": false, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "source", + "in": "query", + "required": false, + "schema": { + "description": "comma-separated source ids", + "type": "string" + }, + "description": "comma-separated source ids" + }, + { + "name": "origin", + "in": "query", + "required": false, + "schema": { + "description": "comma-separated origins: feed, crowd, federation, derived", + "type": "string" + }, + "description": "comma-separated origins: feed, crowd, federation, derived" + }, + { + "name": "minSeverity", + "in": "query", + "required": false, + "schema": { + "type": "string", + "enum": ["minor", "moderate", "major", "critical"] + } + }, + { + "name": "at", + "in": "query", + "required": false, + "schema": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$", + "description": "the instant situations are current at" + }, + "description": "the instant situations are current at" + }, + { + "name": "horizonDays", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 0, + "maximum": 366, + "description": "only situations starting within this many days after `at`" + }, + "description": "only situations starting within this many days after `at`" + }, + { + "name": "dedupe", + "in": "query", + "required": false, + "schema": { + "type": "string", + "enum": ["0", "1"], + "description": "1 conservatively folds compatible reports across the complete feed; unknown or incomplete reports remain separate" + }, + "description": "1 conservatively folds compatible reports across the complete feed; unknown or incomplete reports remain separate" + }, + { + "name": "subtype", + "in": "query", + "required": false, + "schema": { + "description": "comma-separated subtype codes", + "type": "string" + }, + "description": "comma-separated subtype codes" + } + ], + "security": [{}], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": {} + } + }, + "400": { + "description": "Invalid request" + }, + "401": { + "description": "A bearer token other than the configured operator token (with none configured, a bearer token reads in public scope)", + "content": { + "application/json": {} + } + }, + "413": { + "description": "More than 20,000 candidate situations or 32 MiB of JSON; narrow bbox, source or time filters", + "content": { + "application/json": {} + } + }, + "429": { + "description": "The client's rate limit is spent; `Retry-After` says when to retry", + "content": { + "application/json": {} + } + } + } + } + }, "/datex2/situations.xml": { "get": { "operationId": "listSituationsDatex", diff --git a/services/ingest/src/__tests__/api-openapi.test.ts b/services/ingest/src/__tests__/api-openapi.test.ts index 56d936915..d8cfd2601 100644 --- a/services/ingest/src/__tests__/api-openapi.test.ts +++ b/services/ingest/src/__tests__/api-openapi.test.ts @@ -237,6 +237,8 @@ describe("the OpenAPI document", () => { "/situations.geojson", "/situations.jsonld", "/traff.xml", + "/cifs.xml", + "/cifs.json", "/datex2/situations.xml", "/stream", "/features.geojson", @@ -293,3 +295,27 @@ describe("complete TraFF API contract", () => { expect(op.responses["413"]).toBeDefined(); }); }); + +describe("complete CIFS API contract", () => { + it.each(["/cifs.xml", "/cifs.json"])( + "%s offers point-in-time filters without page controls, simplify or from/to and documents 413", + (path) => { + const op = ( + openApiDocument().paths[path] as { + get: { + parameters: { name: string }[]; + responses: Record; + }; + } + ).get; + expect(op.parameters.map((p) => p.name)).toContain("bbox"); + expect(op.parameters.map((p) => p.name)).toContain("at"); + expect(op.parameters.map((p) => p.name)).not.toContain("cursor"); + expect(op.parameters.map((p) => p.name)).not.toContain("limit"); + expect(op.parameters.map((p) => p.name)).not.toContain("simplify"); + expect(op.parameters.map((p) => p.name)).not.toContain("from"); + expect(op.parameters.map((p) => p.name)).not.toContain("to"); + expect(op.responses["413"]).toBeDefined(); + }, + ); +}); diff --git a/services/ingest/src/__tests__/cifs-feed.integration.test.ts b/services/ingest/src/__tests__/cifs-feed.integration.test.ts new file mode 100644 index 000000000..7cdf35abe --- /dev/null +++ b/services/ingest/src/__tests__/cifs-feed.integration.test.ts @@ -0,0 +1,381 @@ +import { + type CatalogFeed, + createFetchState, + type FeedDefinition, + type LookupFn, + toCatalogFeed, +} from "@openconditions/ingest-framework"; +import { syncSources } from "@openconditions/storage"; +import { createTestDatabase, type TestDatabase } from "@openconditions/test-database"; +import Fastify from "fastify"; +import type postgres from "postgres"; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { registerApiRoutes } from "../api/routes.js"; +import { registerScope } from "../api/scope.js"; +import { createRoleState, runSource } from "../pipeline/run.js"; +import { registry, situationDraft, writeSituations } from "./helpers/situations.js"; + +let db: TestDatabase; +let sql: postgres.Sql; +let app: ReturnType; +const AT = "at=2026-09-06T10:00:00Z"; +const TOKEN = "cifs-operator-token-01234567890123456789"; + +const LINE_LOCATION = { + geometry: { + type: "LineString", + coordinates: [ + [9.18, 48.78], + [9.19, 48.79], + ], + }, + extent: "linear", + geometryOrigin: "source", + fuzziness: "exact", + roads: [{ name: [{ lang: "de", text: "B10 Stuttgart" }] }], + direction: { value: "positive", basis: "geometry" }, +}; + +beforeAll(async () => { + db = await createTestDatabase(); + sql = db.sql; + app = Fastify(); + registerScope(app, TOKEN); + registerApiRoutes(app, sql, { registry }); + await app.ready(); +}); +afterAll(async () => { + await app?.close(); + await db?.close(); +}); +beforeEach(async () => { + await sql`TRUNCATE conditions.situation CASCADE`; +}); + +async function seed(count: number) { + await writeSituations(sql, "de-autobahn-events", [ + situationDraft("seed", { location: LINE_LOCATION }), + ]); + await sql` + WITH copies AS MATERIALIZED ( + SELECT jsonb_populate_record(NULL::conditions.situation, to_jsonb(s) || + jsonb_build_object('id', n.id, 'canonical_id', n.id, 'source_record_id', n.local, + 'record', jsonb_set(jsonb_set(s.record, '{id}', to_jsonb(n.id)), + '{provenance,recordId}', to_jsonb(n.local)))) AS row + FROM conditions.situation s + CROSS JOIN (SELECT 'item-' || lpad(i::text, 5, '0') AS local, + 'oc:situation:de-autobahn-events:item-' || lpad(i::text, 5, '0') AS id + FROM generate_series(1, ${count}) i) n + WHERE s.id = 'oc:situation:de-autobahn-events:seed') + INSERT INTO conditions.situation SELECT (row).* FROM copies`; + await sql`DELETE FROM conditions.situation WHERE source_record_id = 'seed'`; +} + +const xmlIncidentIds = (body: string) => + [...body.matchAll(/ m[1]); + +describe("complete public CIFS feeds", () => { + it("reads beyond a full internal page in both XML and JSON without pagination links", async () => { + await seed(5001); + const xmlRes = await app.inject(`/cifs.xml?${AT}`); + expect(xmlRes.statusCode).toBe(200); + expect(xmlRes.headers["content-type"]).toContain("application/xml"); + const xmlIds = xmlIncidentIds(xmlRes.body); + expect(xmlIds).toHaveLength(5001); + expect(xmlIds.at(0)).toBe("oc:situation:de-autobahn-events:item-00001"); + expect(xmlIds.at(-1)).toBe("oc:situation:de-autobahn-events:item-05001"); + expect(xmlRes.headers["link"]).toBeUndefined(); + + const jsonRes = await app.inject(`/cifs.json?${AT}`); + expect(jsonRes.statusCode).toBe(200); + expect(jsonRes.headers["content-type"]).toContain("application/json"); + const body = jsonRes.json() as { incidents: { id: string }[] }; + expect(body.incidents.map((i) => i.id)).toEqual(xmlIds); + }); + + it("refuses oversized selections (>20,000 candidates) with 413 JSON and Cache-Control: no-store", async () => { + await seed(20001); + for (const path of ["/cifs.xml", "/cifs.json"]) { + const res = await app.inject(`${path}?${AT}`); + expect(res.statusCode).toBe(413); + expect(res.headers["cache-control"]).toBe("no-store"); + expect(res.headers["content-type"]).toContain("application/json"); + expect(res.json()).toMatchObject({ error: expect.stringMatching(/narrow/i) }); + } + }); + + it("bounds UTF-8 bytes on both /cifs.xml and /cifs.json", async () => { + await seed(1); + await sql`UPDATE conditions.situation SET record = jsonb_set(record, '{location,roads}', + jsonb_build_array(jsonb_build_object('ref', repeat('é', 17 * 1024 * 1024))))`; + for (const path of ["/cifs.xml", "/cifs.json"]) { + const res = await app.inject(`${path}?${AT}`); + expect(res.statusCode).toBe(413); + expect(res.headers["cache-control"]).toBe("no-store"); + } + }); + + it.each([ + "limit=1", + "cursor=oc%3Asituation%3Ax%3Ay", + "simplify=0.01", + "from=2026-09-01T00:00:00Z", + "to=2026-09-06T00:00:00Z", + ])("rejects unsupported query controls (%s) on /cifs.xml and /cifs.json", async (query) => { + for (const path of ["/cifs.xml", "/cifs.json"]) { + const res = await app.inject(`${path}?${AT}&${query}`); + expect(res.statusCode).toBe(400); + } + }); + + it("keeps public licence and source restrictions even with the operator token", async () => { + const source = "de-autobahn-events"; + const saDraft = situationDraft("sa", { location: LINE_LOCATION }); + await writeSituations(sql, source, [ + situationDraft("open", { location: LINE_LOCATION }), + { + ...saDraft, + provenance: { + ...(saDraft["provenance"] as Record), + attribution: { provider: "SA", license: "CC-BY-SA-4.0" }, + }, + }, + ]); + await writeSituations(sql, "cifs-restricted", [ + situationDraft("secret", { location: LINE_LOCATION }, "cifs-restricted"), + ]); + await syncSources(sql, [ + { + id: "cifs-restricted", + domain: "roads", + format: "autobahn", + product: "events", + tier: "authoritative", + country: "DE", + operator: "test", + license: "CC0-1.0", + attribution: "test", + restricted: true, + cadenceSec: 60, + freshnessWindowSec: 3600, + }, + ]); + for (const headers of [{}, { authorization: `Bearer ${TOKEN}` }]) { + const xmlRes = await app.inject({ url: `/cifs.xml?${AT}`, headers }); + expect(xmlRes.statusCode).toBe(200); + expect(xmlIncidentIds(xmlRes.body)).toEqual(["oc:situation:de-autobahn-events:open"]); + expect(xmlRes.headers["x-data-license"]).toBe("DL-DE-BY-2.0"); + + const jsonRes = await app.inject({ url: `/cifs.json?${AT}`, headers }); + expect(jsonRes.statusCode).toBe(200); + expect( + (jsonRes.json() as { incidents: { id: string }[] }).incidents.map((i) => i.id), + ).toEqual(["oc:situation:de-autobahn-events:open"]); + expect(jsonRes.headers["x-data-license"]).toBe("DL-DE-BY-2.0"); + } + }); +}); + +describe("CIFS pipeline acquisition, TTL renewal, and withdrawal authority", () => { + const fakeLookup: LookupFn = async () => [{ address: "93.184.216.34", family: 4 }]; + const CIFS_BODY = JSON.stringify({ + timestamp: "2026-09-06T09:55:00Z", + incidents: [ + { + id: "closure-1", + type: "ROAD_CLOSED", + subtype: "ROAD_CLOSED_CONSTRUCTION", + description: "Bridge work", + street: "B10 Stuttgart", + polyline: "48.780000 9.180000 48.790000 9.190000", + direction: "ONE_DIRECTION", + starttime: "2026-09-06T08:00:00Z", + endtime: "2026-09-07T08:00:00Z", + }, + ], + }); + + function cifsFeed(id: string, over: Partial = {}): CatalogFeed { + const def: FeedDefinition = { + operator: "test", + qualifier: id, + product: "events", + name: "Test CIFS", + format: "cifs", + tier: "authoritative", + license: "CC0-1.0", + attribution: "Test CIFS", + privacyUrl: "https://example.test/privacy", + endpoints: { main: { url: `https://cifs.example.test/${id}.json`, cadenceSec: 60 } }, + freshnessWindowSec: 300, + }; + return { + ...toCatalogFeed(def, { + domain: "roads", + region: "de", + file: "feeds/roads/de.jsonc", + maintainers: [], + }), + id, + ...over, + }; + } + + it("renews retrieval TTL across HTTP 304s, fails closed on errors/malformed polls, and enforces withdrawal authority", async () => { + const feed = cifsFeed("de-test-cifs-partial"); + const roles = createRoleState(); + const fetchState = createFetchState(); + let mode: "ok" | "not_modified" | "server_error" | "malformed" | "string_status_503" | "empty" = + "ok"; + let lastIfNoneMatch: string | null = null; + + const fakeFetch = async ( + _input: string | URL | Request, + init?: RequestInit, + ): Promise => { + lastIfNoneMatch = new Headers(init?.headers).get("if-none-match"); + if (mode === "ok") { + return new Response(CIFS_BODY, { status: 200, headers: { ETag: '"v1"' } }); + } + if (mode === "not_modified") { + return new Response(null, { status: 304, headers: { ETag: '"v1"' } }); + } + if (mode === "server_error") { + return new Response("upstream down", { status: 500 }); + } + if (mode === "malformed") { + return new Response( + JSON.stringify({ + incidents: [ + JSON.parse(CIFS_BODY).incidents[0], + { + id: "bad", + type: "NO_SUCH_TYPE", + description: "bad", + street: "B10", + polyline: "48.78 9.18 48.79 9.19", + }, + ], + }), + { status: 200 }, + ); + } + if (mode === "string_status_503") { + return new Response(JSON.stringify({ status: "503", incidents: [] }), { status: 200 }); + } + return new Response(JSON.stringify({ incidents: [] }), { status: 200 }); + }; + + const pollAt = async (iso: string) => + runSource(feed, { + sql, + fetch: fakeFetch as typeof fetch, + fetchState, + lookup: fakeLookup, + roles, + now: () => iso, + }); + + // 1. Initial 200 lands closure with expiresAt = T0 + 300s (10:05:00Z) + const r1 = await pollAt("2026-09-06T10:00:00Z"); + expect(r1.error).toBeUndefined(); + expect(r1.count).toBe(1); + const [row1] = await sql<{ expires_at: Date; tombstoned_at: Date | null }[]>` + SELECT expires_at, tombstoned_at FROM conditions.situation WHERE source_id = ${feed.id}`; + expect(row1?.expires_at.toISOString()).toBe("2026-09-06T10:05:00.000Z"); + + // 2. Repeated 304s crossing the original TTL (10:03 then 10:06) advance expiresAt so the closure stays visible + mode = "not_modified"; + await pollAt("2026-09-06T10:03:00Z"); + expect(lastIfNoneMatch).toBe('"v1"'); + await pollAt("2026-09-06T10:06:00Z"); + const [row2] = await sql<{ expires_at: Date; tombstoned_at: Date | null }[]>` + SELECT expires_at, tombstoned_at FROM conditions.situation WHERE source_id = ${feed.id}`; + expect(row2?.expires_at.toISOString()).toBe("2026-09-06T10:11:00.000Z"); + expect(row2?.tombstoned_at).toBeNull(); + + const servedAfter304 = await app.inject( + "/cifs.json?at=2026-09-06T10:06:00Z&source=de-test-cifs-partial", + ); + expect(servedAfter304.statusCode).toBe(200); + expect((servedAfter304.json() as { incidents: { id: string }[] }).incidents).toHaveLength(1); + + // 3. Failed 500 poll does NOT withdraw or extend expiresAt + mode = "server_error"; + const rFail = await pollAt("2026-09-06T10:08:00Z"); + expect(rFail.outcome).toBe("failed"); + const [rowAfterFail] = await sql<{ expires_at: Date; tombstoned_at: Date | null }[]>` + SELECT expires_at, tombstoned_at FROM conditions.situation WHERE source_id = ${feed.id}`; + expect(rowAfterFail?.expires_at.toISOString()).toBe("2026-09-06T10:11:00.000Z"); + expect(rowAfterFail?.tombstoned_at).toBeNull(); + + // 4. Malformed mixed poll fails closed and must NOT poison the held payload for later 304s + mode = "malformed"; + const rBad = await pollAt("2026-09-06T10:09:00Z"); + expect(rBad.error).toBeDefined(); + const [rowAfterBad] = await sql<{ expires_at: Date; tombstoned_at: Date | null }[]>` + SELECT expires_at, tombstoned_at FROM conditions.situation WHERE source_id = ${feed.id}`; + expect(rowAfterBad?.expires_at.toISOString()).toBe("2026-09-06T10:11:00.000Z"); + expect(rowAfterBad?.tombstoned_at).toBeNull(); + + // 4b. Subsequent 304 for If-None-Match: "v1" replays the last accepted "v1" body and renews TTL + mode = "not_modified"; + const rRecover = await pollAt("2026-09-06T10:09:30Z"); + expect(lastIfNoneMatch).toBe('"v1"'); + expect(rRecover.error).toBeUndefined(); + const [rowAfterRecover] = await sql<{ expires_at: Date; tombstoned_at: Date | null }[]>` + SELECT expires_at, tombstoned_at FROM conditions.situation WHERE source_id = ${feed.id}`; + expect(rowAfterRecover?.expires_at.toISOString()).toBe("2026-09-06T10:14:30.000Z"); + expect(rowAfterRecover?.tombstoned_at).toBeNull(); + + // 5. Empty 200 poll on default partial CIFS does NOT withdraw existing closure + mode = "empty"; + await pollAt("2026-09-06T10:10:00Z"); + const [rowAfterPartialEmpty] = await sql<{ tombstoned_at: Date | null }[]>` + SELECT tombstoned_at FROM conditions.situation WHERE source_id = ${feed.id}`; + expect(rowAfterPartialEmpty?.tombstoned_at).toBeNull(); + + // 6. Qualified complete CIFS feed refuses HTTP 200 failure envelopes (including string "503") + // and only withdraws on a recognized empty 200 snapshot + const completeFeed = cifsFeed("de-test-cifs-complete", { + snapshot: { completeness: "complete" }, + }); + const completeRoles = createRoleState(); + const completeFetchState = createFetchState(); + mode = "ok"; + await runSource(completeFeed, { + sql, + fetch: fakeFetch as typeof fetch, + fetchState: completeFetchState, + lookup: fakeLookup, + roles: completeRoles, + now: () => "2026-09-06T10:00:00Z", + }); + mode = "string_status_503"; + const rStatus503 = await runSource(completeFeed, { + sql, + fetch: fakeFetch as typeof fetch, + fetchState: completeFetchState, + lookup: fakeLookup, + roles: completeRoles, + now: () => "2026-09-06T10:01:00Z", + }); + expect(rStatus503.error).toBeDefined(); + const [rowAfter503Envelope] = await sql<{ tombstoned_at: Date | null }[]>` + SELECT tombstoned_at FROM conditions.situation WHERE source_id = ${completeFeed.id}`; + expect(rowAfter503Envelope?.tombstoned_at).toBeNull(); + + mode = "empty"; + await runSource(completeFeed, { + sql, + fetch: fakeFetch as typeof fetch, + fetchState: completeFetchState, + lookup: fakeLookup, + roles: completeRoles, + now: () => "2026-09-06T10:02:00Z", + }); + const [rowAfterCompleteEmpty] = await sql<{ tombstoned_at: Date | null }[]>` + SELECT tombstoned_at FROM conditions.situation WHERE source_id = ${completeFeed.id}`; + expect(rowAfterCompleteEmpty?.tombstoned_at).not.toBeNull(); + }); +}); diff --git a/services/ingest/src/__tests__/feed-inspect.test.ts b/services/ingest/src/__tests__/feed-inspect.test.ts index 104b48df8..577eceec3 100644 --- a/services/ingest/src/__tests__/feed-inspect.test.ts +++ b/services/ingest/src/__tests__/feed-inspect.test.ts @@ -23,8 +23,10 @@ describe("offline feed inspection", () => { }); expect(report.exports.geojson.features).toHaveLength(3); expect(report.exports.traff).toContain(" { @@ -37,6 +39,7 @@ describe("offline feed inspection", () => { ); expect(report.exports.geojson.features).toHaveLength(0); expect(report.exports.traff).not.toContain(" { expect(report.counts).toMatchObject({ parsed: 1, valid: 1, publicEligible: 1 }); expect(report.records[0]!.projection).toMatchObject({ traff: { messages: 0, reason: "vehicle_specific_effect" }, + cifs: { incidents: 0, reason: "vehicle_specific_effect" }, datex: { records: 0, reason: "vehicle_specific_effect" }, }); expect(report.exports.geojson.features[0]!.geometry).not.toBeNull(); @@ -155,7 +159,7 @@ it("exposes publisher loss paths alongside actual outputs, including successful ], at, ); - for (const format of ["traff", "datex"] as const) { + for (const format of ["traff", "cifs", "datex"] as const) { expect(weights.records[0]!.projection[format].diagnostics).toEqual( expect.arrayContaining([ expect.objectContaining({ @@ -174,6 +178,7 @@ it("does not run XML diagnostics on records blocked before projection", () => { const report = inspectFeed({ ...feed, restricted: true }, [payload], at); for (const record of report.records) { expect(record.projection.traff).toMatchObject({ reason: "restricted_source", diagnostics: [] }); + expect(record.projection.cifs).toMatchObject({ reason: "restricted_source", diagnostics: [] }); expect(record.projection.datex).toMatchObject({ reason: "restricted_source", diagnostics: [] }); } }); diff --git a/services/ingest/src/__tests__/skip-reasons/roads-events.ts b/services/ingest/src/__tests__/skip-reasons/roads-events.ts index baf9ee94e..5461ec6ba 100644 --- a/services/ingest/src/__tests__/skip-reasons/roads-events.ts +++ b/services/ingest/src/__tests__/skip-reasons/roads-events.ts @@ -13,6 +13,14 @@ export const SAMPLES: SkipSamples = { }), }, }, + "roads/cifs": { + reason: "no_geometry", + payloads: { + main: JSON.stringify({ + incidents: [{ id: "no-geo", type: "ACCIDENT", description: "x", street: "Main St" }], + }), + }, + }, "roads/open511": { reason: "unknown_value", payloads: { diff --git a/services/ingest/src/api/openapi.ts b/services/ingest/src/api/openapi.ts index 33e47a1eb..f5b50618c 100644 --- a/services/ingest/src/api/openapi.ts +++ b/services/ingest/src/api/openapi.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import { AtQuery, + CifsQuery, FeatureListQuery, FeatureQuery, GridQuery, @@ -77,6 +78,28 @@ export const API_ROUTES: readonly ApiRoute[] = [ produces: ["application/xml"], alwaysPublic: true, }, + { + path: "/cifs.xml", + operationId: "listSituationsCifsXml", + summary: + "A complete public point-in-time CIFS v2 XML feed (`cifsv2.xsd`) from one database snapshot, not paged. No cursor, limit, simplify or historical from/to parameters. At most 20,000 candidate situations and 32 MiB of UTF-8 XML; narrow bbox, source or time filters on 413. Road closures require a complete, mandatory, confirmed, road-wide closure effect, explicit validity.start and a non-circular line up to 20 km; single-point alerts require explicit bilateral direction.", + query: CifsQuery, + tooLarge: + "More than 20,000 candidate situations or 32 MiB of XML; narrow bbox, source or time filters", + produces: ["application/xml"], + alwaysPublic: true, + }, + { + path: "/cifs.json", + operationId: "listSituationsCifsJson", + summary: + "A complete public point-in-time CIFS v2 JSON feed from one database snapshot, not paged, sharing the exact projection of `/cifs.xml`. No cursor, limit, simplify or historical from/to parameters. At most 20,000 candidate situations and 32 MiB of UTF-8 JSON; narrow bbox, source or time filters on 413.", + query: CifsQuery, + tooLarge: + "More than 20,000 candidate situations or 32 MiB of JSON; narrow bbox, source or time filters", + produces: ["application/json"], + alwaysPublic: true, + }, { path: "/datex2/situations.xml", operationId: "listSituationsDatex", diff --git a/services/ingest/src/api/query.ts b/services/ingest/src/api/query.ts index 69675eadd..915024546 100644 --- a/services/ingest/src/api/query.ts +++ b/services/ingest/src/api/query.ts @@ -150,6 +150,22 @@ export const TraffQuery = SituationListBase.omit({ cursor: true, limit: true }) }) .superRefine(checkSituationWindow); +/** A complete CIFS feed is point-in-time (`at`), without page controls, `simplify`, or historical `from`/`to` windows. */ +export const CifsQuery = SituationListBase.omit({ + cursor: true, + limit: true, + simplify: true, + from: true, + to: true, +}).extend({ + dedupe: z + .enum(["0", "1"]) + .describe( + "1 conservatively folds compatible reports across the complete feed; unknown or incomplete reports remain separate", + ) + .optional(), +}); + /** What is wrong with a situation read's time window, if anything. */ export function windowIssue(from: Date, to: Date): string | undefined { if (from > to) return "from must not be after to"; diff --git a/services/ingest/src/api/routes.ts b/services/ingest/src/api/routes.ts index edbc23552..7ddd99fd6 100644 --- a/services/ingest/src/api/routes.ts +++ b/services/ingest/src/api/routes.ts @@ -41,6 +41,8 @@ import { featuresToGeoJSON, featuresToJsonLd, nextEffectTransition, + situationsToCifsJson, + situationsToCifsXml, situationsToDatex, situationsToGeoJSON, situationsToJsonLd, @@ -59,6 +61,7 @@ import type { InFlight } from "../shutdown.js"; import { openApiDocument } from "./openapi.js"; import { AtQuery, + CifsQuery, FeatureListQuery, FeatureQuery, GridQuery, @@ -75,7 +78,14 @@ import { import { scopeOf } from "./scope.js"; import { crowdSourceOf, sourcesOf } from "./sources.js"; import { taxonomyOf } from "./taxonomy.js"; -import { MAX_TRAFF_BYTES, readTraffSnapshot, TraffFeedTooLargeError } from "./traff.js"; +import { + CifsFeedTooLargeError, + MAX_CIFS_BYTES, + MAX_TRAFF_BYTES, + readCifsSnapshot, + readTraffSnapshot, + TraffFeedTooLargeError, +} from "./traff.js"; type Rec = Record; @@ -550,6 +560,42 @@ export function registerApiRoutes( } }); + async function serveCifs(req: FastifyRequest, reply: FastifyReply, wire: "xml" | "json") { + const q = parse(CifsQuery, req.query, reply); + if (!q) return reply; + const at = q.at ? new Date(q.at) : now(); + try { + const read = await readCifsSnapshot(sql, { + at, + ...filtersOf(q), + ...(q.subtype ? { subtypes: q.subtype } : {}), + ...(q.horizonDays !== undefined ? { horizonDays: q.horizonDays } : {}), + }); + const shown = egress(read, "public"); + const records = q.dedupe === "1" ? dedupeSituations(shown) : shown; + const info = { timestamp: at.toISOString() }; + const body = + wire === "xml" + ? situationsToCifsXml(records, at, info) + : JSON.stringify(situationsToCifsJson(records, at, info)); + if (Buffer.byteLength(body, "utf8") > MAX_CIFS_BYTES) throw new CifsFeedTooLargeError(); + cacheFor(reply, records, at); + reply.header( + "Content-Type", + wire === "xml" ? "application/xml; charset=utf-8" : "application/json; charset=utf-8", + ); + reply.header("X-Data-License", licensesOf(records)); + return reply.send(body); + } catch (error) { + if (!(error instanceof CifsFeedTooLargeError)) throw error; + reply.header("Cache-Control", "no-store"); + return reply.status(413).send({ error: error.message }); + } + } + + app.get("/cifs.xml", (req, reply) => serveCifs(req, reply, "xml")); + app.get("/cifs.json", (req, reply) => serveCifs(req, reply, "json")); + app.get("/datex2/situations.xml", async (req, reply) => { const q = parseSituations(req, reply); if (!q) return reply; diff --git a/services/ingest/src/api/traff.ts b/services/ingest/src/api/traff.ts index e4ddc315c..14ceaff5a 100644 --- a/services/ingest/src/api/traff.ts +++ b/services/ingest/src/api/traff.ts @@ -3,18 +3,33 @@ import type postgres from "postgres"; const PAGE_SIZE = 5000; const MAX_SITUATIONS = 20_000; -export const MAX_TRAFF_BYTES = 32 * 1024 * 1024; +export const MAX_COMPLETE_FEED_BYTES = 32 * 1024 * 1024; +export const MAX_TRAFF_BYTES = MAX_COMPLETE_FEED_BYTES; +export const MAX_CIFS_BYTES = MAX_COMPLETE_FEED_BYTES; -export class TraffFeedTooLargeError extends Error { +export class CompleteFeedTooLargeError extends Error { + constructor(feedName: string) { + super(`${feedName} feed too large; narrow the bbox, source or time filters`); + } +} + +export class TraffFeedTooLargeError extends CompleteFeedTooLargeError { constructor() { - super("TraFF feed too large; narrow the bbox, source or time filters"); + super("TraFF"); + } +} + +export class CifsFeedTooLargeError extends CompleteFeedTooLargeError { + constructor() { + super("CIFS"); } } /** Read a bounded, consistent public snapshot; never return a successful partial feed. */ -export async function readTraffSnapshot( +export async function readCompletePublicSnapshot( sql: postgres.Sql, query: Omit & { at: Date }, + tooLarge: () => CompleteFeedTooLargeError = () => new CompleteFeedTooLargeError("Feed"), ): Promise[]> { return sql.begin("isolation level repeatable read read only", async (tx) => { const db: QueryRunner = { @@ -32,8 +47,24 @@ export async function readTraffSnapshot( }); out.push(...read.records); cursor = read.next; - if (cursor !== null && out.length >= MAX_SITUATIONS) throw new TraffFeedTooLargeError(); + if (cursor !== null && out.length >= MAX_SITUATIONS) throw tooLarge(); } while (cursor !== null); return out; }); } + +/** Read a bounded, consistent public snapshot for TraFF; never return a successful partial feed. */ +export async function readTraffSnapshot( + sql: postgres.Sql, + query: Omit & { at: Date }, +): Promise[]> { + return readCompletePublicSnapshot(sql, query, () => new TraffFeedTooLargeError()); +} + +/** Read a bounded, consistent public snapshot for CIFS; never return a successful partial feed. */ +export async function readCifsSnapshot( + sql: postgres.Sql, + query: Omit & { at: Date }, +): Promise[]> { + return readCompletePublicSnapshot(sql, query, () => new CifsFeedTooLargeError()); +} diff --git a/services/ingest/src/ops/feed-inspect.ts b/services/ingest/src/ops/feed-inspect.ts index 672679db0..552d4c4d5 100644 --- a/services/ingest/src/ops/feed-inspect.ts +++ b/services/ingest/src/ops/feed-inspect.ts @@ -4,9 +4,11 @@ import { publicRecords, resolveAttribution } from "@openconditions/ingest-framew import { sealRecord } from "@openconditions/model"; import { productionRegistry } from "@openconditions/model-registry"; import { + cifsIncidentsOf, datexRecordsOf, type ExportDiagnostic, effectStatesAt, + situationsToCifsXml, situationsToDatex, situationsToGeoJSON, situationsToTraff, @@ -116,6 +118,7 @@ export function inspectFeed( projection: { public: { eligible: false, reason: "invalid_draft" }, traff: { messages: 0, reason: "invalid_draft", diagnostics: [] as ExportDiagnostic[] }, + cifs: { incidents: 0, reason: "invalid_draft", diagnostics: [] as ExportDiagnostic[] }, datex: { records: 0, reason: "invalid_draft", diagnostics: [] as ExportDiagnostic[] }, }, }; @@ -132,6 +135,7 @@ export function inspectFeed( ? "non_public_license" : null; const traffDiagnostics: ExportDiagnostic[] = []; + const cifsDiagnostics: ExportDiagnostic[] = []; const datexDiagnostics: ExportDiagnostic[] = []; const traff = shown ? situationsToTraff(registry, [shown], instant, (d) => traffDiagnostics.push(d)) @@ -140,6 +144,9 @@ export function inspectFeed( // XMLBuilder always emits this unprefixed element; attributes may contain // escaped text, never a literal ')/g) ?? []).length; + const cifsCount = shown + ? cifsIncidentsOf(shown, instant, (d) => cifsDiagnostics.push(d)).length + : 0; const datexCount = shown ? datexRecordsOf(shown, instant, (d) => datexDiagnostics.push(d)).length : 0; @@ -161,6 +168,16 @@ export function inspectFeed( : null), diagnostics: traffDiagnostics, }, + cifs: { + incidents: cifsCount, + reason: + reason ?? + (cifsCount === 0 + ? (cifsDiagnostics.find((d) => d.disposition === "withheld")?.code ?? + "no_representable_message") + : null), + diagnostics: cifsDiagnostics, + }, datex: { records: datexCount, reason: @@ -206,6 +223,7 @@ export function inspectFeed( exports: { geojson: situationsToGeoJSON(publicSituations, info, { at: instant }), traff: situationsToTraff(registry, publicSituations, instant), + cifs: situationsToCifsXml(publicSituations, instant, { timestamp }), datex: situationsToDatex( publicSituations, instant,