/** * Loads Mapbox GL JS from Mapbox's CDN. * * Mapbox GL JS v2+ is proprietary, so anymap-ts must not bundle it into its * MIT-licensed builds. The npm package is a dev dependency used only for types * and for the SRI test: `tests/typescript/mapboxGlLoader.test.ts` fails until * these constants match the installed version, and the `mapbox-gl` esbuild alias * in package.json fails the build if a runtime import reaches any bundle. */ import type mapboxgl from 'mapbox-gl'; export const MAPBOX_GL_VERSION = '3.34.1'; const CDN_BASE = `https://api.mapbox.com/mapbox-gl-js/v${MAPBOX_GL_VERSION}`; export const MAPBOX_GL_SCRIPT_URL = `${CDN_BASE}/mapbox-gl.js`; export const MAPBOX_GL_STYLE_URL = `${CDN_BASE}/mapbox-gl.css`; export const MAPBOX_GL_SCRIPT_INTEGRITY = 'sha384-bRGpP2/mvLNdh4nRXgIf97xnGmUJRpB58iFa5NaGLEFu8v+0T/Bc0c+iX+AvMgVP'; export const MAPBOX_GL_STYLE_INTEGRITY = 'sha384-QWCpuitI3tz8lJHSbcFQpEAx5BkQcYir4RLGZBb8zOIH0es6XDO8Kv6Gat+wOJRN'; export type MapboxGl = typeof mapboxgl; /** * anywidget can evaluate this module once per widget, so the load is cached on * the page rather than in a module variable. */ const LOAD_KEY = Symbol.for(`anymap-ts.mapbox-gl.${MAPBOX_GL_VERSION}`); type LoaderGlobals = { [LOAD_KEY]?: Promise; mapboxgl?: MapboxGl; define?: { amd?: unknown }; }; /** * Add a script or stylesheet element to the page and wait for it. * * @param element The element, with its URL and integrity already set. * @param url The URL to name in the error message. * @returns A promise that settles with the element's load or error event. */ function appendAndWait(element: HTMLElement, url: string): Promise { return new Promise((resolve, reject) => { element.addEventListener('load', () => resolve(), { once: true }); element.addEventListener( 'error', () => { element.remove(); reject(new Error(`Could not load ${url}`)); }, { once: true }, ); document.head.appendChild(element); }); } /** * Run the Mapbox GL JS script on a page with an AMD loader. * * Classic notebooks define one, which would make the UMD script register an * anonymous module instead of setting `window.mapboxgl`. An inline script runs * synchronously on append, so `define.amd` is hidden only while Mapbox's own * code runs and other modules loading through that loader are not affected. * * @param define The page's AMD `define`. * @returns A promise that settles once the script has run. */ async function runScriptUnderAmd(define: { amd?: unknown }): Promise { const response = await fetch(MAPBOX_GL_SCRIPT_URL, { integrity: MAPBOX_GL_SCRIPT_INTEGRITY }); if (!response.ok) { throw new Error(`Could not load ${MAPBOX_GL_SCRIPT_URL} (HTTP ${response.status})`); } const script = document.createElement('script'); script.textContent = await response.text(); const amd = define.amd; define.amd = undefined; try { document.head.appendChild(script); } finally { define.amd = amd; } } /** * Load the Mapbox GL JS script. * * @returns A promise that settles once the script has run. */ function loadScript(): Promise { const define = (globalThis as unknown as LoaderGlobals).define; if (define?.amd) return runScriptUnderAmd(define); const script = document.createElement('script'); script.src = MAPBOX_GL_SCRIPT_URL; script.integrity = MAPBOX_GL_SCRIPT_INTEGRITY; script.crossOrigin = 'anonymous'; return appendAndWait(script, MAPBOX_GL_SCRIPT_URL); } /** * Load the Mapbox GL stylesheet. * * @returns A promise that settles once the stylesheet has loaded. */ function loadStyle(): Promise { const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = MAPBOX_GL_STYLE_URL; link.integrity = MAPBOX_GL_STYLE_INTEGRITY; link.crossOrigin = 'anonymous'; return appendAndWait(link, MAPBOX_GL_STYLE_URL); } /** * Load Mapbox GL JS and its stylesheet, once per page. * * A failed load is not cached, so the next widget tries again. Both files settle * before that can happen, so a retry never overlaps an attempt still in flight. * * @returns The `mapboxgl` namespace. */ export function loadMapboxGl(): Promise { const page = globalThis as unknown as LoaderGlobals; const cached = page[LOAD_KEY]; if (cached) return cached; const load = Promise.allSettled([loadScript(), loadStyle()]) .then((results) => { for (const result of results) { if (result.status === 'rejected') throw result.reason; } // A script that throws while running still fires `load`. if (!page.mapboxgl) throw new Error('Mapbox GL JS did not define `mapboxgl`.'); return page.mapboxgl; }) .catch((error: unknown) => { delete page[LOAD_KEY]; throw error; }); page[LOAD_KEY] = load; return load; }