-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.js
More file actions
1496 lines (1370 loc) · 62 KB
/
Copy pathcode.js
File metadata and controls
1496 lines (1370 loc) · 62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: deep-gray; icon-glyph: magic;
// ============================================================
// Transperth Train Widget v4.6
// Cancellation-aware, cache-horizon and accessible multi-line edition
// ============================================================
//
// Uses Transperth's combined "All" station boards and identifies
// services that actually make the configured journey by:
// 1. Matching TripId at a destination station at a later time; or
// 2. Matching a train terminating at the destination station.
//
// Preserves the journey-correlation engine and responsive layouts.
// Adds delay-aware countdowns, accessibility profiles, isolated journey
// caches, shared rate-limit backoff, shared short-lived station boards,
// render-time expiry pruning, cache coverage, cache provenance metadata,
// richer migration diagnostics, clearer cache-exhausted states, and
// first-class cancellation detection, alerts, styling and cache coverage.
//
// Scriptable can request a refresh time, but iOS ultimately decides
// when a Home Screen widget is refreshed.
// ============================================================
const CONFIG = {
journey: {
originStation: "Mt Lawley Stn",
originAlias: "Mt Lawley",
destinationStations: ["Perth Stn"],
destinationLabel: "Perth",
apiLine: "All",
maximumJourneyHours: 4,
allowTerminalDestinationFallback: true
},
departuresShown: {
small: 2,
medium: 3,
large: 6
},
// Display limits and cache depth are deliberately independent.
cacheDepartureBuffer: 2,
cacheHorizonMinutes: 180,
maximumCachedDepartures: 40,
cachedDepartureGraceMinutes: 2,
maximumCachedRealtimeAgeMinutes: 180,
staleStatusDisplay: "suppress", // "show", "suppress", or "replace"
staleStatusReplacement: "Cached schedule",
// Supported values: "alert", "show", or "hide".
// alert shows cancellations separately without consuming usable-service rows.
cancelledServiceDisplay: "alert",
cancelledAlertsShown: {
small: 1,
medium: 1,
large: 1
},
cancelledLabel: "Cancelled",
normalRefreshMinutes: 60,
travelRefreshMinutes: 10,
useTravelWindows: true,
travelWindows: [
{ start: "06:00", end: "08:30" },
{ start: "16:00", end: "18:30" }
],
refreshAtTravelWindowStart: true,
reuseFreshCacheWithoutRequest: false,
freshCacheReuseMinutes: 1,
staleMinutes: 10,
maximumCacheAgeMinutes: 180,
cacheSchemaVersion: 7,
requestTimeoutSeconds: 15,
retryTransientFailures: true,
maximumRequestAttempts: 2,
retryDelayMilliseconds: 400,
rateLimitBackoffMinutes: 15,
sharedBoardReuseSeconds: 45,
instanceId: "",
showBoardScope: true,
showDestination: true,
destinationStyle: "full", // "short" or "full"
showServiceLine: true,
serviceLineStyle: "short", // "short" or "full"
showPlatform: true,
showCars: true,
showTrainSeries: true,
showStatus: true,
showUpdatedTime: true,
useExpectedCountdowns: true,
sortMode: "scheduled", // "scheduled" or "expected"
accessibility: {
highContrastMode: false,
fontProfile: "normal", // "normal", "large", or "extra-large"
layoutProfile: "standard" // "standard" or "countdown"
},
smallWidget: {
showDestination: false,
showServiceLine: true,
showPlatform: false,
showCars: true,
showTrainSeries: true,
showStatus: false
},
darkMode: true,
colours: {
dark: {
background: "#0D1117",
primary: "#FFFFFF",
secondary: "#8B949E"
},
light: {
background: "#F8F9FA",
primary: "#111111",
secondary: "#5F6368"
},
live: "#30D158",
delayed: "#FFB000",
moderate: "#FF7A00",
severe: "#FF453A",
cancelled: "#FF453A",
information: "#64D2FF",
cached: "#FFD60A",
unavailable: "#8B949E"
},
cachePrefix: "transperth-journey-widget",
debugShowCounts: false,
debugShowDiagnostics: false,
debugLogging: true,
debugCacheLogging: true
};
const RUN_STARTED_AT = new Date();
const RUN_STARTED_MS = RUN_STARTED_AT.getTime();
const BASE_URL = "https://www.transperth.wa.gov.au";
const WIDGET_VERSION = "4.6";
const fm = FileManager.local();
function debug(message, value) {
if (!CONFIG.debugLogging) return;
console.log(value === undefined ? message : `${message}: ${JSON.stringify(value)}`);
}
function sleep(milliseconds) {
return new Promise(resolve => Timer.schedule(milliseconds, false, resolve));
}
function text(value) {
return value === null || value === undefined ? "" : String(value).trim();
}
function normaliseStationName(value) {
return text(value).toLowerCase().replace(/\s+stn$/i, "").replace(/\s+/g, " ").trim();
}
function safeFilePart(value) {
return text(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "unknown";
}
function originDisplayName() {
return text(CONFIG.journey.originAlias) || text(CONFIG.journey.originStation).replace(/\s+Stn$/i, "");
}
function getBoardUrl(station) {
return `${BASE_URL}/API/TrainLiveTimes/LiveStatus/GetStationLiveStatusAsync/` +
`${encodeURIComponent(CONFIG.journey.apiLine)}/${encodeURIComponent(station)}/false`;
}
function getLiveUrl() {
return `${BASE_URL}/Timetables/Live-Train-Times?line=` +
`${encodeURIComponent(CONFIG.journey.apiLine)}&station=` +
`${encodeURIComponent(CONFIG.journey.originStation)}`;
}
function requireNonEmptyString(value, description) {
if (typeof value !== "string" || !value.trim()) {
throw new Error(`${description} must be a non-empty string.`);
}
}
function requirePositiveNumber(value, description) {
const number = Number(value);
if (!Number.isFinite(number) || number <= 0) {
throw new Error(`${description} must be a positive number.`);
}
}
function validateColour(value, description) {
if (typeof value !== "string" || !/^#[0-9a-f]{6}$/i.test(value)) {
throw new Error(`${description} must be a six-digit hexadecimal colour.`);
}
}
function clockToMinutes(value) {
const match = text(value).match(/^(\d{1,2}):(\d{2})$/);
if (!match) return null;
const hour = Number(match[1]);
const minute = Number(match[2]);
if (hour > 23 || minute > 59) return null;
return hour * 60 + minute;
}
function validateConfiguration() {
requireNonEmptyString(CONFIG.journey.originStation, "Origin station");
requireNonEmptyString(CONFIG.journey.destinationLabel, "Destination label");
requireNonEmptyString(CONFIG.journey.apiLine, "API line selector");
requirePositiveNumber(CONFIG.journey.maximumJourneyHours, "Maximum journey hours");
if (!Array.isArray(CONFIG.journey.destinationStations) ||
CONFIG.journey.destinationStations.length === 0) {
throw new Error("At least one destination station is required.");
}
CONFIG.journey.destinationStations.forEach((station, index) =>
requireNonEmptyString(station, `Destination station ${index + 1}`));
["small", "medium", "large"].forEach(family =>
requirePositiveNumber(CONFIG.departuresShown[family], `${family} departure limit`));
requirePositiveNumber(CONFIG.normalRefreshMinutes, "Normal refresh interval");
requirePositiveNumber(CONFIG.travelRefreshMinutes, "Travel refresh interval");
requirePositiveNumber(CONFIG.staleMinutes, "Stale threshold");
requirePositiveNumber(CONFIG.maximumCacheAgeMinutes, "Maximum cache age");
requirePositiveNumber(CONFIG.requestTimeoutSeconds, "Request timeout");
requirePositiveNumber(CONFIG.maximumRequestAttempts, "Maximum request attempts");
requirePositiveNumber(CONFIG.cacheHorizonMinutes, "Cache horizon");
requirePositiveNumber(CONFIG.maximumCachedDepartures, "Maximum cached departures");
requirePositiveNumber(CONFIG.cachedDepartureGraceMinutes, "Cached departure grace");
requirePositiveNumber(CONFIG.maximumCachedRealtimeAgeMinutes, "Maximum cached real-time age");
requirePositiveNumber(CONFIG.rateLimitBackoffMinutes, "Rate-limit backoff");
requirePositiveNumber(CONFIG.sharedBoardReuseSeconds, "Shared board reuse interval");
if (typeof CONFIG.instanceId !== "string") throw new Error("instanceId must be a string.");
if (!["short", "full"].includes(CONFIG.destinationStyle)) {
throw new Error('destinationStyle must be "short" or "full".');
}
if (!["short", "full"].includes(CONFIG.serviceLineStyle)) {
throw new Error('serviceLineStyle must be "short" or "full".');
}
if (!["scheduled", "expected"].includes(CONFIG.sortMode)) {
throw new Error('sortMode must be "scheduled" or "expected".');
}
if (!["show", "suppress", "replace"].includes(CONFIG.staleStatusDisplay)) {
throw new Error('staleStatusDisplay must be "show", "suppress", or "replace".');
}
if (!["alert", "show", "hide"].includes(CONFIG.cancelledServiceDisplay)) {
throw new Error('cancelledServiceDisplay must be "alert", "show", or "hide".');
}
requireNonEmptyString(CONFIG.cancelledLabel, "Cancelled label");
["small", "medium", "large"].forEach(family =>
requirePositiveNumber(CONFIG.cancelledAlertsShown[family], `${family} cancellation alert limit`));
if (!CONFIG.accessibility || !["normal", "large", "extra-large"].includes(CONFIG.accessibility.fontProfile)) {
throw new Error('accessibility.fontProfile is invalid.');
}
if (!["standard", "countdown"].includes(CONFIG.accessibility.layoutProfile)) {
throw new Error('accessibility.layoutProfile is invalid.');
}
if (CONFIG.useTravelWindows) {
if (!Array.isArray(CONFIG.travelWindows)) throw new Error("travelWindows must be an array.");
CONFIG.travelWindows.forEach((window, index) => {
if (!window || clockToMinutes(window.start) === null || clockToMinutes(window.end) === null) {
throw new Error(`Travel window ${index + 1} must use valid HH:MM times.`);
}
});
}
const colours = CONFIG.colours;
[
[colours.dark.background, "Dark background"],
[colours.dark.primary, "Dark primary"],
[colours.dark.secondary, "Dark secondary"],
[colours.light.background, "Light background"],
[colours.light.primary, "Light primary"],
[colours.light.secondary, "Light secondary"],
[colours.live, "Live"], [colours.delayed, "Delayed"],
[colours.moderate, "Moderate delay"], [colours.severe, "Severe"],
[colours.cancelled, "Cancelled"], [colours.information, "Information"],
[colours.cached, "Cached"], [colours.unavailable, "Unavailable"]
].forEach(item => validateColour(item[0], item[1]));
}
function stableHash(value) {
let hash = 2166136261;
const input = text(value);
for (let index = 0; index < input.length; index += 1) {
hash ^= input.charCodeAt(index);
hash = Math.imul(hash, 16777619);
}
return (hash >>> 0).toString(16).padStart(8, "0");
}
function scriptIdentity() {
try { return text(Script.name()) || "transperth-widget"; }
catch (_) { return "transperth-widget"; }
}
function cacheIdentityData() {
return {
script: scriptIdentity(),
instanceId: text(CONFIG.instanceId),
origin: normaliseStationName(CONFIG.journey.originStation),
destinations: CONFIG.journey.destinationStations.map(normaliseStationName).sort(),
apiLine: text(CONFIG.journey.apiLine).toLowerCase(),
maximumJourneyHours: Number(CONFIG.journey.maximumJourneyHours),
terminalFallback: Boolean(CONFIG.journey.allowTerminalDestinationFallback),
useExpectedCountdowns: Boolean(CONFIG.useExpectedCountdowns),
sortMode: text(CONFIG.sortMode),
schemaVersion: Number(CONFIG.cacheSchemaVersion)
};
}
const JOURNEY_ID = [CONFIG.journey.originStation, ...CONFIG.journey.destinationStations.slice().sort()]
.map(safeFilePart).join("-to-");
const INSTANCE_HASH = stableHash(JSON.stringify(cacheIdentityData()));
const INSTANCE_LABEL = text(CONFIG.instanceId) || safeFilePart(scriptIdentity());
const CACHE_FILE = `${CONFIG.cachePrefix}-${INSTANCE_LABEL}-${JOURNEY_ID}-${INSTANCE_HASH}.json`;
const CACHE_PATH = fm.joinPath(fm.documentsDirectory(), CACHE_FILE);
const LEGACY_CACHE_PATH = fm.joinPath(fm.documentsDirectory(), `${CONFIG.cachePrefix}-${JOURNEY_ID}.json`);
const GLOBAL_RATE_LIMIT_PATH = fm.joinPath(fm.documentsDirectory(), `${CONFIG.cachePrefix}-global-rate-limit.json`);
const SHARED_BOARD_PREFIX = `${CONFIG.cachePrefix}-station-board`;
function cacheDebug(message, value) {
if (!CONFIG.debugCacheLogging && !CONFIG.debugLogging) return;
console.log(value === undefined
? `[Cache ${INSTANCE_HASH}] ${message}`
: `[Cache ${INSTANCE_HASH}] ${message}: ${JSON.stringify(value)}`);
}
function sharedBoardPath(station) {
const key = `${safeFilePart(station)}-${stableHash(normaliseStationName(station))}`;
return fm.joinPath(fm.documentsDirectory(), `${SHARED_BOARD_PREFIX}-${key}.json`);
}
function fontScaleFactor() {
if (CONFIG.accessibility.fontProfile === "extra-large") return 1.3;
if (CONFIG.accessibility.fontProfile === "large") return 1.15;
return 1;
}
function scaledFontSize(size) {
return Math.max(8, Math.round(size * fontScaleFactor()));
}
function buildStyles() {
const highContrast = Boolean(CONFIG.accessibility.highContrastMode);
const base = CONFIG.darkMode ? CONFIG.colours.dark : CONFIG.colours.light;
const theme = highContrast
? (CONFIG.darkMode
? { background: "#000000", primary: "#FFFFFF", secondary: "#FFFFFF" }
: { background: "#FFFFFF", primary: "#000000", secondary: "#000000" })
: base;
return {
colours: {
background: new Color(theme.background), primary: new Color(theme.primary),
secondary: new Color(theme.secondary),
live: new Color(highContrast ? "#00E676" : CONFIG.colours.live),
delayed: new Color(highContrast ? "#FFD600" : CONFIG.colours.delayed),
moderate: new Color(highContrast ? "#FF8500" : CONFIG.colours.moderate),
severe: new Color(highContrast ? "#FF3B30" : CONFIG.colours.severe),
cancelled: new Color(highContrast ? "#FF3B30" : CONFIG.colours.cancelled),
information: new Color(highContrast ? theme.primary : CONFIG.colours.information),
cached: new Color(highContrast ? "#FFD600" : CONFIG.colours.cached),
unavailable: new Color(highContrast ? theme.secondary : CONFIG.colours.unavailable)
},
fonts: {
smallTitle: Font.boldSystemFont(scaledFontSize(14)), regularTitle: Font.boldSystemFont(scaledFontSize(16)),
smallSubtitle: Font.systemFont(scaledFontSize(10)), regularSubtitle: Font.systemFont(scaledFontSize(11)),
smallTime: Font.mediumMonospacedSystemFont(scaledFontSize(17)), smallCountdown: Font.boldSystemFont(scaledFontSize(17)),
smallCountdownFocus: Font.boldSystemFont(scaledFontSize(22)), smallDetails: Font.systemFont(scaledFontSize(10)),
mediumTime: Font.mediumMonospacedSystemFont(scaledFontSize(15)), mediumCountdown: Font.boldSystemFont(scaledFontSize(14)),
mediumCountdownFocus: Font.boldSystemFont(scaledFontSize(20)), mediumInformation: Font.systemFont(scaledFontSize(10)),
mediumStatus: Font.mediumSystemFont(scaledFontSize(10)), largeTime: Font.mediumMonospacedSystemFont(scaledFontSize(16)),
largeCountdown: Font.boldSystemFont(scaledFontSize(15)), largeCountdownFocus: Font.boldSystemFont(scaledFontSize(22)),
largeInformation: Font.systemFont(scaledFontSize(11)), largeStatus: Font.mediumSystemFont(scaledFontSize(11)),
emptyHeading: Font.semiboldSystemFont(scaledFontSize(13)), emptyDetails: Font.systemFont(scaledFontSize(10)),
smallFooter: Font.systemFont(scaledFontSize(9)), regularFooter: Font.systemFont(scaledFontSize(10))
}
};
}
const STYLES = buildStyles();
function parseApiDate(value) {
const match = text(value).match(
/^(\d{1,2})\/(\d{1,2})\/(\d{4})\s+(\d{1,2}):(\d{2}):(\d{2})$/
);
if (!match) return null;
const date = new Date(Number(match[3]), Number(match[2]) - 1, Number(match[1]),
Number(match[4]), Number(match[5]), Number(match[6]), 0);
return Number.isNaN(date.getTime()) ? null : date;
}
function parseLastUpdated(value) {
return parseApiDate(text(value).replace(/\s+at\s+/i, " "));
}
function parseIsoDate(value) {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? null : date;
}
function minutesBetweenMs(later, earlier) {
return Math.floor((later - earlier) / 60000);
}
function minutesUntilTimestamp(timestamp) {
return Number.isFinite(timestamp) ? Math.ceil((timestamp - RUN_STARTED_MS) / 60000) : null;
}
function formatCountdown(minutes) {
if (minutes === null || !Number.isFinite(minutes)) return "--";
if (minutes <= 0) return "Due";
if (minutes < 60) return `${minutes}m`;
const hours = Math.floor(minutes / 60);
const remainder = minutes % 60;
return remainder === 0 ? `${hours}h` : `${hours}h ${String(remainder).padStart(2, "0")}m`;
}
function shortTime(date) {
if (!(date instanceof Date)) return "--:--";
const formatter = new DateFormatter();
formatter.locale = "en_AU";
formatter.dateFormat = "HH:mm";
return formatter.string(date);
}
function localDateTime(date) {
if (!(date instanceof Date)) return "--";
const formatter = new DateFormatter();
formatter.locale = "en_AU";
formatter.dateFormat = "dd/MM/yyyy HH:mm:ss";
return formatter.string(date);
}
function timeWithinWindow(current, start, end) {
if (start === null || end === null) return false;
return start <= end ? current >= start && current <= end : current >= start || current <= end;
}
function millisecondsUntilNextClockTime(targetMinutes) {
const target = new Date(RUN_STARTED_MS);
target.setHours(Math.floor(targetMinutes / 60), targetMinutes % 60, 0, 0);
if (target.getTime() <= RUN_STARTED_MS) target.setDate(target.getDate() + 1);
return target.getTime() - RUN_STARTED_MS;
}
function determineRefreshSchedule() {
const normal = Math.max(1, Number(CONFIG.normalRefreshMinutes) || 10);
const travel = Math.max(1, Number(CONFIG.travelRefreshMinutes) || 2);
const current = RUN_STARTED_AT.getHours() * 60 + RUN_STARTED_AT.getMinutes();
let inTravelWindow = false;
if (CONFIG.useTravelWindows && Array.isArray(CONFIG.travelWindows)) {
inTravelWindow = CONFIG.travelWindows.some(window =>
timeWithinWindow(current, clockToMinutes(window.start), clockToMinutes(window.end)));
}
let milliseconds = (inTravelWindow ? travel : normal) * 60000;
let reason = inTravelWindow ? "travel interval" : "normal interval";
if (!inTravelWindow && CONFIG.useTravelWindows && CONFIG.refreshAtTravelWindowStart) {
for (const window of CONFIG.travelWindows) {
const start = clockToMinutes(window.start);
if (start === null) continue;
const until = millisecondsUntilNextClockTime(start);
if (until > 0 && until < milliseconds) {
milliseconds = until;
reason = `next travel window at ${window.start}`;
}
}
}
return {
refreshDate: new Date(RUN_STARTED_MS + Math.max(60000, milliseconds)),
intervalMinutes: Math.max(1, Math.ceil(milliseconds / 60000)),
inTravelWindow,
reason
};
}
function buildConfigurationSignature() {
return JSON.stringify({
origin: CONFIG.journey.originStation,
destinations: CONFIG.journey.destinationStations.slice().sort(),
apiLine: CONFIG.journey.apiLine,
maximumJourneyHours: CONFIG.journey.maximumJourneyHours,
terminalFallback: CONFIG.journey.allowTerminalDestinationFallback,
useExpectedCountdowns: CONFIG.useExpectedCountdowns,
sortMode: CONFIG.sortMode,
instanceHash: INSTANCE_HASH
});
}
function buildCacheSignature(payload) {
const departures = payload.departures.map(item => [item.tripId, item.departure, item.tripStopSchedule,
item.destination, item.serviceLine, item.platform, item.cars, item.series, item.status,
item.statusDetail, item.isRealTime, item.matchMethod, item.matchedDestinationStation,
item.destinationCallSchedule].join("|")).join("~");
return [payload.schemaVersion, payload.configurationSignature, payload.updated,
payload.originCount, payload.matchedCount, departures].join("::");
}
function cacheValidation(payload, allowLegacy) {
if (!payload || typeof payload !== "object") return { valid: false, reason: "cache payload is not an object" };
const acceptedLegacySchemas = [5, 6];
if (allowLegacy ? !acceptedLegacySchemas.includes(Number(payload.schemaVersion))
: Number(payload.schemaVersion) !== Number(CONFIG.cacheSchemaVersion)) {
return { valid: false, reason: `schema ${payload.schemaVersion}; expected ${CONFIG.cacheSchemaVersion}` };
}
if (!Array.isArray(payload.departures)) return { valid: false, reason: "departures array is missing" };
if (!allowLegacy && payload.configurationSignature !== buildConfigurationSignature()) {
return { valid: false, reason: "configuration fingerprint does not match" };
}
if (allowLegacy) {
try {
const legacy = JSON.parse(payload.configurationSignature || "{}");
if (legacy.origin !== CONFIG.journey.originStation ||
JSON.stringify(legacy.destinations || []) !== JSON.stringify(CONFIG.journey.destinationStations.slice().sort()) ||
legacy.apiLine !== CONFIG.journey.apiLine) return { valid: false, reason: "legacy journey does not match" };
} catch (_) { return { valid: false, reason: "legacy signature is invalid" }; }
}
const cachedAt = parseIsoDate(payload.cachedAt);
if (!cachedAt) return { valid: false, reason: "cachedAt cannot be parsed" };
const ageMinutes = Math.max(0, minutesBetweenMs(RUN_STARTED_MS, cachedAt.getTime()));
if (ageMinutes > CONFIG.maximumCacheAgeMinutes) return { valid: false, reason: `cache is ${ageMinutes}m old`, ageMinutes };
return { valid: true, reason: "valid", ageMinutes };
}
function readCacheFile(path, allowLegacy) {
if (!fm.fileExists(path)) return { cache: null, reason: "file does not exist", path };
try {
const payload = JSON.parse(fm.readString(path));
const validation = cacheValidation(payload, allowLegacy);
return validation.valid
? { cache: payload, reason: allowLegacy ? "valid legacy cache" : "valid isolated cache", path, ageMinutes: validation.ageMinutes }
: { cache: null, reason: validation.reason, path, ageMinutes: validation.ageMinutes };
} catch (error) { return { cache: null, reason: `read or JSON error: ${error}`, path }; }
}
function nativeCacheProfile(coverage) {
return {
cacheOrigin: "native",
createdByVersion: WIDGET_VERSION,
migratedByVersion: "",
originalSchemaVersion: CONFIG.cacheSchemaVersion,
horizonMinutes: CONFIG.cacheHorizonMinutes,
maximumDepartures: CONFIG.maximumCachedDepartures,
extendedHorizonPopulated: true,
coverage: coverage || null
};
}
function legacyCacheProfile(payload, coverage) {
const existing = payload && payload.cacheProfile ? payload.cacheProfile : {};
return {
cacheOrigin: "legacy-migrated",
createdByVersion: text(existing.createdByVersion) || `schema-${payload.schemaVersion}`,
migratedByVersion: WIDGET_VERSION,
originalSchemaVersion: Number(payload.schemaVersion),
horizonMinutes: Number(existing.horizonMinutes || 0) || null,
maximumDepartures: Number(existing.maximumDepartures || 0) || null,
extendedHorizonPopulated: false,
coverage: coverage || null
};
}
function cacheOrigin(payload) {
return text(payload && payload.cacheProfile && payload.cacheProfile.cacheOrigin) || "unknown";
}
function migrateLegacyCache(result) {
const source = result.cache;
const coverage = buildCoverage(source.departures);
const profile = legacyCacheProfile(source, coverage);
const migrated = {
...source,
schemaVersion: CONFIG.cacheSchemaVersion,
configurationSignature: buildConfigurationSignature(),
instanceHash: INSTANCE_HASH,
scriptIdentity: scriptIdentity(),
migratedFromSchema: Number(source.schemaVersion),
migratedAt: new Date().toISOString(),
coverage,
cacheProfile: profile
};
migrated.signature = buildCacheSignature(migrated);
const first = parseIsoDate(coverage.firstDeparture);
const last = parseIsoDate(coverage.lastDeparture);
const diagnostics = {
from: result.path,
to: CACHE_PATH,
fromSchema: Number(source.schemaVersion),
departureCount: coverage.departureCount,
firstDepartureUtc: coverage.firstDeparture,
firstDepartureLocal: first ? localDateTime(first) : null,
lastDepartureUtc: coverage.lastDeparture,
lastDepartureLocal: last ? localDateTime(last) : null,
cacheAgeMinutes: result.ageMinutes,
cacheOrigin: profile.cacheOrigin,
createdByVersion: profile.createdByVersion,
migratedByVersion: profile.migratedByVersion,
extendedHorizonPopulated: false
};
try {
fm.writeString(CACHE_PATH, JSON.stringify(migrated));
cacheDebug("Legacy cache migrated with limited coverage", diagnostics);
cacheDebug(
"A successful v4.5.1 live refresh is required to populate the extended cache horizon"
);
} catch (error) {
cacheDebug("Legacy migration failed", { error: String(error), ...diagnostics });
}
return migrated;
}
function loadCacheDetailed() {
const isolated = readCacheFile(CACHE_PATH, false);
if (isolated.cache) {
cacheDebug("Cache accepted", {
path: isolated.path,
ageMinutes: isolated.ageMinutes,
entries: isolated.cache.departures.length,
coverage: isolated.cache.coverage,
cacheOrigin: cacheOrigin(isolated.cache),
cacheProfile: isolated.cache.cacheProfile || null
});
return isolated;
}
cacheDebug("Isolated cache unavailable", isolated);
const legacy = readCacheFile(LEGACY_CACHE_PATH, true);
if (legacy.cache) return { cache: migrateLegacyCache(legacy), reason: "legacy cache migrated",
path: CACHE_PATH, ageMinutes: legacy.ageMinutes, migrated: true };
cacheDebug("Legacy cache unavailable", legacy);
return { cache: null, reason: `isolated: ${isolated.reason}; legacy: ${legacy.reason}`, path: CACHE_PATH };
}
function loadCache() { return loadCacheDetailed().cache; }
function saveCacheIfChanged(payload) {
try {
payload.signature = buildCacheSignature(payload);
const existing = readCacheFile(CACHE_PATH, false);
if (existing.cache && existing.cache.signature === payload.signature) return false;
fm.writeString(CACHE_PATH, JSON.stringify(payload));
cacheDebug("Cache written", {
path: CACHE_PATH,
entries: payload.departures.length,
usableEntries: payload.coverage ? payload.coverage.usableDepartureCount : null,
cancelledEntries: payload.coverage ? payload.coverage.cancelledDepartureCount : null,
coverage: payload.coverage
});
return true;
} catch (error) { console.log(`Could not save cache: ${error}`); return false; }
}
function readJsonFile(path) {
try { return fm.fileExists(path) ? JSON.parse(fm.readString(path)) : null; }
catch (_) { return null; }
}
function writeJsonFile(path, value) { try { fm.writeString(path, JSON.stringify(value)); return true; } catch (_) { return false; } }
function activeGlobalBackoff() {
const state = readJsonFile(GLOBAL_RATE_LIMIT_PATH);
const until = state ? parseIsoDate(state.rateLimitUntil) : null;
if (!until || until.getTime() <= RUN_STARTED_MS) return null;
return {
until,
untilUtc: until.toISOString(),
untilLocal: localDateTime(until),
minutesRemaining: Math.max(1, Math.ceil((until - RUN_STARTED_MS) / 60000)),
station: text(state.station),
sourceInstance: text(state.instanceHash)
};
}
function recordGlobalBackoff(station) {
const until = new Date(RUN_STARTED_MS + CONFIG.rateLimitBackoffMinutes * 60000);
const state = {
rateLimitUntil: until.toISOString(),
station,
instanceHash: INSTANCE_HASH,
script: scriptIdentity(),
recordedAt: new Date().toISOString()
};
writeJsonFile(GLOBAL_RATE_LIMIT_PATH, state);
cacheDebug("Shared rate-limit backoff recorded", {
station,
retryAfterUtc: until.toISOString(),
retryAfterLocal: localDateTime(until),
backoffMinutes: CONFIG.rateLimitBackoffMinutes,
statePath: GLOBAL_RATE_LIMIT_PATH
});
return until;
}
function clearExpiredGlobalBackoff() {
const state = readJsonFile(GLOBAL_RATE_LIMIT_PATH);
const until = state ? parseIsoDate(state.rateLimitUntil) : null;
if (until && until.getTime() <= RUN_STARTED_MS) {
try { fm.remove(GLOBAL_RATE_LIMIT_PATH); } catch (_) {}
}
}
function cacheAgeMinutes(payload) {
const cachedAt = payload ? parseIsoDate(payload.cachedAt) : null;
return cachedAt ? Math.max(0, minutesBetweenMs(RUN_STARTED_MS, cachedAt.getTime())) : null;
}
function canReuseFreshCache(payload) {
const age = cacheAgeMinutes(payload);
return Boolean(CONFIG.reuseFreshCacheWithoutRequest && payload && age !== null &&
age <= Math.max(0, Number(CONFIG.freshCacheReuseMinutes) || 0));
}
function destinationDisplayText(value) {
const destination = text(value);
if (CONFIG.destinationStyle === "full") return destination;
const lower = destination.toLowerCase();
if (lower.includes("perth underground")) return "PUG";
if (lower.includes("elizabeth quay")) return "EQY";
if (lower.includes("airport central")) return "APT";
if (lower === "perth") return "PER";
return destination.replace(/\s+Stn$/i, "").split(/\s+/)
.map(part => part.charAt(0).toUpperCase()).join("").slice(0, 4);
}
function serviceLineDisplayText(value) {
const line = text(value);
return CONFIG.serviceLineStyle === "full" ? line : line.replace(/\s+Line$/i, "");
}
function delayMinutesFromText(value) {
const match = text(value).match(/(\d+)\s*min(?:ute)?s?\s+delay/i);
return match ? Number(match[1]) : 0;
}
function clockDateNear(clockValue, anchorDate) {
const match = text(clockValue).match(/^(\d{1,2}):(\d{2})$/);
if (!match || !(anchorDate instanceof Date)) return null;
const candidate = new Date(anchorDate.getTime());
candidate.setHours(Number(match[1]), Number(match[2]), 0, 0);
if (candidate.getTime() < anchorDate.getTime() - 12 * 3600000) candidate.setDate(candidate.getDate() + 1);
else if (candidate.getTime() > anchorDate.getTime() + 12 * 3600000) candidate.setDate(candidate.getDate() - 1);
return candidate;
}
function expectedDepartureDate(departure) {
const scheduled = parseApiDate(departure.tripStopSchedule);
if (!scheduled) return null;
if (departure.isRealTime) {
const live = clockDateNear(departure.departure, scheduled);
if (live) return live;
}
return new Date(scheduled.getTime() + delayMinutesFromText(departure.statusDetail) * 60000);
}
function departureSortTimestamp(departure, useExpected) {
const scheduled = parseApiDate(departure.tripStopSchedule);
if (!scheduled) return Number.MAX_SAFE_INTEGER;
if (useExpected) {
const expected = expectedDepartureDate(departure);
if (expected) return expected.getTime();
}
return scheduled.getTime();
}
function isCancelledService(departure) {
const detail = text(departure && departure.statusDetail);
return /\bcancel(?:led|ed)\b/i.test(detail);
}
function resolvedStatusText(departure) {
if (isCancelledService(departure)) return CONFIG.cancelledLabel;
if (departure.statusDetail) return departure.statusDetail;
if (departure.isRealTime === false) return "Scheduled";
if (Number(departure.status) === 1) return "On Time";
if (Number(departure.status) === 2) return "Delayed";
return "Live";
}
function resolvedStatusKey(departure) {
if (isCancelledService(departure)) return "cancelled";
const delay = delayMinutesFromText(departure.statusDetail);
if (delay >= 10) return "severe";
if (delay >= 5) return "moderate";
if (delay >= 1 || Number(departure.status) === 2) return "delayed";
if (departure.isRealTime === false) return "unavailable";
return "live";
}
function colourForStatusKey(key) {
return STYLES.colours[key] || STYLES.colours.unavailable;
}
function compactApiDeparture(entry, boardStation) {
return {
boardStation: text(boardStation),
tripId: Number(entry.TripId || 0),
departure: text(entry.Departure),
tripStopSchedule: text(entry.TripStopSchedule),
destination: text(entry.Destination),
serviceLine: text(entry.LineName),
platform: text(entry.Platform),
cars: text(entry.Ncar),
series: text(entry.Series),
status: entry.Status === null || entry.Status === undefined ? null : Number(entry.Status),
statusDetail: text(entry.StatusDetail),
isRealTime: Boolean(entry.IsRealTime)
};
}
function retryableHttpStatus(status) {
return [408, 425, 500, 502, 503, 504].includes(status);
}
function classifyFailure(error) {
if (error && error.kind) return error.kind;
const message = text(error && (error.message || error)).toLowerCase();
if (message.includes("rate limit")) return "rate-limited";
if (message.includes("not recognised") || message.includes("configuration")) return "configuration";
if (message.includes("network") || message.includes("internet") || message.includes("timed out")) return "network";
if (message.includes("json") || message.includes("response structure")) return "api-response";
return "request";
}
function failureLabel(kind) {
return ({ "rate-limited": "Rate limited", network: "Network error", configuration: "Configuration error",
"api-response": "API response error", "cache-exhausted": "Cache exhausted" })[kind] || "Live data error";
}
function loadSharedBoard(station) {
const path = sharedBoardPath(station);
const payload = readJsonFile(path);
const fetchedAt = payload ? parseIsoDate(payload.fetchedAt) : null;
if (!payload || !fetchedAt || !Array.isArray(payload.departures)) return null;
const ageSeconds = Math.max(0, Math.floor((RUN_STARTED_MS - fetchedAt.getTime()) / 1000));
if (ageSeconds > CONFIG.sharedBoardReuseSeconds) return null;
cacheDebug("Shared station board reused", { station, ageSeconds, path });
return payload;
}
function saveSharedBoard(result) {
const payload = { ...result, fetchedAt: new Date().toISOString(), schemaVersion: 1 };
writeJsonFile(sharedBoardPath(result.requestedStation), payload);
}
async function performBoardRequest(station) {
const shared = loadSharedBoard(station);
if (shared) return shared;
const request = new Request(getBoardUrl(station));
request.timeoutInterval = Math.max(5, Number(CONFIG.requestTimeoutSeconds) || 15);
request.headers = { "ModuleId": "5111", "TabId": "248",
"Accept": "application/json, text/javascript, */*; q=0.01", "X-Requested-With": "XMLHttpRequest",
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS like Mac OS X) AppleWebKit/605.1.15" };
const responseText = await request.loadString();
const status = request.response ? Number(request.response.statusCode) : null;
if (status === 429) {
const error = new Error(`${station}: Transperth rate limit reached.`);
error.retryable = false; error.kind = "rate-limited"; error.station = station;
error.retryAfterDate = recordGlobalBackoff(station); throw error;
}
if (Number.isFinite(status) && status !== 200) {
const error = new Error(`${station}: HTTP ${status}.`);
error.retryable = retryableHttpStatus(status); error.kind = error.retryable ? "network" : "api-response";
throw error;
}
let body;
try { body = JSON.parse(responseText); }
catch (_) { const error = new Error(`${station}: invalid JSON response.`); error.retryable = false; error.kind = "api-response"; throw error; }
if (!body || body.result !== "success" || !body.data || !Array.isArray(body.data.StatusDetailList)) {
const error = new Error(`${station}: unexpected API response structure.`); error.retryable = false; error.kind = "api-response"; throw error;
}
const returnedStation = text(body.data.Station);
if (returnedStation.toLowerCase().includes("check spelling")) {
const error = new Error(`${station}: station was not recognised.`); error.retryable = false; error.kind = "configuration"; throw error;
}
const result = { requestedStation: station, returnedStation: returnedStation || station,
updated: text(body.data.LastUpdated), departures: body.data.StatusDetailList.map(entry => compactApiDeparture(entry, returnedStation || station)) };
saveSharedBoard(result);
return result;
}
async function requestBoardWithRetry(station) {
const attempts = CONFIG.retryTransientFailures
? Math.min(2, Math.max(1, Math.floor(Number(CONFIG.maximumRequestAttempts) || 1)))
: 1;
let lastError;
for (let attempt = 1; attempt <= attempts; attempt += 1) {
try {
debug("Requesting station board", { station, attempt, attempts });
return await performBoardRequest(station);
} catch (error) {
lastError = error;
if (attempt >= attempts || error.retryable === false) throw error;
await sleep(Math.max(100, Number(CONFIG.retryDelayMilliseconds) || 400));
}
}
throw lastError || new Error(`${station}: request failed.`);
}
function buildTripIndex(departures) {
const index = new Map();
for (const departure of departures) {
if (!departure.tripId) continue;
if (!index.has(departure.tripId)) index.set(departure.tripId, []);
index.get(departure.tripId).push(departure);
}
return index;
}
function derivedTerminalNames() {
const names = new Set();
for (const station of CONFIG.journey.destinationStations) {
names.add(normaliseStationName(station));
}
return names;
}
function findLaterDestinationCall(originDeparture, destinationBoards) {
const originDate = parseApiDate(originDeparture.tripStopSchedule);
if (!originDate || !originDeparture.tripId) return null;
const maximumMilliseconds = Number(CONFIG.journey.maximumJourneyHours) * 3600000;
let best = null;
for (const board of destinationBoards) {
const matches = board.index.get(originDeparture.tripId) || [];
for (const call of matches) {
const callDate = parseApiDate(call.tripStopSchedule);
if (!callDate) continue;
const difference = callDate.getTime() - originDate.getTime();
if (difference <= 0 || difference > maximumMilliseconds) continue;
if (!best || callDate < best.callDate) {
best = {
station: board.station,
call,
callDate,
journeyMinutes: Math.round(difference / 60000)
};
}
}
}
return best;
}
function matchJourney(originDeparture, destinationBoards, terminalNames) {
const laterCall = findLaterDestinationCall(originDeparture, destinationBoards);
if (laterCall) {
return {
matched: true,
method: "trip-id",
destinationStation: laterCall.station,
destinationCallSchedule: laterCall.call.tripStopSchedule,
journeyMinutes: laterCall.journeyMinutes
};
}
const terminalMatch = CONFIG.journey.allowTerminalDestinationFallback &&
terminalNames.has(normaliseStationName(originDeparture.destination));
if (terminalMatch) {
return {
matched: true,
method: "terminal",
destinationStation: originDeparture.destination,
destinationCallSchedule: "",
journeyMinutes: null
};
}
return { matched: false, method: "none" };
}
function departureReferenceTimestamp(departure, useExpected) {
return departureSortTimestamp(departure, useExpected);
}
function correlateJourney(originBoard, destinationResults) {
const destinationBoards = destinationResults.map(result => ({ station: result.returnedStation, index: buildTripIndex(result.departures) }));
const terminalNames = derivedTerminalNames();
const lowerCutoff = RUN_STARTED_MS - CONFIG.cachedDepartureGraceMinutes * 60000;
const matched = [];
for (const departure of originBoard.departures) {
const reference = departureReferenceTimestamp(departure, CONFIG.useExpectedCountdowns);
if (!Number.isFinite(reference) || reference < lowerCutoff) continue;
const journeyMatch = matchJourney(departure, destinationBoards, terminalNames);
if (!journeyMatch.matched) continue;
matched.push({ ...departure, matchMethod: journeyMatch.method,
matchedDestinationStation: journeyMatch.destinationStation,
destinationCallSchedule: journeyMatch.destinationCallSchedule, journeyMinutes: journeyMatch.journeyMinutes });
}
matched.sort((a,b) => departureSortTimestamp(a, CONFIG.sortMode === "expected") - departureSortTimestamp(b, CONFIG.sortMode === "expected"));
return matched;
}
function departuresForCache(departures) {
const horizon = RUN_STARTED_MS + CONFIG.cacheHorizonMinutes * 60000;
return departures.filter(item => {
const timestamp = departureReferenceTimestamp(item, true);
return Number.isFinite(timestamp) && timestamp <= horizon;
}).slice(0, Math.floor(CONFIG.maximumCachedDepartures));
}
function buildCoverage(departures) {