fix(offline): raster tiles a GL map fetches get a service worker cache of their own

Leaflet loads a tile as an image without CORS and the prefetch fetches it
no-cors, so map-tiles holds opaque answers. A GL map reads tiles with a
CORS fetch and cannot use one: once Leaflet had drawn an OpenTopoMap tile,
the GL tour layer failed on the same URL, and a MapLibre template would
fail the same way on every prefetched tile.

A CORS request for a raster preset's tile now goes to map-tiles-gl, which
keeps only readable answers, ahead of the Leaflet rules; images and the
no-cors prefetch stay in map-tiles. The matcher is written into the
service worker by its source text, so its host list is inline, and a test
holds it to the hosts the CSP lets a GL map fetch. OpenHikingMap and
CyclOSM stay out, their usage policies allow no offline copy.

The prefetch takes exactly one way per user: a template MapLibre draws on
such a host is fetched with CORS into map-tiles-gl, at the density the map
asks for, everything else as before. Clearing offline maps drops both
caches, and the iOS trim keeps both within its budget.
This commit is contained in:
Maurice
2026-11-30 15:35:24 +01:00
parent 32879dd528
commit d39d544297
6 changed files with 266 additions and 14 deletions
+1 -1
View File
@@ -68,7 +68,7 @@ The offline core is flagship work surrounded by a periphery that ignores it. New
## Big-picture pieces
- **Maps** (`src/components/Map/`): two interchangeable renderers — Leaflet and Mapbox/MapLibre GL — chosen at runtime by `MapViewAuto.tsx`. Keep both in sync when changing map features, and keep `mapbox-gl` and `maplibre-gl` in separate chunks (`check:gl-split`). The raster prefetcher fetches tiles `no-cors` so custom tile providers without CORS headers keep working; the vector prefetcher deliberately uses `cors` because it has to read the responses — don't "align" one with the other.
- **Maps** (`src/components/Map/`): two interchangeable renderers — Leaflet and Mapbox/MapLibre GL — chosen at runtime by `MapViewAuto.tsx`. Keep both in sync when changing map features, and keep `mapbox-gl` and `maplibre-gl` in separate chunks (`check:gl-split`). The raster prefetcher fetches tiles `no-cors` so custom tile providers without CORS headers keep working, except a template MapLibre draws (`trek:template`), whose tiles a GL map reads with CORS and the service worker keeps apart in `map-tiles-gl` (`src/sync/glTileCache.ts`); the vector prefetcher deliberately uses `cors` because it has to read the responses — don't "align" one with the other.
- **i18n** (`src/i18n/TranslationContext.tsx`): `en` is bundled; every other locale is a dynamic `import('@trek/shared/i18n/<locale>')` so Vite emits one chunk per locale. Strings live in `shared/`, never here. `t()` returns an unknown key unchanged, so `lint:i18n-keys` (`scripts/i18n-keys.mjs`) resolves every literal key in `t()`, `tHtml()`, `tr()`, `<TransHtml html>`, `translateApiError` and `*Key` props against `shared/src/i18n/en`; a template whose interpolations only choose between string literals is expanded and each branch checked as a key; any other template key is read with each interpolation as one key segment and passes by itself only when it reaches between 1 and `MAX_IMPLICIT_MATCHES` (30) en keys; a wider one, or one with no fixed dotted prefix, needs a `DYNAMIC_ALLOWED` entry keyed by file and template that says what bounds the value, and an entry the check no longer needs fails. Pass counts as numbers, and let a plural group pick the wording instead of switching keys on the count.
- **Mobile shell** (`src/mobile/`): below the phone breakpoint (`useIsPhone`) `App.tsx` wraps routes in `MobileShell` and the `M*` screens under `mobile/screens/` take over. A UI change to a domain with an `M*` twin usually needs both, and the logic change goes into the shared hook (see "Desktop and phone views" below).
- **Plugins UI** (`src/components/Plugins/`): third-party surfaces render only inside the sandboxed `PluginFrame` iframe (postMessage bridge, live theme-token sync). Host-rendered contribution points (widgets, schedule rows, map layers, planner columns/actions) render server-normalized primitives only — plugin markup never runs inline. Authoring is covered by the `trek-plugin-dev` skill.
+81
View File
@@ -0,0 +1,81 @@
/**
* The service worker rule for raster tiles a GL map fetches (FE-SYNC-GLTILECACHE-*).
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { RASTER_TILE_HOSTS } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import { GL_TILE_CACHE, isGlRasterTileRequest } from './glTileCache';
import { MAX_TILES } from './tilePrefetcher';
function ask(match: typeof isGlRasterTileRequest, url: string, mode: RequestMode) {
return match({ url: new URL(url), request: { mode } as Request });
}
/** The function as the service worker gets it: its source text, evaluated with nothing around it. */
const serialized = new Function(`return (${isGlRasterTileRequest.toString()})`)() as typeof isGlRasterTileRequest;
describe('isGlRasterTileRequest', () => {
it('FE-SYNC-GLTILECACHE-001: takes the CORS fetches of the cached raster presets', () => {
for (const url of [
'https://a.basemaps.cartocdn.com/light_all/5/16/10@2x.png?key=k',
'https://basemaps.cartocdn.com/light_all/5/16/10.png',
'https://tile.openstreetmap.org/5/16/10.png',
'https://tile.openstreetmap.de/5/16/10.png',
'https://tiles.stadiamaps.com/tiles/alidade_smooth/5/16/10.png',
// The GL tour layer that broke on Leaflet's opaque copies.
'https://b.tile.opentopomap.org/5/16/10.png',
]) {
expect(ask(isGlRasterTileRequest, url, 'cors'), url).toBe(true);
}
});
it("FE-SYNC-GLTILECACHE-002: leaves Leaflet's images and the no-cors prefetch to map-tiles", () => {
expect(ask(isGlRasterTileRequest, 'https://tile.openstreetmap.de/5/16/10.png', 'no-cors')).toBe(false);
expect(ask(isGlRasterTileRequest, 'https://tile.openstreetmap.de/5/16/10.png', 'same-origin')).toBe(false);
});
it('FE-SYNC-GLTILECACHE-003: never a host whose policy forbids an offline copy, a GCJ-02 host or a look-alike', () => {
for (const url of [
'https://tile.openmaps.fr/openhikingmap/5/16/10.png',
'https://a.tile-cyclosm.openstreetmap.fr/cyclosm/5/16/10.png',
'https://webrd01.is.autonavi.com/appmaptile?x=1&y=2&z=3',
'https://tile.openstreetmap.de.example.com/5/16/10.png',
'http://tile.openstreetmap.de/5/16/10.png',
]) {
expect(ask(isGlRasterTileRequest, url, 'cors'), url).toBe(false);
}
});
it('FE-SYNC-GLTILECACHE-004: reaches nothing outside its body, so the copy in the service worker matches alike', () => {
for (const url of ['https://tile.openstreetmap.de/5/16/10.png', 'https://tile.openmaps.fr/x/5/16/10.png']) {
for (const mode of ['cors', 'no-cors'] as const) {
expect(ask(serialized, url, mode)).toBe(ask(isGlRasterTileRequest, url, mode));
}
}
});
it('FE-SYNC-GLTILECACHE-005: every host in the inline list is one the CSP lets a GL map fetch', () => {
const inline = [...isGlRasterTileRequest.toString().matchAll(/'([^']+\.[a-z]+)'/g)].map((m) => m[1]);
expect(inline.length).toBeGreaterThan(0);
for (const host of inline) expect(RASTER_TILE_HOSTS, host).toContain(host);
});
});
describe('the map-tiles-gl rule in vite.config.js', () => {
const config = readFileSync(resolve(process.cwd(), 'vite.config.js'), 'utf8');
const rule = /urlPattern: isGlRasterTileRequest,[\s\S]*?cacheableResponse: \{ statuses: \[200\] \}/.exec(config)?.[0];
it('FE-SYNC-GLTILECACHE-006: keeps only readable answers, as many as the prefetch budget', () => {
expect(GL_TILE_CACHE).toBe('map-tiles-gl');
expect(rule).toBeDefined();
expect(rule).toContain('cacheName: GL_TILE_CACHE');
expect(rule).toContain(`maxEntries: ${MAX_TILES}`);
});
it('FE-SYNC-GLTILECACHE-007: comes before the Leaflet rules for the same hosts, since the first match wins', () => {
expect(config.indexOf('urlPattern: isGlRasterTileRequest')).toBeLessThan(config.indexOf('basemaps\\.cartocdn'));
});
});
+40
View File
@@ -0,0 +1,40 @@
/**
* The service worker cache for raster tiles a GL map fetches.
*
* Leaflet loads a tile as an `<img>` without CORS, and the offline prefetch
* fetches tiles `no-cors` the same way, so `map-tiles` holds opaque responses.
* A GL map reads a tile with a CORS fetch and cannot use an opaque answer: with
* one in the cache under the same URL, every such tile failed, which is what
* broke the OpenTopoMap layer of the GL tour maps once Leaflet had drawn it.
* So a CORS request for a raster tile goes into a cache of its own that keeps
* only readable answers, and Leaflet's requests stay where they were.
*
* The hosts are the raster presets whose tiles `map-tiles` keeps for Leaflet
* (vite.config.js), apart from Amap, whose GCJ-02 tiles a GL map never draws.
* OpenHikingMap and CyclOSM are left out on purpose: their usage policies allow
* no offline copy, which is why `map-tiles` has no rule for them either.
*/
/** Cache Storage name; vite.config.js names it in its rule, the prefetcher writes and clears it. */
export const GL_TILE_CACHE = 'map-tiles-gl';
/**
* Workbox `urlPattern` for that cache. Workbox writes this function into the
* service worker by its source text, so it must not reach anything outside its
* own body: the host list stays inline.
*/
export function isGlRasterTileRequest({ url, request }: { url: URL; request: Request }): boolean {
if (request.mode !== 'cors' || url.protocol !== 'https:') return false;
const hosts = [
'basemaps.cartocdn.com',
'*.basemaps.cartocdn.com',
'tile.openstreetmap.org',
'*.tile.openstreetmap.org',
'tile.openstreetmap.de',
'tiles.stadiamaps.com',
'tile.opentopomap.org',
'*.tile.opentopomap.org',
];
const host = url.hostname.toLowerCase();
return hosts.some((entry) => (entry.startsWith('*.') ? host.endsWith(entry.slice(1)) : host === entry));
}
+53 -12
View File
@@ -33,6 +33,9 @@ import { clearVectorCache, prefetchStyleAssets, prefetchVectorForPlaces } from '
import { isNativeIos } from '../native/platform'
import { isIosDevice } from '../utils/iosDevice'
import { openCacheStorage } from './openCacheStorage'
import { GL_TILE_CACHE, isGlRasterTileRequest } from './glTileCache'
import { useSettingsStore } from '../store/settingsStore'
import { MAPLIBRE_FROM_TEMPLATE } from '@trek/shared'
// ── Constants ─────────────────────────────────────────────────────────────────
@@ -292,8 +295,37 @@ function enumerateTiles(
}
/** Open the tile cache, or null where Cache Storage isn't available. */
async function openTileCache(): Promise<Cache | null> {
return openCacheStorage(TILE_CACHE)
async function openTileCache(cacheName: string = TILE_CACHE): Promise<Cache | null> {
return openCacheStorage(cacheName)
}
/**
* Whether the user's map fetches this template as a GL map: MapLibre drawing it
* through the `trek:template` keyword, from a host whose CORS answers the
* service worker keeps (glTileCache.ts). Such tiles are fetched with CORS into
* map-tiles-gl, every other template as Leaflet's images into map-tiles, never
* both, so a trip's tiles count once against the one budget.
*/
function fetchedAsGl(template: string): boolean {
const { map_provider: provider, maplibre_style: style } = useSettingsStore.getState().settings
if (provider !== 'maplibre-gl' || style !== MAPLIBRE_FROM_TEMPLATE) return false
try {
const url = new URL(template.replace(/\{s\}/g, 'a'))
// The service worker's own matcher, asked about a CORS request for this host.
return isGlRasterTileRequest({ url, request: { mode: 'cors' } as Request })
} catch {
return false
}
}
/**
* The URL a GL map requests for a tile: Leaflet's shard, since both pick it by
* (x + y) modulo the shard count, and `{r}` as `@2x` on a dense screen, as the
* map's raster style decides it (components/Map/basemapSpec.ts).
*/
function buildGlTileUrl(template: string, z: number, x: number, y: number, cartoKey?: string): string {
const retina = typeof window !== 'undefined' && window.devicePixelRatio > 1
return buildTileUrl(template.replace('{r}', retina ? '@2x' : ''), z, x, y, cartoKey)
}
/**
@@ -325,10 +357,11 @@ export async function prefetchTiles(
const coords = enumerateTiles(bbox, minZoom, maxZoom)
if (coords.length === 0) return 0
const gl = fetchedAsGl(tileUrlTemplate)
// Checking Cache Storage from here is far cheaper than letting the request
// reach the SW's CacheFirst handler, so a resumed or repeated prefetch over a
// warm cache costs almost nothing.
const cache = await openTileCache()
const cache = await openTileCache(gl ? GL_TILE_CACHE : TILE_CACHE)
let cursor = 0
let fetched = 0
@@ -339,7 +372,7 @@ export async function prefetchTiles(
if (!navigator.onLine || !isAuthed()) return
const [z, x, y] = coords[cursor++]
const url = buildTileUrl(tileUrlTemplate, z, x, y, cartoKey)
const url = (gl ? buildGlTileUrl : buildTileUrl)(tileUrlTemplate, z, x, y, cartoKey)
if (cache && (await cache.match(url))) continue
@@ -347,7 +380,7 @@ export async function prefetchTiles(
// refusal, a provider that is down, DNS) leaves nothing in the cache and
// must not count towards the tally the caller logs as tiles cached: that
// is what let a fully blocked prefetch still report success (#2180).
const reached = await fetch(url, { mode: 'no-cors' }).then(() => true, () => false)
const reached = await fetch(url, { mode: gl ? 'cors' : 'no-cors' }).then(() => true, () => false)
if (reached) fetched++
}
}
@@ -382,12 +415,17 @@ export async function trimTileCacheForIos(now = Date.now()): Promise<number> {
return 0
}
try {
const cache = await openTileCache()
if (!cache) return 0
const keys = await cache.keys()
const surplus = keys.slice(0, Math.max(0, keys.length - IOS_MAX_TILES))
for (const request of surplus) await cache.delete(request)
return surplus.length
// Both tile caches: a template MapLibre draws fills map-tiles-gl instead.
let removed = 0
for (const name of [TILE_CACHE, GL_TILE_CACHE]) {
const cache = await openTileCache(name)
if (!cache) continue
const keys = await cache.keys()
const surplus = keys.slice(0, Math.max(0, keys.length - IOS_MAX_TILES))
for (const request of surplus) await cache.delete(request)
removed += surplus.length
}
return removed
} catch {
// Cache Storage refused: the tiles stay as they are and tomorrow tries again.
return 0
@@ -409,7 +447,10 @@ export function scheduleTileCacheTrim(delayMs = 15_000): void {
*/
export async function clearTileCache(): Promise<void> {
try {
if (typeof caches !== 'undefined') await caches.delete(TILE_CACHE)
if (typeof caches !== 'undefined') {
await caches.delete(TILE_CACHE)
await caches.delete(GL_TILE_CACHE)
}
} catch {
/* Cache Storage unavailable (no SW / private mode) — nothing to clear */
}
+75 -1
View File
@@ -33,6 +33,7 @@ import { buildPlace } from '../../helpers/factories';
import { prefetchStyleAssets, prefetchVectorForPlaces } from '../../../src/sync/glPrefetcher';
import { isNativeIos } from '../../../src/native/platform';
import { OFM_DARK, OFM_POSITRON } from '../../../src/constants/mapDefaults';
import { useSettingsStore } from '../../../src/store/settingsStore';
// The vector basemap has its own tests (glPrefetcher.test.ts). Here it is a seam,
// so the raster runs below count only their own tile requests.
@@ -769,7 +770,9 @@ describe('the iOS tile budget', () => {
vi.mocked(isIosDevice).mockReturnValue(true);
const keys = tileKeys(IOS_MAX_TILES + 5);
const del = vi.fn().mockResolvedValue(true);
vi.stubGlobal('caches', { open: vi.fn().mockResolvedValue({ keys: vi.fn().mockResolvedValue(keys), delete: del }) });
// The template cache of a MapLibre map is empty here; the next case fills it.
const open = vi.fn(async (name: string) => ({ keys: vi.fn().mockResolvedValue(name === 'map-tiles' ? keys : []), delete: del }));
vi.stubGlobal('caches', { open });
const now = Date.UTC(2026, 10, 8, 12);
expect(await trimTileCacheForIos(now)).toBe(5);
@@ -780,6 +783,17 @@ describe('the iOS tile budget', () => {
expect(del).toHaveBeenCalledTimes(5);
});
it('trims the cache of a MapLibre template the same way', async () => {
vi.mocked(isIosDevice).mockReturnValue(true);
const keys = tileKeys(IOS_MAX_TILES + 3);
const del = vi.fn().mockResolvedValue(true);
const open = vi.fn(async (name: string) => ({ keys: vi.fn().mockResolvedValue(name === 'map-tiles-gl' ? keys : []), delete: del }));
vi.stubGlobal('caches', { open });
expect(await trimTileCacheForIos(Date.UTC(2026, 10, 20, 12))).toBe(3);
expect(open.mock.calls.map(([name]) => name)).toEqual(['map-tiles', 'map-tiles-gl']);
});
it('leaves the cache alone off iOS', async () => {
const open = vi.fn();
vi.stubGlobal('caches', { open });
@@ -787,3 +801,63 @@ describe('the iOS tile budget', () => {
expect(open).not.toHaveBeenCalled();
});
});
// ── a template MapLibre draws ────────────────────────────────────────────────
describe('prefetchTiles for a template MapLibre draws (trek:template)', () => {
const bbox: TileBbox = { minLat: 48.8, maxLat: 48.9, minLng: 2.3, maxLng: 2.4 };
const OSM_DE = 'https://tile.openstreetmap.de/{z}/{x}/{y}.png';
afterEach(() => {
useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, map_provider: 'leaflet', maplibre_style: '' } });
});
function drawnByMapLibre() {
useSettingsStore.setState({
settings: { ...useSettingsStore.getState().settings, map_provider: 'maplibre-gl', maplibre_style: 'trek:template' },
});
}
it('fetches with CORS and looks into map-tiles-gl, never into map-tiles', async () => {
drawnByMapLibre();
const open = vi.fn().mockResolvedValue({ match: vi.fn().mockResolvedValue(undefined) });
vi.stubGlobal('caches', { open });
expect(await prefetchTiles(bbox, OSM_DE, 10, 10)).toBeGreaterThan(0);
expect(open).toHaveBeenCalledWith('map-tiles-gl');
expect(open).not.toHaveBeenCalledWith('map-tiles');
for (const [, init] of vi.mocked(fetch).mock.calls) expect(init).toEqual({ mode: 'cors' });
});
it('asks for the dense tiles the map asks for on a dense screen', async () => {
drawnByMapLibre();
vi.stubGlobal('devicePixelRatio', 2);
await prefetchTiles(bbox, 'https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}{r}.png', 10, 10);
const urls = vi.mocked(fetch).mock.calls.map(([url]) => String(url));
expect(urls.length).toBeGreaterThan(0);
for (const url of urls) expect(url).toMatch(/@2x\.png$/);
});
it('keeps the Leaflet way for a host the service worker does not keep CORS tiles of', async () => {
drawnByMapLibre();
await prefetchTiles(bbox, 'https://tiles.example.com/{z}/{x}/{y}.png', 10, 10);
for (const [, init] of vi.mocked(fetch).mock.calls) expect(init).toEqual({ mode: 'no-cors' });
});
it('keeps the Leaflet way for every map that is not MapLibre on its template', async () => {
useSettingsStore.setState({
settings: { ...useSettingsStore.getState().settings, map_provider: 'maplibre-gl', maplibre_style: '' },
});
await prefetchTiles(bbox, OSM_DE, 10, 10);
for (const [, init] of vi.mocked(fetch).mock.calls) expect(init).toEqual({ mode: 'no-cors' });
});
it('clearing offline maps drops both tile caches', async () => {
const del = vi.fn().mockResolvedValue(true);
vi.stubGlobal('caches', { delete: del });
await clearTileCache();
expect(del).toHaveBeenCalledWith('map-tiles');
expect(del).toHaveBeenCalledWith('map-tiles-gl');
});
});
+16
View File
@@ -5,6 +5,7 @@ import { visualizer } from 'rollup-plugin-visualizer';
import { plyrSpriteAlias } from './plyrSpriteAlias.js';
import { withoutRuntimeFonts } from './bookFontPrecache.js';
import { ICON_CHUNK } from './iconChunk.js';
import { GL_TILE_CACHE, isGlRasterTileRequest } from './src/sync/glTileCache.ts';
import { readFileSync } from 'node:fs';
// The version this bundle is built as, baked in at build time. The Docker build
@@ -115,6 +116,21 @@ export default defineConfig(({ mode }) => ({
cacheableResponse: { statuses: [200] },
},
},
{
// Raster tiles a GL map fetches with CORS: the MapLibre template
// style, the GL tour layers and the template-mode prefetch. Before the
// Leaflet rules below, which match the same hosts: their cache holds
// the opaque answers of Leaflet's images and the no-cors prefetch,
// which a CORS fetch cannot read (src/sync/glTileCache.ts). Only real
// 200s are kept here, and maxEntries is MAX_TILES as for map-tiles.
urlPattern: isGlRasterTileRequest,
handler: 'CacheFirst',
options: {
cacheName: GL_TILE_CACHE,
expiration: { maxEntries: 12288, maxAgeSeconds: 30 * 24 * 60 * 60 },
cacheableResponse: { statuses: [200] },
},
},
{
// Carto map tiles (default provider)
// maxEntries MUST stay >= MAX_TILES in src/sync/tilePrefetcher.ts