-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathmapbox.js
618 lines (518 loc) · 21.4 KB
/
mapbox.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
// @flow
/***** START WARNING REMOVAL OR MODIFICATION OF THE
* FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******
* The following code is used to access Mapbox's APIs. Removal or modification
* of this code can result in higher fees and/or
* termination of your account with Mapbox.
*
* Under the Mapbox Terms of Service, you may not use this code to access Mapbox
* Mapping APIs other than through Mapbox SDKs.
*
* The Mapping APIs documentation is available at https://docs.mapbox.com/api/maps/#maps
* and the Mapbox Terms of Service are available at https://www.mapbox.com/tos/
******************************************************************************/
import config from './config.js';
import window from './window.js';
import webpSupported from './webp_supported.js';
import {createSkuToken, SKU_ID} from './sku_token.js';
import {version as sdkVersion} from '../../package.json';
import {uuid, validateUuid, storageAvailable, b64DecodeUnicode, b64EncodeUnicode, warnOnce, extend} from './util.js';
import {postData, ResourceType, getData} from './ajax.js';
import type {RequestParameters} from './ajax.js';
import type {Cancelable} from '../types/cancelable.js';
import type {TileJSON} from '../types/tilejson.js';
type ResourceTypeEnum = $Keys<typeof ResourceType>;
export type RequestTransformFunction = (url: string, resourceType?: ResourceTypeEnum) => RequestParameters;
type UrlObject = {|
protocol: string,
authority: string,
path: string,
params: Array<string>
|};
type EventCallback = (err: ?Error) => void;
export const AUTH_ERR_MSG: string = 'NO_ACCESS_TOKEN';
export class RequestManager {
_skuToken: string;
_skuTokenExpiresAt: number;
_transformRequestFn: ?RequestTransformFunction;
_customAccessToken: ?string;
_silenceAuthErrors: boolean;
constructor(transformRequestFn?: RequestTransformFunction, customAccessToken?: string, silenceAuthErrors: ?boolean) {
this._transformRequestFn = transformRequestFn;
this._customAccessToken = customAccessToken;
this._silenceAuthErrors = !!silenceAuthErrors;
this._createSkuToken();
}
_createSkuToken() {
const skuToken = createSkuToken();
this._skuToken = skuToken.token;
this._skuTokenExpiresAt = skuToken.tokenExpiresAt;
}
_isSkuTokenExpired(): boolean {
return Date.now() > this._skuTokenExpiresAt;
}
transformRequest(url: string, type: ResourceTypeEnum): RequestParameters {
if (this._transformRequestFn) {
return this._transformRequestFn(url, type) || {url};
}
return {url};
}
normalizeStyleURL(url: string, accessToken?: string): string {
if (!isMapboxURL(url)) return url;
const urlObject = parseUrl(url);
urlObject.path = `/styles/v1${urlObject.path}`;
return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);
}
normalizeGlyphsURL(url: string, accessToken?: string): string {
if (!isMapboxURL(url)) return url;
const urlObject = parseUrl(url);
urlObject.path = `/fonts/v1${urlObject.path}`;
return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);
}
normalizeSourceURL(url: string, accessToken?: ?string, language?: ?string, worldview?: ?string): string {
if (!isMapboxURL(url)) return url;
const urlObject = parseUrl(url);
urlObject.path = `/v4/${urlObject.authority}.json`;
// TileJSON requests need a secure flag appended to their URLs so
// that the server knows to send SSL-ified resource references.
urlObject.params.push('secure');
if (language) {
urlObject.params.push(`language=${language}`);
}
if (worldview) {
urlObject.params.push(`worldview=${worldview}`);
}
return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);
}
normalizeSpriteURL(url: string, format: string, extension: string, accessToken?: string): string {
const urlObject = parseUrl2(url);
if (!isMapboxURL(url)) {
if (urlObject.protocol === undefined) {
return `${url}${format}${extension}`;
} else {
urlObject.path += `${format}${extension}`;
return formatUrl(urlObject);
}
}
urlObject.path = `/styles/v1${urlObject.path}/sprite${format}${extension}`;
return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);
}
normalizeTileURL(tileURL: string, use2x?: boolean, rasterTileSize?: number): string {
if (this._isSkuTokenExpired()) {
this._createSkuToken();
}
if (tileURL && !isMapboxURL(tileURL)) return tileURL;
const urlObject = parseUrl(tileURL);
const imageExtensionRe = /(\.(png|jpg)\d*)(?=$)/;
const extension = webpSupported.supported ? '.webp' : '$1';
// The v4 mapbox tile API supports 512x512 image tiles but they must be requested as '@2x' tiles.
const use2xAs512 = rasterTileSize && urlObject.authority !== 'raster' && rasterTileSize === 512;
const suffix = use2x || use2xAs512 ? '@2x' : '';
urlObject.path = urlObject.path.replace(imageExtensionRe, `${suffix}${extension}`);
if (urlObject.authority === 'raster') {
urlObject.path = `/${config.RASTER_URL_PREFIX}${urlObject.path}`;
} else {
const tileURLAPIPrefixRe = /^.+\/v4\//;
urlObject.path = urlObject.path.replace(tileURLAPIPrefixRe, '/');
urlObject.path = `/${config.TILE_URL_VERSION}${urlObject.path}`;
}
const accessToken = this._customAccessToken || getAccessToken(urlObject.params) || config.ACCESS_TOKEN;
if (config.REQUIRE_ACCESS_TOKEN && accessToken && this._skuToken) {
urlObject.params.push(`sku=${this._skuToken}`);
}
return this._makeAPIURL(urlObject, accessToken);
}
canonicalizeTileURL(url: string, removeAccessToken: boolean): string {
// matches any file extension specified by a dot and one or more alphanumeric characters
const extensionRe = /\.[\w]+$/;
const urlObject = parseUrl(url);
// Make sure that we are dealing with a valid Mapbox tile URL.
// Has to begin with /v4/ or /raster/v1, with a valid filename + extension
if (!urlObject.path.match(/^(\/v4\/|\/raster\/v1\/)/) || !urlObject.path.match(extensionRe)) {
// Not a proper Mapbox tile URL.
return url;
}
// Reassemble the canonical URL from the parts we've parsed before.
let result = "mapbox://";
if (urlObject.path.match(/^\/raster\/v1\//)) {
// If the tile url has /raster/v1/, make the final URL mapbox://raster/....
const rasterPrefix = `/${config.RASTER_URL_PREFIX}/`;
result += `raster/${urlObject.path.replace(rasterPrefix, '')}`;
} else {
const tilesPrefix = `/${config.TILE_URL_VERSION}/`;
result += `tiles/${urlObject.path.replace(tilesPrefix, '')}`;
}
// Append the query string, minus the access token parameter.
let params = urlObject.params;
if (removeAccessToken) {
params = params.filter(p => !p.match(/^access_token=/));
}
if (params.length) result += `?${params.join('&')}`;
return result;
}
canonicalizeTileset(tileJSON: TileJSON, sourceURL?: string): Array<string> {
const removeAccessToken = sourceURL ? isMapboxURL(sourceURL) : false;
const canonical = [];
for (const url of tileJSON.tiles || []) {
if (isMapboxHTTPURL(url)) {
canonical.push(this.canonicalizeTileURL(url, removeAccessToken));
} else {
canonical.push(url);
}
}
return canonical;
}
_makeAPIURL(urlObject: UrlObject, accessToken: string | null | void): string {
const help = 'See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes';
const apiUrlObject = parseUrl(config.API_URL);
urlObject.protocol = apiUrlObject.protocol;
urlObject.authority = apiUrlObject.authority;
if (urlObject.protocol === 'http') {
const i = urlObject.params.indexOf('secure');
if (i >= 0) urlObject.params.splice(i, 1);
}
if (apiUrlObject.path !== '/') {
urlObject.path = `${apiUrlObject.path}${urlObject.path}`;
}
if (!config.REQUIRE_ACCESS_TOKEN) return formatUrl(urlObject);
accessToken = accessToken || config.ACCESS_TOKEN;
if (!this._silenceAuthErrors) {
if (!accessToken)
throw new Error(`An API access token is required to use Mapbox GL. ${help}`);
if (accessToken[0] === 's')
throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${help}`);
}
urlObject.params = urlObject.params.filter((d) => d.indexOf('access_token') === -1);
urlObject.params.push(`access_token=${accessToken || ''}`);
return formatUrl(urlObject);
}
}
export function isMapboxURL(url: string): boolean {
return url.indexOf('mapbox:') === 0;
}
export function isMapboxHTTPURL(url: string): boolean {
return config.API_URL_REGEX.test(url);
}
export function hasCacheDefeatingSku(url: string): boolean {
return url.indexOf('sku=') > 0 && isMapboxHTTPURL(url);
}
function getAccessToken(params: Array<string>): string | null {
for (const param of params) {
const match = param.match(/^access_token=(.*)$/);
if (match) {
return match[1];
}
}
return null;
}
const urlRe = /^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;
function parseUrl(url: string): UrlObject {
const parts = url.match(urlRe);
if (!parts) {
throw new Error('Unable to parse URL object');
}
return {
protocol: parts[1],
authority: parts[2],
path: parts[3] || '/',
params: parts[4] ? parts[4].split('&') : []
};
}
const urlRe2 = /^((\w+):\/\/)?([^/?]*)(\/[^?]+)?\??(.+)?/;
function parseUrl2(url: string): UrlObject {
const parts = url.match(urlRe2);
if (!parts) {
throw new Error('Unable to parse URL object');
}
return {
protocol: parts[2],
authority: parts[3],
path: parts[4] || '/',
params: parts[5] ? parts[5].split('&') : []
};
}
function formatUrl(obj: UrlObject): string {
const params = obj.params.length ? `?${obj.params.join('&')}` : '';
return `${obj.protocol}://${obj.authority}${obj.path}${params}`;
}
const telemEventKey = 'mapbox.eventData';
function parseAccessToken(accessToken: ?string) {
if (!accessToken) {
return null;
}
const parts = accessToken.split('.');
if (!parts || parts.length !== 3) {
return null;
}
try {
const jsonData = JSON.parse(b64DecodeUnicode(parts[1]));
return jsonData;
} catch (e) {
return null;
}
}
type TelemetryEventType = 'appUserTurnstile' | 'map.load' | 'map.auth';
class TelemetryEvent {
eventData: any;
anonId: ?string;
queue: Array<any>;
type: TelemetryEventType;
pendingRequest: ?Cancelable;
_customAccessToken: ?string;
constructor(type: TelemetryEventType) {
this.type = type;
this.anonId = null;
this.eventData = {};
this.queue = [];
this.pendingRequest = null;
}
getStorageKey(domain: ?string): string {
const tokenData = parseAccessToken(config.ACCESS_TOKEN);
let u = '';
if (tokenData && tokenData['u']) {
u = b64EncodeUnicode(tokenData['u']);
} else {
u = config.ACCESS_TOKEN || '';
}
return domain ?
`${telemEventKey}.${domain}:${u}` :
`${telemEventKey}:${u}`;
}
fetchEventData() {
const isLocalStorageAvailable = storageAvailable('localStorage');
const storageKey = this.getStorageKey();
const uuidKey = this.getStorageKey('uuid');
if (isLocalStorageAvailable) {
//Retrieve cached data
try {
const data = window.localStorage.getItem(storageKey);
if (data) {
this.eventData = JSON.parse(data);
}
const uuid = window.localStorage.getItem(uuidKey);
if (uuid) this.anonId = uuid;
} catch (e) {
warnOnce('Unable to read from LocalStorage');
}
}
}
saveEventData() {
const isLocalStorageAvailable = storageAvailable('localStorage');
const storageKey = this.getStorageKey();
const uuidKey = this.getStorageKey('uuid');
if (isLocalStorageAvailable) {
try {
window.localStorage.setItem(uuidKey, this.anonId);
if (Object.keys(this.eventData).length >= 1) {
window.localStorage.setItem(storageKey, JSON.stringify(this.eventData));
}
} catch (e) {
warnOnce('Unable to write to LocalStorage');
}
}
}
processRequests(_: ?string) {}
/*
* If any event data should be persisted after the POST request, the callback should modify eventData`
* to the values that should be saved. For this reason, the callback should be invoked prior to the call
* to TelemetryEvent#saveData
*/
postEvent(timestamp: number, additionalPayload: {[_: string]: any}, callback: EventCallback, customAccessToken?: ?string) {
if (!config.EVENTS_URL) return;
const eventsUrlObject: UrlObject = parseUrl(config.EVENTS_URL);
eventsUrlObject.params.push(`access_token=${customAccessToken || config.ACCESS_TOKEN || ''}`);
const payload: Object = {
event: this.type,
created: new Date(timestamp).toISOString(),
sdkIdentifier: 'mapbox-gl-js',
sdkVersion,
skuId: SKU_ID,
userId: this.anonId
};
const finalPayload = additionalPayload ? extend(payload, additionalPayload) : payload;
const request: RequestParameters = {
url: formatUrl(eventsUrlObject),
headers: {
'Content-Type': 'text/plain' //Skip the pre-flight OPTIONS request
},
body: JSON.stringify([finalPayload])
};
this.pendingRequest = postData(request, (error) => {
this.pendingRequest = null;
callback(error);
this.saveEventData();
this.processRequests(customAccessToken);
});
}
queueRequest(event: number | {id: number, timestamp: number}, customAccessToken?: ?string) {
this.queue.push(event);
this.processRequests(customAccessToken);
}
}
export class MapLoadEvent extends TelemetryEvent {
+success: {[_: number]: boolean};
skuToken: string;
errorCb: EventCallback;
constructor() {
super('map.load');
this.success = {};
this.skuToken = '';
}
postMapLoadEvent(mapId: number, skuToken: string, customAccessToken: ?string, callback: EventCallback) {
this.skuToken = skuToken;
this.errorCb = callback;
if (config.EVENTS_URL) {
if (customAccessToken || config.ACCESS_TOKEN) {
this.queueRequest({id: mapId, timestamp: Date.now()}, customAccessToken);
} else {
this.errorCb(new Error(AUTH_ERR_MSG));
}
}
}
processRequests(customAccessToken?: ?string) {
if (this.pendingRequest || this.queue.length === 0) return;
const {id, timestamp} = this.queue.shift();
// Only one load event should fire per map
if (id && this.success[id]) return;
if (!this.anonId) {
this.fetchEventData();
}
if (!validateUuid(this.anonId)) {
this.anonId = uuid();
}
this.postEvent(timestamp, {skuToken: this.skuToken}, (err) => {
if (err) {
this.errorCb(err);
} else {
if (id) this.success[id] = true;
}
}, customAccessToken);
}
}
export class MapSessionAPI extends TelemetryEvent {
+success: {[_: number]: boolean};
skuToken: string;
errorCb: EventCallback;
constructor() {
super('map.auth');
this.success = {};
this.skuToken = '';
}
getSession(timestamp: number, token: string, callback: EventCallback, customAccessToken?: ?string) {
if (!config.API_URL || !config.SESSION_PATH) return;
const authUrlObject: UrlObject = parseUrl(config.API_URL + config.SESSION_PATH);
authUrlObject.params.push(`sku=${token || ''}`);
authUrlObject.params.push(`access_token=${customAccessToken || config.ACCESS_TOKEN || ''}`);
const request: RequestParameters = {
url: formatUrl(authUrlObject),
headers: {
'Content-Type': 'text/plain', //Skip the pre-flight OPTIONS request
}
};
this.pendingRequest = getData(request, (error) => {
this.pendingRequest = null;
callback(error);
this.saveEventData();
this.processRequests(customAccessToken);
});
}
getSessionAPI(mapId: number, skuToken: string, customAccessToken: ?string, callback: EventCallback) {
this.skuToken = skuToken;
this.errorCb = callback;
if (config.SESSION_PATH && config.API_URL) {
if (customAccessToken || config.ACCESS_TOKEN) {
this.queueRequest({id: mapId, timestamp: Date.now()}, customAccessToken);
} else {
this.errorCb(new Error(AUTH_ERR_MSG));
}
}
}
processRequests(customAccessToken?: ?string) {
if (this.pendingRequest || this.queue.length === 0) return;
const {id, timestamp} = this.queue.shift();
// Only one load event should fire per map
if (id && this.success[id]) return;
this.getSession(timestamp, this.skuToken, (err) => {
if (err) {
this.errorCb(err);
} else {
if (id) this.success[id] = true;
}
}, customAccessToken);
}
}
export class TurnstileEvent extends TelemetryEvent {
constructor(customAccessToken?: ?string) {
super('appUserTurnstile');
this._customAccessToken = customAccessToken;
}
postTurnstileEvent(tileUrls: Array<string>, customAccessToken?: ?string) {
//Enabled only when Mapbox Access Token is set and a source uses
// mapbox tiles.
if (config.EVENTS_URL &&
config.ACCESS_TOKEN &&
Array.isArray(tileUrls) &&
tileUrls.some(url => isMapboxURL(url) || isMapboxHTTPURL(url))) {
this.queueRequest(Date.now(), customAccessToken);
}
}
processRequests(customAccessToken?: ?string) {
if (this.pendingRequest || this.queue.length === 0) {
return;
}
if (!this.anonId || !this.eventData.lastSuccess || !this.eventData.tokenU) {
//Retrieve cached data
this.fetchEventData();
}
const tokenData = parseAccessToken(config.ACCESS_TOKEN);
const tokenU = tokenData ? tokenData['u'] : config.ACCESS_TOKEN;
//Reset event data cache if the access token owner changed.
let dueForEvent = tokenU !== this.eventData.tokenU;
if (!validateUuid(this.anonId)) {
this.anonId = uuid();
dueForEvent = true;
}
const nextUpdate = this.queue.shift();
// Record turnstile event once per calendar day.
if (this.eventData.lastSuccess) {
const lastUpdate = new Date(this.eventData.lastSuccess);
const nextDate = new Date(nextUpdate);
const daysElapsed = (nextUpdate - this.eventData.lastSuccess) / (24 * 60 * 60 * 1000);
dueForEvent = dueForEvent || daysElapsed >= 1 || daysElapsed < -1 || lastUpdate.getDate() !== nextDate.getDate();
} else {
dueForEvent = true;
}
if (!dueForEvent) {
this.processRequests();
return;
}
this.postEvent(nextUpdate, {"enabled.telemetry": false}, (err) => {
if (!err) {
this.eventData.lastSuccess = nextUpdate;
this.eventData.tokenU = tokenU;
}
}, customAccessToken);
}
}
const turnstileEvent_ = new TurnstileEvent();
export const postTurnstileEvent: (tileUrls: Array<string>, customAccessToken?: ?string) => void = turnstileEvent_.postTurnstileEvent.bind(turnstileEvent_);
const mapLoadEvent_ = new MapLoadEvent();
export const postMapLoadEvent: (number, string, ?string, EventCallback) => void = mapLoadEvent_.postMapLoadEvent.bind(mapLoadEvent_);
const mapSessionAPI_ = new MapSessionAPI();
export const getMapSessionAPI: (number, string, ?string, EventCallback) => void = mapSessionAPI_.getSessionAPI.bind(mapSessionAPI_);
const authenticatedMaps = new Set();
export function storeAuthState(gl: WebGLRenderingContext, state: boolean) {
if (state) {
authenticatedMaps.add(gl);
} else {
authenticatedMaps.delete(gl);
}
}
export function isMapAuthenticated(gl: WebGLRenderingContext): boolean {
return authenticatedMaps.has(gl);
}
export function removeAuthState(gl: WebGLRenderingContext) {
authenticatedMaps.delete(gl);
}
/***** END WARNING - REMOVAL OR MODIFICATION OF THE
PRECEDING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******/