Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript
41.8 KB
Raw Blame
// @vitest-environment happy-dom
import { describe, expect, it, vi } from 'vitest';
import {
  OVERLAY_IDS,
  imageryError,
  isGround,
  rasterSource,
  readableReason,
  sourceMaxZoom,
  sourceMinZoom,
  tileTemplate,
  tileUrls,
} from './basemap.js';
import { BORDER_LINES } from './borders.js';

/**
 * The provider shapes are the ones `/api/satellite/providers` really answers
 * with (api/satellite.py) — trimmed to the fields the layer reads.
 */
const ESRI = {
  id: 'esri-world-imagery',
  url: 'https://services.arcgisonline.com/.../tile/{z}/{y}/{x}',
  attribution: 'Imagery © Esri',
  max_zoom: 19,
  max_native_zoom: null,
  tile_size: 256,
  meter: null,
};
const CUSTOM_XYZ = {
  id: 'custom-1',
  url: 'https://{s}.tiles.example.org/{z}/{x}/{y}.png',
  attribution: 'Someone',
  max_zoom: 18,
  max_native_zoom: null,
  tile_size: 256,
  meter: null,
};
const SENTINEL = {
  id: 'sentinel2',
  url: 'https://sh.dataspace.copernicus.eu/ogc/wmts/{key}?...',
  attribution: '© Copernicus Sentinel data',
  max_zoom: 18,
  max_native_zoom: 14,
  min_zoom: 7,
  tile_size: 512,
  meter: 'sentinelhub',
};
const GOOGLE_TILES = {
  id: 'google-satellite',
  url: 'https://tile.googleapis.com/v1/2dtiles/{z}/{x}/{y}',
  attribution: 'Map data © Google',
  max_zoom: 22,
  max_native_zoom: null,
  tile_size: 1024,
  meter: 'google',
};
const WIDGET = {
  ...GOOGLE_TILES,
  id: 'google-js',
  widget: 'google-maps-js',
  max_zoom: 21,
  meter: 'google_js',
};

it('explains imagery failures without exposing the upstream URL or response', () => {
  expect(imageryError({ status: 400, message: 'private upstream URL' })).toContain('display layer');
  expect(imageryError({ status: 404 })).toContain('No imagery');
  expect(imageryError({ status: 403 })).toContain('key');
  expect(imageryError({ status: 429 })).toContain('allowance');
  expect(imageryError(new Error('private upstream URL'))).toBe('A tile could not be loaded; try again.');
  // how much of the view is missing is the difference between a hole and a blank
  expect(imageryError(new Error('private upstream URL'), 7)).toBe(
    '7 tiles could not be loaded; try again.'
  );
  // a named failure says why, whatever it took down with it
  expect(imageryError({ status: 429 }, 12)).toContain('allowance');
});

it('prefers what the service said to anything we could write for it', () => {
  const said = 'Could not load necessary digital elevation model.';
  // without it a Copernicus outage is indistinguishable from a bug in Azimut
  expect(imageryError({ status: 500 }, 9, said)).toBe(said);
  expect(imageryError({ status: 400 }, 1, said)).toBe(said);
  // except where ours names what to go and do, which the service cannot know
  expect(imageryError({ status: 403 }, 1, said)).toContain('Settings');
  expect(imageryError({ status: 429 }, 1, said)).toContain('Settings');
});

it('shows a provider sentence only while it still looks like one', () => {
  expect(readableReason('  Orthorectification failed.  ')).toBe('Orthorectification failed.');
  expect(readableReason('')).toBe('');
  expect(readableReason(null)).toBe('');
  // a second pair of eyes on what the proxy already stripped
  expect(readableReason('failed for https://services.sentinel-hub.com/ogc/wmts/abc')).toBe('');
  expect(readableReason('x'.repeat(241))).toBe('');
});

describe('where a provider’s tiles are fetched from', () => {
  it('sends every provider it can through the backend proxy', () => {
    // keys and session tokens stay server-side, and a billed tile is counted
    // exactly once — the proxy is the only place that can do either
    expect(tileTemplate(ESRI, 'esri-world-imagery')).toBe(
      '/api/tiles/esri-world-imagery/{z}/{x}/{y}'
    );
  });

  it('asks for the variant it is showing, not the bare provider', () => {
    // Sentinel-2's layer, window and ceiling ride on the id, so a tile cannot
    // be rendered from one window and filed as another
    expect(tileTemplate(SENTINEL, 'sentinel2~SWIR~2026-05-01~2026-05-01~CC20')).toBe(
      '/api/tiles/sentinel2~SWIR~2026-05-01~2026-05-01~CC20/{z}/{x}/{y}'
    );
  });

  it('leaves a subdomain template direct, because the proxy cannot expand it', () => {
    expect(tileTemplate(CUSTOM_XYZ, 'custom-1')).toBe(CUSTOM_XYZ.url);
  });

  it('expands a subdomain template itself, since the engine takes a list', () => {
    expect(tileUrls(CUSTOM_XYZ.url, undefined)).toEqual([
      'https://a.tiles.example.org/{z}/{x}/{y}.png',
      'https://b.tiles.example.org/{z}/{x}/{y}.png',
      'https://c.tiles.example.org/{z}/{x}/{y}.png',
    ]);
    expect(tileUrls(CUSTOM_XYZ.url, ['x', 'y'])).toEqual([
      'https://x.tiles.example.org/{z}/{x}/{y}.png',
      'https://y.tiles.example.org/{z}/{x}/{y}.png',
    ]);
  });

  it('leaves the proxy’s own template as itself', () => {
    expect(tileUrls('/api/tiles/esri/{z}/{x}/{y}')).toEqual(['/api/tiles/esri/{z}/{x}/{y}']);
  });
});

