maplibre-gl
Version:
BSD licensed community fork of mapbox-gl, a WebGL interactive maps library
1 lines • 84.1 kB
Source Map (JSON)
{"version":3,"file":"maplibre-gl-worker-dev.mjs","names":[],"sources":["../src/style/style_layer_index.ts","../src/render/glyph_atlas.ts","../src/source/worker_tile.ts","../src/source/worker_tile_state.ts","../src/util/request_performance.ts","../src/source/vector_tile_overzoomed.ts","../src/source/vector_tile_worker_source.ts","../src/source/raster_dem_tile_worker_source.ts","../src/source/geojson_worker_source.ts","../src/source/worker.ts"],"sourcesContent":["import {createStyleLayer} from './create_style_layer.ts';\nimport {featureFilter, groupByLayout} from '@maplibre/maplibre-gl-style-spec';\nimport {GEOJSON_TILE_LAYER_NAME} from '../data/feature_index.ts';\nimport type {StyleLayer} from './style_layer.ts';\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\n\nexport type LayerConfigs = {[_: string]: LayerSpecification};\n\nexport class StyleLayerIndex {\n familiesBySource: {\n [source: string]: {\n [sourceLayer: string]: StyleLayer[][];\n };\n };\n keyCache: {[source: string]: string};\n\n _layerConfigs: LayerConfigs;\n _layers: {[_: string]: StyleLayer};\n\n constructor(layerConfigs?: LayerSpecification[] | null, globalState?: Record<string, any>) {\n this.keyCache = {};\n if (layerConfigs) {\n this.replace(layerConfigs, globalState);\n }\n }\n\n replace(layerConfigs: LayerSpecification[], globalState?: Record<string, any>): void {\n this._layerConfigs = {};\n this._layers = {};\n this.update(layerConfigs, [], globalState);\n }\n\n update(layerConfigs: LayerSpecification[], removedIds: string[], globalState?: Record<string, any>): void {\n for (const layerConfig of layerConfigs) {\n this._layerConfigs[layerConfig.id] = layerConfig;\n\n const layer = this._layers[layerConfig.id] = createStyleLayer(layerConfig, globalState);\n layer._featureFilter = featureFilter(layer.filter, `layers[${layerConfig.id}].filter`, globalState);\n if (this.keyCache[layerConfig.id])\n delete this.keyCache[layerConfig.id];\n }\n for (const id of removedIds) {\n delete this.keyCache[id];\n delete this._layerConfigs[id];\n delete this._layers[id];\n }\n\n this.familiesBySource = {};\n\n const groups = groupByLayout(Object.values(this._layerConfigs), this.keyCache);\n\n for (const layerConfigs of groups) {\n const layers = layerConfigs.map((layerConfig) => this._layers[layerConfig.id]);\n\n const layer = layers[0];\n if (layer.isHidden()) {\n continue;\n }\n\n const sourceId = layer.source || '';\n let sourceGroup = this.familiesBySource[sourceId];\n sourceGroup ||= this.familiesBySource[sourceId] = {};\n\n const sourceLayerId = layer.sourceLayer || GEOJSON_TILE_LAYER_NAME;\n let sourceLayerFamilies = sourceGroup[sourceLayerId];\n sourceLayerFamilies ||= sourceGroup[sourceLayerId] = [];\n\n sourceLayerFamilies.push(layers);\n }\n }\n}\n","import {AlphaImage} from '../util/image.ts';\nimport {register} from '../util/web_worker_transfer.ts';\nimport potpack from 'potpack';\n\nimport type {GlyphMetrics} from '../style/style_glyph.ts';\nimport type {GetGlyphsResponse} from '../util/actor_messages.ts';\n\nconst padding = 1;\n\n/**\n * A rectangle type with position, width and height.\n */\nexport type Rect = {\n x: number;\n y: number;\n w: number;\n h: number;\n};\n\n/**\n * The glyph's position\n */\nexport type GlyphPosition = {\n rect: Rect;\n metrics: GlyphMetrics;\n};\n\n/**\n * The glyphs' positions\n */\nexport type GlyphPositions = {\n [_: string]: {\n [_: number]: GlyphPosition;\n };\n};\n\nexport class GlyphAtlas {\n image: AlphaImage;\n positions: GlyphPositions;\n\n constructor(stacks: GetGlyphsResponse) {\n const positions = {};\n const bins = [];\n\n for (const stack in stacks) {\n const glyphs = stacks[stack];\n const stackPositions = positions[stack] = {};\n\n for (const id in glyphs) {\n const src = glyphs[+id];\n if (!src || src.bitmap.width === 0 || src.bitmap.height === 0) continue;\n\n const bin = {\n x: 0,\n y: 0,\n w: src.bitmap.width + 2 * padding,\n h: src.bitmap.height + 2 * padding\n };\n bins.push(bin);\n stackPositions[id] = {rect: bin, metrics: src.metrics};\n }\n }\n\n const {w, h} = potpack(bins);\n const image = new AlphaImage({width: w || 1, height: h || 1});\n\n for (const stack in stacks) {\n const glyphs = stacks[stack];\n\n for (const id in glyphs) {\n const src = glyphs[+id];\n if (!src || src.bitmap.width === 0 || src.bitmap.height === 0) continue;\n const bin = positions[stack][id].rect;\n AlphaImage.copy(src.bitmap, image, {x: 0, y: 0}, {x: bin.x + padding, y: bin.y + padding}, src.bitmap);\n }\n }\n\n this.image = image;\n this.positions = positions;\n }\n}\n\nregister('GlyphAtlas', GlyphAtlas);\n","import {FeatureIndex} from '../data/feature_index.ts';\nimport {performSymbolLayout} from '../symbol/symbol_layout.ts';\nimport {CollisionBoxArray} from '../data/array_types.g.ts';\nimport {DictionaryCoder} from '../util/dictionary_coder.ts';\nimport {SymbolBucket} from '../data/bucket/symbol_bucket.ts';\nimport {LineBucket} from '../data/bucket/line_bucket.ts';\nimport {FillBucket} from '../data/bucket/fill_bucket.ts';\nimport {FillExtrusionBucket} from '../data/bucket/fill_extrusion_bucket.ts';\nimport {warnOnce, mapObject} from '../util/util.ts';\nimport {ImageAtlas} from '../render/image_atlas.ts';\nimport {GlyphAtlas} from '../render/glyph_atlas.ts';\nimport {EvaluationParameters} from '../style/evaluation_parameters.ts';\nimport {OverscaledTileID} from '../tile/tile_id.ts';\n\nimport type {Bucket} from '../data/bucket.ts';\nimport type {IActor} from '../util/actor.ts';\nimport type {StyleLayer} from '../style/style_layer.ts';\nimport type {StyleLayerIndex} from '../style/style_layer_index.ts';\nimport type {\n WorkerTileParameters,\n WorkerTileResult,\n} from './worker_source.ts';\nimport type {PromoteIdSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport type {VectorTileLike} from '@maplibre/vt-pbf';\nimport {type GetDashesResponse, MessageType, type GetGlyphsResponse, type GetImagesResponse} from '../util/actor_messages.ts';\nimport type {SubdivisionGranularitySetting} from '../render/subdivision_granularity_settings.ts';\nexport class WorkerTile {\n tileID: OverscaledTileID;\n uid: string | number;\n zoom: number;\n pixelRatio: number;\n tileSize: number;\n source: string;\n promoteId: PromoteIdSpecification;\n overscaling: number;\n showCollisionBoxes: boolean;\n collectResourceTiming: boolean;\n returnDependencies: boolean;\n\n data: VectorTileLike;\n collisionBoxArray: CollisionBoxArray;\n\n abort: AbortController;\n vectorTile: VectorTileLike;\n inFlightDependencies: AbortController[];\n\n constructor(params: WorkerTileParameters) {\n this.tileID = new OverscaledTileID(params.tileID.overscaledZ, params.tileID.wrap, params.tileID.canonical.z, params.tileID.canonical.x, params.tileID.canonical.y);\n this.uid = params.uid;\n this.zoom = params.zoom;\n this.pixelRatio = params.pixelRatio;\n this.tileSize = params.tileSize;\n this.source = params.source;\n this.overscaling = this.tileID.overscaleFactor();\n this.showCollisionBoxes = params.showCollisionBoxes;\n this.collectResourceTiming = !!params.collectResourceTiming;\n this.returnDependencies = !!params.returnDependencies;\n this.promoteId = params.promoteId;\n this.inFlightDependencies = [];\n }\n\n async parse(data: VectorTileLike, layerIndex: StyleLayerIndex, availableImages: string[], actor: IActor, subdivisionGranularity: SubdivisionGranularitySetting): Promise<WorkerTileResult> {\n this.data = data;\n\n this.collisionBoxArray = new CollisionBoxArray();\n const sourceLayerCoder = new DictionaryCoder(Object.keys(data.layers).sort());\n\n const featureIndex = new FeatureIndex(this.tileID, this.promoteId);\n featureIndex.bucketLayerIDs = [];\n\n const buckets: {[_: string]: Bucket} = {};\n\n const options = {\n featureIndex,\n iconDependencies: {},\n patternDependencies: {},\n glyphDependencies: {},\n dashDependencies: {},\n availableImages,\n subdivisionGranularity\n };\n\n const layerFamilies = layerIndex.familiesBySource[this.source];\n for (const sourceLayerId in layerFamilies) {\n const sourceLayer = data.layers[sourceLayerId];\n if (!sourceLayer) {\n continue;\n }\n\n if (sourceLayer.version === 1) {\n warnOnce(`Vector tile source \"${this.source}\" layer \"${sourceLayerId}\" ` +\n 'does not use vector tile spec v2 and therefore may have some rendering errors.');\n }\n\n const sourceLayerIndex = sourceLayerCoder.encode(sourceLayerId);\n const features = [];\n for (let index = 0; index < sourceLayer.length; index++) {\n const feature = sourceLayer.feature(index);\n const id = featureIndex.getId(feature, sourceLayerId);\n features.push({feature, id, index, sourceLayerIndex});\n }\n\n for (const family of layerFamilies[sourceLayerId]) {\n const layer = family[0];\n\n if (layer.source !== this.source) {\n warnOnce(`layer.source = ${layer.source} does not equal this.source = ${this.source}`);\n }\n if (layer.isHidden(this.zoom, true)) continue;\n recalculateLayers(family, this.zoom, availableImages);\n\n const bucket = buckets[layer.id] = layer.createBucket({\n index: featureIndex.bucketLayerIDs.length,\n layers: family,\n zoom: this.zoom,\n pixelRatio: this.pixelRatio,\n overscaling: this.overscaling,\n collisionBoxArray: this.collisionBoxArray,\n sourceLayerIndex,\n sourceID: this.source\n });\n\n bucket.populate(features, options, this.tileID.canonical);\n featureIndex.bucketLayerIDs.push(family.map((l) => l.id));\n }\n }\n\n // options.glyphDependencies looks like: {\"SomeFontName\":{\"10\":true,\"32\":true}}\n // this line makes an object like: {\"SomeFontName\":[10,32]}\n const stacks: {[_: string]: number[]} = mapObject(options.glyphDependencies, (glyphs) => Object.keys(glyphs).map(Number));\n\n for (const request of this.inFlightDependencies) {\n request?.abort();\n }\n this.inFlightDependencies = [];\n\n let getGlyphsPromise = Promise.resolve<GetGlyphsResponse>({});\n if (Object.keys(stacks).length) {\n const abortController = new AbortController();\n this.inFlightDependencies.push(abortController);\n getGlyphsPromise = actor.sendAsync({type: MessageType.getGlyphs, data: {stacks, source: this.source, tileID: this.tileID, type: 'glyphs'}}, abortController);\n }\n\n const icons = Object.keys(options.iconDependencies);\n let getIconsPromise = Promise.resolve<GetImagesResponse>({});\n if (icons.length) {\n const abortController = new AbortController();\n this.inFlightDependencies.push(abortController);\n getIconsPromise = actor.sendAsync({type: MessageType.getImages, data: {icons, source: this.source, tileID: this.tileID, type: 'icons'}}, abortController);\n }\n\n const patterns = Object.keys(options.patternDependencies);\n let getPatternsPromise = Promise.resolve<GetImagesResponse>({});\n if (patterns.length) {\n const abortController = new AbortController();\n this.inFlightDependencies.push(abortController);\n getPatternsPromise = actor.sendAsync({type: MessageType.getImages, data: {icons: patterns, source: this.source, tileID: this.tileID, type: 'patterns'}}, abortController);\n }\n\n const dashes = options.dashDependencies;\n let getDashesPromise = Promise.resolve<GetDashesResponse>({} as GetDashesResponse);\n if (Object.keys(dashes).length) {\n const abortController = new AbortController();\n this.inFlightDependencies.push(abortController);\n getDashesPromise = actor.sendAsync({type: MessageType.getDashes, data: {dashes}}, abortController);\n }\n\n const [glyphMap, iconMap, patternMap, dashPositions] = await Promise.all([getGlyphsPromise, getIconsPromise, getPatternsPromise, getDashesPromise]);\n\n const glyphAtlas = new GlyphAtlas(glyphMap);\n const imageAtlas = new ImageAtlas(iconMap, patternMap);\n\n for (const key in buckets) {\n const bucket = buckets[key];\n if (bucket instanceof SymbolBucket) {\n recalculateLayers(bucket.layers, this.zoom, availableImages);\n performSymbolLayout({\n bucket,\n glyphMap,\n glyphPositions: glyphAtlas.positions,\n imageMap: iconMap,\n imagePositions: imageAtlas.iconPositions,\n showCollisionBoxes: this.showCollisionBoxes,\n canonical: this.tileID.canonical,\n subdivisionGranularity: options.subdivisionGranularity\n });\n } else if (bucket.hasDependencies && (bucket instanceof FillBucket || bucket instanceof FillExtrusionBucket || bucket instanceof LineBucket)) {\n recalculateLayers(bucket.layers, this.zoom, availableImages);\n bucket.addFeatures(options, this.tileID.canonical, imageAtlas.patternPositions, dashPositions);\n }\n }\n\n return {\n buckets: Object.values(buckets).filter(b => !b.isEmpty()),\n featureIndex,\n collisionBoxArray: this.collisionBoxArray,\n glyphAtlasImage: glyphAtlas.image,\n imageAtlas,\n dashPositions,\n // Only used for benchmarking:\n glyphMap: this.returnDependencies ? glyphMap : null,\n iconMap: this.returnDependencies ? iconMap : null,\n glyphPositions: this.returnDependencies ? glyphAtlas.positions : null\n };\n }\n}\n\nfunction recalculateLayers(layers: readonly StyleLayer[], zoom: number, availableImages: string[]) {\n // Layers are shared and may have been used by a WorkerTile with a different zoom.\n const parameters = new EvaluationParameters(zoom);\n for (const layer of layers) {\n layer.recalculate(parameters, availableImages);\n }\n}\n","import type {WorkerTile} from './worker_tile.ts';\nimport {type ExpiryData} from '../util/ajax.ts';\n\nexport type ParsingState = {\n rawData: ArrayBufferLike;\n cacheControl?: ExpiryData;\n resourceTiming?: any;\n};\n\nexport class WorkerTileState {\n loading: Record<string, WorkerTile> = {};\n loaded: Record<string, WorkerTile> = {};\n parsing: Record<string, ParsingState> = {};\n\n startLoading(uid: string | number, tile: WorkerTile): void {\n this.loading[uid] = tile;\n }\n\n finishLoading(uid: string | number): void {\n delete this.loading[uid];\n }\n\n abort(uid: string | number): void {\n const tile = this.loading[uid];\n if (!tile?.abort) return;\n tile.abort.abort();\n delete this.loading[uid];\n }\n\n getParsing(uid: string | number): ParsingState | undefined {\n return this.parsing[uid];\n }\n\n setParsing(uid: string | number, state: ParsingState): void {\n this.parsing[uid] = state;\n }\n\n removeParsing(uid: string | number): void {\n delete this.parsing[uid];\n }\n\n markLoaded(uid: string | number, tile: WorkerTile): void {\n this.loaded[uid] = tile;\n }\n\n getLoaded(uid: string | number): WorkerTile | undefined {\n const tile = this.loaded[uid];\n if (!tile) return undefined;\n return tile;\n }\n\n removeLoaded(uid: string | number): void {\n delete this.loaded[uid];\n }\n\n clearLoaded(): void {\n this.loaded = {};\n }\n}\n","/**\n * @internal\n * Safe wrapper for the performance resource timing API in web workers with graceful degradation\n */\nexport class RequestPerformance {\n private start: string;\n private end: string;\n private measure: string;\n\n constructor (url: string) {\n this.start = `${url}#start`;\n this.end = `${url}#end`;\n this.measure = url;\n\n performance.mark(this.start);\n }\n\n finish(): PerformanceEntryList {\n performance.mark(this.end);\n let resourceTimingData = performance.getEntriesByName(this.measure);\n\n // fallback if web worker implementation of perf.getEntriesByName returns empty\n if (resourceTimingData.length === 0) {\n performance.measure(this.measure, this.start, this.end);\n resourceTimingData = performance.getEntriesByName(this.measure);\n\n // cleanup\n performance.clearMarks(this.start);\n performance.clearMarks(this.end);\n performance.clearMeasures(this.measure);\n }\n\n return resourceTimingData;\n }\n}\n","import Point from '@mapbox/point-geometry';\nimport {clipGeometry} from '../symbol/clip_line.ts';\nimport type {CanonicalTileID} from '../tile/tile_id.ts';\nimport type {VectorTileFeatureLike, VectorTileLayerLike, VectorTileLike} from '@maplibre/vt-pbf';\n\nclass VectorTileFeatureOverzoomed implements VectorTileFeatureLike {\n pointsArray: Point[][];\n type: VectorTileFeatureLike['type'];\n properties: VectorTileFeatureLike['properties'];\n id: VectorTileFeatureLike['id'];\n extent: VectorTileFeatureLike['extent'];\n\n constructor(\n type: VectorTileFeatureLike['type'],\n geometry: Point[][],\n properties: VectorTileFeatureLike['properties'],\n id: VectorTileFeatureLike['id'],\n extent: VectorTileFeatureLike['extent']\n ) {\n this.type = type;\n this.properties = properties ? properties : {};\n this.extent = extent;\n this.pointsArray = geometry;\n this.id = id;\n }\n\n loadGeometry(): Point[][] {\n // Clone the geometry and ensure all points are Point instances\n return this.pointsArray.map(ring =>\n ring.map(point => new Point(point.x, point.y))\n );\n }\n}\n\nclass VectorTileLayerOverzoomed implements VectorTileLayerLike {\n private _myFeatures: VectorTileFeatureOverzoomed[];\n name: string;\n extent: number;\n version: number = 2;\n length: number;\n\n constructor(features: VectorTileFeatureOverzoomed[], layerName: string, extent: number) {\n this._myFeatures = features;\n this.name = layerName;\n this.length = features.length;\n this.extent = extent;\n }\n\n feature(i: number): VectorTileFeatureLike {\n return this._myFeatures[i];\n }\n}\n\nexport class VectorTileOverzoomed implements VectorTileLike {\n layers: Record<string, VectorTileLayerLike> = {};\n\n addLayer(layer: VectorTileLayerOverzoomed): void {\n this.layers[layer.name] = layer;\n }\n}\n\n/**\n * This function slices a source tile layer into an overzoomed tile layer for a target tile ID.\n * @param sourceLayer - the source tile layer to slice\n * @param maxZoomTileID - the maximum zoom tile ID\n * @param targetTileID - the target tile ID\n * @returns - the overzoomed tile layer\n */\nexport function sliceVectorTileLayer(sourceLayer: VectorTileLayerLike, maxZoomTileID: CanonicalTileID, targetTileID: CanonicalTileID): VectorTileLayerOverzoomed {\n const {extent} = sourceLayer;\n const dz = targetTileID.z - maxZoomTileID.z;\n const scale = Math.pow(2, dz);\n \n // Calculate the target tile's position within the source tile in target coordinate space\n // This ensures all tiles share the same coordinate system\n const offsetX = (targetTileID.x - maxZoomTileID.x * scale) * extent;\n const offsetY = (targetTileID.y - maxZoomTileID.y * scale) * extent;\n\n const featureWrappers: VectorTileFeatureOverzoomed[] = [];\n for (let index = 0; index < sourceLayer.length; index++) {\n const feature: VectorTileFeatureLike = sourceLayer.feature(index);\n let geometry = feature.loadGeometry();\n \n // Transform all coordinates to target tile space\n for (const ring of geometry) {\n for (const point of ring) {\n point.x = point.x * scale - offsetX;\n point.y = point.y * scale - offsetY;\n }\n }\n \n const buffer = 128;\n geometry = clipGeometry(geometry, feature.type, -buffer, -buffer, extent + buffer, extent + buffer);\n if (geometry.length === 0) {\n continue;\n }\n \n featureWrappers.push(new VectorTileFeatureOverzoomed(\n feature.type,\n geometry,\n feature.properties,\n feature.id,\n extent\n ));\n }\n return new VectorTileLayerOverzoomed(featureWrappers, sourceLayer.name, extent);\n}","import {PbfReader} from 'pbf';\nimport {VectorTile} from '@mapbox/vector-tile';\nimport {fromVectorTileJs, type VectorTileLayerLike, type VectorTileLike} from '@maplibre/vt-pbf';\nimport {type ExpiryData, getArrayBuffer} from '../util/ajax.ts';\nimport {WorkerTile} from './worker_tile.ts';\nimport {WorkerTileState} from './worker_tile_state.ts';\nimport {BoundedLRUCache} from '../tile/tile_cache.ts';\nimport {ensureError, extend} from '../util/util.ts';\nimport {RequestPerformance} from '../util/request_performance.ts';\nimport {VectorTileOverzoomed, sliceVectorTileLayer} from './vector_tile_overzoomed.ts';\nimport {MLTVectorTile} from './vector_tile_mlt.ts';\nimport type {\n WorkerSource,\n WorkerTileParameters,\n TileParameters,\n WorkerTileResult\n} from '../source/worker_source.ts';\nimport type {IActor} from '../util/actor.ts';\nimport type {StyleLayer} from '../style/style_layer.ts';\nimport type {StyleLayerIndex} from '../style/style_layer_index.ts';\n\nexport type LoadVectorTileResult = {\n vectorTile: VectorTileLike;\n rawData: ArrayBufferLike;\n};\n\n/**\n * The {@link WorkerSource} implementation that supports {@link VectorTileSource}. This class is\n * used by vector tile sources to perform tile processing operations in a separate worker thread.\n */\nexport class VectorTileWorkerSource implements WorkerSource {\n actor: IActor;\n layerIndex: StyleLayerIndex;\n availableImages: string[];\n tileState: WorkerTileState;\n overzoomedTileResultCache: BoundedLRUCache<string, LoadVectorTileResult>;\n\n constructor(actor: IActor, layerIndex: StyleLayerIndex, availableImages: string[]) {\n this.actor = actor;\n this.layerIndex = layerIndex;\n this.availableImages = availableImages;\n this.tileState = new WorkerTileState();\n this.overzoomedTileResultCache = new BoundedLRUCache<string, LoadVectorTileResult>(1000);\n }\n\n /**\n * Loads a vector tile\n */\n loadVectorTile(params: WorkerTileParameters, rawData: ArrayBuffer): LoadVectorTileResult {\n try {\n const vectorTile = params.encoding !== 'mlt'\n ? new VectorTile(new PbfReader(rawData))\n : new MLTVectorTile(rawData);\n\n return {vectorTile, rawData};\n } catch (ex) {\n const bytes = new Uint8Array(rawData);\n const isGzipped = bytes[0] === 0x1f && bytes[1] === 0x8b;\n let errorMessage = `Unable to parse the tile at ${params.request.url}, `;\n if (isGzipped) {\n errorMessage += 'please make sure the data is not gzipped and that you have configured the relevant header in the server';\n } else {\n errorMessage += `got error: ${ensureError(ex).message}`;\n }\n throw new Error(errorMessage);\n }\n }\n\n /**\n * Implements {@link WorkerSource.loadTile}.\n */\n async loadTile(params: WorkerTileParameters): Promise<WorkerTileResult | null> {\n const {uid, overzoomParameters} = params;\n\n if (overzoomParameters) {\n params.request = overzoomParameters.overzoomRequest;\n }\n\n const timing = this._startRequestTiming(params);\n const workerTile = new WorkerTile(params);\n\n this.tileState.startLoading(uid, workerTile);\n const abortController = new AbortController();\n workerTile.abort = abortController;\n try {\n // Download the tile data from the network.\n const tileResponse = await getArrayBuffer(params.request, abortController);\n\n // Tile data hasn't changed (etag support) - return an unmodified result\n if (params.etag && params.etag === tileResponse.etag) {\n this.tileState.finishLoading(uid);\n return this._getEtagUnmodifiedResult(tileResponse, timing);\n }\n\n const tileResult = this.loadVectorTile(params, tileResponse.data);\n this.tileState.finishLoading(uid);\n if (!tileResult) return null;\n\n let {vectorTile, rawData} = tileResult;\n if (overzoomParameters) {\n ({vectorTile, rawData} = this._getOverzoomTile(params, vectorTile));\n }\n\n const cacheControl = this._getExpiryData(tileResponse);\n const resourceTiming = this._finishRequestTiming(timing);\n\n workerTile.vectorTile = vectorTile;\n this.tileState.markLoaded(uid, workerTile);\n const parsingState = {rawData, cacheControl, resourceTiming};\n this.tileState.setParsing(uid, parsingState);\n\n return await this._parseWorkerTile(workerTile, params);\n } catch (err) {\n this.tileState.finishLoading(uid);\n this.tileState.markLoaded(uid, workerTile);\n throw err;\n }\n }\n\n _getEtagUnmodifiedResult(response: ExpiryData, timing: RequestPerformance): WorkerTileResult {\n const cacheControl = this._getExpiryData(response);\n const resourceTiming = this._finishRequestTiming(timing);\n return extend({etagUnmodified: true as const}, cacheControl, resourceTiming);\n }\n\n async _parseWorkerTile(workerTile: WorkerTile, params: WorkerTileParameters): Promise<WorkerTileResult> {\n const parseState = this.tileState.getParsing(workerTile.uid);\n\n let result = await workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor, params.subdivisionGranularity);\n\n // We need to pass rawTileData back to the main thread so that it can be stored in the Tile and FeatureIndex.\n // After the main thread has successfully received and stored rawTileData,\n // we no longer need to store it in the worker or transfer additional copies of it.\n if (parseState) {\n const {rawData, cacheControl, resourceTiming} = parseState;\n // Overzoomed tiles are always re-encoded to MVT protobuf by _getOverzoomTile\n const encoding = params.overzoomParameters ? 'mvt' : params.encoding;\n // Return a copy of rawData to the main thread to avoid clearing the worker's buffer\n result = extend({rawTileData: rawData.slice(0), encoding}, result, cacheControl, resourceTiming);\n this.tileState.removeParsing(workerTile.uid);\n }\n // else: this seems like a missing case where cache control is lost? see #3309\n\n return result;\n }\n\n _getExpiryData({expires, cacheControl, etag}: ExpiryData): ExpiryData {\n const data: ExpiryData = {};\n if (expires) data.expires = expires;\n if (cacheControl) data.cacheControl = cacheControl;\n if (etag) data.etag = etag;\n return data;\n }\n\n _startRequestTiming(params: WorkerTileParameters): RequestPerformance | undefined {\n if (!params.request?.collectResourceTiming) return;\n return new RequestPerformance(params.request.url);\n }\n\n _finishRequestTiming(timing: RequestPerformance): {resourceTiming?: any} {\n const timingData = timing?.finish();\n if (!timingData) return {};\n\n // it's necessary to eval the result of getEntriesByName() here via parse/stringify\n // late evaluation in the main thread causes TypeError: illegal invocation\n return {resourceTiming: JSON.parse(JSON.stringify(timingData))};\n }\n\n /**\n * If we are seeking a tile deeper than the source's max available canonical tile, get the overzoomed tile\n * @param params - the worker tile parameters\n * @param maxZoomVectorTile - the original vector tile at the source's max available canonical zoom\n * @returns the overzoomed tile and its raw data\n */\n private _getOverzoomTile(params: WorkerTileParameters, maxZoomVectorTile: VectorTileLike): LoadVectorTileResult {\n const {tileID, source, overzoomParameters} = params;\n const {maxZoomTileID} = overzoomParameters;\n\n const cacheKey = `${maxZoomTileID.key}_${tileID.key}_${params.request?.url}`;\n const cachedOverzoomTile = this.overzoomedTileResultCache.get(cacheKey);\n\n if (cachedOverzoomTile) {\n return cachedOverzoomTile;\n }\n\n const overzoomedVectorTile = new VectorTileOverzoomed();\n const layerFamilies: Record<string, StyleLayer[][]> = this.layerIndex.familiesBySource[source];\n\n for (const sourceLayerId in layerFamilies) {\n const sourceLayer: VectorTileLayerLike = maxZoomVectorTile.layers[sourceLayerId];\n if (!sourceLayer) {\n continue;\n }\n\n const slicedTileLayer = sliceVectorTileLayer(sourceLayer, maxZoomTileID, tileID.canonical);\n if (slicedTileLayer.length > 0) {\n overzoomedVectorTile.addLayer(slicedTileLayer);\n }\n }\n const overzoomedVectorTileResult = {\n vectorTile: overzoomedVectorTile,\n rawData: fromVectorTileJs(overzoomedVectorTile).buffer\n };\n this.overzoomedTileResultCache.set(cacheKey, overzoomedVectorTileResult);\n\n return overzoomedVectorTileResult;\n }\n\n /**\n * Implements {@link WorkerSource.reloadTile}.\n */\n async reloadTile(params: WorkerTileParameters): Promise<WorkerTileResult> {\n const uid = params.uid;\n const workerTile = this.tileState.getLoaded(uid);\n if (!workerTile) throw new Error('Should not be trying to reload a tile that was never loaded or has been removed');\n\n // If there was no vector tile data on the initial load, don't try to reparse the tile.\n if (!workerTile.vectorTile) {\n return;\n }\n\n workerTile.showCollisionBoxes = params.showCollisionBoxes;\n return await this._parseWorkerTile(workerTile, params);\n }\n\n /**\n * Implements {@link WorkerSource.abortTile}.\n */\n async abortTile(params: TileParameters): Promise<void> {\n this.tileState.abort(params.uid);\n }\n\n /**\n * Implements {@link WorkerSource.removeTile}.\n */\n async removeTile(params: TileParameters): Promise<void> {\n this.tileState.removeLoaded(params.uid);\n }\n}\n","import {DEMData} from '../data/dem_data.ts';\nimport {RGBAImage} from '../util/image.ts';\nimport type {Actor} from '../util/actor.ts';\nimport type {\n WorkerDEMTileParameters,\n TileParameters\n} from './worker_source.ts';\nimport {getImageData, isImageBitmap} from '../util/util.ts';\n\nexport class RasterDEMTileWorkerSource {\n actor: Actor;\n loaded: {[_: string]: DEMData};\n\n constructor() {\n this.loaded = {};\n }\n\n async loadTile(params: WorkerDEMTileParameters): Promise<DEMData | null> {\n const {uid, encoding, rawImageData, redFactor, greenFactor, blueFactor, baseShift} = params;\n const width = rawImageData.width + 2;\n const height = rawImageData.height + 2;\n const imagePixels: RGBAImage | ImageData = isImageBitmap(rawImageData) ?\n new RGBAImage({width, height}, await getImageData(rawImageData, -1, -1, width, height)) :\n rawImageData;\n const dem = new DEMData(uid, imagePixels, encoding, redFactor, greenFactor, blueFactor, baseShift);\n this.loaded ||= {};\n this.loaded[uid] = dem;\n return dem;\n }\n\n removeTile(params: TileParameters): void {\n const loaded = this.loaded,\n uid = params.uid;\n if (loaded?.[uid]) {\n delete loaded[uid];\n }\n }\n}\n","import {getJSON} from '../util/ajax.ts';\nimport {RequestPerformance} from '../util/request_performance.ts';\nimport {fromVectorTileJs, GeoJSONWrapper} from '@maplibre/vt-pbf';\nimport {EXTENT} from '../data/extent.ts';\nimport {GeoJSONVT, type GeoJSONVTOptions} from '@maplibre/geojson-vt';\nimport {createExpression, type FilterSpecification} from '@maplibre/maplibre-gl-style-spec';\nimport {isAbortError} from '../util/abort_error.ts';\nimport {WorkerTile} from './worker_tile.ts';\nimport {WorkerTileState} from './worker_tile_state.ts';\nimport {extend, JSON_PREFIX} from '../util/util.ts';\n\nimport type {GeoJSONSourceDiff} from './geojson_source_diff.ts';\nimport type {WorkerSource, WorkerTileParameters, TileParameters, WorkerTileResult} from './worker_source.ts';\nimport type {LoadVectorTileResult} from './vector_tile_worker_source.ts';\nimport type {RequestParameters} from '../util/ajax.ts';\nimport type {ClusterIDAndSource, GeoJSONWorkerSourceLoadDataResult, RemoveSourceParams} from '../util/actor_messages.ts';\nimport type {IActor} from '../util/actor.ts';\nimport type {StyleLayerIndex} from '../style/style_layer_index.ts';\n\n/**\n * The geojson worker options that can be passed to the worker\n */\nexport type GeoJSONWorkerOptions = {\n source?: string;\n geojsonVtOptions?: GeoJSONVTOptions;\n clusterProperties?: Record<string, [unknown, unknown]>;\n filter?: FilterSpecification;\n collectResourceTiming?: boolean;\n};\n\n/**\n * Parameters needed to load GeoJSON to the worker - must specify either a `request`, `data` or `dataDiff`.\n */\nexport type LoadGeoJSONParameters = GeoJSONWorkerOptions & {\n type: 'geojson';\n /** The geojson source ID. */\n source: string;\n /**\n * Request parameters including a URL to fetch GeoJSON data.\n */\n request?: RequestParameters;\n /**\n * GeoJSON data to set as the source's data.\n */\n data?: GeoJSON.GeoJSON;\n /**\n * GeoJSONSourceDiff to apply to the existing GeoJSON source data.\n */\n dataDiff?: GeoJSONSourceDiff;\n /**\n * Update the supercluster using the latest worker cluster options.\n */\n updateCluster?: boolean;\n};\n\n/**\n * The {@link WorkerSource} implementation that supports {@link GeoJSONSource}.\n * This class is designed to be easily reused to support custom source types\n * for data formats that can be parsed/converted into an in-memory GeoJSON\n * representation. To do so, create it with\n * `new GeoJSONWorkerSource(actor, layerIndex, customLoadGeoJSONFunction)`.\n * For a full example, see [mapbox-gl-topojson](https://github.com/developmentseed/mapbox-gl-topojson).\n */\nexport class GeoJSONWorkerSource implements WorkerSource {\n actor: IActor;\n layerIndex: StyleLayerIndex;\n availableImages: string[];\n tileState: WorkerTileState;\n\n _pendingRequest: AbortController;\n _geoJSONIndex: GeoJSONVT;\n _createGeoJSONIndex: typeof createGeoJSONIndex;\n\n constructor(actor: IActor, layerIndex: StyleLayerIndex, availableImages: string[], createGeoJSONIndexFunc: typeof createGeoJSONIndex = createGeoJSONIndex) {\n this.actor = actor;\n this.layerIndex = layerIndex;\n this.availableImages = availableImages;\n this.tileState = new WorkerTileState();\n this._createGeoJSONIndex = createGeoJSONIndexFunc;\n }\n\n /**\n * Retrieves and sends loaded vector tiles to the main thread.\n */\n loadVectorTile(params: WorkerTileParameters): LoadVectorTileResult | null {\n if (!this._geoJSONIndex) throw new Error('Unable to parse the data into a cluster or geojson');\n\n const {z, x, y} = params.tileID.canonical;\n const geoJSONTile = this._geoJSONIndex.getTile(z, x, y);\n if (!geoJSONTile) return null;\n\n const geojsonWrapper = new GeoJSONWrapper(geoJSONTile.features, {version: 2, extent: EXTENT});\n return {\n vectorTile: geojsonWrapper,\n rawData: fromVectorTileJs(geojsonWrapper, JSON_PREFIX).buffer\n };\n\n }\n\n /**\n * Implements {@link WorkerSource.loadTile}.\n */\n async loadTile(params: WorkerTileParameters): Promise<WorkerTileResult | null> {\n const {uid} = params;\n\n const workerTile = new WorkerTile(params);\n workerTile.abort = new AbortController();\n try {\n const loadResult = this.loadVectorTile(params);\n if (!loadResult) return null;\n\n const {vectorTile, rawData} = loadResult;\n\n workerTile.vectorTile = vectorTile;\n this.tileState.markLoaded(uid, workerTile);\n const parsingState = {rawData};\n this.tileState.setParsing(uid, parsingState);\n\n return await this._parseWorkerTile(workerTile, params);\n } catch (err) {\n this.tileState.markLoaded(uid, workerTile);\n throw err;\n }\n }\n\n async _parseWorkerTile(workerTile: WorkerTile, params: WorkerTileParameters): Promise<WorkerTileResult> {\n const parseState = this.tileState.getParsing(workerTile.uid);\n\n let result = await workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor, params.subdivisionGranularity);\n\n // We need to pass rawTileData back to the main thread so that it can be stored in the Tile and FeatureIndex.\n // After the main thread has successfully received and stored rawTileData,\n // we no longer need to store it in the worker or transfer additional copies of it.\n if (parseState) {\n const {rawData} = parseState;\n // Return a copy of rawData to the main thread to avoid clearing the worker's buffer\n result = extend({rawTileData: rawData.slice(0), encoding: 'mvt'}, result);\n this.tileState.removeParsing(workerTile.uid);\n }\n\n return result;\n }\n\n /**\n * Implements {@link WorkerSource.abortTile}.\n */\n async abortTile(params: TileParameters): Promise<void> {\n this.tileState.abort(params.uid);\n }\n\n /**\n * Implements {@link WorkerSource.removeTile}.\n */\n async removeTile(params: TileParameters): Promise<void> {\n this.tileState.removeLoaded(params.uid);\n }\n\n /**\n * Fetches (if appropriate), parses and indexes geojson data into tiles. This\n * preparatory method must be called before {@link GeoJSONWorkerSource.loadTile}\n * can correctly serve up tiles. The first call to this method must contain a valid\n * {@link params.data}, {@link params.request} or {@link params.dataDiff}. Subsequent\n * calls may omit these parameters to reprocess the existing data (such as to update\n * clustering options).\n *\n * Defers to {@link GeoJSONWorkerSource.loadAndProcessGeoJSON} for the pre-processing.\n *\n * When a `loadData` request comes in while a previous one is being processed,\n * the previous one is aborted.\n *\n * @param params - the parameters\n * @returns a promise that resolves when the data is loaded and parsed into a GeoJSON object\n */\n async loadData(params: LoadGeoJSONParameters): Promise<GeoJSONWorkerSourceLoadDataResult> {\n this._pendingRequest?.abort();\n\n const timing = this._startRequestTiming(params);\n this._pendingRequest = new AbortController();\n try {\n await this.loadAndProcessGeoJSON(params, this._pendingRequest);\n delete this._pendingRequest;\n this.tileState.clearLoaded();\n\n // Sending a large GeoJSON payload from the worker to the main thread is slow so only do if necessary.\n // Send data only if it was loaded from a URL, otherwise the main thread already has a copy of this data.\n const result: GeoJSONWorkerSourceLoadDataResult = {};\n if (params.request) result.data = params.data;\n\n this._finishRequestTiming(timing, params, result);\n return result;\n } catch (err) {\n delete this._pendingRequest;\n if (!isAbortError(err)) throw err;\n return {abandoned: true};\n }\n }\n\n _startRequestTiming(params: LoadGeoJSONParameters): RequestPerformance | undefined {\n if (!params.request?.collectResourceTiming) return;\n return new RequestPerformance(params.request.url);\n }\n\n _finishRequestTiming(timing: RequestPerformance, params: LoadGeoJSONParameters, result: GeoJSONWorkerSourceLoadDataResult): void {\n const timingData = timing?.finish();\n if (!timingData) return;\n\n // it's necessary to eval the result of getEntriesByName() here via parse/stringify\n // late evaluation in the main thread causes TypeError: illegal invocation\n result.resourceTiming = {[params.source]: JSON.parse(JSON.stringify(timingData))};\n }\n\n /**\n * Implements {@link WorkerSource.reloadTile}.\n *\n * If the tile is loaded, reload by re-parsing the already available tile data.\n * Otherwise, such as after a setData() call, we load the tile fresh.\n *\n * @param params - the parameters\n * @returns A promise that resolves when the tile is reloaded\n */\n async reloadTile(params: WorkerTileParameters): Promise<WorkerTileResult> {\n const uid = params.uid;\n const workerTile = this.tileState.getLoaded(uid);\n if (!workerTile) {\n return await this.loadTile(params);\n }\n\n // If there was no vector tile data on the initial load, don't try to reparse the tile.\n if (!workerTile.vectorTile) {\n return;\n }\n\n workerTile.showCollisionBoxes = params.showCollisionBoxes;\n return await this._parseWorkerTile(workerTile, params);\n }\n\n /**\n * Fetch, parse and process GeoJSON according to the given parameters.\n * Defers to {@link GeoJSONWorkerSource._loadGeoJSONFromString} for the fetching and parsing.\n *\n * @param params - the parameters\n * @param abortController - the abort controller that allows aborting this operation\n * @returns a promise that is resolved with the processes GeoJSON\n */\n async loadAndProcessGeoJSON(params: LoadGeoJSONParameters, abortController: AbortController): Promise<GeoJSON.GeoJSON> {\n if (params.request) {\n params.data = (await getJSON<GeoJSON.GeoJSON>(params.request, abortController)).data;\n }\n\n if (params.data) {\n params.data = this._filterGeoJSON(params.data, params.filter, params.source);\n this._geoJSONIndex = this._createGeoJSONIndex(params.data, params);\n return;\n }\n\n if (params.dataDiff) {\n this._geoJSONIndex ??= this._createGeoJSONIndex({type: 'FeatureCollection', features: []}, params);\n this._geoJSONIndex.updateData(params.dataDiff, this._getFilterPredicate(params.filter, params.source));\n return;\n }\n\n if (params.updateCluster) {\n this._geoJSONIndex.updateClusterOptions(params.geojsonVtOptions.cluster, getSuperclusterOptions(params));\n }\n\n if (this._geoJSONIndex == null) {\n throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`);\n }\n }\n\n /**\n * Applies a filter to a GeoJSON object.\n */\n _filterGeoJSON(data: GeoJSON.GeoJSON, filter: FilterSpecification, source: string): GeoJSON.GeoJSON {\n if (data.type !== 'FeatureCollection') return data;\n\n const predicate = this._getFilterPredicate(filter, source);\n if (!predicate) return data;\n\n return {type: 'FeatureCollection', features: data.features.filter(feature => predicate(feature))};\n }\n\n /**\n * Gets a predicate function that can be used to filter GeoJSON features.\n */\n _getFilterPredicate(filter: FilterSpecification, source: string): (feature: GeoJSON.Feature) => boolean {\n if (typeof filter !== 'boolean' && !filter?.length) return undefined;\n\n const compiled = createExpression(filter, `sources.${source}.filter`, {type: 'boolean', 'property-type': 'data-driven', overridable: false, transition: false} as any);\n if (compiled.result === 'error') {\n throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', '));\n }\n\n return (feature: GeoJSON.Feature) => compiled.value.evaluate({zoom: 0}, feature as any);\n }\n\n async removeSource(_params: RemoveSourceParams): Promise<void> {\n this._pendingRequest?.abort();\n }\n\n getClusterExpansionZoom(params: ClusterIDAndSource): number {\n return this._geoJSONIndex.getClusterExpansionZoom(params.clusterId);\n }\n\n getClusterChildren(params: ClusterIDAndSource): GeoJSON.Feature[] {\n return this._geoJSONIndex.getClusterChildren(params.clusterId);\n }\n\n getClusterLeaves(params: {\n clusterId: number;\n limit: number;\n offset: number;\n }): GeoJSON.Feature[] {\n return this._geoJSONIndex.getClusterLeaves(params.clusterId, params.limit, params.offset);\n }\n}\n\nexport function createGeoJSONIndex(data: GeoJSON.GeoJSON, params: LoadGeoJSONParameters): GeoJSONVT {\n const options = extend(params.geojsonVtOptions || {}, {\n updateable: true,\n clusterOptions: getSuperclusterOptions(params),\n });\n\n return new GeoJSONVT(data, options);\n}\n\nfunction getSuperclusterOptions({geojsonVtOptions, clusterProperties, source}: LoadGeoJSONParameters) {\n if (!clusterProperties || !geojsonVtOptions.clusterOptions) return geojsonVtOptions.clusterOptions;\n\n const mapExpressions = {};\n const reduceExpressions = {};\n const globals = {accumulated: null, zoom: 0};\n const feature = {properties: null};\n const propertyNames = Object.keys(clusterProperties);\n\n for (const key of propertyNames) {\n const [operator, mapExpression] = clusterProperties[key];\n\n const mapExpressionParsed = createExpression(mapExpression, `sources.${source}.clusterProperties.${key}[1]`);\n const reduceExpressionParsed = createExpression(\n typeof operator === 'string' ? [operator, ['accumulated'], ['get', key]] : operator, `sources.${source}.clusterProperties.${key}[0]`);\n\n mapExpressions[key] = mapExpressionParsed.value;\n reduceExpressions[key] = reduceExpressionParsed.value;\n }\n\n geojsonVtOptions.clusterOptions.map = (pointProperties) => {\n feature.properties = pointProperties;\n const properties = {};\n for (const key of propertyNames) {\n properties[key] = mapExpressions[key].evaluate(globals, feature);\n }\n return properties;\n };\n geojsonVtOptions.clusterOptions.reduce = (accumulated, clusterProperties) => {\n feature.properties = clusterProperties;\n for (const key of propertyNames) {\n globals.accumulated = accumulated[key];\n accumulated[key] = reduceExpressions[key].evaluate(globals, feature);\n }\n };\n return geojsonVtOptions.clusterOptions;\n}\n","import {Actor, type ActorTarget, type IActor} from '../util/actor.ts';\nimport {StyleLayerIndex} from '../style/style_layer_index.ts';\nimport {VectorTileWorkerSource} from './vector_tile_worker_source.ts';\nimport {RasterDEMTileWorkerSource} from './raster_dem_tile_worker_source.ts';\nimport {rtlWorkerPlugin, type RTLTextPlugin} from './rtl_text_plugin_worker.ts';\nimport {GeoJSONWorkerSource, type LoadGeoJSONParameters} from './geojson_worker_source.ts';\nimport {isWorker} from '../util/util.ts';\nimport {addProtocol, removeProtocol} from './protocol_crud.ts';\nimport {makeRequest} from '../util/ajax.ts';\n\nimport {type PluginState} from './rtl_text_plugin_status.ts';\nimport type {\n WorkerSource,\n WorkerSourceConstructor,\n WorkerTileParameters,\n WorkerDEMTileParameters,\n TileParameters\n} from '../source/worker_source.ts