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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/README.md +12 -7
  2. package/THIRD-PARTY-NOTICES.md +7 -5
  3. package/dist/geojson-task-worker.js +3166 -0
  4. package/dist/geojson-task-worker.js.map +6 -0
  5. package/dist/geojson-worker.js +1089 -7
  6. package/dist/geojson-worker.js.map +3 -3
  7. package/dist/index.cjs +9588 -2093
  8. package/dist/index.cjs.map +3 -3
  9. package/dist/index.js +9599 -2090
  10. package/dist/index.js.map +3 -3
  11. package/dist/map-style.cjs +456 -20
  12. package/dist/map-style.cjs.map +3 -3
  13. package/dist/map-style.js +456 -19
  14. package/dist/map-style.js.map +2 -2
  15. package/dist/types/basemap-error.d.ts +52 -0
  16. package/dist/types/basemap-layer.d.ts +378 -25
  17. package/dist/types/basemap-protocol.d.ts +91 -0
  18. package/dist/types/basemap-request.d.ts +73 -0
  19. package/dist/types/circle-layer.d.ts +65 -8
  20. package/dist/types/color-relief-layer.d.ts +184 -0
  21. package/dist/types/dem-pixels.d.ts +40 -0
  22. package/dist/types/feature-state.d.ts +55 -0
  23. package/dist/types/fill-extrusion-lighting-extension.d.ts +1 -2
  24. package/dist/types/fill-outline-extension.d.ts +2 -3
  25. package/dist/types/fill-pattern.d.ts +35 -3
  26. package/dist/types/fill-style-extensions.d.ts +11 -59
  27. package/dist/types/geojson-resource.d.ts +18 -0
  28. package/dist/types/geojson-source.d.ts +13 -2
  29. package/dist/types/geojson-task-handler.d.ts +2 -0
  30. package/dist/types/geojson-task.d.ts +26 -0
  31. package/dist/types/geojson-tiler.d.ts +29 -2
  32. package/dist/types/geojson-worker.d.ts +5 -1
  33. package/dist/types/globe-horizon-extension.d.ts +2 -45
  34. package/dist/types/globe-layers.d.ts +141 -45
  35. package/dist/types/globe-line-angle-extension.d.ts +20 -17
  36. package/dist/types/glyph-store.d.ts +10 -1
  37. package/dist/types/heatmap-layer.d.ts +99 -0
  38. package/dist/types/hillshade-layer.d.ts +159 -27
  39. package/dist/types/icon-text-fit.d.ts +92 -0
  40. package/dist/types/image-source-layer.d.ts +142 -0
  41. package/dist/types/index.d.ts +25 -1
  42. package/dist/types/line-blur-extension.d.ts +3 -11
  43. package/dist/types/line-dash-extension.d.ts +53 -0
  44. package/dist/types/line-gradient-extension.d.ts +69 -0
  45. package/dist/types/line-metrics.d.ts +24 -0
  46. package/dist/types/line-pattern-extension.d.ts +50 -0
  47. package/dist/types/line-shape-extension.d.ts +76 -0
  48. package/dist/types/map-style-loader.d.ts +1 -1
  49. package/dist/types/map-style.d.ts +2 -2
  50. package/dist/types/mvt-label-layer.d.ts +111 -20
  51. package/dist/types/pmtiles-source.d.ts +38 -0
  52. package/dist/types/projected-background-layer.d.ts +63 -0
  53. package/dist/types/projected-bitmap-layer.d.ts +58 -0
  54. package/dist/types/projected-tile-data.d.ts +16 -0
  55. package/dist/types/projected-tile-selection.d.ts +72 -0
  56. package/dist/types/projected-tileset.d.ts +92 -0
  57. package/dist/types/projected-viewport.d.ts +76 -0
  58. package/dist/types/raster-color-extension.d.ts +4 -7
  59. package/dist/types/raster-fade.d.ts +155 -0
  60. package/dist/types/raster-tile-fingerprint.d.ts +11 -0
  61. package/dist/types/raster-tile-loader.d.ts +80 -0
  62. package/dist/types/shader-injection-plugin.d.ts +8 -0
  63. package/dist/types/source-features.d.ts +58 -0
  64. package/dist/types/source-tiles.d.ts +32 -0
  65. package/dist/types/sprite.d.ts +37 -3
  66. package/dist/types/stretch-icon-layer.d.ts +28 -0
  67. package/dist/types/style-accessor.d.ts +50 -12
  68. package/dist/types/style-expression.d.ts +22 -2
  69. package/dist/types/style-resolver.d.ts +47 -2
  70. package/dist/types/terrain-query.d.ts +39 -0
  71. package/dist/types/zoom-load-gate.d.ts +22 -0
  72. package/dist/types/zoom-paint-extension.d.ts +80 -11
  73. package/package.json +24 -21
  74. package/src/basemap-error.ts +82 -0
  75. package/src/basemap-layer.ts +1289 -101
  76. package/src/basemap-protocol.ts +353 -0
  77. package/src/basemap-request.ts +212 -0
  78. package/src/circle-layer.ts +430 -54
  79. package/src/color-relief-layer.ts +572 -0
  80. package/src/dem-pixels.ts +174 -0
  81. package/src/feature-state.ts +164 -0
  82. package/src/fill-extrusion-lighting-extension.ts +126 -9
  83. package/src/fill-outline-extension.ts +4 -4
  84. package/src/fill-pattern.ts +87 -9
  85. package/src/fill-style-extensions.ts +114 -44
  86. package/src/geojson-resource.ts +58 -0
  87. package/src/geojson-source.ts +106 -85
  88. package/src/geojson-task-handler.ts +11 -0
  89. package/src/geojson-task-worker.ts +8 -0
  90. package/src/geojson-task.ts +34 -0
  91. package/src/geojson-tiler.ts +270 -4
  92. package/src/geojson-worker.ts +36 -6
  93. package/src/globe-horizon-extension.ts +14 -4
  94. package/src/globe-layers.ts +1905 -406
  95. package/src/globe-line-angle-extension.ts +183 -23
  96. package/src/glyph-store.ts +28 -6
  97. package/src/heatmap-layer.ts +591 -0
  98. package/src/hillshade-layer.ts +309 -88
  99. package/src/icon-text-fit.ts +358 -0
  100. package/src/image-source-layer.ts +380 -0
  101. package/src/index.ts +58 -1
  102. package/src/line-blur-extension.ts +14 -12
  103. package/src/line-dash-extension.ts +303 -0
  104. package/src/line-gradient-extension.ts +191 -0
  105. package/src/line-metrics.ts +90 -0
  106. package/src/line-pattern-extension.ts +173 -0
  107. package/src/line-shape-extension.ts +272 -0
  108. package/src/map-style-loader.ts +5 -4
  109. package/src/map-style.ts +2 -1
  110. package/src/mvt-label-layer.ts +568 -144
  111. package/src/pmtiles-source.ts +276 -0
  112. package/src/projected-background-layer.ts +202 -0
  113. package/src/projected-bitmap-layer.ts +262 -0
  114. package/src/projected-tile-data.ts +132 -0
  115. package/src/projected-tile-selection.ts +605 -0
  116. package/src/projected-tileset.ts +183 -0
  117. package/src/projected-viewport.ts +254 -0
  118. package/src/raster-color-extension.ts +43 -18
  119. package/src/raster-fade.ts +319 -0
  120. package/src/raster-tile-fingerprint.ts +31 -0
  121. package/src/raster-tile-loader.ts +211 -0
  122. package/src/shader-injection-plugin.ts +25 -0
  123. package/src/source-features.ts +170 -0
  124. package/src/source-tiles.ts +102 -0
  125. package/src/sprite.ts +122 -15
  126. package/src/stretch-icon-layer.ts +87 -0
  127. package/src/style-accessor.ts +105 -17
  128. package/src/style-expression.ts +80 -3
  129. package/src/style-resolver.ts +200 -22
  130. package/src/terrain-query.ts +86 -0
  131. package/src/text-layout.ts +2 -3
  132. package/src/zoom-load-gate.ts +57 -0
  133. package/src/zoom-paint-extension.ts +245 -47
  134. package/dist/types/arabic-shaping.d.ts +0 -7
  135. package/dist/types/bidi.d.ts +0 -8
  136. package/dist/types/polylabel.d.ts +0 -17
  137. package/src/arabic-shaping.ts +0 -366
  138. package/src/bidi.ts +0 -199
  139. package/src/polylabel.ts +0 -312
