Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -549,13 +549,14 @@ All error responses follow this format:

### Map Errors

| Code | Status | Description |
| -------------------- | ------ | ------------------------------------------------------------------------ |
| `MAP_NOT_FOUND` | 404 | The requested map does not exist |
| `RESOURCE_NOT_FOUND` | 404 | The map exists but the requested resource (tile, sprite, glyph) does not |
| `INVALID_MAP_FILE` | 400 | The uploaded file is not a valid SMP file |
| `UPLOAD_IN_PROGRESS` | 409 | Another upload for this map is already in progress |
| `UPLOAD_TIMEOUT` | 408 | Upload aborted: no body data received within the idle timeout |
| Code | Status | Description |
| ---------------------- | ------ | ------------------------------------------------------------------------ |
| `MAP_NOT_FOUND` | 404 | The requested map does not exist |
| `RESOURCE_NOT_FOUND` | 404 | The map exists but the requested resource (tile, sprite, glyph) does not |
| `INVALID_MAP_FILE` | 400 | The uploaded file is not a valid SMP file |
| `UPLOAD_IN_PROGRESS` | 409 | Another upload for this map is already in progress |
| `UPLOAD_TIMEOUT` | 408 | Upload aborted: no body data received within the idle timeout |
| `INVALID_ONLINE_STYLE` | 502 | The online (Mapbox) style was fetched but could not be read |

### Map Share Errors (Sender-side)

Expand Down
5 changes: 5 additions & 0 deletions src/lib/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,11 @@ const errorsList = [
message: 'Invalid map file',
status: 400,
},
{
code: 'INVALID_ONLINE_STYLE',
message: 'The online map style could not be read',
status: 502,
},
{
code: 'MAP_WRITE_ERROR',
message: 'Failed to write map data',
Expand Down
47 changes: 36 additions & 11 deletions src/routes/maps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import Mutex from 'p-mutex'
import { notoGlyphFallback } from 'smp-noto-glyphs'
import { emptyTileFallback } from 'styled-map-package-api/fallbacks'
import { createServer as createSmpServer } from 'styled-map-package-api/server'
import { Type as T } from 'typebox'
import { Compile } from 'typebox/compile'

import type { Context } from '../context.js'
import {
Expand All @@ -15,6 +17,22 @@ import { BASE_MAPBOX_API_URL, transformUrls } from '../lib/style.js'
import { addTrailingSlash } from '../lib/utils.js'
import type { MapInfoResponse } from '../types.js'

// Only the parts transformUrls reads; anything else in the style is passed on
const CompiledOnlineStyle = Compile(
T.Object({
version: T.Number(),
sources: T.Record(T.String(), T.Object({})),
layers: T.Array(T.Unknown()),
sprite: T.Optional(
T.Union([
T.String(),
T.Array(T.Object({ id: T.String(), url: T.String() })),
]),
),
glyphs: T.Optional(T.String()),
}),
)

type MapRequest = IRequestStrict & {
params: {
mapId: string
Expand Down Expand Up @@ -172,17 +190,24 @@ export function MapsRouter(

if (response && response.ok) {
if (url.toString().startsWith(BASE_MAPBOX_API_URL)) {
const body = (await response.json()) as Parameters<
typeof transformUrls
>[0]

transformUrls(body, {
accessToken:
defaultOnlineStyleUrl.searchParams.get('access_token') ||
undefined,
})

return Response.json(body, {
let style: unknown
try {
style = await response.json()
if (!CompiledOnlineStyle.Check(style)) {
throw new Error('Not a map style')
}
transformUrls(style as Parameters<typeof transformUrls>[0], {
accessToken:
defaultOnlineStyleUrl.searchParams.get('access_token') ||
undefined,
})
} catch (err) {
throw new errors.INVALID_ONLINE_STYLE(
`The online map style could not be read: ${(err as Error).message}`,
)
}

return Response.json(style, {
status: 200,
headers: {
'access-control-allow-origin': '*',
Expand Down
73 changes: 72 additions & 1 deletion test/maps.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import path from 'node:path'
import { setTimeout as delay } from 'node:timers/promises'
import { fileURLToPath } from 'node:url'

import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
import { Reader } from 'styled-map-package-api/reader'
import Value from 'typebox/value'
import { describe, it, expect, vi } from 'vitest'
import { describe, it, expect, vi, type TestContext } from 'vitest'

import { MapInfoResponse } from '../src/types.js'
import {
Expand Down Expand Up @@ -303,6 +305,75 @@ describe('Online Style Fallback', () => {
})
})

describe('Mapbox Style', () => {
const nonExistentPath = path.join(
os.tmpdir(),
`nonexistent-map-${randomBytes(8).toString('hex')}.smp`,
)
const MAPBOX_STYLE_URL =
'https://api.mapbox.com/styles/v1/mapbox/streets-v12?access_token=pk.test'

function mockMapbox(t: TestContext, response: () => Response) {
const server = setupServer(
http.get('https://api.mapbox.com/styles/*', response),
)
server.listen({ onUnhandledRequest: 'bypass' })
t.onTestFinished(() => server.close())
}

it('serves the Mapbox style with its URLs rewritten', async (t) => {
const fixture = fs.readFileSync(
new URL('./fixtures/mapbox-streets-v12.json', import.meta.url),
'utf8',
)
mockMapbox(t, () => HttpResponse.json(JSON.parse(fixture)))
const { localBaseUrl } = await startServer(t, {
customMapPath: nonExistentPath,
defaultOnlineStyleUrl: MAPBOX_STYLE_URL,
})
const response = await fetch(`${localBaseUrl}/maps/default/style.json`)
expect(response.status).toBe(200)
const style: any = await response.json()
expect(style.glyphs).toMatch(/^https:\/\/api\.mapbox\.com\//)
})

for (const [name, body] of [
['not JSON', '<html>Oops</html>'],
['JSON null', 'null'],
['an array', '[]'],
['missing layers', '{"version": 8, "sources": {}}'],
['sources as an array', '{"version": 8, "sources": [], "layers": []}'],
[
'a sprite of the wrong type',
'{"version": 8, "sources": {}, "layers": [], "sprite": 5}',
],
[
'a style with an invalid sprite URL',
'{"version": 8, "sources": {}, "layers": [], "sprite": "not a url"}',
],
]) {
it(`responds INVALID_ONLINE_STYLE when the Mapbox response is ${name}`, async (t) => {
mockMapbox(
t,
() =>
new HttpResponse(body, {
headers: { 'content-type': 'application/json' },
}),
)
const { localBaseUrl } = await startServer(t, {
customMapPath: nonExistentPath,
defaultOnlineStyleUrl: MAPBOX_STYLE_URL,
})
const response = await fetch(`${localBaseUrl}/maps/default/style.json`, {
redirect: 'manual',
})
expect(response.status).toBe(502)
const error: any = await response.json()
expect(error.code).toBe('INVALID_ONLINE_STYLE')
})
}
})

describe('Fallback Map Fallback', () => {
const nonExistentPath = path.join(
os.tmpdir(),
Expand Down
Loading