mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-19 21:46:49 +00:00
9dd0a851ca
* fix(mcp): accept per-leg times on create_transport and update_transport metadata was pinned to Record<string, string>, so a legs array could not get through and a multi-leg flight built over MCP lost every intermediate time. The booking ended up with correct endpoints and no legs, which every reader then treats as a single segment. legs is now a real, typed parameter with its contract in @trek/shared, shaped exactly the way the planner form and the importers write metadata.legs. The folding checks what the readers depend on: one leg fewer than endpoints (the AirTrail dedupe builds its signatures on that), day ids that belong to the trip, airport codes that agree with their endpoint, and the times, where a stopover endpoint carries the departure and the last one the arrival. metadata keeps its type and its replace semantics. Segments smuggled through metadata.legs as a JSON string used to be stored and then ignored by everything that read them; they are refused now and point at the legs parameter instead. Closes #1914 * fix(atlas): refuse a bucket list entry that is already on the list Nothing gave a bucket entry an identity, so the same country could be added as often as it was clicked. A wish is now identified by name, country, target date and, where it has them, coordinates. A different target date is a different wish and still lands, which is what the report asked for; two real places sharing a name stay separate because their coordinates differ. Empty string and NULL are normalised on both sides of the comparison, otherwise the dateless case, which is the one that was reported, would slip through. Deliberately no unique index and no migration. better-sqlite3 is synchronous and the server is a single process, so the race an index would guard against cannot happen here, and an index would have needed a destructive dedupe of existing rows first. create_bucket_list_item had no target_date parameter at all, so over MCP the allowed "same place, other date" case was unreachable. It takes one now. The plugin RPC reports the duplicate as bad params instead of letting it surface as an internal error. Closes #1898 * fix(settings): keep a free-form LLM endpoint in admin hands Any account could name the address the server calls, and the guard in front of it deliberately allows loopback and LAN so a self-hosted Ollama works. That is a reasonable trade for whoever runs the instance, because the network is theirs. It is not one for an arbitrary account, which could aim a request from inside that network at a target only it chose and read how the target answered. A free base URL, and the local provider that is one by another name, now come only from an admin controlled source: the addon config, the instance-wide defaults, or an admin's own settings. OpenAI and Anthropic stay available to everyone, because they go to a fixed address with the user's own key. The resolver is where this is enforced, since it is the single point both the booking import and the plugin host pass through, and the only one that also covers values already sitting in the database. The write path refuses as well, so nothing is stored that would never be read. The hint text promised something users no longer have, so it changed with it. Closes #1772 * fix(calendar): span a date-only booking to its end date A DATE event without DTEND is exactly one day per RFC 5545, so a multi-day booking that carries an end date still collapsed onto its first day. It gets an exclusive DTEND now, built the same way the stay branch already builds one. A booking without an end date serialises byte for byte as before. While in here: the stays query joins reservations on the accommodation, and two bookings pointed at the same stay fanned it out into two events sharing one UID. Duplicate UIDs in a feed are undefined behaviour and calendar clients pick one at random. The same "at most one booking per stay" assumption sat in the accommodations service, where it was worse than cosmetic: accommodation_id carries no foreign key, so deleting a stay took only the first booking and left the second pointing at something that no longer existed. Both the sync and the delete walk all of them now. The callers keep reading linkedReservationId; the list is additional. Refs #1869 * fix(vacay): say that the region is required, because it is The placeholder called the region optional while the add button stayed disabled until one was picked. The wording predates multiple calendars per plan, which is what introduced the gate. Only the value of the existing key changed, in all locales, so the key set stays identical. Two things the same screen got wrong were in the way of a clean answer: The button was clickable while the region list was still loading, which put the user in exactly the state the wording describes, and it is the state the report was filed from. It waits for the list now. Changing the country on an existing calendar kept the previous country's regions on screen, so a German region could be picked for the Netherlands. The list is cleared with the country, which only works in combination with the loading gate: without it, the empty list would happen to enable the button instead. Closes #1813 * fix(collections): let a saved place's address be corrected The edit form offered name, category and labels, and the address only on the way in. The cause was not the form: the update contract never declared address, so the validation pipe stripped it and the UPDATE had no column for it. Coordinates were pulled through for #1435 and the address was missed. It travels the whole chain now, contract to service to both forms. No migration, the column has always been there. The mobile add sheet had no address input at all, showing whatever the search result carried as read-only, so editing would have worked while creating still would not. It has one. The MCP tool description had drifted further than the address, never having mentioned the coordinates either. Both are in it now. Closes #1870 * fix(collections): keep the place search usable after the first save The add dialog stays open on purpose so several places can be added in a row, but after a save it gave no way back into the search. A search with no results was silent, with no empty state and no toast, so typing another name and pressing enter looked like nothing happened. The reporter described both halves and it is the silent search that matches "nothing happens" most closely. There is an empty state now, using a key that already existed in every locale and was unused. The search row is sticky inside the dialog body, so it stays reachable after the save instead of sitting above the scroll position. Also fixed while in here: refreshing the collection after each add reset the select mode, the selection and the label filter. In the very flow this dialog is built for, the user quietly lost all three. Closes #1921 * fix(vacay): make the phone year grid and the dock button do what they look like Two separate faults met on this screen. Tapping a day in the year grid did nothing unless the edit mode was already on, and the only way into it was a floating button that looks exactly like the one the dock draws in the same spot. A tap now opens that month in the editor, where the cells are big enough to hit. At 390px the grid cells are around 21px, which is too small to be mutating data with in the first place. The dock's plus was not wired for this route, so it fell through to creating a trip on the dashboard. Two different actions were stacked in one place, and the wrong one was on top whenever the screen had not painted yet, which includes the time its chunk is still loading. The dock leaves the slot to the screen now, and holds the geometry so the tab groups stay symmetric. Closes #1811 * fix(budget): settle in whole cents so balances stop drifting The report is a balance that moves on its own, with nothing added, edited or removed, on a trip where everything is in euro. Two mechanisms were behind it and both are real. The display currency is a fourth value, a per-user setting, so "everything is in euro" never covered it. Each balance was converted and rounded on its own, and the set no longer summed to zero: at 0.855 and 0.9312 it came out one cent over, at 0.94 it came out even. That cent appears and disappears with the six hour rate cache alone, which is exactly the symptom. The flows were rounded separately from the balances, so the two never had to agree. And a receipt line nobody was ticked for counted toward the total, and therefore toward the payer's credit, while landing in no share. That difference is permanent, and the client sent it that way. The settlement converts once, at the edge, and does integer arithmetic after that. Equal splits distribute the credited cents by largest remainder rather than the entered total, so credits and debits of one expense cancel exactly even in a foreign currency. Display conversion goes through the same largest-remainder allocation, so the sum survives it. With that, the 0.01 epsilon can go. It could never create a cent, but it stranded them: a one cent balance was filtered out of the flows while staying visible in the list, which is the "settle up offers nothing" half of the report. Closes #1382 * fix(journey): reach the book export and the suggestion toggle on a phone Below 1024px the hero card is dropped, and it held the only way to either action. The floating bar that replaces it was never given them. It has them now, and the hero is unmounted rather than hidden, so there is no second invisible copy of the same controls in the document. The bar's own buttons moved onto the appearance tokens while they were being touched. The phone screen never had either action at all and now carries both. The book itself was hardwired to English, cover and dates included, while the keys for it had been sitting in every locale unused. It takes the page's translator and locale, sets the document language, and prints mood and weather, which were on screen but never in the book. Closes #1848 * fix(journey): offer the connected photo providers in the phone entry editor The desktop editor grew an external photo source in #1632; the phone editor that came out of the mobile rewrite never did, so editing an entry on a phone had no way to Immich or Synology. It mirrors the desktop mechanics, including the part that is easy to miss: a save that creates the entry and then fails on the photos keeps the sheet open, and without remembering what was just created the retry creates a second entry. The sheet no longer kicks off its own addon load. The list is loaded once on boot and this only reacts to it; a second load races the other consumers and overwrites the store when it lands. Closes #1808 * fix(mobile): let the document scroll so Safari can collapse its URL bar iOS Safari only shrinks its address bar when the document scrolls, and TREK's never did: the root was locked and the mobile shell put a scroll container inside it. On the bottom tab layout that costs about a sixth of the viewport, permanently. Below 768px the document is the scroller again and the full-bleed screens measure their own height instead of leaning on the shell. That makes the body scroll locks real for the first time on a phone, and they were not ready for it. Three of them reset the overflow unconditionally, one of those on every run of its effect rather than on unmount, so a system notice could hand the page back while a sheet was still open. They all go through one reference counted lock now, which is the part that had to land first. Worth knowing for the issue: this reaches the flow screens. The trip planner, the journal, the atlas and the vacay screen keep their own full-height scrollers and still will not collapse the bar. Closes #1809 * fix(mobile): keep the screen gradient visible behind the translucent cards The gradient layer introduced with the scroll change sat at z-index -10. A negative layer paints above the canvas but below the backgrounds of ordinary blocks, and body carries an opaque one, so the gradient was hidden behind it. The mobile cards are translucent and take their depth from what is behind them, so every surface ended up compositing against a single flat colour and the whole phone UI read as one tone. The layer is positioned at z-index 0 now and the content above it at 10, which puts both over body's background. Same visual as before the scroll change, and the shell still owns no scroll container. * test(reservations): teach the accommodation delete stub about the id lists The RPC walks every linked booking since the delete stopped stopping at the first one. The stub still answered with the two singular fields, so the loop had nothing to iterate and the cascade events never fired. * fix(settings): move the free-form LLM endpoint out of user settings entirely Hiding it from non-admins closed the hole, but it left the option sitting in the admin's own personal settings, which is not what was asked for and not where it belongs: an instance has exactly one address it calls out to, and there was a second, invisible place to set it. The provider list is now the two hosted ones for everybody, the endpoint field is gone, and the resolver takes the address from the admin-controlled instance defaults for every caller including an admin. It no longer reads the users table at all. The write path refuses the keys for everyone, so nothing can be stored that would never be read. The endpoint is configured on the addon in the admin settings, which already carries provider, model, base URL and key, plus the Ollama model list. Nothing is lost, it just has one home now. Behaviour change worth a release note: an admin who set a personal Ollama endpoint has to move it to the addon config. A non-admin was already in that position after the previous commit. Refs #1772 * fix(journey): make the book preview usable on a phone The preview document carried no viewport, so a phone laid it out at its default 980px while the page is A4 landscape and about 1123px wide. It spilled out of the frame, which reads as being zoomed far in. Declaring the real width lets the browser scale the page to fit. Printing is unaffected, it goes by @page. The preview chrome had the same problem in miniature: a title and two labels on one row, sized inline, which does not fit a phone and fits translated labels even less. It moved to a stylesheet, and below 640px the card goes full-bleed, the decorative title steps aside and the two actions share the width. Refs #1848 * fix(mobile): stop the shell trapping the screens' own overlays Lifting the background layer into the positioned range meant the content wrapper had to be positioned too, and a positioned wrapper with a z-index is a stacking context. Every fixed overlay a screen renders inside it got clamped to that level: the vacay view/edit FAB sits at z-50 precisely so it beats the dock at z-40, and it disappeared behind it. The layer goes back to a negative z-index and the wrapper back to no positioning at all. What it needed in the first place was for body to stop painting over it, which is one line in the phone media block rather than a new stacking context. * fix(mobile): let the phone background override actually win A media query adds no specificity, so the themed body rule further down the file kept winning on source order and painted over the shell's background layer. The override is on html body now. The gradient was back to being invisible, which is the flat single-tone phone UI again. * fix(vacay): draw today's ring around the day instead of replacing it On the phone, today short-circuited the day-cell matrix and returned a ring on an empty cell. A vacation day or a company holiday logged for today was stored and counted in the totals, but the cell showed nothing, so it read as if the tap had not taken. Today is an annotation now, layered like the school band and the shared-calendar rings, which is how the desktop month card has always treated it. The strong ink stays only where the cell has no fill of its own, since --m-ink is light in dark mode and would disappear on a pastel. * fix(map): stop serving a stale GL style document from the service worker The Workbox rule for Mapbox matched every URL under api.mapbox.com, and the style document lives there too. Under StaleWhileRevalidate the map was built from the previous revision on every load, with the refresh landing one load too late, so a style republished in Studio with different label languages kept rendering the old ones. The network tab showed a 200 throughout, because the service worker's own answer is a real 200, which is why this looked like the app rewriting text-field at runtime. The style now has its own rule ahead of the tile rules, on NetworkFirst so it is current whenever the network is, and still cached so the map opens offline. Its own small cache too: sharing an LRU with three thousand tiles made the staleness come and go at random. OpenFreeMap styles had the same problem and are covered by the same rule. Closes #1924
522 lines
21 KiB
TypeScript
522 lines
21 KiB
TypeScript
/**
|
|
* tilePrefetcher unit tests.
|
|
*
|
|
* Covers: bbox computation, tile math, URL building, size guard,
|
|
* offline/no-SW guard, syncMeta update.
|
|
*/
|
|
import { readFileSync } from 'node:fs';
|
|
import { resolve } from 'node:path';
|
|
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
|
import 'fake-indexeddb/auto';
|
|
import {
|
|
computeBbox,
|
|
lngToTileX,
|
|
latToTileY,
|
|
buildTileUrl,
|
|
countTiles,
|
|
prefetchTiles,
|
|
prefetchTilesForTrip,
|
|
clearTileCache,
|
|
MAX_TILES,
|
|
TILE_CONCURRENCY,
|
|
type TileBbox,
|
|
} from '../../../src/sync/tilePrefetcher';
|
|
import { offlineDb, clearAll, upsertSyncMeta } from '../../../src/db/offlineDb';
|
|
import { setAuthed } from '../../../src/sync/authGate';
|
|
import { buildPlace } from '../../helpers/factories';
|
|
|
|
beforeEach(async () => {
|
|
await clearAll();
|
|
setAuthed(true);
|
|
Object.defineProperty(navigator, 'onLine', { value: true, writable: true, configurable: true });
|
|
// Stub fetch + serviceWorker so prefetch path is exercised
|
|
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }));
|
|
Object.defineProperty(navigator, 'serviceWorker', {
|
|
value: { controller: {} },
|
|
writable: true,
|
|
configurable: true,
|
|
});
|
|
});
|
|
|
|
afterEach(() => {
|
|
setAuthed(false);
|
|
vi.restoreAllMocks();
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
// ── bbox computation ──────────────────────────────────────────────────────────
|
|
|
|
describe('computeBbox', () => {
|
|
it('returns null when no places have coordinates', () => {
|
|
const places = [buildPlace({ lat: null, lng: null })];
|
|
expect(computeBbox(places)).toBeNull();
|
|
});
|
|
|
|
it('expands single-point bbox to at least 0.1° span', () => {
|
|
const place = buildPlace({ lat: 48.8566, lng: 2.3522 });
|
|
const bbox = computeBbox([place])!;
|
|
expect(bbox.maxLat - bbox.minLat).toBeGreaterThan(0.09);
|
|
expect(bbox.maxLng - bbox.minLng).toBeGreaterThan(0.09);
|
|
});
|
|
|
|
it('computes multi-point bbox with padding', () => {
|
|
const places = [
|
|
buildPlace({ lat: 48.8566, lng: 2.3522 }), // Paris
|
|
buildPlace({ lat: 51.5074, lng: -0.1278 }), // London
|
|
];
|
|
const bbox = computeBbox(places, 0.1)!;
|
|
// Padded bbox should extend beyond raw points
|
|
expect(bbox.minLat).toBeLessThan(48.8566);
|
|
expect(bbox.maxLat).toBeGreaterThan(51.5074);
|
|
expect(bbox.minLng).toBeLessThan(-0.1278);
|
|
expect(bbox.maxLng).toBeGreaterThan(2.3522);
|
|
});
|
|
|
|
it('clamps to valid Mercator lat bounds', () => {
|
|
const places = [buildPlace({ lat: 85.0, lng: 0 })];
|
|
const bbox = computeBbox(places, 0.5)!;
|
|
expect(bbox.maxLat).toBeLessThanOrEqual(85.0511);
|
|
});
|
|
});
|
|
|
|
// ── tile math ─────────────────────────────────────────────────────────────────
|
|
|
|
describe('lngToTileX', () => {
|
|
it('returns 0 for lng=-180 at any zoom', () => {
|
|
expect(lngToTileX(-180, 10)).toBe(0);
|
|
});
|
|
|
|
it('returns max tile for lng=180 at zoom 1', () => {
|
|
// At zoom 1: 2^1 = 2 tiles, lng=180 → x = floor(360/360 * 2) = floor(2) = 2
|
|
// But tile range is 0..1, so this is the "overflow" edge — that's fine
|
|
expect(lngToTileX(180, 1)).toBe(2);
|
|
});
|
|
|
|
it('increases with more easterly longitude', () => {
|
|
const x1 = lngToTileX(0, 10);
|
|
const x2 = lngToTileX(10, 10);
|
|
expect(x2).toBeGreaterThan(x1);
|
|
});
|
|
});
|
|
|
|
describe('latToTileY', () => {
|
|
it('returns smaller y for higher latitude (north = top)', () => {
|
|
const yNorth = latToTileY(60, 10);
|
|
const ySouth = latToTileY(10, 10);
|
|
expect(yNorth).toBeLessThan(ySouth);
|
|
});
|
|
|
|
it('equator is roughly half the tile grid', () => {
|
|
const yEq = latToTileY(0, 1);
|
|
// zoom 1 → 2 rows, equator ≈ row 1
|
|
expect(yEq).toBe(1);
|
|
});
|
|
});
|
|
|
|
// ── URL building ───────────────────────────────────────────────────────────────
|
|
|
|
describe('buildTileUrl', () => {
|
|
it('replaces {z}, {x}, {y}, {r} correctly', () => {
|
|
const tmpl = 'https://tile.example.com/{z}/{x}/{y}.png';
|
|
const url = buildTileUrl(tmpl, 10, 500, 300);
|
|
expect(url).toBe('https://tile.example.com/10/500/300.png');
|
|
});
|
|
|
|
it('replaces {s} with a subdomain character', () => {
|
|
const tmpl = 'https://{s}.tiles.example.com/{z}/{x}/{y}.png';
|
|
const url = buildTileUrl(tmpl, 10, 0, 0);
|
|
expect(url).toMatch(/^https:\/\/[abc]\.tiles\.example\.com\/10\/0\/0\.png$/);
|
|
});
|
|
|
|
it('picks the subdomain deterministically so a tile keeps one URL', () => {
|
|
const tmpl = 'https://{s}.tiles.example.com/{z}/{x}/{y}.png';
|
|
// A rotating counter would hand out a different host on each call, which
|
|
// both breaks the cache lookup and stores the tile once per host.
|
|
const first = buildTileUrl(tmpl, 10, 479, 329);
|
|
buildTileUrl(tmpl, 10, 480, 330);
|
|
expect(buildTileUrl(tmpl, 10, 479, 329)).toBe(first);
|
|
});
|
|
|
|
it('spreads neighbouring tiles across subdomains', () => {
|
|
const tmpl = 'https://{s}.tiles.example.com/{z}/{x}/{y}.png';
|
|
const hosts = new Set(
|
|
[0, 1, 2].map(dy => buildTileUrl(tmpl, 10, 479, 329 + dy).slice(8, 9)),
|
|
);
|
|
expect(hosts.size).toBe(3);
|
|
});
|
|
|
|
it('uses the same subdomain rotation as Leaflet', () => {
|
|
// Leaflet's TileLayer defaults to subdomains 'abc' and indexes it with
|
|
// Math.abs(x + y) % length. A different list length here would cache each
|
|
// tile under a host the map never asks for.
|
|
const tmpl = 'https://{s}.tiles.example.com/{z}/{x}/{y}.png';
|
|
const leaflet = 'abc';
|
|
for (const [x, y] of [[479, 329], [480, 330], [12, 7], [0, 0], [5, 4]]) {
|
|
const expected = leaflet[Math.abs(x + y) % leaflet.length];
|
|
expect(buildTileUrl(tmpl, 10, x, y)).toBe(
|
|
`https://${expected}.tiles.example.com/10/${x}/${y}.png`,
|
|
);
|
|
}
|
|
});
|
|
|
|
it('collapses the retired OSM subdomain sharding onto the single host', () => {
|
|
// d.tile.openstreetmap.org stopped resolving after OSM dropped sharding, so
|
|
// a template saved before that must not reach the network as-is (#1733).
|
|
const url = buildTileUrl('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 13, 4091, 2722);
|
|
expect(url).toBe('https://tile.openstreetmap.org/13/4091/2722.png');
|
|
});
|
|
|
|
it('removes {r} (retina placeholder)', () => {
|
|
const tmpl = 'https://tiles.example.com/{z}/{x}/{y}{r}.png';
|
|
const url = buildTileUrl(tmpl, 10, 0, 0);
|
|
expect(url).toBe('https://tiles.example.com/10/0/0.png');
|
|
});
|
|
});
|
|
|
|
// ── countTiles ────────────────────────────────────────────────────────────────
|
|
|
|
describe('countTiles', () => {
|
|
it('returns more tiles at higher zoom levels', () => {
|
|
const bbox: TileBbox = { minLat: 48.7, maxLat: 49.0, minLng: 2.2, maxLng: 2.5 };
|
|
const low = countTiles(bbox, 10, 10);
|
|
const high = countTiles(bbox, 12, 12);
|
|
expect(high).toBeGreaterThan(low);
|
|
});
|
|
|
|
it('stops counting after exceeding MAX_TILES', () => {
|
|
// Very large bbox — should hit cap quickly at high zooms
|
|
const bbox: TileBbox = { minLat: -60, maxLat: 60, minLng: -180, maxLng: 180 };
|
|
const count = countTiles(bbox, 10, 16);
|
|
expect(count).toBeGreaterThan(MAX_TILES);
|
|
});
|
|
});
|
|
|
|
// ── prefetchTiles guards ───────────────────────────────────────────────────────
|
|
|
|
describe('prefetchTiles — offline guard', () => {
|
|
it('returns 0 and does not fetch when offline', async () => {
|
|
Object.defineProperty(navigator, 'onLine', { value: false });
|
|
const bbox: TileBbox = { minLat: 48.8, maxLat: 48.9, minLng: 2.3, maxLng: 2.4 };
|
|
const count = await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 10);
|
|
expect(count).toBe(0);
|
|
expect(vi.mocked(fetch)).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('returns 0 when no service worker controller', async () => {
|
|
Object.defineProperty(navigator, 'serviceWorker', {
|
|
value: { controller: null },
|
|
configurable: true,
|
|
});
|
|
const bbox: TileBbox = { minLat: 48.8, maxLat: 48.9, minLng: 2.3, maxLng: 2.4 };
|
|
const count = await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 10);
|
|
expect(count).toBe(0);
|
|
});
|
|
});
|
|
|
|
describe('prefetchTiles — normal operation', () => {
|
|
it('fetches tiles and returns count', async () => {
|
|
const bbox: TileBbox = { minLat: 48.84, maxLat: 48.87, minLng: 2.33, maxLng: 2.37 };
|
|
const count = await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 11);
|
|
expect(count).toBeGreaterThan(0);
|
|
expect(vi.mocked(fetch)).toHaveBeenCalled();
|
|
});
|
|
|
|
it('stops at zoom level where cap is exceeded', async () => {
|
|
// Use a very small MAX_TILES override by using a huge bbox
|
|
const bbox: TileBbox = { minLat: -80, maxLat: 80, minLng: -170, maxLng: 170 };
|
|
// This bbox at zoom 10 alone has thousands of tiles — should trigger early stop
|
|
const count = await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 16);
|
|
expect(count).toBeLessThanOrEqual(MAX_TILES);
|
|
});
|
|
});
|
|
|
|
// ── throttling ────────────────────────────────────────────────────────────────
|
|
|
|
describe('prefetchTiles — throttling', () => {
|
|
/** fetch stub that resolves on the next macrotask and tracks concurrency. */
|
|
function trackingFetch() {
|
|
const state = { inFlight: 0, peak: 0, calls: 0 };
|
|
vi.stubGlobal('fetch', vi.fn(() => {
|
|
state.calls++;
|
|
state.inFlight++;
|
|
state.peak = Math.max(state.peak, state.inFlight);
|
|
return new Promise(resolve => setTimeout(() => {
|
|
state.inFlight--;
|
|
resolve({ ok: true });
|
|
}, 0));
|
|
}));
|
|
return state;
|
|
}
|
|
|
|
it('never exceeds TILE_CONCURRENCY requests in flight', async () => {
|
|
const state = trackingFetch();
|
|
const bbox: TileBbox = { minLat: 48.0, maxLat: 49.0, minLng: 2.0, maxLng: 3.0 };
|
|
|
|
await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 12);
|
|
|
|
expect(state.calls).toBeGreaterThan(TILE_CONCURRENCY);
|
|
expect(state.peak).toBeLessThanOrEqual(TILE_CONCURRENCY);
|
|
});
|
|
|
|
it('resolves only once every tile has been dealt with', async () => {
|
|
const state = trackingFetch();
|
|
const bbox: TileBbox = { minLat: 48.8, maxLat: 48.9, minLng: 2.3, maxLng: 2.4 };
|
|
|
|
const fetched = await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 11);
|
|
|
|
expect(fetched).toBe(state.calls);
|
|
expect(state.inFlight).toBe(0);
|
|
});
|
|
|
|
it('stops fetching when the user logs out mid-run', async () => {
|
|
let calls = 0;
|
|
vi.stubGlobal('fetch', vi.fn(() => {
|
|
if (++calls === TILE_CONCURRENCY) setAuthed(false);
|
|
return Promise.resolve({ ok: true });
|
|
}));
|
|
const bbox: TileBbox = { minLat: 48.0, maxLat: 49.0, minLng: 2.0, maxLng: 3.0 };
|
|
|
|
await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 12);
|
|
|
|
// The workers finish their current tile, then bail — nowhere near the ~336
|
|
// tiles this bbox enumerates.
|
|
expect(calls).toBeLessThan(2 * TILE_CONCURRENCY);
|
|
});
|
|
|
|
it('goes quiet when the connection drops mid-run', async () => {
|
|
let calls = 0;
|
|
vi.stubGlobal('fetch', vi.fn(() => {
|
|
if (++calls === TILE_CONCURRENCY) {
|
|
Object.defineProperty(navigator, 'onLine', { value: false, configurable: true });
|
|
}
|
|
return Promise.resolve({ ok: true });
|
|
}));
|
|
const bbox: TileBbox = { minLat: 48.0, maxLat: 49.0, minLng: 2.0, maxLng: 3.0 };
|
|
|
|
await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 12);
|
|
|
|
expect(calls).toBeLessThan(2 * TILE_CONCURRENCY);
|
|
});
|
|
});
|
|
|
|
// ── cache reuse ───────────────────────────────────────────────────────────────
|
|
|
|
describe('prefetchTiles — cache reuse', () => {
|
|
it('skips tiles already in Cache Storage instead of hitting the network', async () => {
|
|
vi.stubGlobal('caches', {
|
|
open: vi.fn().mockResolvedValue({ match: vi.fn().mockResolvedValue({}) }),
|
|
});
|
|
const bbox: TileBbox = { minLat: 48.8, maxLat: 48.9, minLng: 2.3, maxLng: 2.4 };
|
|
|
|
const fetched = await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 11);
|
|
|
|
expect(fetched).toBe(0);
|
|
expect(vi.mocked(fetch)).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('still fetches when Cache Storage has no entry for the tile', async () => {
|
|
vi.stubGlobal('caches', {
|
|
open: vi.fn().mockResolvedValue({ match: vi.fn().mockResolvedValue(undefined) }),
|
|
});
|
|
const bbox: TileBbox = { minLat: 48.8, maxLat: 48.9, minLng: 2.3, maxLng: 2.4 };
|
|
|
|
const fetched = await prefetchTiles(bbox, 'https://{s}.example.com/{z}/{x}/{y}.png', 10, 11);
|
|
|
|
expect(fetched).toBeGreaterThan(0);
|
|
});
|
|
});
|
|
|
|
// ── prefetchTilesForTrip ──────────────────────────────────────────────────────
|
|
|
|
describe('prefetchTilesForTrip', () => {
|
|
it('no-ops when no places have coordinates', async () => {
|
|
const places = [buildPlace({ lat: null, lng: null })];
|
|
await prefetchTilesForTrip(1, places);
|
|
expect(vi.mocked(fetch)).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('updates syncMeta tilesBbox after prefetch', async () => {
|
|
await upsertSyncMeta({ tripId: 1, lastSyncedAt: Date.now(), status: 'idle', tilesBbox: null, filesCachedCount: 0 });
|
|
|
|
const places = [
|
|
buildPlace({ trip_id: 1, lat: 48.8566, lng: 2.3522 }),
|
|
];
|
|
await prefetchTilesForTrip(1, places, 'https://{s}.example.com/{z}/{x}/{y}.png');
|
|
|
|
const meta = await offlineDb.syncMeta.get(1);
|
|
expect(meta!.tilesBbox).not.toBeNull();
|
|
expect(meta!.tilesBbox).toHaveLength(4);
|
|
});
|
|
|
|
it('zoom-clamps instead of skipping when the bbox exceeds MAX_TILES', async () => {
|
|
await upsertSyncMeta({ tripId: 1, lastSyncedAt: Date.now(), status: 'idle', tilesBbox: null, filesCachedCount: 0 });
|
|
|
|
// ~4° road-trip span: low zooms fit the budget, high zooms (z14+) blow past
|
|
// it. The old guard skipped the whole trip; now we keep what fits.
|
|
const places = [
|
|
buildPlace({ trip_id: 1, lat: 45.0, lng: 0.0 }),
|
|
buildPlace({ trip_id: 1, lat: 49.0, lng: 4.0 }),
|
|
];
|
|
await prefetchTilesForTrip(1, places, 'https://{s}.example.com/{z}/{x}/{y}.png');
|
|
|
|
// Previously this skipped entirely; now it prefetches a clamped subset.
|
|
const calls = vi.mocked(fetch).mock.calls.length;
|
|
expect(calls).toBeGreaterThan(0);
|
|
expect(calls).toBeLessThanOrEqual(MAX_TILES);
|
|
});
|
|
|
|
it('prefetches a region-sized (0.5°) trip that the old all-or-nothing guard would have skipped', async () => {
|
|
await upsertSyncMeta({ tripId: 1, lastSyncedAt: Date.now(), status: 'idle', tilesBbox: null, filesCachedCount: 0 });
|
|
|
|
const places = [
|
|
buildPlace({ trip_id: 1, lat: 48.6, lng: 2.1 }),
|
|
buildPlace({ trip_id: 1, lat: 49.1, lng: 2.6 }),
|
|
];
|
|
await prefetchTilesForTrip(1, places, 'https://{s}.example.com/{z}/{x}/{y}.png');
|
|
|
|
const calls = vi.mocked(fetch).mock.calls.length;
|
|
expect(calls).toBeGreaterThan(0);
|
|
expect(calls).toBeLessThanOrEqual(MAX_TILES);
|
|
});
|
|
});
|
|
|
|
// ── repeat runs ───────────────────────────────────────────────────────────────
|
|
|
|
describe('prefetchTilesForTrip — repeat runs', () => {
|
|
const places = [buildPlace({ trip_id: 1, lat: 48.8566, lng: 2.3522 })];
|
|
const tmpl = 'https://{s}.example.com/{z}/{x}/{y}.png';
|
|
|
|
beforeEach(async () => {
|
|
await upsertSyncMeta({ tripId: 1, lastSyncedAt: Date.now(), status: 'idle', tilesBbox: null, filesCachedCount: 0 });
|
|
});
|
|
|
|
it('does nothing on a second run with an unchanged bbox', async () => {
|
|
await prefetchTilesForTrip(1, places, tmpl);
|
|
const first = vi.mocked(fetch).mock.calls.length;
|
|
expect(first).toBeGreaterThan(0);
|
|
|
|
vi.mocked(fetch).mockClear();
|
|
await prefetchTilesForTrip(1, places, tmpl);
|
|
|
|
expect(vi.mocked(fetch)).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('prefetches again once a place moves the bbox', async () => {
|
|
await prefetchTilesForTrip(1, places, tmpl);
|
|
vi.mocked(fetch).mockClear();
|
|
|
|
const moved = [...places, buildPlace({ trip_id: 1, lat: 45.4642, lng: 9.19 })];
|
|
await prefetchTilesForTrip(1, moved, tmpl);
|
|
|
|
expect(vi.mocked(fetch)).toHaveBeenCalled();
|
|
});
|
|
|
|
it('runs anyway when forced (prepare for offline)', async () => {
|
|
await prefetchTilesForTrip(1, places, tmpl);
|
|
vi.mocked(fetch).mockClear();
|
|
|
|
await prefetchTilesForTrip(1, places, tmpl, true);
|
|
|
|
expect(vi.mocked(fetch)).toHaveBeenCalled();
|
|
});
|
|
|
|
it('clearTileCache resets the bboxes so the next sync refills the cache', async () => {
|
|
await prefetchTilesForTrip(1, places, tmpl);
|
|
vi.mocked(fetch).mockClear();
|
|
|
|
vi.stubGlobal('caches', { delete: vi.fn().mockResolvedValue(true) });
|
|
await clearTileCache();
|
|
expect((await offlineDb.syncMeta.get(1))!.tilesBbox).toBeNull();
|
|
|
|
vi.unstubAllGlobals();
|
|
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }));
|
|
await prefetchTilesForTrip(1, places, tmpl);
|
|
|
|
expect(vi.mocked(fetch)).toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
// ── cap coherence ───────────────────────────────────────────────────────────────
|
|
|
|
describe('MAX_TILES budget', () => {
|
|
it('matches the Workbox map-tiles maxEntries in vite.config.js (drift guard)', () => {
|
|
expect(MAX_TILES).toBe(12288);
|
|
});
|
|
});
|
|
|
|
// ── service worker rule coherence ───────────────────────────────────────────────
|
|
|
|
describe('the map-tiles rule for OpenStreetMap (#1733)', () => {
|
|
// Vitest runs with the client package as its root, so cwd is stable here.
|
|
const config = readFileSync(resolve(process.cwd(), 'vite.config.js'), 'utf8');
|
|
|
|
// Pull the OSM runtimeCaching pattern back out of the config and exercise it,
|
|
// so this stays a statement about matching behaviour rather than about the
|
|
// exact characters someone typed.
|
|
const osmRule = /urlPattern:\s*(\/\^https[^\n]*openstreetmap[^\n]*\/i),/.exec(config);
|
|
if (!osmRule) throw new Error('no OpenStreetMap runtimeCaching rule found in vite.config.js');
|
|
const literal = osmRule[1];
|
|
const pattern = new RegExp(literal.slice(1, literal.lastIndexOf('/')), 'i');
|
|
|
|
it('caches the single-host URLs the prefetcher now builds', () => {
|
|
// Without this the prefetch writes nothing to map-tiles, cache.match() never
|
|
// hits, and the offline tile store stays empty.
|
|
const url = buildTileUrl('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 13, 4091, 2722);
|
|
expect(url).toBe('https://tile.openstreetmap.org/13/4091/2722.png');
|
|
expect(pattern.test(url)).toBe(true);
|
|
});
|
|
|
|
it('still matches the sharded URLs already sitting in existing caches', () => {
|
|
for (const shard of ['a', 'b', 'c']) {
|
|
expect(pattern.test(`https://${shard}.tile.openstreetmap.org/13/4091/2722.png`)).toBe(true);
|
|
}
|
|
});
|
|
|
|
it('does not swallow a look-alike host', () => {
|
|
expect(pattern.test('https://tile.openstreetmap.org.example.com/13/4091/2722.png')).toBe(false);
|
|
expect(pattern.test('https://tile.openstreetmap.de/13/4091/2722.png')).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe('the GL style document is not served stale (#1924)', () => {
|
|
const config = readFileSync(resolve(process.cwd(), 'vite.config.js'), 'utf8');
|
|
|
|
// Read the rules in file order and exercise them the way Workbox does: the
|
|
// first route whose pattern matches wins, so order is behaviour here, not style.
|
|
const rules = [...config.matchAll(/urlPattern:\s*(\/[^\n]*?\/i),\s*\n\s*handler:\s*'([A-Za-z]+)'/g)].map(m => ({
|
|
pattern: new RegExp(m[1].slice(1, m[1].lastIndexOf('/')), 'i'),
|
|
handler: m[2],
|
|
}));
|
|
const firstMatch = (url: string) => rules.find(r => r.pattern.test(url));
|
|
|
|
const MAPBOX_STYLE = 'https://api.mapbox.com/styles/v1/acme/ckabc123?sdk=js-3.25.0&access_token=pk.test';
|
|
const OPENFREEMAP_STYLE = 'https://tiles.openfreemap.org/styles/liberty';
|
|
const MAPBOX_TILE = 'https://a.tiles.mapbox.com/v4/mapbox.mapbox-streets-v8/13/4091/2722.vector.pbf';
|
|
const MAPBOX_GLYPHS = 'https://api.mapbox.com/fonts/v1/mapbox/DIN%20Pro%20Regular/0-255.pbf';
|
|
|
|
it('finds the runtime caching rules at all (guards the parser above)', () => {
|
|
expect(rules.length).toBeGreaterThan(4);
|
|
});
|
|
|
|
it('takes the Mapbox style from the network first', () => {
|
|
// Under the tile rule's StaleWhileRevalidate the map was built from the
|
|
// previous revision on every load, so a style republished with different
|
|
// label languages kept rendering the old ones.
|
|
expect(firstMatch(MAPBOX_STYLE)?.handler).toBe('NetworkFirst');
|
|
});
|
|
|
|
it('takes the OpenFreeMap style from the network first too', () => {
|
|
expect(firstMatch(OPENFREEMAP_STYLE)?.handler).toBe('NetworkFirst');
|
|
});
|
|
|
|
it('leaves tiles, glyphs and sprites on the offline-friendly rule', () => {
|
|
// Those are safe to serve stale and are what makes the basemap work offline.
|
|
expect(firstMatch(MAPBOX_TILE)?.handler).toBe('StaleWhileRevalidate');
|
|
expect(firstMatch(MAPBOX_GLYPHS)?.handler).toBe('StaleWhileRevalidate');
|
|
});
|
|
|
|
it('keeps the style out of the tile cache, so tile eviction cannot reach it', () => {
|
|
expect(config).toMatch(/cacheName:\s*'gl-map-styles'/);
|
|
});
|
|
});
|