@@ -2024,8 +2024,161 @@
2024
2024
  Polygon: 2,
2025
2025
  MultiPolygon: 3
2026
2026
  };
2027
- function createTileIndex(data, options) {
2028
- return new GeoJSONVT(data, options);
2027
+ function createTileIndex(data, options, clipToMercatorRange = false) {
2028
+ const clipped = clipToMercatorRange ? clipFeaturesToMercatorRange(data, options) : { data, outside: 0 };
2029
+ const indexOptions = clipped.data !== data && options.generateId ? { ...options, generateId: false } : options;
2030
+ return { index: new GeoJSONVT(clipped.data, indexOptions), outside: clipped.outside };
2031
+ }
2032
+ var MERCATOR_LATITUDE = Math.atan(Math.sinh(Math.PI)) * 180 / Math.PI;
2033
+ function getMercatorY(latitude) {
2034
+ const sin = Math.sin(Math.max(-89.9999, Math.min(89.9999, latitude)) * Math.PI / 180);
2035
+ return 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;
2036
+ }
2037
+ var EDGE_TOLERANCE = 1e-12;
2038
+ var isInsideY = (y) => y >= -EDGE_TOLERANCE && y <= 1 + EDGE_TOLERANCE;
2039
+ function isInside(position) {
2040
+ return Math.abs(position[1]) <= MERCATOR_LATITUDE;
2041
+ }
2042
+ function interpolate(a, b, t, edge) {
2043
+ return [a[0] + t * (b[0] - a[0]), edge === 0 ? MERCATOR_LATITUDE : -MERCATOR_LATITUDE];
2044
+ }
2045
+ function clipLine2(line) {
2046
+ const points = [];
2047
+ for (let i = 0; i < line.length; i++) {
2048
+ if (i > 0) {
2049
+ const a = line[i - 1];
2050
+ const ya = getMercatorY(a[1]);
2051
+ const dy = getMercatorY(line[i][1]) - ya;
2052
+ const crossings = [0, 1].map((edge) => ({ edge, t: (edge - ya) / dy })).filter(({ t }) => t > 0 && t < 1).sort((p, q) => p.t - q.t);
2053
+ for (const { edge, t } of crossings) points.push(interpolate(a, line[i], t, edge));
2054
+ }
2055
+ points.push(line[i]);
2056
+ }
2057
+ const ys = points.map((point) => getMercatorY(point[1]));
2058
+ const distances = [0];
2059
+ for (let i = 1; i < points.length; i++) {
2060
+ const dx = (points[i][0] - points[i - 1][0]) / 360;
2061
+ const dy = Math.min(1, Math.max(0, ys[i])) - Math.min(1, Math.max(0, ys[i - 1]));
2062
+ distances.push(distances[i - 1] + Math.hypot(dx, dy));
2063
+ }
2064
+ const length = distances[distances.length - 1] || 1;
2065
+ const parts = [];
2066
+ let first = -1;
2067
+ for (let i = 0; i < points.length; i++) {
2068
+ const middle = i < points.length - 1 ? (ys[i] + ys[i + 1]) / 2 : NaN;
2069
+ const inside = isInsideY(middle);
2070
+ if (inside && first < 0) {
2071
+ first = i;
2072
+ } else if (!inside && first >= 0) {
2073
+ parts.push({ line: points.slice(first, i + 1), start: distances[first] / length, end: distances[i] / length });
2074
+ first = -1;
2075
+ }
2076
+ }
2077
+ return parts;
2078
+ }
2079
+ function clipRing(ring) {
2080
+ let points = ring;
2081
+ for (const edge of [0, 1]) {
2082
+ const inside = (y) => edge === 0 ? y >= -EDGE_TOLERANCE : y <= 1 + EDGE_TOLERANCE;
2083
+ const clipped = [];
2084
+ for (let i = 0; i < points.length; i++) {
2085
+ const a = points[i];
2086
+ const b = points[(i + 1) % points.length];
2087
+ const ya = getMercatorY(a[1]);
2088
+ const yb = getMercatorY(b[1]);
2089
+ if (inside(ya)) clipped.push(a);
2090
+ if (inside(ya) !== inside(yb)) {
2091
+ clipped.push(interpolate(a, b, (edge - ya) / (yb - ya), edge));
2092
+ }
2093
+ }
2094
+ points = clipped;
2095
+ }
2096
+ const [first] = points;
2097
+ const last = points[points.length - 1];
2098
+ if (first && (first[0] !== last[0] || first[1] !== last[1])) {
2099
+ points.push(first);
2100
+ }
2101
+ return points.length >= 4 ? points : null;
2102
+ }
2103
+ function clipPolygon(rings) {
2104
+ const [outer, ...holes] = rings.map((ring) => ring.every(isInside) ? ring : clipRing(ring));
2105
+ return outer ? [outer, ...holes.filter((hole) => hole !== null)] : null;
2106
+ }
2107
+ function isGeometryInside(geometry) {
2108
+ if (geometry.type === "GeometryCollection") {
2109
+ return (geometry.geometries || []).every(isGeometryInside);
2110
+ }
2111
+ const visit = (value) => !Array.isArray(value) || (typeof value[0] === "number" ? isInside(value) : value.every(visit));
2112
+ return visit(geometry.coordinates);
2113
+ }
2114
+ var getLines = (parts) => parts.map((part) => part.line);
2115
+ var LINE_PART_START = "tangram_line_part_start";
2116
+ var LINE_PART_END = "tangram_line_part_end";
2117
+ var LINE_CLIP_START = "geojsonvt_clip_start";
2118
+ var LINE_CLIP_END = "geojsonvt_clip_end";
2119
+ function clipGeometry(geometry) {
2120
+ const { type, coordinates } = geometry;
2121
+ const multi = (multiType, parts, singleType) => parts.length === 0 ? null : parts.length === 1 ? { type: singleType, coordinates: parts[0] } : { type: multiType, coordinates: parts };
2122
+ switch (type) {
2123
+ case "Point":
2124
+ return isInside(coordinates) ? geometry : null;
2125
+ case "MultiPoint":
2126
+ return multi("MultiPoint", coordinates.filter(isInside), "Point");
2127
+ case "LineString":
2128
+ return multi("MultiLineString", getLines(clipLine2(coordinates)), "LineString");
2129
+ case "MultiLineString":
2130
+ return multi("MultiLineString", getLines(coordinates.flatMap(clipLine2)), "LineString");
2131
+ case "Polygon":
2132
+ return multi("MultiPolygon", [clipPolygon(coordinates)].filter(Boolean), "Polygon");
2133
+ case "MultiPolygon":
2134
+ return multi("MultiPolygon", coordinates.map(clipPolygon).filter(Boolean), "Polygon");
2135
+ case "GeometryCollection": {
2136
+ const geometries = (geometry.geometries || []).map((child) => isGeometryInside(child) ? child : clipGeometry(child)).filter((child) => child !== null);
2137
+ return geometries.length ? { type, geometries } : null;
2138
+ }
2139
+ default:
2140
+ return geometry;
2141
+ }
2142
+ }
2143
+ function clipFeaturesToMercatorRange(data, { generateId = false, lineMetrics = false } = {}) {
2144
+ let outside = 0;
2145
+ const clipFeature = (feature) => {
2146
+ const geometry = feature?.geometry;
2147
+ if (!geometry || isGeometryInside(geometry)) {
2148
+ return [feature];
2149
+ }
2150
+ outside++;
2151
+ const isLine = geometry.type === "LineString" || geometry.type === "MultiLineString";
2152
+ if (lineMetrics && isLine) {
2153
+ const lines = geometry.type === "LineString" ? [geometry.coordinates] : geometry.coordinates;
2154
+ return lines.flatMap(clipLine2).map(({ line, start, end }) => ({
2155
+ ...feature,
2156
+ geometry: { type: "LineString", coordinates: line },
2157
+ properties: { ...feature.properties, [LINE_PART_START]: start, [LINE_PART_END]: end }
2158
+ }));
2159
+ }
2160
+ const clipped = clipGeometry(geometry);
2161
+ return clipped ? [{ ...feature, geometry: clipped }] : [];
2162
+ };
2163
+ const withIds = (features, index) => generateId ? features.map((feature) => feature && { ...feature, id: index }) : features;
2164
+ const value = data;
2165
+ if (value?.type === "FeatureCollection" && Array.isArray(value.features)) {
2166
+ const features = value.features.map(clipFeature);
2167
+ return outside ? { data: { ...value, features: features.flatMap(withIds) }, outside } : { data, outside };
2168
+ }
2169
+ if (value?.type === "Feature") {
2170
+ const features = clipFeature(value);
2171
+ return outside ? { data: { type: "FeatureCollection", features: withIds(features, 0) }, outside } : { data, outside };
2172
+ }
2173
+ if (value && typeof value === "object" && "type" in value) {
2174
+ const geometry = value;
2175
+ if (isGeometryInside(geometry)) {
2176
+ return { data, outside };
2177
+ }
2178
+ const features = clipFeature({ type: "Feature", properties: {}, geometry });
2179
+ return { data: { type: "FeatureCollection", features: withIds(features, 0) }, outside };
2180
+ }
2181
+ return { data, outside };
2029
2182
  }
2030
2183
  function getSignedArea(ring) {
2031
2184
  let sum = 0;
@@ -2068,6 +2221,17 @@
2068
2221
  }
2069
2222
  return polygons.length === 1 ? { type: "Polygon", coordinates: polygons[0] } : { type: "MultiPolygon", coordinates: polygons };
2070
2223
  }
