@foreverworks/mcp-romania-trains 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +197 -2
  4. package/dist/app/ports.d.ts +71 -0
  5. package/dist/app/ports.js +2 -0
  6. package/dist/app/usecases/common.d.ts +31 -0
  7. package/dist/app/usecases/common.js +57 -0
  8. package/dist/app/usecases/live.d.ts +62 -0
  9. package/dist/app/usecases/live.js +71 -0
  10. package/dist/app/usecases/timetable.d.ts +167 -0
  11. package/dist/app/usecases/timetable.js +172 -0
  12. package/dist/composition.d.ts +16 -0
  13. package/dist/composition.js +17 -0
  14. package/dist/domain/board.d.ts +18 -0
  15. package/dist/domain/board.js +25 -0
  16. package/dist/domain/errors.d.ts +29 -0
  17. package/dist/domain/errors.js +19 -0
  18. package/dist/domain/journeys.d.ts +62 -0
  19. package/dist/domain/journeys.js +130 -0
  20. package/dist/domain/network.d.ts +46 -0
  21. package/dist/domain/network.js +81 -0
  22. package/dist/domain/text.d.ts +10 -0
  23. package/dist/domain/text.js +16 -0
  24. package/dist/domain/timetable.d.ts +67 -0
  25. package/dist/domain/timetable.js +54 -0
  26. package/dist/index.d.ts +2 -0
  27. package/dist/index.js +24 -0
  28. package/dist/infra/datagov.d.ts +40 -0
  29. package/dist/infra/datagov.js +175 -0
  30. package/dist/infra/liveMap.d.ts +37 -0
  31. package/dist/infra/liveMap.js +128 -0
  32. package/dist/infra/xml.d.ts +10 -0
  33. package/dist/infra/xml.js +148 -0
  34. package/dist/mcp/envelope.d.ts +4 -0
  35. package/dist/mcp/envelope.js +5 -0
  36. package/dist/mcp/policy.d.ts +3 -0
  37. package/dist/mcp/policy.js +11 -0
  38. package/dist/mcp/register.d.ts +4 -0
  39. package/dist/mcp/register.js +78 -0
  40. package/icons/icon-48.png +0 -0
  41. package/icons/icon-512.png +0 -0
  42. package/icons/icon.svg +1 -0
  43. package/package.json +54 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # @foreverworks/mcp-romania-trains
