@classic-homes/maps-core 0.1.1

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.
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,390 @@
1
+ 'use strict';
2
+
3
+ // src/workers/SpatialWorkerClient.ts
4
+ var SpatialWorkerClient = class _SpatialWorkerClient {
5
+ constructor(options = {}) {
6
+ this.worker = null;
7
+ this.pendingRequests = /* @__PURE__ */ new Map();
8
+ this.requestCounter = 0;
9
+ this.initialized = false;
10
+ this.ready = false;
11
+ this.readyResolve = null;
12
+ this.options = {
13
+ requestTimeout: options.requestTimeout ?? 3e4,
14
+ useRTree: options.useRTree ?? true,
15
+ gridTargetCells: options.gridTargetCells ?? 1024,
16
+ rtreeMaxEntries: options.rtreeMaxEntries ?? 9,
17
+ workerFactory: options.workerFactory,
18
+ workerUrl: options.workerUrl
19
+ };
20
+ this.readyPromise = new Promise((resolve) => {
21
+ this.readyResolve = resolve;
22
+ });
23
+ this.createWorker();
24
+ }
25
+ /**
26
+ * Check if Web Workers are supported
27
+ */
28
+ static isSupported() {
29
+ return typeof Worker !== "undefined";
30
+ }
31
+ /**
32
+ * Create the worker instance
33
+ */
34
+ createWorker() {
35
+ if (!_SpatialWorkerClient.isSupported()) {
36
+ console.warn("[maps-core] Web Workers not supported. SpatialWorkerClient will not function.");
37
+ return;
38
+ }
39
+ if (!this.options.workerFactory && !this.options.workerUrl) {
40
+ console.warn(
41
+ "[maps-core] SpatialWorkerClient: No workerFactory or workerUrl provided. Worker will not be created until setWorker() is called."
42
+ );
43
+ return;
44
+ }
45
+ try {
46
+ if (this.options.workerFactory) {
47
+ this.worker = this.options.workerFactory();
48
+ } else if (this.options.workerUrl) {
49
+ this.worker = new Worker(this.options.workerUrl, { type: "module" });
50
+ }
51
+ if (this.worker) {
52
+ this.worker.onmessage = this.handleMessage.bind(this);
53
+ this.worker.onerror = this.handleError.bind(this);
54
+ }
55
+ } catch (error) {
56
+ console.error("[maps-core] Failed to create spatial worker:", error);
57
+ }
58
+ }
59
+ /**
60
+ * Set the worker instance manually
61
+ *
62
+ * Use this when you need to create the worker yourself,
63
+ * or when using a bundler-specific worker import.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * import SpatialWorker from './spatial.worker?worker';
68
+ * const client = new SpatialWorkerClient();
69
+ * client.setWorker(new SpatialWorker());
70
+ * ```
71
+ */
72
+ setWorker(worker) {
73
+ if (this.worker) {
74
+ this.worker.terminate();
75
+ }
76
+ this.worker = worker;
77
+ this.worker.onmessage = this.handleMessage.bind(this);
78
+ this.worker.onerror = this.handleError.bind(this);
79
+ this.ready = false;
80
+ this.readyPromise = new Promise((resolve) => {
81
+ this.readyResolve = resolve;
82
+ });
83
+ }
84
+ /**
85
+ * Handle messages from the worker
86
+ */
87
+ handleMessage(event) {
88
+ const message = event.data;
89
+ if (message.type === "ready") {
90
+ this.ready = true;
91
+ this.readyResolve?.();
92
+ return;
93
+ }
94
+ const response = message;
95
+ const pending = this.pendingRequests.get(response.requestId);
96
+ if (pending) {
97
+ clearTimeout(pending.timeout);
98
+ this.pendingRequests.delete(response.requestId);
99
+ if (response.success) {
100
+ pending.resolve(response);
101
+ } else {
102
+ pending.reject(new Error(response.error || "Unknown worker error"));
103
+ }
104
+ }
105
+ }
106
+ /**
107
+ * Handle worker errors
108
+ */
109
+ handleError(error) {
110
+ console.error("[maps-core] Spatial worker error:", error);
111
+ for (const [requestId, pending] of this.pendingRequests) {
112
+ clearTimeout(pending.timeout);
113
+ pending.reject(new Error(`Worker error: ${error.message}`));
114
+ this.pendingRequests.delete(requestId);
115
+ }
116
+ }
117
+ /**
118
+ * Generate a unique request ID
119
+ */
120
+ generateRequestId() {
121
+ return `req_${++this.requestCounter}_${Date.now()}`;
122
+ }
123
+ /**
124
+ * Send a request to the worker and wait for response
125
+ */
126
+ async sendRequest(request) {
127
+ if (!this.worker) {
128
+ throw new Error("Worker not available");
129
+ }
130
+ await this.readyPromise;
131
+ return new Promise((resolve, reject) => {
132
+ const timeout = setTimeout(() => {
133
+ this.pendingRequests.delete(request.requestId);
134
+ reject(new Error(`Request timeout: ${request.type}`));
135
+ }, this.options.requestTimeout);
136
+ this.pendingRequests.set(request.requestId, {
137
+ resolve,
138
+ reject,
139
+ timeout
140
+ });
141
+ this.worker.postMessage(request);
142
+ });
143
+ }
144
+ /**
145
+ * Initialize the worker with GeoJSON data
146
+ *
147
+ * @param data The GeoJSON FeatureCollection to index
148
+ * @returns Initialization result with build statistics
149
+ */
150
+ async initialize(data) {
151
+ const startTime = performance.now();
152
+ const request = {
153
+ type: "initialize",
154
+ requestId: this.generateRequestId(),
155
+ data,
156
+ options: {
157
+ useRTree: this.options.useRTree,
158
+ gridTargetCells: this.options.gridTargetCells,
159
+ rtreeMaxEntries: this.options.rtreeMaxEntries
160
+ }
161
+ };
162
+ try {
163
+ const response = await this.sendRequest(request);
164
+ this.initialized = response.success;
165
+ return {
166
+ success: response.success,
167
+ featureCount: response.stats?.featureCount ?? 0,
168
+ indexType: response.stats?.indexType ?? "rtree",
169
+ buildTimeMs: response.stats?.buildTimeMs ?? performance.now() - startTime,
170
+ error: response.error
171
+ };
172
+ } catch (error) {
173
+ return {
174
+ success: false,
175
+ featureCount: 0,
176
+ indexType: "rtree",
177
+ buildTimeMs: performance.now() - startTime,
178
+ error: error instanceof Error ? error.message : "Unknown error"
179
+ };
180
+ }
181
+ }
182
+ /**
183
+ * Query features within the given bounds
184
+ *
185
+ * @param bounds Viewport bounds [[swLng, swLat], [neLng, neLat]]
186
+ * @param options Query options
187
+ * @returns Query result with features and statistics
188
+ */
189
+ async query(bounds, options = {}) {
190
+ if (!this.initialized) {
191
+ return {
192
+ success: false,
193
+ data: { type: "FeatureCollection", features: [] },
194
+ stats: {
195
+ totalFeatures: 0,
196
+ visibleFeatures: 0,
197
+ culledPercent: 0,
198
+ cellsChecked: 0,
199
+ totalCells: 0
200
+ },
201
+ queryTimeMs: 0,
202
+ error: "Worker not initialized"
203
+ };
204
+ }
205
+ const startTime = performance.now();
206
+ const request = {
207
+ type: "query",
208
+ requestId: this.generateRequestId(),
209
+ bounds,
210
+ options
211
+ };
212
+ try {
213
+ const response = await this.sendRequest(request);
214
+ const queryTimeMs = performance.now() - startTime;
215
+ const rawStats = response.stats;
216
+ const stats = rawStats ? {
217
+ totalFeatures: rawStats.totalFeatures,
218
+ visibleFeatures: rawStats.visibleFeatures,
219
+ culledPercent: rawStats.culledPercent,
220
+ cellsChecked: "cellsChecked" in rawStats ? rawStats.cellsChecked : 0,
221
+ totalCells: "totalCells" in rawStats ? rawStats.totalCells : 0
222
+ } : {
223
+ totalFeatures: 0,
224
+ visibleFeatures: 0,
225
+ culledPercent: 0,
226
+ cellsChecked: 0,
227
+ totalCells: 0
228
+ };
229
+ return {
230
+ success: response.success,
231
+ data: response.data ?? { type: "FeatureCollection", features: [] },
232
+ stats,
233
+ queryTimeMs,
234
+ error: response.error
235
+ };
236
+ } catch (error) {
237
+ return {
238
+ success: false,
239
+ data: { type: "FeatureCollection", features: [] },
240
+ stats: {
241
+ totalFeatures: 0,
242
+ visibleFeatures: 0,
243
+ culledPercent: 0,
244
+ cellsChecked: 0,
245
+ totalCells: 0
246
+ },
247
+ queryTimeMs: performance.now() - startTime,
248
+ error: error instanceof Error ? error.message : "Unknown error"
249
+ };
250
+ }
251
+ }
252
+ /**
253
+ * Query with predictive pan loading
254
+ *
255
+ * Tracks viewport movement and expands buffer in the predicted
256
+ * direction of panning to eliminate pop-in.
257
+ *
258
+ * @param bounds Current viewport bounds
259
+ * @param options Predictive query options
260
+ * @returns Query result with velocity info
261
+ */
262
+ async queryPredictive(bounds, options = {}) {
263
+ if (!this.initialized) {
264
+ return {
265
+ success: false,
266
+ data: { type: "FeatureCollection", features: [] },
267
+ stats: {
268
+ totalFeatures: 0,
269
+ visibleFeatures: 0,
270
+ culledPercent: 0,
271
+ cellsChecked: 0,
272
+ totalCells: 0
273
+ },
274
+ queryTimeMs: 0,
275
+ velocity: { lngPerSec: 0, latPerSec: 0, magnitude: 0 },
276
+ updated: false,
277
+ error: "Worker not initialized"
278
+ };
279
+ }
280
+ const startTime = performance.now();
281
+ const request = {
282
+ type: "predictive-query",
283
+ requestId: this.generateRequestId(),
284
+ bounds,
285
+ timestamp: performance.now(),
286
+ options
287
+ };
288
+ try {
289
+ const response = await this.sendRequest(request);
290
+ const queryTimeMs = performance.now() - startTime;
291
+ return {
292
+ success: response.success,
293
+ data: response.data ?? { type: "FeatureCollection", features: [] },
294
+ stats: response.stats ?? {
295
+ totalFeatures: 0,
296
+ visibleFeatures: 0,
297
+ culledPercent: 0,
298
+ cellsChecked: 0,
299
+ totalCells: 0
300
+ },
301
+ queryTimeMs,
302
+ velocity: response.velocity ?? { lngPerSec: 0, latPerSec: 0, magnitude: 0 },
303
+ updated: response.updated,
304
+ error: response.error
305
+ };
306
+ } catch (error) {
307
+ return {
308
+ success: false,
309
+ data: { type: "FeatureCollection", features: [] },
310
+ stats: {
311
+ totalFeatures: 0,
312
+ visibleFeatures: 0,
313
+ culledPercent: 0,
314
+ cellsChecked: 0,
315
+ totalCells: 0
316
+ },
317
+ queryTimeMs: performance.now() - startTime,
318
+ velocity: { lngPerSec: 0, latPerSec: 0, magnitude: 0 },
319
+ updated: false,
320
+ error: error instanceof Error ? error.message : "Unknown error"
321
+ };
322
+ }
323
+ }
324
+ /**
325
+ * Reset predictive pan state
326
+ *
327
+ * Call this when the user stops panning or when you want
328
+ * to clear the velocity tracking.
329
+ */
330
+ async resetPredictive() {
331
+ if (!this.worker) return;
332
+ const request = {
333
+ type: "reset-predictive",
334
+ requestId: this.generateRequestId()
335
+ };
336
+ await this.sendRequest(request);
337
+ }
338
+ /**
339
+ * Get current index statistics
340
+ */
341
+ async getStats() {
342
+ if (!this.initialized || !this.worker) {
343
+ return null;
344
+ }
345
+ const request = {
346
+ type: "get-stats",
347
+ requestId: this.generateRequestId()
348
+ };
349
+ try {
350
+ const response = await this.sendRequest(request);
351
+ return response.stats ?? null;
352
+ } catch {
353
+ return null;
354
+ }
355
+ }
356
+ /**
357
+ * Check if the client is initialized
358
+ */
359
+ isInitialized() {
360
+ return this.initialized;
361
+ }
362
+ /**
363
+ * Check if the worker is ready
364
+ */
365
+ isReady() {
366
+ return this.ready;
367
+ }
368
+ /**
369
+ * Terminate the worker and clean up resources
370
+ */
371
+ terminate() {
372
+ for (const [requestId, pending] of this.pendingRequests) {
373
+ clearTimeout(pending.timeout);
374
+ pending.reject(new Error("Worker terminated"));
375
+ this.pendingRequests.delete(requestId);
376
+ }
377
+ if (this.worker) {
378
+ this.worker.terminate();
379
+ this.worker = null;
380
+ }
381
+ this.initialized = false;
382
+ this.ready = false;
383
+ }
384
+ };
385
+ function createSpatialWorkerClient(options) {
386
+ return new SpatialWorkerClient(options);
387
+ }
388
+
389
+ exports.SpatialWorkerClient = SpatialWorkerClient;
390
+ exports.createSpatialWorkerClient = createSpatialWorkerClient;