2224
+ function getProperties(tags) {
2225
+ if (!tags || !(LINE_PART_START in tags)) {
2226
+ return tags || {};
2227
+ }
2228
+ const { [LINE_PART_START]: start, [LINE_PART_END]: end, ...properties } = tags;
2229
+ if (LINE_CLIP_START in properties) {
2230
+ properties[LINE_CLIP_START] = start + properties[LINE_CLIP_START] * (end - start);
2231
+ properties[LINE_CLIP_END] = start + properties[LINE_CLIP_END] * (end - start);
2232
+ }
2233
+ return properties;
2234
+ }
2071
2235
  function cutTile(index, z, x, y) {
2072
2236
  const features = [];
2073
2237
  const positions = [];
@@ -2088,7 +2252,7 @@
2088
2252
  continue;
2089
2253
  }
2090
2254
  writeCoordinates(geometry.coordinates, GEOMETRY_DEPTHS[geometry.type]);
2091
- const encoded = { type: geometry.type, properties: feature.tags || {} };
2255
+ const encoded = { type: geometry.type, properties: getProperties(feature.tags) };
2092
2256
  if (feature.id !== void 0) {
2093
2257
  encoded.id = feature.id;
2094
2258
  }
@@ -2097,11 +2261,926 @@
2097
2261
  return { features, positions: Int32Array.from(positions), lengths: Uint32Array.from(lengths) };
2098
2262
  }
2099
2263
 
