@foreverworks/mcp-bucharest-transit 0.0.0-stage → 0.1.1

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 (59) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/LICENSE +21 -0
  3. package/README.md +116 -2
  4. package/dist/app/ports.d.ts +69 -0
  5. package/dist/app/ports.js +2 -0
  6. package/dist/app/usecases/alerts.d.ts +7 -0
  7. package/dist/app/usecases/alerts.js +49 -0
  8. package/dist/app/usecases/common.d.ts +46 -0
  9. package/dist/app/usecases/common.js +117 -0
  10. package/dist/app/usecases/places.d.ts +12 -0
  11. package/dist/app/usecases/places.js +128 -0
  12. package/dist/app/usecases/route.d.ts +13 -0
  13. package/dist/app/usecases/route.js +163 -0
  14. package/dist/app/usecases/timetable.d.ts +16 -0
  15. package/dist/app/usecases/timetable.js +117 -0
  16. package/dist/composition.d.ts +16 -0
  17. package/dist/composition.js +31 -0
  18. package/dist/domain/calendar.d.ts +27 -0
  19. package/dist/domain/calendar.js +36 -0
  20. package/dist/domain/errors.d.ts +30 -0
  21. package/dist/domain/errors.js +20 -0
  22. package/dist/domain/fares.d.ts +36 -0
  23. package/dist/domain/fares.js +100 -0
  24. package/dist/domain/feed.d.ts +151 -0
  25. package/dist/domain/feed.js +23 -0
  26. package/dist/domain/network.d.ts +52 -0
  27. package/dist/domain/network.js +113 -0
  28. package/dist/domain/places.d.ts +52 -0
  29. package/dist/domain/places.js +187 -0
  30. package/dist/domain/raptor.d.ts +60 -0
  31. package/dist/domain/raptor.js +176 -0
  32. package/dist/domain/schedule.d.ts +65 -0
  33. package/dist/domain/schedule.js +105 -0
  34. package/dist/domain/text.d.ts +12 -0
  35. package/dist/domain/text.js +36 -0
  36. package/dist/index.d.ts +2 -0
  37. package/dist/index.js +24 -0
  38. package/dist/infra/alerts.d.ts +12 -0
  39. package/dist/infra/alerts.js +84 -0
  40. package/dist/infra/csv.d.ts +11 -0
  41. package/dist/infra/csv.js +82 -0
  42. package/dist/infra/feedSource.d.ts +28 -0
  43. package/dist/infra/feedSource.js +132 -0
  44. package/dist/infra/gtfs.d.ts +5 -0
  45. package/dist/infra/gtfs.js +246 -0
  46. package/dist/infra/protobuf.d.ts +16 -0
  47. package/dist/infra/protobuf.js +47 -0
  48. package/dist/infra/zip.d.ts +12 -0
  49. package/dist/infra/zip.js +68 -0
  50. package/dist/mcp/envelope.d.ts +4 -0
  51. package/dist/mcp/envelope.js +5 -0
  52. package/dist/mcp/policy.d.ts +3 -0
  53. package/dist/mcp/policy.js +11 -0
  54. package/dist/mcp/register.d.ts +4 -0
  55. package/dist/mcp/register.js +86 -0
  56. package/icons/icon-48.png +0 -0
  57. package/icons/icon-512.png +0 -0
  58. package/icons/icon.svg +1 -0
  59. package/package.json +58 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # @foreverworks/mcp-bucharest-transit