describe('the deepest tile a provider is asked for', () => {
  it('is its own ceiling, on a plain 256 px grid', () => {
    expect(sourceMaxZoom(ESRI, 256)).toBe(19);
  });

  it('stops at the last level with real pixels, not at the last useful view', () => {
    // Sentinel-2 stops at z14 and stays useful to z18; requesting z18 would buy
    // server-side upsampling of the same pixels, 16× the tiles, every one billed
    expect(sourceMaxZoom(SENTINEL, 512)).toBe(13);
  });

  it('shifts down a level for every doubling of the cell', () => {
    // a 512 px cell covers the ground of four 256 px tiles one zoom deeper, so
    // the URL zoom it asks for is one shallower — the same shift the old
    // engine's zoomOffset made
    expect(sourceMaxZoom(GOOGLE_TILES, 512)).toBe(21);
    // and the z17 detail boost, a 256 px cell for a 1024 px tile
    expect(sourceMaxZoom(GOOGLE_TILES, 256)).toBe(22);
  });
});

describe('the shallowest tile a provider is asked for', () => {
  it('is its floor, shifted down like the ceiling for a bigger cell', () => {
    expect(sourceMinZoom(ESRI, 256)).toBe(0);
    // Sentinel Hub renders no pixel over 1500 m: view z7, grid level 6 of its 512 px tiles
    expect(sourceMinZoom(SENTINEL, 512)).toBe(6);
  });
});

describe('the source one provider is served from', () => {
  it('is a raster grid of the cell size asked for, credited to the provider', () => {
    expect(rasterSource(ESRI, ESRI.id, 256)).toEqual({
      type: 'raster',
      tiles: ['/api/tiles/esri-world-imagery/{z}/{x}/{y}'],
      tileSize: 256,
      minzoom: 0,
      maxzoom: 19,
      attribution: 'Imagery © Esri',
    });
  });

  it('never asks below zero, whatever the cell does to the numbering', () => {
    // a 512 px cell at world zoom would otherwise want a negative URL z
    expect(rasterSource(SENTINEL, 'sentinel2~a~~~CC100', 512).minzoom).toBe(0);
  });
});

/** The FIRMS overlay's engine layers, lowest first (`firePoints.js`). */
const FIRE_LAYERS = ['basemap-firms-foot-fill', 'basemap-firms-foot-ring', 'basemap-firms-foot-edge', 'basemap-firms-mark'];
/** The borders' engine layers, lowest first (`borders.js`). */
const BORDER_LAYERS = BORDER_LINES.layers.map((entry) => `basemap-boundaries-${entry.id}`);

