gtfs-to-html 2.7.2 → 2.8.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 (93) hide show
  1. package/dist/app/index.d.ts +2 -0
  2. package/dist/app/index.js +1846 -0
  3. package/dist/app/index.js.map +1 -0
  4. package/dist/bin/gtfs-to-html.d.ts +1 -0
  5. package/dist/bin/gtfs-to-html.js +2222 -0
  6. package/dist/bin/gtfs-to-html.js.map +1 -0
  7. package/dist/index.d.ts +23 -0
  8. package/dist/index.js +2165 -0
  9. package/dist/index.js.map +1 -0
  10. package/package.json +23 -8
  11. package/.eslintrc.json +0 -28
  12. package/.husky/pre-commit +0 -4
  13. package/CHANGELOG.md +0 -1018
  14. package/app/index.js +0 -138
  15. package/bin/gtfs-to-html.js +0 -48
  16. package/config-sample.json +0 -59
  17. package/docker/Dockerfile +0 -14
  18. package/docker/README.md +0 -5
  19. package/docker/docker-compose.yml +0 -10
  20. package/examples/stop_attributes.txt +0 -6
  21. package/examples/timetable_notes.txt +0 -8
  22. package/examples/timetable_notes_references.txt +0 -8
  23. package/examples/timetable_pages.txt +0 -3
  24. package/examples/timetable_stop_order.txt +0 -16
  25. package/examples/timetables.txt +0 -9
  26. package/index.js +0 -1
  27. package/lib/file-utils.js +0 -202
  28. package/lib/formatters.js +0 -518
  29. package/lib/geojson-utils.js +0 -96
  30. package/lib/gtfs-to-html.js +0 -214
  31. package/lib/log-utils.js +0 -215
  32. package/lib/template-functions.js +0 -192
  33. package/lib/time-utils.js +0 -90
  34. package/lib/utils.js +0 -1702
  35. package/views/default/css/overview_styles.css +0 -197
  36. package/views/default/css/timetable_pdf_styles.css +0 -7
  37. package/views/default/css/timetable_styles.css +0 -447
  38. package/views/default/formatting_functions.pug +0 -113
  39. package/views/default/js/system-map.js +0 -594
  40. package/views/default/js/timetable-map.js +0 -358
  41. package/views/default/js/timetable-menu.js +0 -63
  42. package/views/default/layout.pug +0 -11
  43. package/views/default/overview.pug +0 -27
  44. package/views/default/overview_full.pug +0 -16
  45. package/views/default/timetable_continuation_as.pug +0 -7
  46. package/views/default/timetable_continuation_from.pug +0 -7
  47. package/views/default/timetable_horizontal.pug +0 -42
  48. package/views/default/timetable_hourly.pug +0 -30
  49. package/views/default/timetable_menu.pug +0 -48
  50. package/views/default/timetable_note_symbol.pug +0 -5
  51. package/views/default/timetable_stop_name.pug +0 -13
  52. package/views/default/timetable_stoptime.pug +0 -17
  53. package/views/default/timetable_vertical.pug +0 -67
  54. package/views/default/timetablepage.pug +0 -66
  55. package/views/default/timetablepage_full.pug +0 -22
  56. package/www/README.md +0 -33
  57. package/www/babel.config.js +0 -3
  58. package/www/blog/2020-07-07-New-Documentation.md +0 -12
  59. package/www/blog/2020-08-20-Version-1.0.0.md +0 -29
  60. package/www/blog/2021-11-06-CSV-Export.md +0 -26
  61. package/www/docs/additional-files.md +0 -24
  62. package/www/docs/configuration.md +0 -568
  63. package/www/docs/current-usage.md +0 -48
  64. package/www/docs/custom-templates.md +0 -13
  65. package/www/docs/introduction.md +0 -39
  66. package/www/docs/logging-sql-queries.md +0 -12
  67. package/www/docs/previewing-html-output.md +0 -24
  68. package/www/docs/processing-large-gtfs.md +0 -10
  69. package/www/docs/quick-start.md +0 -136
  70. package/www/docs/related-libraries.md +0 -54
  71. package/www/docs/reviewing-changes.md +0 -29
  72. package/www/docs/stop-attributes.md +0 -30
  73. package/www/docs/support.md +0 -12
  74. package/www/docs/timetable-notes-references.md +0 -44
  75. package/www/docs/timetable-notes.md +0 -33
  76. package/www/docs/timetable-pages.md +0 -37
  77. package/www/docs/timetable-stop-order.md +0 -63
  78. package/www/docs/timetables.md +0 -64
  79. package/www/docusaurus.config.js +0 -104
  80. package/www/package.json +0 -21
  81. package/www/sidebars.js +0 -10
  82. package/www/src/css/custom.css +0 -25
  83. package/www/src/pages/index.js +0 -270
  84. package/www/src/pages/styles.module.css +0 -53
  85. package/www/static/.nojekyll +0 -0
  86. package/www/static/img/favicon.ico +0 -0
  87. package/www/static/img/gtfs-to-html-logo.svg +0 -18
  88. package/www/static/img/overview-example.jpg +0 -0
  89. package/www/static/img/timetable-example.jpg +0 -0
  90. package/www/static/img/undraw_happy_music.svg +0 -1
  91. package/www/static/img/undraw_proud_coder.svg +0 -1
  92. package/www/static/img/undraw_spreadsheets.svg +0 -1
  93. package/www/yarn.lock +0 -8351
