diff --git a/src/serve_style.js b/src/serve_style.js index 7de4f06..3c0c75a 100644 --- a/src/serve_style.js +++ b/src/serve_style.js @@ -7,44 +7,12 @@ import clone from 'clone'; import express from 'express'; import { validateStyleMin } from '@maplibre/maplibre-gl-style-spec'; -import { getPublicUrl } from './utils.js'; +import { fixUrl, allowedOptions } from './utils.js'; const httpTester = /^https?:\/\//i; -const allowedSpriteScales = allowedOptions(['', '@2x', '@3x'], ''); +const allowedSpriteScales = allowedOptions(['', '@2x', '@3x']); const allowedSpriteFormats = allowedOptions(['png', 'json']); -/** - * - * @param opts - * @param root0 - * @param root0.defaultValue - */ -function allowedOptions(opts, { defaultValue } = {}) { - const values = Object.fromEntries(opts.map((key) => [key, key])); - return (value) => values[value] || defaultValue; -} - -/** - * - * @param req - * @param url - * @param publicUrl - */ -function fixUrl(req, url, publicUrl) { - if (!url || typeof url !== 'string' || url.indexOf('local://') !== 0) { - return url; - } - const queryParams = []; - if (req.query.key) { - queryParams.unshift(`key=${encodeURIComponent(req.query.key)}`); - } - let query = ''; - if (queryParams.length) { - query = `?${queryParams.join('&')}`; - } - return url.replace('local://', getPublicUrl(publicUrl, req)) + query; -} - export const serve_style = { init: (options, repo) => { const app = express().disable('x-powered-by'); diff --git a/src/utils.js b/src/utils.js index 2a516bc..b5b737b 100644 --- a/src/utils.js +++ b/src/utils.js @@ -6,6 +6,38 @@ import fs, { existsSync } from 'node:fs'; import clone from 'clone'; import glyphCompose from '@mapbox/glyph-pbf-composite'; +/** + * Restrict user input to an allowed set of options. + * @param opts + * @param root0 + * @param root0.defaultValue + */ +export function allowedOptions(opts, { defaultValue } = {}) { + const values = Object.fromEntries(opts.map((key) => [key, key])); + return (value) => values[value] || defaultValue; +} + +/** + * Replace local:// urls with public http(s):// urls + * @param req + * @param url + * @param publicUrl + */ +export function fixUrl(req, url, publicUrl) { + if (!url || typeof url !== 'string' || url.indexOf('local://') !== 0) { + return url; + } + const queryParams = []; + if (req.query.key) { + queryParams.unshift(`key=${encodeURIComponent(req.query.key)}`); + } + let query = ''; + if (queryParams.length) { + query = `?${queryParams.join('&')}`; + } + return url.replace('local://', getPublicUrl(publicUrl, req)) + query; +} + /** * Generate new URL object * @param req