2264
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/node/worker_threads-browser.js
2265
+ var parentPort = globalThis.process?.getBuiltinModule?.("node:worker_threads")?.parentPort ?? null;
2266
+
2267
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-utils/get-transfer-list.js
2268
+ function getTransferList(object, recursive = true, transfers) {
2269
+ const transfersSet = transfers || /* @__PURE__ */ new Set();
2270
+ const seen = /* @__PURE__ */ new Set();
2271
+ function visit(value) {
2272
+ if (!value || typeof value !== "object" || seen.has(value))
2273
+ return;
2274
+ seen.add(value);
2275
+ if (isTransferable(value))
2276
+ transfersSet.add(value);
2277
+ else if (ArrayBuffer.isView(value)) {
2278
+ if (isTransferable(value.buffer))
2279
+ transfersSet.add(value.buffer);
2280
+ } else if (recursive && typeof MessageChannel !== "undefined" && value instanceof MessageChannel) {
2281
+ visit(value.port1);
2282
+ visit(value.port2);
2283
+ } else if (recursive && value instanceof Map) {
2284
+ for (const [key, item] of value) {
2285
+ visit(key);
2286
+ visit(item);
2287
+ }
2288
+ } else if (recursive && value instanceof Set) {
2289
+ for (const item of value)
2290
+ visit(item);
2291
+ } else if (recursive) {
2292
+ for (const key of Object.keys(value))
2293
+ visit(value[key]);
2294
+ }
2295
+ }
2296
+ visit(object);
2297
+ return transfers === void 0 ? Array.from(transfersSet) : [];
2298
+ }
2299
+ function isTransferable(object) {
2300
+ if (!object) {
2301
+ return false;
2302
+ }
2303
+ if (object instanceof ArrayBuffer) {
2304
+ return true;
2305
+ }
2306
+ if (typeof MessagePort !== "undefined" && object instanceof MessagePort) {
2307
+ return true;
2308
+ }
2309
+ if (typeof ImageBitmap !== "undefined" && object instanceof ImageBitmap) {
2310
+ return true;
2311
+ }
2312
+ if (typeof OffscreenCanvas !== "undefined" && object instanceof OffscreenCanvas) {
2313
+ return true;
2314
+ }
2315
+ return false;
2316
+ }
2317
+
2318
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-farm/worker-body.js
2319
+ async function getParentPort() {
2320
+ return parentPort;
2321
+ }
2322
+ var onMessageWrapperMap = /* @__PURE__ */ new Map();
2323
+ var WorkerBody = class {
2324
+ /** Check that we are actually in a worker thread */
2325
+ static async inWorkerThread() {
2326
+ const workerGlobalScope = globalThis.WorkerGlobalScope;
2327
+ return typeof workerGlobalScope === "function" && globalThis instanceof workerGlobalScope || Boolean(await getParentPort());
2328
+ }
2329
+ /*
2330
+ * (type: WorkerMessageType, payload: WorkerMessagePayload) => any
2331
+ */
2332
+ static set onmessage(onMessage) {
2333
+ async function handleMessage(message) {
2334
+ const parentPort2 = await getParentPort();
2335
+ const { type, payload } = parentPort2 ? message : message.data;
2336
+ onMessage(type, payload);
2337
+ }
2338
+ getParentPort().then((parentPort2) => {
2339
+ if (parentPort2) {
2340
+ parentPort2.on("message", (message) => {
2341
+ handleMessage(message);
2342
+ });
2343
+ parentPort2.on("exit", () => console.debug("Node worker closing"));
2344
+ } else {
2345
+ globalThis.onmessage = handleMessage;
2346
+ }
2347
+ });
2348
+ }
2349
+ static async addEventListener(onMessage) {
2350
+ let onMessageWrapper = onMessageWrapperMap.get(onMessage);
2351
+ if (!onMessageWrapper) {
2352
+ onMessageWrapper = (message) => {
2353
+ const messageData = getWorkerMessageData(message);
2354
+ if (!messageData) {
2355
+ return;
2356
+ }
2357
+ onMessage(messageData.type, messageData.payload);
2358
+ };
2359
+ onMessageWrapperMap.set(onMessage, onMessageWrapper);
2360
+ }
2361
+ const parentPort2 = await getParentPort();
2362
+ if (parentPort2) {
2363
+ parentPort2.on("message", onMessageWrapper);
2364
+ } else {
2365
+ globalThis.addEventListener("message", onMessageWrapper);
2366
+ }
2367
+ }
2368
+ static async removeEventListener(onMessage) {
2369
+ const onMessageWrapper = onMessageWrapperMap.get(onMessage);
2370
+ onMessageWrapperMap.delete(onMessage);
2371
+ if (!onMessageWrapper) {
2372
+ return;
2373
+ }
2374
+ const parentPort2 = await getParentPort();
2375
+ if (parentPort2) {
2376
+ parentPort2.off("message", onMessageWrapper);
2377
+ } else {
2378
+ globalThis.removeEventListener("message", onMessageWrapper);
2379
+ }
2380
+ }
2381
+ /**
2382
+ * Send a message from a worker to creating thread (main thread)
2383
+ * @param type
2384
+ * @param payload
2385
+ */
2386
+ static async postMessage(type, payload, copy = false) {
2387
+ const data = { source: "loaders.gl", type, payload };
2388
+ const transferList = copy ? [] : getTransferList(payload);
2389
+ const parentPort2 = await getParentPort();
2390
+ if (parentPort2) {
2391
+ parentPort2.postMessage(data, transferList);
2392
+ } else {
2393
+ globalThis.postMessage(data, transferList);
2394
+ }
2395
+ }
2396
+ };
2397
+ function getWorkerMessageData(message) {
2398
+ if (!message || typeof message !== "object") {
2399
+ return null;
2400
+ }
2401
+ const messageData = "data" in message && message.type === "message" ? message.data : message;
2402
+ return messageData && typeof messageData.source === "string" && messageData.source.startsWith("loaders.gl") ? messageData : null;
2403
+ }
2404
+
2405
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/async-queue/async-queue.js
2406
+ var AsyncQueue = class {
2407
+ constructor() {
2408
+ this._values = [];
2409
+ this._settlers = [];
2410
+ this._closed = false;
2411
+ }
2412
+ /** Return an async iterator for this queue */
2413
+ [Symbol.asyncIterator]() {
2414
+ return this;
2415
+ }
2416
+ /** Push a new value - the async iterator will yield a promise resolved to this value */
2417
+ push(value) {
2418
+ return this.enqueue(value);
2419
+ }
2420
+ /**
2421
+ * Push a new value - the async iterator will yield a promise resolved to this value
2422
+ * Add an error - the async iterator will yield a promise rejected with this value
2423
+ */
2424
+ enqueue(value) {
2425
+ if (this._closed) {
2426
+ throw new Error("Closed");
2427
+ }
2428
+ if (this._settlers.length > 0) {
2429
+ if (this._values.length > 0) {
2430
+ throw new Error("Illegal internal state");
2431
+ }
2432
+ const settler = this._settlers.shift();
2433
+ if (value instanceof Error) {
2434
+ settler.reject(value);
2435
+ } else {
2436
+ settler.resolve({ value });
2437
+ }
2438
+ } else {
2439
+ this._values.push(value);
2440
+ }
2441
+ }
2442
+ /** Indicate that we not waiting for more values - The async iterator will be done */
2443
+ close() {
2444
+ while (this._settlers.length > 0) {
2445
+ const settler = this._settlers.shift();
2446
+ settler.resolve({ done: true });
2447
+ }
2448
+ this._closed = true;
2449
+ }
2450
+ // ITERATOR IMPLEMENTATION
2451
+ /** @returns a Promise for an IteratorResult */
2452
+ next() {
2453
+ if (this._values.length > 0) {
2454
+ const value = this._values.shift();
2455
+ if (value instanceof Error) {
2456
+ return Promise.reject(value);
2457
+ }
2458
+ return Promise.resolve({ done: false, value });
2459
+ }
2460
+ if (this._closed) {
2461
+ if (this._settlers.length > 0) {
2462
+ throw new Error("Illegal internal state");
2463
+ }
2464
+ return Promise.resolve({ done: true, value: void 0 });
2465
+ }
2466
+ return new Promise((resolve, reject) => {
2467
+ this._settlers.push({ resolve, reject });
2468
+ });
2469
+ }
2470
+ };
2471
+
2472
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-api/shared-state.js
2473
+ var SharedWorkerState = class {
2474
+ constructor(buffer) {
2475
+ if (typeof SharedArrayBuffer === "undefined" || !(buffer instanceof SharedArrayBuffer) || buffer.byteLength !== 16)
2476
+ throw new Error("Expected a 16-byte shared worker control buffer");
2477
+ this.buffer = buffer;
2478
+ this.values = new Int32Array(buffer);
2479
+ }
2480
+ get snapshot() {
2481
+ return {
2482
+ cancelled: Atomics.load(this.values, 0) !== 0,
2483
+ completed: Atomics.load(this.values, 1),
2484
+ total: Atomics.load(this.values, 2),
2485
+ revision: Atomics.load(this.values, 3)
2486
+ };
2487
+ }
2488
+ cancel() {
2489
+ Atomics.store(this.values, 0, 1);
2490
+ Atomics.add(this.values, 3, 1);
2491
+ Atomics.notify(this.values, 0);
2492
+ }
2493
+ throwIfCancelled() {
2494
+ if (Atomics.load(this.values, 0) !== 0) {
2495
+ const error = new Error("Shared worker task was cancelled");
2496
+ error.name = "AbortError";
2497
+ throw error;
2498
+ }
2499
+ }
2500
+ /** Integer counters for application-defined work; messages still carry phase names and units. */
2501
+ setProgress(completed, total = -1) {
2502
+ if (!Number.isInteger(completed) || completed < 0 || completed > 2147483647 || !Number.isInteger(total) || total < -1 || total > 2147483647) {
2503
+ throw new RangeError("Shared progress requires nonnegative int32 counts (or total -1)");
2504
+ }
2505
+ Atomics.store(this.values, 1, completed);
2506
+ Atomics.store(this.values, 2, total);
2507
+ Atomics.add(this.values, 3, 1);
2508
+ }
2509
+ };
2510
+
2511
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-api/validate-output-ownership.js
2512
+ function validateOutputOwnership(ownership) {
2513
+ if (ownership !== void 0 && ownership !== "copy" && ownership !== "transfer") {
2514
+ throw new Error("Invalid worker output ownership");
2515
+ }
2516
+ }
2517
+
2518
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-api/create-worker.js
2519
+ var requestId = 0;
2520
+ var activeController = null;
2521
+ var activeInputBatches = null;
2522
+ var activeOutputAcknowledgements = null;
2523
+ async function createWorker(process, processInBatches, preload) {
2524
+ if (!await WorkerBody.inWorkerThread()) {
2525
+ return;
2526
+ }
2527
+ const context = {
2528
+ process: processOnMainThread
2529
+ };
2530
+ WorkerBody.onmessage = async (type, payload) => {
2531
+ if (type === "cancel") {
2532
+ activeController?.abort();
2533
+ activeInputBatches?.close();
2534
+ activeOutputAcknowledgements?.close();
2535
+ return;
2536
+ }
2537
+ const controller = type === "process" || type === "process-in-batches" ? new AbortController() : void 0;
2538
+ if (controller)
2539
+ activeController = controller;
2540
+ const startedAt = performance.now();
2541
+ const reporter = type === "process" || type === "process-in-batches" ? createProgressReporter() : void 0;
2542
+ let sharedState;
2543
+ const throwIfAborted = () => {
2544
+ controller?.signal.throwIfAborted();
2545
+ sharedState?.throwIfCancelled();
2546
+ };
2547
+ const jobContext = {
2548
+ ...context,
2549
+ signal: controller?.signal,
2550
+ sharedState,
2551
+ throwIfAborted,
2552
+ reportProgress: (progress) => {
2553
+ if (!controller?.signal.aborted && !sharedState?.snapshot.cancelled)
2554
+ reporter?.report(progress);
2555
+ }
2556
+ };
2557
+ try {
2558
+ if (controller && payload.options?.["sharedState"]) {
2559
+ sharedState = new SharedWorkerState(payload.options["sharedState"]);
2560
+ jobContext.sharedState = sharedState;
2561
+ }
2562
+ switch (type) {
2563
+ case "preload":
2564
+ await preload?.();
2565
+ WorkerBody.postMessage("done", {});
2566
+ break;
2567
+ case "process":
2568
+ throwIfAborted();
2569
+ validateOutputOwnership(payload.options?.["outputOwnership"]);
2570
+ if (!process) {
2571
+ throw new Error("Worker does not support atomic processing");
2572
+ }
2573
+ const result = await process(payload.input, payload.options || {}, jobContext, payload.context || {});
2574
+ throwIfAborted();
2575
+ reporter?.finish();
2576
+ await WorkerBody.postMessage("done", {
2577
+ result,
2578
+ executionMs: performance.now() - startedAt
2579
+ }, payload.options?.["outputOwnership"] === "copy");
2580
+ break;
2581
+ case "process-in-batches":
2582
+ throwIfAborted();
2583
+ validateOutputOwnership(payload.options?.["outputOwnership"]);
2584
+ if (!processInBatches) {
2585
+ throw new Error("Worker does not support batched processing");
2586
+ }
2587
+ const inputBatches = new AsyncQueue();
2588
+ const outputAcknowledgements = new AsyncQueue();
2589
+ activeInputBatches = inputBatches;
2590
+ activeOutputAcknowledgements = outputAcknowledgements;
2591
+ try {
2592
+ const resultIterator = processInBatches(createDemandDrivenIterator(inputBatches), payload.options || {}, jobContext, payload.context || {});
2593
+ for await (const batch of resultIterator) {
2594
+ throwIfAborted();
2595
+ await WorkerBody.postMessage("output-batch", { result: batch }, payload.options?.["outputOwnership"] === "copy");
2596
+ await outputAcknowledgements.next();
2597
+ }
2598
+ throwIfAborted();
2599
+ reporter?.finish();
2600
+ await WorkerBody.postMessage("done", { executionMs: performance.now() - startedAt });
2601
+ } finally {
2602
+ activeInputBatches = null;
2603
+ activeOutputAcknowledgements = null;
2604
+ }
2605
+ break;
2606
+ case "input-batch":
2607
+ if (!activeInputBatches) {
2608
+ throw new Error("Worker has no active batched processing session");
2609
+ }
2610
+ activeInputBatches.push(payload.input);
2611
+ break;
2612
+ case "input-done":
2613
+ if (!activeInputBatches) {
2614
+ throw new Error("Worker has no active batched processing session");
2615
+ }
2616
+ activeInputBatches.close();
2617
+ break;
2618
+ case "output-ack":
2619
+ if (!activeOutputAcknowledgements) {
2620
+ throw new Error("Worker has no active batched processing session");
2621
+ }
2622
+ activeOutputAcknowledgements.push(void 0);
2623
+ break;
2624
+ default:
2625
+ }
2626
+ } catch (error) {
2627
+ reporter?.finish(controller?.signal.aborted || sharedState?.snapshot.cancelled);
2628
+ const message = error instanceof Error ? error.message : "";
2629
+ await WorkerBody.postMessage("error", {
2630
+ error: message,
2631
+ errorName: error instanceof Error ? error.name : "Error"
2632
+ });
2633
+ } finally {
2634
+ if (controller && activeController === controller)
2635
+ activeController = null;
2636
+ }
2637
+ };
2638
+ await WorkerBody.postMessage("ready", {});
2639
+ }
2640
+ async function* createDemandDrivenIterator(inputBatches) {
2641
+ while (true) {
2642
+ await WorkerBody.postMessage("input-request", {});
2643
+ const nextBatch = await inputBatches.next();
2644
+ if (nextBatch.done) {
2645
+ return;
2646
+ }
2647
+ yield nextBatch.value;
2648
+ }
2649
+ }
2650
+ function processOnMainThread(arrayBuffer, options = {}, jobContext = {}) {
2651
+ const signal = activeController?.signal;
2652
+ signal?.throwIfAborted();
2653
+ return new Promise((resolve, reject) => {
2654
+ const id = requestId++;
2655
+ const cleanup = () => {
2656
+ signal?.removeEventListener("abort", abort);
2657
+ void WorkerBody.removeEventListener(onMessage);
2658
+ };
2659
+ const abort = () => {
2660
+ cleanup();
2661
+ reject(signal?.reason);
2662
+ };
2663
+ const onMessage = (type, payload) => {
2664
+ if (payload.id !== id)
2665
+ return;
2666
+ if (type === "done") {
2667
+ cleanup();
2668
+ resolve(payload.result);
2669
+ } else if (type === "error") {
2670
+ cleanup();
2671
+ reject(payload.error);
2672
+ }
2673
+ };
2674
+ void WorkerBody.addEventListener(onMessage).then(async () => {
2675
+ if (signal?.aborted) {
2676
+ abort();
2677
+ return;
2678
+ }
2679
+ signal?.addEventListener("abort", abort, { once: true });
2680
+ await WorkerBody.postMessage("process", {
2681
+ id,
2682
+ input: arrayBuffer,
2683
+ options,
2684
+ context: jobContext
2685
+ });
2686
+ }).catch((error) => {
2687
+ cleanup();
2688
+ reject(error);
2689
+ });
2690
+ });
2691
+ }
2692
+ function createProgressReporter() {
2693
+ let pending2;
2694
+ let finished = false;
2695
+ let scheduled = false;
2696
+ const flush = () => {
2697
+ scheduled = false;
2698
+ if (pending2) {
2699
+ WorkerBody.postMessage("progress", { progress: pending2 });
2700
+ pending2 = void 0;
2701
+ }
2702
+ };
2703
+ return {
2704
+ /** Records progress while retaining phase transitions. */
2705
+ report(progress) {
2706
+ if (finished)
2707
+ return;
2708
+ if (pending2 && pending2.phase !== progress.phase)
2709
+ flush();
2710
+ pending2 = { ...progress };
2711
+ if (!scheduled) {
2712
+ scheduled = true;
2713
+ setTimeout(flush, 0);
2714
+ }
2715
+ },
2716
+ /** Flushes final progress and suppresses reports from stale callbacks. */
2717
+ finish(discard = false) {
2718
+ if (discard)
2719
+ pending2 = void 0;
2720
+ flush();
2721
+ finished = true;
2722
+ }
2723
+ };
2724
+ }
2725
+
2726
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/index.js
2727
+ var import_meta = {};
2728
+ var path = typeof __filename === "string" ? __filename.replace(/\\/g, "/") : "";
2729
+ var moduleUrl = path ? `file://${path.startsWith("/") ? "" : "/"}${encodeURI(path).replace(/#/g, "%23").replace(/\?/g, "%3F")}` : import_meta.url;
2730
+
2731
+ // ../../node_modules/@math.gl/tasks/dist/tasks/task-preload.js
2732
+ var pending = /* @__PURE__ */ new WeakMap();
2733
+ var loaded = /* @__PURE__ */ new WeakSet();
2734
+ function preloadTaskCode(task, signal) {
2735
+ if (!task.preload)
2736
+ return Promise.resolve();
2737
+ let promise = pending.get(task);
2738
+ if (!promise) {
2739
+ promise = Promise.resolve().then(() => task.preload()).then(() => {
2740
+ loaded.add(task);
2741
+ });
2742
+ pending.set(task, promise);
2743
+ void promise.catch(() => pending.delete(task));
2744
+ }
2745
+ return withSignal(promise, signal);
2746
+ }
2747
+ function withSignal(operation, signal) {
2748
+ if (!signal)
2749
+ return operation;
2750
+ return new Promise((resolve, reject) => {
2751
+ const abort = () => {
2752
+ signal.removeEventListener("abort", abort);
2753
+ reject(signal.reason);
2754
+ };
2755
+ signal.addEventListener("abort", abort, { once: true });
2756
+ if (signal.aborted)
2757
+ abort();
2758
+ operation.then((value) => {
2759
+ signal.removeEventListener("abort", abort);
2760
+ resolve(value);
2761
+ }, (error) => {
2762
+ signal.removeEventListener("abort", abort);
2763
+ reject(error);
2764
+ });
2765
+ });
2766
+ }
2767
+
2768
+ // ../../node_modules/@math.gl/tasks/dist/tasks/task-channel.js
2769
+ var TaskRequestError = class extends Error {
2770
+ };
2771
+ var TaskChannel = class {
2772
+ constructor(options) {
2773
+ this.options = options;
2774
+ this.nextId = 1;
2775
+ this.pending = /* @__PURE__ */ new Map();
2776
+ this.incoming = /* @__PURE__ */ new Map();
2777
+ }
2778
+ /** Send a request without serializing other in-flight requests. */
2779
+ request(operation, value, signal, transfer = []) {
2780
+ if (this.failure)
2781
+ return Promise.reject(this.failure.reason);
2782
+ if (signal?.aborted)
2783
+ return Promise.reject(signal.reason);
2784
+ const id = this.nextId++;
2785
+ return new Promise((resolve, reject) => {
2786
+ const abort = () => {
2787
+ const pending2 = this.pending.get(id);
2788
+ if (!pending2)
2789
+ return;
2790
+ this.pending.delete(id);
2791
+ pending2.cleanup();
2792
+ reject(signal?.reason);
2793
+ this.send({ source: "math.gl/tasks", kind: "cancel", id });
2794
+ };
2795
+ this.pending.set(id, {
2796
+ resolve,
2797
+ reject,
2798
+ cleanup: () => signal?.removeEventListener("abort", abort)
2799
+ });
2800
+ signal?.addEventListener("abort", abort, { once: true });
2801
+ this.send({ source: "math.gl/tasks", kind: "request", id, operation, value }, transfer);
2802
+ });
2803
+ }
2804
+ /** Send a one-way notification. */
2805
+ emit(operation, value, transfer = []) {
2806
+ if (this.failure)
2807
+ throw this.failure.reason;
2808
+ this.send({ source: "math.gl/tasks", kind: "event", id: 0, operation, value }, transfer);
2809
+ }
2810
+ /** Dispatch a transport message; unrelated protocols are ignored. */
2811
+ receive(message) {
2812
+ if (this.failure || message?.source !== "math.gl/tasks")
2813
+ return;
2814
+ if (message.kind === "failure") {
2815
+ const reason = new Error(message.error?.message ?? "Task channel failed");
2816
+ this.close(reason);
2817
+ this.options.onFailure?.(reason);
2818
+ } else if (message.kind === "result" || message.kind === "error") {
2819
+ const pending2 = this.pending.get(message.id);
2820
+ if (!pending2)
2821
+ return;
2822
+ this.pending.delete(message.id);
2823
+ pending2.cleanup();
2824
+ if (message.kind === "result")
2825
+ pending2.resolve(message.value);
2826
+ else {
2827
+ const error = new TaskRequestError(message.error?.message ?? "Task request failed");
2828
+ error.name = message.error?.name ?? "Error";
2829
+ pending2.reject(error);
2830
+ }
2831
+ } else if (message.kind === "cancel") {
2832
+ this.incoming.get(message.id)?.abort(new DOMException("Task request cancelled", "AbortError"));
2833
+ } else if (message.kind === "event") {
2834
+ try {
2835
+ this.options.handleEvent?.(message.operation, message.value);
2836
+ } catch (error) {
2837
+ this.fail(error);
2838
+ }
2839
+ } else if (message.kind === "request") {
2840
+ if (this.incoming.has(message.id)) {
2841
+ this.fail(new Error("Duplicate task request identifier"));
2842
+ return;
2843
+ }
2844
+ const controller = new AbortController();
2845
+ this.incoming.set(message.id, controller);
2846
+ void Promise.resolve().then(() => {
2847
+ controller.signal.throwIfAborted();
2848
+ return this.options.handleRequest(message.operation, message.value, controller.signal);
2849
+ }).then((value) => {
2850
+ if (!controller.signal.aborted && !this.failure) {
2851
+ this.send({ source: "math.gl/tasks", kind: "result", id: message.id, value }, this.options.getResultTransferList?.(value, message.value));
2852
+ }
2853
+ }).catch((reason) => {
2854
+ if (!controller.signal.aborted && !this.failure) {
2855
+ this.send({
2856
+ source: "math.gl/tasks",
2857
+ kind: "error",
2858
+ id: message.id,
2859
+ error: {
2860
+ name: reason instanceof Error ? reason.name : "Error",
2861
+ message: reason instanceof Error ? reason.message : String(reason)
2862
+ }
2863
+ });
2864
+ }
2865
+ }).finally(() => this.incoming.delete(message.id));
2866
+ }
2867
+ }
2868
+ /** Reject all outstanding calls with a common cause and abort incoming callbacks. */
2869
+ close(reason = new Error("Task channel closed")) {
2870
+ if (this.failure)
2871
+ return;
2872
+ this.failure = { reason };
2873
+ for (const pending2 of this.pending.values()) {
2874
+ pending2.cleanup();
2875
+ pending2.reject(reason);
2876
+ }
2877
+ this.pending.clear();
2878
+ for (const controller of this.incoming.values())
2879
+ controller.abort(reason);
2880
+ this.incoming.clear();
2881
+ }
2882
+ send(message, transfer = []) {
2883
+ if (this.failure)
2884
+ return;
2885
+ try {
2886
+ this.options.send(message, transfer);
2887
+ } catch (error) {
2888
+ this.fail(error);
2889
+ }
2890
+ }
2891
+ /** Invalidate the channel and notify the peer when the transport still works. */
2892
+ fail(reason) {
2893
+ if (this.failure)
2894
+ return;
2895
+ this.close(reason);
2896
+ try {
2897
+ this.options.send({
2898
+ source: "math.gl/tasks",
2899
+ kind: "failure",
2900
+ id: 0,
2901
+ error: {
2902
+ name: reason instanceof Error ? reason.name : "Error",
2903
+ message: reason instanceof Error ? reason.message : String(reason)
2904
+ }
2905
+ }, []);
2906
+ } catch {
2907
+ }
2908
+ this.options.onFailure?.(reason);
2909
+ }
2910
+ };
2911
+
2912
+ // ../../node_modules/@math.gl/tasks/dist/tasks/task-runtime.js
2913
+ function assertPayload(value) {
2914
+ if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype) {
2915
+ throw new TypeError("Task payloads must be plain objects with named fields");
2916
+ }
2917
+ }
2918
+ function clonePayload(value, ownership = "copy") {
2919
+ assertPayload(value);
2920
+ if (!["copy", "transfer", "share"].includes(ownership))
2921
+ throw new TypeError("Invalid input ownership");
2922
+ const transfer = getTransferList(value);
2923
+ if (ownership === "share" && transfer.length)
2924
+ throw new TypeError("Share requires shared storage");
2925
+ return structuredClone(value, {
2926
+ transfer: ownership === "transfer" ? transfer : []
2927
+ });
2928
+ }
2929
+ function taskContext(state, context = {}) {
2930
+ const signal = context.signal ?? new AbortController().signal;
2931
+ return {
2932
+ state,
2933
+ signal,
2934
+ requestHost: async (operation, payload, controls) => {
2935
+ signal.throwIfAborted();
2936
+ if (!context.requestHost)
2937
+ throw new Error("No host request handler configured");
2938
+ return context.requestHost(operation, payload, controls);
2939
+ },
2940
+ emitHost: (operation, payload) => {
2941
+ signal.throwIfAborted();
2942
+ context.emitHost?.(operation, payload);
2943
+ },
2944
+ throwIfAborted: () => {
2945
+ signal.throwIfAborted();
2946
+ context.throwIfAborted?.();
2947
+ },
2948
+ reportProgress: (progress) => context.reportProgress?.({
2949
+ ...progress,
2950
+ phase: progress.phase ?? "process",
2951
+ unit: progress.unit ?? "items"
2952
+ })
2953
+ };
2954
+ }
2955
+ var TaskRuntime = class {
2956
+ constructor(task) {
2957
+ this.task = task;
2958
+ this.initialized = false;
2959
+ }
2960
+ async initialize(input, context = {}) {
2961
+ if (this.initialized)
2962
+ throw new Error("Task is already initialized");
2963
+ assertPayload(input);
2964
+ await preloadTaskCode(this.task, context.signal);
2965
+ context.signal?.throwIfAborted();
2966
+ this.state = await this.task.initialize?.(input, taskContext(void 0, context));
2967
+ this.initialized = true;
2968
+ return {};
2969
+ }
2970
+ async destroy() {
2971
+ if (this.initialized) {
2972
+ this.initialized = false;
2973
+ const state = this.state;
2974
+ this.state = void 0;
2975
+ if (this.task.initialize)
2976
+ await this.task.destroy?.(state);
2977
+ }
2978
+ return {};
2979
+ }
2980
+ async process(input, options, context = {}) {
2981
+ if (!this.initialized)
2982
+ throw new Error("Task is not initialized");
2983
+ if (!this.task.process)
2984
+ throw new Error("Task has no atomic processor");
2985
+ assertPayload(input);
2986
+ const result = await this.task.process(input, options, taskContext(this.state, context));
2987
+ assertPayload(result);
2988
+ return result;
2989
+ }
2990
+ async *stream(inputs, options, context = {}) {
2991
+ if (!this.initialized)
2992
+ throw new Error("Task is not initialized");
2993
+ if (!this.task.processInBatches)
2994
+ throw new Error("Task has no streaming processor");
2995
+ for await (const output of this.task.processInBatches(inputs, options, taskContext(this.state, context))) {
2996
+ assertPayload(output);
2997
+ yield output;
2998
+ }
2999
+ }
3000
+ };
3001
+ async function initializeTaskWorker(task) {
3002
+ if (!await WorkerBody.inWorkerThread())
3003
+ throw new Error("initializeTaskWorker must run inside a worker");
3004
+ if (installed)
3005
+ throw new Error("A task is already installed in this worker");
3006
+ installed = true;
3007
+ const runtime = new TaskRuntime(task);
3008
+ let channelStream;
3009
+ const channel = new TaskChannel({
3010
+ getResultTransferList: (value, request) => request.outputOwnership === "transfer" ? getTransferList(value) : [],
3011
+ send: (message, transfer) => {
3012
+ const snapshot = structuredClone(message, { transfer });
3013
+ void WorkerBody.postMessage("task-channel", snapshot).catch((reason) => channel.fail(reason));
3014
+ },
3015
+ handleRequest: async (operation, value, signal) => {
3016
+ const request = value;
3017
+ const context = {
3018
+ signal,
3019
+ reportProgress: (progress) => channel.emit("task:progress", { id: request.progressId, progress }),
3020
+ requestHost: (operation2, payload, controls = {}) => {
3021
+ const request2 = {
3022
+ operation: operation2,
3023
+ payload: clonePayload(payload, controls.inputOwnership),
3024
+ outputOwnership: controls.outputOwnership ?? "copy"
3025
+ };
3026
+ return channel.request("task:host-request", request2, signal, getTransferList(request2));
3027
+ },
3028
+ emitHost: (operation2, payload) => channel.emit("task:host-event", { operation: operation2, payload, id: request.progressId })
3029
+ };
3030
+ switch (operation) {
3031
+ case "initialize":
3032
+ return runtime.initialize(request.input, context);
3033
+ case "process":
3034
+ return runtime.process(request.input, request.options, context);
3035
+ case "stream-open": {
3036
+ if (channelStream)
3037
+ throw new Error("A task stream is already open");
3038
+ async function* inputs() {
3039
+ while (true) {
3040
+ const result = await channel.request("task:next-input", { outputOwnership: "transfer" }, signal);
3041
+ if (result.done)
3042
+ return;
3043
+ yield result.value;
3044
+ }
3045
+ }
3046
+ channelStream = runtime.stream(inputs(), request.options, context)[Symbol.asyncIterator]();
3047
+ return {};
3048
+ }
3049
+ case "stream-next":
3050
+ if (!channelStream)
3051
+ throw new Error("No active task stream");
3052
+ return channelStream.next();
3053
+ case "stream-close":
3054
+ try {
3055
+ await channelStream?.return?.();
3056
+ } finally {
3057
+ channelStream = void 0;
3058
+ }
3059
+ return {};
3060
+ case "destroy":
3061
+ return runtime.destroy();
3062
+ default:
3063
+ throw new Error("Unknown task channel operation");
3064
+ }
3065
+ }
3066
+ });
3067
+ await WorkerBody.addEventListener((type, payload) => {
3068
+ if (type === "task-channel")
3069
+ channel.receive(payload);
3070
+ });
3071
+ let streamOptions = {};
3072
+ return createWorker(async (request, _options, context) => {
3073
+ switch (request.operation) {
3074
+ case "initialize":
3075
+ return runtime.initialize(request.input, context);
3076
+ case "destroy":
3077
+ return runtime.destroy();
3078
+ case "stream-options":
3079
+ streamOptions = request.options;
3080
+ return {};
3081
+ case "process":
3082
+ return runtime.process(request.input, request.options, context);
3083
+ default:
3084
+ throw new Error("Unknown task operation");
3085
+ }
3086
+ }, async function* (inputs, _options, context) {
3087
+ async function* batches() {
3088
+ for await (const input of inputs) {
3089
+ assertPayload(input);
3090
+ yield input;
3091
+ }
3092
+ }
3093
+ try {
3094
+ yield* runtime.stream(batches(), streamOptions, context);
3095
+ } finally {
3096
+ streamOptions = {};
3097
+ }
3098
+ }, () => preloadTaskCode(task));
3099
+ }
3100
+ var installed = false;
3101
+
3102
+ // src/geojson-resource.ts
3103
+ function createGeoJsonResourceState() {
3104
+ return { pendingFeatures: /* @__PURE__ */ new Map(), indexes: /* @__PURE__ */ new Map() };
3105
+ }
3106
+ function runGeoJsonResource(state, message) {
3107
+ switch (message.type) {
3108
+ case "features": {
3109
+ const features = state.pendingFeatures.get(message.source);
3110
+ if (features) for (const feature of message.features) features.push(feature);
3111
+ else state.pendingFeatures.set(message.source, message.features);
3112
+ return null;
3113
+ }
3114
+ case "index": {
3115
+ const data = message.data ?? { type: "FeatureCollection", features: state.pendingFeatures.get(message.source) || [] };
3116
+ state.pendingFeatures.delete(message.source);
3117
+ try {
3118
+ const { index, outside } = createTileIndex(data, message.options, message.clipToMercatorRange);
3119
+ state.indexes.set(message.source, index);
3120
+ return outside;
3121
+ } catch (error) {
3122
+ state.indexes.set(message.source, error instanceof Error ? error : new Error(String(error)));
3123
+ return 0;
3124
+ }
3125
+ }
3126
+ case "tile": {
3127
+ const index = state.indexes.get(message.source);
3128
+ if (!index) throw new Error("GeoJSON source has no index");
3129
+ if (index instanceof Error) throw index;
3130
+ return cutTile(index, message.z, message.x, message.y);
3131
+ }
3132
+ case "remove":
3133
+ state.pendingFeatures.delete(message.source);
3134
+ state.indexes.delete(message.source);
3135
+ return null;
3136
+ }
3137
+ }
3138
+
3139
+ // src/geojson-task.ts
3140
+ var import_meta2 = {};
3141
+ var GeoJsonTask = {
3142
+ id: "tangram-geojson",
3143
+ worker: {
3144
+ create: () => new Worker(new URL("./geojson-task-worker.js", import_meta2.url), { type: "module" }),
3145
+ capabilities: { atomic: true, streaming: false }
3146
+ },
3147
+ initialize: (_input) => createGeoJsonResourceState(),
3148
+ process: (input, _options, { state }) => {
3149
+ try {
3150
+ const output = runGeoJsonResource(state, input);
3151
+ return typeof output === "number" ? { tile: null, outside: output } : { tile: output };
3152
+ } catch (error) {
3153
+ return { error: error instanceof Error ? error.message : String(error) };
3154
+ }
3155
+ }
3156
+ };
3157
+
3158
+ // src/geojson-task-handler.ts
3159
+ function installGeoJsonTaskHandler() {
3160
+ return initializeTaskWorker(GeoJsonTask);
3161
+ }
3162
+
2100
3163
  // src/geojson-worker.ts