describe('the layers on a map', () => {
  /** A MapLibre map, as far as basemap.js reaches into it. */
  function stubMap() {
    const sources = new Map();
    const layers = [];
    const images = new Map();
    const calls = { setMaxZoom: [], on: [], off: [] };
    return {
      calls,
      sources,
      layers,
      images,
      hasImage: (name) => images.has(name),
      addImage: (name, image, options) => images.set(name, { image, options }),
      addSource: (id, spec) => sources.set(id, spec),
      removeSource: (id) => sources.delete(id),
      getSource: (id) => sources.get(id),
      addLayer: (layer, beforeId) => {
        const at = beforeId ? layers.findIndex((l) => l.id === beforeId) : -1;
        if (at === -1) layers.push(layer);
        else layers.splice(at, 0, layer);
      },
      removeLayer: (id) => {
        const at = layers.findIndex((l) => l.id === id);
        if (at !== -1) layers.splice(at, 1);
      },
      getLayer: (id) => layers.find((l) => l.id === id),
      getLayersOrder: () => layers.map((l) => l.id),
      setPaintProperty: (id, name, value) => {
        const layer = layers.find((l) => l.id === id);
        layer.paint = { ...layer.paint, [name]: value };
      },
      setMaxZoom: (...args) => calls.setMaxZoom.push(args),
      on: (...args) => calls.on.push(args),
      off: (...args) => calls.off.push(args),
    };
  }

  /** The façade, as far as basemap.js reaches into it. */
  function stubEngine(map = stubMap()) {
    return { impl: map, container: document.createElement('div') };
  }

  /**
   * The Google widget costs money to build, so `basemap.js` is exercised with
   * `gmaps.js` stubbed: what matters here is how many were ever made.
   */
  async function withStubbedGoogle(run, loader) {
    vi.resetModules();
    const glasses = [];
    vi.doMock('./gmaps.js', () => ({
      loadGoogleMaps: loader ?? vi.fn(async () => {}),
      createGoogleGlass: () => {
        const glass = { shown: 0, hidden: 0, destroyed: 0 };
        glass.show = () => (glass.shown += 1);
        glass.hide = () => (glass.hidden += 1);
        glass.destroy = () => (glass.destroyed += 1);
        glasses.push(glass);
        return glass;
      },
    }));
    const { createBasemaps } = await import('./basemap.js');
    try {
      await run({ createBasemaps, glasses });
    } finally {
      vi.doUnmock('./gmaps.js');
      vi.resetModules();
    }
  }

  it('takes the previous imagery off before putting the next one on', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.show(ESRI, ESRI.id, 256);
      basemaps.show(SENTINEL, 'sentinel2~TRUE_COLOR~~~CC100', 512);
      expect(map.layers.map((l) => l.id)).toEqual(['basemap-imagery']);
      expect(map.sources.get('basemap-imagery').tiles[0]).toContain('sentinel2~TRUE_COLOR');
    });
  });

  it('lays a second picture over the first and flips it without a reload', async () => {
    // Detect blinks pass A against pass B: both stay loaded, only the paint moves
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const onMeteredTiles = vi.fn();
      const basemaps = createBasemaps(stubEngine(map), { onMeteredTiles });
      basemaps.show(SENTINEL, 'sentinel2~TRUE_COLOR~2026-09-21~2026-09-21~CC100', 512);
      basemaps.setOverlay('boundaries', true);
      basemaps.setAlternate({ ...SENTINEL, meter: 'copernicus' }, 'sentinel2~TRUE_COLOR~2026-09-08~2026-09-08~CC100', 512);
      const order = map.layers.map((l) => l.id);
      expect(order.slice(0, 2)).toEqual(['basemap-imagery', 'basemap-alternate']);
      expect(order.length).toBeGreaterThan(2);  // the borders stay over both pictures
      const second = map.sources.get('basemap-alternate');
      expect(second.tiles[0]).toContain('2026-09-08');
      expect(map.getLayer('basemap-alternate').paint['raster-opacity']).toBe(0);
      expect(onMeteredTiles).toHaveBeenCalled();
      basemaps.showAlternate(true);
      expect(map.getLayer('basemap-alternate').paint['raster-opacity']).toBe(1);
      basemaps.showAlternate(false);
      basemaps.setAlternate({ ...SENTINEL, meter: 'copernicus' }, 'sentinel2~TRUE_COLOR~2026-09-08~2026-09-08~CC100', 512);
      expect(map.sources.get('basemap-alternate')).toBe(second);
      // a new basemap still goes under the second picture
      basemaps.show(ESRI, ESRI.id, 256);
      expect(map.layers.map((l) => l.id).slice(0, 2)).toEqual(['basemap-imagery', 'basemap-alternate']);
      basemaps.setAlternate(null);
      expect(map.getLayer('basemap-alternate')).toBe(undefined);
      expect(map.sources.has('basemap-alternate')).toBe(false);
    });
  });

  it('caps the view at what the provider can serve', async () => {
    // capture sizing reads the view zoom against the provider maximum, and a
    // shallower provider asked past its ceiling answers with a placard
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      createBasemaps(stubEngine(map)).show({ ...ESRI, max_zoom: 17 }, 'opentopomap', 256);
      // the engine counts one level shallower than the app does
      expect(map.calls.setMaxZoom).toEqual([[16]]);
    });
  });

  it('takes the picture off for a plain ground and gives the view its own depth back', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = { ...stubMap(), getMaxZoom: () => current };
      let current = 22;
      map.setMaxZoom = (zoom) => { map.calls.setMaxZoom.push([zoom]); current = zoom; };
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.show({ ...ESRI, max_zoom: 17 }, ESRI.id, 256);
      expect(map.sources.size).toBe(1);
      basemaps.hide();
      expect(map.sources.size).toBe(0);
      expect(map.layers).toEqual([]);
      expect(map.calls.setMaxZoom).toEqual([[16], [22]]);
      // the same picture again is put back, not taken for the one still there
      basemaps.show({ ...ESRI, max_zoom: 17 }, ESRI.id, 256);
      expect(map.sources.size).toBe(1);
    });
  });

  it('stops a linked map at the shallower of its own and the shared ceiling', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.show({ ...ESRI, max_zoom: 19 }, ESRI.id, 256);
      basemaps.setZoomCeiling(17);
      basemaps.setZoomCeiling(21);
      basemaps.setZoomCeiling(null);
      expect(map.calls.setMaxZoom).toEqual([[18], [16], [18], [18]]);
    });
  });

  it('hands the engine a ceiling only when it changes', async () => {
    // Over relief the engine settles the camera by a hair on every ceiling it is
    // handed and reports a move; the surface re-states the basemap on every
    // settled view, so an unchanged ceiling handed back each time froze the page.
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      let ceiling = 22;
      map.getMaxZoom = () => ceiling;
      map.setMaxZoom = (zoom) => {
        map.calls.setMaxZoom.push([zoom]);
        ceiling = zoom;
      };
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.show({ ...ESRI, max_zoom: 19 }, ESRI.id, 256);
      basemaps.show({ ...ESRI, max_zoom: 19 }, ESRI.id, 256);
      basemaps.setZoomCeiling(null);
      expect(map.calls.setMaxZoom).toEqual([[18]]);
      basemaps.setZoomCeiling(17);
      expect(map.calls.setMaxZoom).toEqual([[18], [16]]);
    });
  });

  it('leaves a layer alone when nothing about it changed', async () => {
    // returning to the tab refetches the providers, and the fresh objects re-run
    // the layer effect, so this is the common path rather than an edge case
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.show(ESRI, ESRI.id, 256);
      const first = map.sources.get('basemap-imagery');
      basemaps.show(ESRI, ESRI.id, 256);
      expect(map.sources.get('basemap-imagery')).toBe(first);
    });
  });

  it('rebuilds when the cell changes, because that is a different grid', async () => {
    // Google's oversample halves the cell at one zoom bracket
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.show(GOOGLE_TILES, GOOGLE_TILES.id, 512);
      basemaps.show(GOOGLE_TILES, GOOGLE_TILES.id, 256);
      expect(map.sources.get('basemap-imagery').tileSize).toBe(256);
    });
  });

  it('builds the Google widget once, however often it is shown', async () => {
    // every google.maps.Map instantiation is a billed dynamic map load
    await withStubbedGoogle(async ({ createBasemaps, glasses }) => {
      const onWidgetLoad = vi.fn();
      const basemaps = createBasemaps(stubEngine(), { onWidgetLoad });
      await basemaps.show(WIDGET, WIDGET.id, 256);
      basemaps.show(ESRI, ESRI.id, 256);
      await basemaps.show(WIDGET, WIDGET.id, 256);
      expect(glasses).toHaveLength(1);
      expect(onWidgetLoad).toHaveBeenCalledTimes(1);
    });
  });

  it('hides the widget rather than destroying it when the analyst moves on', async () => {
    await withStubbedGoogle(async ({ createBasemaps, glasses }) => {
      const basemaps = createBasemaps(stubEngine());
      await basemaps.show(WIDGET, WIDGET.id, 256);
      basemaps.show(ESRI, ESRI.id, 256);
      expect(glasses[0].hidden).toBe(1);
      expect(glasses[0].destroyed).toBe(0);
    });
  });

  it('takes the tiles off the map while the widget is showing', async () => {
    // the widget renders under a transparent canvas, so a tile layer left on
    // would sit between the analyst and Google's imagery
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.show(ESRI, ESRI.id, 256);
      await basemaps.show(WIDGET, WIDGET.id, 256);
      expect(map.getLayer('basemap-imagery')).toBeUndefined();
      expect(map.getSource('basemap-imagery')).toBeUndefined();
    });
  });

  it('reports a refused key instead of showing a dead basemap', async () => {
    const onWidgetFailed = vi.fn();
    await withStubbedGoogle(
      async ({ createBasemaps, glasses }) => {
        await createBasemaps(stubEngine(), { onWidgetFailed }).show(WIDGET, WIDGET.id, 256);
        expect(onWidgetFailed).toHaveBeenCalledWith(WIDGET, expect.any(Error));
        expect(glasses).toHaveLength(0); // nothing built, so nothing billed
      },
      vi.fn(async () => {
        throw new Error('could not load the Google Maps script');
      })
    );
  });

  it('drops a widget load the analyst has already moved on from', async () => {
    let release;
    await withStubbedGoogle(
      async ({ createBasemaps, glasses }) => {
        const basemaps = createBasemaps(stubEngine());
        const pending = basemaps.show(WIDGET, WIDGET.id, 256);
        basemaps.show(ESRI, ESRI.id, 256);
        release();
        await pending;
        expect(glasses).toHaveLength(0);
      },
      () => new Promise((resolve) => (release = resolve))
    );
  });

  it('keeps the pill honest for a billed layer, on arrival and once painted', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const onMeteredTiles = vi.fn();
      createBasemaps(stubEngine(map), { onMeteredTiles }).show(
        SENTINEL,
        'sentinel2~a~~~CC100',
        512
      );
      expect(onMeteredTiles).toHaveBeenCalledTimes(1);
      const painted = map.calls.on.find(([name]) => name === 'sourcedata')[1];
      painted({ sourceId: 'basemap-imagery', isSourceLoaded: true });
      expect(onMeteredTiles).toHaveBeenCalledTimes(2);
      // a tile still on its way says nothing yet
      painted({ sourceId: 'basemap-imagery', isSourceLoaded: false });
      expect(onMeteredTiles).toHaveBeenCalledTimes(2);
    });
  });

  it('says nothing about usage for a key-less layer', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const onMeteredTiles = vi.fn();
      createBasemaps(stubEngine(map), { onMeteredTiles }).show(ESRI, ESRI.id, 256);
      expect(onMeteredTiles).not.toHaveBeenCalled();
      const painted = map.calls.on.find(([name]) => name === 'sourcedata')[1];
      painted({ sourceId: 'basemap-imagery', isSourceLoaded: true });
      expect(onMeteredTiles).not.toHaveBeenCalled();
    });
  });

  it('stops an overlay at its own last level rather than blowing it up', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      createBasemaps(stubEngine(map)).setOverlay('railway', true);
      // the deepest tile, and the deepest view, which the engine counts one
      // shallower — the same number, two questions
      expect(map.sources.get('basemap-railway').maxzoom).toBe(19);
      expect(map.getLayer('basemap-railway').maxzoom).toBe(19);
      expect(map.sources.get('basemap-railway').tiles).toHaveLength(3);
      expect(map.sources.get('basemap-railway').tileSize).toBe(256);
    });
  });

  it('draws FIRMS as marks the map paints itself, at every zoom and for any question', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.setOverlay('firms', true, { sensor: 'viirs', window: '7d' });
      const marks = map.sources.get('basemap-firms-marks');
      // one vector source from z0: no picture to swell while the next level loads
      expect(marks).toMatchObject({ type: 'vector', minzoom: 0, maxzoom: 13, tileSize: 512 });
      expect(marks.tiles).toEqual(['/api/firms/points/{z}/{x}/{y}?sensor=viirs&window=7d&v=2']);
      expect(map.layers.map((l) => l.id)).toEqual(FIRE_LAYERS);
      for (const layer of map.layers) expect(layer.source).toBe('basemap-firms-marks');
      // one tintable square for both colours
      expect(map.images.get('firms-square').options).toEqual({ sdf: true });
      // a dated range is the same marks, asked with its days
      basemaps.setOverlay('firms', true, { sensor: 'viirs', window: 'dates', first: '2026-09-01', last: '2026-09-03' });
      expect(map.sources.get('basemap-firms-marks').tiles[0]).toContain('window=dates&first=2026-09-01&last=2026-09-03');
      expect(map.layers.map((l) => l.id)).toEqual(FIRE_LAYERS);
      // and nothing else is laid for it: no picture layer under the marks
      expect([...map.sources.keys()]).toEqual(['basemap-firms-marks']);
    });
  });

  it('tells the tool when a tile of one of its overlays fails, and of nothing else', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const trouble = vi.fn();
      const basemaps = createBasemaps(stubEngine(map), { onOverlayTrouble: trouble });
      const [, onError] = map.calls.on.find(([name]) => name === 'error');
      onError({ sourceId: 'basemap-firms-marks' });
      onError({ sourceId: 'somebody-else' });
      onError({ error: new Error('style') });
      expect(trouble.mock.calls).toEqual([['firms']]);
      basemaps.dispose();
      expect(map.calls.off).toContainEqual(['error', onError]);
    });
  });

  it('reports the failed imagery variant and rebuilds it only when Retry is pressed', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const trouble = vi.fn();
      const basemaps = createBasemaps(stubEngine(map), { onImageryTrouble: trouble });
      const id = 'sentinel2~TRUE_COLOR~2026-09-25~2026-09-25';
      basemaps.show(SENTINEL, id, 512);
      basemaps.setAlternate(SENTINEL, 'sentinel2~SWIR', 512);
      const [, onError] = map.calls.on.find(([name]) => name === 'error');
      const settle = map.calls.on.find(([name]) => name === 'sourcedata')[1];
      const error = { status: 400 };
      onError({ sourceId: 'basemap-imagery', error });
      onError({ sourceId: 'basemap-alternate', error });
      onError({ sourceId: 'basemap-roads', error });
      // one tile is a gap, not a verdict: the view it belongs to speaks first
      expect(trouble).not.toHaveBeenCalled();
      settle({ sourceId: 'basemap-imagery', isSourceLoaded: true });
      settle({ sourceId: 'basemap-alternate', isSourceLoaded: true });
      expect(trouble.mock.calls).toEqual([
        [{ id, error, failed: 1, reason: '' }],
        [{ id: 'sentinel2~SWIR', error, failed: 1, reason: '' }],
      ]);
      const source = map.sources.get('basemap-imagery');
      basemaps.show(SENTINEL, id, 512);
      expect(map.sources.get('basemap-imagery')).toBe(source);
      basemaps.retry(SENTINEL, id, 512);
      expect(map.sources.get('basemap-imagery')).not.toBe(source);
      expect(map.sources.get('basemap-imagery').tiles[0]).toContain(id);
    });
  });

  it('takes back the trouble it reported once a settle comes through clean', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const trouble = vi.fn();
      const basemaps = createBasemaps(stubEngine(map), { onImageryTrouble: trouble });
      const id = 'sentinel2~TRUE_COLOR~2026-09-25~2026-09-25';
      basemaps.show(SENTINEL, id, 512);
      const [, onError] = map.calls.on.find(([name]) => name === 'error');
      const settle = map.calls.on.find(([name]) => name === 'sourcedata')[1];
      onError({ sourceId: 'basemap-imagery', error: { status: 500 } });
      settle({ sourceId: 'basemap-imagery', isSourceLoaded: true });
      expect(trouble).toHaveBeenLastCalledWith({ id, error: { status: 500 }, failed: 1, reason: '' });
      // the analyst pans, the tiles come through: nothing is wrong any more
      settle({ sourceId: 'basemap-imagery', isSourceLoaded: true });
      expect(trouble).toHaveBeenLastCalledWith({ id, error: null, failed: 0, reason: '' });
    });
  });

  it('passes on what the provider said about the tile it refused', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const trouble = vi.fn();
      const basemaps = createBasemaps(stubEngine(map), { onImageryTrouble: trouble });
      const id = 'sentinel1~2026-10-06~151800';
      basemaps.show(SENTINEL, id, 512);
      const [, onError] = map.calls.on.find(([name]) => name === 'error');
      const settle = map.calls.on.find(([name]) => name === 'sourcedata')[1];
      // what the proxy hands over: the service's own sentence, already stripped
      const said = 'Could not load necessary digital elevation model.';
      const error = { status: 500, body: { text: () => Promise.resolve(said) } };

      onError({ sourceId: 'basemap-imagery', error });
      settle({ sourceId: 'basemap-imagery', isSourceLoaded: true });
      await Promise.resolve();
      await Promise.resolve();

      expect(trouble).toHaveBeenLastCalledWith({ id, error, failed: 1, reason: said });
    });
  });

  it('says so without waiting when enough tiles fail that nothing will settle', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const trouble = vi.fn();
      const basemaps = createBasemaps(stubEngine(map), { onImageryTrouble: trouble });
      const id = 'sentinel2~TRUE_COLOR~2026-09-25~2026-09-25';
      basemaps.show(SENTINEL, id, 512);
      const [, onError] = map.calls.on.find(([name]) => name === 'error');
      const error = { status: 502 };
      for (const _ of [1, 2, 3]) onError({ sourceId: 'basemap-imagery', error });
      expect(trouble).not.toHaveBeenCalled();
      onError({ sourceId: 'basemap-imagery', error });
      expect(trouble.mock.calls).toEqual([[{ id, error, failed: 4, reason: '' }]]);
    });
  });

  it('adds an overlay once and takes it off when asked', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.setOverlay('railway', true);
      basemaps.setOverlay('railway', true);
      expect(map.layers.map((l) => l.id)).toEqual(['basemap-railway']);
      basemaps.setOverlay('railway', false);
      expect(map.layers).toEqual([]);
    });
  });

  it('ignores an overlay it does not have', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      createBasemaps(stubEngine(map)).setOverlay('weather', true);
      expect(map.layers).toEqual([]);
    });
  });

  it('builds a layer that is a question from the question it was asked', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      createBasemaps(stubEngine(map)).setOverlay('firms', true, {
        sensor: 'modis',
        window: '48h',
      });
      const [url] = map.sources.get('basemap-firms-marks').tiles;
      // through the app, because the key is NASA's and stays on the backend
      expect(url).toContain('/api/firms/points/{z}/{x}/{y}?');
      expect(url).toContain('sensor=modis');
      expect(url).toContain('window=48h');
    });
  });

  it('rebuilds that layer when the question changes, and only then', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      const params = { sensor: 'viirs', window: '24h' };
      basemaps.setOverlay('firms', true, params);
      const first = map.sources.get('basemap-firms-marks');
      // the same question again is the same tiles: rebuilding would refetch
      // every one of them, which reads on screen as a reloading map
      basemaps.setOverlay('firms', true, { ...params });
      expect(map.sources.get('basemap-firms-marks')).toBe(first);

      basemaps.setOverlay('firms', true, { sensor: 'viirs', window: '7d' });
      expect(map.sources.get('basemap-firms-marks')).not.toBe(first);
      expect(map.sources.get('basemap-firms-marks').tiles[0]).toContain('window=7d');
      expect(map.layers.map((l) => l.id)).toEqual(FIRE_LAYERS);
    });
  });

  it('draws the fires over the names, because when it is on it is the subject', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.setOverlay('firms', true, { sensor: 'viirs', window: '24h' });
      basemaps.setOverlay('boundaries', true);
      basemaps.setOverlay('railway', true);
      expect(map.layers.map((l) => l.id)).toEqual(['basemap-railway', ...BORDER_LAYERS, ...FIRE_LAYERS]);
    });
  });

  it('holds the overlay stack however they are switched on', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      // the names last, whichever order they arrive in: a station label under
      // its own track is a label nobody can read
      basemaps.setOverlay('boundaries', true);
      basemaps.setOverlay('railway', true);
      expect(map.layers.map((l) => l.id)).toEqual(['basemap-railway', ...BORDER_LAYERS]);
    });
  });

  it('keeps every overlay over the imagery and all of them under what a tool draws', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.show(ESRI, ESRI.id, 256);
      basemaps.setOverlay('railway', true);
      basemaps.setOverlay('boundaries', true);
      // a tool's own layer, appended above all three
      map.addLayer({ id: 'sfc-1-fill' });
      // and now a different provider, which must not land on top of any of them
      basemaps.show(SENTINEL, 'sentinel2~a~~~CC100', 512);
      expect(map.layers.map((l) => l.id)).toEqual([
        'basemap-imagery',
        'basemap-railway',
        ...BORDER_LAYERS,
        'sfc-1-fill',
      ]);
    });
  });

  it('draws a vector overlay as all of its layers, and takes them all off together', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.setOverlay('power', true);
      expect([...map.sources.keys()]).toEqual([
        'basemap-power-power',
        'basemap-power-telecoms',
        'basemap-power-petroleum',
      ]);
      expect(map.sources.get('basemap-power-power')).toMatchObject({
        type: 'vector',
        tiles: ['https://openinframap.org/map/power/{z}/{x}/{y}.pbf'],
      });
      const ids = map.layers.map((l) => l.id);
      expect(ids[0]).toBe('basemap-power-pipeline');
      expect(ids).toContain('basemap-power-tower');
      // every layer reads the source it names, under this overlay's own prefix
      expect(map.getLayer('basemap-power-mast').source).toBe('basemap-power-telecoms');
      basemaps.setOverlay('power', false);
      expect(map.layers).toEqual([]);
      expect(map.sources.size).toBe(0);
    });
  });

  it('reads the place names from the TileJSON that names OpenFreeMap’s current build', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.setOverlay('boundaries', true);
      expect(map.sources.has('basemap-placenames-openmaptiles')).toBe(false);

      basemaps.setOverlay('placenames', true);
      const source = map.sources.get('basemap-placenames-openmaptiles');
      expect(source).toMatchObject({
        type: 'vector',
        url: 'https://tiles.openfreemap.org/planet',
        maxzoom: 14,
        attribution: expect.stringContaining('OpenStreetMap'),
      });
      // a dated template would break the week the build it names is removed
      expect(source).not.toHaveProperty('tiles');
      // over the borders, whose own names are the larger places
      expect(map.layers.map((l) => l.id)).toEqual([...BORDER_LAYERS, 'basemap-placenames-label']);
      expect(map.getLayer('basemap-placenames-label').source).toBe('basemap-placenames-openmaptiles');

      basemaps.setOverlay('placenames', false);
      expect(map.sources.has('basemap-placenames-openmaptiles')).toBe(false);
      expect(map.layers.map((l) => l.id)).toEqual(BORDER_LAYERS);
    });
  });

  it('draws the borders as OpenFreeMap’s lines and names, under the place names', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.show(ESRI, ESRI.id, 256);
      basemaps.setOverlay('roads', true);
      basemaps.setOverlay('boundaries', true);
      basemaps.setOverlay('placenames', true);
      const ids = map.layers.map((l) => l.id);
      const lines = ids.filter((id) => id.startsWith('basemap-boundaries-'));
      expect(lines).toContain('basemap-boundaries-region');
      expect(lines).toContain('basemap-boundaries-country');
      expect(lines.at(-1)).toBe('basemap-boundaries-names');
      // over the roads, under the place names
      expect(ids.slice(0, 2)).toEqual(['basemap-imagery', 'basemap-roads']);
      expect(ids.slice(2, -1).every((id) => id.startsWith('basemap-boundaries-'))).toBe(true);
      expect(ids.at(-1)).toBe('basemap-placenames-label');
      expect(map.sources.get('basemap-boundaries-openmaptiles')).toMatchObject({
        type: 'vector',
        url: 'https://tiles.openfreemap.org/planet',
        attribution: expect.stringContaining('OpenFreeMap'),
      });
      basemaps.setOverlay('boundaries', false);
      expect(map.layers.map((l) => l.id)).toEqual(['basemap-imagery', 'basemap-roads', 'basemap-placenames-label']);
      expect(map.sources.has('basemap-boundaries-openmaptiles')).toBe(false);
    });
  });

  it('traces a failed tile of the borders’ lines back to the borders', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const onOverlayTrouble = vi.fn();
      const basemaps = createBasemaps(stubEngine(map), { onOverlayTrouble });
      basemaps.setOverlay('boundaries', true);
      const onError = map.calls.on.find(([name]) => name === 'error')[1];
      onError({ sourceId: 'basemap-boundaries-openmaptiles', error: { status: 503 } });
      expect(onOverlayTrouble).toHaveBeenCalledWith('boundaries');
    });
  });

  it('slides a vector overlay into the stack as one block', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.setOverlay('boundaries', true);
      basemaps.setOverlay('railway', true);
      basemaps.setOverlay('power', true);
      const ids = map.layers.map((l) => l.id);
      // over the tracks, under the names
      expect(ids[0]).toBe('basemap-railway');
      expect(ids.slice(-BORDER_LAYERS.length)).toEqual(BORDER_LAYERS);
      expect(ids.slice(1, -BORDER_LAYERS.length).every((id) => id.startsWith('basemap-power-'))).toBe(true);
    });
  });

  it('holds the whole stack, lowest first, whatever order the switches were pressed in', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.show(ESRI, ESRI.id, 256);
      for (const id of ['firms', 'placenames', 'boundaries', 'seamarks', 'railway', 'roads', 'gpstraces']) {
        basemaps.setOverlay(id, true, id === 'firms' ? { sensor: 'viirs', window: '24h' } : undefined);
      }
      basemaps.setOverlay('nightlights', true, { source: 'noaa20', day: '2026-09-12' });
      expect(map.layers.map((l) => l.id)).toEqual([
        'basemap-imagery',
        'basemap-nightlights',
        'basemap-gpstraces',
        'basemap-roads',
        'basemap-railway',
        'basemap-seamarks',
        ...BORDER_LAYERS,
        'basemap-placenames-label',
        ...FIRE_LAYERS,
      ]);
    });
  });

  it('has no CARTO labels layer: its tiles now ask for a key', () => {
    expect(OVERLAY_IDS).not.toContain('labels');
  });

  it('asks GIBS for the night it was given, and lets its coarse pixels be read zoomed in', async () => {
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      basemaps.setOverlay('nightlights', true, { source: 'snpp', day: '2022-02-24' });
      const source = map.sources.get('basemap-nightlights');
      expect(source.tiles[0]).toContain('/VIIRS_SNPP_DayNightBand_At_Sensor_Radiance/default/2022-02-24/');
      expect(source.maxzoom).toBe(8);
      const layer = map.getLayer('basemap-nightlights');
      expect(layer.maxzoom).toBe(24);
      expect(layer.paint['raster-opacity']).toBeLessThan(1);

      basemaps.setOverlay('nightlights', true, { source: 'snpp', day: '2022-02-25' });
      expect(map.sources.get('basemap-nightlights').tiles[0]).toContain('/2022-02-25/');
    });
  });

  it('fetches every key-less overlay straight from its own server, over https', async () => {
    // none of them is keyed or billed, so none of them needs the app in between;
    // FIRMS is the one whose key has to stay on the backend
    await withStubbedGoogle(async ({ createBasemaps }) => {
      const { OVERLAY_IDS } = await import('./basemap.js');
      const params = {
        firms: { sensor: 'viirs', window: '24h' },
        nightlights: { source: 'noaa20', day: '2026-09-12' },
      };
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      for (const id of OVERLAY_IDS) basemaps.setOverlay(id, true, params[id]);
      for (const [id, source] of map.sources) {
        const expected = id === 'basemap-firms-marks' ? /^\/api\/firms\/points\// : /^https:\/\//;
        for (const url of source.tiles ?? [source.url]) expect(url, id).toMatch(expected);
        expect(source.attribution, id).toBeTruthy();
      }
    });
  });

  it('stops listening when the map goes, and lets the widget go with it', async () => {
    await withStubbedGoogle(async ({ createBasemaps, glasses }) => {
      const map = stubMap();
      const basemaps = createBasemaps(stubEngine(map));
      await basemaps.show(WIDGET, WIDGET.id, 256);
      basemaps.dispose();
      expect(map.calls.off).toEqual([
        ['sourcedata', expect.any(Function)],
        ['error', expect.any(Function)],
      ]);
      expect(glasses[0].destroyed).toBe(1);
    });
  });
});