@@ -0,0 +1,1846 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/app/index.ts
8
+ import path2 from "node:path";
9
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
10
+ import { readFileSync } from "node:fs";
11
+ import { map } from "lodash-es";
12
+ import yargs from "yargs";
13
+ import { hideBin } from "yargs/helpers";
14
+ import { openDb as openDb2 } from "gtfs";
15
+ import express from "express";
16
+ import logger from "morgan";
17
+ import untildify2 from "untildify";
18
+
19
+ // src/lib/formatters.ts
20
+ import {
21
+ clone,
22
+ find as find2,
23
+ first as first2,
24
+ groupBy as groupBy2,
25
+ last as last2,
26
+ omit,
27
+ sortBy as sortBy2,
28
+ zipObject
29
+ } from "lodash-es";
30
+ import moment3 from "moment";
31
+
32
+ // src/lib/time-utils.ts
33
+ import moment from "moment";
34
+ function fromGTFSTime(timeString) {
35
+ const duration = moment.duration(timeString);
36
+ return moment({
37
+ hour: duration.hours(),
38
+ minute: duration.minutes(),
39
+ second: duration.seconds()
40
+ });
41
+ }
42
+ function toGTFSTime(time) {
43
+ return time.format("HH:mm:ss");
44
+ }
45
+ function fromGTFSDate(gtfsDate) {
46
+ return moment(gtfsDate, "YYYYMMDD");
47
+ }
48
+ function toGTFSDate(date) {
49
+ return moment(date).format("YYYYMMDD");
50
+ }
51
+ function calendarToCalendarCode(c) {
52
+ if (c.service_id) {
53
+ return c.service_id;
54
+ }
55
+ return `${c.monday}${c.tuesday}${c.wednesday}${c.thursday}${c.friday}${c.saturday}${c.sunday}`;
56
+ }
57
+ function calendarCodeToCalendar(code) {
58
+ const days2 = [
59
+ "monday",
60
+ "tuesday",
61
+ "wednesday",
62
+ "thursday",
63
+ "friday",
64
+ "saturday",
65
+ "sunday"
66
+ ];
67
+ const calendar = {};
68
+ for (const [index, day] of days2.entries()) {
69
+ calendar[day] = code[index];
70
+ }
71
+ return calendar;
72
+ }
73
+ function secondsAfterMidnight(timeString) {
74
+ return moment.duration(timeString).asSeconds();
75
+ }
76
+ function minutesAfterMidnight(timeString) {
77
+ return moment.duration(timeString).asMinutes();
78
+ }
79
+ function updateTimeByOffset(timeString, offsetSeconds) {
80
+ const newTime = fromGTFSTime(timeString);
81
+ return toGTFSTime(newTime.add(offsetSeconds, "seconds"));
82
+ }
83
+
84
+ // src/lib/utils.ts
85
+ import {
86
+ cloneDeep,
87
+ compact,
88
+ countBy,
89
+ entries,
90
+ every as every2,
91
+ find,
92
+ findLast,
93
+ first,
94
+ flatMap as flatMap2,
95
+ flattenDeep,
96
+ flow,
97
+ isEqual,
98
+ groupBy,
99
+ head,
100
+ last,
101
+ maxBy,
102
+ partialRight,
103
+ reduce,
104
+ size,
105
+ some,
106
+ sortBy,
107
+ uniq,
108
+ uniqBy,
109
+ zip
110
+ } from "lodash-es";
111
+ import {
112
+ getCalendarDates,
113
+ getTrips,
114
+ getTimetableNotesReferences,
115
+ getTimetableNotes,
116
+ getRoutes,
117
+ getCalendars,
118
+ getTimetableStopOrders,
119
+ getStops,
120
+ getStopAttributes,
121
+ getStoptimes,
122
+ getFrequencies,
123
+ getTimetables,
124
+ getTimetablePages,
125
+ getAgencies,
126
+ openDb
127
+ } from "gtfs";
128
+ import { stringify } from "csv-stringify";
129
+ import moment2 from "moment";
130
+ import sqlString from "sqlstring";
131
+ import toposort from "toposort";
132
+
133
+ // src/lib/file-utils.ts
134
+ import path from "node:path";
135
+ import { fileURLToPath } from "node:url";
136
+ import copydir from "copy-dir";
137
+ import _ from "lodash-es";
138
+ import archiver from "archiver";
139
+ import beautify from "js-beautify";
140
+ import { renderFile } from "pug";
141
+ import puppeteer from "puppeteer";
142
+ import sanitize from "sanitize-filename";
143
+ import untildify from "untildify";
144
+ import insane from "insane";
145
+ import { marked } from "marked";
146
+
147
+ // src/lib/template-functions.ts
148
+ var template_functions_exports = {};
149
+ __export(template_functions_exports, {
150
+ formatHtmlId: () => formatHtmlId,
151
+ formatTripName: () => formatTripName,
152
+ formatTripNameForCSV: () => formatTripNameForCSV,
153
+ getNotesForStop: () => getNotesForStop,
154
+ getNotesForStoptime: () => getNotesForStoptime,
155
+ getNotesForTimetableLabel: () => getNotesForTimetableLabel,
156
+ getNotesForTrip: () => getNotesForTrip,
157
+ hasNotesOrNotices: () => hasNotesOrNotices,
158
+ timetableHasDifferentDays: () => timetableHasDifferentDays,
159
+ timetablePageHasDifferentDays: () => timetablePageHasDifferentDays,
160
+ timetablePageHasDifferentLabels: () => timetablePageHasDifferentLabels
161
+ });
162
+ import { every } from "lodash-es";
163
+ function formatHtmlId(id) {
164
+ return id.replace(/([^\w[\]{}.:-])\s?/g, "");
165
+ }
166
+ function timetableHasDifferentDays(timetable) {
167
+ return !every(timetable.orderedTrips, (trip, idx) => {
168
+ if (idx === 0) {
169
+ return true;
170
+ }
171
+ return trip.dayList === timetable.orderedTrips[idx - 1].dayList;
172
+ });
173
+ }
174
+ function timetablePageHasDifferentDays(timetablePage) {
175
+ return !every(timetablePage.consolidatedTimetables, (timetable, idx) => {
176
+ if (idx === 0) {
177
+ return true;
178
+ }
179
+ return timetable.dayListLong === timetablePage.consolidatedTimetables[idx - 1].dayListLong;
180
+ });
181
+ }
182
+ function timetablePageHasDifferentLabels(timetablePage) {
183
+ return !every(timetablePage.consolidatedTimetables, (timetable, idx) => {
184
+ if (idx === 0) {
185
+ return true;
186
+ }
187
+ return timetable.timetable_label === timetablePage.consolidatedTimetables[idx - 1].timetable_label;
188
+ });
189
+ }
190
+ function hasNotesOrNotices(timetable) {
191
+ return timetable.requestPickupSymbolUsed || timetable.noPickupSymbolUsed || timetable.requestDropoffSymbolUsed || timetable.noDropoffSymbolUsed || timetable.noServiceSymbolUsed || timetable.interpolatedStopSymbolUsed || timetable.notes.length > 0;
192
+ }
193
+ function getNotesForTimetableLabel(notes) {
194
+ return notes.filter((note) => !note.stop_id && !note.trip_id);
195
+ }
196
+ function getNotesForStop(notes, stop) {
197
+ return notes.filter((note) => {
198
+ if (note.trip_id) {
199
+ return false;
200
+ }
201
+ if (note.stop_sequence && !stop.trips.some((trip) => trip.stop_sequence === note.stop_sequence)) {
202
+ return false;
203
+ }
204
+ return note.stop_id === stop.stop_id;
205
+ });
206
+ }
207
+ function getNotesForTrip(notes, trip) {
208
+ return notes.filter((note) => {
209
+ if (note.stop_id) {
210
+ return false;
211
+ }
212
+ return note.trip_id === trip.trip_id;
213
+ });
214
+ }
215
+ function getNotesForStoptime(notes, stoptime) {
216
+ return notes.filter((note) => {
217
+ if (!note.trip_id && note.stop_id === stoptime.stop_id && note.show_on_stoptime === 1) {
218
+ return true;
219
+ }
220
+ if (!note.stop_id && note.trip_id === stoptime.trip_id && note.show_on_stoptime === 1) {
221
+ return true;
222
+ }
223
+ return note.trip_id === stoptime.trip_id && note.stop_id === stoptime.stop_id;
224
+ });
225
+ }
226
+ function formatTripName(trip, index, timetable) {
227
+ let tripName;
228
+ if (timetable.routes.length > 1) {
229
+ tripName = trip.route_short_name;
230
+ } else if (timetable.orientation === "horizontal") {
231
+ if (trip.trip_short_name) {
232
+ tripName = trip.trip_short_name;
233
+ } else {
234
+ tripName = `Run #${index + 1}`;
235
+ }
236
+ }
237
+ if (timetableHasDifferentDays(timetable)) {
238
+ tripName += ` ${trip.dayList}`;
239
+ }
240
+ return tripName;
241
+ }
242
+ function formatTripNameForCSV(trip, timetable) {
243
+ let tripName = "";
244
+ if (timetable.routes.length > 1) {
245
+ tripName += `${trip.route_short_name} - `;
246
+ }
247
+ if (trip.trip_short_name) {
248
+ tripName += trip.trip_short_name;
249
+ } else {
250
+ tripName += trip.trip_id;
251
+ }
252
+ if (trip.trip_headsign) {
253
+ tripName += ` - ${trip.trip_headsign}`;
254
+ }
255
+ if (timetableHasDifferentDays(timetable)) {
256
+ tripName += ` - ${trip.dayList}`;
257
+ }
258
+ return tripName;
259
+ }
260
+
261
+ // src/lib/file-utils.ts
262
+ function getTemplatePath(templateFileName, config2) {
263
+ let fullTemplateFileName = templateFileName;
264
+ if (config2.noHead !== true) {
265
+ fullTemplateFileName += "_full";
266
+ }
267
+ const templatePath = config2.templatePath === void 0 ? path.join(fileURLToPath(import.meta.url), "../../../views/default") : untildify(config2.templatePath);
268
+ return path.join(templatePath, `${fullTemplateFileName}.pug`);
269
+ }
270
+ function generateFileName(timetable, config2, extension = "html") {
271
+ let filename = timetable.timetable_id;
272
+ for (const route of timetable.routes) {
273
+ filename += isNullOrEmpty(route.route_short_name) ? `_${route.route_long_name.replace(/\s/g, "-")}` : `_${route.route_short_name.replace(/\s/g, "-")}`;
274
+ }
275
+ if (!isNullOrEmpty(timetable.direction_id)) {
276
+ filename += `_${timetable.direction_id}`;
277
+ }
278
+ filename += `_${formatDays(timetable, config2).replace(/\s/g, "")}.${extension}`;
279
+ return sanitize(filename).toLowerCase();
280
+ }
281
+ async function renderTemplate(templateFileName, templateVars, config2) {
282
+ const templatePath = getTemplatePath(templateFileName, config2);
283
+ const html = await renderFile(templatePath, {
284
+ _,
285
+ md: (text) => insane(marked.parseInline(text)),
286
+ ...template_functions_exports,
287
+ formatRouteColor,
288
+ formatRouteTextColor,
289
+ ...templateVars
290
+ });
291
+ if (config2.beautify === true) {
292
+ return beautify.html_beautify(html, {
293
+ indent_size: 2
294
+ });
295
+ }
296
+ return html;
297
+ }
298
+
299
+ // src/lib/geojson-utils.ts
300
+ import { getShapesAsGeoJSON, getStopsAsGeoJSON } from "gtfs";
301
+ import { flatMap } from "lodash-es";
302
+ import simplify from "@turf/simplify";
303
+ import { featureCollection, round } from "@turf/helpers";
304
+ var mergeGeojson = (...geojsons) => featureCollection(flatMap(geojsons, (geojson) => geojson.features));
305
+ var truncateGeoJSONDecimals = (geojson, config2) => {
306
+ for (const feature of geojson.features) {
307
+ if (feature.geometry.coordinates) {
308
+ if (feature.geometry.type.toLowerCase() === "point") {
309
+ feature.geometry.coordinates = feature.geometry.coordinates.map(
310
+ (number) => round(number, config2.coordinatePrecision)
311
+ );
312
+ } else if (feature.geometry.type.toLowerCase() === "linestring") {
313
+ feature.geometry.coordinates = feature.geometry.coordinates.map(
314
+ (coordinate) => coordinate.map(
315
+ (number) => round(number, config2.coordinatePrecision)
316
+ )
317
+ );
318
+ } else if (feature.geometry.type.toLowerCase() === "multilinestring") {
319
+ feature.geometry.coordinates = feature.geometry.coordinates.map(
320
+ (linestring) => linestring.map(
321
+ (coordinate) => coordinate.map(
322
+ (number) => round(number, config2.coordinatePrecision)
323
+ )
324
+ )
325
+ );
326
+ }
327
+ }
328
+ }
329
+ return geojson;
330
+ };
331
+ var simplifyGeoJSON = (geojson, config2) => {
332
+ try {
333
+ const simplifiedGeojson = simplify(geojson, {
334
+ tolerance: 1 / 10 ** config2.coordinatePrecision,
335
+ highQuality: true
336
+ });
337
+ return truncateGeoJSONDecimals(simplifiedGeojson, config2);
338
+ } catch {
339
+ config2.logWarning("Unable to simplify geojson");
340
+ return truncateGeoJSONDecimals(geojson, config2);
341
+ }
342
+ };
343
+ function getTimetableGeoJSON(timetable, config2) {
344
+ const shapesGeojsons = timetable.route_ids.map(
345
+ (routeId) => getShapesAsGeoJSON({
346
+ route_id: routeId,
347
+ direction_id: timetable.direction_id,
348
+ trip_id: timetable.orderedTrips.map((trip) => trip.trip_id)
349
+ })
350
+ );
351
+ const stopsGeojsons = timetable.route_ids.map(
352
+ (routeId) => getStopsAsGeoJSON({
353
+ route_id: routeId,
354
+ direction_id: timetable.direction_id,
355
+ trip_id: timetable.orderedTrips.map((trip) => trip.trip_id)
356
+ })
357
+ );
358
+ const geojson = mergeGeojson(...shapesGeojsons, ...stopsGeojsons);
359
+ return simplifyGeoJSON(geojson, config2);
360
+ }
361
+ function getAgencyGeoJSON(config2) {
362
+ const shapesGeojsons = getShapesAsGeoJSON();
363
+ const stopsGeojsons = getStopsAsGeoJSON();
364
+ const geojson = mergeGeojson(shapesGeojsons, stopsGeojsons);
365
+ return simplifyGeoJSON(geojson, config2);
366
+ }
367
+
368
+ // package.json
369
+ var version = "2.8.0";
370
+
371
+ // src/lib/utils.ts
372
+ var isTimepoint = (stoptime) => {
373
+ if (isNullOrEmpty(stoptime.timepoint)) {
374
+ return !isNullOrEmpty(stoptime.arrival_time) && !isNullOrEmpty(stoptime.departure_time);
375
+ }
376
+ return stoptime.timepoint === 1;
377
+ };
378
+ var getLongestTripStoptimes = (trips, config2) => {
379
+ const filteredTripStoptimes = trips.map(
380
+ (trip) => trip.stoptimes.filter((stoptime) => {
381
+ if (config2.showOnlyTimepoint === true) {
382
+ return isTimepoint(stoptime);
383
+ }
384
+ return true;
385
+ })
386
+ );
387
+ return maxBy(filteredTripStoptimes, (stoptimes) => size(stoptimes));
388
+ };
389
+ var findCommonStopId = (trips, config2) => {
390
+ const longestTripStoptimes = getLongestTripStoptimes(trips, config2);
391
+ if (!longestTripStoptimes) {
392
+ return null;
393
+ }
394
+ const commonStoptime = longestTripStoptimes.find((stoptime, idx) => {
395
+ if (idx === 0 && stoptime.stop_id === last(longestTripStoptimes).stop_id) {
396
+ return false;
397
+ }
398
+ if (isNullOrEmpty(stoptime.arrival_time)) {
399
+ return false;
400
+ }
401
+ return every2(
402
+ trips,
403
+ (trip) => trip.stoptimes.find(
404
+ (tripStoptime) => tripStoptime.stop_id === stoptime.stop_id && tripStoptime.arrival_time !== null
405
+ )
406
+ );
407
+ });
408
+ return commonStoptime ? commonStoptime.stop_id : null;
409
+ };
410
+ var deduplicateTrips = (trips, commonStopId) => {
411
+ const deduplicatedTrips = [];
412
+ for (const trip of trips) {
413
+ if (deduplicatedTrips.length === 0 || trip.stoptimes.length === 0) {
414
+ deduplicatedTrips.push(trip);
415
+ continue;
416
+ }
417
+ const stoptimes = trip.stoptimes.map((stoptime) => stoptime.departure_time);
418
+ const selectedStoptime = commonStopId ? find(trip.stoptimes, {
419
+ stop_id: commonStopId
420
+ }) : trip.stoptimes[0];
421
+ const similarTrips = deduplicatedTrips.filter((trip2) => {
422
+ const stoptime = find(trip2.stoptimes, {
423
+ stop_id: selectedStoptime.stop_id
424
+ });
425
+ if (!stoptime) {
426
+ return false;
427
+ }
428
+ return stoptime.departure_time === selectedStoptime.departure_time;
429
+ });
430
+ const tripIsUnique = every2(similarTrips, (similarTrip) => {
431
+ const similarTripStoptimes = similarTrip.stoptimes.map(
432
+ (stoptime) => stoptime.departure_time
433
+ );
434
+ return !isEqual(stoptimes, similarTripStoptimes);
435
+ });
436
+ if (tripIsUnique) {
437
+ deduplicatedTrips.push(trip);
438
+ }
439
+ }
440
+ return deduplicatedTrips;
441
+ };
442
+ var sortTrips = (trips, config2) => {
443
+ let sortedTrips;
444
+ let commonStopId;
445
+ if (config2.sortingAlgorithm === "common") {
446
+ commonStopId = findCommonStopId(trips, config2);
447
+ if (commonStopId) {
448
+ sortedTrips = sortTripsByStoptimeAtStop(trips, commonStopId);
449
+ } else {
450
+ sortedTrips = sortTrips(trips, {
451
+ ...config2,
452
+ sortingAlgorithm: "beginning"
453
+ });
454
+ }
455
+ } else if (config2.sortingAlgorithm === "beginning") {
456
+ for (const trip of trips) {
457
+ if (trip.stoptimes.length === 0) {
458
+ continue;
459
+ }
460
+ trip.firstStoptime = timeToSeconds(first(trip.stoptimes).departure_time);
461
+ trip.lastStoptime = timeToSeconds(last(trip.stoptimes).departure_time);
462
+ }
463
+ sortedTrips = sortBy(
464
+ trips,
465
+ ["firstStoptime", "lastStoptime"],
466
+ ["asc", "asc"]
467
+ );
468
+ } else if (config2.sortingAlgorithm === "end") {
469
+ for (const trip of trips) {
470
+ if (trip.stoptimes.length === 0) {
471
+ continue;
472
+ }
473
+ trip.firstStoptime = timeToSeconds(first(trip.stoptimes).departure_time);
474
+ trip.lastStoptime = timeToSeconds(last(trip.stoptimes).departure_time);
475
+ }
476
+ sortedTrips = sortBy(
477
+ trips,
478
+ ["lastStoptime", "firstStoptime"],
479
+ ["asc", "asc"]
480
+ );
481
+ } else if (config2.sortingAlgorithm === "first") {
482
+ const longestTripStoptimes = getLongestTripStoptimes(trips, config2);
483
+ const firstStopId = first(longestTripStoptimes).stop_id;
484
+ sortedTrips = sortTripsByStoptimeAtStop(trips, firstStopId);
485
+ } else if (config2.sortingAlgorithm === "last") {
486
+ const longestTripStoptimes = getLongestTripStoptimes(trips, config2);
487
+ const lastStopId = last(longestTripStoptimes).stop_id;
488
+ sortedTrips = sortTripsByStoptimeAtStop(trips, lastStopId);
489
+ }
490
+ return deduplicateTrips(sortedTrips, commonStopId);
491
+ };
492
+ var sortTripsByStoptimeAtStop = (trips, stopId) => sortBy(trips, (trip) => {
493
+ const stoptime = find(trip.stoptimes, { stop_id: stopId });
494
+ return stoptime ? timeToSeconds(stoptime.departure_time) : void 0;
495
+ });
496
+ var getCalendarDatesForTimetable = (timetable, config2) => {
497
+ const calendarDates = getCalendarDates(
498
+ {
499
+ service_id: timetable.service_ids
500
+ },
501
+ [],
502
+ [["date", "ASC"]]
503
+ );
504
+ const start = fromGTFSDate(timetable.start_date);
505
+ const end = fromGTFSDate(timetable.end_date);
506
+ const excludedDates = [];
507
+ const includedDates = [];
508
+ for (const calendarDate of calendarDates) {
509
+ if (moment2(calendarDate.date, "YYYYMMDD").isBetween(start, end)) {
510
+ if (calendarDate.exception_type === 1) {
511
+ includedDates.push(formatDate(calendarDate, config2.dateFormat));
512
+ } else if (calendarDate.exception_type === 2) {
513
+ excludedDates.push(formatDate(calendarDate, config2.dateFormat));
514
+ }
515
+ }
516
+ }
517
+ const includedAndExcludedDates = excludedDates.filter(
518
+ (date) => includedDates.includes(date)
519
+ );
520
+ return {
521
+ excludedDates: excludedDates.filter(
522
+ (date) => !includedAndExcludedDates.includes(date)
523
+ ),
524
+ includedDates: includedDates.filter(
525
+ (date) => !includedAndExcludedDates.includes(date)
526
+ )
527
+ };
528
+ };
529
+ var getDaysFromCalendars = (calendars) => {
530
+ const days2 = {
531
+ monday: 0,
532
+ tuesday: 0,
533
+ wednesday: 0,
534
+ thursday: 0,
535
+ friday: 0,
536
+ saturday: 0,
537
+ sunday: 0
538
+ };
539
+ for (const calendar of calendars) {
540
+ for (const [day, value] of Object.entries(days2)) {
541
+ days2[day] = value | calendar[day];
542
+ }
543
+ }
544
+ return days2;
545
+ };
546
+ var getDirectionHeadsignFromTimetable = (timetable) => {
547
+ const trips = getTrips(
548
+ {
549
+ direction_id: timetable.direction_id,
550
+ route_id: timetable.route_ids
551
+ },
552
+ ["trip_headsign"]
553
+ );
554
+ if (trips.length === 0) {
555
+ return "";
556
+ }
557
+ const mostCommonHeadsign = flow(
558
+ countBy,
559
+ entries,
560
+ partialRight(maxBy, last),
561
+ head
562
+ )(compact(trips.map((trip) => trip.trip_headsign)));
563
+ return mostCommonHeadsign;
564
+ };
565
+ var getTimetableNotesForTimetable = (timetable, config2) => {
566
+ const noteReferences = [
567
+ // Get all notes for this timetable.
568
+ ...getTimetableNotesReferences({
569
+ timetable_id: timetable.timetable_id
570
+ }),
571
+ // Get all notes for this route.
572
+ ...getTimetableNotesReferences({
573
+ route_id: timetable.routes.map((route) => route.route_id),
574
+ timetable_id: null
575
+ }),
576
+ // Get all notes for all trips in this timetable.
577
+ ...getTimetableNotesReferences({
578
+ trip_id: timetable.orderedTrips.map((trip) => trip.trip_id)
579
+ }),
580
+ // Get all notes for all stops in this timetable.
581
+ ...getTimetableNotesReferences({
582
+ stop_id: timetable.stops.map((stop) => stop.stop_id),
583
+ trip_id: null,
584
+ route_id: null,
585
+ timetable_id: null
586
+ })
587
+ ];
588
+ const usedNoteReferences = [];
589
+ for (const noteReference of noteReferences) {
590
+ if (noteReference.stop_sequence === "" || noteReference.stop_sequence === null) {
591
+ usedNoteReferences.push(noteReference);
592
+ continue;
593
+ }
594
+ if (noteReference.stop_id === "" || noteReference.stop_id === null) {
595
+ config2.logWarning(
596
+ `Timetable Note Reference for note_id=${noteReference.note_id} has a \`stop_sequence\` but no \`stop_id\` - ignoring`
597
+ );
598
+ continue;
599
+ }
600
+ const stop = timetable.stops.find(
601
+ (stop2) => stop2.stop_id === noteReference.stop_id
602
+ );
603
+ if (!stop) {
604
+ continue;
605
+ }
606
+ const tripWithMatchingStopSequence = stop.trips.find(
607
+ (trip) => trip.stop_sequence === noteReference.stop_sequence
608
+ );
609
+ if (tripWithMatchingStopSequence) {
610
+ usedNoteReferences.push(noteReference);
611
+ }
612
+ }
613
+ const notes = getTimetableNotes({
614
+ note_id: usedNoteReferences.map((noteReference) => noteReference.note_id)
615
+ });
616
+ const symbols = "abcdefghijklmnopqrstuvwxyz".split("");
617
+ let symbolIndex = 0;
618
+ for (const note of notes) {
619
+ if (note.symbol === "" || note.symbol === null) {
620
+ note.symbol = symbolIndex < symbols.length - 1 ? symbols[symbolIndex] : symbolIndex - symbols.length;
621
+ symbolIndex += 1;
622
+ }
623
+ }
624
+ const formattedNotes = usedNoteReferences.map((noteReference) => ({
625
+ ...noteReference,
626
+ ...notes.find((note) => note.note_id === noteReference.note_id)
627
+ }));
628
+ return sortBy(formattedNotes, "symbol");
629
+ };
630
+ var convertTimetableToTimetablePage = (timetable, config2) => {
631
+ if (!timetable.routes) {
632
+ timetable.routes = getRoutes({
633
+ route_id: timetable.route_ids
634
+ });
635
+ }
636
+ const filename = generateFileName(timetable, config2, "html");
637
+ return {
638
+ timetable_page_id: timetable.timetable_id,
639
+ timetable_page_label: timetable.timetable_label,
640
+ timetables: [timetable],
641
+ filename
642
+ };
643
+ };
644
+ var convertRouteToTimetablePage = (route, direction, calendars, calendarDates, config2) => {
645
+ const timetable = {
646
+ route_ids: [route.route_id],
647
+ direction_id: direction ? direction.direction_id : void 0,
648
+ direction_name: direction ? direction.trip_headsign : void 0,
649
+ routes: [route],
650
+ include_exceptions: calendarDates && calendarDates.length > 0 ? 1 : 0,
651
+ service_id: calendarDates && calendarDates.length > 0 ? calendarDates[0].service_id : null,
652
+ service_notes: null,
653
+ timetable_label: null,
654
+ start_time: null,
655
+ end_time: null,
656
+ orientation: null,
657
+ timetable_sequence: null,
658
+ show_trip_continuation: null,
659
+ start_date: null,
660
+ end_date: null
661
+ };
662
+ if (calendars && calendars.length > 0) {
663
+ Object.assign(timetable, getDaysFromCalendars(calendars));
664
+ timetable.start_date = toGTFSDate(
665
+ moment2.min(
666
+ calendars.map((calendar) => fromGTFSDate(calendar.start_date))
667
+ )
668
+ );
669
+ timetable.end_date = toGTFSDate(
670
+ moment2.max(calendars.map((calendar) => fromGTFSDate(calendar.end_date)))
671
+ );
672
+ }
673
+ timetable.timetable_id = formatTimetableId(timetable);
674
+ return convertTimetableToTimetablePage(timetable, config2);
675
+ };
676
+ var convertRoutesToTimetablePages = (config2) => {
677
+ const db = openDb(config2);
678
+ const routes = getRoutes();
679
+ let whereClause = "";
680
+ const whereClauses = [];
681
+ if (config2.endDate) {
682
+ whereClauses.push(
683
+ `start_date <= ${sqlString.escape(toGTFSDate(moment2(config2.endDate)))}`
684
+ );
685
+ }
686
+ if (config2.startDate) {
687
+ whereClauses.push(
688
+ `end_date >= ${sqlString.escape(toGTFSDate(moment2(config2.startDate)))}`
689
+ );
690
+ }
691
+ if (whereClauses.length > 0) {
692
+ whereClause = `WHERE ${whereClauses.join(" AND ")}`;
693
+ }
694
+ const calendars = db.prepare(`SELECT * FROM calendar ${whereClause}`).all();
695
+ const serviceIds = calendars.map((calendar) => calendar.service_id);
696
+ const calendarDates = db.prepare(
697
+ `SELECT * FROM calendar_dates WHERE exception_type = 1 AND service_id NOT IN (${serviceIds.map((serviceId) => `'${serviceId}'`).join(", ")})`
698
+ ).all();
699
+ const timetablePages = routes.map((route) => {
700
+ const trips = getTrips(
701
+ {
702
+ route_id: route.route_id
703
+ },
704
+ ["trip_headsign", "direction_id", "trip_id", "service_id"]
705
+ );
706
+ const directions = uniqBy(trips, (trip) => trip.direction_id);
707
+ const dayGroups = groupBy(calendars, calendarToCalendarCode);
708
+ const calendarDateGroups = groupBy(calendarDates, "service_id");
709
+ return directions.map((direction) => [
710
+ Object.values(dayGroups).map((calendars2) => {
711
+ const tripsForCalendars = trips.filter(
712
+ (trip) => some(calendars2, { service_id: trip.service_id })
713
+ );
714
+ if (tripsForCalendars.length > 0) {
715
+ return convertRouteToTimetablePage(
716
+ route,
717
+ direction,
718
+ calendars2,
719
+ null,
720
+ config2
721
+ );
722
+ }
723
+ }),
724
+ Object.values(calendarDateGroups).map((calendarDates2) => {
725
+ const tripsForCalendarDates = trips.filter(
726
+ (trip) => some(calendarDates2, { service_id: trip.service_id })
727
+ );
728
+ if (tripsForCalendarDates.length > 0) {
729
+ return convertRouteToTimetablePage(
730
+ route,
731
+ direction,
732
+ null,
733
+ calendarDates2,
734
+ config2
735
+ );
736
+ }
737
+ })
738
+ ]);
739
+ });
740
+ return compact(flattenDeep(timetablePages));
741
+ };
742
+ var generateTripsByFrequencies = (trip, frequencies, config2) => {
743
+ const formattedFrequencies = frequencies.map(
744
+ (frequency) => formatFrequency(frequency, config2)
745
+ );
746
+ const resetTrip = resetStoptimesToMidnight(trip);
747
+ const trips = [];
748
+ for (const frequency of formattedFrequencies) {
749
+ const startSeconds = secondsAfterMidnight(frequency.start_time);
750
+ const endSeconds = secondsAfterMidnight(frequency.end_time);
751
+ for (let offset = startSeconds; offset < endSeconds; offset += frequency.headway_secs) {
752
+ const newTrip = cloneDeep(resetTrip);
753
+ trips.push({
754
+ ...newTrip,
755
+ trip_id: `${resetTrip.trip_id}_freq_${trips.length}`,
756
+ stoptimes: updateStoptimesByOffset(newTrip, offset)
757
+ });
758
+ }
759
+ }
760
+ return trips;
761
+ };
762
+ var duplicateStopsForDifferentArrivalDeparture = (stopIds, timetable, config2) => {
763
+ if (config2.showArrivalOnDifference === null) {
764
+ return stopIds;
765
+ }
766
+ for (const trip of timetable.orderedTrips) {
767
+ for (const stoptime of trip.stoptimes) {
768
+ const timepointDifference = fromGTFSTime(stoptime.departure_time).diff(
769
+ fromGTFSTime(stoptime.arrival_time),
770
+ "minutes"
771
+ );
772
+ if (timepointDifference < config2.showArrivalOnDifference) {
773
+ continue;
774
+ }
775
+ const index = stopIds.indexOf(stoptime.stop_id);
776
+ if (index === 0 || index === stopIds.length - 1) {
777
+ continue;
778
+ }
779
+ if (stoptime.stop_id === stopIds[index + 1] || stoptime.stop_id === stopIds[index - 1]) {
780
+ continue;
781
+ }
782
+ stopIds.splice(index, 0, stoptime.stop_id);
783
+ }
784
+ }
785
+ return stopIds;
786
+ };
787
+ var getStopOrder = (timetable, config2) => {
788
+ const timetableStopOrders = getTimetableStopOrders(
789
+ {
790
+ timetable_id: timetable.timetable_id
791
+ },
792
+ ["stop_id"],
793
+ [["stop_sequence", "ASC"]]
794
+ );
795
+ if (timetableStopOrders.length > 0) {
796
+ return timetableStopOrders.map(
797
+ (timetableStopOrder) => timetableStopOrder.stop_id
798
+ );
799
+ }
800
+ try {
801
+ const stopGraph = [];
802
+ for (const trip of timetable.orderedTrips) {
803
+ const sortedStopIds = trip.stoptimes.filter((stoptime) => {
804
+ if (config2.showOnlyTimepoint === true) {
805
+ return isTimepoint(stoptime);
806
+ }
807
+ return true;
808
+ }).map((stoptime) => stoptime.stop_id);
809
+ for (const [index, stopId] of sortedStopIds.entries()) {
810
+ if (index === sortedStopIds.length - 1) {
811
+ continue;
812
+ }
813
+ stopGraph.push([stopId, sortedStopIds[index + 1]]);
814
+ }
815
+ }
816
+ const stopIds2 = toposort(stopGraph);
817
+ return duplicateStopsForDifferentArrivalDeparture(
818
+ stopIds2,
819
+ timetable,
820
+ config2
821
+ );
822
+ } catch {
823
+ }
824
+ const longestTripStoptimes = getLongestTripStoptimes(
825
+ timetable.orderedTrips,
826
+ config2
827
+ );
828
+ const stopIds = longestTripStoptimes.map((stoptime) => stoptime.stop_id);
829
+ return duplicateStopsForDifferentArrivalDeparture(stopIds, timetable, config2);
830
+ };
831
+ var getStopsForTimetable = (timetable, config2) => {
832
+ if (timetable.orderedTrips.length === 0) {
833
+ return [];
834
+ }
835
+ const orderedStopIds = getStopOrder(timetable, config2);
836
+ const orderedStops = orderedStopIds.map((stopId, index) => {
837
+ const stops = getStops({
838
+ stop_id: stopId
839
+ });
840
+ if (stops.length === 0) {
841
+ throw new Error(
842
+ `No stop found found for stop_id=${stopId} in timetable_id=${timetable.timetable_id}`
843
+ );
844
+ }
845
+ const stop = {
846
+ ...stops[0],
847
+ trips: []
848
+ };
849
+ if (index < orderedStopIds.length - 1 && stopId === orderedStopIds[index + 1]) {
850
+ stop.type = "arrival";
851
+ } else if (index > 0 && stopId === orderedStopIds[index - 1]) {
852
+ stop.type = "departure";
853
+ }
854
+ return stop;
855
+ });
856
+ if (timetable.showStopCity) {
857
+ const stopAttributes = getStopAttributes({
858
+ stop_id: orderedStopIds
859
+ });
860
+ for (const stopAttribute of stopAttributes) {
861
+ const stop = orderedStops.find(
862
+ (stop2) => stop2.stop_id === stopAttribute.stop_id
863
+ );
864
+ if (stop) {
865
+ stop.stop_city = stopAttribute.stop_city;
866
+ }
867
+ }
868
+ }
869
+ return orderedStops;
870
+ };
871
+ var getCalendarsFromTimetable = (timetable) => {
872
+ const db = openDb();
873
+ let whereClause = "";
874
+ const whereClauses = [];
875
+ if (timetable.end_date) {
876
+ if (!moment2(timetable.end_date, "YYYYMMDD", true).isValid()) {
877
+ throw new Error(
878
+ `Invalid end_date=${timetable.end_date} for timetable_id=${timetable.timetable_id}`
879
+ );
880
+ }
881
+ whereClauses.push(`start_date <= ${sqlString.escape(timetable.end_date)}`);
882
+ }
883
+ if (timetable.start_date) {
884
+ if (!moment2(timetable.start_date, "YYYYMMDD", true).isValid()) {
885
+ throw new Error(
886
+ `Invalid start_date=${timetable.start_date} for timetable_id=${timetable.timetable_id}`
887
+ );
888
+ }
889
+ whereClauses.push(`end_date >= ${sqlString.escape(timetable.start_date)}`);
890
+ }
891
+ const days2 = getDaysFromCalendars([timetable]);
892
+ const dayQueries = reduce(
893
+ days2,
894
+ (memo, value, key) => {
895
+ if (value === 1) {
896
+ memo.push(`${key} = 1`);
897
+ }
898
+ return memo;
899
+ },
900
+ []
901
+ );
902
+ if (dayQueries.length > 0) {
903
+ whereClauses.push(`(${dayQueries.join(" OR ")})`);
904
+ }
905
+ if (whereClauses.length > 0) {
906
+ whereClause = `WHERE ${whereClauses.join(" AND ")}`;
907
+ }
908
+ return db.prepare(`SELECT * FROM calendar ${whereClause}`).all();
909
+ };
910
+ var getCalendarDatesServiceIds = (startDate, endDate) => {
911
+ const db = openDb();
912
+ const whereClauses = ["exception_type = 1"];
913
+ if (endDate) {
914
+ whereClauses.push(`date <= ${sqlString.escape(endDate)}`);
915
+ }
916
+ if (startDate) {
917
+ whereClauses.push(`date >= ${sqlString.escape(startDate)}`);
918
+ }
919
+ const calendarDates = db.prepare(
920
+ `SELECT DISTINCT service_id FROM calendar_dates WHERE ${whereClauses.join(
921
+ " AND "
922
+ )}`
923
+ ).all();
924
+ return calendarDates.map((calendarDate) => calendarDate.service_id);
925
+ };
926
+ var getAllStationStopIds = (stopId) => {
927
+ const stops = getStops({
928
+ stop_id: stopId
929
+ });
930
+ if (stops.length === 0) {
931
+ throw new Error(`No stop found for stop_id=${stopId}`);
932
+ }
933
+ const stop = stops[0];
934
+ if (isNullOrEmpty(stop.parent_station)) {
935
+ return [stopId];
936
+ }
937
+ const stopsInParentStation = getStops(
938
+ {
939
+ parent_station: stop.parent_station
940
+ },
941
+ ["stop_id"]
942
+ );
943
+ return [
944
+ stop.parent_station,
945
+ ...stopsInParentStation.map((stop2) => stop2.stop_id)
946
+ ];
947
+ };
948
+ var getTripsWithSameBlock = (trip, timetable) => {
949
+ const trips = getTrips(
950
+ {
951
+ block_id: trip.block_id,
952
+ service_id: timetable.service_ids
953
+ },
954
+ ["trip_id", "route_id"]
955
+ );
956
+ for (const blockTrip of trips) {
957
+ const stopTimes = getStoptimes(
958
+ {
959
+ trip_id: blockTrip.trip_id
960
+ },
961
+ [],
962
+ [["stop_sequence", "ASC"]]
963
+ );
964
+ if (stopTimes.length === 0) {
965
+ throw new Error(
966
+ `No stoptimes found found for trip_id=${blockTrip.trip_id}`
967
+ );
968
+ }
969
+ blockTrip.firstStoptime = first(stopTimes);
970
+ blockTrip.lastStoptime = last(stopTimes);
971
+ }
972
+ return sortBy(trips, (trip2) => trip2.firstStoptime.departure_timestamp);
973
+ };
974
+ var addTripContinuation = (trip, timetable) => {
975
+ if (!trip.block_id || trip.stoptimes.length === 0) {
976
+ return;
977
+ }
978
+ const maxContinuesAsWaitingTimeSeconds = 60 * 60;
979
+ const firstStoptime = first(trip.stoptimes);
980
+ const firstStopIds = getAllStationStopIds(firstStoptime.stop_id);
981
+ const lastStoptime = last(trip.stoptimes);
982
+ const lastStopIds = getAllStationStopIds(lastStoptime.stop_id);
983
+ const blockTrips = getTripsWithSameBlock(trip, timetable);
984
+ const previousTrip = findLast(
985
+ blockTrips,
986
+ (blockTrip) => blockTrip.lastStoptime.arrival_timestamp <= firstStoptime.departure_timestamp
987
+ );
988
+ if (previousTrip && previousTrip.route_id !== trip.route_id && previousTrip.lastStoptime.arrival_timestamp >= firstStoptime.departure_timestamp - maxContinuesAsWaitingTimeSeconds && firstStopIds.includes(previousTrip.lastStoptime.stop_id)) {
989
+ const routes = getRoutes({
990
+ route_id: previousTrip.route_id
991
+ });
992
+ previousTrip.route = routes[0];
993
+ trip.continues_from_route = previousTrip;
994
+ }
995
+ const nextTrip = find(
996
+ blockTrips,
997
+ (blockTrip) => blockTrip.firstStoptime.departure_timestamp >= lastStoptime.arrival_timestamp
998
+ );
999
+ if (nextTrip && nextTrip.route_id !== trip.route_id && nextTrip.firstStoptime.departure_timestamp <= lastStoptime.arrival_timestamp + maxContinuesAsWaitingTimeSeconds && lastStopIds.includes(nextTrip.firstStoptime.stop_id)) {
1000
+ const routes = getRoutes({
1001
+ route_id: nextTrip.route_id
1002
+ });
1003
+ nextTrip.route = routes[0];
1004
+ trip.continues_as_route = nextTrip;
1005
+ }
1006
+ };
1007
+ var filterTrips = (timetable) => {
1008
+ let filteredTrips = timetable.orderedTrips;
1009
+ for (const trip of filteredTrips) {
1010
+ const combinedStoptimes = [];
1011
+ for (const [index, stoptime] of trip.stoptimes.entries()) {
1012
+ if (index === 0 || stoptime.stop_id !== trip.stoptimes[index - 1].stop_id) {
1013
+ combinedStoptimes.push(stoptime);
1014
+ } else {
1015
+ combinedStoptimes[combinedStoptimes.length - 1].departure_time = stoptime.departure_time;
1016
+ }
1017
+ }
1018
+ trip.stoptimes = combinedStoptimes;
1019
+ }
1020
+ const timetableStopIds = new Set(timetable.stops.map((stop) => stop.stop_id));
1021
+ for (const trip of filteredTrips) {
1022
+ trip.stoptimes = trip.stoptimes.filter(
1023
+ (stoptime) => timetableStopIds.has(stoptime.stop_id)
1024
+ );
1025
+ }
1026
+ filteredTrips = filteredTrips.filter((trip) => trip.stoptimes.length > 1);
1027
+ return filteredTrips;
1028
+ };
1029
+ var getTripsForTimetable = (timetable, calendars, config2) => {
1030
+ const tripQuery = {
1031
+ route_id: timetable.route_ids,
1032
+ service_id: timetable.service_ids
1033
+ };
1034
+ if (!isNullOrEmpty(timetable.direction_id)) {
1035
+ tripQuery.direction_id = timetable.direction_id;
1036
+ }
1037
+ const trips = getTrips(tripQuery);
1038
+ if (trips.length === 0) {
1039
+ timetable.warnings.push(
1040
+ `No trips found for route_id=${timetable.route_ids.join(
1041
+ "_"
1042
+ )}, direction_id=${timetable.direction_id}, service_ids=${JSON.stringify(
1043
+ timetable.service_ids
1044
+ )}, timetable_id=${timetable.timetable_id}`
1045
+ );
1046
+ }
1047
+ const frequencies = getFrequencies({
1048
+ trip_id: trips.map((trip) => trip.trip_id)
1049
+ });
1050
+ timetable.service_ids = uniq(trips.map((trip) => trip.service_id));
1051
+ const formattedTrips = [];
1052
+ for (const trip of trips) {
1053
+ const formattedTrip = formatTrip(trip, timetable, calendars, config2);
1054
+ formattedTrip.stoptimes = getStoptimes(
1055
+ {
1056
+ trip_id: formattedTrip.trip_id
1057
+ },
1058
+ [],
1059
+ [["stop_sequence", "ASC"]]
1060
+ );
1061
+ if (formattedTrip.stoptimes.length === 0) {
1062
+ timetable.warnings.push(
1063
+ `No stoptimes found for trip_id=${formattedTrip.trip_id}, route_id=${timetable.route_ids.join("_")}, timetable_id=${timetable.timetable_id}`
1064
+ );
1065
+ }
1066
+ if (timetable.start_timestamp !== "" && timetable.start_timestamp !== null && timetable.start_timestamp !== void 0 && trip.stoptimes[0].arrival_timestamp < timetable.start_timestamp) {
1067
+ return;
1068
+ }
1069
+ if (timetable.end_timestamp !== "" && timetable.end_timestamp !== null && timetable.end_timestamp !== void 0 && trip.stoptimes[0].arrival_timestamp >= timetable.end_timestamp) {
1070
+ return;
1071
+ }
1072
+ if (timetable.show_trip_continuation) {
1073
+ addTripContinuation(formattedTrip, timetable);
1074
+ if (formattedTrip.continues_as_route) {
1075
+ timetable.has_continues_as_route = true;
1076
+ }
1077
+ if (formattedTrip.continues_from_route) {
1078
+ timetable.has_continues_from_route = true;
1079
+ }
1080
+ }
1081
+ const tripFrequencies = frequencies.filter(
1082
+ (frequency) => frequency.trip_id === trip.trip_id
1083
+ );
1084
+ if (tripFrequencies.length === 0) {
1085
+ formattedTrips.push(formattedTrip);
1086
+ } else {
1087
+ const frequencyTrips = generateTripsByFrequencies(
1088
+ formattedTrip,
1089
+ frequencies,
1090
+ config2
1091
+ );
1092
+ formattedTrips.push(...frequencyTrips);
1093
+ timetable.frequencies = frequencies;
1094
+ timetable.frequencyExactTimes = some(frequencies, {
1095
+ exact_times: 1
1096
+ });
1097
+ }
1098
+ }
1099
+ if (config2.useParentStation) {
1100
+ const stopIds = [];
1101
+ for (const trip of formattedTrips) {
1102
+ for (const stoptime of trip.stoptimes) {
1103
+ stopIds.push(stoptime.stop_id);
1104
+ }
1105
+ }
1106
+ const stops = getStops(
1107
+ {
1108
+ stop_id: uniq(stopIds)
1109
+ },
1110
+ ["parent_station", "stop_id"]
1111
+ );
1112
+ for (const trip of formattedTrips) {
1113
+ for (const stoptime of trip.stoptimes) {
1114
+ const stop = stops.find((stop2) => stop2.stop_id === stoptime.stop_id);
1115
+ if (stop?.parent_station) {
1116
+ stoptime.stop_id = stop.parent_station;
1117
+ }
1118
+ }
1119
+ }
1120
+ }
1121
+ return sortTrips(formattedTrips, config2);
1122
+ };
1123
+ var formatTimetables = (timetables, config2) => {
1124
+ const formattedTimetables = timetables.map((timetable) => {
1125
+ timetable.warnings = [];
1126
+ const dayList = formatDays(timetable, config2);
1127
+ const calendars = getCalendarsFromTimetable(timetable);
1128
+ let serviceIds = calendars.map((calendar) => calendar.service_id);
1129
+ if (timetable.include_exceptions === 1) {
1130
+ const calendarDatesServiceIds = getCalendarDatesServiceIds(
1131
+ timetable.start_date,
1132
+ timetable.end_date
1133
+ );
1134
+ serviceIds = uniq([...serviceIds, ...calendarDatesServiceIds]);
1135
+ }
1136
+ Object.assign(timetable, {
1137
+ noServiceSymbolUsed: false,
1138
+ requestDropoffSymbolUsed: false,
1139
+ noDropoffSymbolUsed: false,
1140
+ requestPickupSymbolUsed: false,
1141
+ noPickupSymbolUsed: false,
1142
+ interpolatedStopSymbolUsed: false,
1143
+ showStopCity: config2.showStopCity,
1144
+ showStopDescription: config2.showStopDescription,
1145
+ noServiceSymbol: config2.noServiceSymbol,
1146
+ requestDropoffSymbol: config2.requestDropoffSymbol,
1147
+ noDropoffSymbol: config2.noDropoffSymbol,
1148
+ requestPickupSymbol: config2.requestPickupSymbol,
1149
+ noPickupSymbol: config2.noPickupSymbol,
1150
+ interpolatedStopSymbol: config2.interpolatedStopSymbol,
1151
+ orientation: timetable.orientation || config2.defaultOrientation,
1152
+ service_ids: serviceIds,
1153
+ dayList,
1154
+ dayListLong: formatDaysLong(dayList, config2)
1155
+ });
1156
+ timetable.orderedTrips = getTripsForTimetable(timetable, calendars, config2);
1157
+ timetable.stops = getStopsForTimetable(timetable, config2);
1158
+ timetable.calendarDates = getCalendarDatesForTimetable(timetable, config2);
1159
+ timetable.timetable_label = formatTimetableLabel(timetable);
1160
+ timetable.notes = getTimetableNotesForTimetable(timetable, config2);
1161
+ if (config2.showMap) {
1162
+ timetable.geojson = getTimetableGeoJSON(timetable, config2);
1163
+ }
1164
+ timetable.orderedTrips = filterTrips(timetable);
1165
+ timetable.stops = formatStops(timetable, config2);
1166
+ return timetable;
1167
+ });
1168
+ if (config2.allowEmptyTimetables) {
1169
+ return formattedTimetables;
1170
+ }
1171
+ return formattedTimetables.filter(
1172
+ (timetable) => timetable.orderedTrips.length > 0
1173
+ );
1174
+ };
1175
+ function getTimetablePagesForAgency(config2) {
1176
+ const timetables = mergeTimetablesWithSameId(getTimetables());
1177
+ if (timetables.length === 0) {
1178
+ return convertRoutesToTimetablePages(config2);
1179
+ }
1180
+ const timetablePages = getTimetablePages(
1181
+ {},
1182
+ [],
1183
+ [["timetable_page_id", "ASC"]]
1184
+ );
1185
+ if (timetablePages.length === 0) {
1186
+ return timetables.map(
1187
+ (timetable) => convertTimetableToTimetablePage(timetable, config2)
1188
+ );
1189
+ }
1190
+ const routes = getRoutes();
1191
+ return timetablePages.map((timetablePage) => {
1192
+ timetablePage.timetables = sortBy(
1193
+ timetables.filter(
1194
+ (timetable) => timetable.timetable_page_id === timetablePage.timetable_page_id
1195
+ ),
1196
+ "timetable_sequence"
1197
+ );
1198
+ for (const timetable of timetablePage.timetables) {
1199
+ timetable.routes = routes.filter(
1200
+ (route) => timetable.route_ids.includes(route.route_id)
1201
+ );
1202
+ }
1203
+ return timetablePage;
1204
+ });
1205
+ }
1206
+ var getTimetablePageById = (timetablePageId, config2) => {
1207
+ const timetablePages = getTimetablePages({
1208
+ timetable_page_id: timetablePageId
1209
+ });
1210
+ const timetables = mergeTimetablesWithSameId(getTimetables());
1211
+ if (timetablePages.length > 1) {
1212
+ throw new Error(
1213
+ `Multiple timetable_pages found for timetable_page_id=${timetablePageId}`
1214
+ );
1215
+ }
1216
+ if (timetablePages.length === 1) {
1217
+ const timetablePage = timetablePages[0];
1218
+ timetablePage.timetables = sortBy(
1219
+ timetables.filter(
1220
+ (timetable) => timetable.timetable_page_id === timetablePageId
1221
+ ),
1222
+ "timetable_sequence"
1223
+ );
1224
+ for (const timetable of timetablePage.timetables) {
1225
+ timetable.routes = getRoutes({
1226
+ route_id: timetable.route_ids
1227
+ });
1228
+ }
1229
+ return timetablePage;
1230
+ }
1231
+ if (timetables.length > 0) {
1232
+ const timetablePageTimetables = timetables.filter(
1233
+ (timetable) => timetable.timetable_id === timetablePageId
1234
+ );
1235
+ if (timetablePageTimetables.length === 0) {
1236
+ throw new Error(
1237
+ `No timetable found for timetable_page_id=${timetablePageId}`
1238
+ );
1239
+ }
1240
+ return convertTimetableToTimetablePage(timetablePageTimetables[0], config2);
1241
+ }
1242
+ let calendarCode;
1243
+ let calendars;
1244
+ let calendarDates;
1245
+ let serviceId;
1246
+ let directionId = "";
1247
+ const parts = timetablePageId.split("|");
1248
+ if (parts.length > 2) {
1249
+ directionId = Number.parseInt(parts.pop(), 10);
1250
+ calendarCode = parts.pop();
1251
+ } else if (parts.length > 1) {
1252
+ directionId = null;
1253
+ calendarCode = parts.pop();
1254
+ }
1255
+ const routeId = parts.join("|");
1256
+ const routes = getRoutes({
1257
+ route_id: routeId
1258
+ });
1259
+ const trips = getTrips(
1260
+ {
1261
+ route_id: routeId,
1262
+ direction_id: directionId
1263
+ },
1264
+ ["trip_headsign", "direction_id"]
1265
+ );
1266
+ const directions = uniqBy(trips, (trip) => trip.direction_id);
1267
+ if (directions.length === 0) {
1268
+ throw new Error(
1269
+ `No trips found for timetable_page_id=${timetablePageId} route_id=${routeId} direction_id=${directionId}`
1270
+ );
1271
+ }
1272
+ if (/^[01]*$/.test(calendarCode)) {
1273
+ calendars = getCalendars({
1274
+ ...calendarCodeToCalendar(calendarCode)
1275
+ });
1276
+ } else {
1277
+ serviceId = calendarCode;
1278
+ calendarDates = getCalendarDates({
1279
+ exception_type: 1,
1280
+ service_id: serviceId
1281
+ });
1282
+ }
1283
+ return convertRouteToTimetablePage(
1284
+ routes[0],
1285
+ directions[0],
1286
+ calendars,
1287
+ calendarDates,
1288
+ config2
1289
+ );
1290
+ };
1291
+ function setDefaultConfig(initialConfig) {
1292
+ const defaults = {
1293
+ allowEmptyTimetables: false,
1294
+ beautify: false,
1295
+ coordinatePrecision: 5,
1296
+ dateFormat: "MMM D, YYYY",
1297
+ daysShortStrings: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
1298
+ daysStrings: [
1299
+ "Monday",
1300
+ "Tuesday",
1301
+ "Wednesday",
1302
+ "Thursday",
1303
+ "Friday",
1304
+ "Saturday",
1305
+ "Sunday"
1306
+ ],
1307
+ defaultOrientation: "vertical",
1308
+ interpolatedStopSymbol: "\u2022",
1309
+ interpolatedStopText: "Estimated time of arrival",
1310
+ gtfsToHtmlVersion: version,
1311
+ linkStopUrls: false,
1312
+ menuType: "jump",
1313
+ noDropoffSymbol: "\u2021",
1314
+ noDropoffText: "No drop off available",
1315
+ noHead: false,
1316
+ noPickupSymbol: "**",
1317
+ noPickupText: "No pickup available",
1318
+ noServiceSymbol: "-",
1319
+ noServiceText: "No service at this stop",
1320
+ outputFormat: "html",
1321
+ requestDropoffSymbol: "\u2020",
1322
+ requestDropoffText: "Must request drop off",
1323
+ requestPickupSymbol: "***",
1324
+ requestPickupText: "Request stop - call for pickup",
1325
+ serviceNotProvidedOnText: "Service not provided on",
1326
+ serviceProvidedOnText: "Service provided on",
1327
+ showArrivalOnDifference: 0.2,
1328
+ showCalendarExceptions: true,
1329
+ showMap: false,
1330
+ showOnlyTimepoint: false,
1331
+ showRouteTitle: true,
1332
+ showStopCity: false,
1333
+ showStopDescription: false,
1334
+ showStoptimesForRequestStops: true,
1335
+ skipImport: false,
1336
+ sortingAlgorithm: "common",
1337
+ timeFormat: "h:mma",
1338
+ useParentStation: true,
1339
+ verbose: true,
1340
+ zipOutput: false
1341
+ };
1342
+ const config2 = Object.assign(defaults, initialConfig);
1343
+ if (config2.outputFormat === "pdf") {
1344
+ config2.noHead = false;
1345
+ }
1346
+ return config2;
1347
+ }
1348
+ function getFormattedTimetablePage(timetablePageId, config2) {
1349
+ const timetablePage = getTimetablePageById(
1350
+ timetablePageId,
1351
+ config2
1352
+ );
1353
+ const timetableRoutes = getRoutes(
1354
+ {
1355
+ route_id: timetablePage.route_ids
1356
+ },
1357
+ ["agency_id"]
1358
+ );
1359
+ const consolidatedTimetables = formatTimetables(
1360
+ timetablePage.timetables,
1361
+ config2
1362
+ );
1363
+ for (const timetable of consolidatedTimetables) {
1364
+ if (isNullOrEmpty(timetable.direction_name)) {
1365
+ timetable.direction_name = getDirectionHeadsignFromTimetable(timetable);
1366
+ }
1367
+ if (!timetable.routes) {
1368
+ timetable.routes = getRoutes({
1369
+ route_id: timetable.route_ids
1370
+ });
1371
+ }
1372
+ }
1373
+ const formattedTimetablePage = {
1374
+ ...timetablePage,
1375
+ consolidatedTimetables,
1376
+ dayList: formatDays(getDaysFromCalendars(consolidatedTimetables), config2),
1377
+ dayLists: uniq(
1378
+ consolidatedTimetables.map((timetable) => timetable.dayList)
1379
+ ),
1380
+ route_ids: uniq(flatMap2(consolidatedTimetables, "route_ids")),
1381
+ agency_ids: uniq(compact(timetableRoutes.map((route) => route.agency_id))),
1382
+ filename: timetablePage.filename ?? `${timetablePage.timetable_page_id}.html`
1383
+ };
1384
+ return formattedTimetablePage;
1385
+ }
1386
+ function generateTimetableHTML(timetablePage, config2) {
1387
+ const templateVars = {
1388
+ timetablePage,
1389
+ config: config2
1390
+ };
1391
+ return renderTemplate("timetablepage", templateVars, config2);
1392
+ }
1393
+ function generateOverviewHTML(timetablePages, config2) {
1394
+ const agencies = getAgencies();
1395
+ if (agencies.length === 0) {
1396
+ throw new Error("No agencies found");
1397
+ }
1398
+ let geojson;
1399
+ if (config2.showMap) {
1400
+ geojson = getAgencyGeoJSON(config2);
1401
+ }
1402
+ const sortedTimetablePages = sortBy(timetablePages, [
1403
+ (timetablePage) => {
1404
+ if (timetablePage.consolidatedTimetables.length > 0 && timetablePage.consolidatedTimetables[0].routes.length > 0) {
1405
+ return Number.parseInt(
1406
+ timetablePage.consolidatedTimetables[0].routes[0].route_short_name?.replace(
1407
+ /^\D+/g,
1408
+ ""
1409
+ ),
1410
+ 10
1411
+ ) || 0;
1412
+ }
1413
+ },
1414
+ (timetablePage) => {
1415
+ if (timetablePage.consolidatedTimetables.length > 0 && timetablePage.consolidatedTimetables[0].routes.length > 0) {
1416
+ return timetablePage.consolidatedTimetables[0].routes[0].route_short_name;
1417
+ }
1418
+ }
1419
+ ]);
1420
+ const templateVars = {
1421
+ agency: {
1422
+ ...first(agencies),
1423
+ geojson
1424
+ },
1425
+ agencies,
1426
+ geojson,
1427
+ config: config2,
1428
+ timetablePages: sortedTimetablePages
1429
+ };
1430
+ return renderTemplate("overview", templateVars, config2);
1431
+ }
1432
+
1433
+ // src/lib/formatters.ts
1434
+ function replaceAll(string, mapObject) {
1435
+ const re = new RegExp(Object.keys(mapObject).join("|"), "gi");
1436
+ return string.replace(re, (matched) => mapObject[matched]);
1437
+ }
1438
+ function isNullOrEmpty(value) {
1439
+ return value === null || value === "";
1440
+ }
1441
+ function formatDate(date, dateFormat) {
1442
+ if (date.holiday_name) {
1443
+ return date.holiday_name;
1444
+ }
1445
+ return moment3(date.date, "YYYYMMDD").format(dateFormat);
1446
+ }
1447
+ function timeToSeconds(time) {
1448
+ return moment3.duration(time).asSeconds();
1449
+ }
1450
+ function formatStopTime(stoptime, timetable, config2) {
1451
+ stoptime.classes = [];
1452
+ if (stoptime.type === "arrival" && stoptime.arrival_time) {
1453
+ const arrivalTime = fromGTFSTime(stoptime.arrival_time);
1454
+ stoptime.formatted_time = arrivalTime.format(config2.timeFormat);
1455
+ stoptime.classes.push(arrivalTime.format("a"));
1456
+ } else if (stoptime.type === "departure" && stoptime.departure_time) {
1457
+ const departureTime = fromGTFSTime(stoptime.departure_time);
1458
+ stoptime.formatted_time = departureTime.format(config2.timeFormat);
1459
+ stoptime.classes.push(departureTime.format("a"));
1460
+ }
1461
+ if (stoptime.pickup_type === 1) {
1462
+ stoptime.noPickup = true;
1463
+ stoptime.classes.push("no-pickup");
1464
+ if (timetable.noPickupSymbol !== null) {
1465
+ timetable.noPickupSymbolUsed = true;
1466
+ }
1467
+ } else if (stoptime.pickup_type === 2 || stoptime.pickup_type === 3) {
1468
+ stoptime.requestPickup = true;
1469
+ stoptime.classes.push("request-pickup");
1470
+ if (timetable.requestPickupSymbol !== null) {
1471
+ timetable.requestPickupSymbolUsed = true;
1472
+ }
1473
+ }
1474
+ if (stoptime.drop_off_type === 1) {
1475
+ stoptime.noDropoff = true;
1476
+ stoptime.classes.push("no-drop-off");
1477
+ if (timetable.noDropoffSymbol !== null) {
1478
+ timetable.noDropoffSymbolUsed = true;
1479
+ }
1480
+ } else if (stoptime.drop_off_type === 2 || stoptime.drop_off_type === 3) {
1481
+ stoptime.requestDropoff = true;
1482
+ stoptime.classes.push("request-drop-off");
1483
+ if (timetable.requestDropoffSymbol !== null) {
1484
+ timetable.requestDropoffSymbolUsed = true;
1485
+ }
1486
+ }
1487
+ if (stoptime.timepoint === 0 || stoptime.departure_time === "") {
1488
+ stoptime.interpolated = true;
1489
+ stoptime.classes.push("interpolated");
1490
+ if (timetable.interpolatedStopSymbol !== null) {
1491
+ timetable.interpolatedStopSymbolUsed = true;
1492
+ }
1493
+ }
1494
+ if (stoptime.timepoint === null && stoptime.departure_time === null) {
1495
+ stoptime.skipped = true;
1496
+ stoptime.classes.push("skipped");
1497
+ if (timetable.noServiceSymbol !== null) {
1498
+ timetable.noServiceSymbolUsed = true;
1499
+ }
1500
+ }
1501
+ if (stoptime.timepoint === 1) {
1502
+ stoptime.classes.push("timepoint");
1503
+ }
1504
+ return stoptime;
1505
+ }
1506
+ function filterHourlyTimes(stops) {
1507
+ const firstStopTimes = [];
1508
+ const firstTripMinutes = minutesAfterMidnight(stops[0].trips[0].arrival_time);
1509
+ for (const trip of stops[0].trips) {
1510
+ const minutes = minutesAfterMidnight(trip.arrival_time);
1511
+ if (minutes >= firstTripMinutes + 60) {
1512
+ break;
1513
+ }
1514
+ firstStopTimes.push(fromGTFSTime(trip.arrival_time));
1515
+ }
1516
+ const firstStopTimesAndIndex = firstStopTimes.map((time, idx) => ({
1517
+ idx,
1518
+ time
1519
+ }));
1520
+ const sortedFirstStopTimesAndIndex = sortBy2(
1521
+ firstStopTimesAndIndex,
1522
+ (item) => Number.parseInt(item.time.format("m"), 10)
1523
+ );
1524
+ return stops.map((stop) => {
1525
+ stop.hourlyTimes = sortedFirstStopTimesAndIndex.map(
1526
+ (item) => fromGTFSTime(stop.trips[item.idx].arrival_time).format(":mm")
1527
+ );
1528
+ return stop;
1529
+ });
1530
+ }
1531
+ var days = [
1532
+ "monday",
1533
+ "tuesday",
1534
+ "wednesday",
1535
+ "thursday",
1536
+ "friday",
1537
+ "saturday",
1538
+ "sunday"
1539
+ ];
1540
+ function formatDays(calendar, config2) {
1541
+ const daysShort = config2.daysShortStrings;
1542
+ let daysInARow = 0;
1543
+ let dayString = "";
1544
+ if (!calendar) {
1545
+ return "";
1546
+ }
1547
+ for (let i = 0; i <= 6; i += 1) {
1548
+ const currentDayOperating = calendar[days[i]] === 1;
1549
+ const previousDayOperating = i > 0 ? calendar[days[i - 1]] === 1 : false;
1550
+ const nextDayOperating = i < 6 ? calendar[days[i + 1]] === 1 : false;
1551
+ if (currentDayOperating) {
1552
+ if (dayString.length > 0) {
1553
+ if (!previousDayOperating) {
1554
+ dayString += ", ";
1555
+ } else if (daysInARow === 1) {
1556
+ dayString += "-";
1557
+ }
1558
+ }
1559
+ daysInARow += 1;
1560
+ if (dayString.length === 0 || !nextDayOperating || i === 6 || !previousDayOperating) {
1561
+ dayString += daysShort[i];
1562
+ }
1563
+ } else {
1564
+ daysInARow = 0;
1565
+ }
1566
+ }
1567
+ if (dayString.length === 0) {
1568
+ dayString = "No regular service days";
1569
+ }
1570
+ return dayString;
1571
+ }
1572
+ function formatDaysLong(dayList, config2) {
1573
+ const mapObject = zipObject(config2.daysShortStrings, config2.daysStrings);
1574
+ return replaceAll(dayList, mapObject);
1575
+ }
1576
+ function formatTrip(trip, timetable, calendars, config2) {
1577
+ trip.calendar = find2(calendars, {
1578
+ service_id: trip.service_id
1579
+ });
1580
+ trip.dayList = formatDays(trip.calendar, config2);
1581
+ trip.dayListLong = formatDaysLong(trip.dayList, config2);
1582
+ if (timetable.routes.length === 1) {
1583
+ trip.route_short_name = timetable.routes[0].route_short_name;
1584
+ } else {
1585
+ const route = timetable.routes.find(
1586
+ (route2) => route2.route_id === trip.route_id
1587
+ );
1588
+ trip.route_short_name = route.route_short_name;
1589
+ }
1590
+ return trip;
1591
+ }
1592
+ function formatFrequency(frequency, config2) {
1593
+ const startTime = fromGTFSTime(frequency.start_time);
1594
+ const endTime = fromGTFSTime(frequency.end_time);
1595
+ const headway = moment3.duration(frequency.headway_secs, "seconds");
1596
+ frequency.start_formatted_time = startTime.format(config2.timeFormat);
1597
+ frequency.end_formatted_time = endTime.format(config2.timeFormat);
1598
+ frequency.headway_min = Math.round(headway.asMinutes());
1599
+ return frequency;
1600
+ }
1601
+ function formatTimetableId(timetable) {
1602
+ let timetableId = `${timetable.route_ids.join("_")}|${calendarToCalendarCode(
1603
+ timetable
1604
+ )}`;
1605
+ if (!isNullOrEmpty(timetable.direction_id)) {
1606
+ timetableId += `|${timetable.direction_id}`;
1607
+ }
1608
+ return timetableId;
1609
+ }
1610
+ function createEmptyStoptime(stopId, tripId) {
1611
+ return {
1612
+ id: null,
1613
+ trip_id: tripId,
1614
+ arrival_time: null,
1615
+ departure_time: null,
1616
+ stop_id: stopId,
1617
+ stop_sequence: null,
1618
+ stop_headsign: null,
1619
+ pickup_type: null,
1620
+ drop_off_type: null,
1621
+ continuous_pickup: null,
1622
+ continuous_drop_off: null,
1623
+ shape_dist_traveled: null,
1624
+ timepoint: null
1625
+ };
1626
+ }
1627
+ function formatStops(timetable, config2) {
1628
+ for (const trip of timetable.orderedTrips) {
1629
+ let stopIndex = -1;
1630
+ for (const [idx, stoptime] of trip.stoptimes.entries()) {
1631
+ const stop = find2(timetable.stops, (st, idx2) => {
1632
+ if (st.stop_id === stoptime.stop_id && idx2 > stopIndex) {
1633
+ stopIndex = idx2;
1634
+ return true;
1635
+ }
1636
+ return false;
1637
+ });
1638
+ if (!stop) {
1639
+ continue;
1640
+ }
1641
+ if (idx === 0) {
1642
+ stoptime.drop_off_type = 0;
1643
+ }
1644
+ if (idx === trip.stoptimes.length - 1) {
1645
+ stoptime.pickup_type = 0;
1646
+ }
1647
+ if (stop.type === "arrival" && idx < trip.stoptimes.length - 1) {
1648
+ const departureStoptime = clone(stoptime);
1649
+ departureStoptime.type = "departure";
1650
+ timetable.stops[stopIndex + 1].trips.push(
1651
+ formatStopTime(departureStoptime, timetable, config2)
1652
+ );
1653
+ }
1654
+ if (!(stop.type === "arrival" && idx === 0)) {
1655
+ stoptime.type = "arrival";
1656
+ stop.trips.push(formatStopTime(stoptime, timetable, config2));
1657
+ }
1658
+ }
1659
+ for (const stop of timetable.stops) {
1660
+ const lastStopTime = last2(stop.trips);
1661
+ if (!lastStopTime || lastStopTime.trip_id !== trip.trip_id) {
1662
+ stop.trips.push(
1663
+ formatStopTime(
1664
+ createEmptyStoptime(stop.stop_id, trip.trip_id),
1665
+ timetable,
1666
+ config2
1667
+ )
1668
+ );
1669
+ }
1670
+ }
1671
+ }
1672
+ if (timetable.orientation === "hourly") {
1673
+ timetable.stops = filterHourlyTimes(timetable.stops);
1674
+ }
1675
+ for (const stop of timetable.stops) {
1676
+ stop.is_timepoint = stop.trips.some((stoptime) => isTimepoint(stoptime));
1677
+ }
1678
+ return timetable.stops;
1679
+ }
1680
+ function resetStoptimesToMidnight(trip) {
1681
+ const offsetSeconds = secondsAfterMidnight(
1682
+ first2(trip.stoptimes).departure_time
1683
+ );
1684
+ if (offsetSeconds > 0) {
1685
+ for (const stoptime of trip.stoptimes) {
1686
+ stoptime.departure_time = toGTFSTime(
1687
+ fromGTFSTime(stoptime.departure_time).subtract(
1688
+ offsetSeconds,
1689
+ "seconds"
1690
+ )
1691
+ );
1692
+ stoptime.arrival_time = toGTFSTime(
1693
+ fromGTFSTime(stoptime.arrival_time).subtract(offsetSeconds, "seconds")
1694
+ );
1695
+ }
1696
+ }
1697
+ return trip;
1698
+ }
1699
+ function updateStoptimesByOffset(trip, offsetSeconds) {
1700
+ return trip.stoptimes.map((stoptime) => {
1701
+ delete stoptime._id;
1702
+ stoptime.departure_time = updateTimeByOffset(
1703
+ stoptime.departure_time,
1704
+ offsetSeconds
1705
+ );
1706
+ stoptime.arrival_time = updateTimeByOffset(
1707
+ stoptime.arrival_time,
1708
+ offsetSeconds
1709
+ );
1710
+ stoptime.trip_id = trip.trip_id;
1711
+ return stoptime;
1712
+ });
1713
+ }
1714
+ function formatRouteColor(route) {
1715
+ return route.route_color ? `#${route.route_color}` : "#000000";
1716
+ }
1717
+ function formatRouteTextColor(route) {
1718
+ return route.route_text_color ? `#${route.route_text_color}` : "#FFFFFF";
1719
+ }
1720
+ function formatTimetableLabel(timetable) {
1721
+ if (!isNullOrEmpty(timetable.timetable_label)) {
1722
+ return timetable.timetable_label;
1723
+ }
1724
+ let timetableLabel = "";
1725
+ if (timetable.routes && timetable.routes.length > 0) {
1726
+ timetableLabel += "Route ";
1727
+ if (!isNullOrEmpty(timetable.routes[0].route_short_name)) {
1728
+ timetableLabel += timetable.routes[0].route_short_name;
1729
+ } else if (!isNullOrEmpty(timetable.routes[0].route_long_name)) {
1730
+ timetableLabel += timetable.routes[0].route_long_name;
1731
+ }
1732
+ }
1733
+ if (timetable.stops && timetable.stops.length > 0) {
1734
+ const firstStop = timetable.stops[0].stop_name;
1735
+ const lastStop = timetable.stops[timetable.stops.length - 1].stop_name;
1736
+ if (firstStop === lastStop) {
1737
+ if (!isNullOrEmpty(timetable.routes[0].route_long_name)) {
1738
+ timetableLabel += ` - ${timetable.routes[0].route_long_name}`;
1739
+ }
1740
+ timetableLabel += " - Loop";
1741
+ } else {
1742
+ timetableLabel += ` - ${firstStop} to ${lastStop}`;
1743
+ }
1744
+ } else if (timetable.direction_name !== null) {
1745
+ timetableLabel += ` to ${timetable.direction_name}`;
1746
+ }
1747
+ return timetableLabel;
1748
+ }
1749
+ function mergeTimetablesWithSameId(timetables) {
1750
+ if (timetables.length === 0) {
1751
+ return [];
1752
+ }
1753
+ const mergedTimetables = groupBy2(timetables, "timetable_id");
1754
+ return Object.values(mergedTimetables).map((timetableGroup) => {
1755
+ const mergedTimetable = omit(timetableGroup[0], "route_id");
1756
+ mergedTimetable.route_ids = timetableGroup.map(
1757
+ (timetable) => timetable.route_id
1758
+ );
1759
+ return mergedTimetable;
1760
+ });
1761
+ }
1762
+
1763
+ // src/app/index.ts
1764
+ var argv = yargs(hideBin(process.argv)).option("c", {
1765
+ alias: "configPath",
1766
+ describe: "Path to config file",
1767
+ default: "./config.json",
1768
+ type: "string"
1769
+ }).parseSync();
1770
+ var app = express();
1771
+ var router = express.Router();
1772
+ var configPath = argv.configPath || new URL("../../config.json", import.meta.url);
1773
+ var selectedConfig = JSON.parse(readFileSync(configPath, "utf8"));
1774
+ var config = setDefaultConfig(selectedConfig);
1775
+ config.noHead = false;
1776
+ config.assetPath = "/";
1777
+ config.log = console.log;
1778
+ config.logWarning = console.warn;
1779
+ config.logError = console.error;
1780
+ try {
1781
+ openDb2(config);
1782
+ } catch (error) {
1783
+ if (error?.code === "SQLITE_CANTOPEN") {
1784
+ config.logError(
1785
+ `Unable to open sqlite database "${config.sqlitePath}" defined as \`sqlitePath\` config.json. Ensure the parent directory exists or remove \`sqlitePath\` from config.json.`
1786
+ );
1787
+ }
1788
+ throw error;
1789
+ }
1790
+ router.get("/", async (request, response, next) => {
1791
+ try {
1792
+ const timetablePages = [];
1793
+ const timetablePageIds = map(
1794
+ getTimetablePagesForAgency(config),
1795
+ "timetable_page_id"
1796
+ );
1797
+ for (const timetablePageId of timetablePageIds) {
1798
+ const timetablePage = await getFormattedTimetablePage(
1799
+ timetablePageId,
1800
+ config
1801
+ );
1802
+ if (!timetablePage.consolidatedTimetables || timetablePage.consolidatedTimetables.length === 0) {
1803
+ console.error(
1804
+ `No timetables found for timetable_page_id=${timetablePage.timetable_page_id}`
1805
+ );
1806
+ }
1807
+ timetablePage.relativePath = `/timetables/${timetablePage.timetable_page_id}`;
1808
+ for (const timetable of timetablePage.consolidatedTimetables) {
1809
+ timetable.timetable_label = formatTimetableLabel(timetable);
1810
+ }
1811
+ timetablePages.push(timetablePage);
1812
+ }
1813
+ const html = await generateOverviewHTML(timetablePages, config);
1814
+ response.send(html);
1815
+ } catch (error) {
1816
+ console.error(error);
1817
+ next(error);
1818
+ }
1819
+ });
1820
+ router.get("/timetables/:timetablePageId", async (request, response, next) => {
1821
+ const { timetablePageId } = request.params;
1822
+ if (!timetablePageId) {
1823
+ return next(new Error("No timetablePageId provided"));
1824
+ }
1825
+ try {
1826
+ const timetablePage = await getFormattedTimetablePage(
1827
+ timetablePageId,
1828
+ config
1829
+ );
1830
+ const html = await generateTimetableHTML(timetablePage, config);
1831
+ response.send(html);
1832
+ } catch (error) {
1833
+ next(error);
1834
+ }
1835
+ });
1836
+ app.set("views", path2.join(fileURLToPath2(import.meta.url), "../../../views"));
1837
+ app.set("view engine", "pug");
1838
+ app.use(logger("dev"));
1839
+ var staticAssetPath = config.templatePath === void 0 ? path2.join(fileURLToPath2(import.meta.url), "../../../views/default") : untildify2(config.templatePath);
1840
+ app.use(express.static(staticAssetPath));
1841
+ app.use("/", router);
1842
+ app.set("port", process.env.PORT || 3e3);
1843
+ var server = app.listen(app.get("port"), () => {
1844
+ console.log(`Express server listening on port ${app.get("port")}`);
1845
+ });
1846
+ //# sourceMappingURL=index.js.map