maplibre-gl
Version:
BSD licensed community fork of mapbox-gl, a WebGL interactive maps library
1 lines • 90.5 kB
Source Map (JSON)
{"version":3,"file":"maplibre-gl-worker.mjs","names":["ensureError","removeProtocol","getJSON","clipGeometry","AlphaImage","makeRequest","potpack","JSON_PREFIX","rtlWorkerPlugin","CollisionBoxArray","GeoJSONVT","ImageAtlas","isAbortError","addProtocol","RGBAImage","warnOnce","Point","EXTENT","getArrayBuffer","createStyleLayer","GeoJSONWrapper","OverscaledTileID","VectorTile","Actor","mapObject","refProperties","MLTVectorTile","fromVectorTileJs","featureFilter","isImageBitmap","isWorker","DictionaryCoder","FeatureIndex","register","getImageData","BoundedLRUCache","EvaluationParameters","extend","createExpression","DEMData","PbfReader","stringify","type","obj","str","val","keys","i","getKey","key","k","layer","groupByLayout","groups","layers","cachedKeys","group","result","StyleLayerIndex","layerConfigs","globalState","layerConfig","id","removedIds","sourceId","sourceGroup","sourceLayerId","sourceLayerFamilies","GlyphAtlas","positions","bins","stack","stacks","stackPositions","variant","glyphs","src","bin","image","w","h","WorkerTile","params","data","sourceLayerCoder","featureIndex","buckets","options","layerFamilies","layerIndex","sourceLayer","sourceLayerIndex","features","index","feature","family","recalculateLayers","availableImages","l","variants","request","getGlyphsPromise","abortController","actor","icons","getIconsPromise","patterns","getPatternsPromise","dashes","getDashesPromise","glyphMap","iconMap","patternMap","dashPositions","glyphAtlas","imageAtlas","bucket","b","parameters","zoom","WorkerTileState","uid","tile","state","RequestPerformance","url","resourceTimingData","VectorTileFeatureOverzoomed","properties","extent","geometry","ring","point","VectorTileLayerOverzoomed","layerName","VectorTileOverzoomed","sliceVectorTileLayer","scale","targetTileID","maxZoomTileID","offsetX","offsetY","featureWrappers","VectorTileWorkerSource","rawData","ex","bytes","isGzipped","errorMessage","overzoomParameters","timing","workerTile","tileResponse","tileResult","vectorTile","cacheControl","resourceTiming","parsingState","err","response","parseState","encoding","expires","etag","timingData","cacheKey","tileID","cachedOverzoomTile","overzoomedVectorTile","source","maxZoomVectorTile","slicedTileLayer","overzoomedVectorTileResult","RasterDEMTileWorkerSource","width","rawImageData","height","imagePixels","dem","redFactor","greenFactor","blueFactor","baseShift","loaded","GeoJSONWorkerSource","createGeoJSONIndex","createGeoJSONIndexFunc","geoJSONTile","z","x","y","geojsonWrapper","loadResult","getSuperclusterOptions","predicate","filter","compiled","clusterProperties","geojsonVtOptions","mapExpressions","reduceExpressions","globals","propertyNames","operator","mapExpression","mapExpressionParsed","reduceExpressionParsed","pointProperties","accumulated","loadScript","code","blobUrl","Worker","self","name","WorkerSource","rtlTextPlugin","mapId","worker","images","workerSource","ws","incomingState","layerIndexes","sourceType","sourceName","message"],"sources":["../node_modules/@maplibre/maplibre-gl-style-spec/dist/group_by_layout.mjs","../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 { refProperties } from \"./util/ref_properties.mjs\";\n//#region src/group_by_layout.ts\nfunction stringify(obj) {\n\tconst type = typeof obj;\n\tif (type === \"number\" || type === \"boolean\" || type === \"string\" || obj === void 0 || obj === null) return JSON.stringify(obj);\n\tif (Array.isArray(obj)) {\n\t\tlet str = \"[\";\n\t\tfor (const val of obj) str += `${stringify(val)},`;\n\t\treturn `${str}]`;\n\t}\n\tconst keys = Object.keys(obj).sort();\n\tlet str = \"{\";\n\tfor (let i = 0; i < keys.length; i++) str += `${JSON.stringify(keys[i])}:${stringify(obj[keys[i]])},`;\n\treturn `${str}}`;\n}\nfunction getKey(layer) {\n\tlet key = \"\";\n\tfor (const k of refProperties) key += `/${stringify(layer[k])}`;\n\treturn key;\n}\n/**\n* Groups layers by their layout-affecting properties.\n* These are the properties that were formerly used by explicit `ref` mechanism\n* for layers: 'type', 'source', 'source-layer', 'minzoom', 'maxzoom',\n* 'filter', and 'layout'.\n*\n* The input is not modified. The output layers are references to the\n* input layers.\n*\n* @param layers - an array of {@link LayerSpecification}.\n* @param cachedKeys - an object to keep already calculated keys.\n* @returns an array of arrays of {@link LayerSpecification} objects, where each inner array\n* contains layers that share the same layout-affecting properties.\n*/\nfunction groupByLayout(layers, cachedKeys) {\n\tconst groups = {};\n\tfor (let i = 0; i < layers.length; i++) {\n\t\tconst k = cachedKeys && cachedKeys[layers[i].id] || getKey(layers[i]);\n\t\tif (cachedKeys) cachedKeys[layers[i].id] = k;\n\t\tlet group = groups[k];\n\t\tif (!group) group = groups[k] = [];\n\t\tgroup.push(layers[i]);\n\t}\n\tconst result = [];\n\tfor (const k in groups) result.push(groups[k]);\n\treturn result;\n}\n//#endregion\nexport { groupByLayout };\n\n//# sourceMappingURL=group_by_layout.mjs.map","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';\n\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 {GlyphMap, GlyphMetrics} from '../style/style_glyph.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 * Glyph positions keyed by font stack, variant, and grapheme cluster.\n */\nexport type GlyphPositions = Record<string, Record<string, Record<string, GlyphPosition>>>;\n\nexport class GlyphAtlas {\n image: AlphaImage;\n positions: GlyphPositions;\n\n constructor(stacks: GlyphMap) {\n const positions: GlyphPositions = {};\n const bins = [];\n\n for (const stack in stacks) {\n const stackPositions = positions[stack] = {};\n\n for (const variant in stacks[stack]) {\n const glyphs = stacks[stack][variant];\n stackPositions[variant] = {};\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[variant][id] = {rect: bin, metrics: src.metrics};\n }\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 for (const variant in stacks[stack]) {\n const glyphs = stacks[stack][variant];\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][variant][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\n this.image = image;\n this.positions = positions;\n }\n}\n\nregister('GlyphAtlas', GlyphAtlas);\n","import {FeatureIndex} from '../data/feature_index.ts';\nimport {CollisionBoxArray} from '../data/array_types.g.ts';\nimport {DictionaryCoder} from '../util/dictionary_coder.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';\nimport {type GetDashesResponse, MessageType, type GetImagesResponse} from '../util/actor_messages.ts';\n\nimport type {Bucket, PopulateParameters} 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 {GlyphMap} from '../style/style_glyph.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 {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 /**\n * The etag of the response this tile was loaded from. A reload has no new response, so it is returned again\n * to keep the main thread's tile etag intact for the next expiry refresh.\n */\n etag?: string;\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: PopulateParameters = {\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 const stacks = mapObject(options.glyphDependencies, variants => mapObject(variants, glyphs => Object.keys(glyphs)));\n\n for (const request of this.inFlightDependencies) {\n request?.abort();\n }\n this.inFlightDependencies = [];\n\n let getGlyphsPromise = Promise.resolve<GlyphMap>({});\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.hasDependencies) continue;\n\n recalculateLayers(bucket.layers, this.zoom, availableImages);\n bucket.addFeatures({\n options,\n canonical: this.tileID.canonical,\n glyphMap,\n glyphPositions: glyphAtlas.positions,\n iconMap,\n iconPositions: imageAtlas.iconPositions,\n patternMap,\n patternPositions: imageAtlas.patternPositions,\n dashPositions,\n showCollisionBoxes: this.showCollisionBoxes\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 {ExpiryData} from '../util/ajax.ts';\nimport type {WorkerTile} from './worker_tile.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';\n\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';\n\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 workerTile.etag = tileResponse.etag;\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 } else if (workerTile.etag) {\n // Reload: return the stored etag since the main thread overwrites the tile's etag with every\n // result (#3309). cacheControl/expires are deliberately not re-sent: the main thread anchors\n // max-age to the time it receives them, and the tile's expiration already survives a reload.\n result = extend(result, {etag: workerTile.etag});\n }\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 {getImageData, isImageBitmap} from '../util/util.ts';\n\nimport type {Actor} from '../util/actor.ts';\nimport type {\n WorkerDEMTileParameters,\n TileParameters\n} from './worker_source.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 + 4;\n const height = rawImageData.height + 4;\n const imagePixels: RGBAImage | ImageData = isImageBitmap(rawImageData) ?\n new RGBAImage({width, height}, await getImageData(rawImageData, -2, -2, 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, after applying {@link dataDiff} if there is one.\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 }\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';\nimport {\n MessageType,\n type ClusterIDAndSource,\n type GetClusterLeavesParams,\n type RemoveSourceParams,\n type UpdateLayersParameters\n} from '../util/actor_messages.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';\nimport type {WorkerGlobalScopeInterface} from '../util/web_worker.ts';\nimport type {LayerSpecification} from '@maplibre/maplibre-gl-style-spec';\n\n/**\n * Loads an external script into worker (global) scope. The loader picks a\n * strategy based on what the script actually is:\n *\n * - `.mjs` URLs: dynamic `import()` directly, no fetch/sniff overhead. Worker\n * CSP needs `script-src` to permit the URL.\n *\n * - Other URLs: fetch the source and sniff for ESM syntax (top-level `import`\n * or `export`). If ESM is detected, run it through a blob-URL dynamic\n * `import()` so the browser parses it as a module; this requires\n * `script-src blob:` in the worker CSP. Otherwise treat it as UMD/IIFE and\n * run it via `globalThis.eval`, which requires `script-src 'unsafe-eval'`.\n */\nasync function loadScript(url: string): Promise<void> {\n if (url.endsWith('.mjs')) {\n await import(/* @vite-ignore */ url);\n return;\n }\n const response = await fetch(url, {credentials: 'same-origin'});\n if (!response.ok) {\n throw new Error(`Failed to load ${url}: ${response.status}`);\n }\n const code = await response.text();\n // Top-level `import`/`export` keywords are unique to ESM. UMD scripts\n // assign to `module.exports` / `exports.foo` — those don't match.\n if (/^[ \\t]*(import|export)\\s/m.test(code)) {\n const blobUrl = URL.createObjectURL(new Blob([code], {type: 'text/javascript'}));\n try {\n await import(/* @vite-ignore */ blobUrl);\n } finally {\n URL.revokeObjectURL(blobUrl);\n }\n return;\n }\n // Run the code in the worker's global scope (not inside this function),\n // so UMD/IIFE plugin scripts can assign to globals like\n // `self.registerRTLTextPlugin`. Calling eval as a property access\n // (rather than the bare `eval` identifier) is what makes it global-scope.\n globalThis.eval(code);\n}\n\n/**\n * The Worker class responsible for background thread related execution\n */\nexport default class Worker {\n self: WorkerGlobalScopeInterface & ActorTarget;\n actor: Actor;\n layerIndexes: {[_: string]: StyleLayerIndex};\n availableImages: {[_: string]: string[]};\n externalWorkerSourceTypes: { [_: string]: WorkerSourceConstructor };\n /**\n * This holds a cache for the already created worker source instances.\n * The cache is build with the following hierarchy:\n * [mapId][sourceType][sourceName]: worker source instance\n * sourceType can be 'vector' for example\n */\n workerSources: {\n [_: string]: {\n [_: string]: {\n [_: string]: WorkerSource;\n };\n };\n };\n /**\n * This holds a cache for the already created DEM worker source instances.\n * The cache is build with the following hierarchy:\n * [mapId][sourceType]: DEM worker source instance\n * sourceType can be 'raster-dem' for example\n */\n demWorkerSources: {\n [_: string]: {\n [_: string]: RasterDEMTileWorkerSource;\n };\n };\n referrer: string;\n globalStates: Map<string, Record<string, any>>;\n\n constructor(self: WorkerGlobalScopeInterface & ActorTarget) {\n this.self = self;\n this.actor = new Actor(self);\n\n this.layerIndexes = {};\n this.availableImages = {};\n\n this.workerSources = {};\n this.demWorkerSources = {};\n this.externalWorkerSourceTypes = {};\n\n this.globalStates = new Map<string, Record<string, any>>();\n\n this.self.registerWorkerSource = (name: string, WorkerSource: WorkerSourceConstructor) => {\n if (this.externalWorkerSourceTypes[name]) {\n throw new Error(`Worker source with name \"${name}\" already registered.`);\n }\n this.externalWorkerSourceTypes[name] = WorkerSource;\n };\n\n this.self.addProtocol = addProtocol;\n this.self.removeProtocol = removeProtocol;\n\n /**\n * Invoked by a right-to-left text plugin once it has fetched and parsed.\n *\n * @deprecated MapLibre shapes Arabic and reorders bidirectional text itself. A plugin\n * registered here still replaces the built-in implementation, but this will be removed in a\n * future release.\n */\n this.self.registerRTLTextPlugin = (rtlTextPlugin: RTLTextPlugin) => {\n rtlWorkerPlugin.setMethods(rtlTextPlugin);\n };\n\n this.self.makeRequest = makeRequest;\n\n this.actor.registerMessageHandler(MessageType.loadDEMTile, (mapId: string, params: WorkerDEMTileParameters) => {\n return this._getDEMWorkerSource(mapId, params.source).loadTile(params);\n });\n\n this.actor.registerMessageHandler(MessageType.removeDEMTile, async (mapId: string, params: TileParameters) => {\n this._getDEMWorkerSource(mapId, params.source).removeTile(params);\n });\n\n this.actor.registerMessageHandler(MessageType.getClusterExpansionZoom, async (mapId: string, params: ClusterIDAndSource) => {\n return (this._getWorkerSource(mapId, params.type, params.source) as GeoJSONWorkerSource).getClusterExpansionZoom(params);\n });\n\n this.actor.registerMessageHandler(MessageType.getClusterChildren, async (mapId: string, params: ClusterIDAndSource) => {\n return (this._getWorkerSource(mapId, params.type, params.source) as GeoJSONWorkerSource).getClusterChildren(params);\n });\n\n this.actor.registerMessageHandler(MessageType.getClusterLeaves, async (mapId: string, params: GetClusterLeavesParams) => {\n return (this._getWorkerSource(mapId, params.type, params.source) as GeoJSONWorkerSource).getClusterLeaves(params);\n });\n\n this.actor.registerMessageHandler(MessageType.loadData, (mapId: string, params: LoadGeoJSONParameters) => {\n return (this._getWorkerSource(mapId, params.type, params.source) as GeoJSONWorkerSource).loadData(params);\n });\n\n this.actor.registerMessageHandler(MessageType.loadTile, (mapId: string, params: WorkerTileParameters) => {\n return this._getWorkerSource(mapId, params.type, params.source).loadTile(params);\n });\n\n this.actor.registerMessageHandler(MessageType.reloadTile, (mapId: string, params: WorkerTileParameters) => {\n return this._getWorkerSource(mapId, params.type, params.source).reloadTile(params);\n });\n\n this.actor.registerMessageHandler(MessageType.abortTile, (mapId: string, params: TileParameters) => {\n return this._getWorkerSource(mapId, params.type, params.source).abortTile(params);\n });\n\n this.actor.registerMessageHandler(MessageType.removeTile, (mapId: string, params: TileParameters) => {\n return this._getWorkerSource(mapId, params.type, params.source).removeTile(params);\n });\n\n this.actor.registerMessageHandler(MessageType.removeSource, async (mapId: string, params: RemoveSourceParams) => {\n if (!this.workerSources[mapId]?.[params.type]?.[params.source]) {\n return;\n }\n\n const worker = this.workerSources[mapId][params.type][params.source];\n delete this.workerSources[mapId][params.type][params.source];\n\n if (worker.removeSource !== undefined) {\n worker.removeSource(params);\n }\n });\n\n this.actor.registerMessageHandler(MessageType.removeMap, async (mapId: string) => {\n delete this.layerIndexes[mapId];\n delete this.availableImages[mapId];\n delete this.workerSources[mapId];\n delete this.demWorkerSources[mapId];\n this.globalStates.delete(mapId);\n });\n\n this.actor.registerMessageHandler(MessageType.setReferrer, async (_mapId: string, params: string) => {\n this.referrer = params;\n });\n\n this.actor.registerMessageHandler(MessageType.syncRTLPluginState, (mapId: string, params: PluginState) => {\n return this._syncRTLPluginState(mapId, params);\n });\n\n this.actor.registerMessageHandler(MessageType.importScript, async (_mapId: string, params: string) => {\n await loadScript(params);\n });\n\n this.actor.registerMessageHandler(MessageType.setImages, (mapId: string, params: string[]) => {\n return this._setImages(mapId, params);\n });\n\n this.actor.registerMessageHandler(MessageType.updateLayers, async (mapId: string, params: UpdateLayersParameters) => {\n this._getLayerIndex(mapId).update(params.layers, params.removedIds, this._getGlobalState(mapId));\n });\n\n this.actor.registerMessageHandler(MessageType.updateGlobalState, async (mapId: string, params: Record<string, any>) => {\n const globalState = this._getGlobalState(mapId);\n for (const key in params) {\n globalState[key] = params[key];\n }\n });\n\n this.actor.registerMessageHandler(MessageType.setLayers, async (mapId: string, params: LayerSpecification[]) => {\n this._getLayerIndex(mapId).replace(params, this._getGlobalState(mapId));\n });\n }\n\n private _getGlobalState(mapId: string): Record<string, any> {\n let state = this.globalStates.get(mapId);\n if (!state) {\n state = {};\n this.globalStates.set(mapId, state);\n }\n return state;\n }\n\n private async _setImages(mapId: string, images: string[]): Promise<void> {\n this.availableImages[mapId] = images;\n for (const workerSource in this.workerSources[mapId]) {\n const ws = this.workerSources[mapId][workerSource];\n for (const source in ws) {\n ws[source].availableImages = images;\n }\n }\n }\n\n private async _syncRTLPluginState(mapId: string, incomingState: PluginState): Promise<PluginState> {\n return await rtlWorkerPlugin.syncState(incomingState, loadScript);\n }\n\n private _getAvailableImages(mapId: string) {\n let availableImages = this.availableImages[mapId];\n\n availableImages ||= [];\n\n return availableImages;\n }\n\n private _getLayerIndex(mapId: string) {\n let layerIndexes = this.layerIndexes[mapId];\n layerIndexes ||= this.layerIndexes[mapId] = new StyleLayerIndex();\n return layerIndexes;\n }\n\n /**\n * This is basically a lazy initialization of a worker per mapId and sourceType and sourceName\n * @param mapId - the mapId\n * @param sourceType - the source type - 'vector' for example\n * @param sourceName - the source name - 'osm' for example\n * @returns a new instance or a cached one\n */\n private _getWorkerSource(mapId: string, sourceType: string, sourceName: string): WorkerSource {\n this.workerSources[mapId] ||= {};\n this.workerSources[mapId][sourceType] ||= {};\n\n if (!this.workerSources[mapId][sourceType][sourceName]) {\n // use a wrapped actor so that we can attach a target mapId param\n // to any messages invoked by the WorkerSource, this is very important when there are multiple maps\n const actor: IActor = {\n sendAsync: (message, abortController) => {\n message.targetMapId = mapId;\n return this.actor.sendAsync(message, abortController);\n }\n };\n switch (sourceType) {\n case 'vector':\n this.workerSources[mapId][sourceType][sourceName] = new VectorTileWorkerSource(actor, this._getLayerIndex(mapId), this._getAvailableImages(mapId));\n break;\n case 'geojson':\n this.workerSources[mapId][sourceType][sourceName] = new GeoJSONWorkerSource(actor, this._getLayerIndex(mapId), this._getAvailableImages(mapId));\n break;\n default:\n this.workerSources[mapId][sourceType][sourceName] = new (this.externalWorkerSourceTypes[sourceType])(actor, this._getLayerIndex(mapId), this._getAvailableImages(mapId));\n break;\n }\n }\n\n return this.workerSources[mapId][sourceType][sourceName];\n }\n\n /**\n * This is basically a lazy initialization of a worker per mapId and source\n * @param mapId - the mapId\n * @param sourceType - the source type - 'raster-dem' for example\n * @returns a new instance or a cached one\n */\n private _getDEMWorkerSource(mapId: string, sourceType: string) {\n this.demWorkerSources[mapId] ||= {};\n this.demWorkerSources[mapId][sourceType] ||= new RasterDEMTileWorkerSource();\n\n return this.demWorkerSources[mapId][sourceType];\n }\n}\n\nif (isWorker(self)) {\n self.worker = new Worker(self);\n}\n"],"x_google_ignoreList":[0],"mappings":";;;;+VAEA,SAASyC,EAAU,EAAK,CACvB,IAAMC,EAAO,OAAOC,EACpB,GAAID,IAAS,UAAYA,IAAS,WAAaA,IAAS,UAAYC,GAA0B,KAAM,OAAO,KAAK,UAAUA,CAAG,EAC7H,GAAI,MAAM,QAAQA,CAAG,EAAG,CACvB,IAAIC,EAAM,IACV,IAAK,IAAMC,KAAOF,EAAK,GAAO,GAAGF,EAAUI,CAAG,EAAE,GAChD,MAAO,GAAGD,EAAI,EACf,CACA,IAAME,EAAO,OAAO,KAAKH,CAAG,CAAC,CAAC,KAAK,EAC/BC,EAAM,IACV,IAAK,IAAIG,EAAI,EAAGA,EAAID,EAAK,OAAQ,IAAK,GAAO,GAAG,KAAK,UAAUA,EAAKC,EAAE,EAAE,GAAGN,EAAUE,EAAIG,EAAKC,GAAG,EAAE,GACnG,MAAO,GAAGH,EAAI,EACf,CACA,SAASI,EAAO,EAAO,CACtB,IAAIC,EAAM,GACV,IAAK,IAAMC,KAAKzB,EAAe,GAAO,IAAIgB,EAAUU,EAAMD,EAAE,IAC5D,OAAOD,CACR,CAeA,SAASG,EAAc,EAAQ,EAAY,CAC1C,IAAMC,EAAS,CAAC,EAChB,IAAK,IAAIN,EAAI,EAAGA,EAAIO,EAAO,OAAQ,IAAK,CACvC,IAAMJ,EAAIK,GAAcA,EAAWD,EAAOP,EAAE,CAAC,KAAOC,EAAOM,EAAOP,EAAE,EAChEQ,IAAY,EAAWD,EAAOP,EAAE,CAAC,IAAMG,GAC3C,IAAIM,EAAQH,EAAOH,GACnB,AAAYM,IAAQ,EAAON,GAAK,CAAC,EACjCM,EAAM,KAAKF,EAAOP,EAAE,CACrB,CACA,IAAMU,EAAS,CAAC,EAChB,IAAK,IAAMP,KAAKG,EAAQI,EAAO,KAAKJ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