describe('billed tiles on a map that can tilt', () => {
  it('asks a billed provider through the guard, and a free one at its own address', () => {
    expect(rasterSource(SENTINEL, 'sentinel2', 512, 'm4').tiles).toEqual([
      'azimut-billed://m4/sentinel2/{z}/{x}/{y}',
    ]);
    expect(rasterSource(ESRI, 'esri-world-imagery', 256, 'm4').tiles).toEqual(['/api/tiles/esri-world-imagery/{z}/{x}/{y}']);
    // a direct {s} template is never billed and never passes through the app
    expect(rasterSource({ ...CUSTOM_XYZ, meter: 'x' }, 'custom-1', 256, 'm4').tiles[0]).toContain('tiles.example.org');
    // without a map to read the view from, the plain proxy address
    expect(rasterSource(SENTINEL, 'sentinel2', 512).tiles).toEqual(['/api/tiles/sentinel2/{z}/{x}/{y}']);
  });

  it('asks a free provider the app keeps in batches, and leaves every other at its own address', () => {
    const kept = { ...ESRI, cacheable: true };
    expect(rasterSource(kept, 'esri-wayback~20', 256, 'm4').tiles).toEqual(['azimut-tiles://esri-wayback~20/{z}/{x}/{y}']);
    // the browser's own cache spares a provider the app does not keep a second request
    expect(rasterSource({ ...ESRI, cacheable: false }, 'esri-world-imagery', 256, 'm4').tiles).toEqual(['/api/tiles/esri-world-imagery/{z}/{x}/{y}']);
    // billed tiles keep the guard, which counts each one; widgets and direct templates never pass through here
    expect(rasterSource({ ...SENTINEL, cacheable: true }, 'sentinel2', 512, 'm4').tiles).toEqual(['azimut-billed://m4/sentinel2/{z}/{x}/{y}']);
    expect(rasterSource({ ...kept, widget: 'google_js' }, 'g', 256, 'm4').tiles).toEqual(['/api/tiles/g/{z}/{x}/{y}']);
    expect(rasterSource({ ...CUSTOM_XYZ, cacheable: true }, 'custom-1', 256, 'm4').tiles[0]).toContain('tiles.example.org');
    // a source outside the app's maps keeps the plain address
    expect(rasterSource(kept, 'esri-world-imagery', 256).tiles).toEqual(['/api/tiles/esri-world-imagery/{z}/{x}/{y}']);
  });
});

describe('the picture itself, apart from what is laid over it', () => {
  it('counts the imagery and the second picture Blink lays on it as the ground', () => {
    expect(isGround('basemap-imagery')).toBe(true);
    expect(isGround('basemap-alternate')).toBe(true);
    expect(isGround('basemap-boundaries-country')).toBe(false);
    expect(isGround('basemap-placenames-labels')).toBe(false);
    // the case's marks and added layers are laid over it too
    expect(isGround('sfc-3-fill')).toBe(false);
  });

  it('counts an overlay in when the reading is made of it, every one of its layers', () => {
    expect(isGround('basemap-nightlights', ['nightlights'])).toBe(true);
    expect(isGround('basemap-firms-marks', ['firms'])).toBe(true);
    expect(isGround('basemap-firms-marks', ['nightlights'])).toBe(false);
  });
});