@tangram.gl/basemap-layers 0.0.1 → 10.0.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/README.md +12 -7
  2. package/THIRD-PARTY-NOTICES.md +7 -5
  3. package/dist/geojson-task-worker.js +3166 -0
  4. package/dist/geojson-task-worker.js.map +6 -0
  5. package/dist/geojson-worker.js +1089 -7
  6. package/dist/geojson-worker.js.map +3 -3
  7. package/dist/index.cjs +9588 -2093
  8. package/dist/index.cjs.map +3 -3
  9. package/dist/index.js +9599 -2090
  10. package/dist/index.js.map +3 -3
  11. package/dist/map-style.cjs +456 -20
  12. package/dist/map-style.cjs.map +3 -3
  13. package/dist/map-style.js +456 -19
  14. package/dist/map-style.js.map +2 -2
  15. package/dist/types/basemap-error.d.ts +52 -0
  16. package/dist/types/basemap-layer.d.ts +378 -25
  17. package/dist/types/basemap-protocol.d.ts +91 -0
  18. package/dist/types/basemap-request.d.ts +73 -0
  19. package/dist/types/circle-layer.d.ts +65 -8
  20. package/dist/types/color-relief-layer.d.ts +184 -0
  21. package/dist/types/dem-pixels.d.ts +40 -0
  22. package/dist/types/feature-state.d.ts +55 -0
  23. package/dist/types/fill-extrusion-lighting-extension.d.ts +1 -2
  24. package/dist/types/fill-outline-extension.d.ts +2 -3
  25. package/dist/types/fill-pattern.d.ts +35 -3
  26. package/dist/types/fill-style-extensions.d.ts +11 -59
  27. package/dist/types/geojson-resource.d.ts +18 -0
  28. package/dist/types/geojson-source.d.ts +13 -2
  29. package/dist/types/geojson-task-handler.d.ts +2 -0
  30. package/dist/types/geojson-task.d.ts +26 -0
  31. package/dist/types/geojson-tiler.d.ts +29 -2
  32. package/dist/types/geojson-worker.d.ts +5 -1
  33. package/dist/types/globe-horizon-extension.d.ts +2 -45
  34. package/dist/types/globe-layers.d.ts +141 -45
  35. package/dist/types/globe-line-angle-extension.d.ts +20 -17
  36. package/dist/types/glyph-store.d.ts +10 -1
  37. package/dist/types/heatmap-layer.d.ts +99 -0
  38. package/dist/types/hillshade-layer.d.ts +159 -27
  39. package/dist/types/icon-text-fit.d.ts +92 -0
  40. package/dist/types/image-source-layer.d.ts +142 -0
  41. package/dist/types/index.d.ts +25 -1
  42. package/dist/types/line-blur-extension.d.ts +3 -11
  43. package/dist/types/line-dash-extension.d.ts +53 -0
  44. package/dist/types/line-gradient-extension.d.ts +69 -0
  45. package/dist/types/line-metrics.d.ts +24 -0
  46. package/dist/types/line-pattern-extension.d.ts +50 -0
  47. package/dist/types/line-shape-extension.d.ts +76 -0
  48. package/dist/types/map-style-loader.d.ts +1 -1
  49. package/dist/types/map-style.d.ts +2 -2
  50. package/dist/types/mvt-label-layer.d.ts +111 -20
  51. package/dist/types/pmtiles-source.d.ts +38 -0
  52. package/dist/types/projected-background-layer.d.ts +63 -0
  53. package/dist/types/projected-bitmap-layer.d.ts +58 -0
  54. package/dist/types/projected-tile-data.d.ts +16 -0
  55. package/dist/types/projected-tile-selection.d.ts +72 -0
  56. package/dist/types/projected-tileset.d.ts +92 -0
  57. package/dist/types/projected-viewport.d.ts +76 -0
  58. package/dist/types/raster-color-extension.d.ts +4 -7
  59. package/dist/types/raster-fade.d.ts +155 -0
  60. package/dist/types/raster-tile-fingerprint.d.ts +11 -0
  61. package/dist/types/raster-tile-loader.d.ts +80 -0
  62. package/dist/types/shader-injection-plugin.d.ts +8 -0
  63. package/dist/types/source-features.d.ts +58 -0
  64. package/dist/types/source-tiles.d.ts +32 -0
  65. package/dist/types/sprite.d.ts +37 -3
  66. package/dist/types/stretch-icon-layer.d.ts +28 -0
  67. package/dist/types/style-accessor.d.ts +50 -12
  68. package/dist/types/style-expression.d.ts +22 -2
  69. package/dist/types/style-resolver.d.ts +47 -2
  70. package/dist/types/terrain-query.d.ts +39 -0
  71. package/dist/types/zoom-load-gate.d.ts +22 -0
  72. package/dist/types/zoom-paint-extension.d.ts +80 -11
  73. package/package.json +24 -21
  74. package/src/basemap-error.ts +82 -0
  75. package/src/basemap-layer.ts +1289 -101
  76. package/src/basemap-protocol.ts +353 -0
  77. package/src/basemap-request.ts +212 -0
  78. package/src/circle-layer.ts +430 -54
  79. package/src/color-relief-layer.ts +572 -0
  80. package/src/dem-pixels.ts +174 -0
  81. package/src/feature-state.ts +164 -0
  82. package/src/fill-extrusion-lighting-extension.ts +126 -9
  83. package/src/fill-outline-extension.ts +4 -4
  84. package/src/fill-pattern.ts +87 -9
  85. package/src/fill-style-extensions.ts +114 -44
  86. package/src/geojson-resource.ts +58 -0
  87. package/src/geojson-source.ts +106 -85
  88. package/src/geojson-task-handler.ts +11 -0
  89. package/src/geojson-task-worker.ts +8 -0
  90. package/src/geojson-task.ts +34 -0
  91. package/src/geojson-tiler.ts +270 -4
  92. package/src/geojson-worker.ts +36 -6
  93. package/src/globe-horizon-extension.ts +14 -4
  94. package/src/globe-layers.ts +1905 -406
  95. package/src/globe-line-angle-extension.ts +183 -23
  96. package/src/glyph-store.ts +28 -6
  97. package/src/heatmap-layer.ts +591 -0
  98. package/src/hillshade-layer.ts +309 -88
  99. package/src/icon-text-fit.ts +358 -0
  100. package/src/image-source-layer.ts +380 -0
  101. package/src/index.ts +58 -1
  102. package/src/line-blur-extension.ts +14 -12
  103. package/src/line-dash-extension.ts +303 -0
  104. package/src/line-gradient-extension.ts +191 -0
  105. package/src/line-metrics.ts +90 -0
  106. package/src/line-pattern-extension.ts +173 -0
  107. package/src/line-shape-extension.ts +272 -0
  108. package/src/map-style-loader.ts +5 -4
  109. package/src/map-style.ts +2 -1
  110. package/src/mvt-label-layer.ts +568 -144
  111. package/src/pmtiles-source.ts +276 -0
  112. package/src/projected-background-layer.ts +202 -0
  113. package/src/projected-bitmap-layer.ts +262 -0
  114. package/src/projected-tile-data.ts +132 -0
  115. package/src/projected-tile-selection.ts +605 -0
  116. package/src/projected-tileset.ts +183 -0
  117. package/src/projected-viewport.ts +254 -0
  118. package/src/raster-color-extension.ts +43 -18
  119. package/src/raster-fade.ts +319 -0
  120. package/src/raster-tile-fingerprint.ts +31 -0
  121. package/src/raster-tile-loader.ts +211 -0
  122. package/src/shader-injection-plugin.ts +25 -0
  123. package/src/source-features.ts +170 -0
  124. package/src/source-tiles.ts +102 -0
  125. package/src/sprite.ts +122 -15
  126. package/src/stretch-icon-layer.ts +87 -0
  127. package/src/style-accessor.ts +105 -17
  128. package/src/style-expression.ts +80 -3
  129. package/src/style-resolver.ts +200 -22
  130. package/src/terrain-query.ts +86 -0
  131. package/src/text-layout.ts +2 -3
  132. package/src/zoom-load-gate.ts +57 -0
  133. package/src/zoom-paint-extension.ts +245 -47
  134. package/dist/types/arabic-shaping.d.ts +0 -7
  135. package/dist/types/bidi.d.ts +0 -8
  136. package/dist/types/polylabel.d.ts +0 -17
  137. package/src/arabic-shaping.ts +0 -366
  138. package/src/bidi.ts +0 -199
  139. package/src/polylabel.ts +0 -312