2101
3164
  var pendingFeatures = /* @__PURE__ */ new Map();
2102
3165
  var indexes = /* @__PURE__ */ new Map();
2103
3166
  var scope = globalThis;
2104
- scope.onmessage = ({ data: message }) => {
3167
+ var taskInstalled = false;
3168
+ var taskReady;
3169
+ var pendingTaskMessages = [];
3170
+ scope.addEventListener("message", (event) => {
3171
+ const { data } = event;
3172
+ if (data && typeof data === "object" && "source" in data && data.source === "loaders.gl") {
3173
+ if (!taskInstalled) {
3174
+ event.stopImmediatePropagation();
3175
+ pendingTaskMessages.push(data);
3176
+ taskReady ??= installGeoJsonTaskHandler().then(() => {
3177
+ taskInstalled = true;
3178
+ for (const data2 of pendingTaskMessages.splice(0)) globalThis.dispatchEvent(new MessageEvent("message", { data: data2 }));
3179
+ });
3180
+ }
3181
+ return;
3182
+ }
3183
+ const message = data;
2105
3184
  switch (message.type) {
2106
3185
  case "features": {
2107
3186
  const features = pendingFeatures.get(message.source);
@@ -2115,13 +3194,16 @@
2115
3194
  break;
2116
3195
  }
2117
3196
  case "index": {
2118
- const data = message.data ?? {
3197
+ const data2 = message.data ?? {
2119
3198
  type: "FeatureCollection",
2120
3199
  features: pendingFeatures.get(message.source) || []
2121
3200
  };
2122
3201
  pendingFeatures.delete(message.source);
2123
3202
  try {
2124
- indexes.set(message.source, createTileIndex(data, message.options));
3203
+ indexes.set(
3204
+ message.source,
3205
+ createTileIndex(data2, message.options, message.clipToMercatorRange).index
3206
+ );
2125
3207
  } catch (error) {
2126
3208
  indexes.set(message.source, error instanceof Error ? error : new Error(String(error)));
2127
3209
  }
@@ -2155,6 +3237,6 @@
2155
3237
  break;
2156
3238
  default:
2157
3239
  }
2158
- };
3240
+ });
2159
3241
  })();
2160
3242
  //# sourceMappingURL=geojson-worker.js.map