import { useSyncExternalStore } from 'react'; import { GL_BASEMAP_SOURCE, isGlRasterStyle } from './glBasemap'; /* * Whether a raster template a MapLibre map draws actually loads here. * * glCanFetch answers from the policy TREK ships, but a reverse proxy can send a * different Content-Security-Policy, and a tile server can refuse cross-origin * requests that Leaflet's images never made. Either way every tile fails and the * GL map stays empty while Leaflet would have drawn the template. So the first * requests are watched: when the browser reports a CSP refusal for one of the * template's tiles, or the first FIRST_TILES all fail without one success, the * template is marked for the rest of the session and every map drawing it takes * Leaflet instead, with a pill that says so. Nothing is stored: the next session * tries GL again. */ /** How many tile results decide: all of them failing is no outage of one tile. */ const FIRST_TILES = 12; const failed = new Set(); const listeners = new Set<() => void>(); let version = 0; function markFailed(template: string): void { if (failed.has(template)) return; failed.add(template); version++; for (const listener of listeners) listener(); } /** Whether a GL map failed to load this template's tiles in this session. */ export function rasterTemplateFailed(template: string): boolean { return failed.has(template); } function subscribe(listener: () => void): () => void { listeners.add(listener); return () => { listeners.delete(listener); }; } /** Re-renders the caller when a template was marked, so its map can switch to Leaflet. */ export function useRasterHealth(): number { return useSyncExternalStore( subscribe, () => version, () => version ); } /** The events of a GL map this module reads; both engines fire them in this shape. */ interface WatchedMap { on(type: 'data' | 'error', listener: (event: { sourceId?: string; tile?: unknown }) => void): unknown; once(type: 'remove', listener: () => void): unknown; } /** The origins of a style's tile URLs, `https://host[:port]`, to match a refused URL against. */ function tileOrigins(tiles: string[]): string[] { return tiles.flatMap((url) => { try { return [new URL(url).origin]; } catch { return []; } }); } function isWatchable(map: unknown): map is WatchedMap { const candidate = map as Partial | null; return typeof candidate?.on === 'function' && typeof candidate.once === 'function'; } /** * Watches a freshly built map whose style draws a raster template (buildGlMap * calls this for every map it builds). Any other style is left alone. Stops on * its own once a tile arrived, the template was marked, or the map is removed. */ export function watchRasterHealth(map: unknown, style: unknown): (() => void) | undefined { if (!isGlRasterStyle(style) || !isWatchable(map)) return; const template = style.metadata['trek:template']; const origins = tileOrigins(style.sources[GL_BASEMAP_SOURCE]?.tiles ?? []); let failures = 0; let settled = false; function settle(broken: boolean): void { if (settled) return; settled = true; document.removeEventListener('securitypolicyviolation', onViolation); if (broken) markFailed(template); } function onViolation(event: SecurityPolicyViolationEvent): void { const blocked = event.blockedURI; if (origins.some((origin) => blocked === origin || blocked.startsWith(`${origin}/`))) settle(true); } document.addEventListener('securitypolicyviolation', onViolation); map.on('data', (event) => { if (event.sourceId === GL_BASEMAP_SOURCE && event.tile) settle(false); }); map.on('error', (event) => { if (event.sourceId !== GL_BASEMAP_SOURCE || settled) return; failures++; if (failures >= FIRST_TILES) settle(true); }); map.once('remove', () => settle(false)); return () => settle(false); } /** Test seam: a fresh session. */ export function resetRasterHealth(): void { failed.clear(); version++; }