2
+
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 13f3694: Published through npm's trusted publishing: from this version on, each release names GitHub Actions as its publisher, with a provenance statement that ties the package to the commit it was built from.
8
+
9
+ ## 0.1.0
10
+
11
+ The first release. Bucharest's metro and surface lines (Metrorex, STB and the Ilfov operators) from the transport authority's official GTFS timetable, kept on disk and refreshed by itself: plan a journey between two places with real departures, transfers, walking, station exits and the fare; see a station's lines, exits and first and last trains; a line's stops and frequency; the next departures from a stop; and the live service alerts. Every tool reads; none is `money`.
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,117 @@
1
- # Temporary Holding Version
1
+ # <img src="icons/icon.svg" width="36" height="36" alt="Bucharest transit icon"> Bucharest transit 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 across Bucharest and get a real answer: which metro or bus to take, when the next ones leave, where to change and how long the walk is, which exit to use at the end, and what the ticket costs. It covers the metro (Metrorex, M1 to M5) and the surface lines (STB buses, trams and trolleybuses, and the Ilfov operators), from the transport authority's official GTFS timetable, the same one map apps use. It also tells a station's exits and lifts, its first and last trains, a line's stops and frequency, and the disruptions announced right now. It only reads: nothing is bought, booked or sent.
4
+
5
+ **You need** nothing: no account and no key. On its first run the server downloads the timetable (about 9 MB) and keeps it on disk; after that every answer comes from that copy, and it checks for a new timetable about once a week. Only `alerts` goes online when you call it.
6
+
7
+ ## What you can ask
8
+
9
+ - "How do I get from Pipera to Tudor Arghezi right now, and how much is the ticket?"
10
+ - "I need to be at Universitate by 9:00 tomorrow, coming from Aeroport Băneasa. When do I leave?"
11
+ - "Which exit at Piața Unirii has a lift?"
12
+ - "When is the last metro from Piața Victoriei tonight?"
13
+ - "How often does the 336 run on Saturday morning?"
14
+ - "Is anything disrupted on M4 today?"
15
+
16
+ ## Install
17
+
18
+ <!-- install:begin -->
19
+ [![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=bucharest-transit&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40foreverworks%2Fmcp-bucharest-transit%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=bucharest-transit&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsIkBmb3JldmVyd29ya3MvbWNwLWJ1Y2hhcmVzdC10cmFuc2l0Il19) [![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-bucharest-transit.mcpb)
20
+
21
+ With Claude Code:
22
+
23
+ ```bash
24
+ claude mcp add bucharest-transit -- npx -y @foreverworks/mcp-bucharest-transit
25
+ ```
26
+
27
+ Claude Desktop (Settings, Developer, Edit Config) and most other clients read the same command as JSON:
28
+
29
+ ```json
30
+ {
31
+ "mcpServers": {
32
+ "bucharest-transit": {
33
+ "command": "npx",
34
+ "args": ["-y", "@foreverworks/mcp-bucharest-transit"]
35
+ }
36
+ }
37
+ }
38
+ ```
39
+
40
+ Each runs the published package on Node 22.19 or newer. It needs no settings.
41
+
42
+ ### From a clone
43
+
44
+ ```bash
45
+ git clone https://github.com/foreverworks/mcps.git && cd mcps
46
+ npm ci && npm run build
47
+ claude mcp add bucharest-transit -- node "$PWD/servers/bucharest-transit/dist/index.js"
48
+ ```
49
+
50
+ In a JSON configuration, the command is `node` and its one argument the full path of `servers/bucharest-transit/dist/index.js`. To share one running copy between several clients over HTTP, see [docs/deploying.md](../../docs/deploying.md).
51
+ <!-- install:end -->
52
+
53
+ ## Configuration
54
+
55
+ Nothing is required. These change where the timetable comes from and where it is kept:
56
+
57
+ | Variable | Required | Meaning |
58
+ |---|---|---|
59
+ | `BUCHAREST_TRANSIT_STATE_DIR` | no | Where the downloaded timetable is kept (`feed.zip` and `feed.json`). Default: the server's state directory, see [docs/configuration.md](../../docs/configuration.md). |
60
+ | `BUCHAREST_TRANSIT_FEED_URL` | no | The GTFS feed to download. Default `https://gtfs.tpbi.ro/regional/BUCHAREST-REGION.zip`. |
61
+ | `BUCHAREST_TRANSIT_FEED_FILE` | no | A GTFS ZIP on disk to read instead; the server then never downloads or refreshes it. For offline use and tests. |
62
+ | `BUCHAREST_TRANSIT_ALERTS_URL` | no | The GTFS-Realtime service alerts to read. Default `https://gtfs.tpbi.ro/api/gtfs-rt/serviceAlerts`. |
63
+
64
+ ## First run
65
+
66
+ 1. Ask for `health`. The first call downloads and indexes the timetable, which takes a few seconds. A good answer names the feed's version, the days it covers and `days_left`.
67
+ 2. Ask for a journey between two stations you know. Names work with or without diacritics ("Piata Unirii", "Piața Unirii").
68
+
69
+ ## Tools
70
+
71
+ Every tool only reads.
72
+
73
+ | Tool | Access | What it does |
74
+ |---|---|---|
75
+ | `route` | read | The next few journeys between two places: lines, where to change, walking, total time, exits at the end, and the fare. Leave at a time or arrive by one; metro only if you like. |
76
+ | `find_station` | read | Stations and stops by part of a name, diacritics optional, small misspellings forgiven; or everything near a point. |
77
+ | `station` | read | A station's platforms and directions, entrances with stairs, escalators and lifts, levels, amenities, and first and last departures on weekdays and weekends. |
78
+ | `line` | read | A line's stops in order with minutes, its variants, and how often it runs through the day. |
79
+ | `departures` | read | The next departures from a station or stop, every line, including trips past midnight. |
80
+ | `alerts` | read | The disruptions the transport authority publishes now, by line or station, in Romanian and English. |
81
+ | `health` | read | The timetable in use: version, the days it covers, days left, when it was last checked. |
82
+
83
+ ## Troubleshooting
84
+
85
+ **`health` has a `warning` that the timetable ends soon.** The authority publishes a new timetable about every three months. The server looks for it every day in the last two weeks; if the warning stays, the authority has not published one yet, and answers after the end date are about a calendar that is over.
86
+
87
+ **`stale` in an answer.** The last check for a new timetable failed (the authority's server did not answer). The copy on disk keeps answering, and the server tries again in 15 minutes.
88
+
89
+ **"matches several places far apart".** Some stop names repeat across the city. The message lists each with its street and id; pass the id (`stop:1234`) instead of the name.
90
+
91
+ **A station's platform is named for the wrong line.** The feed's own names and its timetable sometimes disagree (as of December 2026, the halls of Piața Victoriei carry each other's names). The answer then carries a `feed_note` saying which lines actually call there; the journeys follow the timetable.
92
+
93
+ ## How it works
94
+
95
+ **The timetable.** The source is the regional GTFS feed of ADTPBI, the Bucharest-Ilfov public transport authority, produced by FlashWeb IT: about 66,000 trips and 1.5 million stop times. Reading it takes about 2.5 seconds and 45 MB of memory, and indexing it for journeys a few seconds more, so it is read once and kept in memory. The server stores the ZIP and compares it with the published one with a conditional request on its ETag; an unchanged feed costs one tiny response. A new download replaces the old one only after it has been read successfully.
96
+
97
+ **Journeys.** `route` uses RAPTOR, an algorithm that finds, round by round, the earliest arrival with one vehicle, then two, and so on, and keeps every journey that is not beaten on both time and number of changes. It scans the trips that really run on the day asked (weekday, Saturday or Sunday services), including trips that started the day before and run past midnight. Between vehicles it walks: inside a metro station between its platforms, or on the street to any stop within 500 metres.
98
+
99
+ **Walking times are estimates.** The feed describes the walkways, stairs, escalators and lifts inside stations, but gives no times for them, and no minimum transfer times. The server estimates a walk from the distance: 90 seconds plus the walk inside a station, and on the street a detour factor and two minutes for each metro platform reached from the street. Transfers the feed marks as impossible (between Gara de Nord 1 and 2, which have no connection inside) are made on the street.
100
+
101
+ **Fares.** Prices come from the feed's own fare tables (GTFS Fares v2), never from this code: which ticket each network takes, how long a ticket carries over to another ride, and the integrated ticket valid on both. Every answer names the feed version its fare comes from. The price shown is a single ride on the cheapest medium; passes are not compared.
102
+
103
+ **Alerts.** Read live from the authority's GTFS-Realtime service alerts, at most once a minute.
104
+
105
+ ## Limitations
106
+
107
+ - Scheduled times only. The authority also publishes live trip updates and vehicle positions, which this server does not read yet.
108
+ - Public holidays: the feed marks no exceptions, so a holiday runs the weekday timetable here unless the authority publishes one.
109
+ - No addresses: give a station or stop, or a point as latitude and longitude. The server never calls a geocoder.
110
+ - Walking inside stations and on the street is estimated from distance (see How it works).
111
+ - Line M6 to the airport is not in the feed while it is under construction.
112
+
113
+ **Data and licence.** The timetable and alerts are published by ADTPBI (Asociația de Dezvoltare Intercomunitară pentru Transport Public București-Ilfov), with data from STB, Metrorex, STV, STCM and Regio Serv, produced by FlashWeb IT. As of December 2026 neither the feed, tpbi.ro nor the Mobility Database states a licence or terms of reuse for it. This server credits them in its answers and keeps no copy of the data in this repository; check the authority's terms before you publish what it returns.
114
+
115
+ ## Other servers for Bucharest transit
116
+
117
+ Searched on 2026-12-05 (the MCP Registry, npm, PyPI and GitHub): no MCP server for Bucharest's public transport was found. The closest is [metro-mcp](https://github.com/aarekaz/metro-mcp), which covers Washington DC and New York. The apps people use in Bucharest (MetroBUC, Citymapper, Google Maps, Bucharest Transit) offer no API an assistant can use.
@@ -0,0 +1,69 @@
1
+ import type { Feed } from "../domain/feed.js";
2
+ import type { Network } from "../domain/network.js";
3
+ import type { Place } from "../domain/places.js";
4
+ /** Where the feed in memory came from and when it was last compared with the published one. */
5
+ export type FeedSource = {
6
+ readonly url: string;
7
+ /** "download" for a copy this server fetched and keeps on disk, "file" for a feed file it was pointed at. */
8
+ readonly origin: "download" | "file";
9
+ readonly etag: string | undefined;
10
+ readonly lastModified: string | undefined;
11
+ /** Epoch ms when the bytes in use were downloaded (or the file read). */
12
+ readonly fetchedAt: number;
13
+ /** Epoch ms of the last check against the publisher, 304 or 200. */
14
+ readonly checkedAt: number;
15
+ readonly bytes: number;
16
+ };
17
+ /** The feed, read and indexed. */
18
+ export type Loaded = {
19
+ readonly feed: Feed;
20
+ readonly network: Network;
21
+ readonly places: readonly Place[];
22
+ readonly source: FeedSource;
23
+ /** Set when a check against the publisher failed and the copy on disk answers instead. */
24
+ readonly stale?: string;
25
+ };
26
+ /** The static GTFS feed: read from disk or downloaded on first use, compared with the published one about weekly. */
27
+ export type FeedPort = {
28
+ readonly loaded: () => Promise<Loaded>;
29
+ /** The feed in memory, if any, without reading or fetching anything. */
30
+ readonly peek: () => Loaded | undefined;
31
+ };
32
+ export type Alert = {
33
+ readonly id: string;
34
+ readonly cause: string;
35
+ readonly effect: string;
36
+ readonly severity: string;
37
+ /** Language code to text; "" for an untagged translation. */
38
+ readonly header: Readonly<Record<string, string>>;
39
+ readonly description: Readonly<Record<string, string>>;
40
+ readonly url: Readonly<Record<string, string>>;
41
+ /** POSIX seconds; either end may be open. */
42
+ readonly periods: readonly {
43
+ readonly start: number | undefined;
44
+ readonly end: number | undefined;
45
+ }[];
46
+ /** GTFS ids the alert names. */
47
+ readonly informed: readonly {
48
+ readonly agency: string | undefined;
49
+ readonly route: string | undefined;
50
+ readonly stop: string | undefined;
51
+ readonly trip: string | undefined;
52
+ }[];
53
+ };
54
+ export type AlertsSnapshot = {
55
+ readonly fetchedAt: number;
56
+ readonly feedTimestamp: number | undefined;
57
+ readonly alerts: readonly Alert[];
58
+ };
59
+ /** Live service alerts: read at most once a minute. */
60
+ export type AlertsPort = {
61
+ readonly snapshot: () => Promise<AlertsSnapshot>;
62
+ };
63
+ export type Deps = {
64
+ readonly feed: FeedPort;
65
+ readonly alerts: AlertsPort;
66
+ readonly now: () => number;
67
+ /** Bucharest's: every date and time in and out is local. */
68
+ readonly timeZone: string;
69
+ };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1,7 @@
1
+ import type { Deps } from "../ports.js";
2
+ export declare const alerts: (deps: Deps, a: {
3
+ line?: string | undefined;
4
+ station?: string | undefined;
5
+ include_upcoming: boolean;
6
+ limit: number;
7
+ }) => Promise<Record<string, unknown>>;
@@ -0,0 +1,49 @@
1
+ import { routeFor } from "./common.js";
2
+ import { stopIdsOf } from "./places.js";
3
+ const local = (timeZone, seconds) => seconds === undefined || seconds === 0
4
+ ? undefined
5
+ : new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(seconds * 1000)).replace(" ", "T");
6
+ export const alerts = async (deps, a) => {
7
+ const [loaded, snapshot] = await Promise.all([deps.feed.loaded(), deps.alerts.snapshot()]);
8
+ const { feed } = loaded;
9
+ const routeIds = a.line === undefined ? undefined : new Set([feed.routes[routeFor(loaded, a.line)]?.id ?? ""]);
10
+ const stopIds = a.station === undefined ? undefined : stopIdsOf(loaded, a.station);
11
+ const nowSeconds = Math.floor(deps.now() / 1000);
12
+ const byRoute = new Map(feed.routes.map((r) => [r.id, r]));
13
+ const byStop = new Map(feed.stops.map((s) => [s.id, s]));
14
+ const list = snapshot.alerts
15
+ .map((alert) => {
16
+ const active = alert.periods.length === 0 || alert.periods.some((p) => (p.start ?? 0) <= nowSeconds && (p.end === undefined || p.end === 0 || p.end >= nowSeconds));
17
+ const upcoming = !active && alert.periods.some((p) => (p.start ?? 0) > nowSeconds);
18
+ return { alert, active, upcoming };
19
+ })
20
+ .filter(({ active, upcoming }) => active || (a.include_upcoming && upcoming))
21
+ .filter(({ alert }) => routeIds === undefined || alert.informed.some((e) => e.route !== undefined && routeIds.has(e.route)))
22
+ .filter(({ alert }) => stopIds === undefined || alert.informed.some((e) => e.stop !== undefined && stopIds.has(e.stop)));
23
+ return {
24
+ alerts: list.slice(0, a.limit).map(({ alert, active }) => {
25
+ const lines = [...new Set(alert.informed.map((e) => byRoute.get(e.route ?? "")?.shortName).filter((x) => x !== undefined))];
26
+ const stops = [...new Set(alert.informed.map((e) => byStop.get(e.stop ?? "")?.name).filter((x) => x !== undefined))];
27
+ const operators = [...new Set(alert.informed.map((e) => feed.agencies.find((g) => g.id === e.agency)?.name).filter((x) => x !== undefined))];
28
+ return {
29
+ id: alert.id,
30
+ in_effect_now: active,
31
+ header: alert.header,
32
+ ...(Object.keys(alert.description).length > 0 ? { description: alert.description } : {}),
33
+ ...(alert.effect ? { effect: alert.effect } : {}),
34
+ ...(alert.cause ? { cause: alert.cause } : {}),
35
+ ...(alert.severity ? { severity: alert.severity } : {}),
36
+ ...(lines.length > 0 ? { lines } : {}),
37
+ ...(stops.length > 0 ? { stops } : {}),
38
+ ...(operators.length > 0 ? { operators } : {}),
39
+ periods: alert.periods.map((p) => ({ from: local(deps.timeZone, p.start), until: local(deps.timeZone, p.end) })),
40
+ ...(Object.keys(alert.url).length > 0 ? { url: Object.values(alert.url)[0] } : {}),
41
+ };
42
+ }),
43
+ matching: list.length,
44
+ published: snapshot.alerts.length,
45
+ read_at: new Date(snapshot.fetchedAt).toISOString(),
46
+ source: "the transport authority's GTFS-Realtime service alerts, read live (at most once a minute)",
47
+ };
48
+ };
49
+ //# sourceMappingURL=alerts.js.map
@@ -0,0 +1,46 @@
1
+ import type { Route } from "../../domain/feed.js";
2
+ import { type Place } from "../../domain/places.js";
3
+ import type { Endpoint, Lane } from "../../domain/raptor.js";
4
+ import type { Deps, Loaded } from "../ports.js";
5
+ /** The calendar date in `timeZone` at `epochMs`, YYYY-MM-DD. */
6
+ export declare const dateIn: (timeZone: string, epochMs: number) => string;
7
+ /** Seconds after midnight in `timeZone` at `epochMs`. */
8
+ export declare const clockIn: (timeZone: string, epochMs: number) => number;
9
+ export declare const todayOf: (deps: Deps) => string;
10
+ /** "08:05" or "8:05" to seconds; undefined for anything else. */
11
+ export declare const secondsOfClock: (text: string) => number | undefined;
12
+ /** Seconds after midnight of `date` as local date and time, YYYY-MM-DDTHH:MM; 25:10 is 01:10 the next day. */
13
+ export declare const stamp: (date: string, seconds: number) => string;
14
+ /** Seconds after midnight as HH:MM, with "+1" for the small hours of the next day. */
15
+ export declare const clock: (seconds: number) => string;
16
+ /** A date argument, default today, inside the feed's calendar. */
17
+ export declare const checkedDate: (deps: Deps, loaded: Loaded, date: string | undefined) => string;
18
+ /** The second of the day to start from: the time given, else now when the date is today, else `fallback`. */
19
+ export declare const startOf: (deps: Deps, date: string, time: string | undefined, fallback?: number) => number;
20
+ /** The service days a day's questions touch: the day before (trips past midnight), the day, the next day. */
21
+ export declare const lanesFor: (loaded: Loaded, date: string) => Lane[];
22
+ export type Where = {
23
+ /** What the argument resolved to, for the answer. */
24
+ readonly name: string;
25
+ readonly places: readonly Place[];
26
+ /** Stops to start from or arrive at, with the walk to or from them. */
27
+ readonly endpoints: readonly Endpoint[];
28
+ readonly point: {
29
+ readonly lat: number;
30
+ readonly lon: number;
31
+ } | undefined;
32
+ };
33
+ /** A place argument: a name, an id from find_station, or "latitude,longitude" (then every stop within a walk). */
34
+ export declare const whereOf: (loaded: Loaded, text: string, role: string) => Where;
35
+ export declare const operatorOf: (loaded: Loaded, route: Route) => string;
36
+ export declare const lineOut: (loaded: Loaded, route: Route) => {
37
+ line: string;
38
+ mode: string;
39
+ operator: string;
40
+ };
41
+ /** Line names in a stable order: metro first, then by number. */
42
+ export declare const lineNames: (loaded: Loaded, routes: readonly number[]) => string[];
43
+ export declare const placeOut: (loaded: Loaded, p: Place) => Record<string, unknown>;
44
+ /** The routes a line argument names: its short name as on the vehicle, "M2", "336", "1"; case and spaces ignored. */
45
+ export declare const routeFor: (loaded: Loaded, text: string) => number;
46
+ export declare const sourceOf: (loaded: Loaded) => string;
@@ -0,0 +1,117 @@
1
+ import { addDays, isIsoDate } from "@foreverworks/mcp-kit";
2
+ import { activeOn, dayAfter, dayBefore } from "../../domain/calendar.js";
3
+ import { fail, inputError, notFound } from "../../domain/errors.js";
4
+ import { MAX_WALK_METRES, metresBetween, streetSeconds } from "../../domain/network.js";
5
+ import { resolvePlace } from "../../domain/places.js";
6
+ /** The calendar date in `timeZone` at `epochMs`, YYYY-MM-DD. */
7
+ export const dateIn = (timeZone, epochMs) => new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).format(new Date(epochMs));
8
+ /** Seconds after midnight in `timeZone` at `epochMs`. */
9
+ export const clockIn = (timeZone, epochMs) => {
10
+ const parts = new Intl.DateTimeFormat("en-GB", { timeZone, hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" }).formatToParts(new Date(epochMs));
11
+ const part = (type) => Number(parts.find((p) => p.type === type)?.value ?? "0");
12
+ return part("hour") * 3600 + part("minute") * 60 + part("second");
13
+ };
14
+ export const todayOf = (deps) => dateIn(deps.timeZone, deps.now());
15
+ /** "08:05" or "8:05" to seconds; undefined for anything else. */
16
+ export const secondsOfClock = (text) => {
17
+ const m = /^(\d{1,2}):(\d{2})$/.exec(text.trim());
18
+ if (m === null || Number(m[1]) > 23 || Number(m[2]) > 59)
19
+ return undefined;
20
+ return Number(m[1]) * 3600 + Number(m[2]) * 60;
21
+ };
22
+ /** Seconds after midnight of `date` as local date and time, YYYY-MM-DDTHH:MM; 25:10 is 01:10 the next day. */
23
+ export const stamp = (date, seconds) => {
24
+ const days = Math.floor(seconds / 86_400);
25
+ const rest = seconds - days * 86_400;
26
+ const hh = String(Math.floor(rest / 3600)).padStart(2, "0");
27
+ const mm = String(Math.floor((rest % 3600) / 60)).padStart(2, "0");
28
+ return `${days === 0 ? date : addDays(date, days)}T${hh}:${mm}`;
29
+ };
30
+ /** Seconds after midnight as HH:MM, with "+1" for the small hours of the next day. */
31
+ export const clock = (seconds) => {
32
+ const days = Math.floor(seconds / 86_400);
33
+ const rest = seconds - days * 86_400;
34
+ return `${String(Math.floor(rest / 3600)).padStart(2, "0")}:${String(Math.floor((rest % 3600) / 60)).padStart(2, "0")}${days > 0 ? ` (+${days} day)` : ""}`;
35
+ };
36
+ /** A date argument, default today, inside the feed's calendar. */
37
+ export const checkedDate = (deps, loaded, date) => {
38
+ const d = date?.trim() || todayOf(deps);
39
+ if (!isIsoDate(d))
40
+ fail(inputError(`date must be a calendar date, YYYY-MM-DD, not "${date ?? ""}"`));
41
+ const { start, end } = loaded.feed.info;
42
+ if ((start !== "" && d < start) || (end !== "" && d > end))
43
+ fail(notFound(`the timetable in use (feed ${loaded.feed.info.version}) covers ${start} to ${end}; ${d} is outside it`));
44
+ return d;
45
+ };
46
+ /** The second of the day to start from: the time given, else now when the date is today, else `fallback`. */
47
+ export const startOf = (deps, date, time, fallback = 0) => {
48
+ if (time !== undefined && time.trim() !== "")
49
+ return secondsOfClock(time) ?? fail(inputError(`time must be HH:MM, 24-hour, not "${time}"`));
50
+ if (date !== todayOf(deps))
51
+ return fallback;
52
+ const now = clockIn(deps.timeZone, deps.now());
53
+ return now - (now % 60);
54
+ };
55
+ /** The service days a day's questions touch: the day before (trips past midnight), the day, the next day. */
56
+ export const lanesFor = (loaded, date) => [
57
+ { offset: -86_400, active: activeOn(loaded.feed, dayBefore(date)) },
58
+ { offset: 0, active: activeOn(loaded.feed, date) },
59
+ { offset: 86_400, active: activeOn(loaded.feed, dayAfter(date)) },
60
+ ];
61
+ const COORDINATES = /^\s*(-?\d{1,2}\.\d+)\s*[,; ]\s*(-?\d{1,3}\.\d+)\s*$/;
62
+ /** A place argument: a name, an id from find_station, or "latitude,longitude" (then every stop within a walk). */
63
+ export const whereOf = (loaded, text, role) => {
64
+ const m = COORDINATES.exec(text);
65
+ if (m !== null) {
66
+ const lat = Number(m[1]);
67
+ const lon = Number(m[2]);
68
+ const { stops } = loaded.feed;
69
+ const endpoints = [];
70
+ stops.forEach((s, i) => {
71
+ if (!loaded.network.boardable[i])
72
+ return;
73
+ const metres = metresBetween(lat, lon, s.lat, s.lon);
74
+ if (metres <= MAX_WALK_METRES * 1.6)
75
+ endpoints.push({ stop: i, seconds: streetSeconds(metres, loaded.network.metro[i] ?? 0) });
76
+ });
77
+ if (endpoints.length === 0)
78
+ fail(notFound(`no stop is within ${Math.round(MAX_WALK_METRES * 1.6)} m of ${lat}, ${lon} (${role})`));
79
+ return { name: `${lat}, ${lon}`, places: [], endpoints, point: { lat, lon } };
80
+ }
81
+ const r = resolvePlace(loaded.places, text);
82
+ switch (r.kind) {
83
+ case "none":
84
+ return fail(inputError(`no stop or station matches ${role} "${text}"; find_station searches by part of a name, without diacritics if you like`));
85
+ case "ambiguous":
86
+ return fail(inputError(`${role} "${text}" matches several places far apart; name one by its id: ${r.candidates.map((p) => `${p.name}${p.detail ? ` (${p.detail})` : ""} = ${p.id}`).join("; ")}`));
87
+ case "found":
88
+ return { name: r.name, places: r.places, endpoints: [...new Set(r.places.flatMap((p) => p.stops))].map((stop) => ({ stop, seconds: 0 })), point: undefined };
89
+ }
90
+ };
91
+ export const operatorOf = (loaded, route) => loaded.feed.agencies.find((a) => a.id === route.agency)?.name ?? route.agency;
92
+ export const lineOut = (loaded, route) => ({ line: route.shortName, mode: route.mode, operator: operatorOf(loaded, route) });
93
+ /** Line names in a stable order: metro first, then by number. */
94
+ export const lineNames = (loaded, routes) => routes
95
+ .map((r) => loaded.feed.routes[r])
96
+ .filter((r) => r !== undefined)
97
+ .sort((a, b) => (a.mode === "metro" ? 0 : 1) - (b.mode === "metro" ? 0 : 1) || a.shortName.localeCompare(b.shortName, "en", { numeric: true }))
98
+ .map((r) => r.shortName);
99
+ export const placeOut = (loaded, p) => ({
100
+ id: p.id,
101
+ name: p.name,
102
+ kind: p.kind,
103
+ lines: lineNames(loaded, p.routes),
104
+ ...(p.detail ? { street: p.detail } : {}),
105
+ lat: Number(p.lat.toFixed(6)),
106
+ lon: Number(p.lon.toFixed(6)),
107
+ });
108
+ /** The routes a line argument names: its short name as on the vehicle, "M2", "336", "1"; case and spaces ignored. */
109
+ export const routeFor = (loaded, text) => {
110
+ const key = text.trim().toLowerCase().replace(/^metro(u)?\s*/, "m").replace(/\s+/g, "");
111
+ const index = loaded.feed.routes.findIndex((r) => r.shortName.toLowerCase().replace(/\s+/g, "") === key);
112
+ if (index < 0)
113
+ fail(notFound(`no line is called "${text}"; metro lines are M1 to M5, surface lines go by their number`));
114
+ return index;
115
+ };
116
+ export const sourceOf = (loaded) => `TPBI GTFS feed ${loaded.feed.info.version} (${loaded.feed.info.start} to ${loaded.feed.info.end}), published by ${loaded.feed.info.publisher || "the transport authority"} for ADTPBI`;
117
+ //# sourceMappingURL=common.js.map
@@ -0,0 +1,12 @@
1
+ import type { Deps, Loaded } from "../ports.js";
2
+ export declare const findStation: (deps: Deps, a: {
3
+ query: string;
4
+ limit: number;
5
+ kind?: "metro" | "surface" | undefined;
6
+ }) => Promise<Record<string, unknown>>;
7
+ export declare const station: (deps: Deps, a: {
8
+ station: string;
9
+ date?: string | undefined;
10
+ }) => Promise<Record<string, unknown>>;
11
+ /** Every place a stop id or a name of a place belongs to, for filters. */
12
+ export declare const stopIdsOf: (loaded: Loaded, text: string) => Set<string>;
@@ -0,0 +1,128 @@
1
+ import { dayTypes, activeOn } from "../../domain/calendar.js";
2
+ import { metresBetween } from "../../domain/network.js";
3
+ import { searchPlaces } from "../../domain/places.js";
4
+ import { firstAndLast } from "../../domain/schedule.js";
5
+ import { checkedDate, clock, lineNames, lineOut, placeOut, sourceOf, todayOf, whereOf } from "./common.js";
6
+ export const findStation = async (deps, a) => {
7
+ const loaded = await deps.feed.loaded();
8
+ const coordinates = /^\s*(-?\d{1,2}\.\d+)\s*[,; ]\s*(-?\d{1,3}\.\d+)\s*$/.exec(a.query);
9
+ if (coordinates !== null) {
10
+ const lat = Number(coordinates[1]);
11
+ const lon = Number(coordinates[2]);
12
+ const near = loaded.places
13
+ .filter((p) => a.kind === undefined || p.kind === a.kind)
14
+ .map((p) => ({ p, metres: Math.round(metresBetween(lat, lon, p.lat, p.lon)) }))
15
+ .filter((x) => x.metres <= 1000)
16
+ .sort((x, y) => x.metres - y.metres)
17
+ .slice(0, a.limit);
18
+ return { query: a.query, places: near.map((x) => ({ ...placeOut(loaded, x.p), metres_away: x.metres })) };
19
+ }
20
+ const matches = searchPlaces(loaded.places, a.query).filter((m) => a.kind === undefined || m.place.kind === a.kind);
21
+ return {
22
+ query: a.query,
23
+ places: matches.slice(0, a.limit).map((m) => {
24
+ const out = placeOut(loaded, m.place);
25
+ const claimed = claimedLines(m.place.name);
26
+ const lines = out["lines"];
27
+ const mismatch = m.place.kind === "metro" && claimed.length > 0 && !claimed.some((c) => lines.includes(c));
28
+ return { ...out, match: m.score >= 100 ? "exact" : m.score >= 60 ? "partial" : "spelling", ...(mismatch ? { feed_note: `the feed names this hall "${m.place.name}", but its timetable has ${lines.join(", ")} trains calling here` } : {}) };
29
+ }),
30
+ ...(matches.length === 0 ? { hint: "nothing matched: try fewer words, or part of the name (\"unirii\", \"gara\")" } : {}),
31
+ };
32
+ };
33
+ const WAYS = { 1: "walkway", 2: "stairs", 3: "moving walkway", 4: "escalator", 5: "elevator", 6: "fare gate", 7: "exit gate" };
34
+ /** Lines a platform's name claims ("Piața Victoriei 1 (M1)") that do not call there: the feed's names and its trips disagree. */
35
+ const claimedLines = (name) => [...name.matchAll(/\(([^)]*)\)/g)].flatMap((m) => (m[1] ?? "").split("/")).map((x) => x.trim().toUpperCase()).map((x) => (/^\d+$/.test(x) ? `M${x}` : x)).filter((x) => /^M\d$/.test(x));
36
+ export const station = async (deps, a) => {
37
+ const loaded = await deps.feed.loaded();
38
+ const where = whereOf(loaded, a.station, "station");
39
+ const { feed, network } = loaded;
40
+ const stops = [...new Set(where.endpoints.map((e) => e.stop))];
41
+ const stations = [...new Set(where.places.flatMap((p) => p.stations))];
42
+ const platforms = stops.map((s) => {
43
+ const stop = feed.stops[s];
44
+ const lines = lineNames(loaded, [...new Set((network.patternsAt[s] ?? []).map((x) => network.patterns[x.pattern]?.route ?? -1))].filter((r) => r >= 0));
45
+ const towards = [...new Set((network.patternsAt[s] ?? []).filter((x) => x.position < (network.patterns[x.pattern]?.stops.length ?? 0) - 1).map((x) => network.patterns[x.pattern]?.headsign ?? ""))].filter((h) => h !== "");
46
+ const claimed = claimedLines(stop?.name ?? "");
47
+ const mismatch = claimed.length > 0 && network.metro[s] && !claimed.some((c) => lines.includes(c));
48
+ return {
49
+ id: stop?.id,
50
+ name: stop?.name,
51
+ ...(stop?.platformCode ? { platform: stop.platformCode } : {}),
52
+ ...(stop?.desc ? { street: stop.desc } : {}),
53
+ lines,
54
+ towards,
55
+ ...(stop?.level ? { level: feed.levels.get(stop.level)?.name ?? stop.level } : {}),
56
+ ...(mismatch ? { feed_note: `the feed names this platform "${stop?.name}", but its timetable has ${lines.join(", ")} trains calling here` } : {}),
57
+ };
58
+ });
59
+ const children = (parents) => feed.stops.flatMap((s, i) => (parents.includes(s.parent) ? [i] : []));
60
+ const entrances = children(stations)
61
+ .filter((i) => feed.stops[i]?.kind === "entrance")
62
+ .map((i) => {
63
+ const e = feed.stops[i];
64
+ const touching = feed.pathways.filter((p) => p.from === i || p.to === i);
65
+ const ways = [...new Set(touching.map((p) => `${WAYS[p.mode] ?? "path"}${!p.bidirectional && (p.mode === 4 || p.mode === 3) ? (p.to === i ? " (up to the street only)" : " (down only)") : ""}`))];
66
+ return {
67
+ id: e?.id,
68
+ name: e?.name,
69
+ ...(e?.desc ? { street: e.desc } : {}),
70
+ lat: e?.lat,
71
+ lon: e?.lon,
72
+ ways,
73
+ ...(e?.level ? { level: feed.levels.get(e.level)?.name ?? e.level } : {}),
74
+ };
75
+ });
76
+ const amenityStops = new Set([...stations, ...stops, ...children(stations)]);
77
+ const amenities = [...new Set(feed.amenities.filter((x) => amenityStops.has(x.stop)).map((x) => `${x.type}${x.available ? "" : " (out of service)"}`))];
78
+ const levels = [...new Set([...amenityStops].map((i) => feed.stops[i]?.level ?? "").filter((l) => l !== ""))]
79
+ .map((l) => feed.levels.get(l))
80
+ .filter((l) => l !== undefined)
81
+ .sort((x, y) => x.index - y.index)
82
+ .map((l) => l.name);
83
+ const from = a.date === undefined ? todayOf(deps) : checkedDate(deps, loaded, a.date);
84
+ const days = dayTypes(from).filter((d) => d.date <= loaded.feed.info.end);
85
+ const service = Object.fromEntries(days.map((d) => [
86
+ d.name,
87
+ {
88
+ date: d.date,
89
+ departures: firstAndLast(network, stops, activeOn(feed, d.date))
90
+ .map((x) => {
91
+ const route = feed.routes[x.route];
92
+ return { ...(route === undefined ? {} : lineOut(loaded, route)), towards: x.headsign, from: feed.stops[x.stop]?.name, first: clock(x.first), last: clock(x.last), trips: x.count };
93
+ })
94
+ .sort((x, y) => String(x.line).localeCompare(String(y.line), "en", { numeric: true }) || String(x.towards).localeCompare(String(y.towards))),
95
+ },
96
+ ]));
97
+ return {
98
+ name: where.name,
99
+ places: where.places.map((p) => p.id),
100
+ lines: lineNames(loaded, [...new Set(where.places.flatMap((p) => p.routes))]),
101
+ platforms,
102
+ ...(entrances.length > 0 ? { entrances } : {}),
103
+ ...(levels.length > 0 ? { levels } : {}),
104
+ ...(amenities.length > 0 ? { amenities } : {}),
105
+ first_and_last: service,
106
+ source: sourceOf(loaded),
107
+ };
108
+ };
109
+ /** Every place a stop id or a name of a place belongs to, for filters. */
110
+ export const stopIdsOf = (loaded, text) => {
111
+ const where = whereOf(loaded, text, "station");
112
+ const ids = new Set();
113
+ for (const e of where.endpoints) {
114
+ const s = loaded.feed.stops[e.stop];
115
+ if (s === undefined)
116
+ continue;
117
+ ids.add(s.id);
118
+ const parent = loaded.feed.stops[s.parent];
119
+ if (parent !== undefined)
120
+ ids.add(parent.id);
121
+ }
122
+ for (const p of where.places)
123
+ for (const st of p.stations)
124
+ ids.add(loaded.feed.stops[st]?.id ?? "");
125
+ ids.delete("");
126
+ return ids;
127
+ };
128
+ //# sourceMappingURL=places.js.map
@@ -0,0 +1,13 @@
1
+ import type { Deps } from "../ports.js";
2
+ type Args = {
3
+ from: string;
4
+ to: string;
5
+ date?: string | undefined;
6
+ depart_at?: string | undefined;
7
+ arrive_by?: string | undefined;
8
+ modes: "all" | "metro";
9
+ max_transfers: number;
10
+ limit: number;
11
+ };
12
+ export declare const route: (deps: Deps, a: Args) => Promise<Record<string, unknown>>;
13
+ export {};