2
+
3
+ ## 0.1.0
4
+
5
+ The first release. Romania's passenger train timetables for every operator Infofer publishes on data.gov.ro, read straight from the open data: find a station, see its departures and arrivals on a day, plan a journey between two stations with changes across operators, and read one train's stops and calendar. Live delays and estimated positions of the trains running now come from Infofer's public map, marked as unofficial.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Forever Works
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,198 @@
1
- # Temporary Holding Version
1
+ # <img src="icons/icon.svg" width="36" height="36" alt="Romanian trains icon"> Romanian trains MCP server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Ask your assistant how to get from București to Cluj by train on Friday, what
4
+ leaves Brașov after six tonight, or how late the Iași train is right now, and
5
+ get the answer for every passenger operator in Romania at once: CFR Călători,
6
+ Regio Călători, Transferoviar Călători, Interregional Călători, Astra Trans
7
+ Carpatic, Softrans, Ferotrafic and any other operator that publishes its
8
+ timetable. A journey can change from one company's train to another's, which
9
+ no single operator's site shows you.
10
+
11
+ **You need** nothing: no account and no key. The server reads the yearly
12
+ timetables Informatică Feroviară (Infofer) publishes as open data on
13
+ [data.gov.ro](https://data.gov.ro/organization/sc-informatica-feroviara-sa),
14
+ and the delays from Infofer's public live map.
15
+
16
+ ## What you can ask
17
+
18
+ - "How do I get from București Nord to Sibiu on 15 December, leaving after 6
19
+ in the morning? I don't mind one change."
20
+ - "What trains leave Brașov for anywhere this evening, and which company runs
21
+ each?"
22
+ - "Is there a direct train from Timișoara to Arad on Sunday morning?"
23
+ - "Which days does IR 1621 run in January, and when does it reach Sibiu?"
24
+ - "How late is train 1663 right now, and where is it?"
25
+ - "Which train companies run passenger trains in Romania?"
26
+
27
+ Station names can be typed without diacritics: "Brasov", "Iasi" and "Ploiesti
28
+ Vest" are found as Brașov, Iași and Ploiești Vest.
29
+
30
+ ## Install
31
+
32
+ <!-- install:begin -->
33
+ [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install_Server-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect/mcp/install?name=romania-trains&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40foreverworks%2Fmcp-romania-trains%22%5D%7D) [![Install in Cursor](https://img.shields.io/badge/Cursor-Install_Server-000000?style=flat-square&logo=cursor&logoColor=white)](https://cursor.com/install-mcp?name=romania-trains&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsIkBmb3JldmVyd29ya3MvbWNwLXJvbWFuaWEtdHJhaW5zIl19) [![Download for Claude Desktop](https://img.shields.io/badge/Claude_Desktop-Download_Bundle-D97757?style=flat-square&logo=claude&logoColor=white)](https://github.com/foreverworks/mcps/releases/latest/download/mcp-romania-trains.mcpb)
34
+
35
+ With Claude Code:
36
+
37
+ ```bash
38
+ claude mcp add romania-trains -- npx -y @foreverworks/mcp-romania-trains
39
+ ```
40
+
41
+ Claude Desktop (Settings, Developer, Edit Config) and most other clients read the same command as JSON:
42
+
43
+ ```json
44
+ {
45
+ "mcpServers": {
46
+ "romania-trains": {
47
+ "command": "npx",
48
+ "args": ["-y", "@foreverworks/mcp-romania-trains"]
49
+ }
50
+ }
51
+ }
52
+ ```
53
+
54
+ Each runs the published package on Node 22.19 or newer. It needs no settings.
55
+
56
+ ### From a clone
57
+
58
+ ```bash
59
+ git clone https://github.com/foreverworks/mcps.git && cd mcps
60
+ npm ci && npm run build
61
+ claude mcp add romania-trains -- node "$PWD/servers/romania-trains/dist/index.js"
62
+ ```
63
+
64
+ In a JSON configuration, the command is `node` and its one argument the full path of `servers/romania-trains/dist/index.js`. To share one running copy between several clients over HTTP, see [docs/deploying.md](../../docs/deploying.md).
65
+ <!-- install:end -->
66
+
67
+ ## Configuration
68
+
69
+ None of its own. Dates and times are always Romania's (Europe/Bucharest),
70
+ whatever the zone of the machine it runs on. The shared variables every
71
+ server here reads (HTTP transport, limits) are in
72
+ [docs/configuration.md](../../docs/configuration.md).
73
+
74
+ ## First run
75
+
76
+ The first call downloads every timetable in force, about 20 MB of XML a year
77
+ and twice that around mid December, when two timetable years overlap. That
78
+ takes a few seconds; every call after answers from memory. Call `health` to
79
+ see what was loaded.
80
+
81
+ ## Tools
82
+
83
+ | Tool | Access | What it does |
84
+ |---|---|---|
85
+ | `health` | read | Whether the timetables can be read: operators, trains and stations loaded, the days covered, when data.gov.ro was last read. |
86
+ | `operators` | read | Every operator with a current timetable, its trains, timetable years, licence and dataset; operators whose datasets have none. |
87
+ | `find_station` | read | Stations matching part of a name, diacritics ignored, closest and busiest first, with their codes. |
88
+ | `station_board` | read | A station's departures or arrivals on a day, every operator, in time order; optionally one operator only. |
89
+ | `journeys` | read | Journeys between two stations on a day, direct or with changes across operators, each leg with its train, times and distance. |
90
+ | `train` | read | One train's stops and times, whether it runs on a day, its next days of running and its whole calendar. |
91
+ | `live_trains` | read | Trains running now on Infofer's live map: delay, position (GPS, reported or estimated) and last report, joined to the timetable. |
92
+
93
+ Every tool only reads. A station argument takes a name or the code
94
+ `find_station` gives. A name that starts the names of a handful of stations
95
+ stands for all of them: "Timisoara" is Timișoara Nord, Est, Sud and the rest,
96
+ so a journey may leave from any of them.
97
+
98
+ ## Troubleshooting
99
+
100
+ **"matches several stations".** "Bucuresti" alone starts the names of more
101
+ than a dozen stations. Name one ("Bucuresti Nord") or call `find_station`
102
+ and pass a code.
103
+
104
+ **A change between two parts of one station is not found.** Infofer gives
105
+ some stations several codes (București Nord Gr.A and Gr.B are two), and a
106
+ journey only changes trains at the same code. Asking from or to "Bucuresti
107
+ Nord" covers both parts, but a change in the middle of a journey from one to
108
+ the other is not offered.
109
+
110
+ **A journey I know exists is missing.** Check the transfer time
111
+ (`min_transfer_minutes`, 5 by default) and `max_changes` (2 by default).
112
+ Journeys longer than a day, and journeys another one beats on departure,
113
+ arrival and changes alike, are left out on purpose.
114
+
115
+ **`live_trains` does not list my train.** The map shows only trains running
116
+ at that moment. A train that has not left yet, has arrived or is not reported
117
+ is absent. That never means it is cancelled; the map does not say.
118
+
119
+ ## How it works
120
+
121
+ ### The timetables
122
+
123
+ Infofer publishes one XML file per operator and timetable year in the
124
+ data.gov.ro organisation `sc-informatica-feroviara-sa`. The server asks the
125
+ portal's catalogue (CKAN) which datasets exist, so a new operator is picked
126
+ up without a change here, and reads every file whose year range ends this
127
+ year or later. A timetable year runs from the second Sunday of December to
128
+ the Saturday before the next one, so in December the ending and the starting
129
+ year are both loaded, and each day is answered from the one in force. A
130
+ dataset with no current file (Regiotrans Brașov and Calea Ferată din Moldova
131
+ stopped publishing) is listed as skipped by `operators`. The catalogue is
132
+ read again every six hours, and a file is downloaded again only when it
133
+ changed.
134
+
135
+ Each train in the XML is a list of sections between consecutive stations
136
+ with departure and arrival times in seconds of the day, and a calendar of
137
+ date ranges with weekdays. The server keeps the stations where passengers
138
+ get on or off, counts the times past midnight, and treats public holidays as
139
+ the gaps between ranges, as Infofer writes them. A train is on a day's
140
+ station board when it is at that station on that day, even if it left its
141
+ first station the day before.
142
+
143
+ ### Journeys
144
+
145
+ Journeys come from the Connection Scan Algorithm over every operator's
146
+ trains running that day, the two days before and the day after. Each search
147
+ finds the earliest arrival; the server repeats it from later departures,
148
+ adds the direct trains on their own, and keeps the journeys that no other
149
+ beats on every count.
150
+
151
+ ### Live delays
152
+
153
+ `live_trains` reads `https://mersultrenurilor.infofer.ro/ro-RO/Trains/LoadMapPartial`,
154
+ the data behind Infofer's live map: every running train's delay, an
155
+ position (mostly estimated) and when it was last reported. It needs no key and no
156
+ captcha. The server reads it at most once a minute, and only when the tool
157
+ is called. The pages of Infofer's site that show platforms and the actual
158
+ time at each station are protected by a captcha, and this server does not
159
+ request them.
160
+
161
+ ## Limitations
162
+
163
+ - **Platforms and cancellations are not available.** The timetables do not
164
+ hold platforms, and the live map shows neither.
165
+ - **Live data is unofficial.** Most positions are estimated from traffic
166
+ control reports; some trains send their own GPS fix, and `position_is`
167
+ says which. Delays are as the map shows them at that minute. This server is not affiliated with Infofer, CFR or
168
+ any operator. Infofer's site terms ask for written consent before its
169
+ content is used commercially: ask them before you build a product on
170
+ `live_trains`.
171
+ - **The timetable is the yearly plan.** Engineering works, replacement buses
172
+ and changes made during the year appear only when Infofer publishes a new
173
+ file.
174
+ - **Times are scheduled times.** Fares, seat availability and tickets are out
175
+ of scope.
176
+ - Attribution: timetables © Informatică Feroviară S.A., published on
177
+ data.gov.ro under each dataset's licence (OGL-ROU-1.0 for most, CC BY 4.0
178
+ for Ferotrafic TFI; `operators` lists each).
179
+
180
+ ## Other servers for Romanian trains
181
+
182
+ Searched 2026-12-03. Neither Infofer nor any operator publishes an MCP server
183
+ or an API, and no community MCP server for Romanian trains was found. Servers
184
+ exist for other countries' railways (Deutsche Bahn, SNCF, SBB, National Rail),
185
+ none for Romania.
186
+
187
+ Open projects read the same data without MCP:
188
+
189
+ - **mariuscomper/romania-rail-gtfs** converts the 2025-2026 timetables to a
190
+ static GTFS snapshot, with notes on the data's method and licences.
191
+ - **vasile/data.gov.ro-gtfs-exporter** (Ruby) exports the XML to GTFS.
192
+ - **zandaulion/intarzieri** (Python) shows delays, with the XML's fields
193
+ documented in its README.
194
+
195
+ This one exists for what none of them does: it reads every operator's
196
+ current timetables straight from data.gov.ro, follows the yearly change in
197
+ December by itself, plans journeys across operators, and puts live delays
198
+ beside the timetable, as tools an assistant can call.
@@ -0,0 +1,71 @@
1
+ import type { Network } from "../domain/network.js";
2
+ import type { Operator, Timetable } from "../domain/timetable.js";
3
+ /** An operator's dataset that has no timetable for the current year, and why it was left out. */
4
+ export type Skipped = {
5
+ readonly operator: Operator;
6
+ readonly reason: string;
7
+ };
8
+ /** A timetable file that could not be read; the others still answer. */
9
+ export type Failure = {
10
+ readonly operator: Operator;
11
+ readonly resource: string;
12
+ readonly message: string;
13
+ };
14
+ /** What the catalogue held at the last look, read and indexed. */
15
+ export type Loaded = {
16
+ readonly network: Network;
17
+ readonly timetables: readonly Timetable[];
18
+ readonly skipped: readonly Skipped[];
19
+ readonly failures: readonly Failure[];
20
+ /** Epoch ms of the catalogue read this answers from. */
21
+ readonly checkedAt: number;
22
+ /** Set when a refresh failed and an older load answers instead. */
23
+ readonly stale?: string;
24
+ };
25
+ /** Infofer's timetables as data.gov.ro publishes them. */
26
+ export type TimetablePort = {
27
+ /** The current load: fetched on first use, then checked again for new files every few hours. */
28
+ readonly loaded: () => Promise<Loaded>;
29
+ /** The last load, if there is one, without fetching anything. */
30
+ readonly peek: () => Loaded | undefined;
31
+ };
32
+ /** A train on Infofer's live map: running now, with its delay and an estimated position. */
33
+ export type LiveTrain = {
34
+ /** As the map writes it, leading zeros and all. */
35
+ readonly number: string;
36
+ readonly category: string | undefined;
37
+ /** Positive late, negative early; undefined when the map's words could not be read. */
38
+ readonly delayMinutes: number | undefined;
39
+ /** The map's own words for the delay. */
40
+ readonly said: string | undefined;
41
+ /** Where the map puts the train; absent when its block carries no coordinates. */
42
+ readonly position: {
43
+ readonly latitude: number;
44
+ readonly longitude: number;
45
+ } | undefined;
46
+ readonly bearing: number | undefined;
47
+ /** The map's note on where the position comes from. */
48
+ readonly report: string | undefined;
49
+ /** gps: the train's own last GPS fix; reported: a report by railway staff; estimated: computed from traffic control reports. */
50
+ readonly reportKind: "gps" | "estimated" | "reported" | undefined;
51
+ /** HH:MM, Bucharest, of the last report. */
52
+ readonly reportedAt: string | undefined;
53
+ /** The train's running date, as the map links it. */
54
+ readonly date: string | undefined;
55
+ };
56
+ export type LiveSnapshot = {
57
+ readonly fetchedAt: number;
58
+ readonly trains: readonly LiveTrain[];
59
+ };
60
+ /** Infofer's live map: every train running now. */
61
+ export type LivePort = {
62
+ /** The current snapshot, read again at most once a minute. */
63
+ readonly snapshot: () => Promise<LiveSnapshot>;
64
+ };
65
+ export type Deps = {
66
+ readonly timetables: TimetablePort;
67
+ readonly live: LivePort;
68
+ readonly now: () => number;
69
+ /** Romania's calendar: dates and times are Bucharest's. */
70
+ readonly timeZone: string;
71
+ };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1,31 @@
1
+ import { type Network, type Station } from "../../domain/network.js";
2
+ import { type Train } from "../../domain/timetable.js";
3
+ import type { Deps, Loaded } from "../ports.js";
4
+ /** The calendar date in `timeZone` at `epochMs`, YYYY-MM-DD. */
5
+ export declare const dateIn: (timeZone: string, epochMs: number) => string;
6
+ /** Seconds after midnight in `timeZone` at `epochMs`. */
7
+ export declare const clockIn: (timeZone: string, epochMs: number) => number;
8
+ export declare const todayOf: (deps: Deps) => string;
9
+ /** The days the loaded timetables cover, first and last. */
10
+ export declare const coverageOf: (loaded: Loaded) => {
11
+ readonly from: string;
12
+ readonly to: string;
13
+ };
14
+ /** A date argument, default today, inside what the timetables cover. */
15
+ export declare const checkedDate: (deps: Deps, loaded: Loaded, date: string | undefined) => string;
16
+ /** The second of the day to start from: the time given, else now when the date is today, else midnight. */
17
+ export declare const startOf: (deps: Deps, date: string, time: string | undefined) => number;
18
+ /** The stations a station argument stands for, or a failure naming the candidates. */
19
+ export declare const stationsFor: (network: Network, text: string, role: string) => readonly Station[];
20
+ export declare const stationOut: (s: Station) => {
21
+ code: string;
22
+ name: string;
23
+ };
24
+ export declare const trainOut: (t: Train) => {
25
+ number: string;
26
+ category: string;
27
+ operator: string;
28
+ from: string;
29
+ to: string;
30
+ };
31
+ export declare const SOURCE = "Infofer's yearly timetables on data.gov.ro (static: no delays, cancellations or platforms)";
@@ -0,0 +1,57 @@
1
+ import { isIsoDate } from "@foreverworks/mcp-kit";
2
+ import { fail, inputError, notFound } from "../../domain/errors.js";
3
+ import { resolveStation } from "../../domain/network.js";
4
+ import { secondsOfClock } from "../../domain/timetable.js";
5
+ /** The calendar date in `timeZone` at `epochMs`, YYYY-MM-DD. */
6
+ export const dateIn = (timeZone, epochMs) => new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).format(new Date(epochMs));
7
+ /** Seconds after midnight in `timeZone` at `epochMs`. */
8
+ export const clockIn = (timeZone, epochMs) => {
9
+ const parts = new Intl.DateTimeFormat("en-GB", { timeZone, hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" }).formatToParts(new Date(epochMs));
10
+ const part = (type) => Number(parts.find((p) => p.type === type)?.value ?? "0");
11
+ return part("hour") * 3600 + part("minute") * 60 + part("second");
12
+ };
13
+ export const todayOf = (deps) => dateIn(deps.timeZone, deps.now());
14
+ /** The days the loaded timetables cover, first and last. */
15
+ export const coverageOf = (loaded) => ({
16
+ from: loaded.timetables.map((t) => t.validFrom).sort()[0] ?? "",
17
+ to: loaded.timetables.map((t) => t.validTo).sort().at(-1) ?? "",
18
+ });
19
+ /** A date argument, default today, inside what the timetables cover. */
20
+ export const checkedDate = (deps, loaded, date) => {
21
+ const d = date?.trim() ?? todayOf(deps);
22
+ if (!isIsoDate(d))
23
+ fail(inputError(`date must be a calendar date, YYYY-MM-DD, not "${date ?? ""}"`));
24
+ const { from, to } = coverageOf(loaded);
25
+ if (d < from || d > to)
26
+ fail(notFound(`the timetables published cover ${from} to ${to}; ${d} is outside them`));
27
+ return d;
28
+ };
29
+ /** The second of the day to start from: the time given, else now when the date is today, else midnight. */
30
+ export const startOf = (deps, date, time) => {
31
+ if (time !== undefined) {
32
+ return secondsOfClock(time) ?? fail(inputError(`time must be HH:MM, 24-hour, not "${time}"`));
33
+ }
34
+ return date === todayOf(deps) ? clockIn(deps.timeZone, deps.now()) - (clockIn(deps.timeZone, deps.now()) % 60) : 0;
35
+ };
36
+ /** The stations a station argument stands for, or a failure naming the candidates. */
37
+ export const stationsFor = (network, text, role) => {
38
+ const r = resolveStation(network, text);
39
+ switch (r.kind) {
40
+ case "found":
41
+ return r.stations;
42
+ case "none":
43
+ return fail(inputError(`no station matches ${role} "${text}"; find_station searches by part of a name`));
44
+ case "ambiguous":
45
+ return fail(inputError(`${role} "${text}" matches several stations; name one of them, or give its code: ${r.candidates.map((s) => `${s.name} (${s.code})`).join(", ")}`));
46
+ }
47
+ };
48
+ export const stationOut = (s) => ({ code: s.code, name: s.name });
49
+ export const trainOut = (t) => ({
50
+ number: t.number,
51
+ category: t.category,
52
+ operator: t.operator.name,
53
+ from: t.stops[0]?.name ?? "",
54
+ to: t.stops.at(-1)?.name ?? "",
55
+ });
56
+ export const SOURCE = "Infofer's yearly timetables on data.gov.ro (static: no delays, cancellations or platforms)";
57
+ //# sourceMappingURL=common.js.map
@@ -0,0 +1,62 @@
1
+ import type { Deps } from "../ports.js";
2
+ export declare const LIVE_SOURCE = "Infofer's public live map (mersultrenurilor.infofer.ro), unofficial for this server: delays as the map shows them, positions estimated from traffic control reports";
3
+ /**
4
+ * Trains running now, from Infofer's live map, each joined to its timetable
5
+ * by number for its operator and route.
6
+ */
7
+ export declare const liveTrains: (deps: Deps, a: {
8
+ readonly numbers: readonly string[] | undefined;
9
+ readonly min_delay_minutes: number | undefined;
10
+ readonly limit: number;
11
+ }) => Promise<{
12
+ fetched_at: string;
13
+ running_now: number;
14
+ caveat: string;
15
+ source: string;
16
+ ok: true;
17
+ trains: {
18
+ number: string;
19
+ category?: string;
20
+ operator?: string;
21
+ from?: string;
22
+ to?: string;
23
+ delay_minutes?: number;
24
+ map_says?: string;
25
+ position?: {
26
+ latitude: number;
27
+ longitude: number;
28
+ bearing?: number;
29
+ };
30
+ position_is?: "estimated" | "gps" | "reported";
31
+ last_report?: string;
32
+ running_date?: string;
33
+ }[];
34
+ no_live_data?: {
35
+ number: string;
36
+ note: string;
37
+ }[];
38
+ } | {
39
+ fetched_at: string;
40
+ running_now: number;
41
+ caveat: string;
42
+ source: string;
43
+ ok: true;
44
+ trains: {
45
+ number: string;
46
+ category?: string;
47
+ operator?: string;
48
+ from?: string;
49
+ to?: string;
50
+ delay_minutes?: number;
51
+ map_says?: string;
52
+ position?: {
53
+ latitude: number;
54
+ longitude: number;
55
+ bearing?: number;
56
+ };
57
+ position_is?: "estimated" | "gps" | "reported";
58
+ last_report?: string;
59
+ running_date?: string;
60
+ }[];
61
+ more?: string;
62
+ }>;
@@ -0,0 +1,71 @@
1
+ import { fail, inputError } from "../../domain/errors.js";
2
+ import { trainKey } from "../../domain/timetable.js";
3
+ import { todayOf, trainOut } from "./common.js";
4
+ export const LIVE_SOURCE = "Infofer's public live map (mersultrenurilor.infofer.ro), unofficial for this server: delays as the map shows them, positions estimated from traffic control reports";
5
+ const NO_LIVE = "no live data: the train is not on Infofer's live map now. It may not have left yet, may have arrived, or may not be reported; this is not proof that it is cancelled.";
6
+ /**
7
+ * Trains running now, from Infofer's live map, each joined to its timetable
8
+ * by number for its operator and route.
9
+ */
10
+ export const liveTrains = async (deps, a) => {
11
+ if (a.numbers !== undefined && a.min_delay_minutes !== undefined)
12
+ fail(inputError("min_delay_minutes filters the list of every train; leave it out when asking for numbers"));
13
+ // The join to the timetable is a bonus: a live answer never waits for the first download of every timetable.
14
+ const snapshot = await deps.live.snapshot();
15
+ const loaded = deps.timetables.peek();
16
+ if (loaded === undefined)
17
+ void deps.timetables.loaded().catch(() => undefined);
18
+ const today = todayOf(deps);
19
+ const timetabled = (t) => {
20
+ const versions = loaded?.network.byNumber.get(trainKey(t.number)) ?? [];
21
+ const day = t.date ?? today;
22
+ return versions.find((v) => v.validFrom <= day && day <= v.validTo) ?? versions[0];
23
+ };
24
+ const out = (t) => {
25
+ const known = timetabled(t);
26
+ return {
27
+ number: trainKey(t.number),
28
+ ...(t.category !== undefined ? { category: t.category } : {}),
29
+ ...(known !== undefined ? { operator: known.operator.name, from: trainOut(known).from, to: trainOut(known).to } : {}),
30
+ ...(t.delayMinutes !== undefined ? { delay_minutes: t.delayMinutes } : {}),
31
+ ...(t.said !== undefined ? { map_says: t.said } : {}),
32
+ ...(t.position !== undefined ? { position: { ...t.position, ...(t.bearing !== undefined ? { bearing: t.bearing } : {}) } } : {}),
33
+ ...(t.reportKind !== undefined ? { position_is: t.reportKind } : {}),
34
+ ...(t.reportedAt !== undefined ? { last_report: t.reportedAt } : {}),
35
+ ...(t.date !== undefined ? { running_date: t.date } : {}),
36
+ };
37
+ };
38
+ const fetchedAt = new Date(snapshot.fetchedAt).toISOString();
39
+ const common = {
40
+ fetched_at: fetchedAt,
41
+ running_now: snapshot.trains.length,
42
+ caveat: "Unofficial and estimated: no platforms, no cancellations. A train absent from the map has no live data; that does not mean it is cancelled.",
43
+ source: LIVE_SOURCE,
44
+ };
45
+ if (a.numbers !== undefined && a.numbers.length > 0) {
46
+ const byKey = new Map(snapshot.trains.map((t) => [trainKey(t.number), t]));
47
+ const asked = [...new Set(a.numbers.map(trainKey))];
48
+ const found = asked.flatMap((k) => {
49
+ const t = byKey.get(k);
50
+ return t === undefined ? [] : [out(t)];
51
+ });
52
+ const absent = asked.filter((k) => !byKey.has(k));
53
+ return {
54
+ ok: true,
55
+ trains: found,
56
+ ...(absent.length > 0 ? { no_live_data: absent.map((number) => ({ number, note: NO_LIVE })) } : {}),
57
+ ...common,
58
+ };
59
+ }
60
+ const min = a.min_delay_minutes;
61
+ const chosen = snapshot.trains
62
+ .filter((t) => min === undefined || (t.delayMinutes !== undefined && t.delayMinutes >= min))
63
+ .sort((x, y) => (y.delayMinutes ?? -Infinity) - (x.delayMinutes ?? -Infinity) || x.number.localeCompare(y.number));
64
+ return {
65
+ ok: true,
66
+ trains: chosen.slice(0, a.limit).map(out),
67
+ ...(chosen.length > a.limit ? { more: `${chosen.length - a.limit} more; most delayed first` } : {}),
68
+ ...common,
69
+ };
70
+ };
71
+ //# sourceMappingURL=live.js.map