minotor 12.0.0 → 12.0.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.
@@ -87,8 +87,8 @@ export declare class RoutingState implements IRaptorState {
87
87
  */
88
88
  private readonly maxDuration?;
89
89
  /**
90
- * Every stop that has received an arrival improvement during the current run,
91
- * in the order the improvements occurred. Used by {@link resetFor} to clear
90
+ * Every stop reached during the current run, recorded once in first-reached
91
+ * order. Used by {@link resetFor} to clear
92
92
  * only the touched entries instead of scanning the entire array.
93
93
  */
94
94
  private readonly reachedStops;
@@ -9,7 +9,7 @@ export declare class StopsIndex {
9
9
  private readonly sourceStopsMap;
10
10
  private readonly textIndex;
11
11
  private readonly geoIndex;
12
- private readonly stopPoints;
12
+ private readonly geoStopIds;
13
13
  constructor(stops: Stop[]);
14
14
  /**
15
15
  * Deserializes a binary representation of the stops.
@@ -201,6 +201,8 @@ export declare class Route {
201
201
  * @returns An array of indices where the stop appears in the route, or an empty array if the stop is not found.
202
202
  */
203
203
  stopRouteIndices(stopId: StopId): StopRouteIndex[];
204
+ /** Returns the first occurrence without allocating an array. */
205
+ firstStopRouteIndex(stopId: StopId): StopRouteIndex | undefined;
204
206
  /**
205
207
  * Retrieves the id of a stop at a given index in a route.
206
208
  * @param stopRouteIndex The route index of the stop.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minotor",
3
- "version": "12.0.0",
3
+ "version": "12.0.1",
4
4
  "description": "A lightweight client-side transit routing library.",
5
5
  "keywords": [
6
6
  "minotor",
@@ -65,7 +65,7 @@
65
65
  "format": "prettier --write .",
66
66
  "test": "tsx --test src/**/__tests__/*.test.ts",
67
67
  "e2e": "tsx --test src/__e2e__/*.test.ts",
68
- "perf": "tsx src/cli/minotor perf -s src/__e2e__/timetable/stops.bin -t src/__e2e__/timetable/timetable.bin src/__e2e__/benchmark.json",
68
+ "perf": "node --expose-gc --import tsx src/cli/minotor perf -s src/__e2e__/timetable/stops.bin -t src/__e2e__/timetable/timetable.bin src/__e2e__/benchmark.json",
69
69
  "repl": "tsx src/cli/minotor repl -s src/__e2e__/timetable/stops.bin -t src/__e2e__/timetable/timetable.bin",
70
70
  "test:watch": "tsx --watch --test src/**/*.test.ts",
71
71
  "test:coverage": "c8 -x 'src/**/proto/**/*.ts' -x 'src/**/__tests__/*.ts' --check-coverage --lines=85 tsx --test src/**/__tests__/*.test.ts",
@@ -14,6 +14,7 @@ import { Router, StopsIndex, Timetable } from '../router.js';
14
14
  import {
15
15
  loadQueriesFromJson,
16
16
  loadRangeQueriesFromJson,
17
+ measureRetainedMemory,
17
18
  prettyPrintPerformanceResults,
18
19
  testBestRoutePerformance,
19
20
  testRangeResultPerformance,
@@ -175,9 +176,25 @@ program
175
176
  const stopsIndex = StopsIndex.fromData(
176
177
  fs.readFileSync(options.stopsPath),
177
178
  );
178
- const timetable = Timetable.fromData(
179
- fs.readFileSync(options.timetablePath),
179
+ const loading = measureRetainedMemory(() =>
180
+ Timetable.fromData(fs.readFileSync(options.timetablePath)),
180
181
  );
182
+ const timetable = loading.value;
183
+ console.log(
184
+ `Timetable load (read + decode): ${loading.loadTimeMs.toFixed(2)} ms`,
185
+ );
186
+ if (
187
+ loading.retainedHeapMiB !== undefined &&
188
+ loading.retainedArrayBuffersMiB !== undefined
189
+ ) {
190
+ console.log(
191
+ `Timetable retained after GC: heap ${loading.retainedHeapMiB.toFixed(2)} MiB; ArrayBuffers ${loading.retainedArrayBuffersMiB.toFixed(2)} MiB`,
192
+ );
193
+ } else {
194
+ console.log(
195
+ 'Retained memory skipped: explicit GC unavailable; use node --expose-gc.',
196
+ );
197
+ }
181
198
  const router = new Router(timetable, stopsIndex);
182
199
 
183
200
  const queries = loadQueriesFromJson(routesPath, stopsIndex);
package/src/cli/perf.ts CHANGED
@@ -13,7 +13,68 @@ import { timeFromString, timeToString } from '../timetable/time.js';
13
13
  type PerformanceResult = {
14
14
  label: string;
15
15
  meanTimeUs: number;
16
- meanMemoryMb: number;
16
+ meanHeapMiB: number;
17
+ meanArrayBuffersMiB: number;
18
+ };
19
+
20
+ // Keep operation results reachable until the ending memory sample has been taken.
21
+ const retainedResults: unknown[] = [];
22
+
23
+ /** Observed deltas, not peak memory or total allocations; GC can make them negative. */
24
+ export const measurePerformance = (
25
+ operation: () => unknown,
26
+ iterations: number,
27
+ ): Omit<PerformanceResult, 'label'> => {
28
+ let totalTime = 0;
29
+ let totalHeap = 0;
30
+ let totalArrayBuffers = 0;
31
+ for (let i = 0; i < iterations; i++) {
32
+ global.gc?.();
33
+ const before = process.memoryUsage();
34
+ const start = performance.now();
35
+ const result = operation();
36
+ const end = performance.now();
37
+ retainedResults.push(result);
38
+ const after = process.memoryUsage();
39
+ retainedResults.pop();
40
+ totalTime += (end - start) * 1_000;
41
+ totalHeap += after.heapUsed - before.heapUsed;
42
+ totalArrayBuffers += after.arrayBuffers - before.arrayBuffers;
43
+ }
44
+ return {
45
+ meanTimeUs: totalTime / iterations,
46
+ meanHeapMiB: totalHeap / iterations / (1024 * 1024),
47
+ meanArrayBuffersMiB: totalArrayBuffers / iterations / (1024 * 1024),
48
+ };
49
+ };
50
+
51
+ /** Measure retained storage after collection, keeping only the returned value alive. */
52
+ export const measureRetainedMemory = <T>(
53
+ operation: () => T,
54
+ ): {
55
+ value: T;
56
+ loadTimeMs: number;
57
+ retainedHeapMiB?: number;
58
+ retainedArrayBuffersMiB?: number;
59
+ } => {
60
+ const gc = global.gc;
61
+ gc?.();
62
+ const before = gc ? process.memoryUsage() : undefined;
63
+ const start = performance.now();
64
+ const value = operation();
65
+ const loadTimeMs = performance.now() - start;
66
+ if (!gc || !before) return { value, loadTimeMs };
67
+ // A second collection lets backing storage released by finalization settle.
68
+ gc();
69
+ gc();
70
+ const after = process.memoryUsage();
71
+ return {
72
+ value,
73
+ loadTimeMs,
74
+ retainedHeapMiB: (after.heapUsed - before.heapUsed) / (1024 * 1024),
75
+ retainedArrayBuffersMiB:
76
+ (after.arrayBuffers - before.arrayBuffers) / (1024 * 1024),
77
+ };
17
78
  };
18
79
 
19
80
  type SerializedQuery = {
@@ -204,7 +265,7 @@ export const loadRangeQueriesFromJson = (
204
265
  * yield a more stable mean at the cost of longer wall-clock time.
205
266
  * @param stopsIndex - Used to resolve stop names for result labels.
206
267
  * @returns An array of {@link PerformanceResult} objects, one per query, each
207
- * containing the mean wall-clock time (µs) and mean heap delta (MB).
268
+ * containing the mean wall-clock time (µs) and mean heap and ArrayBuffer deltas (MiB).
208
269
  */
209
270
  export const testRouterPerformance = (
210
271
  router: Router,
@@ -215,32 +276,9 @@ export const testRouterPerformance = (
215
276
  const results: PerformanceResult[] = [];
216
277
 
217
278
  for (const task of tasks) {
218
- let totalTime = 0;
219
- let totalMemory = 0;
220
-
221
- for (let i = 0; i < iterations; i++) {
222
- if (global.gc) {
223
- global.gc();
224
- }
225
-
226
- const startMemory = process.memoryUsage().heapUsed;
227
- const startTime = performance.now();
228
-
229
- router.route(task);
230
-
231
- const endTime = performance.now();
232
- const endMemory = process.memoryUsage().heapUsed;
233
-
234
- totalTime += (endTime - startTime) * 1_000;
235
- if (endMemory >= startMemory) {
236
- totalMemory += endMemory - startMemory;
237
- }
238
- }
239
-
240
279
  results.push({
241
280
  label: buildQueryLabel(task, stopsIndex),
242
- meanTimeUs: totalTime / iterations,
243
- meanMemoryMb: totalMemory / iterations / (1024 * 1024),
281
+ ...measurePerformance(() => router.route(task), iterations),
244
282
  });
245
283
  }
246
284
 
@@ -258,7 +296,7 @@ export const testRouterPerformance = (
258
296
  * @param iterations - Number of times `bestRoute` is called per query.
259
297
  * @param stopsIndex - Used to resolve stop names for result labels.
260
298
  * @returns An array of {@link PerformanceResult} objects, one per query, each
261
- * containing the mean wall-clock time (µs) and mean heap delta (MB) for the
299
+ * containing the mean wall-clock time (µs) and mean heap and ArrayBuffer deltas (MiB) for the
262
300
  * `bestRoute` call alone.
263
301
  */
264
302
  export const testBestRoutePerformance = (
@@ -272,32 +310,9 @@ export const testBestRoutePerformance = (
272
310
  for (const task of tasks) {
273
311
  const result = router.route(task);
274
312
 
275
- let totalTime = 0;
276
- let totalMemory = 0;
277
-
278
- for (let i = 0; i < iterations; i++) {
279
- if (global.gc) {
280
- global.gc();
281
- }
282
-
283
- const startMemory = process.memoryUsage().heapUsed;
284
- const startTime = performance.now();
285
-
286
- result.bestRoute();
287
-
288
- const endTime = performance.now();
289
- const endMemory = process.memoryUsage().heapUsed;
290
-
291
- totalTime += (endTime - startTime) * 1_000;
292
- if (endMemory >= startMemory) {
293
- totalMemory += endMemory - startMemory;
294
- }
295
- }
296
-
297
313
  results.push({
298
314
  label: buildQueryLabel(task, stopsIndex),
299
- meanTimeUs: totalTime / iterations,
300
- meanMemoryMb: totalMemory / iterations / (1024 * 1024),
315
+ ...measurePerformance(() => result.bestRoute(), iterations),
301
316
  });
302
317
  }
303
318
 
@@ -313,7 +328,7 @@ export const testBestRoutePerformance = (
313
328
  * @param iterations - Number of times each query is repeated.
314
329
  * @param stopsIndex - Used to resolve stop names for result labels.
315
330
  * @returns An array of {@link PerformanceResult} objects, one per query, each
316
- * containing the mean wall-clock time (µs) and mean heap delta (MB).
331
+ * containing the mean wall-clock time (µs) and mean heap and ArrayBuffer deltas (MiB).
317
332
  */
318
333
  export const testRangeRouterPerformance = (
319
334
  router: Router,
@@ -324,32 +339,9 @@ export const testRangeRouterPerformance = (
324
339
  const results: PerformanceResult[] = [];
325
340
 
326
341
  for (const task of tasks) {
327
- let totalTime = 0;
328
- let totalMemory = 0;
329
-
330
- for (let i = 0; i < iterations; i++) {
331
- if (global.gc) {
332
- global.gc();
333
- }
334
-
335
- const startMemory = process.memoryUsage().heapUsed;
336
- const startTime = performance.now();
337
-
338
- router.rangeRoute(task);
339
-
340
- const endTime = performance.now();
341
- const endMemory = process.memoryUsage().heapUsed;
342
-
343
- totalTime += (endTime - startTime) * 1_000;
344
- if (endMemory >= startMemory) {
345
- totalMemory += endMemory - startMemory;
346
- }
347
- }
348
-
349
342
  results.push({
350
343
  label: buildQueryLabel(task, stopsIndex),
351
- meanTimeUs: totalTime / iterations,
352
- meanMemoryMb: totalMemory / iterations / (1024 * 1024),
344
+ ...measurePerformance(() => router.rangeRoute(task), iterations),
353
345
  });
354
346
  }
355
347
 
@@ -367,7 +359,7 @@ export const testRangeRouterPerformance = (
367
359
  * @param iterations - Number of times `getRoutes` is called per query.
368
360
  * @param stopsIndex - Used to resolve stop names for result labels.
369
361
  * @returns An array of {@link PerformanceResult} objects, one per query, each
370
- * containing the mean wall-clock time (µs) and mean heap delta (MB) for the
362
+ * containing the mean wall-clock time (µs) and mean heap and ArrayBuffer deltas (MiB) for the
371
363
  * `getRoutes` call alone.
372
364
  */
373
365
  export const testRangeResultPerformance = (
@@ -381,40 +373,15 @@ export const testRangeResultPerformance = (
381
373
  for (const task of tasks) {
382
374
  const rangeResult: RangeResult = router.rangeRoute(task);
383
375
 
384
- let totalTime = 0;
385
- let totalMemory = 0;
386
-
387
- for (let i = 0; i < iterations; i++) {
388
- if (global.gc) {
389
- global.gc();
390
- }
391
-
392
- const startMemory = process.memoryUsage().heapUsed;
393
- const startTime = performance.now();
394
-
395
- rangeResult.getRoutes();
396
-
397
- const endTime = performance.now();
398
- const endMemory = process.memoryUsage().heapUsed;
399
-
400
- totalTime += (endTime - startTime) * 1_000;
401
- if (endMemory >= startMemory) {
402
- totalMemory += endMemory - startMemory;
403
- }
404
- }
405
-
406
376
  results.push({
407
377
  label: buildQueryLabel(task, stopsIndex),
408
- meanTimeUs: totalTime / iterations,
409
- meanMemoryMb: totalMemory / iterations / (1024 * 1024),
378
+ ...measurePerformance(() => rangeResult.getRoutes(), iterations),
410
379
  });
411
380
  }
412
381
 
413
382
  return results;
414
383
  };
415
384
 
416
- // ─── Output ───────────────────────────────────────────────────────────────────
417
-
418
385
  /**
419
386
  * Prints a table summary of performance results to stdout.
420
387
  *
@@ -442,14 +409,19 @@ export const prettyPrintPerformanceResults = (
442
409
  const meanTime =
443
410
  results.reduce((s, r) => s + r.meanTimeUs, 0) / results.length;
444
411
  const meanMem =
445
- results.reduce((s, r) => s + r.meanMemoryMb, 0) / results.length;
412
+ results.reduce((s, r) => s + r.meanHeapMiB, 0) / results.length;
413
+ const meanBuffers =
414
+ results.reduce((s, r) => s + r.meanArrayBuffersMiB, 0) / results.length;
446
415
 
447
416
  const queryHeader = 'Query';
448
417
  const timeHeader = 'Time (µs)';
449
- const memHeader = 'Mem (MB)';
418
+ const memHeader = 'Heap Δ (MiB)';
419
+ const buffersHeader = 'ArrayBuffers Δ (MiB)';
450
420
 
451
421
  const timeVals = results.map((r) => fmtTime(r.meanTimeUs));
452
- const memVals = results.map((r) => fmtMem(r.meanMemoryMb));
422
+ const memVals = results.map((r) => fmtMem(r.meanHeapMiB));
423
+ const bufferVals = results.map((r) => fmtMem(r.meanArrayBuffersMiB));
424
+ const meanBuffersStr = fmtMem(meanBuffers);
453
425
  const meanTimeStr = fmtTime(meanTime);
454
426
  const meanMemStr = fmtMem(meanMem);
455
427
 
@@ -473,14 +445,29 @@ export const prettyPrintPerformanceResults = (
473
445
  { header: queryHeader, width: queryWidth, align: 'left' },
474
446
  { header: timeHeader, width: timeWidth, align: 'right' },
475
447
  { header: memHeader, width: memWidth, align: 'right' },
448
+ {
449
+ header: buffersHeader,
450
+ width: Math.max(
451
+ buffersHeader.length,
452
+ meanBuffersStr.length,
453
+ ...bufferVals.map((v) => v.length),
454
+ ),
455
+ align: 'right',
456
+ },
476
457
  ];
477
458
 
478
459
  const rows = results.map((r, i) => [
479
460
  r.label,
480
461
  timeVals[i] ?? '',
481
462
  memVals[i] ?? '',
463
+ bufferVals[i] ?? '',
482
464
  ]);
483
- const footer = ['mean', meanTimeStr, meanMemStr];
465
+ const footer = ['mean', meanTimeStr, meanMemStr, meanBuffersStr];
484
466
 
485
467
  console.log(renderTable(columns, rows, footer));
468
+ if (!global.gc) {
469
+ console.log(
470
+ 'Explicit GC unavailable; use node --expose-gc for more consistent samples.',
471
+ );
472
+ }
486
473
  };
@@ -76,3 +76,32 @@ describe('RoutingState', () => {
76
76
  });
77
77
  });
78
78
  });
79
+
80
+ describe('RoutingState reuse', () => {
81
+ it('resets repeated improvements and all rounds like a fresh state', () => {
82
+ const access = [{ fromStopId: 0, toStopId: 0, duration: 0 }];
83
+ const state = new RoutingState(100, [2], access, 4, 3, 60);
84
+ state.updateArrival(0, 99, 1);
85
+ state.updateArrival(1, 120, 1);
86
+ state.graph[1]![1] = { stopId: 1, arrival: 120 };
87
+ state.updateArrival(1, 110, 2);
88
+ state.graph[2]![1] = { stopId: 1, arrival: 110 };
89
+ state.updateArrival(2, 130, 3);
90
+ state.graph[3]![2] = { stopId: 2, arrival: 130 };
91
+ for (const departure of [90, 80]) {
92
+ state.resetFor(departure, access);
93
+ const fresh = new RoutingState(departure, [2], access, 4, 3, 60);
94
+ assert.deepStrictEqual([...state.arrivals()], [...fresh.arrivals()]);
95
+ assert.strictEqual(state.destinationBest, fresh.destinationBest);
96
+ assert.strictEqual(state.maxArrivalTime, fresh.maxArrivalTime);
97
+ for (let round = 0; round < state.graph.length; round++) {
98
+ assert.deepStrictEqual(
99
+ Array.from(state.graph[round]!),
100
+ Array.from(fresh.graph[round]!),
101
+ );
102
+ }
103
+ state.updateArrival(1, departure + 10, 1);
104
+ state.graph[1]![1] = { stopId: 1, arrival: departure + 10 };
105
+ }
106
+ });
107
+ });
@@ -111,8 +111,8 @@ export class RoutingState implements IRaptorState {
111
111
  private readonly maxDuration?: Duration;
112
112
 
113
113
  /**
114
- * Every stop that has received an arrival improvement during the current run,
115
- * in the order the improvements occurred. Used by {@link resetFor} to clear
114
+ * Every stop reached during the current run, recorded once in first-reached
115
+ * order. Used by {@link resetFor} to clear
116
116
  * only the touched entries instead of scanning the entire array.
117
117
  */
118
118
  private readonly reachedStops: StopId[] = [];
@@ -219,7 +219,9 @@ export class RoutingState implements IRaptorState {
219
219
  * @param leg The round number (number of transit legs taken so far).
220
220
  */
221
221
  updateArrival(stop: StopId, time: Time, leg: number): void {
222
- this.reachedStops.push(stop);
222
+ if (this.earliestArrivalTimes[stop] === UNREACHED_TIME) {
223
+ this.reachedStops.push(stop);
224
+ }
223
225
  this.earliestArrivalTimes[stop] = time;
224
226
  this.earliestArrivalLegs[stop] = leg;
225
227
  if (this.destinationSet.has(stop) && time < this._destinationBest) {
@@ -382,6 +384,12 @@ export class RoutingState implements IRaptorState {
382
384
  return arr;
383
385
  });
384
386
  state.graph.splice(0, state.graph.length, ...denseRounds);
387
+ state.reachedStops.length = 0;
388
+ const touched = new Set(arrivals.map(([stop]) => stop));
389
+ for (const round of graph) {
390
+ for (const [stop] of round) touched.add(stop);
391
+ }
392
+ state.reachedStops.push(...touched);
385
393
 
386
394
  return state;
387
395
  }
@@ -112,6 +112,19 @@ describe('Stop Finder', () => {
112
112
  });
113
113
 
114
114
  describe('findStopsByLocation', () => {
115
+ it('maps spatial IDs correctly when some stops have no coordinates', () => {
116
+ const stops = mockStops.map((stop, id) =>
117
+ id === 0 || id === 2
118
+ ? { ...stop, lat: undefined, lon: undefined }
119
+ : stop,
120
+ );
121
+ const index = new StopsIndex(stops);
122
+ assert.deepStrictEqual(
123
+ index.findStopsByLocation(46.8, 7.16, 10, 0.75).map((stop) => stop.id),
124
+ [1],
125
+ );
126
+ });
127
+
115
128
  it('should find stops by geographic location', () => {
116
129
  const results = stopFinder.findStopsByLocation(46.8061, 7.1614, 1);
117
130
  assert.strictEqual(results.length, 1);
@@ -8,8 +8,6 @@ import { deserializeStopsMap, serializeStopsMap } from './io.js';
8
8
  import { StopsMap as ProtoStopsMap } from './proto/v1/stops.js';
9
9
  import { SourceStopId, SourceStopsMap, Stop, StopId } from './stops.js';
10
10
 
11
- type StopPoint = { id: StopId; lat: number; lon: number };
12
-
13
11
  /**
14
12
  * The StopsIndex class provides functionality to search for public transport stops
15
13
  * by name or geographic location. It leverages text search and geospatial indexing
@@ -20,13 +18,13 @@ export class StopsIndex {
20
18
  private readonly sourceStopsMap: SourceStopsMap;
21
19
  private readonly textIndex;
22
20
  private readonly geoIndex: KDTree;
23
- private readonly stopPoints: StopPoint[];
21
+ private readonly geoStopIds: StopId[];
24
22
 
25
23
  constructor(stops: Stop[]) {
26
24
  this.stops = stops;
27
25
  this.sourceStopsMap = new Map<SourceStopId, StopId>();
28
26
  const stopsSet = new Map<StopId, { id: StopId; name: string }>();
29
- this.stopPoints = [];
27
+ this.geoStopIds = [];
30
28
  for (let id = 0; id < stops.length; id++) {
31
29
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
32
30
  const stop = stops[id]!;
@@ -45,11 +43,7 @@ export class StopsIndex {
45
43
  }
46
44
 
47
45
  if (stop.lat && stop.lon) {
48
- this.stopPoints.push({
49
- id: id,
50
- lat: stop.lat,
51
- lon: stop.lon,
52
- });
46
+ this.geoStopIds.push(id);
53
47
  }
54
48
  }
55
49
  this.textIndex = createIndex({
@@ -60,11 +54,12 @@ export class StopsIndex {
60
54
  });
61
55
  const stopsArray = Array.from(stopsSet.values());
62
56
  addAll(this.textIndex, stopsArray);
63
- this.geoIndex = new KDTree(this.stopPoints.length);
64
- for (let i = 0; i < this.stopPoints.length; i++) {
57
+ this.geoIndex = new KDTree(this.geoStopIds.length);
58
+ for (let i = 0; i < this.geoStopIds.length; i++) {
65
59
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
66
- const { lat, lon } = this.stopPoints[i]!;
67
- this.geoIndex.add(lon, lat);
60
+ const stop = this.stops[this.geoStopIds[i]!]!;
61
+ // Coordinates were checked when collecting geoStopIds.
62
+ this.geoIndex.add(stop.lon as number, stop.lat as number);
68
63
  }
69
64
  this.geoIndex.finish();
70
65
  }
@@ -112,10 +107,9 @@ export class StopsIndex {
112
107
  * @returns An array of Stop objects that match the search query.
113
108
  */
114
109
  findStopsByName(query: string, maxResults = 5): Stop[] {
115
- const results = search(this.textIndex, query).map(
116
- (result: SearchResult) => this.stops[result.id as number] as Stop,
117
- );
118
- return results.slice(0, maxResults);
110
+ return search(this.textIndex, query)
111
+ .slice(0, maxResults)
112
+ .map((result: SearchResult) => this.stops[result.id as number] as Stop);
119
113
  }
120
114
 
121
115
  /**
@@ -140,8 +134,8 @@ export class StopsIndex {
140
134
  maxResults,
141
135
  radius,
142
136
  ).map((id) => {
143
- const stopPoint = this.stopPoints[id] as StopPoint;
144
- return this.stops[stopPoint.id] as Stop;
137
+ const stopId = this.geoStopIds[id] as StopId;
138
+ return this.stops[stopId] as Stop;
145
139
  });
146
140
  return nearestStops;
147
141
  }
@@ -169,3 +169,30 @@ describe('Timetable IO', () => {
169
169
  assert.deepStrictEqual(deserializedData, routes);
170
170
  });
171
171
  });
172
+
173
+ it('owns compact pickup/drop-off bytes independently of input views', () => {
174
+ const input = Buffer.alloc(128);
175
+ input[17] = 0x12;
176
+ input[29] = 0x34;
177
+ const proto = [17, 29].map((offset) => ({
178
+ stopTimes: new Uint8Array(new Uint16Array([10, 11]).buffer),
179
+ pickupDropOffTypes: input.subarray(offset, offset + 1),
180
+ stops: new Uint8Array(new Uint32Array([0]).buffer),
181
+ serviceRouteId: 0,
182
+ }));
183
+ assert.ok(proto[0]);
184
+ proto.push({ ...proto[0], pickupDropOffTypes: input.subarray(40, 40) });
185
+ const routes = deserializeRoutesAdjacency(proto);
186
+ const [firstRoute, secondRoute, emptyRoute] = routes;
187
+ assert.ok(firstRoute && secondRoute && emptyRoute);
188
+ const first = firstRoute.serialize().pickupDropOffTypes;
189
+ const second = secondRoute.serialize().pickupDropOffTypes;
190
+ assert.notStrictEqual(first.buffer, input.buffer);
191
+ assert.strictEqual(first.buffer, second.buffer);
192
+ assert.strictEqual(first.buffer.byteLength, 2);
193
+ input.fill(0);
194
+ assert.deepStrictEqual([...first], [0x12]);
195
+ assert.deepStrictEqual([...second], [0x34]);
196
+ assert.strictEqual(emptyRoute.serialize().pickupDropOffTypes.length, 0);
197
+ assert.deepStrictEqual(deserializeRoutesAdjacency([]), []);
198
+ });
@@ -279,3 +279,33 @@ describe('Route', () => {
279
279
  });
280
280
  });
281
281
  });
282
+
283
+ it('keeps first-index lookup and stable arrays consistent for unique and repeated stops', () => {
284
+ const route = Route.of({
285
+ id: 0,
286
+ serviceRouteId: 0,
287
+ trips: [
288
+ {
289
+ stops: [5, 7, 5, 9, 5].map((id, index) => ({
290
+ id,
291
+ arrivalTime: index,
292
+ departureTime: index,
293
+ })),
294
+ },
295
+ ],
296
+ });
297
+ assert.strictEqual(route.firstStopRouteIndex(5), 0);
298
+ assert.strictEqual(route.firstStopRouteIndex(7), 1);
299
+ assert.strictEqual(route.firstStopRouteIndex(99), undefined);
300
+ assert.deepStrictEqual(route.stopRouteIndices(99), []);
301
+ assert.deepStrictEqual(route.stopRouteIndices(5), [0, 2, 4]);
302
+ const unique = route.stopRouteIndices(7);
303
+ assert.deepStrictEqual(unique, [1]);
304
+ assert.strictEqual(route.stopRouteIndices(7), unique);
305
+ unique[0] = 3;
306
+ assert.strictEqual(route.firstStopRouteIndex(7), 3);
307
+ const repeated = route.stopRouteIndices(5);
308
+ assert.strictEqual(route.stopRouteIndices(5), repeated);
309
+ repeated.shift();
310
+ assert.strictEqual(route.firstStopRouteIndex(5), 2);
311
+ });
@@ -215,16 +215,30 @@ export const deserializeRoutesAdjacency = (
215
215
  protoRoutesAdjacency: ProtoRoute[],
216
216
  ): Route[] => {
217
217
  const routesAdjacency: Route[] = [];
218
+ // Own the compact payload so small protobuf views do not retain the input file.
219
+ const pickupDropOffStorage = new Uint8Array(
220
+ protoRoutesAdjacency.reduce(
221
+ (size, route) => size + route.pickupDropOffTypes.byteLength,
222
+ 0,
223
+ ),
224
+ );
225
+ let pickupOffset = 0;
218
226
 
219
227
  for (let i = 0; i < protoRoutesAdjacency.length; i++) {
220
228
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
221
229
  const value = protoRoutesAdjacency[i]!;
222
230
  const stops = bytesToUint32Array(value.stops);
231
+ pickupDropOffStorage.set(value.pickupDropOffTypes, pickupOffset);
232
+ const pickupDropOffTypes = pickupDropOffStorage.subarray(
233
+ pickupOffset,
234
+ pickupOffset + value.pickupDropOffTypes.byteLength,
235
+ );
236
+ pickupOffset += value.pickupDropOffTypes.byteLength;
223
237
  routesAdjacency.push(
224
238
  new Route(
225
239
  i,
226
240
  bytesToUint16Array(value.stopTimes),
227
- value.pickupDropOffTypes,
241
+ pickupDropOffTypes,
228
242
  stops,
229
243
  value.serviceRouteId,
230
244
  ),