@mapbox/mapbox-sdk
Advanced tools
Comparing version 0.9.0 to 0.10.0
# Changelog | ||
## 0.10.0 | ||
- **Add:** add new parameters to `Tilesets#listTilesets`: `type`, `limit`, `sortBy`, `start` and `visibility`. | ||
- **Add:** add `Tilesets#tileJSONMetadata` method to retrieve a Tileset TileJSON metadata. | ||
- **Add:** add new `metadata` parameter to `Styles#getStyle` to preserve `mapbox:` specific metadata from the style. | ||
- **Add:** add new Tilesets methods `deleteTileset`, `createTilesetSource`, `getTilesetSource`, `listTilesetSources`, `deleteTilesetSource`, `createTileset`, `publishTileset`, `tilesetStatus`, `tilesetJob`, `listTilesetJobs`, `getTilesetsQueue`, `validateRecipe`, `getRecipe`, `updateRecipe`. | ||
- **Add:** add new `draft` parameter to `Styles#getStyle`, `Styles#deleteStyleIcon` and `Styles#getStyleSprite`, `Styles#getEmbeddableHtml` to work with draft styles. | ||
- **Fix:** Fix responses containing binary data when using `Static#getStaticImage`, `Styles#getStyleSprite` and `Styles#getFontGlyphRange`. | ||
- **Fix:** Fix requests for highres sprites in `Styles#getStyleSprite`. | ||
- **Fix:** set `position.bearing` to `0` if `position.pitch` is defined and `position.bearing` is not in the Static API. | ||
- **Fix:** use `tilesets.getRecipe` in tilesets API example. | ||
## 0.9.0 | ||
@@ -4,0 +16,0 @@ |
@@ -53,2 +53,5 @@ 'use strict'; | ||
* the Node client accepts strings (filepaths) and ReadStreams. | ||
* @property {string} encoding - The encoding of the response. | ||
* @property {string} sendFileAs - The method to send the `file`. Options are | ||
* `data` (x-www-form-urlencoded) or `form` (multipart/form-data). | ||
*/ | ||
@@ -68,2 +71,3 @@ | ||
* @param {Blob|ArrayBuffer|string|ReadStream} [options.file=null] | ||
* @param {string} [options.encoding=utf8] | ||
*/ | ||
@@ -110,2 +114,4 @@ function MapiRequest(client, options) { | ||
this.file = options.file || null; | ||
this.encoding = options.encoding || 'utf8'; | ||
this.sendFileAs = options.sendFileAs || null; | ||
this.headers = headers; | ||
@@ -112,0 +118,0 @@ } |
@@ -6,2 +6,3 @@ 'use strict'; | ||
var got = require('got'); | ||
var FormData = require('form-data'); | ||
var MapiResponse = require('../classes/mapi-response'); | ||
@@ -41,5 +42,17 @@ var MapiError = require('../classes/mapi-error'); | ||
if (typeof request.file === 'string') { | ||
gotOptions.body = fs.createReadStream(request.file); | ||
if (request.sendFileAs && request.sendFileAs === 'form') { | ||
const form = new FormData(); | ||
form.append('file', fs.createReadStream(request.file)); | ||
gotOptions.body = form; | ||
} else { | ||
gotOptions.body = fs.createReadStream(request.file); | ||
} | ||
} else if (request.file && request.file.pipe) { | ||
gotOptions.body = request.file; | ||
if (request.sendFileAs && request.sendFileAs === 'form') { | ||
const form = new FormData(); | ||
form.append('file', request.file); | ||
gotOptions.body = form; | ||
} else { | ||
gotOptions.body = request.file; | ||
} | ||
} else if (typeof request.body === 'string') { | ||
@@ -54,3 +67,3 @@ // matching service needs to send a www-form-urlencoded request | ||
gotStream.setEncoding('utf8'); | ||
gotStream.setEncoding(request.encoding); | ||
@@ -57,0 +70,0 @@ gotStream.on('downloadProgress', function(progress) { |
{ | ||
"name": "@mapbox/mapbox-sdk", | ||
"version": "0.9.0", | ||
"version": "0.10.0", | ||
"description": "JS SDK for accessing Mapbox APIs", | ||
@@ -85,2 +85,3 @@ "main": "index.js", | ||
"eventemitter3": "^3.1.0", | ||
"form-data": "^3.0.0", | ||
"got": "^8.3.2", | ||
@@ -87,0 +88,0 @@ "is-plain-obj": "^1.1.0", |
@@ -139,3 +139,3 @@ # @mapbox/mapbox-sdk | ||
// different on the last page. | ||
if (!res.hasNextPage()) {..} | ||
if (!response.hasNextPage()) {..} | ||
}); | ||
@@ -142,0 +142,0 @@ |
@@ -37,3 +37,4 @@ 'use strict'; | ||
query: {}, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' } | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
@@ -59,6 +60,51 @@ }); | ||
query: {}, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' } | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
}); | ||
test('pitch, no bearing', () => { | ||
service.getStaticImage({ | ||
ownerId: 'mapbox', | ||
styleId: 'streets-v10', | ||
width: 200, | ||
height: 300, | ||
position: { | ||
coordinates: [12, 13], | ||
zoom: 3, | ||
bearing: 0, | ||
pitch: 30 | ||
} | ||
}); | ||
expect(tu.requestConfig(service)).toEqual({ | ||
method: 'GET', | ||
path: '/styles/v1/:ownerId/:styleId/static/12,13,3,0,30/200x300', | ||
query: {}, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
}); | ||
test('bearing, no pitch', () => { | ||
service.getStaticImage({ | ||
ownerId: 'mapbox', | ||
styleId: 'streets-v10', | ||
width: 200, | ||
height: 300, | ||
position: { | ||
coordinates: [12, 13], | ||
zoom: 3, | ||
bearing: 10, | ||
pitch: 0 | ||
} | ||
}); | ||
expect(tu.requestConfig(service)).toEqual({ | ||
method: 'GET', | ||
path: '/styles/v1/:ownerId/:styleId/static/12,13,3,10/200x300', | ||
query: {}, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
}); | ||
test('auto position', () => { | ||
@@ -76,3 +122,4 @@ service.getStaticImage({ | ||
query: {}, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' } | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
@@ -97,3 +144,4 @@ }); | ||
query: {}, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' } | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
@@ -119,3 +167,4 @@ }); | ||
query: { attribution: 'false', logo: 'false' }, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' } | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
@@ -171,3 +220,4 @@ }); | ||
query: {}, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' } | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
@@ -200,3 +250,4 @@ }); | ||
query: { before_layer: 'national_park' }, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' } | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
@@ -236,3 +287,4 @@ }); | ||
query: {}, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' } | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
@@ -282,3 +334,4 @@ }); | ||
query: {}, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' } | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
@@ -313,3 +366,4 @@ }); | ||
query: {}, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' } | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
@@ -355,3 +409,4 @@ expect(polyline.encode).toHaveBeenCalledWith([ | ||
query: {}, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' } | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
@@ -451,3 +506,4 @@ expect(polyline.encode).toHaveBeenCalledWith([ | ||
}, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' } | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
@@ -512,3 +568,4 @@ }); | ||
}, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' } | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
@@ -549,3 +606,4 @@ }); | ||
}, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' } | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
@@ -617,3 +675,4 @@ }); | ||
}, | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' } | ||
params: { ownerId: 'mapbox', styleId: 'streets-v10' }, | ||
encoding: 'binary' | ||
}); | ||
@@ -620,0 +679,0 @@ }); |
@@ -17,5 +17,26 @@ 'use strict'; | ||
method: 'GET', | ||
params: { styleId: 'foo' } | ||
params: { styleId: 'foo' }, | ||
query: {} | ||
}); | ||
}); | ||
test('passes through metadata query param', () => { | ||
styles.getStyle({ styleId: 'foo', metadata: true }); | ||
expect(tu.requestConfig(styles)).toEqual({ | ||
path: '/styles/v1/:ownerId/:styleId', | ||
method: 'GET', | ||
params: { styleId: 'foo' }, | ||
query: { metadata: true } | ||
}); | ||
}); | ||
test('draft works', () => { | ||
styles.getStyle({ styleId: 'foo', draft: true }); | ||
expect(tu.requestConfig(styles)).toEqual({ | ||
path: '/styles/v1/:ownerId/:styleId/draft', | ||
method: 'GET', | ||
params: { styleId: 'foo' }, | ||
query: {} | ||
}); | ||
}); | ||
}); | ||
@@ -160,7 +181,6 @@ | ||
expect(tu.requestConfig(styles)).toEqual({ | ||
path: '/styles/v1/:ownerId/:styleId/:fileName', | ||
path: '/styles/v1/:ownerId/:styleId/sprite.json', | ||
method: 'GET', | ||
params: { | ||
styleId: 'foo', | ||
fileName: 'sprite.json' | ||
styleId: 'foo' | ||
} | ||
@@ -177,7 +197,6 @@ }); | ||
expect(tu.requestConfig(styles)).toEqual({ | ||
path: '/styles/v1/:ownerId/:styleId/:fileName', | ||
path: '/styles/v1/:ownerId/:styleId/sprite@2x.json', | ||
method: 'GET', | ||
params: { | ||
styleId: 'foo', | ||
fileName: 'sprite@2x.json' | ||
styleId: 'foo' | ||
} | ||
@@ -193,8 +212,8 @@ }); | ||
expect(tu.requestConfig(styles)).toEqual({ | ||
path: '/styles/v1/:ownerId/:styleId/:fileName', | ||
path: '/styles/v1/:ownerId/:styleId/sprite.png', | ||
method: 'GET', | ||
params: { | ||
styleId: 'foo', | ||
fileName: 'sprite.png' | ||
} | ||
styleId: 'foo' | ||
}, | ||
encoding: 'binary' | ||
}); | ||
@@ -210,7 +229,21 @@ }); | ||
expect(tu.requestConfig(styles)).toEqual({ | ||
path: '/styles/v1/:ownerId/:styleId/:fileName', | ||
path: '/styles/v1/:ownerId/:styleId/sprite@2x.png', | ||
method: 'GET', | ||
params: { | ||
styleId: 'foo', | ||
fileName: 'sprite@2x.png' | ||
styleId: 'foo' | ||
}, | ||
encoding: 'binary' | ||
}); | ||
}); | ||
test('fetches draft JSON by default', () => { | ||
styles.getStyleSprite({ | ||
styleId: 'foo', | ||
draft: true | ||
}); | ||
expect(tu.requestConfig(styles)).toEqual({ | ||
path: '/styles/v1/:ownerId/:styleId/draft/sprite.json', | ||
method: 'GET', | ||
params: { | ||
styleId: 'foo' | ||
} | ||
@@ -234,3 +267,4 @@ }); | ||
fileName: '0-255.pbf' | ||
} | ||
}, | ||
encoding: 'binary' | ||
}); | ||
@@ -251,3 +285,4 @@ }); | ||
fileName: '0-255.pbf' | ||
} | ||
}, | ||
encoding: 'binary' | ||
}); | ||
@@ -263,7 +298,5 @@ }); | ||
expect(tu.requestConfig(styles)).toEqual({ | ||
path: '/styles/v1/:ownerId/:fileName', | ||
path: '/styles/v1/:ownerId/foo.html', | ||
method: 'GET', | ||
params: { | ||
fileName: 'foo.html' | ||
}, | ||
params: {}, | ||
query: {} | ||
@@ -273,2 +306,15 @@ }); | ||
test('draft works', () => { | ||
styles.getEmbeddableHtml({ | ||
styleId: 'foo', | ||
draft: true | ||
}); | ||
expect(tu.requestConfig(styles)).toEqual({ | ||
path: '/styles/v1/:ownerId/foo/draft.html', | ||
method: 'GET', | ||
params: {}, | ||
query: {} | ||
}); | ||
}); | ||
test('with non-default scrollZoom and title', () => { | ||
@@ -281,7 +327,5 @@ styles.getEmbeddableHtml({ | ||
expect(tu.requestConfig(styles)).toEqual({ | ||
path: '/styles/v1/:ownerId/:fileName', | ||
path: '/styles/v1/:ownerId/foo.html', | ||
method: 'GET', | ||
params: { | ||
fileName: 'foo.html' | ||
}, | ||
params: {}, | ||
query: { zoomwheel: 'false', title: 'true' } | ||
@@ -288,0 +332,0 @@ }); |
@@ -17,14 +17,339 @@ 'use strict'; | ||
method: 'GET', | ||
params: undefined | ||
params: {}, | ||
query: {} | ||
}); | ||
}); | ||
test('works with specified ownerId', () => { | ||
tilesets.listTilesets({ ownerId: 'specialguy' }); | ||
test('works with query params', () => { | ||
tilesets.listTilesets({ | ||
ownerId: 'specialguy', | ||
limit: 250, | ||
type: 'raster' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/:ownerId', | ||
method: 'GET', | ||
params: { ownerId: 'specialguy' } | ||
params: { ownerId: 'specialguy' }, | ||
query: { limit: 250, type: 'raster' } | ||
}); | ||
}); | ||
}); | ||
describe('deleteTileset', () => { | ||
test('works', () => { | ||
tilesets.deleteTileset({ tilesetId: 'hello-world' }); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/:tilesetId', | ||
method: 'DELETE', | ||
params: { tilesetId: 'hello-world' } | ||
}); | ||
}); | ||
}); | ||
describe('tileJSONMetadata', () => { | ||
test('works', () => { | ||
tilesets.tileJSONMetadata({ tilesetId: 'hello-world' }); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/v4/:tilesetId.json', | ||
method: 'GET', | ||
params: { tilesetId: 'hello-world' } | ||
}); | ||
}); | ||
}); | ||
describe('createTilesetSource', () => { | ||
test('works', () => { | ||
tilesets.createTilesetSource({ | ||
id: 'tileset_source_id', | ||
file: 'path/to/file.geojson' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/sources/:ownerId/:id', | ||
method: 'POST', | ||
params: { | ||
id: 'tileset_source_id' | ||
}, | ||
file: 'path/to/file.geojson', | ||
sendFileAs: 'form' | ||
}); | ||
}); | ||
test('works with specified ownerId', () => { | ||
tilesets.createTilesetSource({ | ||
ownerId: 'specialguy', | ||
id: 'tileset_source_id', | ||
file: 'path/to/file.geojson' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/sources/:ownerId/:id', | ||
method: 'POST', | ||
params: { | ||
ownerId: 'specialguy', | ||
id: 'tileset_source_id' | ||
}, | ||
file: 'path/to/file.geojson', | ||
sendFileAs: 'form' | ||
}); | ||
}); | ||
}); | ||
describe('getTilesetSource', () => { | ||
test('works', () => { | ||
tilesets.getTilesetSource({ | ||
id: 'tileset_source_id' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/sources/:ownerId/:id', | ||
method: 'GET', | ||
params: { | ||
id: 'tileset_source_id' | ||
} | ||
}); | ||
}); | ||
test('works with specified ownerId', () => { | ||
tilesets.getTilesetSource({ | ||
ownerId: 'specialguy', | ||
id: 'tileset_source_id' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/sources/:ownerId/:id', | ||
method: 'GET', | ||
params: { | ||
ownerId: 'specialguy', | ||
id: 'tileset_source_id' | ||
} | ||
}); | ||
}); | ||
}); | ||
describe('listTilesetSources', () => { | ||
test('works', () => { | ||
tilesets.listTilesetSources(); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/sources/:ownerId', | ||
method: 'GET', | ||
params: {} | ||
}); | ||
}); | ||
test('works with specified ownerId', () => { | ||
tilesets.listTilesetSources({ | ||
ownerId: 'specialguy' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/sources/:ownerId', | ||
method: 'GET', | ||
params: { | ||
ownerId: 'specialguy' | ||
} | ||
}); | ||
}); | ||
}); | ||
describe('deleteTilesetSource', () => { | ||
test('works', () => { | ||
tilesets.deleteTilesetSource({ | ||
id: 'tileset_source_id' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/sources/:ownerId/:id', | ||
method: 'DELETE', | ||
params: { | ||
id: 'tileset_source_id' | ||
} | ||
}); | ||
}); | ||
test('works with specified ownerId', () => { | ||
tilesets.deleteTilesetSource({ | ||
ownerId: 'specialguy', | ||
id: 'tileset_source_id' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/sources/:ownerId/:id', | ||
method: 'DELETE', | ||
params: { | ||
ownerId: 'specialguy', | ||
id: 'tileset_source_id' | ||
} | ||
}); | ||
}); | ||
}); | ||
describe('createTileset', () => { | ||
test('works', () => { | ||
tilesets.createTileset({ | ||
tilesetId: 'tileset_id', | ||
recipe: { version: 1 }, | ||
name: 'Tileset Name' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/:tilesetId', | ||
method: 'POST', | ||
params: { | ||
tilesetId: 'tileset_id' | ||
}, | ||
body: { | ||
recipe: { version: 1 }, | ||
name: 'Tileset Name' | ||
} | ||
}); | ||
}); | ||
test('works with specified private and description', () => { | ||
tilesets.createTileset({ | ||
tilesetId: 'tileset_id', | ||
recipe: { version: 1 }, | ||
name: 'Tileset Name', | ||
private: false, | ||
description: 'Tileset Description' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/:tilesetId', | ||
method: 'POST', | ||
params: { | ||
tilesetId: 'tileset_id' | ||
}, | ||
body: { | ||
recipe: { version: 1 }, | ||
name: 'Tileset Name', | ||
private: false, | ||
description: 'Tileset Description' | ||
} | ||
}); | ||
}); | ||
}); | ||
describe('publishTileset', () => { | ||
test('works', () => { | ||
tilesets.publishTileset({ | ||
tilesetId: 'tileset_id' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/:tilesetId/publish', | ||
method: 'POST', | ||
params: { | ||
tilesetId: 'tileset_id' | ||
} | ||
}); | ||
}); | ||
}); | ||
describe('tilesetStatus', () => { | ||
test('works', () => { | ||
tilesets.tilesetStatus({ | ||
tilesetId: 'tileset_id' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/:tilesetId/status', | ||
method: 'GET', | ||
params: { | ||
tilesetId: 'tileset_id' | ||
} | ||
}); | ||
}); | ||
}); | ||
describe('tilesetJob', () => { | ||
test('works', () => { | ||
tilesets.tilesetJob({ | ||
tilesetId: 'tileset_id', | ||
jobId: 'job_id' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/:tilesetId/jobs/:jobId', | ||
method: 'GET', | ||
params: { | ||
tilesetId: 'tileset_id', | ||
jobId: 'job_id' | ||
} | ||
}); | ||
}); | ||
}); | ||
describe('listTilesetJobs', () => { | ||
test('works', () => { | ||
tilesets.listTilesetJobs({ | ||
tilesetId: 'tileset_id' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/:tilesetId/jobs', | ||
method: 'GET', | ||
params: { | ||
tilesetId: 'tileset_id' | ||
}, | ||
query: {} | ||
}); | ||
}); | ||
test('works with stage', () => { | ||
tilesets.listTilesetJobs({ | ||
tilesetId: 'tileset_id', | ||
stage: 'success' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/:tilesetId/jobs', | ||
method: 'GET', | ||
params: { | ||
tilesetId: 'tileset_id' | ||
}, | ||
query: { | ||
stage: 'success' | ||
} | ||
}); | ||
}); | ||
}); | ||
describe('getTilesetsQueue', () => { | ||
test('works', () => { | ||
tilesets.getTilesetsQueue(); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/queue', | ||
method: 'PUT' | ||
}); | ||
}); | ||
}); | ||
describe('validateRecipe', () => { | ||
test('works', () => { | ||
tilesets.validateRecipe({ | ||
recipe: { version: 1 } | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/validateRecipe', | ||
method: 'PUT', | ||
body: { version: 1 } | ||
}); | ||
}); | ||
}); | ||
describe('getRecipe', () => { | ||
test('works', () => { | ||
tilesets.getRecipe({ | ||
tilesetId: 'tileset_id' | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/:tilesetId/recipe', | ||
method: 'GET', | ||
params: { | ||
tilesetId: 'tileset_id' | ||
} | ||
}); | ||
}); | ||
}); | ||
describe('updateRecipe', () => { | ||
test('works', () => { | ||
tilesets.updateRecipe({ | ||
tilesetId: 'tileset_id', | ||
recipe: { version: 1 } | ||
}); | ||
expect(tu.requestConfig(tilesets)).toEqual({ | ||
path: '/tilesets/v1/:tilesetId/recipe', | ||
method: 'PATCH', | ||
params: { tilesetId: 'tileset_id' }, | ||
body: { version: 1 } | ||
}); | ||
}); | ||
}); |
@@ -149,4 +149,3 @@ 'use strict'; | ||
* geocodingClient.reverseGeocode({ | ||
* query: [-95.4431142, 33.6875431], | ||
* limit: 2 | ||
* query: [-95.4431142, 33.6875431] | ||
* }) | ||
@@ -153,0 +152,0 @@ * .send() |
@@ -265,3 +265,4 @@ 'use strict'; | ||
params: pick(config, ['ownerId', 'styleId']), | ||
query: query | ||
query: query, | ||
encoding: 'binary' | ||
}); | ||
@@ -274,4 +275,10 @@ }; | ||
return position.coordinates | ||
.concat([position.zoom, position.bearing, position.pitch]) | ||
.filter(Boolean) | ||
.concat([ | ||
position.zoom, | ||
position.pitch && !position.bearing ? 0 : position.bearing, // if pitch is set, but bearing is not, bearing must be 0 | ||
position.pitch === 0 ? undefined : position.pitch | ||
]) | ||
.filter(function(el) { | ||
return el === 0 || el; // filter out undefined and allow 0 values | ||
}) | ||
.join(','); | ||
@@ -278,0 +285,0 @@ } |
@@ -24,2 +24,4 @@ 'use strict'; | ||
* @param {string} [config.ownerId] | ||
* @param {boolean} [config.metadata] - If true, `mapbox:` specific metadata will be preserved | ||
* @param {boolean} [config.draft=false] - If `true` will retrieve the draft style, otherwise will retrieve the published style. | ||
* @return {MapiRequest} | ||
@@ -39,9 +41,17 @@ * | ||
styleId: v.required(v.string), | ||
ownerId: v.string | ||
ownerId: v.string, | ||
metadata: v.boolean, | ||
draft: v.boolean | ||
})(config); | ||
var query = {}; | ||
if (config.metadata) { | ||
query.metadata = config.metadata; | ||
} | ||
return this.client.createRequest({ | ||
method: 'GET', | ||
path: '/styles/v1/:ownerId/:styleId', | ||
params: config | ||
path: '/styles/v1/:ownerId/:styleId' + (config.draft ? '/draft' : ''), | ||
params: pick(config, ['ownerId', 'styleId']), | ||
query: query | ||
}); | ||
@@ -253,2 +263,3 @@ }; | ||
* @param {string} [config.ownerId] | ||
* @param {boolean} [config.draft=false] - If `true` will remove the icon from the draft style, otherwise will remove the icon from the published style. | ||
* @return {MapiRequest} | ||
@@ -270,3 +281,4 @@ * | ||
iconId: v.required(v.string), | ||
ownerId: v.string | ||
ownerId: v.string, | ||
draft: v.boolean | ||
})(config); | ||
@@ -276,4 +288,7 @@ | ||
method: 'DELETE', | ||
path: '/styles/v1/:ownerId/:styleId/sprite/:iconId', | ||
params: config | ||
path: | ||
'/styles/v1/:ownerId/:styleId' + | ||
(config.draft ? '/draft' : '') + | ||
'/sprite/:iconId', | ||
params: pick(config, ['ownerId', 'styleId', 'iconId']) | ||
}); | ||
@@ -293,2 +308,3 @@ }; | ||
* @param {string} [config.ownerId] | ||
* @param {boolean} [config.draft=false] - If `true` will retrieve the draft style sprite, otherwise will retrieve the published style sprite. | ||
* @return {MapiRequest} | ||
@@ -306,2 +322,14 @@ * | ||
* }); | ||
* | ||
* @example | ||
* stylesClient.getStyleSprite({ | ||
* format: 'png', | ||
* styleId: 'foo', | ||
* highRes: true | ||
* }) | ||
* .send() | ||
* .then(response => { | ||
* const sprite = response.body; | ||
* fs.writeFileSync('sprite.png', sprite, 'binary'); | ||
* }); | ||
*/ | ||
@@ -313,15 +341,19 @@ Styles.getStyleSprite = function(config) { | ||
highRes: v.boolean, | ||
ownerId: v.string | ||
ownerId: v.string, | ||
draft: v.boolean | ||
})(config); | ||
var format = config.format || 'json'; | ||
var fileName = 'sprite' + (config.highRes ? '@2x' : '') + '.' + format; | ||
var fileName = '/sprite' + (config.highRes ? '@2x' : '') + '.' + format; | ||
return this.client.createRequest({ | ||
method: 'GET', | ||
path: '/styles/v1/:ownerId/:styleId/:fileName', | ||
params: xtend(pick(config, ['ownerId', 'styleId']), { | ||
fileName: fileName | ||
}) | ||
}); | ||
return this.client.createRequest( | ||
xtend( | ||
{ | ||
method: 'GET', | ||
path: '/styles/v1/:ownerId/:styleId' + (config.draft ? '/draft' : '') + fileName, | ||
params: pick(config, ['ownerId', 'styleId']) | ||
}, | ||
format === 'png' ? { encoding: 'binary' } : {} | ||
) | ||
); | ||
}; | ||
@@ -369,3 +401,4 @@ | ||
fileName: fileName | ||
}) | ||
}), | ||
encoding: 'binary' | ||
}); | ||
@@ -380,8 +413,9 @@ }; | ||
* @param {Object} config | ||
* @param {string} styleId | ||
* @param {boolean} [scrollZoom=true] - If `false`, zooming the map by scrolling will | ||
* @param {string} config.styleId | ||
* @param {boolean} [config.scrollZoom=true] - If `false`, zooming the map by scrolling will | ||
* be disabled. | ||
* @param {boolean} [title=false] - If `true`, the map's title and owner is displayed | ||
* @param {boolean} [config.title=false] - If `true`, the map's title and owner is displayed | ||
* in the upper right corner of the map. | ||
* @param {ownerId} [ownerId] | ||
* @param {string} [config.ownerId] | ||
* @param {boolean} [config.draft=false] - If `true` will retrieve the draft style, otherwise will retrieve the published style. | ||
*/ | ||
@@ -393,6 +427,7 @@ Styles.getEmbeddableHtml = function(config) { | ||
title: v.boolean, | ||
ownerId: v.string | ||
ownerId: v.string, | ||
draft: v.boolean | ||
})(config); | ||
var fileName = config.styleId + '.html'; | ||
var fileName = config.styleId + (config.draft ? '/draft' : '') + '.html'; | ||
var query = {}; | ||
@@ -408,6 +443,4 @@ if (config.scrollZoom !== undefined) { | ||
method: 'GET', | ||
path: '/styles/v1/:ownerId/:fileName', | ||
params: xtend(pick(config, ['ownerId']), { | ||
fileName: fileName | ||
}), | ||
path: '/styles/v1/:ownerId/' + fileName, | ||
params: pick(config, ['ownerId']), | ||
query: query | ||
@@ -414,0 +447,0 @@ }); |
'use strict'; | ||
var v = require('./service-helpers/validator'); | ||
var pick = require('./service-helpers/pick'); | ||
var createServiceFactory = require('./service-helpers/create-service-factory'); | ||
@@ -19,2 +20,7 @@ | ||
* @param {string} [config.ownerId] | ||
* @param {'raster'|'vector'} [config.type] - Filter results by tileset type, either `raster` or `vector`. | ||
* @param {number} [config.limit=100] - The maximum number of tilesets to return, from 1 to 500. | ||
* @param {'created'|'modified'} [config.sortBy] - Sort the listings by their `created` or `modified` timestamps. | ||
* @param {string} [config.start] - The tileset after which to start the listing. | ||
* @param {'public'|'private'} [config.visibility] - Filter results by visibility, either `public` or `private` | ||
* @return {MapiRequest} | ||
@@ -24,2 +30,3 @@ * | ||
* tilesetsClient.listTilesets() | ||
* .send() | ||
* .then(response => { | ||
@@ -37,3 +44,8 @@ * const tilesets = response.body; | ||
v.assertShape({ | ||
ownerId: v.string | ||
ownerId: v.string, | ||
limit: v.range([1, 500]), | ||
sortBy: v.oneOf('created', 'modified'), | ||
start: v.string, | ||
type: v.oneOf('raster', 'vector'), | ||
visibility: v.oneOf('public', 'private') | ||
})(config); | ||
@@ -44,6 +56,471 @@ | ||
path: '/tilesets/v1/:ownerId', | ||
params: config | ||
params: config ? pick(config, ['ownerId']) : {}, | ||
query: config | ||
? pick(config, ['limit', 'sortBy', 'start', 'type', 'visibility']) | ||
: {} | ||
}); | ||
}; | ||
/** | ||
* Delete a tileset | ||
* | ||
* @param {Object} config | ||
* @param {string} config.tilesetId ID of the tileset to be deleted in the form `username.tileset_id`. | ||
* @return {MapiRequest} | ||
* | ||
* @example | ||
* tilesetsClient.deleteTileset({ | ||
* tilesetId: 'username.tileset_id' | ||
* }) | ||
* .send() | ||
* .then(response => { | ||
* const deleted = response.statusCode === 204; | ||
* }); | ||
*/ | ||
Tilesets.deleteTileset = function(config) { | ||
v.assertShape({ | ||
tilesetId: v.required(v.string) | ||
})(config); | ||
return this.client.createRequest({ | ||
method: 'DELETE', | ||
path: '/tilesets/v1/:tilesetId', | ||
params: pick(config, ['tilesetId']) | ||
}); | ||
}; | ||
/** | ||
* Retrieve metadata about a tileset. | ||
* | ||
* @param {Object} [config] | ||
* @param {string} [config.tilesetId] - Unique identifier for the tileset in the format `username.id`. | ||
* | ||
* @return {MapiRequest} | ||
*/ | ||
Tilesets.tileJSONMetadata = function(config) { | ||
v.assertShape({ | ||
tilesetId: v.required(v.string) | ||
})(config); | ||
return this.client.createRequest({ | ||
method: 'GET', | ||
path: '/v4/:tilesetId.json', | ||
params: pick(config, ['tilesetId']) | ||
}); | ||
}; | ||
/** | ||
* Create a tileset source | ||
* | ||
* @param {Object} config | ||
* @param {string} config.id ID of the tileset source to be created. | ||
* @param {UploadableFile} config.file Line-delimeted GeoJSON file. | ||
* @param {string} [config.ownerId] | ||
* @return {MapiRequest} | ||
* | ||
* @example | ||
* tilesetsClient.createTilesetSource({ | ||
* id: 'tileset_source_id', | ||
* // The string filename value works in Node. | ||
* // In the browser, provide a Blob. | ||
* file: 'path/to/file.geojson.ld' | ||
* }) | ||
* .send() | ||
* .then(response => { | ||
* const tilesetSource = response.body; | ||
* }); | ||
*/ | ||
Tilesets.createTilesetSource = function(config) { | ||
v.assertShape({ | ||
id: v.required(v.string), | ||
file: v.required(v.file), | ||
ownerId: v.string | ||
})(config); | ||
return this.client.createRequest({ | ||
method: 'POST', | ||
path: '/tilesets/v1/sources/:ownerId/:id', | ||
params: pick(config, ['ownerId', 'id']), | ||
file: config.file, | ||
sendFileAs: 'form' | ||
}); | ||
}; | ||
/** | ||
* Retrieve a tileset source information | ||
* | ||
* @param {Object} config | ||
* @param {string} config.id ID of the tileset source. | ||
* @param {string} [config.ownerId] | ||
* @return {MapiRequest} | ||
* | ||
* @example | ||
* tilesetsClient.getTilesetSource({ | ||
* id: 'tileset_source_id' | ||
* }) | ||
* .send() | ||
* .then(response => { | ||
* const tilesetSource = response.body; | ||
* }); | ||
*/ | ||
Tilesets.getTilesetSource = function(config) { | ||
v.assertShape({ | ||
id: v.required(v.string), | ||
ownerId: v.string | ||
})(config); | ||
return this.client.createRequest({ | ||
method: 'GET', | ||
path: '/tilesets/v1/sources/:ownerId/:id', | ||
params: pick(config, ['ownerId', 'id']) | ||
}); | ||
}; | ||
/** | ||
* List tileset sources | ||
* | ||
* @param {Object} [config] | ||
* @param {string} [config.ownerId] | ||
* @return {MapiRequest} | ||
* | ||
* @example | ||
* tilesetsClient.listTilesetSources() | ||
* .send() | ||
* .then(response => { | ||
* const tilesetSources = response.body; | ||
* }); | ||
*/ | ||
Tilesets.listTilesetSources = function(config) { | ||
v.assertShape({ | ||
ownerId: v.string | ||
})(config); | ||
return this.client.createRequest({ | ||
method: 'GET', | ||
path: '/tilesets/v1/sources/:ownerId', | ||
params: config ? pick(config, ['ownerId']) : {} | ||
}); | ||
}; | ||
/** | ||
* Delete a tileset source | ||
* | ||
* @param {Object} config | ||
* @param {string} config.id ID of the tileset source to be deleted. | ||
* @param {string} [config.ownerId] | ||
* @return {MapiRequest} | ||
* | ||
* @example | ||
* tilesetsClient.deleteTilesetSource({ | ||
* id: 'tileset_source_id' | ||
* }) | ||
* .send() | ||
* .then(response => { | ||
* const deleted = response.statusCode === 201; | ||
* }); | ||
*/ | ||
Tilesets.deleteTilesetSource = function(config) { | ||
v.assertShape({ | ||
id: v.required(v.string), | ||
ownerId: v.string | ||
})(config); | ||
return this.client.createRequest({ | ||
method: 'DELETE', | ||
path: '/tilesets/v1/sources/:ownerId/:id', | ||
params: pick(config, ['ownerId', 'id']) | ||
}); | ||
}; | ||
/** | ||
* Create a tileset | ||
* | ||
* @param {Object} config | ||
* @param {string} config.tilesetId ID of the tileset to be created in the form `username.tileset_name`. | ||
* @param {Object} config.recipe The [tileset recipe](https://docs.mapbox.com/help/troubleshooting/tileset-recipe-reference/) to use in JSON format. | ||
* @param {string} config.name Name of the tileset. | ||
* @param {boolean} [config.private=true] A private tileset must be used with an access token from your account. | ||
* @param {string} [config.description] Description of the tileset. | ||
* @return {MapiRequest} | ||
* | ||
* @example | ||
* tilesetsClient.createTileset({ | ||
* tilesetId: 'username.tileset_id', | ||
* recipe: { | ||
* version: 1, | ||
* layers: { | ||
* my_new_layer: { | ||
* source: "mapbox://tileset-source/{username}/{id}", | ||
* minzoom: 0, | ||
* maxzoom: 8 | ||
* } | ||
* } | ||
* }, | ||
* name: 'My Tileset' | ||
* }) | ||
* .send() | ||
* .then(response => { | ||
* const message = response.body.message; | ||
* }); | ||
*/ | ||
Tilesets.createTileset = function(config) { | ||
v.assertShape({ | ||
tilesetId: v.required(v.string), | ||
recipe: v.required(v.plainObject), | ||
name: v.required(v.string), | ||
private: v.boolean, | ||
description: v.string | ||
})(config); | ||
return this.client.createRequest({ | ||
method: 'POST', | ||
path: '/tilesets/v1/:tilesetId', | ||
params: pick(config, ['tilesetId']), | ||
body: pick(config, ['recipe', 'name', 'private', 'description']) | ||
}); | ||
}; | ||
/** | ||
* Publish a tileset | ||
* | ||
* @param {Object} config | ||
* @param {string} config.tilesetId ID of the tileset to publish in the form `username.tileset_name`. | ||
* @return {MapiRequest} | ||
* | ||
* @example | ||
* tilesetsClient.publishTileset({ | ||
* tilesetId: 'username.tileset_id' | ||
* }) | ||
* .send() | ||
* .then(response => { | ||
* const tilesetPublishJob = response.body; | ||
* }); | ||
*/ | ||
Tilesets.publishTileset = function(config) { | ||
v.assertShape({ | ||
tilesetId: v.required(v.string) | ||
})(config); | ||
return this.client.createRequest({ | ||
method: 'POST', | ||
path: '/tilesets/v1/:tilesetId/publish', | ||
params: pick(config, ['tilesetId']) | ||
}); | ||
}; | ||
/** | ||
* Retrieve the status of a tileset | ||
* | ||
* @param {Object} config | ||
* @param {string} config.tilesetId ID of the tileset in the form `username.tileset_name`. | ||
* @return {MapiRequest} | ||
* | ||
* @example | ||
* tilesetsClient.tilesetStatus({ | ||
* tilesetId: 'username.tileset_name' | ||
* }) | ||
* .send() | ||
* .then(response => { | ||
* const tilesetStatus = response.body; | ||
* }); | ||
*/ | ||
Tilesets.tilesetStatus = function(config) { | ||
v.assertShape({ | ||
tilesetId: v.required(v.string) | ||
})(config); | ||
return this.client.createRequest({ | ||
method: 'GET', | ||
path: '/tilesets/v1/:tilesetId/status', | ||
params: pick(config, ['tilesetId']) | ||
}); | ||
}; | ||
/** | ||
* Retrieve information about a single tileset job | ||
* | ||
* @param {Object} config | ||
* @param {string} config.tilesetId ID of the tileset in the form `username.tileset_name`. | ||
* @param {string} config.jobId The publish job's ID. | ||
* @return {MapiRequest} | ||
* | ||
* @example | ||
* tilesetsClient.tilesetJob({ | ||
* tilesetId: 'username.tileset_name' | ||
* jobId: 'job_id' | ||
* }) | ||
* .send() | ||
* .then(response => { | ||
* const tilesetJob = response.body; | ||
* }); | ||
*/ | ||
Tilesets.tilesetJob = function(config) { | ||
v.assertShape({ | ||
tilesetId: v.required(v.string), | ||
jobId: v.required(v.string) | ||
})(config); | ||
return this.client.createRequest({ | ||
method: 'GET', | ||
path: '/tilesets/v1/:tilesetId/jobs/:jobId', | ||
params: pick(config, ['tilesetId', 'jobId']) | ||
}); | ||
}; | ||
/** | ||
* List information about all jobs for a tileset | ||
* | ||
* @param {Object} config | ||
* @param {string} config.tilesetId ID of the tileset in the form `username.tileset_name`. | ||
* @param {'processing'|'queued'|'success'|'failed'} [config.stage] | ||
* @return {MapiRequest} | ||
* | ||
* @example | ||
* tilesetsClient.listTilesetJobs({ | ||
* tileset: 'username.tileset_name' | ||
* }) | ||
* .send() | ||
* .then(response => { | ||
* const jobs = response.body; | ||
* }); | ||
*/ | ||
Tilesets.listTilesetJobs = function(config) { | ||
v.assertShape({ | ||
tilesetId: v.required(v.string), | ||
stage: v.oneOf('processing', 'queued', 'success', 'failed') | ||
})(config); | ||
return this.client.createRequest({ | ||
method: 'GET', | ||
path: '/tilesets/v1/:tilesetId/jobs', | ||
params: pick(config, ['tilesetId']), | ||
query: pick(config, ['stage']) | ||
}); | ||
}; | ||
/** | ||
* View Tilesets API global queue | ||
* | ||
* @return {MapiRequest} | ||
* | ||
* @example | ||
* tilesetsClient.getTilesetsQueue() | ||
* .send() | ||
* .then(response => { | ||
* const queue = response.body; | ||
* }); | ||
*/ | ||
Tilesets.getTilesetsQueue = function() { | ||
return this.client.createRequest({ | ||
method: 'PUT', | ||
path: '/tilesets/v1/queue' | ||
}); | ||
}; | ||
/** | ||
* Validate a recipe | ||
* | ||
* @param {Object} config | ||
* @param {Object} config.recipe The [tileset recipe](https://docs.mapbox.com/help/troubleshooting/tileset-recipe-reference/) to validate in JSON format. | ||
* @return {MapiRequest} | ||
* | ||
* @example | ||
* tilesetsClient.validateRecipe({ | ||
* recipe: { | ||
* version: 1, | ||
* layers: { | ||
* my_new_layer: { | ||
* source: "mapbox://tileset-source/{username}/{id}", | ||
* minzoom: 0, | ||
* maxzoom: 8 | ||
* } | ||
* } | ||
* } | ||
* }) | ||
* .send() | ||
* .then(response => { | ||
* const validation = response.body; | ||
* }); | ||
*/ | ||
Tilesets.validateRecipe = function(config) { | ||
v.assertShape({ | ||
recipe: v.required(v.plainObject) | ||
})(config); | ||
return this.client.createRequest({ | ||
method: 'PUT', | ||
path: '/tilesets/v1/validateRecipe', | ||
body: config.recipe | ||
}); | ||
}; | ||
/** | ||
* Retrieve a recipe | ||
* | ||
* @param {Object} config | ||
* @param {string} config.tilesetId ID of the tileset in the form `username.tileset_name`. | ||
* @return {MapiRequest} | ||
* | ||
* @example | ||
* tilesetsClient.getRecipe({ | ||
* tilesetId: 'username.tileset_name' | ||
* }) | ||
* .send() | ||
* .then(response => { | ||
* const recipe = response.body; | ||
* }); | ||
*/ | ||
Tilesets.getRecipe = function(config) { | ||
v.assertShape({ | ||
tilesetId: v.required(v.string) | ||
})(config); | ||
return this.client.createRequest({ | ||
method: 'GET', | ||
path: '/tilesets/v1/:tilesetId/recipe', | ||
params: pick(config, ['tilesetId']) | ||
}); | ||
}; | ||
/** | ||
* Update a tileset recipe | ||
* | ||
* @param {Object} config | ||
* @param {string} config.tilesetId ID of the tileset in the form `username.tileset_name`. | ||
* @param {Object} config.recipe The [tileset recipe](https://docs.mapbox.com/help/troubleshooting/tileset-recipe-reference/) in JSON format. | ||
* @return {MapiRequest} | ||
* | ||
* @example | ||
* tilesetsClient.updateRecipe({ | ||
* tilesetId: 'username.tileset_name', | ||
* recipe: { | ||
* version: 1, | ||
* layers: { | ||
* my_new_layer: { | ||
* source: "mapbox://tileset-source/{username}/{id}", | ||
* minzoom: 0, | ||
* maxzoom: 8 | ||
* } | ||
* } | ||
* } | ||
* }) | ||
* .send() | ||
* .then(response => { | ||
* const updated = response.statusCode === 201; | ||
* }); | ||
*/ | ||
Tilesets.updateRecipe = function(config) { | ||
v.assertShape({ | ||
tilesetId: v.required(v.string), | ||
recipe: v.required(v.plainObject) | ||
})(config); | ||
return this.client.createRequest({ | ||
method: 'PATCH', | ||
path: '/tilesets/v1/:tilesetId/recipe', | ||
params: pick(config, ['tilesetId']), | ||
body: config.recipe | ||
}); | ||
}; | ||
module.exports = createServiceFactory(Tilesets); |
@@ -245,2 +245,22 @@ 'use strict'; | ||
test('@2x is not encoded', () => { | ||
const sendRequest = () => { | ||
return client | ||
.createRequest({ | ||
method: 'GET', | ||
path: '/styles/v1/:ownerId/:styleId/sprite@2x.png', | ||
params: { | ||
ownerId: 'specialguy', | ||
styleId: 'Wolf & Friend' | ||
} | ||
}) | ||
.send(); | ||
}; | ||
return server.captureRequest(sendRequest).then(req => { | ||
expect(req.path).toBe( | ||
`/styles/v1/specialguy/Wolf%20%26%20Friend/sprite@2x.png` | ||
); | ||
}); | ||
}); | ||
test('multiple params', () => { | ||
@@ -247,0 +267,0 @@ const sendRequest = () => { |
@@ -1,1 +0,1 @@ | ||
(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory():typeof define==="function"&&define.amd?define(factory):global.mapboxSdk=factory()})(this,function(){"use strict";function parseParam(param){var parts=param.match(/\s*(.+)\s*=\s*"?([^"]+)"?/);if(!parts)return null;return{key:parts[1],value:parts[2]}}function parseLink(link){var parts=link.match(/<?([^>]*)>(.*)/);if(!parts)return null;var linkUrl=parts[1];var linkParams=parts[2].split(";");var rel=null;var parsedLinkParams=linkParams.reduce(function(result,param){var parsed=parseParam(param);if(!parsed)return result;if(parsed.key==="rel"){if(!rel){rel=parsed.value}return result}result[parsed.key]=parsed.value;return result},{});if(!rel)return null;return{url:linkUrl,rel:rel,params:parsedLinkParams}}function parseLinkHeader(linkHeader){if(!linkHeader)return{};return linkHeader.split(/,\s*</).reduce(function(result,link){var parsed=parseLink(link);if(!parsed)return result;var splitRel=parsed.rel.split(/\s+/);splitRel.forEach(function(rel){if(!result[rel]){result[rel]={url:parsed.url,params:parsed.params}}});return result},{})}var parseLinkHeader_1=parseLinkHeader;function MapiResponse(request,responseData){this.request=request;this.headers=responseData.headers;this.rawBody=responseData.body;this.statusCode=responseData.statusCode;try{this.body=JSON.parse(responseData.body||"{}")}catch(parseError){this.body=responseData.body}this.links=parseLinkHeader_1(this.headers.link)}MapiResponse.prototype.hasNextPage=function hasNextPage(){return!!this.links.next};MapiResponse.prototype.nextPage=function nextPage(){if(!this.hasNextPage())return null;return this.request._extend({path:this.links.next.url})};var mapiResponse=MapiResponse;var constants={API_ORIGIN:"https://api.mapbox.com",EVENT_PROGRESS_DOWNLOAD:"downloadProgress",EVENT_PROGRESS_UPLOAD:"uploadProgress",EVENT_ERROR:"error",EVENT_RESPONSE:"response",ERROR_HTTP:"HttpError",ERROR_REQUEST_ABORTED:"RequestAbortedError"};function MapiError(options){var errorType=options.type||constants.ERROR_HTTP;var body;if(options.body){try{body=JSON.parse(options.body)}catch(e){body=options.body}}else{body=null}var message=options.message||null;if(!message){if(typeof body==="string"){message=body}else if(body&&typeof body.message==="string"){message=body.message}else if(errorType===constants.ERROR_REQUEST_ABORTED){message="Request aborted"}}this.message=message;this.type=errorType;this.statusCode=options.statusCode||null;this.request=options.request;this.body=body}var mapiError=MapiError;function parseSingleHeader(raw){var boundary=raw.indexOf(":");var name=raw.substring(0,boundary).trim().toLowerCase();var value=raw.substring(boundary+1).trim();return{name:name,value:value}}function parseHeaders(raw){var headers={};if(!raw){return headers}raw.trim().split(/[\r|\n]+/).forEach(function(rawHeader){var parsed=parseSingleHeader(rawHeader);headers[parsed.name]=parsed.value});return headers}var parseHeaders_1=parseHeaders;var requestsUnderway={};function browserAbort(request){var xhr=requestsUnderway[request.id];if(!xhr)return;xhr.abort();delete requestsUnderway[request.id]}function createResponse(request,xhr){return new mapiResponse(request,{body:xhr.response,headers:parseHeaders_1(xhr.getAllResponseHeaders()),statusCode:xhr.status})}function normalizeBrowserProgressEvent(event){var total=event.total;var transferred=event.loaded;var percent=100*transferred/total;return{total:total,transferred:transferred,percent:percent}}function sendRequestXhr(request,xhr){return new Promise(function(resolve,reject){xhr.onprogress=function(event){request.emitter.emit(constants.EVENT_PROGRESS_DOWNLOAD,normalizeBrowserProgressEvent(event))};var file=request.file;if(file){xhr.upload.onprogress=function(event){request.emitter.emit(constants.EVENT_PROGRESS_UPLOAD,normalizeBrowserProgressEvent(event))}}xhr.onerror=function(error){reject(error)};xhr.onabort=function(){var mapiError$$1=new mapiError({request:request,type:constants.ERROR_REQUEST_ABORTED});reject(mapiError$$1)};xhr.onload=function(){delete requestsUnderway[request.id];if(xhr.status<200||xhr.status>=400){var mapiError$$1=new mapiError({request:request,body:xhr.response,statusCode:xhr.status});reject(mapiError$$1);return}resolve(xhr)};var body=request.body;if(typeof body==="string"){xhr.send(body)}else if(body){xhr.send(JSON.stringify(body))}else if(file){xhr.send(file)}else{xhr.send()}requestsUnderway[request.id]=xhr}).then(function(xhr){return createResponse(request,xhr)})}function createRequestXhr(request,accessToken){var url=request.url(accessToken);var xhr=new window.XMLHttpRequest;xhr.open(request.method,url);Object.keys(request.headers).forEach(function(key){xhr.setRequestHeader(key,request.headers[key])});return xhr}function browserSend(request){return Promise.resolve().then(function(){var xhr=createRequestXhr(request,request.client.accessToken);return sendRequestXhr(request,xhr)})}var browserLayer={browserAbort:browserAbort,sendRequestXhr:sendRequestXhr,browserSend:browserSend,createRequestXhr:createRequestXhr};var commonjsGlobal=typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};function createCommonjsModule(fn,module){return module={exports:{}},fn(module,module.exports),module.exports}var base64=createCommonjsModule(function(module,exports){(function(root){var freeExports=exports;var freeModule=module&&module.exports==freeExports&&module;var freeGlobal=typeof commonjsGlobal=="object"&&commonjsGlobal;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var InvalidCharacterError=function(message){this.message=message};InvalidCharacterError.prototype=new Error;InvalidCharacterError.prototype.name="InvalidCharacterError";var error=function(message){throw new InvalidCharacterError(message)};var TABLE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var REGEX_SPACE_CHARACTERS=/[\t\n\f\r ]/g;var decode=function(input){input=String(input).replace(REGEX_SPACE_CHARACTERS,"");var length=input.length;if(length%4==0){input=input.replace(/==?$/,"");length=input.length}if(length%4==1||/[^+a-zA-Z0-9/]/.test(input)){error("Invalid character: the string to be decoded is not correctly encoded.")}var bitCounter=0;var bitStorage;var buffer;var output="";var position=-1;while(++position<length){buffer=TABLE.indexOf(input.charAt(position));bitStorage=bitCounter%4?bitStorage*64+buffer:buffer;if(bitCounter++%4){output+=String.fromCharCode(255&bitStorage>>(-2*bitCounter&6))}}return output};var encode=function(input){input=String(input);if(/[^\0-\xFF]/.test(input)){error("The string to be encoded contains characters outside of the "+"Latin1 range.")}var padding=input.length%3;var output="";var position=-1;var a;var b;var c;var buffer;var length=input.length-padding;while(++position<length){a=input.charCodeAt(position)<<16;b=input.charCodeAt(++position)<<8;c=input.charCodeAt(++position);buffer=a+b+c;output+=TABLE.charAt(buffer>>18&63)+TABLE.charAt(buffer>>12&63)+TABLE.charAt(buffer>>6&63)+TABLE.charAt(buffer&63)}if(padding==2){a=input.charCodeAt(position)<<8;b=input.charCodeAt(++position);buffer=a+b;output+=TABLE.charAt(buffer>>10)+TABLE.charAt(buffer>>4&63)+TABLE.charAt(buffer<<2&63)+"="}else if(padding==1){buffer=input.charCodeAt(position);output+=TABLE.charAt(buffer>>2)+TABLE.charAt(buffer<<4&63)+"=="}return output};var base64={encode:encode,decode:decode,version:"0.1.0"};if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=base64}else{for(var key in base64){base64.hasOwnProperty(key)&&(freeExports[key]=base64[key])}}}else{root.base64=base64}})(commonjsGlobal)});var tokenCache={};function parseToken(token){if(tokenCache[token]){return tokenCache[token]}var parts=token.split(".");var usage=parts[0];var rawPayload=parts[1];if(!rawPayload){throw new Error("Invalid token")}var parsedPayload=parsePaylod(rawPayload);var result={usage:usage,user:parsedPayload.u};if(has(parsedPayload,"a"))result.authorization=parsedPayload.a;if(has(parsedPayload,"exp"))result.expires=parsedPayload.exp*1e3;if(has(parsedPayload,"iat"))result.created=parsedPayload.iat*1e3;if(has(parsedPayload,"scopes"))result.scopes=parsedPayload.scopes;if(has(parsedPayload,"client"))result.client=parsedPayload.client;if(has(parsedPayload,"ll"))result.lastLogin=parsedPayload.ll;if(has(parsedPayload,"iu"))result.impersonator=parsedPayload.iu;tokenCache[token]=result;return result}function parsePaylod(rawPayload){try{return JSON.parse(base64.decode(rawPayload))}catch(parseError){throw new Error("Invalid token")}}function has(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)}var parseMapboxToken=parseToken;var immutable=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(){var target={};for(var i=0;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(hasOwnProperty.call(source,key)){target[key]=source[key]}}}return target}var eventemitter3=createCommonjsModule(function(module){var has=Object.prototype.hasOwnProperty,prefix="~";function Events(){}if(Object.create){Events.prototype=Object.create(null);if(!(new Events).__proto__)prefix=false}function EE(fn,context,once){this.fn=fn;this.context=context;this.once=once||false}function addListener(emitter,event,fn,context,once){if(typeof fn!=="function"){throw new TypeError("The listener must be a function")}var listener=new EE(fn,context||emitter,once),evt=prefix?prefix+event:event;if(!emitter._events[evt])emitter._events[evt]=listener,emitter._eventsCount++;else if(!emitter._events[evt].fn)emitter._events[evt].push(listener);else emitter._events[evt]=[emitter._events[evt],listener];return emitter}function clearEvent(emitter,evt){if(--emitter._eventsCount===0)emitter._events=new Events;else delete emitter._events[evt]}function EventEmitter(){this._events=new Events;this._eventsCount=0}EventEmitter.prototype.eventNames=function eventNames(){var names=[],events,name;if(this._eventsCount===0)return names;for(name in events=this._events){if(has.call(events,name))names.push(prefix?name.slice(1):name)}if(Object.getOwnPropertySymbols){return names.concat(Object.getOwnPropertySymbols(events))}return names};EventEmitter.prototype.listeners=function listeners(event){var evt=prefix?prefix+event:event,handlers=this._events[evt];if(!handlers)return[];if(handlers.fn)return[handlers.fn];for(var i=0,l=handlers.length,ee=new Array(l);i<l;i++){ee[i]=handlers[i].fn}return ee};EventEmitter.prototype.listenerCount=function listenerCount(event){var evt=prefix?prefix+event:event,listeners=this._events[evt];if(!listeners)return 0;if(listeners.fn)return 1;return listeners.length};EventEmitter.prototype.emit=function emit(event,a1,a2,a3,a4,a5){var evt=prefix?prefix+event:event;if(!this._events[evt])return false;var listeners=this._events[evt],len=arguments.length,args,i;if(listeners.fn){if(listeners.once)this.removeListener(event,listeners.fn,undefined,true);switch(len){case 1:return listeners.fn.call(listeners.context),true;case 2:return listeners.fn.call(listeners.context,a1),true;case 3:return listeners.fn.call(listeners.context,a1,a2),true;case 4:return listeners.fn.call(listeners.context,a1,a2,a3),true;case 5:return listeners.fn.call(listeners.context,a1,a2,a3,a4),true;case 6:return listeners.fn.call(listeners.context,a1,a2,a3,a4,a5),true}for(i=1,args=new Array(len-1);i<len;i++){args[i-1]=arguments[i]}listeners.fn.apply(listeners.context,args)}else{var length=listeners.length,j;for(i=0;i<length;i++){if(listeners[i].once)this.removeListener(event,listeners[i].fn,undefined,true);switch(len){case 1:listeners[i].fn.call(listeners[i].context);break;case 2:listeners[i].fn.call(listeners[i].context,a1);break;case 3:listeners[i].fn.call(listeners[i].context,a1,a2);break;case 4:listeners[i].fn.call(listeners[i].context,a1,a2,a3);break;default:if(!args)for(j=1,args=new Array(len-1);j<len;j++){args[j-1]=arguments[j]}listeners[i].fn.apply(listeners[i].context,args)}}}return true};EventEmitter.prototype.on=function on(event,fn,context){return addListener(this,event,fn,context,false)};EventEmitter.prototype.once=function once(event,fn,context){return addListener(this,event,fn,context,true)};EventEmitter.prototype.removeListener=function removeListener(event,fn,context,once){var evt=prefix?prefix+event:event;if(!this._events[evt])return this;if(!fn){clearEvent(this,evt);return this}var listeners=this._events[evt];if(listeners.fn){if(listeners.fn===fn&&(!once||listeners.once)&&(!context||listeners.context===context)){clearEvent(this,evt)}}else{for(var i=0,events=[],length=listeners.length;i<length;i++){if(listeners[i].fn!==fn||once&&!listeners[i].once||context&&listeners[i].context!==context){events.push(listeners[i])}}if(events.length)this._events[evt]=events.length===1?events[0]:events;else clearEvent(this,evt)}return this};EventEmitter.prototype.removeAllListeners=function removeAllListeners(event){var evt;if(event){evt=prefix?prefix+event:event;if(this._events[evt])clearEvent(this,evt)}else{this._events=new Events;this._eventsCount=0}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prefixed=prefix;EventEmitter.EventEmitter=EventEmitter;{module.exports=EventEmitter}});function encodeArray(arrayValue){return arrayValue.map(encodeURIComponent).join(",")}function encodeValue(value){if(Array.isArray(value)){return encodeArray(value)}return encodeURIComponent(String(value))}function appendQueryParam(url,key,value){if(value===false||value===null){return url}var punctuation=/\?/.test(url)?"&":"?";var query=encodeURIComponent(key);if(value!==undefined&&value!==""&&value!==true){query+="="+encodeValue(value)}return""+url+punctuation+query}function appendQueryObject(url,queryObject){if(!queryObject){return url}var result=url;Object.keys(queryObject).forEach(function(key){var value=queryObject[key];if(value===undefined){return}if(Array.isArray(value)){value=value.filter(function(v){return!!v}).join(",")}result=appendQueryParam(result,key,value)});return result}function prependOrigin(url,origin){if(!origin){return url}if(url.slice(0,4)==="http"){return url}var delimiter=url[0]==="/"?"":"/";return""+origin.replace(/\/$/,"")+delimiter+url}function interpolateRouteParams(route,params){if(!params){return route}return route.replace(/\/:([a-zA-Z0-9]+)/g,function(_,paramId){var value=params[paramId];if(value===undefined){throw new Error("Unspecified route parameter "+paramId)}var preppedValue=encodeValue(value);return"/"+preppedValue})}var urlUtils={appendQueryObject:appendQueryObject,appendQueryParam:appendQueryParam,prependOrigin:prependOrigin,interpolateRouteParams:interpolateRouteParams};var requestId=1;function MapiRequest(client,options){if(!client){throw new Error("MapiRequest requires a client")}if(!options||!options.path||!options.method){throw new Error("MapiRequest requires an options object with path and method properties")}var defaultHeaders={};if(options.body){defaultHeaders["content-type"]="application/json"}var headersWithDefaults=immutable(defaultHeaders,options.headers);var headers=Object.keys(headersWithDefaults).reduce(function(memo,name){memo[name.toLowerCase()]=headersWithDefaults[name];return memo},{});this.id=requestId++;this._options=options;this.emitter=new eventemitter3;this.client=client;this.response=null;this.error=null;this.sent=false;this.aborted=false;this.path=options.path;this.method=options.method;this.origin=options.origin||client.origin;this.query=options.query||{};this.params=options.params||{};this.body=options.body||null;this.file=options.file||null;this.headers=headers}MapiRequest.prototype.url=function url(accessToken){var url=urlUtils.prependOrigin(this.path,this.origin);url=urlUtils.appendQueryObject(url,this.query);var routeParams=this.params;var actualAccessToken=accessToken==null?this.client.accessToken:accessToken;if(actualAccessToken){url=urlUtils.appendQueryParam(url,"access_token",actualAccessToken);var accessTokenOwnerId=parseMapboxToken(actualAccessToken).user;routeParams=immutable({ownerId:accessTokenOwnerId},routeParams)}url=urlUtils.interpolateRouteParams(url,routeParams);return url};MapiRequest.prototype.send=function send(){var self=this;if(self.sent){throw new Error("This request has already been sent. Check the response and error properties. Create a new request with clone().")}self.sent=true;return self.client.sendRequest(self).then(function(response){self.response=response;self.emitter.emit(constants.EVENT_RESPONSE,response);return response},function(error){self.error=error;self.emitter.emit(constants.EVENT_ERROR,error);throw error})};MapiRequest.prototype.abort=function abort(){if(this._nextPageRequest){this._nextPageRequest.abort();delete this._nextPageRequest}if(this.response||this.error||this.aborted)return;this.aborted=true;this.client.abortRequest(this)};MapiRequest.prototype.eachPage=function eachPage(callback){var self=this;function handleResponse(response){function getNextPage(){delete self._nextPageRequest;var nextPageRequest=response.nextPage();if(nextPageRequest){self._nextPageRequest=nextPageRequest;getPage(nextPageRequest)}}callback(null,response,getNextPage)}function handleError(error){callback(error,null,function(){})}function getPage(request){request.send().then(handleResponse,handleError)}getPage(this)};MapiRequest.prototype.clone=function clone(){return this._extend()};MapiRequest.prototype._extend=function _extend(options){var extendedOptions=immutable(this._options,options);return new MapiRequest(this.client,extendedOptions)};var mapiRequest=MapiRequest;function MapiClient(options){if(!options||!options.accessToken){throw new Error("Cannot create a client without an access token")}parseMapboxToken(options.accessToken);this.accessToken=options.accessToken;this.origin=options.origin||constants.API_ORIGIN}MapiClient.prototype.createRequest=function createRequest(requestOptions){return new mapiRequest(this,requestOptions)};var mapiClient=MapiClient;function BrowserClient(options){mapiClient.call(this,options)}BrowserClient.prototype=Object.create(mapiClient.prototype);BrowserClient.prototype.constructor=BrowserClient;BrowserClient.prototype.sendRequest=browserLayer.browserSend;BrowserClient.prototype.abortRequest=browserLayer.browserAbort;function createBrowserClient(options){return new BrowserClient(options)}var browserClient=createBrowserClient;var toString=Object.prototype.toString;var isPlainObj=function(x){var prototype;return toString.call(x)==="[object Object]"&&(prototype=Object.getPrototypeOf(x),prototype===null||prototype===Object.getPrototypeOf({}))};var DEFAULT_ERROR_PATH="value";var NEWLINE_INDENT="\n ";var v={};v.assert=function(rootValidator,options){options=options||{};return function(value){var message=validate(rootValidator,value);if(!message){return}var errorMessage=processMessage(message,options);if(options.apiName){errorMessage=options.apiName+": "+errorMessage}throw new Error(errorMessage)}};v.shape=function shape(validatorObj){var validators=objectEntries(validatorObj);return function shapeValidator(value){var validationResult=validate(v.plainObject,value);if(validationResult){return validationResult}var key,validator;var errorMessages=[];for(var i=0;i<validators.length;i++){key=validators[i].key;validator=validators[i].value;validationResult=validate(validator,value[key]);if(validationResult){errorMessages.push([key].concat(validationResult))}}if(errorMessages.length<2){return errorMessages[0]}return function(options){errorMessages=errorMessages.map(function(message){var key=message[0];var renderedMessage=processMessage(message,options).split("\n").join(NEWLINE_INDENT);return"- "+key+": "+renderedMessage});var objectId=options.path.join(".");var ofPhrase=objectId===DEFAULT_ERROR_PATH?"":" of "+objectId;return"The following properties"+ofPhrase+" have invalid values:"+NEWLINE_INDENT+errorMessages.join(NEWLINE_INDENT)}}};v.strictShape=function strictShape(validatorObj){var shapeValidator=v.shape(validatorObj);return function strictShapeValidator(value){var shapeResult=shapeValidator(value);if(shapeResult){return shapeResult}var invalidKeys=Object.keys(value).reduce(function(memo,valueKey){if(validatorObj[valueKey]===undefined){memo.push(valueKey)}return memo},[]);if(invalidKeys.length!==0){return function(){return"The following keys are invalid: "+invalidKeys.join(", ")}}}};v.arrayOf=function arrayOf(validator){return createArrayValidator(validator)};v.tuple=function tuple(){var validators=Array.isArray(arguments[0])?arguments[0]:Array.prototype.slice.call(arguments);return createArrayValidator(validators)};function createArrayValidator(validators){var validatingTuple=Array.isArray(validators);var getValidator=function(index){if(validatingTuple){return validators[index]}return validators};return function arrayValidator(value){var validationResult=validate(v.plainArray,value);if(validationResult){return validationResult}if(validatingTuple&&value.length!==validators.length){return"an array with "+validators.length+" items"}for(var i=0;i<value.length;i++){validationResult=validate(getValidator(i),value[i]);if(validationResult){return[i].concat(validationResult)}}}}v.required=function required(validator){function requiredValidator(value){if(value==null){return function(options){return formatErrorMessage(options,isArrayCulprit(options.path)?"cannot be undefined/null.":"is required.")}}return validator.apply(this,arguments)}requiredValidator.__required=true;return requiredValidator};v.oneOfType=function oneOfType(){var validators=Array.isArray(arguments[0])?arguments[0]:Array.prototype.slice.call(arguments);return function oneOfTypeValidator(value){var messages=validators.map(function(validator){return validate(validator,value)}).filter(Boolean);if(messages.length!==validators.length){return}if(messages.every(function(message){return message.length===1&&typeof message[0]==="string"})){return orList(messages.map(function(m){return m[0]}))}return messages.reduce(function(max,arr){return arr.length>max.length?arr:max})}};v.equal=function equal(compareWith){return function equalValidator(value){if(value!==compareWith){return JSON.stringify(compareWith)}}};v.oneOf=function oneOf(){var options=Array.isArray(arguments[0])?arguments[0]:Array.prototype.slice.call(arguments);var validators=options.map(function(value){return v.equal(value)});return v.oneOfType.apply(this,validators)};v.range=function range(compareWith){var min=compareWith[0];var max=compareWith[1];return function rangeValidator(value){var validationResult=validate(v.number,value);if(validationResult||value<min||value>max){return"number between "+min+" & "+max+" (inclusive)"}}};v.any=function any(){return};v.boolean=function boolean(value){if(typeof value!=="boolean"){return"boolean"}};v.number=function number(value){if(typeof value!=="number"){return"number"}};v.plainArray=function plainArray(value){if(!Array.isArray(value)){return"array"}};v.plainObject=function plainObject(value){if(!isPlainObj(value)){return"object"}};v.string=function string(value){if(typeof value!=="string"){return"string"}};v.func=function func(value){if(typeof value!=="function"){return"function"}};function validate(validator,value){if(value==null&&!validator.hasOwnProperty("__required")){return}var result=validator(value);if(result){return Array.isArray(result)?result:[result]}}function processMessage(message,options){var len=message.length;var result=message[len-1];var path=message.slice(0,len-1);if(path.length===0){path=[DEFAULT_ERROR_PATH]}options=immutable(options,{path:path});return typeof result==="function"?result(options):formatErrorMessage(options,prettifyResult(result))}function orList(list){if(list.length<2){return list[0]}if(list.length===2){return list.join(" or ")}return list.slice(0,-1).join(", ")+", or "+list.slice(-1)}function prettifyResult(result){return"must be "+addArticle(result)+"."}function addArticle(nounPhrase){if(/^an? /.test(nounPhrase)){return nounPhrase}if(/^[aeiou]/i.test(nounPhrase)){return"an "+nounPhrase}if(/^[a-z]/i.test(nounPhrase)){return"a "+nounPhrase}return nounPhrase}function formatErrorMessage(options,prettyResult){var arrayCulprit=isArrayCulprit(options.path);var output=options.path.join(".")+" "+prettyResult;var prepend=arrayCulprit?"Item at position ":"";return prepend+output}function isArrayCulprit(path){return typeof path[path.length-1]=="number"||typeof path[0]=="number"}function objectEntries(obj){return Object.keys(obj||{}).map(function(key){return{key:key,value:obj[key]}})}v.validate=validate;v.processMessage=processMessage;var lib=v;function file(value){if(typeof window!=="undefined"){if(value instanceof commonjsGlobal.Blob||value instanceof commonjsGlobal.ArrayBuffer){return}return"Blob or ArrayBuffer"}if(typeof value==="string"||value.pipe!==undefined){return}return"Filename or Readable stream"}function assertShape(validatorObj,apiName){return lib.assert(lib.strictShape(validatorObj),apiName)}function date(value){var msg="date";if(typeof value==="boolean"){return msg}try{var date=new Date(value);if(date.getTime&&isNaN(date.getTime())){return msg}}catch(e){return msg}}function coordinates(value){return lib.tuple(lib.number,lib.number)(value)}var validator=immutable(lib,{file:file,date:date,coordinates:coordinates,assertShape:assertShape});function pick(source,keys){var filter=function(key,val){return keys.indexOf(key)!==-1&&val!==undefined};if(typeof keys==="function"){filter=keys}return Object.keys(source).filter(function(key){return filter(key,source[key])}).reduce(function(result,key){result[key]=source[key];return result},{})}var pick_1=pick;function createServiceFactory(ServicePrototype){return function(clientOrConfig){var client;if(mapiClient.prototype.isPrototypeOf(clientOrConfig)){client=clientOrConfig}else{client=browserClient(clientOrConfig)}var service=Object.create(ServicePrototype);service.client=client;return service}}var createServiceFactory_1=createServiceFactory;var Datasets={};Datasets.listDatasets=function(){return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId"})};Datasets.createDataset=function(config){validator.assertShape({name:validator.string,description:validator.string})(config);return this.client.createRequest({method:"POST",path:"/datasets/v1/:ownerId",body:config})};Datasets.getMetadata=function(config){validator.assertShape({datasetId:validator.required(validator.string),description:validator.string})(config);return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId/:datasetId",params:config})};Datasets.updateMetadata=function(config){validator.assertShape({datasetId:validator.required(validator.string),name:validator.string,description:validator.string})(config);return this.client.createRequest({method:"PATCH",path:"/datasets/v1/:ownerId/:datasetId",params:pick_1(config,["datasetId"]),body:pick_1(config,["name","description"])})};Datasets.deleteDataset=function(config){validator.assertShape({datasetId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/datasets/v1/:ownerId/:datasetId",params:config})};Datasets.listFeatures=function(config){validator.assertShape({datasetId:validator.required(validator.string),limit:validator.number,start:validator.string})(config);return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId/:datasetId/features",params:pick_1(config,["datasetId"]),query:pick_1(config,["limit","start"])})};Datasets.putFeature=function(config){validator.assertShape({datasetId:validator.required(validator.string),featureId:validator.required(validator.string),feature:validator.required(validator.plainObject)})(config);if(config.feature.id!==undefined&&config.feature.id!==config.featureId){throw new Error("featureId must match the id property of the feature")}return this.client.createRequest({method:"PUT",path:"/datasets/v1/:ownerId/:datasetId/features/:featureId",params:pick_1(config,["datasetId","featureId"]),body:config.feature})};Datasets.getFeature=function(config){validator.assertShape({datasetId:validator.required(validator.string),featureId:validator.required(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId/:datasetId/features/:featureId",params:config})};Datasets.deleteFeature=function(config){validator.assertShape({datasetId:validator.required(validator.string),featureId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/datasets/v1/:ownerId/:datasetId/features/:featureId",params:config})};var datasets=createServiceFactory_1(Datasets);function objectClean(obj){return pick_1(obj,function(_,val){return val!=null})}var objectClean_1=objectClean;function objectMap(obj,cb){return Object.keys(obj).reduce(function(result,key){result[key]=cb(key,obj[key]);return result},{})}var objectMap_1=objectMap;function stringifyBoolean(obj){return objectMap_1(obj,function(_,value){return typeof value==="boolean"?JSON.stringify(value):value})}var stringifyBooleans=stringifyBoolean;var Directions={};Directions.getDirections=function(config){validator.assertShape({profile:validator.oneOf("driving-traffic","driving","walking","cycling"),waypoints:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb"),bearing:validator.arrayOf(validator.range([0,360])),radius:validator.oneOfType(validator.number,validator.equal("unlimited")),waypointName:validator.string}))),alternatives:validator.boolean,annotations:validator.arrayOf(validator.oneOf("duration","distance","speed","congestion")),bannerInstructions:validator.boolean,continueStraight:validator.boolean,exclude:validator.string,geometries:validator.string,language:validator.string,overview:validator.string,roundaboutExits:validator.boolean,steps:validator.boolean,voiceInstructions:validator.boolean,voiceUnits:validator.string})(config);config.profile=config.profile||"driving";var path={coordinates:[],approach:[],bearing:[],radius:[],waypointName:[]};var waypointCount=config.waypoints.length;if(waypointCount<2||waypointCount>25){throw new Error("waypoints must include between 2 and 25 DirectionsWaypoints")}config.waypoints.forEach(function(waypoint){path.coordinates.push(waypoint.coordinates[0]+","+waypoint.coordinates[1]);["bearing"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){waypoint[prop]=waypoint[prop].join(",")}});["approach","bearing","radius","waypointName"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){path[prop].push(waypoint[prop])}else{path[prop].push("")}})});["approach","bearing","radius","waypointName"].forEach(function(prop){if(path[prop].every(function(char){return char===""})){delete path[prop]}else{path[prop]=path[prop].join(";")}});var query=stringifyBooleans({alternatives:config.alternatives,annotations:config.annotations,banner_instructions:config.bannerInstructions,continue_straight:config.continueStraight,exclude:config.exclude,geometries:config.geometries,language:config.language,overview:config.overview,roundabout_exits:config.roundaboutExits,steps:config.steps,voice_instructions:config.voiceInstructions,voice_units:config.voiceUnits,approaches:path.approach,bearings:path.bearing,radiuses:path.radius,waypoint_names:path.waypointName});return this.client.createRequest({method:"GET",path:"/directions/v5/mapbox/:profile/:coordinates",params:{profile:config.profile,coordinates:path.coordinates.join(";")},query:objectClean_1(query)})};var directions=createServiceFactory_1(Directions);var Geocoding={};var featureTypes=["country","region","postcode","district","place","locality","neighborhood","address","poi","poi.landmark"];Geocoding.forwardGeocode=function(config){validator.assertShape({query:validator.required(validator.string),mode:validator.oneOf("mapbox.places","mapbox.places-permanent"),countries:validator.arrayOf(validator.string),proximity:validator.coordinates,types:validator.arrayOf(validator.oneOf(featureTypes)),autocomplete:validator.boolean,bbox:validator.arrayOf(validator.number),limit:validator.number,language:validator.arrayOf(validator.string)})(config);config.mode=config.mode||"mapbox.places";var query=stringifyBooleans(immutable({country:config.countries},pick_1(config,["proximity","types","autocomplete","bbox","limit","language"])));return this.client.createRequest({method:"GET",path:"/geocoding/v5/:mode/:query.json",params:pick_1(config,["mode","query"]),query:query})};Geocoding.reverseGeocode=function(config){validator.assertShape({query:validator.required(validator.coordinates),mode:validator.oneOf("mapbox.places","mapbox.places-permanent"),countries:validator.arrayOf(validator.string),types:validator.arrayOf(validator.oneOf(featureTypes)),bbox:validator.arrayOf(validator.number),limit:validator.number,language:validator.arrayOf(validator.string),reverseMode:validator.oneOf("distance","score")})(config);config.mode=config.mode||"mapbox.places";var query=stringifyBooleans(immutable({country:config.countries},pick_1(config,["country","types","bbox","limit","language","reverseMode"])));return this.client.createRequest({method:"GET",path:"/geocoding/v5/:mode/:query.json",params:pick_1(config,["mode","query"]),query:query})};var geocoding=createServiceFactory_1(Geocoding);var MapMatching={};MapMatching.getMatch=function(config){validator.assertShape({points:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb"),radius:validator.range([0,50]),isWaypoint:validator.boolean,waypointName:validator.string,timestamp:validator.date}))),profile:validator.oneOf("driving-traffic","driving","walking","cycling"),annotations:validator.arrayOf(validator.oneOf("duration","distance","speed")),geometries:validator.oneOf("geojson","polyline","polyline6"),language:validator.string,overview:validator.oneOf("full","simplified","false"),steps:validator.boolean,tidy:validator.boolean})(config);var pointCount=config.points.length;if(pointCount<2||pointCount>100){throw new Error("points must include between 2 and 100 MapMatchingPoints")}config.profile=config.profile||"driving";var path={coordinates:[],approach:[],radius:[],isWaypoint:[],waypointName:[],timestamp:[]};config.points.forEach(function(obj){path.coordinates.push(obj.coordinates[0]+","+obj.coordinates[1]);if(obj.hasOwnProperty("isWaypoint")&&obj.isWaypoint!=null){path.isWaypoint.push(obj.isWaypoint)}else{path.isWaypoint.push(true)}if(obj.hasOwnProperty("timestamp")&&obj.timestamp!=null){path.timestamp.push(Number(new Date(obj.timestamp)))}else{path.timestamp.push("")}["approach","radius","waypointName"].forEach(function(prop){if(obj.hasOwnProperty(prop)&&obj[prop]!=null){path[prop].push(obj[prop])}else{path[prop].push("")}})});["coordinates","approach","radius","waypointName","timestamp"].forEach(function(prop){if(path[prop].every(function(value){return value===""})){delete path[prop]}else{path[prop]=path[prop].join(";")}});path.isWaypoint[0]=true;path.isWaypoint[path.isWaypoint.length-1]=true;if(path.isWaypoint.every(function(value){return value===true})){delete path.isWaypoint}else{path.isWaypoint=path.isWaypoint.map(function(val,i){return val===true?i:""}).filter(function(x){return x===0||Boolean(x)}).join(";")}var body=stringifyBooleans(objectClean_1({annotations:config.annotations,geometries:config.geometries,language:config.language,overview:config.overview,steps:config.steps,tidy:config.tidy,approaches:path.approach,radiuses:path.radius,waypoints:path.isWaypoint,timestamps:path.timestamp,waypoint_names:path.waypointName,coordinates:path.coordinates}));return this.client.createRequest({method:"POST",path:"/matching/v5/mapbox/:profile",params:{profile:config.profile},body:urlUtils.appendQueryObject("",body).substring(1),headers:{"content-type":"application/x-www-form-urlencoded"}})};var mapMatching=createServiceFactory_1(MapMatching);var Matrix={};Matrix.getMatrix=function(config){validator.assertShape({points:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb")}))),profile:validator.oneOf("driving-traffic","driving","walking","cycling"),annotations:validator.arrayOf(validator.oneOf("duration","distance")),sources:validator.oneOfType(validator.equal("all"),validator.arrayOf(validator.number)),destinations:validator.oneOfType(validator.equal("all"),validator.arrayOf(validator.number))})(config);var pointCount=config.points.length;if(pointCount<2||pointCount>100){throw new Error("points must include between 2 and 100 MatrixPoints")}config.profile=config.profile||"driving";var path={coordinates:[],approach:[]};config.points.forEach(function(obj){path.coordinates.push(obj.coordinates[0]+","+obj.coordinates[1]);if(obj.hasOwnProperty("approach")&&obj.approach!=null){path.approach.push(obj.approach)}else{path.approach.push("")}});if(path.approach.every(function(value){return value===""})){delete path.approach}else{path.approach=path.approach.join(";")}var query={sources:Array.isArray(config.sources)?config.sources.join(";"):config.sources,destinations:Array.isArray(config.destinations)?config.destinations.join(";"):config.destinations,approaches:path.approach,annotations:config.annotations&&config.annotations.join(",")};return this.client.createRequest({method:"GET",path:"/directions-matrix/v1/mapbox/:profile/:coordinates",params:{profile:config.profile,coordinates:path.coordinates.join(";")},query:objectClean_1(query)})};var matrix=createServiceFactory_1(Matrix);var Optimization={};Optimization.getOptimization=function(config){validator.assertShape({profile:validator.oneOf("driving","walking","cycling"),waypoints:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb"),bearing:validator.arrayOf(validator.range([0,360])),radius:validator.oneOfType(validator.number,validator.equal("unlimited"))}))),annotations:validator.arrayOf(validator.oneOf("duration","distance","speed")),geometries:validator.oneOf("geojson","polyline","polyline6"),language:validator.string,overview:validator.oneOf("simplified","full","false"),roundtrip:validator.boolean,steps:validator.boolean,source:validator.oneOf("any","first"),destination:validator.oneOf("any","last"),distributions:validator.arrayOf(validator.shape({pickup:validator.number,dropoff:validator.number}))})(config);var path={coordinates:[],approach:[],bearing:[],radius:[],distributions:[]};var waypointCount=config.waypoints.length;if(waypointCount<2||waypointCount>12){throw new Error("waypoints must include between 2 and 12 OptimizationWaypoints")}config.waypoints.forEach(function(waypoint){path.coordinates.push(waypoint.coordinates[0]+","+waypoint.coordinates[1]);["bearing"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){waypoint[prop]=waypoint[prop].join(",")}});["approach","bearing","radius"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){path[prop].push(waypoint[prop])}else{path[prop].push("")}})});if(config.distributions){config.distributions.forEach(function(dist){path.distributions.push(dist.pickup+","+dist.dropoff)})}["approach","bearing","radius","distributions"].forEach(function(prop){if(path[prop].every(function(char){return char===""})){delete path[prop]}else{path[prop]=path[prop].join(";")}});var query=stringifyBooleans({geometries:config.geometries,language:config.language,overview:config.overview,roundtrip:config.roundtrip,steps:config.steps,source:config.source,destination:config.destination,distributions:path.distributions,approaches:path.approach,bearings:path.bearing,radiuses:path.radius});return this.client.createRequest({method:"GET",path:"/optimized-trips/v1/mapbox/:profile/:coordinates",params:{profile:config.profile||"driving",coordinates:path.coordinates.join(";")},query:objectClean_1(query)})};var optimization=createServiceFactory_1(Optimization);var polyline_1=createCommonjsModule(function(module){var polyline={};function py2_round(value){return Math.floor(Math.abs(value)+.5)*(value>=0?1:-1)}function encode(current,previous,factor){current=py2_round(current*factor);previous=py2_round(previous*factor);var coordinate=current-previous;coordinate<<=1;if(current-previous<0){coordinate=~coordinate}var output="";while(coordinate>=32){output+=String.fromCharCode((32|coordinate&31)+63);coordinate>>=5}output+=String.fromCharCode(coordinate+63);return output}polyline.decode=function(str,precision){var index=0,lat=0,lng=0,coordinates=[],shift=0,result=0,byte=null,latitude_change,longitude_change,factor=Math.pow(10,precision||5);while(index<str.length){byte=null;shift=0;result=0;do{byte=str.charCodeAt(index++)-63;result|=(byte&31)<<shift;shift+=5}while(byte>=32);latitude_change=result&1?~(result>>1):result>>1;shift=result=0;do{byte=str.charCodeAt(index++)-63;result|=(byte&31)<<shift;shift+=5}while(byte>=32);longitude_change=result&1?~(result>>1):result>>1;lat+=latitude_change;lng+=longitude_change;coordinates.push([lat/factor,lng/factor])}return coordinates};polyline.encode=function(coordinates,precision){if(!coordinates.length){return""}var factor=Math.pow(10,precision||5),output=encode(coordinates[0][0],0,factor)+encode(coordinates[0][1],0,factor);for(var i=1;i<coordinates.length;i++){var a=coordinates[i],b=coordinates[i-1];output+=encode(a[0],b[0],factor);output+=encode(a[1],b[1],factor)}return output};function flipped(coords){var flipped=[];for(var i=0;i<coords.length;i++){flipped.push(coords[i].slice().reverse())}return flipped}polyline.fromGeoJSON=function(geojson,precision){if(geojson&&geojson.type==="Feature"){geojson=geojson.geometry}if(!geojson||geojson.type!=="LineString"){throw new Error("Input must be a GeoJSON LineString")}return polyline.encode(flipped(geojson.coordinates),precision)};polyline.toGeoJSON=function(str,precision){var coords=polyline.decode(str,precision);return{type:"LineString",coordinates:flipped(coords)}};if(module.exports){module.exports=polyline}});var Static={};Static.getStaticImage=function(config){validator.assertShape({ownerId:validator.required(validator.string),styleId:validator.required(validator.string),width:validator.required(validator.range([1,1280])),height:validator.required(validator.range([1,1280])),position:validator.required(validator.oneOfType(validator.oneOf("auto"),validator.strictShape({coordinates:validator.required(validator.coordinates),zoom:validator.required(validator.range([0,20])),bearing:validator.range([0,360]),pitch:validator.range([0,60])}))),overlays:validator.arrayOf(validator.plainObject),highRes:validator.boolean,before_layer:validator.string,addlayer:validator.plainObject,setfilter:validator.plainArray,layer_id:validator.string,attribution:validator.boolean,logo:validator.boolean})(config);var encodedOverlay=(config.overlays||[]).map(function(overlayItem){if(overlayItem.marker){return encodeMarkerOverlay(overlayItem.marker)}if(overlayItem.path){return encodePathOverlay(overlayItem.path)}return encodeGeoJsonOverlay(overlayItem.geoJson)}).join(",");var encodedPosition=encodePosition(config.position);var encodedDimensions=config.width+"x"+config.height;if(config.highRes){encodedDimensions+="@2x"}var preEncodedUrlParts=[encodedOverlay,encodedPosition,encodedDimensions].filter(Boolean).join("/");var query={};if(config.attribution!==undefined){query.attribution=String(config.attribution)}if(config.logo!==undefined){query.logo=String(config.logo)}if(config.before_layer!==undefined){query.before_layer=config.before_layer}if(config.addlayer!==undefined){query.addlayer=JSON.stringify(config.addlayer)}if(config.setfilter!==undefined){query.setfilter=JSON.stringify(config.setfilter)}if(config.layer_id!==undefined){query.layer_id=config.layer_id}if(config.setfilter!==undefined&&config.layer_id===undefined){throw new Error("Must include layer_id in setfilter request")}if((config.setfilter!==undefined||config.addlayer!==undefined)&&config.position==="auto"&&config.overlays===undefined){throw new Error("Auto extent cannot be used with style parameters and no overlay")}if(config.addlayer!==undefined&&config.setfilter!==undefined){throw new Error("addlayer and setfilter cannot be used in the same request")}return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId/:styleId/static/"+preEncodedUrlParts,params:pick_1(config,["ownerId","styleId"]),query:query})};function encodePosition(position){if(position==="auto")return"auto";return position.coordinates.concat([position.zoom,position.bearing,position.pitch]).filter(Boolean).join(",")}function encodeMarkerOverlay(o){if(o.url){return encodeCustomMarkerOverlay(o)}return encodeSimpleMarkerOverlay(o)}function encodeSimpleMarkerOverlay(o){validator.assertShape({coordinates:validator.required(validator.coordinates),size:validator.oneOf("large","small"),label:validator.string,color:validator.string})(o);var result=o.size==="large"?"pin-l":"pin-s";if(o.label){result+="-"+String(o.label).toLowerCase()}if(o.color){result+="+"+sanitizeHexColor(o.color)}result+="("+o.coordinates.join(",")+")";return result}function encodeCustomMarkerOverlay(o){validator.assertShape({coordinates:validator.required(validator.coordinates),url:validator.required(validator.string)})(o);var result="url-"+encodeURIComponent(o.url);result+="("+o.coordinates.join(",")+")";return result}function encodePathOverlay(o){validator.assertShape({coordinates:validator.required(validator.arrayOf(validator.coordinates)),strokeWidth:validator.number,strokeColor:validator.string,strokeOpacity:validator.number,fillColor:validator.string,fillOpacity:validator.number})(o);if(o.strokeOpacity!==undefined&&o.strokeColor===undefined){throw new Error("strokeOpacity requires strokeColor")}if(o.fillColor!==undefined&&o.strokeColor===undefined){throw new Error("fillColor requires strokeColor")}if(o.fillOpacity!==undefined&&o.fillColor===undefined){throw new Error("fillOpacity requires fillColor")}var result="path";if(o.strokeWidth){result+="-"+o.strokeWidth}if(o.strokeColor){result+="+"+sanitizeHexColor(o.strokeColor)}if(o.strokeOpacity){result+="-"+o.strokeOpacity}if(o.fillColor){result+="+"+sanitizeHexColor(o.fillColor)}if(o.fillOpacity){result+="-"+o.fillOpacity}var reversedCoordinates=o.coordinates.map(function(c){return c.reverse()});var encodedPolyline=polyline_1.encode(reversedCoordinates);result+="("+encodeURIComponent(encodedPolyline)+")";return result}function encodeGeoJsonOverlay(o){validator.assert(validator.required(validator.plainObject))(o);return"geojson("+encodeURIComponent(JSON.stringify(o))+")"}function sanitizeHexColor(color){return color.replace(/^#/,"")}var _static=createServiceFactory_1(Static);var Styles={};Styles.getStyle=function(config){validator.assertShape({styleId:validator.required(validator.string),ownerId:validator.string})(config);return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId/:styleId",params:config})};Styles.createStyle=function(config){validator.assertShape({style:validator.plainObject,ownerId:validator.string})(config);return this.client.createRequest({method:"POST",path:"/styles/v1/:ownerId",params:pick_1(config,["ownerId"]),body:config.style})};Styles.updateStyle=function(config){validator.assertShape({styleId:validator.required(validator.string),style:validator.required(validator.plainObject),lastKnownModification:validator.date,ownerId:validator.string})(config);var headers={};if(config.lastKnownModification){headers["If-Unmodified-Since"]=new Date(config.lastKnownModification).toUTCString()}return this.client.createRequest({method:"PATCH",path:"/styles/v1/:ownerId/:styleId",params:pick_1(config,["styleId","ownerId"]),headers:headers,body:config.style})};Styles.deleteStyle=function(config){validator.assertShape({styleId:validator.required(validator.string),ownerId:validator.string})(config);return this.client.createRequest({method:"DELETE",path:"/styles/v1/:ownerId/:styleId",params:config})};Styles.listStyles=function(config){config=config||{};validator.assertShape({start:validator.string,ownerId:validator.string})(config);var query={};if(config.start){query.start=config.start}return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId",params:pick_1(config,["ownerId"]),query:query})};Styles.putStyleIcon=function(config){validator.assertShape({styleId:validator.required(validator.string),iconId:validator.required(validator.string),file:validator.file,ownerId:validator.string})(config);return this.client.createRequest({method:"PUT",path:"/styles/v1/:ownerId/:styleId/sprite/:iconId",params:pick_1(config,["ownerId","styleId","iconId"]),file:config.file})};Styles.deleteStyleIcon=function(config){validator.assertShape({styleId:validator.required(validator.string),iconId:validator.required(validator.string),ownerId:validator.string})(config);return this.client.createRequest({method:"DELETE",path:"/styles/v1/:ownerId/:styleId/sprite/:iconId",params:config})};Styles.getStyleSprite=function(config){validator.assertShape({styleId:validator.required(validator.string),format:validator.oneOf("json","png"),highRes:validator.boolean,ownerId:validator.string})(config);var format=config.format||"json";var fileName="sprite"+(config.highRes?"@2x":"")+"."+format;return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId/:styleId/:fileName",params:immutable(pick_1(config,["ownerId","styleId"]),{fileName:fileName})})};Styles.getFontGlyphRange=function(config){validator.assertShape({fonts:validator.required(validator.oneOfType(validator.string,validator.arrayOf(validator.string))),start:validator.required(validator.number),end:validator.required(validator.number),ownerId:validator.string})(config);var fileName=config.start+"-"+config.end+".pbf";return this.client.createRequest({method:"GET",path:"/fonts/v1/:ownerId/:fontList/:fileName",params:immutable(pick_1(config,["ownerId"]),{fontList:[].concat(config.fonts),fileName:fileName})})};Styles.getEmbeddableHtml=function(config){validator.assertShape({styleId:validator.required(validator.string),scrollZoom:validator.boolean,title:validator.boolean,ownerId:validator.string})(config);var fileName=config.styleId+".html";var query={};if(config.scrollZoom!==undefined){query.zoomwheel=String(config.scrollZoom)}if(config.title!==undefined){query.title=String(config.title)}return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId/:fileName",params:immutable(pick_1(config,["ownerId"]),{fileName:fileName}),query:query})};var styles=createServiceFactory_1(Styles);var Tilequery={};Tilequery.listFeatures=function(config){validator.assertShape({mapIds:validator.required(validator.arrayOf(validator.string)),coordinates:validator.required(validator.coordinates),radius:validator.number,limit:validator.range([1,50]),dedupe:validator.boolean,geometry:validator.oneOf("polygon","linestring","point"),layers:validator.arrayOf(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/v4/:mapIds/tilequery/:coordinates.json",params:{mapIds:config.mapIds,coordinates:config.coordinates},query:pick_1(config,["radius","limit","dedupe","layers","geometry"])})};var tilequery=createServiceFactory_1(Tilequery);var Tilesets={};Tilesets.listTilesets=function(config){validator.assertShape({ownerId:validator.string})(config);return this.client.createRequest({method:"GET",path:"/tilesets/v1/:ownerId",params:config})};var tilesets=createServiceFactory_1(Tilesets);var Tokens={};Tokens.listTokens=function(){return this.client.createRequest({method:"GET",path:"/tokens/v2/:ownerId"})};Tokens.createToken=function(config){config=config||{};validator.assertShape({note:validator.string,scopes:validator.arrayOf(validator.string),resources:validator.arrayOf(validator.string),allowedUrls:validator.arrayOf(validator.string)})(config);var body={};body.scopes=config.scopes||[];if(config.note!==undefined){body.note=config.note}if(config.resources){body.resources=config.resources}if(config.allowedUrls){body.allowedUrls=config.allowedUrls}return this.client.createRequest({method:"POST",path:"/tokens/v2/:ownerId",params:pick_1(config,["ownerId"]),body:body})};Tokens.createTemporaryToken=function(config){validator.assertShape({expires:validator.required(validator.date),scopes:validator.required(validator.arrayOf(validator.string))})(config);return this.client.createRequest({method:"POST",path:"/tokens/v2/:ownerId",params:pick_1(config,["ownerId"]),body:{expires:new Date(config.expires).toISOString(),scopes:config.scopes}})};Tokens.updateToken=function(config){validator.assertShape({tokenId:validator.required(validator.string),note:validator.string,scopes:validator.arrayOf(validator.string),resources:validator.arrayOf(validator.string),allowedUrls:validator.arrayOf(validator.string)})(config);var body={};if(config.scopes){body.scopes=config.scopes}if(config.note!==undefined){body.note=config.note}if(config.resources||config.resources===null){body.resources=config.resources}if(config.allowedUrls||config.allowedUrls===null){body.allowedUrls=config.allowedUrls}return this.client.createRequest({method:"PATCH",path:"/tokens/v2/:ownerId/:tokenId",params:pick_1(config,["ownerId","tokenId"]),body:body})};Tokens.getToken=function(){return this.client.createRequest({method:"GET",path:"/tokens/v2"})};Tokens.deleteToken=function(config){validator.assertShape({tokenId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/tokens/v2/:ownerId/:tokenId",params:pick_1(config,["ownerId","tokenId"])})};Tokens.listScopes=function(){return this.client.createRequest({method:"GET",path:"/scopes/v1/:ownerId"})};var tokens=createServiceFactory_1(Tokens);var Uploads={};Uploads.listUploads=function(config){validator.assertShape({reverse:validator.boolean})(config);return this.client.createRequest({method:"GET",path:"/uploads/v1/:ownerId",query:config})};Uploads.createUploadCredentials=function(){return this.client.createRequest({method:"POST",path:"/uploads/v1/:ownerId/credentials"})};Uploads.createUpload=function(config){validator.assertShape({mapId:validator.required(validator.string),url:validator.required(validator.string),tilesetName:validator.string})(config);return this.client.createRequest({method:"POST",path:"/uploads/v1/:ownerId",body:{tileset:config.mapId,url:config.url,name:config.tilesetName}})};Uploads.getUpload=function(config){validator.assertShape({uploadId:validator.required(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/uploads/v1/:ownerId/:uploadId",params:config})};Uploads.deleteUpload=function(config){validator.assertShape({uploadId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/uploads/v1/:ownerId/:uploadId",params:config})};var uploads=createServiceFactory_1(Uploads);var Isochrone={};Isochrone.getContours=function(config){validator.assertShape({profile:validator.oneOf("driving","walking","cycling"),coordinates:validator.coordinates,minutes:validator.arrayOf(validator.number),colors:validator.arrayOf(validator.string),polygons:validator.boolean,denoise:validator.number,generalize:validator.number})(config);config.profile=config.profile||"driving";var minutesCount=config.minutes.length;if(minutesCount<1||minutesCount>4){throw new Error("minutes must contain between 1 and 4 contour values")}if(config.colors!==undefined&&config.minutes!==undefined&&config.colors.length!==config.minutes.length){throw new Error("colors should have the same number of entries as minutes")}if(!config.minutes.every(function(minute){return minute<=60})){throw new Error("minutes must be less than 60")}if(config.generalize&&config.generalize<0){throw new Error("generalize tolerance must be a positive number")}if(config.colors){config.colors=config.colors.map(function(color){if(color[0]==="#")return color.substring(1);return color})}var query=stringifyBooleans({contours_minutes:config.minutes.join(","),contours_colors:config.colors?config.colors.join(","):null,polygons:config.polygons,denoise:config.denoise,generalize:config.generalize});return this.client.createRequest({method:"GET",path:"/isochrone/v1/mapbox/:profile/:coordinates",params:{profile:config.profile,coordinates:config.coordinates.join(",")},query:objectClean_1(query)})};var isochrone=createServiceFactory_1(Isochrone);function mapboxSdk(options){var client=browserClient(options);client.datasets=datasets(client);client.directions=directions(client);client.geocoding=geocoding(client);client.mapMatching=mapMatching(client);client.matrix=matrix(client);client.optimization=optimization(client);client.static=_static(client);client.styles=styles(client);client.tilequery=tilequery(client);client.tilesets=tilesets(client);client.tokens=tokens(client);client.uploads=uploads(client);client.isochrone=isochrone(client);return client}var bundle=mapboxSdk;return bundle}); | ||
(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory():typeof define==="function"&&define.amd?define(factory):global.mapboxSdk=factory()})(this,function(){"use strict";function parseParam(param){var parts=param.match(/\s*(.+)\s*=\s*"?([^"]+)"?/);if(!parts)return null;return{key:parts[1],value:parts[2]}}function parseLink(link){var parts=link.match(/<?([^>]*)>(.*)/);if(!parts)return null;var linkUrl=parts[1];var linkParams=parts[2].split(";");var rel=null;var parsedLinkParams=linkParams.reduce(function(result,param){var parsed=parseParam(param);if(!parsed)return result;if(parsed.key==="rel"){if(!rel){rel=parsed.value}return result}result[parsed.key]=parsed.value;return result},{});if(!rel)return null;return{url:linkUrl,rel:rel,params:parsedLinkParams}}function parseLinkHeader(linkHeader){if(!linkHeader)return{};return linkHeader.split(/,\s*</).reduce(function(result,link){var parsed=parseLink(link);if(!parsed)return result;var splitRel=parsed.rel.split(/\s+/);splitRel.forEach(function(rel){if(!result[rel]){result[rel]={url:parsed.url,params:parsed.params}}});return result},{})}var parseLinkHeader_1=parseLinkHeader;function MapiResponse(request,responseData){this.request=request;this.headers=responseData.headers;this.rawBody=responseData.body;this.statusCode=responseData.statusCode;try{this.body=JSON.parse(responseData.body||"{}")}catch(parseError){this.body=responseData.body}this.links=parseLinkHeader_1(this.headers.link)}MapiResponse.prototype.hasNextPage=function hasNextPage(){return!!this.links.next};MapiResponse.prototype.nextPage=function nextPage(){if(!this.hasNextPage())return null;return this.request._extend({path:this.links.next.url})};var mapiResponse=MapiResponse;var constants={API_ORIGIN:"https://api.mapbox.com",EVENT_PROGRESS_DOWNLOAD:"downloadProgress",EVENT_PROGRESS_UPLOAD:"uploadProgress",EVENT_ERROR:"error",EVENT_RESPONSE:"response",ERROR_HTTP:"HttpError",ERROR_REQUEST_ABORTED:"RequestAbortedError"};function MapiError(options){var errorType=options.type||constants.ERROR_HTTP;var body;if(options.body){try{body=JSON.parse(options.body)}catch(e){body=options.body}}else{body=null}var message=options.message||null;if(!message){if(typeof body==="string"){message=body}else if(body&&typeof body.message==="string"){message=body.message}else if(errorType===constants.ERROR_REQUEST_ABORTED){message="Request aborted"}}this.message=message;this.type=errorType;this.statusCode=options.statusCode||null;this.request=options.request;this.body=body}var mapiError=MapiError;function parseSingleHeader(raw){var boundary=raw.indexOf(":");var name=raw.substring(0,boundary).trim().toLowerCase();var value=raw.substring(boundary+1).trim();return{name:name,value:value}}function parseHeaders(raw){var headers={};if(!raw){return headers}raw.trim().split(/[\r|\n]+/).forEach(function(rawHeader){var parsed=parseSingleHeader(rawHeader);headers[parsed.name]=parsed.value});return headers}var parseHeaders_1=parseHeaders;var requestsUnderway={};function browserAbort(request){var xhr=requestsUnderway[request.id];if(!xhr)return;xhr.abort();delete requestsUnderway[request.id]}function createResponse(request,xhr){return new mapiResponse(request,{body:xhr.response,headers:parseHeaders_1(xhr.getAllResponseHeaders()),statusCode:xhr.status})}function normalizeBrowserProgressEvent(event){var total=event.total;var transferred=event.loaded;var percent=100*transferred/total;return{total:total,transferred:transferred,percent:percent}}function sendRequestXhr(request,xhr){return new Promise(function(resolve,reject){xhr.onprogress=function(event){request.emitter.emit(constants.EVENT_PROGRESS_DOWNLOAD,normalizeBrowserProgressEvent(event))};var file=request.file;if(file){xhr.upload.onprogress=function(event){request.emitter.emit(constants.EVENT_PROGRESS_UPLOAD,normalizeBrowserProgressEvent(event))}}xhr.onerror=function(error){reject(error)};xhr.onabort=function(){var mapiError$$1=new mapiError({request:request,type:constants.ERROR_REQUEST_ABORTED});reject(mapiError$$1)};xhr.onload=function(){delete requestsUnderway[request.id];if(xhr.status<200||xhr.status>=400){var mapiError$$1=new mapiError({request:request,body:xhr.response,statusCode:xhr.status});reject(mapiError$$1);return}resolve(xhr)};var body=request.body;if(typeof body==="string"){xhr.send(body)}else if(body){xhr.send(JSON.stringify(body))}else if(file){xhr.send(file)}else{xhr.send()}requestsUnderway[request.id]=xhr}).then(function(xhr){return createResponse(request,xhr)})}function createRequestXhr(request,accessToken){var url=request.url(accessToken);var xhr=new window.XMLHttpRequest;xhr.open(request.method,url);Object.keys(request.headers).forEach(function(key){xhr.setRequestHeader(key,request.headers[key])});return xhr}function browserSend(request){return Promise.resolve().then(function(){var xhr=createRequestXhr(request,request.client.accessToken);return sendRequestXhr(request,xhr)})}var browserLayer={browserAbort:browserAbort,sendRequestXhr:sendRequestXhr,browserSend:browserSend,createRequestXhr:createRequestXhr};var commonjsGlobal=typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};function createCommonjsModule(fn,module){return module={exports:{}},fn(module,module.exports),module.exports}var base64=createCommonjsModule(function(module,exports){(function(root){var freeExports=exports;var freeModule=module&&module.exports==freeExports&&module;var freeGlobal=typeof commonjsGlobal=="object"&&commonjsGlobal;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var InvalidCharacterError=function(message){this.message=message};InvalidCharacterError.prototype=new Error;InvalidCharacterError.prototype.name="InvalidCharacterError";var error=function(message){throw new InvalidCharacterError(message)};var TABLE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var REGEX_SPACE_CHARACTERS=/[\t\n\f\r ]/g;var decode=function(input){input=String(input).replace(REGEX_SPACE_CHARACTERS,"");var length=input.length;if(length%4==0){input=input.replace(/==?$/,"");length=input.length}if(length%4==1||/[^+a-zA-Z0-9/]/.test(input)){error("Invalid character: the string to be decoded is not correctly encoded.")}var bitCounter=0;var bitStorage;var buffer;var output="";var position=-1;while(++position<length){buffer=TABLE.indexOf(input.charAt(position));bitStorage=bitCounter%4?bitStorage*64+buffer:buffer;if(bitCounter++%4){output+=String.fromCharCode(255&bitStorage>>(-2*bitCounter&6))}}return output};var encode=function(input){input=String(input);if(/[^\0-\xFF]/.test(input)){error("The string to be encoded contains characters outside of the "+"Latin1 range.")}var padding=input.length%3;var output="";var position=-1;var a;var b;var c;var buffer;var length=input.length-padding;while(++position<length){a=input.charCodeAt(position)<<16;b=input.charCodeAt(++position)<<8;c=input.charCodeAt(++position);buffer=a+b+c;output+=TABLE.charAt(buffer>>18&63)+TABLE.charAt(buffer>>12&63)+TABLE.charAt(buffer>>6&63)+TABLE.charAt(buffer&63)}if(padding==2){a=input.charCodeAt(position)<<8;b=input.charCodeAt(++position);buffer=a+b;output+=TABLE.charAt(buffer>>10)+TABLE.charAt(buffer>>4&63)+TABLE.charAt(buffer<<2&63)+"="}else if(padding==1){buffer=input.charCodeAt(position);output+=TABLE.charAt(buffer>>2)+TABLE.charAt(buffer<<4&63)+"=="}return output};var base64={encode:encode,decode:decode,version:"0.1.0"};if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=base64}else{for(var key in base64){base64.hasOwnProperty(key)&&(freeExports[key]=base64[key])}}}else{root.base64=base64}})(commonjsGlobal)});var tokenCache={};function parseToken(token){if(tokenCache[token]){return tokenCache[token]}var parts=token.split(".");var usage=parts[0];var rawPayload=parts[1];if(!rawPayload){throw new Error("Invalid token")}var parsedPayload=parsePaylod(rawPayload);var result={usage:usage,user:parsedPayload.u};if(has(parsedPayload,"a"))result.authorization=parsedPayload.a;if(has(parsedPayload,"exp"))result.expires=parsedPayload.exp*1e3;if(has(parsedPayload,"iat"))result.created=parsedPayload.iat*1e3;if(has(parsedPayload,"scopes"))result.scopes=parsedPayload.scopes;if(has(parsedPayload,"client"))result.client=parsedPayload.client;if(has(parsedPayload,"ll"))result.lastLogin=parsedPayload.ll;if(has(parsedPayload,"iu"))result.impersonator=parsedPayload.iu;tokenCache[token]=result;return result}function parsePaylod(rawPayload){try{return JSON.parse(base64.decode(rawPayload))}catch(parseError){throw new Error("Invalid token")}}function has(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)}var parseMapboxToken=parseToken;var immutable=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(){var target={};for(var i=0;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(hasOwnProperty.call(source,key)){target[key]=source[key]}}}return target}var eventemitter3=createCommonjsModule(function(module){var has=Object.prototype.hasOwnProperty,prefix="~";function Events(){}if(Object.create){Events.prototype=Object.create(null);if(!(new Events).__proto__)prefix=false}function EE(fn,context,once){this.fn=fn;this.context=context;this.once=once||false}function addListener(emitter,event,fn,context,once){if(typeof fn!=="function"){throw new TypeError("The listener must be a function")}var listener=new EE(fn,context||emitter,once),evt=prefix?prefix+event:event;if(!emitter._events[evt])emitter._events[evt]=listener,emitter._eventsCount++;else if(!emitter._events[evt].fn)emitter._events[evt].push(listener);else emitter._events[evt]=[emitter._events[evt],listener];return emitter}function clearEvent(emitter,evt){if(--emitter._eventsCount===0)emitter._events=new Events;else delete emitter._events[evt]}function EventEmitter(){this._events=new Events;this._eventsCount=0}EventEmitter.prototype.eventNames=function eventNames(){var names=[],events,name;if(this._eventsCount===0)return names;for(name in events=this._events){if(has.call(events,name))names.push(prefix?name.slice(1):name)}if(Object.getOwnPropertySymbols){return names.concat(Object.getOwnPropertySymbols(events))}return names};EventEmitter.prototype.listeners=function listeners(event){var evt=prefix?prefix+event:event,handlers=this._events[evt];if(!handlers)return[];if(handlers.fn)return[handlers.fn];for(var i=0,l=handlers.length,ee=new Array(l);i<l;i++){ee[i]=handlers[i].fn}return ee};EventEmitter.prototype.listenerCount=function listenerCount(event){var evt=prefix?prefix+event:event,listeners=this._events[evt];if(!listeners)return 0;if(listeners.fn)return 1;return listeners.length};EventEmitter.prototype.emit=function emit(event,a1,a2,a3,a4,a5){var evt=prefix?prefix+event:event;if(!this._events[evt])return false;var listeners=this._events[evt],len=arguments.length,args,i;if(listeners.fn){if(listeners.once)this.removeListener(event,listeners.fn,undefined,true);switch(len){case 1:return listeners.fn.call(listeners.context),true;case 2:return listeners.fn.call(listeners.context,a1),true;case 3:return listeners.fn.call(listeners.context,a1,a2),true;case 4:return listeners.fn.call(listeners.context,a1,a2,a3),true;case 5:return listeners.fn.call(listeners.context,a1,a2,a3,a4),true;case 6:return listeners.fn.call(listeners.context,a1,a2,a3,a4,a5),true}for(i=1,args=new Array(len-1);i<len;i++){args[i-1]=arguments[i]}listeners.fn.apply(listeners.context,args)}else{var length=listeners.length,j;for(i=0;i<length;i++){if(listeners[i].once)this.removeListener(event,listeners[i].fn,undefined,true);switch(len){case 1:listeners[i].fn.call(listeners[i].context);break;case 2:listeners[i].fn.call(listeners[i].context,a1);break;case 3:listeners[i].fn.call(listeners[i].context,a1,a2);break;case 4:listeners[i].fn.call(listeners[i].context,a1,a2,a3);break;default:if(!args)for(j=1,args=new Array(len-1);j<len;j++){args[j-1]=arguments[j]}listeners[i].fn.apply(listeners[i].context,args)}}}return true};EventEmitter.prototype.on=function on(event,fn,context){return addListener(this,event,fn,context,false)};EventEmitter.prototype.once=function once(event,fn,context){return addListener(this,event,fn,context,true)};EventEmitter.prototype.removeListener=function removeListener(event,fn,context,once){var evt=prefix?prefix+event:event;if(!this._events[evt])return this;if(!fn){clearEvent(this,evt);return this}var listeners=this._events[evt];if(listeners.fn){if(listeners.fn===fn&&(!once||listeners.once)&&(!context||listeners.context===context)){clearEvent(this,evt)}}else{for(var i=0,events=[],length=listeners.length;i<length;i++){if(listeners[i].fn!==fn||once&&!listeners[i].once||context&&listeners[i].context!==context){events.push(listeners[i])}}if(events.length)this._events[evt]=events.length===1?events[0]:events;else clearEvent(this,evt)}return this};EventEmitter.prototype.removeAllListeners=function removeAllListeners(event){var evt;if(event){evt=prefix?prefix+event:event;if(this._events[evt])clearEvent(this,evt)}else{this._events=new Events;this._eventsCount=0}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prefixed=prefix;EventEmitter.EventEmitter=EventEmitter;{module.exports=EventEmitter}});function encodeArray(arrayValue){return arrayValue.map(encodeURIComponent).join(",")}function encodeValue(value){if(Array.isArray(value)){return encodeArray(value)}return encodeURIComponent(String(value))}function appendQueryParam(url,key,value){if(value===false||value===null){return url}var punctuation=/\?/.test(url)?"&":"?";var query=encodeURIComponent(key);if(value!==undefined&&value!==""&&value!==true){query+="="+encodeValue(value)}return""+url+punctuation+query}function appendQueryObject(url,queryObject){if(!queryObject){return url}var result=url;Object.keys(queryObject).forEach(function(key){var value=queryObject[key];if(value===undefined){return}if(Array.isArray(value)){value=value.filter(function(v){return!!v}).join(",")}result=appendQueryParam(result,key,value)});return result}function prependOrigin(url,origin){if(!origin){return url}if(url.slice(0,4)==="http"){return url}var delimiter=url[0]==="/"?"":"/";return""+origin.replace(/\/$/,"")+delimiter+url}function interpolateRouteParams(route,params){if(!params){return route}return route.replace(/\/:([a-zA-Z0-9]+)/g,function(_,paramId){var value=params[paramId];if(value===undefined){throw new Error("Unspecified route parameter "+paramId)}var preppedValue=encodeValue(value);return"/"+preppedValue})}var urlUtils={appendQueryObject:appendQueryObject,appendQueryParam:appendQueryParam,prependOrigin:prependOrigin,interpolateRouteParams:interpolateRouteParams};var requestId=1;function MapiRequest(client,options){if(!client){throw new Error("MapiRequest requires a client")}if(!options||!options.path||!options.method){throw new Error("MapiRequest requires an options object with path and method properties")}var defaultHeaders={};if(options.body){defaultHeaders["content-type"]="application/json"}var headersWithDefaults=immutable(defaultHeaders,options.headers);var headers=Object.keys(headersWithDefaults).reduce(function(memo,name){memo[name.toLowerCase()]=headersWithDefaults[name];return memo},{});this.id=requestId++;this._options=options;this.emitter=new eventemitter3;this.client=client;this.response=null;this.error=null;this.sent=false;this.aborted=false;this.path=options.path;this.method=options.method;this.origin=options.origin||client.origin;this.query=options.query||{};this.params=options.params||{};this.body=options.body||null;this.file=options.file||null;this.encoding=options.encoding||"utf8";this.sendFileAs=options.sendFileAs||null;this.headers=headers}MapiRequest.prototype.url=function url(accessToken){var url=urlUtils.prependOrigin(this.path,this.origin);url=urlUtils.appendQueryObject(url,this.query);var routeParams=this.params;var actualAccessToken=accessToken==null?this.client.accessToken:accessToken;if(actualAccessToken){url=urlUtils.appendQueryParam(url,"access_token",actualAccessToken);var accessTokenOwnerId=parseMapboxToken(actualAccessToken).user;routeParams=immutable({ownerId:accessTokenOwnerId},routeParams)}url=urlUtils.interpolateRouteParams(url,routeParams);return url};MapiRequest.prototype.send=function send(){var self=this;if(self.sent){throw new Error("This request has already been sent. Check the response and error properties. Create a new request with clone().")}self.sent=true;return self.client.sendRequest(self).then(function(response){self.response=response;self.emitter.emit(constants.EVENT_RESPONSE,response);return response},function(error){self.error=error;self.emitter.emit(constants.EVENT_ERROR,error);throw error})};MapiRequest.prototype.abort=function abort(){if(this._nextPageRequest){this._nextPageRequest.abort();delete this._nextPageRequest}if(this.response||this.error||this.aborted)return;this.aborted=true;this.client.abortRequest(this)};MapiRequest.prototype.eachPage=function eachPage(callback){var self=this;function handleResponse(response){function getNextPage(){delete self._nextPageRequest;var nextPageRequest=response.nextPage();if(nextPageRequest){self._nextPageRequest=nextPageRequest;getPage(nextPageRequest)}}callback(null,response,getNextPage)}function handleError(error){callback(error,null,function(){})}function getPage(request){request.send().then(handleResponse,handleError)}getPage(this)};MapiRequest.prototype.clone=function clone(){return this._extend()};MapiRequest.prototype._extend=function _extend(options){var extendedOptions=immutable(this._options,options);return new MapiRequest(this.client,extendedOptions)};var mapiRequest=MapiRequest;function MapiClient(options){if(!options||!options.accessToken){throw new Error("Cannot create a client without an access token")}parseMapboxToken(options.accessToken);this.accessToken=options.accessToken;this.origin=options.origin||constants.API_ORIGIN}MapiClient.prototype.createRequest=function createRequest(requestOptions){return new mapiRequest(this,requestOptions)};var mapiClient=MapiClient;function BrowserClient(options){mapiClient.call(this,options)}BrowserClient.prototype=Object.create(mapiClient.prototype);BrowserClient.prototype.constructor=BrowserClient;BrowserClient.prototype.sendRequest=browserLayer.browserSend;BrowserClient.prototype.abortRequest=browserLayer.browserAbort;function createBrowserClient(options){return new BrowserClient(options)}var browserClient=createBrowserClient;var toString=Object.prototype.toString;var isPlainObj=function(x){var prototype;return toString.call(x)==="[object Object]"&&(prototype=Object.getPrototypeOf(x),prototype===null||prototype===Object.getPrototypeOf({}))};var DEFAULT_ERROR_PATH="value";var NEWLINE_INDENT="\n ";var v={};v.assert=function(rootValidator,options){options=options||{};return function(value){var message=validate(rootValidator,value);if(!message){return}var errorMessage=processMessage(message,options);if(options.apiName){errorMessage=options.apiName+": "+errorMessage}throw new Error(errorMessage)}};v.shape=function shape(validatorObj){var validators=objectEntries(validatorObj);return function shapeValidator(value){var validationResult=validate(v.plainObject,value);if(validationResult){return validationResult}var key,validator;var errorMessages=[];for(var i=0;i<validators.length;i++){key=validators[i].key;validator=validators[i].value;validationResult=validate(validator,value[key]);if(validationResult){errorMessages.push([key].concat(validationResult))}}if(errorMessages.length<2){return errorMessages[0]}return function(options){errorMessages=errorMessages.map(function(message){var key=message[0];var renderedMessage=processMessage(message,options).split("\n").join(NEWLINE_INDENT);return"- "+key+": "+renderedMessage});var objectId=options.path.join(".");var ofPhrase=objectId===DEFAULT_ERROR_PATH?"":" of "+objectId;return"The following properties"+ofPhrase+" have invalid values:"+NEWLINE_INDENT+errorMessages.join(NEWLINE_INDENT)}}};v.strictShape=function strictShape(validatorObj){var shapeValidator=v.shape(validatorObj);return function strictShapeValidator(value){var shapeResult=shapeValidator(value);if(shapeResult){return shapeResult}var invalidKeys=Object.keys(value).reduce(function(memo,valueKey){if(validatorObj[valueKey]===undefined){memo.push(valueKey)}return memo},[]);if(invalidKeys.length!==0){return function(){return"The following keys are invalid: "+invalidKeys.join(", ")}}}};v.arrayOf=function arrayOf(validator){return createArrayValidator(validator)};v.tuple=function tuple(){var validators=Array.isArray(arguments[0])?arguments[0]:Array.prototype.slice.call(arguments);return createArrayValidator(validators)};function createArrayValidator(validators){var validatingTuple=Array.isArray(validators);var getValidator=function(index){if(validatingTuple){return validators[index]}return validators};return function arrayValidator(value){var validationResult=validate(v.plainArray,value);if(validationResult){return validationResult}if(validatingTuple&&value.length!==validators.length){return"an array with "+validators.length+" items"}for(var i=0;i<value.length;i++){validationResult=validate(getValidator(i),value[i]);if(validationResult){return[i].concat(validationResult)}}}}v.required=function required(validator){function requiredValidator(value){if(value==null){return function(options){return formatErrorMessage(options,isArrayCulprit(options.path)?"cannot be undefined/null.":"is required.")}}return validator.apply(this,arguments)}requiredValidator.__required=true;return requiredValidator};v.oneOfType=function oneOfType(){var validators=Array.isArray(arguments[0])?arguments[0]:Array.prototype.slice.call(arguments);return function oneOfTypeValidator(value){var messages=validators.map(function(validator){return validate(validator,value)}).filter(Boolean);if(messages.length!==validators.length){return}if(messages.every(function(message){return message.length===1&&typeof message[0]==="string"})){return orList(messages.map(function(m){return m[0]}))}return messages.reduce(function(max,arr){return arr.length>max.length?arr:max})}};v.equal=function equal(compareWith){return function equalValidator(value){if(value!==compareWith){return JSON.stringify(compareWith)}}};v.oneOf=function oneOf(){var options=Array.isArray(arguments[0])?arguments[0]:Array.prototype.slice.call(arguments);var validators=options.map(function(value){return v.equal(value)});return v.oneOfType.apply(this,validators)};v.range=function range(compareWith){var min=compareWith[0];var max=compareWith[1];return function rangeValidator(value){var validationResult=validate(v.number,value);if(validationResult||value<min||value>max){return"number between "+min+" & "+max+" (inclusive)"}}};v.any=function any(){return};v.boolean=function boolean(value){if(typeof value!=="boolean"){return"boolean"}};v.number=function number(value){if(typeof value!=="number"){return"number"}};v.plainArray=function plainArray(value){if(!Array.isArray(value)){return"array"}};v.plainObject=function plainObject(value){if(!isPlainObj(value)){return"object"}};v.string=function string(value){if(typeof value!=="string"){return"string"}};v.func=function func(value){if(typeof value!=="function"){return"function"}};function validate(validator,value){if(value==null&&!validator.hasOwnProperty("__required")){return}var result=validator(value);if(result){return Array.isArray(result)?result:[result]}}function processMessage(message,options){var len=message.length;var result=message[len-1];var path=message.slice(0,len-1);if(path.length===0){path=[DEFAULT_ERROR_PATH]}options=immutable(options,{path:path});return typeof result==="function"?result(options):formatErrorMessage(options,prettifyResult(result))}function orList(list){if(list.length<2){return list[0]}if(list.length===2){return list.join(" or ")}return list.slice(0,-1).join(", ")+", or "+list.slice(-1)}function prettifyResult(result){return"must be "+addArticle(result)+"."}function addArticle(nounPhrase){if(/^an? /.test(nounPhrase)){return nounPhrase}if(/^[aeiou]/i.test(nounPhrase)){return"an "+nounPhrase}if(/^[a-z]/i.test(nounPhrase)){return"a "+nounPhrase}return nounPhrase}function formatErrorMessage(options,prettyResult){var arrayCulprit=isArrayCulprit(options.path);var output=options.path.join(".")+" "+prettyResult;var prepend=arrayCulprit?"Item at position ":"";return prepend+output}function isArrayCulprit(path){return typeof path[path.length-1]=="number"||typeof path[0]=="number"}function objectEntries(obj){return Object.keys(obj||{}).map(function(key){return{key:key,value:obj[key]}})}v.validate=validate;v.processMessage=processMessage;var lib=v;function file(value){if(typeof window!=="undefined"){if(value instanceof commonjsGlobal.Blob||value instanceof commonjsGlobal.ArrayBuffer){return}return"Blob or ArrayBuffer"}if(typeof value==="string"||value.pipe!==undefined){return}return"Filename or Readable stream"}function assertShape(validatorObj,apiName){return lib.assert(lib.strictShape(validatorObj),apiName)}function date(value){var msg="date";if(typeof value==="boolean"){return msg}try{var date=new Date(value);if(date.getTime&&isNaN(date.getTime())){return msg}}catch(e){return msg}}function coordinates(value){return lib.tuple(lib.number,lib.number)(value)}var validator=immutable(lib,{file:file,date:date,coordinates:coordinates,assertShape:assertShape});function pick(source,keys){var filter=function(key,val){return keys.indexOf(key)!==-1&&val!==undefined};if(typeof keys==="function"){filter=keys}return Object.keys(source).filter(function(key){return filter(key,source[key])}).reduce(function(result,key){result[key]=source[key];return result},{})}var pick_1=pick;function createServiceFactory(ServicePrototype){return function(clientOrConfig){var client;if(mapiClient.prototype.isPrototypeOf(clientOrConfig)){client=clientOrConfig}else{client=browserClient(clientOrConfig)}var service=Object.create(ServicePrototype);service.client=client;return service}}var createServiceFactory_1=createServiceFactory;var Datasets={};Datasets.listDatasets=function(){return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId"})};Datasets.createDataset=function(config){validator.assertShape({name:validator.string,description:validator.string})(config);return this.client.createRequest({method:"POST",path:"/datasets/v1/:ownerId",body:config})};Datasets.getMetadata=function(config){validator.assertShape({datasetId:validator.required(validator.string),description:validator.string})(config);return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId/:datasetId",params:config})};Datasets.updateMetadata=function(config){validator.assertShape({datasetId:validator.required(validator.string),name:validator.string,description:validator.string})(config);return this.client.createRequest({method:"PATCH",path:"/datasets/v1/:ownerId/:datasetId",params:pick_1(config,["datasetId"]),body:pick_1(config,["name","description"])})};Datasets.deleteDataset=function(config){validator.assertShape({datasetId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/datasets/v1/:ownerId/:datasetId",params:config})};Datasets.listFeatures=function(config){validator.assertShape({datasetId:validator.required(validator.string),limit:validator.number,start:validator.string})(config);return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId/:datasetId/features",params:pick_1(config,["datasetId"]),query:pick_1(config,["limit","start"])})};Datasets.putFeature=function(config){validator.assertShape({datasetId:validator.required(validator.string),featureId:validator.required(validator.string),feature:validator.required(validator.plainObject)})(config);if(config.feature.id!==undefined&&config.feature.id!==config.featureId){throw new Error("featureId must match the id property of the feature")}return this.client.createRequest({method:"PUT",path:"/datasets/v1/:ownerId/:datasetId/features/:featureId",params:pick_1(config,["datasetId","featureId"]),body:config.feature})};Datasets.getFeature=function(config){validator.assertShape({datasetId:validator.required(validator.string),featureId:validator.required(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId/:datasetId/features/:featureId",params:config})};Datasets.deleteFeature=function(config){validator.assertShape({datasetId:validator.required(validator.string),featureId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/datasets/v1/:ownerId/:datasetId/features/:featureId",params:config})};var datasets=createServiceFactory_1(Datasets);function objectClean(obj){return pick_1(obj,function(_,val){return val!=null})}var objectClean_1=objectClean;function objectMap(obj,cb){return Object.keys(obj).reduce(function(result,key){result[key]=cb(key,obj[key]);return result},{})}var objectMap_1=objectMap;function stringifyBoolean(obj){return objectMap_1(obj,function(_,value){return typeof value==="boolean"?JSON.stringify(value):value})}var stringifyBooleans=stringifyBoolean;var Directions={};Directions.getDirections=function(config){validator.assertShape({profile:validator.oneOf("driving-traffic","driving","walking","cycling"),waypoints:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb"),bearing:validator.arrayOf(validator.range([0,360])),radius:validator.oneOfType(validator.number,validator.equal("unlimited")),waypointName:validator.string}))),alternatives:validator.boolean,annotations:validator.arrayOf(validator.oneOf("duration","distance","speed","congestion")),bannerInstructions:validator.boolean,continueStraight:validator.boolean,exclude:validator.string,geometries:validator.string,language:validator.string,overview:validator.string,roundaboutExits:validator.boolean,steps:validator.boolean,voiceInstructions:validator.boolean,voiceUnits:validator.string})(config);config.profile=config.profile||"driving";var path={coordinates:[],approach:[],bearing:[],radius:[],waypointName:[]};var waypointCount=config.waypoints.length;if(waypointCount<2||waypointCount>25){throw new Error("waypoints must include between 2 and 25 DirectionsWaypoints")}config.waypoints.forEach(function(waypoint){path.coordinates.push(waypoint.coordinates[0]+","+waypoint.coordinates[1]);["bearing"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){waypoint[prop]=waypoint[prop].join(",")}});["approach","bearing","radius","waypointName"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){path[prop].push(waypoint[prop])}else{path[prop].push("")}})});["approach","bearing","radius","waypointName"].forEach(function(prop){if(path[prop].every(function(char){return char===""})){delete path[prop]}else{path[prop]=path[prop].join(";")}});var query=stringifyBooleans({alternatives:config.alternatives,annotations:config.annotations,banner_instructions:config.bannerInstructions,continue_straight:config.continueStraight,exclude:config.exclude,geometries:config.geometries,language:config.language,overview:config.overview,roundabout_exits:config.roundaboutExits,steps:config.steps,voice_instructions:config.voiceInstructions,voice_units:config.voiceUnits,approaches:path.approach,bearings:path.bearing,radiuses:path.radius,waypoint_names:path.waypointName});return this.client.createRequest({method:"GET",path:"/directions/v5/mapbox/:profile/:coordinates",params:{profile:config.profile,coordinates:path.coordinates.join(";")},query:objectClean_1(query)})};var directions=createServiceFactory_1(Directions);var Geocoding={};var featureTypes=["country","region","postcode","district","place","locality","neighborhood","address","poi","poi.landmark"];Geocoding.forwardGeocode=function(config){validator.assertShape({query:validator.required(validator.string),mode:validator.oneOf("mapbox.places","mapbox.places-permanent"),countries:validator.arrayOf(validator.string),proximity:validator.coordinates,types:validator.arrayOf(validator.oneOf(featureTypes)),autocomplete:validator.boolean,bbox:validator.arrayOf(validator.number),limit:validator.number,language:validator.arrayOf(validator.string)})(config);config.mode=config.mode||"mapbox.places";var query=stringifyBooleans(immutable({country:config.countries},pick_1(config,["proximity","types","autocomplete","bbox","limit","language"])));return this.client.createRequest({method:"GET",path:"/geocoding/v5/:mode/:query.json",params:pick_1(config,["mode","query"]),query:query})};Geocoding.reverseGeocode=function(config){validator.assertShape({query:validator.required(validator.coordinates),mode:validator.oneOf("mapbox.places","mapbox.places-permanent"),countries:validator.arrayOf(validator.string),types:validator.arrayOf(validator.oneOf(featureTypes)),bbox:validator.arrayOf(validator.number),limit:validator.number,language:validator.arrayOf(validator.string),reverseMode:validator.oneOf("distance","score")})(config);config.mode=config.mode||"mapbox.places";var query=stringifyBooleans(immutable({country:config.countries},pick_1(config,["country","types","bbox","limit","language","reverseMode"])));return this.client.createRequest({method:"GET",path:"/geocoding/v5/:mode/:query.json",params:pick_1(config,["mode","query"]),query:query})};var geocoding=createServiceFactory_1(Geocoding);var MapMatching={};MapMatching.getMatch=function(config){validator.assertShape({points:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb"),radius:validator.range([0,50]),isWaypoint:validator.boolean,waypointName:validator.string,timestamp:validator.date}))),profile:validator.oneOf("driving-traffic","driving","walking","cycling"),annotations:validator.arrayOf(validator.oneOf("duration","distance","speed")),geometries:validator.oneOf("geojson","polyline","polyline6"),language:validator.string,overview:validator.oneOf("full","simplified","false"),steps:validator.boolean,tidy:validator.boolean})(config);var pointCount=config.points.length;if(pointCount<2||pointCount>100){throw new Error("points must include between 2 and 100 MapMatchingPoints")}config.profile=config.profile||"driving";var path={coordinates:[],approach:[],radius:[],isWaypoint:[],waypointName:[],timestamp:[]};config.points.forEach(function(obj){path.coordinates.push(obj.coordinates[0]+","+obj.coordinates[1]);if(obj.hasOwnProperty("isWaypoint")&&obj.isWaypoint!=null){path.isWaypoint.push(obj.isWaypoint)}else{path.isWaypoint.push(true)}if(obj.hasOwnProperty("timestamp")&&obj.timestamp!=null){path.timestamp.push(Number(new Date(obj.timestamp)))}else{path.timestamp.push("")}["approach","radius","waypointName"].forEach(function(prop){if(obj.hasOwnProperty(prop)&&obj[prop]!=null){path[prop].push(obj[prop])}else{path[prop].push("")}})});["coordinates","approach","radius","waypointName","timestamp"].forEach(function(prop){if(path[prop].every(function(value){return value===""})){delete path[prop]}else{path[prop]=path[prop].join(";")}});path.isWaypoint[0]=true;path.isWaypoint[path.isWaypoint.length-1]=true;if(path.isWaypoint.every(function(value){return value===true})){delete path.isWaypoint}else{path.isWaypoint=path.isWaypoint.map(function(val,i){return val===true?i:""}).filter(function(x){return x===0||Boolean(x)}).join(";")}var body=stringifyBooleans(objectClean_1({annotations:config.annotations,geometries:config.geometries,language:config.language,overview:config.overview,steps:config.steps,tidy:config.tidy,approaches:path.approach,radiuses:path.radius,waypoints:path.isWaypoint,timestamps:path.timestamp,waypoint_names:path.waypointName,coordinates:path.coordinates}));return this.client.createRequest({method:"POST",path:"/matching/v5/mapbox/:profile",params:{profile:config.profile},body:urlUtils.appendQueryObject("",body).substring(1),headers:{"content-type":"application/x-www-form-urlencoded"}})};var mapMatching=createServiceFactory_1(MapMatching);var Matrix={};Matrix.getMatrix=function(config){validator.assertShape({points:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb")}))),profile:validator.oneOf("driving-traffic","driving","walking","cycling"),annotations:validator.arrayOf(validator.oneOf("duration","distance")),sources:validator.oneOfType(validator.equal("all"),validator.arrayOf(validator.number)),destinations:validator.oneOfType(validator.equal("all"),validator.arrayOf(validator.number))})(config);var pointCount=config.points.length;if(pointCount<2||pointCount>100){throw new Error("points must include between 2 and 100 MatrixPoints")}config.profile=config.profile||"driving";var path={coordinates:[],approach:[]};config.points.forEach(function(obj){path.coordinates.push(obj.coordinates[0]+","+obj.coordinates[1]);if(obj.hasOwnProperty("approach")&&obj.approach!=null){path.approach.push(obj.approach)}else{path.approach.push("")}});if(path.approach.every(function(value){return value===""})){delete path.approach}else{path.approach=path.approach.join(";")}var query={sources:Array.isArray(config.sources)?config.sources.join(";"):config.sources,destinations:Array.isArray(config.destinations)?config.destinations.join(";"):config.destinations,approaches:path.approach,annotations:config.annotations&&config.annotations.join(",")};return this.client.createRequest({method:"GET",path:"/directions-matrix/v1/mapbox/:profile/:coordinates",params:{profile:config.profile,coordinates:path.coordinates.join(";")},query:objectClean_1(query)})};var matrix=createServiceFactory_1(Matrix);var Optimization={};Optimization.getOptimization=function(config){validator.assertShape({profile:validator.oneOf("driving","walking","cycling"),waypoints:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb"),bearing:validator.arrayOf(validator.range([0,360])),radius:validator.oneOfType(validator.number,validator.equal("unlimited"))}))),annotations:validator.arrayOf(validator.oneOf("duration","distance","speed")),geometries:validator.oneOf("geojson","polyline","polyline6"),language:validator.string,overview:validator.oneOf("simplified","full","false"),roundtrip:validator.boolean,steps:validator.boolean,source:validator.oneOf("any","first"),destination:validator.oneOf("any","last"),distributions:validator.arrayOf(validator.shape({pickup:validator.number,dropoff:validator.number}))})(config);var path={coordinates:[],approach:[],bearing:[],radius:[],distributions:[]};var waypointCount=config.waypoints.length;if(waypointCount<2||waypointCount>12){throw new Error("waypoints must include between 2 and 12 OptimizationWaypoints")}config.waypoints.forEach(function(waypoint){path.coordinates.push(waypoint.coordinates[0]+","+waypoint.coordinates[1]);["bearing"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){waypoint[prop]=waypoint[prop].join(",")}});["approach","bearing","radius"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){path[prop].push(waypoint[prop])}else{path[prop].push("")}})});if(config.distributions){config.distributions.forEach(function(dist){path.distributions.push(dist.pickup+","+dist.dropoff)})}["approach","bearing","radius","distributions"].forEach(function(prop){if(path[prop].every(function(char){return char===""})){delete path[prop]}else{path[prop]=path[prop].join(";")}});var query=stringifyBooleans({geometries:config.geometries,language:config.language,overview:config.overview,roundtrip:config.roundtrip,steps:config.steps,source:config.source,destination:config.destination,distributions:path.distributions,approaches:path.approach,bearings:path.bearing,radiuses:path.radius});return this.client.createRequest({method:"GET",path:"/optimized-trips/v1/mapbox/:profile/:coordinates",params:{profile:config.profile||"driving",coordinates:path.coordinates.join(";")},query:objectClean_1(query)})};var optimization=createServiceFactory_1(Optimization);var polyline_1=createCommonjsModule(function(module){var polyline={};function py2_round(value){return Math.floor(Math.abs(value)+.5)*(value>=0?1:-1)}function encode(current,previous,factor){current=py2_round(current*factor);previous=py2_round(previous*factor);var coordinate=current-previous;coordinate<<=1;if(current-previous<0){coordinate=~coordinate}var output="";while(coordinate>=32){output+=String.fromCharCode((32|coordinate&31)+63);coordinate>>=5}output+=String.fromCharCode(coordinate+63);return output}polyline.decode=function(str,precision){var index=0,lat=0,lng=0,coordinates=[],shift=0,result=0,byte=null,latitude_change,longitude_change,factor=Math.pow(10,precision||5);while(index<str.length){byte=null;shift=0;result=0;do{byte=str.charCodeAt(index++)-63;result|=(byte&31)<<shift;shift+=5}while(byte>=32);latitude_change=result&1?~(result>>1):result>>1;shift=result=0;do{byte=str.charCodeAt(index++)-63;result|=(byte&31)<<shift;shift+=5}while(byte>=32);longitude_change=result&1?~(result>>1):result>>1;lat+=latitude_change;lng+=longitude_change;coordinates.push([lat/factor,lng/factor])}return coordinates};polyline.encode=function(coordinates,precision){if(!coordinates.length){return""}var factor=Math.pow(10,precision||5),output=encode(coordinates[0][0],0,factor)+encode(coordinates[0][1],0,factor);for(var i=1;i<coordinates.length;i++){var a=coordinates[i],b=coordinates[i-1];output+=encode(a[0],b[0],factor);output+=encode(a[1],b[1],factor)}return output};function flipped(coords){var flipped=[];for(var i=0;i<coords.length;i++){flipped.push(coords[i].slice().reverse())}return flipped}polyline.fromGeoJSON=function(geojson,precision){if(geojson&&geojson.type==="Feature"){geojson=geojson.geometry}if(!geojson||geojson.type!=="LineString"){throw new Error("Input must be a GeoJSON LineString")}return polyline.encode(flipped(geojson.coordinates),precision)};polyline.toGeoJSON=function(str,precision){var coords=polyline.decode(str,precision);return{type:"LineString",coordinates:flipped(coords)}};if(module.exports){module.exports=polyline}});var Static={};Static.getStaticImage=function(config){validator.assertShape({ownerId:validator.required(validator.string),styleId:validator.required(validator.string),width:validator.required(validator.range([1,1280])),height:validator.required(validator.range([1,1280])),position:validator.required(validator.oneOfType(validator.oneOf("auto"),validator.strictShape({coordinates:validator.required(validator.coordinates),zoom:validator.required(validator.range([0,20])),bearing:validator.range([0,360]),pitch:validator.range([0,60])}))),overlays:validator.arrayOf(validator.plainObject),highRes:validator.boolean,before_layer:validator.string,addlayer:validator.plainObject,setfilter:validator.plainArray,layer_id:validator.string,attribution:validator.boolean,logo:validator.boolean})(config);var encodedOverlay=(config.overlays||[]).map(function(overlayItem){if(overlayItem.marker){return encodeMarkerOverlay(overlayItem.marker)}if(overlayItem.path){return encodePathOverlay(overlayItem.path)}return encodeGeoJsonOverlay(overlayItem.geoJson)}).join(",");var encodedPosition=encodePosition(config.position);var encodedDimensions=config.width+"x"+config.height;if(config.highRes){encodedDimensions+="@2x"}var preEncodedUrlParts=[encodedOverlay,encodedPosition,encodedDimensions].filter(Boolean).join("/");var query={};if(config.attribution!==undefined){query.attribution=String(config.attribution)}if(config.logo!==undefined){query.logo=String(config.logo)}if(config.before_layer!==undefined){query.before_layer=config.before_layer}if(config.addlayer!==undefined){query.addlayer=JSON.stringify(config.addlayer)}if(config.setfilter!==undefined){query.setfilter=JSON.stringify(config.setfilter)}if(config.layer_id!==undefined){query.layer_id=config.layer_id}if(config.setfilter!==undefined&&config.layer_id===undefined){throw new Error("Must include layer_id in setfilter request")}if((config.setfilter!==undefined||config.addlayer!==undefined)&&config.position==="auto"&&config.overlays===undefined){throw new Error("Auto extent cannot be used with style parameters and no overlay")}if(config.addlayer!==undefined&&config.setfilter!==undefined){throw new Error("addlayer and setfilter cannot be used in the same request")}return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId/:styleId/static/"+preEncodedUrlParts,params:pick_1(config,["ownerId","styleId"]),query:query,encoding:"binary"})};function encodePosition(position){if(position==="auto")return"auto";return position.coordinates.concat([position.zoom,position.pitch&&!position.bearing?0:position.bearing,position.pitch===0?undefined:position.pitch]).filter(function(el){return el===0||el}).join(",")}function encodeMarkerOverlay(o){if(o.url){return encodeCustomMarkerOverlay(o)}return encodeSimpleMarkerOverlay(o)}function encodeSimpleMarkerOverlay(o){validator.assertShape({coordinates:validator.required(validator.coordinates),size:validator.oneOf("large","small"),label:validator.string,color:validator.string})(o);var result=o.size==="large"?"pin-l":"pin-s";if(o.label){result+="-"+String(o.label).toLowerCase()}if(o.color){result+="+"+sanitizeHexColor(o.color)}result+="("+o.coordinates.join(",")+")";return result}function encodeCustomMarkerOverlay(o){validator.assertShape({coordinates:validator.required(validator.coordinates),url:validator.required(validator.string)})(o);var result="url-"+encodeURIComponent(o.url);result+="("+o.coordinates.join(",")+")";return result}function encodePathOverlay(o){validator.assertShape({coordinates:validator.required(validator.arrayOf(validator.coordinates)),strokeWidth:validator.number,strokeColor:validator.string,strokeOpacity:validator.number,fillColor:validator.string,fillOpacity:validator.number})(o);if(o.strokeOpacity!==undefined&&o.strokeColor===undefined){throw new Error("strokeOpacity requires strokeColor")}if(o.fillColor!==undefined&&o.strokeColor===undefined){throw new Error("fillColor requires strokeColor")}if(o.fillOpacity!==undefined&&o.fillColor===undefined){throw new Error("fillOpacity requires fillColor")}var result="path";if(o.strokeWidth){result+="-"+o.strokeWidth}if(o.strokeColor){result+="+"+sanitizeHexColor(o.strokeColor)}if(o.strokeOpacity){result+="-"+o.strokeOpacity}if(o.fillColor){result+="+"+sanitizeHexColor(o.fillColor)}if(o.fillOpacity){result+="-"+o.fillOpacity}var reversedCoordinates=o.coordinates.map(function(c){return c.reverse()});var encodedPolyline=polyline_1.encode(reversedCoordinates);result+="("+encodeURIComponent(encodedPolyline)+")";return result}function encodeGeoJsonOverlay(o){validator.assert(validator.required(validator.plainObject))(o);return"geojson("+encodeURIComponent(JSON.stringify(o))+")"}function sanitizeHexColor(color){return color.replace(/^#/,"")}var _static=createServiceFactory_1(Static);var Styles={};Styles.getStyle=function(config){validator.assertShape({styleId:validator.required(validator.string),ownerId:validator.string,metadata:validator.boolean,draft:validator.boolean})(config);var query={};if(config.metadata){query.metadata=config.metadata}return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId/:styleId"+(config.draft?"/draft":""),params:pick_1(config,["ownerId","styleId"]),query:query})};Styles.createStyle=function(config){validator.assertShape({style:validator.plainObject,ownerId:validator.string})(config);return this.client.createRequest({method:"POST",path:"/styles/v1/:ownerId",params:pick_1(config,["ownerId"]),body:config.style})};Styles.updateStyle=function(config){validator.assertShape({styleId:validator.required(validator.string),style:validator.required(validator.plainObject),lastKnownModification:validator.date,ownerId:validator.string})(config);var headers={};if(config.lastKnownModification){headers["If-Unmodified-Since"]=new Date(config.lastKnownModification).toUTCString()}return this.client.createRequest({method:"PATCH",path:"/styles/v1/:ownerId/:styleId",params:pick_1(config,["styleId","ownerId"]),headers:headers,body:config.style})};Styles.deleteStyle=function(config){validator.assertShape({styleId:validator.required(validator.string),ownerId:validator.string})(config);return this.client.createRequest({method:"DELETE",path:"/styles/v1/:ownerId/:styleId",params:config})};Styles.listStyles=function(config){config=config||{};validator.assertShape({start:validator.string,ownerId:validator.string})(config);var query={};if(config.start){query.start=config.start}return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId",params:pick_1(config,["ownerId"]),query:query})};Styles.putStyleIcon=function(config){validator.assertShape({styleId:validator.required(validator.string),iconId:validator.required(validator.string),file:validator.file,ownerId:validator.string})(config);return this.client.createRequest({method:"PUT",path:"/styles/v1/:ownerId/:styleId/sprite/:iconId",params:pick_1(config,["ownerId","styleId","iconId"]),file:config.file})};Styles.deleteStyleIcon=function(config){validator.assertShape({styleId:validator.required(validator.string),iconId:validator.required(validator.string),ownerId:validator.string,draft:validator.boolean})(config);return this.client.createRequest({method:"DELETE",path:"/styles/v1/:ownerId/:styleId"+(config.draft?"/draft":"")+"/sprite/:iconId",params:pick_1(config,["ownerId","styleId","iconId"])})};Styles.getStyleSprite=function(config){validator.assertShape({styleId:validator.required(validator.string),format:validator.oneOf("json","png"),highRes:validator.boolean,ownerId:validator.string,draft:validator.boolean})(config);var format=config.format||"json";var fileName="/sprite"+(config.highRes?"@2x":"")+"."+format;return this.client.createRequest(immutable({method:"GET",path:"/styles/v1/:ownerId/:styleId"+(config.draft?"/draft":"")+fileName,params:pick_1(config,["ownerId","styleId"])},format==="png"?{encoding:"binary"}:{}))};Styles.getFontGlyphRange=function(config){validator.assertShape({fonts:validator.required(validator.oneOfType(validator.string,validator.arrayOf(validator.string))),start:validator.required(validator.number),end:validator.required(validator.number),ownerId:validator.string})(config);var fileName=config.start+"-"+config.end+".pbf";return this.client.createRequest({method:"GET",path:"/fonts/v1/:ownerId/:fontList/:fileName",params:immutable(pick_1(config,["ownerId"]),{fontList:[].concat(config.fonts),fileName:fileName}),encoding:"binary"})};Styles.getEmbeddableHtml=function(config){validator.assertShape({styleId:validator.required(validator.string),scrollZoom:validator.boolean,title:validator.boolean,ownerId:validator.string,draft:validator.boolean})(config);var fileName=config.styleId+(config.draft?"/draft":"")+".html";var query={};if(config.scrollZoom!==undefined){query.zoomwheel=String(config.scrollZoom)}if(config.title!==undefined){query.title=String(config.title)}return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId/"+fileName,params:pick_1(config,["ownerId"]),query:query})};var styles=createServiceFactory_1(Styles);var Tilequery={};Tilequery.listFeatures=function(config){validator.assertShape({mapIds:validator.required(validator.arrayOf(validator.string)),coordinates:validator.required(validator.coordinates),radius:validator.number,limit:validator.range([1,50]),dedupe:validator.boolean,geometry:validator.oneOf("polygon","linestring","point"),layers:validator.arrayOf(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/v4/:mapIds/tilequery/:coordinates.json",params:{mapIds:config.mapIds,coordinates:config.coordinates},query:pick_1(config,["radius","limit","dedupe","layers","geometry"])})};var tilequery=createServiceFactory_1(Tilequery);var Tilesets={};Tilesets.listTilesets=function(config){validator.assertShape({ownerId:validator.string,limit:validator.range([1,500]),sortBy:validator.oneOf("created","modified"),start:validator.string,type:validator.oneOf("raster","vector"),visibility:validator.oneOf("public","private")})(config);return this.client.createRequest({method:"GET",path:"/tilesets/v1/:ownerId",params:config?pick_1(config,["ownerId"]):{},query:config?pick_1(config,["limit","sortBy","start","type","visibility"]):{}})};Tilesets.deleteTileset=function(config){validator.assertShape({tilesetId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/tilesets/v1/:tilesetId",params:pick_1(config,["tilesetId"])})};Tilesets.tileJSONMetadata=function(config){validator.assertShape({tilesetId:validator.required(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/v4/:tilesetId.json",params:pick_1(config,["tilesetId"])})};Tilesets.createTilesetSource=function(config){validator.assertShape({id:validator.required(validator.string),file:validator.required(validator.file),ownerId:validator.string})(config);return this.client.createRequest({method:"POST",path:"/tilesets/v1/sources/:ownerId/:id",params:pick_1(config,["ownerId","id"]),file:config.file,sendFileAs:"form"})};Tilesets.getTilesetSource=function(config){validator.assertShape({id:validator.required(validator.string),ownerId:validator.string})(config);return this.client.createRequest({method:"GET",path:"/tilesets/v1/sources/:ownerId/:id",params:pick_1(config,["ownerId","id"])})};Tilesets.listTilesetSources=function(config){validator.assertShape({ownerId:validator.string})(config);return this.client.createRequest({method:"GET",path:"/tilesets/v1/sources/:ownerId",params:config?pick_1(config,["ownerId"]):{}})};Tilesets.deleteTilesetSource=function(config){validator.assertShape({id:validator.required(validator.string),ownerId:validator.string})(config);return this.client.createRequest({method:"DELETE",path:"/tilesets/v1/sources/:ownerId/:id",params:pick_1(config,["ownerId","id"])})};Tilesets.createTileset=function(config){validator.assertShape({tilesetId:validator.required(validator.string),recipe:validator.required(validator.plainObject),name:validator.required(validator.string),private:validator.boolean,description:validator.string})(config);return this.client.createRequest({method:"POST",path:"/tilesets/v1/:tilesetId",params:pick_1(config,["tilesetId"]),body:pick_1(config,["recipe","name","private","description"])})};Tilesets.publishTileset=function(config){validator.assertShape({tilesetId:validator.required(validator.string)})(config);return this.client.createRequest({method:"POST",path:"/tilesets/v1/:tilesetId/publish",params:pick_1(config,["tilesetId"])})};Tilesets.tilesetStatus=function(config){validator.assertShape({tilesetId:validator.required(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/tilesets/v1/:tilesetId/status",params:pick_1(config,["tilesetId"])})};Tilesets.tilesetJob=function(config){validator.assertShape({tilesetId:validator.required(validator.string),jobId:validator.required(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/tilesets/v1/:tilesetId/jobs/:jobId",params:pick_1(config,["tilesetId","jobId"])})};Tilesets.listTilesetJobs=function(config){validator.assertShape({tilesetId:validator.required(validator.string),stage:validator.oneOf("processing","queued","success","failed")})(config);return this.client.createRequest({method:"GET",path:"/tilesets/v1/:tilesetId/jobs",params:pick_1(config,["tilesetId"]),query:pick_1(config,["stage"])})};Tilesets.getTilesetsQueue=function(){return this.client.createRequest({method:"PUT",path:"/tilesets/v1/queue"})};Tilesets.validateRecipe=function(config){validator.assertShape({recipe:validator.required(validator.plainObject)})(config);return this.client.createRequest({method:"PUT",path:"/tilesets/v1/validateRecipe",body:config.recipe})};Tilesets.getRecipe=function(config){validator.assertShape({tilesetId:validator.required(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/tilesets/v1/:tilesetId/recipe",params:pick_1(config,["tilesetId"])})};Tilesets.updateRecipe=function(config){validator.assertShape({tilesetId:validator.required(validator.string),recipe:validator.required(validator.plainObject)})(config);return this.client.createRequest({method:"PATCH",path:"/tilesets/v1/:tilesetId/recipe",params:pick_1(config,["tilesetId"]),body:config.recipe})};var tilesets=createServiceFactory_1(Tilesets);var Tokens={};Tokens.listTokens=function(){return this.client.createRequest({method:"GET",path:"/tokens/v2/:ownerId"})};Tokens.createToken=function(config){config=config||{};validator.assertShape({note:validator.string,scopes:validator.arrayOf(validator.string),resources:validator.arrayOf(validator.string),allowedUrls:validator.arrayOf(validator.string)})(config);var body={};body.scopes=config.scopes||[];if(config.note!==undefined){body.note=config.note}if(config.resources){body.resources=config.resources}if(config.allowedUrls){body.allowedUrls=config.allowedUrls}return this.client.createRequest({method:"POST",path:"/tokens/v2/:ownerId",params:pick_1(config,["ownerId"]),body:body})};Tokens.createTemporaryToken=function(config){validator.assertShape({expires:validator.required(validator.date),scopes:validator.required(validator.arrayOf(validator.string))})(config);return this.client.createRequest({method:"POST",path:"/tokens/v2/:ownerId",params:pick_1(config,["ownerId"]),body:{expires:new Date(config.expires).toISOString(),scopes:config.scopes}})};Tokens.updateToken=function(config){validator.assertShape({tokenId:validator.required(validator.string),note:validator.string,scopes:validator.arrayOf(validator.string),resources:validator.arrayOf(validator.string),allowedUrls:validator.arrayOf(validator.string)})(config);var body={};if(config.scopes){body.scopes=config.scopes}if(config.note!==undefined){body.note=config.note}if(config.resources||config.resources===null){body.resources=config.resources}if(config.allowedUrls||config.allowedUrls===null){body.allowedUrls=config.allowedUrls}return this.client.createRequest({method:"PATCH",path:"/tokens/v2/:ownerId/:tokenId",params:pick_1(config,["ownerId","tokenId"]),body:body})};Tokens.getToken=function(){return this.client.createRequest({method:"GET",path:"/tokens/v2"})};Tokens.deleteToken=function(config){validator.assertShape({tokenId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/tokens/v2/:ownerId/:tokenId",params:pick_1(config,["ownerId","tokenId"])})};Tokens.listScopes=function(){return this.client.createRequest({method:"GET",path:"/scopes/v1/:ownerId"})};var tokens=createServiceFactory_1(Tokens);var Uploads={};Uploads.listUploads=function(config){validator.assertShape({reverse:validator.boolean})(config);return this.client.createRequest({method:"GET",path:"/uploads/v1/:ownerId",query:config})};Uploads.createUploadCredentials=function(){return this.client.createRequest({method:"POST",path:"/uploads/v1/:ownerId/credentials"})};Uploads.createUpload=function(config){validator.assertShape({mapId:validator.required(validator.string),url:validator.required(validator.string),tilesetName:validator.string})(config);return this.client.createRequest({method:"POST",path:"/uploads/v1/:ownerId",body:{tileset:config.mapId,url:config.url,name:config.tilesetName}})};Uploads.getUpload=function(config){validator.assertShape({uploadId:validator.required(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/uploads/v1/:ownerId/:uploadId",params:config})};Uploads.deleteUpload=function(config){validator.assertShape({uploadId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/uploads/v1/:ownerId/:uploadId",params:config})};var uploads=createServiceFactory_1(Uploads);var Isochrone={};Isochrone.getContours=function(config){validator.assertShape({profile:validator.oneOf("driving","walking","cycling"),coordinates:validator.coordinates,minutes:validator.arrayOf(validator.number),colors:validator.arrayOf(validator.string),polygons:validator.boolean,denoise:validator.number,generalize:validator.number})(config);config.profile=config.profile||"driving";var minutesCount=config.minutes.length;if(minutesCount<1||minutesCount>4){throw new Error("minutes must contain between 1 and 4 contour values")}if(config.colors!==undefined&&config.minutes!==undefined&&config.colors.length!==config.minutes.length){throw new Error("colors should have the same number of entries as minutes")}if(!config.minutes.every(function(minute){return minute<=60})){throw new Error("minutes must be less than 60")}if(config.generalize&&config.generalize<0){throw new Error("generalize tolerance must be a positive number")}if(config.colors){config.colors=config.colors.map(function(color){if(color[0]==="#")return color.substring(1);return color})}var query=stringifyBooleans({contours_minutes:config.minutes.join(","),contours_colors:config.colors?config.colors.join(","):null,polygons:config.polygons,denoise:config.denoise,generalize:config.generalize});return this.client.createRequest({method:"GET",path:"/isochrone/v1/mapbox/:profile/:coordinates",params:{profile:config.profile,coordinates:config.coordinates.join(",")},query:objectClean_1(query)})};var isochrone=createServiceFactory_1(Isochrone);function mapboxSdk(options){var client=browserClient(options);client.datasets=datasets(client);client.directions=directions(client);client.geocoding=geocoding(client);client.mapMatching=mapMatching(client);client.matrix=matrix(client);client.optimization=optimization(client);client.static=_static(client);client.styles=styles(client);client.tilequery=tilequery(client);client.tilesets=tilesets(client);client.tokens=tokens(client);client.uploads=uploads(client);client.isochrone=isochrone(client);return client}var bundle=mapboxSdk;return bundle}); |
Sorry, the diff of this file is too big to display
504539
13992
8
+ Addedform-data@^3.0.0
+ Addedasynckit@0.4.0(transitive)
+ Addedcall-bind-apply-helpers@1.0.2(transitive)
+ Addedcombined-stream@1.0.8(transitive)
+ Addeddelayed-stream@1.0.0(transitive)
+ Addeddunder-proto@1.0.1(transitive)
+ Addedes-define-property@1.0.1(transitive)
+ Addedes-errors@1.3.0(transitive)
+ Addedes-object-atoms@1.1.1(transitive)
+ Addedes-set-tostringtag@2.1.0(transitive)
+ Addedform-data@3.0.3(transitive)
+ Addedget-intrinsic@1.3.0(transitive)
+ Addedget-proto@1.0.1(transitive)
+ Addedgopd@1.2.0(transitive)
+ Addedhas-symbols@1.1.0(transitive)
+ Addedhas-tostringtag@1.0.2(transitive)
+ Addedmath-intrinsics@1.1.0(transitive)
+ Addedmime-db@1.52.0(transitive)
+ Addedmime-types@2.1.35(transitive)