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