@@ -0,0 +1,353 @@
1
+ // tangram-layers
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import {SharedMVTLayer} from '@deck.gl-community/layers/geo-layers';
6
+ import {Layer, type LayerProps} from '@deck.gl/core';
7
+ import {load, parse, type LoaderOptions} from '@loaders.gl/core';
8
+
9
+ /**
10
+ * The kind of resource a request expects, as MapLibre GL JS's `RequestParameters.type`: `'json'`
11
+ * for a style, a TileJSON, a sprite index or GeoJSON data, `'arrayBuffer'` for a vector tile or a
12
+ * glyph range, `'image'` for a raster or raster-dem tile or a sprite image.
13
+ */
14
+ export type BasemapRequestType = 'string' | 'json' | 'arrayBuffer' | 'image';
15
+
16
+ /** The request a protocol handler receives, shaped as MapLibre GL JS's `RequestParameters`. */
17
+ export type BasemapRequestParameters = {
18
+ /** The URL requested, with its scheme. */
19
+ url: string;
20
+ /** The kind of resource expected. */
21
+ type: BasemapRequestType;
22
+ /** The headers of the request's `fetchOptions`. */
23
+ headers?: HeadersInit;
24
+ /** The method of the request's `fetchOptions`. */
25
+ method?: string;
26
+ /** The body of the request's `fetchOptions`. */
27
+ body?: BodyInit | null;
28
+ /** The credentials mode of the request's `fetchOptions`. */
29
+ credentials?: RequestCredentials;
30
+ /** The cache mode of the request's `fetchOptions`. */
31
+ cache?: RequestCache;
32
+ };
33
+
34
+ /** What a protocol handler resolves with, as MapLibre GL JS's `GetResourceResponse`. */
35
+ export type BasemapResourceResponse = {
36
+ /**
37
+ * The resource: an `ArrayBuffer`, a typed array or a `Blob` of its bytes (an image is its
38
+ * encoded bytes), a string, or, for a `'json'` request, the parsed JSON value. `null` or
39
+ * `undefined` is an empty resource, such as a tile without data.
40
+ */
41
+ data: unknown;
42
+ /** Accepted for MapLibre GL JS compatibility; not used. */
43
+ cacheControl?: string | null;
44
+ /** Accepted for MapLibre GL JS compatibility; not used. */
45
+ expires?: string | Date | null;
46
+ };
47
+
48
+ /**
49
+ * Loads the resource of a URL with a registered scheme. `abortController` aborts when the request
50
+ * is cancelled, for example when deck.gl no longer needs a tile. The same function works as a
51
+ * MapLibre GL JS `addProtocol` handler.
52
+ */
53
+ export type BasemapProtocolHandler = (
54
+ requestParameters: BasemapRequestParameters,
55
+ abortController: AbortController
56
+ ) => Promise<BasemapResourceResponse>;
57
+
58
+ /** Schemes that load with `fetch` and are never given to a handler, as in MapLibre GL JS. */
59
+ const FETCH_SCHEMES = new Set(['http', 'https', 'file']);
60
+
61
+ const SCHEME = /^[a-z][a-z\d+.-]*$/i;
62
+
63
+ const protocols = new Map<string, BasemapProtocolHandler>();
64
+
65
+ /**
66
+ * Loads every URL `<scheme>://...` that `BasemapLayer` requests with `handler`: the style, TileJSON,
67
+ * vector, raster and raster-dem tiles, sprites, glyphs and GeoJSON data. A second registration of
68
+ * the same scheme replaces the first. As in MapLibre GL JS, `http`, `https` and `file` URLs always
69
+ * load with `fetch`.
70
+ */
71
+ export function registerBasemapProtocol(scheme: string, handler: BasemapProtocolHandler): void {
72
+ if (!SCHEME.test(scheme)) {
73
+ throw new Error(`Invalid basemap protocol scheme "${scheme}": give the scheme without "://"`);
74
+ }
75
+ if (FETCH_SCHEMES.has(scheme.toLowerCase())) {
76
+ throw new Error(`The basemap protocol scheme "${scheme}" always loads with fetch`);
77
+ }
78
+ if (typeof handler !== 'function') {
79
+ throw new Error(`The handler of basemap protocol "${scheme}" is not a function`);
80
+ }
81
+ protocols.set(scheme.toLowerCase(), handler);
82
+ }
83
+
84
+ /** Removes the handler of `scheme`. Its URLs then fail to load. */
85
+ export function unregisterBasemapProtocol(scheme: string): void {
86
+ protocols.delete(scheme.toLowerCase());
87
+ }
88
+
89
+ /** The scheme of a URL `<scheme>://...` that does not load with `fetch`, or null. */
90
+ function getCustomScheme(url: string): string | null {
91
+ const end = url.indexOf('://');
92
+ if (end <= 0) {
93
+ return null;
94
+ }
95
+ const scheme = url.slice(0, end).toLowerCase();
96
+ return SCHEME.test(scheme) && !FETCH_SCHEMES.has(scheme) ? scheme : null;
97
+ }
98
+
99
+ /**
100
+ * Whether `url` is `<scheme>://...` with a scheme other than `http`, `https` and `file`: a URL that
101
+ * only a protocol handler loads.
102
+ */
103
+ export function hasCustomScheme(url: string): boolean {
104
+ return getCustomScheme(url) !== null;
105
+ }
106
+
107
+ /** Whether `url` has a scheme with a registered handler. Such a URL is not resolved against a base. */
108
+ export function isBasemapProtocolUrl(url: unknown): url is string {
109
+ if (typeof url !== 'string') {
110
+ return false;
111
+ }
112
+ const scheme = getCustomScheme(url);
113
+ return scheme !== null && protocols.has(scheme);
114
+ }
115
+
116
+ function getUrl(input: RequestInfo | URL): string {
117
+ return typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
118
+ }
119
+
120
+ function getAbortError(signal: AbortSignal): unknown {
121
+ return signal.reason ?? new DOMException('The operation was aborted.', 'AbortError');
122
+ }
123
+
124
+ /**
125
+ * Calls the handler of a URL's scheme. The handler's abort controller aborts with `init.signal`,
126
+ * and the request rejects at once when it does, even if the handler ignores the abort.
127
+ */
128
+ async function requestProtocolResource(
129
+ handler: BasemapProtocolHandler,
130
+ url: string,
131
+ type: BasemapRequestType,
132
+ init?: RequestInit
133
+ ): Promise<unknown> {
134
+ const signal = init?.signal ?? undefined;
135
+ if (signal?.aborted) {
136
+ throw getAbortError(signal);
137
+ }
138
+ const abortController = new AbortController();
139
+ const requestParameters: BasemapRequestParameters = {url, type};
140
+ for (const key of ['headers', 'method', 'body', 'credentials', 'cache'] as const) {
141
+ if (init?.[key] !== undefined) {
142
+ (requestParameters as Record<string, unknown>)[key] = init[key];
143
+ }
144
+ }
145
+ if (!signal) {
146
+ return (await handler(requestParameters, abortController))?.data;
147
+ }
148
+ let onAbort = () => {};
149
+ const aborted = new Promise<never>((_, reject) => {
150
+ onAbort = () => {
151
+ abortController.abort(signal.reason);
152
+ reject(getAbortError(signal));
153
+ };
154
+ signal.addEventListener('abort', onAbort, {once: true});
155
+ });
156
+ try {
157
+ const response = await Promise.race([handler(requestParameters, abortController), aborted]);
158
+ return response?.data;
159
+ } finally {
160
+ signal.removeEventListener('abort', onAbort);
161
+ }
162
+ }
163
+
164
+ function isBinary(data: unknown): data is ArrayBuffer | ArrayBufferView | Blob {
165
+ return (
166
+ data instanceof ArrayBuffer ||
167
+ ArrayBuffer.isView(data) ||
168
+ (typeof Blob !== 'undefined' && data instanceof Blob)
169
+ );
170
+ }
171
+
172
+ /** The data a handler resolved with, as the body of a `Response`. */
173
+ function getResponseBody(url: string, type: BasemapRequestType, data: unknown): BodyInit | null {
174
+ if (data === null || data === undefined || typeof data === 'string' || isBinary(data)) {
175
+ return (data ?? null) as BodyInit | null;
176
+ }
177
+ if (type === 'json' && typeof data === 'object') {
178
+ return JSON.stringify(data);
179
+ }
180
+ throw new Error(
181
+ `The basemap protocol handler of ${url} returned ${Object.prototype.toString.call(data)}; ` +
182
+ 'return bytes, a string or, for a json request, a JSON value'
183
+ );
184
+ }
185
+
186
+ function getUnregisteredSchemeError(scheme: string, url: string): Error {
187
+ return new Error(
188
+ `No basemap protocol is registered for "${scheme}://" (${url}). ` +
189
+ `Call registerBasemapProtocol('${scheme}', handler) first.`
190
+ );
191
+ }
192
+
193
+ /**
194
+ * A `fetch` that loads URLs with a registered scheme with their handler, as a `Response`, and
195
+ * every other URL with `fetchFn`, or the global `fetch` without one. Without `fetchFn`, a URL
196
+ * with another scheme than `http`, `https` and `file` and no handler fails with an error that names
197
+ * the scheme.
198
+ */
199
+ export function getBasemapFetch(
200
+ fetchFn: typeof fetch | undefined,
201
+ type: BasemapRequestType
202
+ ): typeof fetch {
203
+ return async (input, init) => {
204
+ const url = getUrl(input);
205
+ const scheme = getCustomScheme(url);
206
+ const handler = scheme ? protocols.get(scheme) : undefined;
207
+ if (handler) {
208
+ const data = await requestProtocolResource(handler, url, type, init);
209
+ return new Response(getResponseBody(url, type, data), {status: 200});
210
+ }
211
+ if (scheme && !fetchFn) {
212
+ throw getUnregisteredSchemeError(scheme, url);
213
+ }
214
+ return fetchFn ? fetchFn(input, init) : globalThis.fetch(input, init);
215
+ };
216
+ }
217
+
218
+ /** A deck.gl layer `fetch` prop. */
219
+ export type BasemapLayerFetch = NonNullable<LayerProps['fetch']>;
220
+
221
+ /** The context deck.gl passes to a layer's `fetch` prop. */
222
+ type LayerFetchContext = Parameters<BasemapLayerFetch>[1];
223
+
224
+ const layerFetches = new Map<BasemapRequestType, WeakMap<BasemapLayerFetch, BasemapLayerFetch>>();
225
+
226
+ /**
227
+ * A deck.gl layer `fetch` prop that loads URLs with a registered scheme with their handler, then
228
+ * parses the bytes with the layer's loaders, and every other URL with `nextFetch`. A tile that
229
+ * deck.gl cancels aborts the handler. The same function is returned for the same `nextFetch` and
230
+ * `type`, so that a layer's props stay equal.
231
+ */
232
+ export function getBasemapLayerFetch(
233
+ nextFetch: BasemapLayerFetch,
234
+ type: BasemapRequestType
235
+ ): BasemapLayerFetch {
236
+ let byFetch = layerFetches.get(type);
237
+ if (!byFetch) {
238
+ byFetch = new WeakMap();
239
+ layerFetches.set(type, byFetch);
240
+ }
241
+ let layerFetchWithProtocols = byFetch.get(nextFetch);
242
+ if (!layerFetchWithProtocols) {
243
+ layerFetchWithProtocols = (url, context) => {
244
+ const scheme = typeof url === 'string' ? getCustomScheme(url) : null;
245
+ const handler = scheme ? protocols.get(scheme) : undefined;
246
+ if (handler) {
247
+ return loadProtocolTile(handler, url, type, context);
248
+ }
249
+ if (isDefaultLayerFetch(nextFetch)) {
250
+ const loadOptions = getLayerLoadOptions(context);
251
+ const fetchOption = loadOptions?.fetch ?? loadOptions?.core?.fetch;
252
+ if (scheme && typeof fetchOption !== 'function') {
253
+ return Promise.reject(getUnregisteredSchemeError(scheme, url));
254
+ }
255
+ if (loadOptions && (fetchOption || loadOptions.fetchOptions || loadOptions.mimeType)) {
256
+ const options = getTileLoaderOptions(loadOptions, context.signal);
257
+ const hasCustomFetch = typeof options.core?.fetch === 'function';
258
+ // SharedMVTLayer always spreads core.fetch as request options, dropping function overrides.
259
+ if (hasCustomFetch && nextFetch === DEFAULT_MVT_FETCH) {
260
+ return load(url, context.loaders || context.layer.props.loaders, options);
261
+ }
262
+ // deck.gl also spreads core.fetch when the context has a signal. loaders.gl reads it from options.
263
+ return nextFetch(url, {
264
+ ...context,
265
+ loadOptions: options,
266
+ signal: hasCustomFetch ? undefined : context.signal
267
+ });
268
+ }
269
+ }
270
+ return nextFetch(url, context);
271
+ };
272
+ byFetch.set(nextFetch, layerFetchWithProtocols);
273
+ }
274
+ return layerFetchWithProtocols;
275
+ }
276
+
277
+ /** deck.gl's default layer `fetch`, which loads with loaders.gl and the global `fetch`. */
278
+ export const DEFAULT_LAYER_FETCH = (Layer.defaultProps as {fetch: {value: BasemapLayerFetch}})
279
+ .fetch.value;
280
+
281
+ /** `SharedMVTLayer`'s default `fetch`, which also loads without a deck.gl context. */
282
+ export const DEFAULT_MVT_FETCH = (SharedMVTLayer.defaultProps as {fetch: BasemapLayerFetch}).fetch;
283
+
284
+ /** Whether a layer `fetch` loads with the global `fetch`, which cannot load a custom scheme. */
285
+ function isDefaultLayerFetch(layerFetch: BasemapLayerFetch): boolean {
286
+ return layerFetch === DEFAULT_LAYER_FETCH || layerFetch === DEFAULT_MVT_FETCH;
287
+ }
288
+
289
+ type TileLoadOptions = LoaderOptions & {
290
+ fetch?: NonNullable<LoaderOptions['core']>['fetch'];
291
+ fetchOptions?: RequestInit;
292
+ mimeType?: string;
293
+ };
294
+
295
+ /** The loaders.gl options of a layer `fetch` call, as deck.gl's default `fetch` takes them. */
296
+ function getLayerLoadOptions(context: LayerFetchContext): TileLoadOptions | undefined {
297
+ return context.loadOptions || context.layer.getLoadOptions();
298
+ }
299
+
300
+ /** Translates the basemap's tile request options to the loaders.gl core namespace. */
301
+ function getTileLoaderOptions(
302
+ loadOptions: TileLoadOptions,
303
+ signal: AbortSignal | undefined
304
+ ): LoaderOptions {
305
+ const {fetch: legacyFetch, fetchOptions, mimeType, core, ...loaderOptions} = loadOptions;
306
+ const fetchOption = legacyFetch ?? core?.fetch;
307
+ const requestDefaults = {...(typeof fetchOption === 'object' ? fetchOption : undefined), ...fetchOptions};
308
+ return {
309
+ ...loaderOptions,
310
+ signal: signal ?? loaderOptions.signal,
311
+ core: {
312
+ ...core,
313
+ mimeType: core?.mimeType ?? mimeType,
314
+ fetch: typeof fetchOption === 'function'
315
+ ? (url: string, init?: RequestInit) => {
316
+ const headers = new Headers(requestDefaults.headers);
317
+ new Headers(init?.headers).forEach((value, name) => headers.set(name, value));
318
+ return fetchOption(url, {...requestDefaults, ...init, headers});
319
+ }
320
+ : requestDefaults
321
+ }
322
+ };
323
+ }
324
+
325
+ /** Loads a tile with a protocol handler and parses it; an empty resource is a tile without data. */
326
+ async function loadProtocolTile(
327
+ handler: BasemapProtocolHandler,
328
+ url: string,
329
+ type: BasemapRequestType,
330
+ context: LayerFetchContext
331
+ ): Promise<unknown> {
332
+ const loadOptions = getLayerLoadOptions(context);
333
+ const data = await requestProtocolResource(handler, url, type, {
334
+ ...loadOptions?.fetchOptions,
335
+ signal: context.signal
336
+ });
337
+ const body = getResponseBody(url, type, data);
338
+ const bytes =
339
+ typeof Blob !== 'undefined' && body instanceof Blob
340
+ ? await body.arrayBuffer()
341
+ : ArrayBuffer.isView(body)
342
+ ? body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength)
343
+ : body;
344
+ if (bytes === null || bytes === '' || (bytes instanceof ArrayBuffer && bytes.byteLength === 0)) {
345
+ return null;
346
+ }
347
+ return parse(
348
+ bytes as ArrayBuffer | string,
349
+ context.loaders || context.layer.props.loaders,
350
+ // loaders.gl selects a loader for bytes without a URL only from `core.mimeType`.
351
+ loadOptions && getTileLoaderOptions(loadOptions, context.signal)
352
+ );
353
+ }
@@ -0,0 +1,212 @@
1
+ // tangram-layers
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import type {LayerProps} from '@deck.gl/core';
6
+ import {getBasemapFetch, getBasemapLayerFetch as getProtocolLayerFetch, type BasemapRequestType} from './basemap-protocol';
7
+
8
+ /**
9
+ * The kind of resource a request is for, with the names of MapLibre GL JS's `ResourceType`:
10
+ * `'Style'` for the style document, `'Source'` for a TileJSON and for the `data` URL of a GeoJSON
11
+ * source, `'Tile'` for a vector, raster or raster-dem tile, `'Glyphs'` for a glyph range,
12
+ * `'SpriteJSON'` and `'SpriteImage'` for the sprite index and image.
13
+ */
14
+ export type BasemapResourceType =
15
+ | 'Unknown'
16
+ | 'Style'
17
+ | 'Source'
18
+ | 'Tile'
19
+ | 'Glyphs'
20
+ | 'SpriteImage'
21
+ | 'SpriteJSON'
22
+ | 'Image';
23
+
24
+ /**
25
+ * The request that a {@link BasemapTransformRequest} returns, as MapLibre GL JS's
26
+ * `RequestParameters`. Each field that is set replaces the field of the same name in the request;
27
+ * `headers` are merged into the request's headers by name.
28
+ */
29
+ export type BasemapTransformedRequest = {
30
+ /** The URL to request in place of the original URL. */
31
+ url: string;
32
+ /** Headers to add to the request, or to replace in it. */
33
+ headers?: HeadersInit;
34
+ /** The request method. */
35
+ method?: string;
36
+ /** The request body. */
37
+ body?: BodyInit | null;
38
+ /** The credentials mode of the request, such as `'include'` to send cookies to another origin. */
39
+ credentials?: RequestCredentials;
40
+ /** The cache mode of the request. */
41
+ cache?: RequestCache;
42
+ /** Accepted for MapLibre GL JS compatibility; not used. */
43
+ type?: string;
44
+ /** Accepted for MapLibre GL JS compatibility; not used. */
45
+ collectResourceTiming?: boolean;
46
+ };
47
+
48
+ /**
49
+ * Changes a request before it is sent, as MapLibre GL JS's `transformRequest` map option: receives
50
+ * the absolute URL and the kind of resource, and returns the URL and request fields to use, or
51
+ * nothing to send the request as it is.
52
+ */
53
+ export type BasemapTransformRequest = (
54
+ url: string,
55
+ resourceType: BasemapResourceType
56
+ ) => BasemapTransformedRequest | null | undefined | void;
57
+
58
+ /** The request fields a transformed request can set, other than its URL and headers. */
59
+ const REQUEST_FIELDS = ['method', 'body', 'credentials', 'cache'] as const;
60
+
61
+ /**
62
+ * Applies `transformRequest` to a request: the URL to send, and `init` with the fields of the
63
+ * transformed request. Without `transformRequest`, or when it returns nothing, the URL and `init`
64
+ * are returned as they are. The `signal` of `init` is always kept.
65
+ */
66
+ export function transformBasemapRequest(
67
+ transformRequest: BasemapTransformRequest | null | undefined,
68
+ url: string,
69
+ resourceType: BasemapResourceType,
70
+ init?: RequestInit
71
+ ): {url: string; init: RequestInit | undefined} {
72
+ const request = transformRequest?.(url, resourceType);
73
+ if (!request) {
74
+ return {url, init};
75
+ }
76
+ const nextInit: RequestInit = {...init};
77
+ for (const field of REQUEST_FIELDS) {
78
+ if (request[field] !== undefined) {
79
+ (nextInit as Record<string, unknown>)[field] = request[field];
80
+ }
81
+ }
82
+ if (request.headers !== undefined) {
83
+ const headers = new Headers(init?.headers);
84
+ new Headers(request.headers).forEach((value, name) => headers.set(name, value));
85
+ nextInit.headers = headers;
86
+ }
87
+ return {url: typeof request.url === 'string' && request.url ? request.url : url, init: nextInit};
88
+ }
89
+
90
+ /**
91
+ * A `fetch` for one kind of resource: it applies `transformRequest` to each request, then sends
92
+ * it with `fetch`, or with the global `fetch` without one.
93
+ */
94
+ export function getBasemapRequestFetch(
95
+ resourceType: BasemapResourceType,
96
+ {
97
+ fetch: fetchFn,
98
+ transformRequest
99
+ }: {fetch?: typeof fetch; transformRequest?: BasemapTransformRequest | null} = {}
100
+ ): typeof fetch {
101
+ const send = fetchFn || ((...args: Parameters<typeof fetch>) => globalThis.fetch(...args));
102
+ if (!transformRequest) {
103
+ return send;
104
+ }
105
+ return (input, init) => {
106
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
107
+ if (url.startsWith('pmtiles://')) {
108
+ return send(input, init);
109
+ }
110
+ const request = transformBasemapRequest(transformRequest, url, resourceType, init);
111
+ return send(request.url, request.init);
112
+ };
113
+ }
114
+
115
+ /** A deck.gl layer `fetch` prop. */
116
+ type LayerFetch = NonNullable<LayerProps['fetch']>;
117
+
118
+ /** The context deck.gl passes to a layer's `fetch` prop. */
119
+ type LayerFetchContext = Parameters<LayerFetch>[1];
120
+
121
+ const layerFetches = new WeakMap<BasemapTransformRequest, WeakMap<LayerFetch, LayerFetch>>();
122
+
123
+ /**
124
+ * A deck.gl layer `fetch` prop for tiles that applies `transformRequest` to each tile URL, then
125
+ * loads the tile with `nextFetch`. The fields of the transformed request are added to each
126
+ * request that the loaders make, through the `fetch` of the loader options. Returns `nextFetch`
127
+ * without `transformRequest`, and the same function for the same arguments, so that the props of
128
+ * a tile layer stay equal.
129
+ */
130
+ export function getBasemapLayerFetch(
131
+ nextFetch: LayerFetch,
132
+ transformRequest: BasemapTransformRequest | null | undefined
133
+ ): LayerFetch {
134
+ if (!transformRequest) {
135
+ return nextFetch;
136
+ }
137
+ let byFetch = layerFetches.get(transformRequest);
138
+ if (!byFetch) {
139
+ byFetch = new WeakMap();
140
+ layerFetches.set(transformRequest, byFetch);
141
+ }
142
+ let layerFetch = byFetch.get(nextFetch);
143
+ if (!layerFetch) {
144
+ layerFetch = (url, context) => {
145
+ if (url.startsWith('pmtiles://')) {
146
+ return nextFetch(url, context);
147
+ }
148
+ const request = transformBasemapRequest(transformRequest, url, 'Tile');
149
+ if (!request.init || Object.keys(request.init).length === 0) {
150
+ return nextFetch(request.url, context);
151
+ }
152
+ return nextFetch(request.url, {
153
+ ...context,
154
+ loadOptions: getRequestLoadOptions(context, request.init)
155
+ });
156
+ };
157
+ byFetch.set(nextFetch, layerFetch);
158
+ }
159
+ return layerFetch;
160
+ }
161
+
162
+ /**
163
+ * The loader options of a tile request, with a `fetch` that adds the fields of `requestInit` to
164
+ * the request. The loader options' own `fetch` sends it, as a function, or as the request options
165
+ * it gives as an object; the request keeps the tile's abort signal.
166
+ */
167
+ function getRequestLoadOptions(context: LayerFetchContext, requestInit: RequestInit): any {
168
+ const loadOptions = context.loadOptions || context.layer.getLoadOptions();
169
+ const baseFetch = loadOptions?.fetch ?? loadOptions?.core?.fetch;
170
+ const send: typeof fetch =
171
+ typeof baseFetch === 'function'
172
+ ? baseFetch
173
+ : (input, init) =>
174
+ globalThis.fetch(input, {...(baseFetch as RequestInit | undefined), ...init});
175
+ const requestFetch: typeof fetch = (input, init) => {
176
+ const signal = init?.signal ?? context.signal;
177
+ const headers = new Headers(init?.headers);
178
+ new Headers(requestInit.headers).forEach((value, name) => headers.set(name, value));
179
+ return send(input, {
180
+ ...init,
181
+ ...requestInit,
182
+ headers,
183
+ ...(signal ? {signal} : {})
184
+ });
185
+ };
186
+ const fetchOptions = {...loadOptions?.fetchOptions, ...requestInit};
187
+ const headers = new Headers(loadOptions?.fetchOptions?.headers);
188
+ new Headers(requestInit.headers).forEach((value, name) => headers.set(name, value));
189
+ fetchOptions.headers = headers;
190
+ return {...loadOptions, fetchOptions, fetch: requestFetch};
191
+ }
192
+
193
+ /** Applies the request transformation before protocol dispatch for a resource. */
194
+ export function getBasemapResourceFetch(
195
+ resourceType: BasemapResourceType,
196
+ type: BasemapRequestType,
197
+ options: {fetch?: typeof fetch; transformRequest?: BasemapTransformRequest | null} = {}
198
+ ): typeof fetch {
199
+ return getBasemapRequestFetch(resourceType, {
200
+ fetch: getBasemapFetch(options.fetch, type),
201
+ transformRequest: options.transformRequest
202
+ });
203
+ }
204
+
205
+ /** Applies the request transformation before protocol dispatch for a tile. */
206
+ export function getBasemapTileFetch(
207
+ nextFetch: LayerFetch,
208
+ type: BasemapRequestType,
209
+ transformRequest: BasemapTransformRequest | null | undefined
210
+ ): LayerFetch {
211
+ return getBasemapLayerFetch(getProtocolLayerFetch(nextFetch, type), transformRequest);
212
+ }