geo-engine-node 1.1.2 → 2.0.0

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.
package/dist/index.js CHANGED
@@ -1,95 +1,920 @@
1
- // index.js
2
- var DEFAULTS = {
3
- managementUrl: "https://api.geoengine.dev",
4
- ingestUrl: "https://ingest.geoengine.dev",
5
- timeout: 1e4
1
+ // src/errors.ts
2
+ var GeoEngineError = class extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "GeoEngineError";
6
+ Object.setPrototypeOf(this, new.target.prototype);
7
+ }
6
8
  };
7
- var GeoEngine = class {
9
+ var ClientClosedError = class extends GeoEngineError {
10
+ constructor(message = "geoengine: client is closed") {
11
+ super(message);
12
+ this.name = "ClientClosedError";
13
+ }
14
+ };
15
+ var ValidationError = class extends GeoEngineError {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = "ValidationError";
19
+ }
20
+ };
21
+ var DeviceIDRequiredError = class extends ValidationError {
22
+ constructor(message = "geoengine: device_id is required") {
23
+ super(message);
24
+ this.name = "DeviceIDRequiredError";
25
+ }
26
+ };
27
+ var GeofenceIDRequiredError = class extends ValidationError {
28
+ constructor(message = "geoengine: geofence_id is required") {
29
+ super(message);
30
+ this.name = "GeofenceIDRequiredError";
31
+ }
32
+ };
33
+ var InvalidLatitudeError = class extends ValidationError {
34
+ constructor(message = "geoengine: latitude must be between -90 and 90 degrees") {
35
+ super(message);
36
+ this.name = "InvalidLatitudeError";
37
+ }
38
+ };
39
+ var InvalidLongitudeError = class extends ValidationError {
40
+ constructor(message = "geoengine: longitude must be between -180 and 180 degrees") {
41
+ super(message);
42
+ this.name = "InvalidLongitudeError";
43
+ }
44
+ };
45
+ var InvalidCoordinatesError = class extends ValidationError {
46
+ constructor(message = "geoengine: at least 3 coordinate pairs are required for a polygon") {
47
+ super(message);
48
+ this.name = "InvalidCoordinatesError";
49
+ }
50
+ };
51
+ var APIError = class extends GeoEngineError {
52
+ statusCode;
53
+ constructor(statusCode, message) {
54
+ super(`geoengine: API error (status ${statusCode}): ${message}`);
55
+ this.name = "APIError";
56
+ this.statusCode = statusCode;
57
+ }
58
+ };
59
+ var SpatialAPIError = class extends APIError {
60
+ code;
61
+ statusText;
62
+ details;
63
+ constructor(statusCode, code, message, statusText, details = []) {
64
+ const formattedMessage = code ? `geoengine: spatial API error (status ${statusCode}, code ${code}): ${message}` : `geoengine: spatial API error (status ${statusCode}): ${message}`;
65
+ super(statusCode, formattedMessage);
66
+ this.name = "SpatialAPIError";
67
+ this.code = code;
68
+ this.statusText = statusText;
69
+ this.details = details;
70
+ }
71
+ /**
72
+ * Returns true if the error indicates the geofence or resource was not found.
73
+ */
74
+ isNotFound() {
75
+ return this.statusCode === 204 || this.statusCode === 404 || this.code === "NOT_FOUND";
76
+ }
77
+ /**
78
+ * Returns true if the error indicates quota limit was hit.
79
+ */
80
+ isQuotaExceeded() {
81
+ return this.statusCode === 402 || this.code === "QUOTA_EXCEEDED";
82
+ }
83
+ /**
84
+ * Returns true if authentication failed.
85
+ */
86
+ isUnauthorized() {
87
+ return this.statusCode === 401 || this.code === "UNAUTHORIZED" || this.code === "MISSING_API_KEY" || this.code === "MISSING_ORGANIZATION";
88
+ }
89
+ /**
90
+ * Returns true if access to the requested resource is forbidden.
91
+ */
92
+ isForbidden() {
93
+ return this.statusCode === 403 || this.code === "FORBIDDEN";
94
+ }
95
+ };
96
+ var GeofenceNotFoundError = class extends SpatialAPIError {
97
+ constructor(message = "geofence not found", statusCode = 204, details = []) {
98
+ super(statusCode, "NOT_FOUND", message, "Not Found", details);
99
+ this.name = "GeofenceNotFoundError";
100
+ }
101
+ };
102
+ var QuotaExceededError = class extends SpatialAPIError {
103
+ constructor(message = "request quota exceeded", statusCode = 402, details = []) {
104
+ super(statusCode, "QUOTA_EXCEEDED", message, "Payment Required", details);
105
+ this.name = "QuotaExceededError";
106
+ }
107
+ };
108
+ var AuthenticationError = class extends SpatialAPIError {
109
+ constructor(message = "unauthorized API request", statusCode = 401, details = []) {
110
+ super(statusCode, "UNAUTHORIZED", message, "Unauthorized", details);
111
+ this.name = "AuthenticationError";
112
+ }
113
+ };
114
+ var ForbiddenError = class extends SpatialAPIError {
115
+ constructor(message = "access forbidden", statusCode = 403, details = []) {
116
+ super(statusCode, "FORBIDDEN", message, "Forbidden", details);
117
+ this.name = "ForbiddenError";
118
+ }
119
+ };
120
+ var TimeoutError = class extends GeoEngineError {
121
+ constructor(timeoutMs) {
122
+ super(`geoengine: request exceeded the timeout limit of ${timeoutMs}ms`);
123
+ this.name = "TimeoutError";
124
+ }
125
+ };
126
+
127
+ // src/crypto.ts
128
+ import { createHmac } from "crypto";
129
+ function generateHMACSignature(key, timestamp) {
130
+ if (!key) {
131
+ return "";
132
+ }
133
+ return createHmac("sha256", key).update(timestamp.toString()).digest("hex");
134
+ }
135
+
136
+ // src/http.ts
137
+ var USER_AGENT = "GeoEngineNodeSDK/2.0.0";
138
+ function parseHttpError(statusCode, bodyText, isSpatial = false) {
139
+ let parsedErrorContainer = null;
140
+ try {
141
+ parsedErrorContainer = JSON.parse(bodyText);
142
+ } catch {
143
+ }
144
+ const container = parsedErrorContainer?.error;
145
+ let code = container?.status ?? "";
146
+ let message = container?.message ?? parsedErrorContainer?.message ?? bodyText.trim();
147
+ const details = container?.details ?? [];
148
+ if (container?.details && container.details.length > 0) {
149
+ for (const detail of container.details) {
150
+ if (detail.reason) {
151
+ code = detail.reason;
152
+ break;
153
+ }
154
+ }
155
+ }
156
+ if (!code) {
157
+ switch (statusCode) {
158
+ case 204:
159
+ case 404:
160
+ code = "NOT_FOUND";
161
+ break;
162
+ case 402:
163
+ code = "QUOTA_EXCEEDED";
164
+ break;
165
+ case 401:
166
+ code = "UNAUTHORIZED";
167
+ break;
168
+ case 403:
169
+ code = "FORBIDDEN";
170
+ break;
171
+ default:
172
+ code = "";
173
+ }
174
+ }
175
+ if (!message) {
176
+ message = `HTTP ${statusCode}`;
177
+ }
178
+ if (statusCode === 204 || statusCode === 404 || code === "NOT_FOUND") {
179
+ return new GeofenceNotFoundError(message, statusCode, details);
180
+ }
181
+ if (statusCode === 402 || code === "QUOTA_EXCEEDED") {
182
+ return new QuotaExceededError(message, statusCode, details);
183
+ }
184
+ if (statusCode === 401 || code === "UNAUTHORIZED" || code === "MISSING_API_KEY" || code === "MISSING_ORGANIZATION") {
185
+ return new AuthenticationError(message, statusCode, details);
186
+ }
187
+ if (statusCode === 403 || code === "FORBIDDEN") {
188
+ return new ForbiddenError(message, statusCode, details);
189
+ }
190
+ if (isSpatial) {
191
+ return new SpatialAPIError(statusCode, code, message, void 0, details);
192
+ }
193
+ return new APIError(statusCode, message);
194
+ }
195
+ var HttpClient = class {
196
+ config;
197
+ constructor(options = {}) {
198
+ const defaultManagement = "https://management.geoengine.dev";
199
+ const defaultIngest = "https://ingest.geoengine.dev";
200
+ const defaultApiService = "https://api.geoengine.dev";
201
+ this.config = {
202
+ apiKey: options.apiKey ?? "",
203
+ jwtToken: options.jwtToken,
204
+ environment: options.environment ?? "live",
205
+ managementUrl: options.baseUrl ?? options.managementUrl ?? defaultManagement,
206
+ ingestUrl: options.baseUrl ?? options.ingestUrl ?? defaultIngest,
207
+ apiServiceUrl: options.baseUrl ?? options.apiServiceUrl ?? defaultApiService,
208
+ timeout: options.timeout ?? 1e4,
209
+ maxRetries: options.maxRetries ?? 2,
210
+ batchSize: options.batchSize ?? 100,
211
+ flushInterval: options.flushInterval ?? 500,
212
+ bufferSize: options.bufferSize ?? 5e3,
213
+ fetch: options.fetch ?? globalThis.fetch
214
+ };
215
+ }
216
+ get options() {
217
+ return this.config;
218
+ }
8
219
  /**
9
- * Inicializa el cliente de Geo-Engine.
10
- * @param {string} apiKey - Tu API Key.
11
- * @param {Object} [options] - Configuración opcional.
12
- */
13
- constructor(apiKey, options = {}) {
14
- if (!apiKey) {
15
- throw new Error("GeoEngine: API Key es requerida.");
16
- }
17
- this.apiKey = apiKey;
18
- this.config = { ...DEFAULTS, ...options };
19
- this.userAgent = "GeoEngineNode/1.1.2";
20
- }
21
- /**
22
- * Helper privado para hacer peticiones con timeout
23
- */
24
- async _request(url, method, body) {
25
- const controller = new AbortController();
26
- const id = setTimeout(() => controller.abort(), this.config.timeout);
27
- try {
28
- const response = await fetch(url, {
29
- method,
30
- headers: {
31
- "Content-Type": "application/json",
32
- "X-API-Key": this.apiKey,
33
- "User-Agent": this.userAgent
34
- },
35
- body: JSON.stringify(body),
36
- signal: controller.signal
37
- });
38
- clearTimeout(id);
39
- if (!response.ok) {
40
- const errorText = await response.text();
41
- throw new Error(`GeoEngine API Error (${response.status}): ${errorText}`);
220
+ * Executes an HTTP request with timeout, authentication headers and exponential backoff retry.
221
+ */
222
+ async request(opts) {
223
+ const method = opts.method ?? "POST";
224
+ const timeoutMs = opts.timeout ?? this.config.timeout;
225
+ const maxRetries = this.config.maxRetries;
226
+ let attempt = 0;
227
+ while (true) {
228
+ attempt++;
229
+ const controller = new globalThis.AbortController();
230
+ const timeoutId = globalThis.setTimeout(() => controller.abort(), timeoutMs);
231
+ const now = Date.now();
232
+ const headers = {
233
+ "Content-Type": "application/json",
234
+ "X-API-Key": this.config.apiKey,
235
+ "X-Geo-Environment": this.config.environment,
236
+ "X-Request-Time": now.toString(),
237
+ "X-Signature": generateHMACSignature(this.config.apiKey, now),
238
+ "User-Agent": USER_AGENT
239
+ };
240
+ if (this.config.jwtToken) {
241
+ headers["Authorization"] = `Bearer ${this.config.jwtToken}`;
42
242
  }
43
- if (response.status === 204) return null;
44
- return await response.json();
45
- } catch (error) {
46
- clearTimeout(id);
47
- if (error.name === "AbortError") {
48
- throw new Error(`GeoEngine: La petici\xF3n excedi\xF3 el tiempo l\xEDmite de ${this.config.timeout}ms`);
243
+ try {
244
+ const response = await this.config.fetch(opts.endpoint, {
245
+ method,
246
+ headers,
247
+ body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0,
248
+ signal: controller.signal
249
+ });
250
+ globalThis.clearTimeout(timeoutId);
251
+ if (response.status === 204) {
252
+ if (opts.isSpatial) {
253
+ throw new GeofenceNotFoundError("geofence not found", 204);
254
+ }
255
+ return null;
256
+ }
257
+ if ((response.status === 429 || response.status >= 500) && attempt <= maxRetries) {
258
+ const delay = Math.min(100 * Math.pow(2, attempt) + Math.random() * 50, 2e3);
259
+ await new Promise(
260
+ (resolve) => globalThis.setTimeout(() => resolve(), delay)
261
+ );
262
+ continue;
263
+ }
264
+ const responseText = await response.text();
265
+ if (!response.ok) {
266
+ throw parseHttpError(response.status, responseText, opts.isSpatial);
267
+ }
268
+ if (!responseText || responseText.trim() === "") {
269
+ return null;
270
+ }
271
+ const json = JSON.parse(responseText);
272
+ if (opts.isSpatial && typeof json === "object" && json !== null && "success" in json) {
273
+ if (!json.success) {
274
+ throw parseHttpError(response.status, responseText, true);
275
+ }
276
+ return json.data;
277
+ }
278
+ return json;
279
+ } catch (err) {
280
+ globalThis.clearTimeout(timeoutId);
281
+ if (err instanceof Error && err.name === "AbortError") {
282
+ throw new TimeoutError(timeoutMs);
283
+ }
284
+ if (err instanceof APIError) {
285
+ throw err;
286
+ }
287
+ if (attempt <= maxRetries) {
288
+ const delay = Math.min(100 * Math.pow(2, attempt) + Math.random() * 50, 2e3);
289
+ await new Promise(
290
+ (resolve) => globalThis.setTimeout(() => resolve(), delay)
291
+ );
292
+ continue;
293
+ }
294
+ throw err;
295
+ }
296
+ }
297
+ }
298
+ };
299
+
300
+ // src/ingester.ts
301
+ import { clearInterval, setInterval } from "timers";
302
+ var AsyncIngester = class {
303
+ client;
304
+ bufferSize;
305
+ batchSize;
306
+ intervalMs;
307
+ queue = [];
308
+ inFlightPromises = /* @__PURE__ */ new Set();
309
+ timer = null;
310
+ isClosed = false;
311
+ constructor(client, bufferSize = 5e3, batchSize = 100, flushIntervalMs = 500) {
312
+ this.client = client;
313
+ this.bufferSize = bufferSize;
314
+ this.batchSize = batchSize;
315
+ this.intervalMs = flushIntervalMs;
316
+ this.timer = setInterval(() => {
317
+ void this.flush();
318
+ }, this.intervalMs);
319
+ if (this.timer && typeof this.timer.unref === "function") {
320
+ this.timer.unref();
321
+ }
322
+ }
323
+ /**
324
+ * Non-blockingly appends a location ping to the ingestion buffer queue.
325
+ *
326
+ * @param ping Location ping object
327
+ * @returns true if successfully queued, false if queue is full or ingester is stopped
328
+ */
329
+ enqueue(ping) {
330
+ if (!ping || this.isClosed) {
331
+ return false;
332
+ }
333
+ if (this.queue.length >= this.bufferSize) {
334
+ return false;
335
+ }
336
+ this.queue.push(ping);
337
+ if (this.queue.length >= this.batchSize) {
338
+ void this.flush();
339
+ }
340
+ return true;
341
+ }
342
+ /**
343
+ * Flushes current queued batch of location telemetry items.
344
+ */
345
+ async flush() {
346
+ if (this.queue.length === 0) {
347
+ return;
348
+ }
349
+ const batch = this.queue.splice(0, this.batchSize);
350
+ if (batch.length === 0) {
351
+ return;
352
+ }
353
+ const flushPromise = Promise.all(
354
+ batch.map(
355
+ (item) => this.client.sendLocation(item.deviceId, item.latitude, item.longitude).catch(() => {
356
+ })
357
+ )
358
+ ).finally(() => {
359
+ this.inFlightPromises.delete(flushPromise);
360
+ });
361
+ this.inFlightPromises.add(flushPromise);
362
+ await flushPromise;
363
+ }
364
+ /**
365
+ * Drains all remaining pending items, halts worker timer, and releases resources.
366
+ * Safe to call multiple times.
367
+ */
368
+ async stop() {
369
+ if (this.isClosed) {
370
+ return;
371
+ }
372
+ this.isClosed = true;
373
+ if (this.timer) {
374
+ clearInterval(this.timer);
375
+ this.timer = null;
376
+ }
377
+ while (this.queue.length > 0) {
378
+ await this.flush();
379
+ }
380
+ if (this.inFlightPromises.size > 0) {
381
+ await Promise.all(Array.from(this.inFlightPromises));
382
+ }
383
+ }
384
+ };
385
+
386
+ // src/models.ts
387
+ var SpatialValidationResult = class {
388
+ inside;
389
+ geofenceId;
390
+ geofenceName;
391
+ latitude;
392
+ longitude;
393
+ constructor(data) {
394
+ this.inside = Boolean(data.inside);
395
+ this.geofenceId = data.geofence_id ?? data.geofenceId ?? "";
396
+ this.geofenceName = data.geofence_name ?? data.geofenceName;
397
+ this.latitude = data.latitude;
398
+ this.longitude = data.longitude;
399
+ }
400
+ /**
401
+ * Returns true if the coordinate is inside the geofence.
402
+ */
403
+ isInside() {
404
+ return this.inside;
405
+ }
406
+ /**
407
+ * Returns true if the coordinate is outside the geofence.
408
+ */
409
+ isOutside() {
410
+ return !this.inside;
411
+ }
412
+ /**
413
+ * Returns latitude and longitude as a [latitude, longitude] tuple.
414
+ */
415
+ coordinates() {
416
+ return [this.latitude, this.longitude];
417
+ }
418
+ /**
419
+ * Formats the result into a clean, human-readable log string matching Go's String().
420
+ */
421
+ toString() {
422
+ const status = this.inside ? "INSIDE" : "OUTSIDE";
423
+ const name = this.geofenceName || "unnamed";
424
+ return `[${status}] geofence=${this.geofenceId} (${name}) at (${this.latitude.toFixed(6)}, ${this.longitude.toFixed(6)})`;
425
+ }
426
+ };
427
+ var SpatialGeneralResult = class {
428
+ inside;
429
+ totalMatches;
430
+ matchedGeofences;
431
+ latitude;
432
+ longitude;
433
+ constructor(data) {
434
+ this.inside = Boolean(data.inside);
435
+ this.totalMatches = data.total_matches ?? data.totalMatches ?? (data.matched_geofences?.length ?? data.matchedGeofences?.length ?? 0);
436
+ this.matchedGeofences = data.matched_geofences ?? data.matchedGeofences ?? [];
437
+ this.latitude = data.latitude;
438
+ this.longitude = data.longitude;
439
+ }
440
+ /**
441
+ * Returns true if the coordinate falls inside at least one geofence.
442
+ */
443
+ isInside() {
444
+ return this.inside;
445
+ }
446
+ /**
447
+ * Returns true if one or more geofences matched the point.
448
+ */
449
+ hasMatches() {
450
+ return this.totalMatches > 0;
451
+ }
452
+ /**
453
+ * Returns the first matched geofence, or null if no matches found.
454
+ */
455
+ firstMatch() {
456
+ return this.matchedGeofences[0] ?? null;
457
+ }
458
+ /**
459
+ * Returns all matched geofence IDs as a string array.
460
+ */
461
+ geofenceIds() {
462
+ return this.matchedGeofences.map((m) => m.id);
463
+ }
464
+ /**
465
+ * Returns all matched geofence names as a string array.
466
+ */
467
+ geofenceNames() {
468
+ return this.matchedGeofences.map((m) => m.name);
469
+ }
470
+ /**
471
+ * Checks whether a specific geofence ID or name is among the matches.
472
+ */
473
+ containsGeofence(idOrName) {
474
+ return this.findMatch(idOrName) !== null;
475
+ }
476
+ /**
477
+ * Searches for a matched geofence by ID or name and returns it if found, or null.
478
+ */
479
+ findMatch(idOrName) {
480
+ for (const match of this.matchedGeofences) {
481
+ if (match.id === idOrName || match.name === idOrName) {
482
+ return match;
49
483
  }
50
- throw error;
51
484
  }
485
+ return null;
486
+ }
487
+ /**
488
+ * Returns latitude and longitude as a [latitude, longitude] tuple.
489
+ */
490
+ coordinates() {
491
+ return [this.latitude, this.longitude];
492
+ }
493
+ /**
494
+ * Formats the result into a clean, human-readable log string matching Go's String().
495
+ */
496
+ toString() {
497
+ const status = this.inside ? "INSIDE" : "OUTSIDE";
498
+ const names = this.geofenceNames().join(", ");
499
+ return `[${status}] matches=${this.totalMatches} (${names}) at (${this.latitude.toFixed(6)}, ${this.longitude.toFixed(6)})`;
500
+ }
501
+ };
502
+
503
+ // src/validation.ts
504
+ function validateCoordinates(lat, lng) {
505
+ if (typeof lat !== "number" || Number.isNaN(lat) || lat < -90 || lat > 90) {
506
+ throw new InvalidLatitudeError();
507
+ }
508
+ if (typeof lng !== "number" || Number.isNaN(lng) || lng < -180 || lng > 180) {
509
+ throw new InvalidLongitudeError();
510
+ }
511
+ }
512
+ function validateDeviceId(deviceId) {
513
+ if (!deviceId || typeof deviceId !== "string" || deviceId.trim() === "") {
514
+ throw new DeviceIDRequiredError();
515
+ }
516
+ return deviceId.trim();
517
+ }
518
+ function validateGeofenceId(geofenceId) {
519
+ if (!geofenceId || typeof geofenceId !== "string" || geofenceId.trim() === "") {
520
+ throw new GeofenceIDRequiredError();
521
+ }
522
+ return geofenceId.trim();
523
+ }
524
+ function validateAndNormalizePolygon(coordinates) {
525
+ if (!Array.isArray(coordinates) || coordinates.length < 3) {
526
+ throw new InvalidCoordinatesError();
527
+ }
528
+ const polygon = [];
529
+ for (const p of coordinates) {
530
+ if (!Array.isArray(p) || p.length !== 2) {
531
+ throw new ValidationError(
532
+ `geoengine: invalid coordinate format: ${JSON.stringify(p)} (expected [lat, lng])`
533
+ );
534
+ }
535
+ const lat = p[0];
536
+ const lng = p[1];
537
+ validateCoordinates(lat, lng);
538
+ polygon.push([lng, lat]);
539
+ }
540
+ const first = polygon[0];
541
+ const last = polygon[polygon.length - 1];
542
+ if (first[0] !== last[0] || first[1] !== last[1]) {
543
+ polygon.push([first[0], first[1]]);
544
+ }
545
+ return polygon;
546
+ }
547
+
548
+ // src/spatial.ts
549
+ var SpatialService = class {
550
+ constructor(http) {
551
+ this.http = http;
552
+ }
553
+ http;
554
+ /**
555
+ * Convenience method to check if coordinates fall within a specific geofence.
556
+ *
557
+ * @param geofenceId Unique identifier of the geofence
558
+ * @param lat Decimal latitude [-90, 90]
559
+ * @param lng Decimal longitude [-180, 180]
560
+ * @returns SpatialValidationResult
561
+ */
562
+ async validatePoint(geofenceId, lat, lng) {
563
+ const validId = validateGeofenceId(geofenceId);
564
+ validateCoordinates(lat, lng);
565
+ return this.validateLocation({
566
+ geofenceId: validId,
567
+ latitude: lat,
568
+ longitude: lng
569
+ });
570
+ }
571
+ /**
572
+ * Checks if coordinates fall inside the specified geofence using the api-service.
573
+ *
574
+ * @param req SpatialValidationRequest containing geofenceId, latitude, and longitude
575
+ * @returns SpatialValidationResult
576
+ */
577
+ async validateLocation(req) {
578
+ const validId = validateGeofenceId(req.geofenceId);
579
+ validateCoordinates(req.latitude, req.longitude);
580
+ const endpoint = `${this.http.options.apiServiceUrl.replace(/\/+$/, "")}/api/spatial/validate`;
581
+ const payload = {
582
+ geofence_id: validId,
583
+ latitude: req.latitude,
584
+ longitude: req.longitude
585
+ };
586
+ const rawData = await this.http.request({
587
+ endpoint,
588
+ method: "POST",
589
+ body: payload,
590
+ isSpatial: true
591
+ });
592
+ return new SpatialValidationResult(rawData);
593
+ }
594
+ /**
595
+ * Checks whether coordinates intersect any geofence belonging to the organization.
596
+ *
597
+ * @param lat Decimal latitude [-90, 90]
598
+ * @param lng Decimal longitude [-180, 180]
599
+ * @returns SpatialGeneralResult
600
+ */
601
+ async validateGeneral(lat, lng) {
602
+ validateCoordinates(lat, lng);
603
+ return this.validateGeneralLocation({
604
+ latitude: lat,
605
+ longitude: lng
606
+ });
607
+ }
608
+ /**
609
+ * Checks whether coordinates intersect any geofence using the api-service.
610
+ *
611
+ * @param req SpatialGeneralRequest containing latitude and longitude
612
+ * @returns SpatialGeneralResult
613
+ */
614
+ async validateGeneralLocation(req) {
615
+ validateCoordinates(req.latitude, req.longitude);
616
+ const endpoint = `${this.http.options.apiServiceUrl.replace(/\/+$/, "")}/api/spatial/validate-general`;
617
+ const payload = {
618
+ latitude: req.latitude,
619
+ longitude: req.longitude
620
+ };
621
+ const rawData = await this.http.request({
622
+ endpoint,
623
+ method: "POST",
624
+ body: payload,
625
+ isSpatial: true
626
+ });
627
+ return new SpatialGeneralResult(rawData);
628
+ }
629
+ /**
630
+ * Initializes a fluent query builder for spatial coordinate validation.
631
+ *
632
+ * @param lat Decimal latitude
633
+ * @param lng Decimal longitude
634
+ * @returns SpatialCheckBuilder
635
+ */
636
+ check(lat, lng) {
637
+ return new SpatialCheckBuilder(this, lat, lng);
638
+ }
639
+ };
640
+ var SpatialCheckBuilder = class {
641
+ constructor(service, lat, lng) {
642
+ this.service = service;
643
+ this.lat = lat;
644
+ this.lng = lng;
645
+ }
646
+ service;
647
+ lat;
648
+ lng;
649
+ /**
650
+ * Configures validation targeting a specific geofence ID.
651
+ */
652
+ inGeofence(geofenceId) {
653
+ return new SingleGeofenceCheck(this.service, geofenceId, this.lat, this.lng);
654
+ }
655
+ /**
656
+ * Configures validation against all organization geofences.
657
+ */
658
+ inAllGeofences() {
659
+ return new GeneralGeofenceCheck(this.service, this.lat, this.lng);
660
+ }
661
+ };
662
+ var SingleGeofenceCheck = class {
663
+ constructor(service, geofenceId, lat, lng) {
664
+ this.service = service;
665
+ this.geofenceId = geofenceId;
666
+ this.lat = lat;
667
+ this.lng = lng;
668
+ }
669
+ service;
670
+ geofenceId;
671
+ lat;
672
+ lng;
673
+ /**
674
+ * Performs the single geofence spatial query.
675
+ */
676
+ async execute() {
677
+ return this.service.validatePoint(this.geofenceId, this.lat, this.lng);
678
+ }
679
+ /**
680
+ * Alias for execute().
681
+ */
682
+ async executeSingle() {
683
+ return this.execute();
684
+ }
685
+ /**
686
+ * Alias for execute().
687
+ */
688
+ async validate() {
689
+ return this.execute();
690
+ }
691
+ };
692
+ var GeneralGeofenceCheck = class {
693
+ constructor(service, lat, lng) {
694
+ this.service = service;
695
+ this.lat = lat;
696
+ this.lng = lng;
697
+ }
698
+ service;
699
+ lat;
700
+ lng;
701
+ /**
702
+ * Performs the general spatial query against all organization geofences.
703
+ */
704
+ async execute() {
705
+ return this.service.validateGeneral(this.lat, this.lng);
706
+ }
707
+ /**
708
+ * Alias for execute().
709
+ */
710
+ async executeGeneral() {
711
+ return this.execute();
712
+ }
713
+ /**
714
+ * Alias for execute().
715
+ */
716
+ async validate() {
717
+ return this.execute();
718
+ }
719
+ };
720
+
721
+ // src/client.ts
722
+ var GeoEngine = class {
723
+ http;
724
+ isClosed = false;
725
+ /**
726
+ * Spatial provides point-in-polygon querying and geofence validation capabilities.
727
+ */
728
+ spatial;
729
+ /**
730
+ * Alias for spatial (to maintain exact casing compatibility with Go client.Spatial).
731
+ */
732
+ Spatial;
733
+ /**
734
+ * Initializes a new GeoEngine client instance.
735
+ *
736
+ * @param apiKey Your GeoEngine API Key (required)
737
+ * @param options Optional configuration parameters
738
+ */
739
+ constructor(apiKeyOrOptions, maybeOptions = {}) {
740
+ let resolvedOptions;
741
+ if (typeof apiKeyOrOptions === "string") {
742
+ resolvedOptions = { ...maybeOptions, apiKey: apiKeyOrOptions };
743
+ } else if (typeof apiKeyOrOptions === "object" && apiKeyOrOptions !== null) {
744
+ resolvedOptions = { ...apiKeyOrOptions };
745
+ } else {
746
+ resolvedOptions = {};
747
+ }
748
+ if (!resolvedOptions.apiKey || resolvedOptions.apiKey.trim() === "") {
749
+ throw new ValidationError("GeoEngine: API Key es requerida.");
750
+ }
751
+ this.http = new HttpClient(resolvedOptions);
752
+ this.spatial = new SpatialService(this.http);
753
+ this.Spatial = this.spatial;
52
754
  }
53
755
  /**
54
- * Envía una ubicación al motor de ingestión.
756
+ * Current configuration options.
757
+ */
758
+ get options() {
759
+ return this.http.options;
760
+ }
761
+ /**
762
+ * Sends device coordinates over HTTP REST.
763
+ * Equivalent to Go's Client.SendLocation.
764
+ *
765
+ * @param deviceId Unique vehicle/device identifier
766
+ * @param lat Decimal latitude
767
+ * @param lng Decimal longitude
55
768
  */
56
769
  async sendLocation(deviceId, lat, lng) {
57
- if (!deviceId || lat === void 0 || lng === void 0) {
58
- throw new Error("GeoEngine: deviceId, lat y lng son obligatorios.");
770
+ if (this.isClosed) {
771
+ throw new ClientClosedError();
59
772
  }
773
+ const validId = validateDeviceId(deviceId);
60
774
  const payload = {
61
- device_id: deviceId,
62
- latitude: parseFloat(lat),
63
- longitude: parseFloat(lng),
775
+ device_id: validId,
776
+ latitude: lat,
777
+ longitude: lng,
64
778
  timestamp: Math.floor(Date.now() / 1e3)
65
779
  };
66
- return this._request(`${this.config.ingestUrl}/ingest`, "POST", payload);
780
+ const endpoint = `${this.http.options.ingestUrl.replace(/\/+$/, "")}/ingest`;
781
+ await this.http.request({
782
+ endpoint,
783
+ method: "POST",
784
+ body: payload
785
+ });
67
786
  }
68
787
  /**
69
- * Crea una nueva geocerca.
788
+ * Creates a spatial geofence polygon in PostGIS via the management REST API.
789
+ * Automatically validates and closes the polygon ring.
790
+ * Equivalent to Go's Client.CreateGeofence.
791
+ *
792
+ * @param name Geofence name
793
+ * @param coordinates Array of [latitude, longitude] pairs (at least 3 coordinates)
794
+ * @param webhookUrl Optional webhook URL triggered upon enter/exit
70
795
  */
71
796
  async createGeofence(name, coordinates, webhookUrl) {
72
- if (!name || !coordinates || coordinates.length < 3) {
73
- throw new Error("GeoEngine: Se requiere un nombre y al menos 3 coordenadas.");
797
+ if (this.isClosed) {
798
+ throw new ClientClosedError();
74
799
  }
75
- const polygon = coordinates.map((p) => [p[1], p[0]]);
76
- const first = polygon[0];
77
- const last = polygon[polygon.length - 1];
78
- if (first[0] !== last[0] || first[1] !== last[1]) {
79
- polygon.push(first);
800
+ if (!name || typeof name !== "string" || name.trim() === "") {
801
+ throw new ValidationError("geoengine: name is required");
80
802
  }
803
+ const polygon = validateAndNormalizePolygon(coordinates);
81
804
  const payload = {
82
- name,
805
+ name: name.trim(),
83
806
  webhook_url: webhookUrl,
84
807
  geojson: {
85
808
  type: "Polygon",
86
809
  coordinates: [polygon]
87
810
  }
88
811
  };
89
- return this._request(`${this.config.managementUrl}/geofences`, "POST", payload);
812
+ const endpoint = `${this.http.options.managementUrl.replace(/\/+$/, "")}/geofences`;
813
+ return this.http.request({
814
+ endpoint,
815
+ method: "POST",
816
+ body: payload
817
+ });
818
+ }
819
+ // --- Spatial Validation Direct Shortcuts ---
820
+ /**
821
+ * Validates if coordinates fall within a geofence by ID via the Spatial service.
822
+ * Shortcut matching Go's Client.ValidateSpatialPoint.
823
+ */
824
+ async validateSpatialPoint(geofenceId, lat, lng) {
825
+ if (this.isClosed) {
826
+ throw new ClientClosedError();
827
+ }
828
+ return this.spatial.validatePoint(geofenceId, lat, lng);
829
+ }
830
+ /**
831
+ * Validates if coordinates fall within a geofence via the Spatial service.
832
+ * Shortcut matching Go's Client.ValidateSpatialLocation.
833
+ */
834
+ async validateSpatialLocation(req) {
835
+ if (this.isClosed) {
836
+ throw new ClientClosedError();
837
+ }
838
+ return this.spatial.validateLocation(req);
839
+ }
840
+ /**
841
+ * Validates coordinates against all active geofences via the Spatial service.
842
+ * Shortcut matching Go's Client.ValidateSpatialGeneral.
843
+ */
844
+ async validateSpatialGeneral(lat, lng) {
845
+ if (this.isClosed) {
846
+ throw new ClientClosedError();
847
+ }
848
+ return this.spatial.validateGeneral(lat, lng);
849
+ }
850
+ /**
851
+ * Validates coordinates against all active geofences via the Spatial service.
852
+ * Shortcut matching Go's Client.ValidateSpatialGeneralLocation.
853
+ */
854
+ async validateSpatialGeneralLocation(req) {
855
+ if (this.isClosed) {
856
+ throw new ClientClosedError();
857
+ }
858
+ return this.spatial.validateGeneralLocation(req);
859
+ }
860
+ /**
861
+ * Instantiates a new AsyncIngester connected to this client.
862
+ * Matches Go NewAsyncIngester.
863
+ *
864
+ * @param bufferSize Queue buffer capacity (default: options.bufferSize ?? 5000)
865
+ * @param batchSize Batch size before flushing (default: options.batchSize ?? 100)
866
+ * @param flushIntervalMs Flush interval in ms (default: options.flushInterval ?? 500)
867
+ */
868
+ createAsyncIngester(bufferSize, batchSize, flushIntervalMs) {
869
+ return new AsyncIngester(
870
+ this,
871
+ bufferSize ?? this.http.options.bufferSize,
872
+ batchSize ?? this.http.options.batchSize,
873
+ flushIntervalMs ?? this.http.options.flushInterval
874
+ );
875
+ }
876
+ /**
877
+ * Closes the client, marking it inactive. Idempotent.
878
+ * Subsequent requests will throw ClientClosedError.
879
+ * Equivalent to Go's Client.Close.
880
+ */
881
+ close() {
882
+ this.isClosed = true;
90
883
  }
91
884
  };
885
+
886
+ // src/index.ts
92
887
  var index_default = GeoEngine;
93
888
  export {
94
- index_default as default
889
+ APIError,
890
+ AsyncIngester,
891
+ AuthenticationError,
892
+ GeoEngine as Client,
893
+ ClientClosedError,
894
+ DeviceIDRequiredError,
895
+ ForbiddenError,
896
+ GeneralGeofenceCheck,
897
+ GeoEngine,
898
+ GeoEngineError,
899
+ GeofenceIDRequiredError,
900
+ GeofenceNotFoundError,
901
+ InvalidCoordinatesError,
902
+ InvalidLatitudeError,
903
+ InvalidLongitudeError,
904
+ QuotaExceededError,
905
+ SingleGeofenceCheck,
906
+ SpatialAPIError,
907
+ SpatialCheckBuilder,
908
+ SpatialGeneralResult,
909
+ SpatialService,
910
+ SpatialValidationResult,
911
+ TimeoutError,
912
+ ValidationError,
913
+ index_default as default,
914
+ generateHMACSignature,
915
+ validateAndNormalizePolygon,
916
+ validateCoordinates,
917
+ validateDeviceId,
918
+ validateGeofenceId
95
919
  };
920
+ //# sourceMappingURL=index.js.map