geo-engine-node 1.1.3 → 2.1.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/Readme.md CHANGED
@@ -1,132 +1,391 @@
1
- # 📦 Geo-Engine Node.js SDK
1
+ # 📦 Geo-Engine Node.js & TypeScript SDK
2
2
 
3
- ![NPM Version](https://img.shields.io/npm/v/geo-engine-node?style=flat-square&color=blue)
4
- ![License](https://img.shields.io/npm/l/geo-engine-node?style=flat-square)
5
- ![Types](https://img.shields.io/npm/types/geo-engine-node?style=flat-square)
6
- ![Size](https://img.shields.io/bundlephobia/minzip/geo-engine-node?style=flat-square)
3
+ [![NPM Version](https://img.shields.io/npm/v/geo-engine-node?style=flat-square&color=blue)](https://www.npmjs.com/package/geo-engine-node)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Strict-blue.svg)](https://www.typescriptlang.org/)
6
+ [![Tests](https://img.shields.io/badge/Tests-Vitest-green.svg)](https://vitest.dev/)
7
7
 
8
- Cliente oficial de alto rendimiento para interactuar con la plataforma **Geo-Engine**.
9
- Procesa ubicaciones en tiempo real, detecta cruces de geocercas y dispara webhooks en milisegundos.
8
+ > *Read this in Spanish: [README.es.md](./README.es.md)*
9
+
10
+ Official idiomatic **Node.js & TypeScript** client for the **Geo-Engine** platform.
11
+ Designed for **high performance**, strict type-safety, and 1:1 parity with the official Go SDK (`v2.1.0`). Seamlessly integrates into backend microservices, Serverless functions, and modern edge environments.
10
12
 
11
13
  ---
12
14
 
13
- ## ✨ Características
15
+ ## ✨ Features
14
16
 
15
- - 🚀 **Rendimiento:** Diseñado para manejar alta ingestión de datos.
16
- - 🛡️ **Type-Safe:** Incluye definiciones TypeScript (`.d.ts`) nativas.
17
- - 📦 **Híbrido:** Funciona con `require` (CommonJS) y `import` (ES Modules).
18
- - ⚡ **Ligero:** Cero dependencias pesadas.
17
+ - 📍 **Real-time Ingestion:** Sub-10ms telemetry coordinate dispatch via HTTP REST.
18
+ - 🗺️ **Advanced Spatial Module:** High-performance Point-in-Polygon spatial evaluation (single and general validation against all geofences).
19
+ - 👥 **Users Module:** Management of organization members, roles, and email invitations.
20
+ - 🛡️ **GeoIdentity Module:** Access rules (IP blacklists, geographic boundaries, Tor/datacenter blocking) assignable to users or to the entire organization.
21
+ - 🏗️ **Fluent Query Builder:** Fluent syntax `client.spatial.check(lat, lng).inGeofence(...)` for maximum readability.
22
+ - 🚧 **Geofence Management:** Dynamic creation and automatic normalization of PostGIS-backed GeoJSON polygons.
23
+ - 🔄 **Background AsyncIngester:** In-memory queue with auto-flush by batch size and time interval for high-throughput fleet and IoT ingestion.
24
+ - 🛡️ **Native Security:** Automatic HMAC-SHA256 signature generation (`X-Signature`), anti-replay timestamps, and JWT Bearer token support.
25
+ - 📦 **Dual Package (ESM & CommonJS):** Compatible with native `import` and `require()`, bundled with `tsup` and full `.d.ts` type definitions.
26
+ - ⚡ **Zero Runtime Dependencies:** Built on standard Node.js APIs (native `fetch`, `node:crypto`, `AbortController`). Compatible with Serverless and Edge runtimes (Cloudflare Workers, Next.js, Bun).
19
27
 
20
28
  ---
21
29
 
22
- ## 🚀 Instalación
30
+ ## 🚀 Installation
23
31
 
24
32
  ```bash
25
33
  npm install geo-engine-node
26
- ````
34
+ ```
27
35
 
28
- ---
36
+ Or using Yarn / PNPM / Bun:
29
37
 
30
- ## ⚡ Inicio Rápido
38
+ ```bash
39
+ pnpm add geo-engine-node
40
+ # or
41
+ bun add geo-engine-node
42
+ ```
31
43
 
32
- Geo-Engine soporta tanto sintaxis moderna como clásica.
44
+ ---
33
45
 
34
- ### Opción A: ES Modules (Recomendado)
46
+ ## ⚡ Quick Start
35
47
 
36
- ```js
48
+ ### TypeScript / ES Modules (Recommended)
49
+
50
+ ```ts
37
51
  import GeoEngine from 'geo-engine-node';
38
52
 
39
- // Inicializa con tu API Key
40
- const geo = new GeoEngine('sk_test_12345abcdef');
53
+ // Initialize with your secret API key
54
+ const client = new GeoEngine('geo_live_123456');
41
55
 
42
- // Envía una coordenada (ID, Latitud, Longitud)
43
56
  try {
44
- const res = await geo.sendLocation('camion-01', 19.4326, -99.1332);
45
- console.log('✅ Ubicación procesada:', res);
46
- } catch (err) {
47
- console.error('❌ Error:', err.message);
57
+ await client.sendLocation('truck-01', 19.4326, -99.1332);
58
+ console.log('✅ Coordinate sent successfully');
59
+ } catch (error) {
60
+ console.error('❌ Error sending location:', error);
61
+ } finally {
62
+ client.close();
48
63
  }
49
64
  ```
50
65
 
51
- ### Opción B: CommonJS (Legacy)
66
+ ### CommonJS (Legacy)
52
67
 
53
68
  ```js
54
69
  const GeoEngine = require('geo-engine-node');
55
70
 
56
- const geo = new GeoEngine('sk_test_...');
71
+ const client = new GeoEngine('geo_live_123456');
72
+
73
+ client.sendLocation('scooter-09', 19.4326, -99.1332)
74
+ .then(() => console.log('Location registered'))
75
+ .catch((err) => console.error(err));
57
76
  ```
58
77
 
59
78
  ---
60
79
 
61
- ## 📚 Referencia de la API
80
+ ## 🗺️ Spatial Module & Point Validation
81
+
82
+ The `client.spatial` module connects directly to the GeoEngine API service to evaluate spatial containment:
62
83
 
63
- ### `new GeoEngine(apiKey, [options])`
84
+ ### Single Geofence Validation
64
85
 
65
- Crea una nueva instancia del cliente.
86
+ ```ts
87
+ import GeoEngine, { GeofenceNotFoundError } from 'geo-engine-node';
66
88
 
67
- **Parámetros:**
89
+ const client = new GeoEngine('geo_live_123456');
68
90
 
69
- * `apiKey` (`string`): Tu clave secreta de API.
70
- * `options` (`object`, opcional):
91
+ try {
92
+ const res = await client.spatial.validatePoint('geofence_123', 19.4326, -99.1332);
93
+
94
+ if (res.isInside()) {
95
+ console.log(`✅ The device is inside ${res.geofenceName} (${res.geofenceId})`);
96
+ } else {
97
+ console.log('⚠️ The device is outside the geofence');
98
+ }
99
+
100
+ console.log('Coordinates:', res.coordinates()); // [19.4326, -99.1332]
101
+ console.log('Formatted log:', res.toString()); // [INSIDE] geofence=geofence_123 (Downtown) at (19.432600, -99.133200)
102
+ } catch (err) {
103
+ if (err instanceof GeofenceNotFoundError) {
104
+ console.warn('The requested geofence does not exist');
105
+ } else {
106
+ throw err;
107
+ }
108
+ }
109
+ ```
71
110
 
72
- * `timeout`: Tiempo de espera en ms (default: `10000`)
73
- * `ingestUrl`: URL personalizada (útil para proxies o testing)
74
- * `managementUrl`: URL del servicio de administración
111
+ ### General Validation (Against All Active Geofences)
112
+
113
+ ```ts
114
+ const res = await client.spatial.validateGeneral(19.4326, -99.1332);
115
+
116
+ if (res.hasMatches()) {
117
+ console.log(`Matched ${res.totalMatches} geofences:`, res.geofenceNames());
118
+
119
+ if (res.containsGeofence('CDMX Downtown')) {
120
+ console.log('The vehicle is in CDMX Downtown');
121
+ }
122
+
123
+ const match = res.findMatch('CDMX Downtown');
124
+ console.log('Found ID:', match?.id);
125
+ }
126
+ ```
127
+
128
+ ### Fluent Query Builder
129
+
130
+ For maximum readability, you can construct fluent queries:
131
+
132
+ ```ts
133
+ // Validation in a specific geofence
134
+ const singleRes = await client.spatial
135
+ .check(19.4326, -99.1332)
136
+ .inGeofence('geofence_123')
137
+ .execute();
138
+
139
+ // Validation against all geofences
140
+ const generalRes = await client.spatial
141
+ .check(19.4326, -99.1332)
142
+ .inAllGeofences()
143
+ .execute();
144
+ ```
75
145
 
76
146
  ---
77
147
 
78
- ### `geo.sendLocation(deviceId, lat, lng)`
148
+ ## 👥 Users Module
149
+
150
+ The `client.users` module manages the members of the organization that owns the API key:
79
151
 
80
- Envía un punto de rastreo al motor de ingestión.
81
- El sistema evaluará automáticamente las reglas espaciales.
152
+ ```ts
153
+ import GeoEngine, { Roles, InvitationPendingError, LastAdminError } from 'geo-engine-node';
82
154
 
83
- **Parámetros:**
155
+ const client = new GeoEngine('geo_live_123456');
84
156
 
85
- * `deviceId` (`string`): ID único (placa, UUID, etc).
86
- * `lat` (`number`): Latitud decimal (Ej: `19.43`)
87
- * `lng` (`number`): Longitud decimal (Ej: `-99.13`)
157
+ // List members and available roles
158
+ const users = await client.users.list();
159
+ const roles = await client.users.listRoles();
160
+ const user = await client.users.get('user_123');
161
+
162
+ // Invite a new member (GeoEngine sends the invitation email)
163
+ try {
164
+ const inv = await client.users.invite({
165
+ email: 'ana@acme.com',
166
+ role: Roles.Viewer,
167
+ lang: 'es', // 'es' (default) | 'en' | 'pt'
168
+ });
169
+ console.log('Invitation link:', inv.inviteUrl);
170
+ } catch (err) {
171
+ if (err instanceof InvitationPendingError) {
172
+ console.warn('There is already a pending invitation for this email');
173
+ } else {
174
+ throw err;
175
+ }
176
+ }
177
+
178
+ // Update a member's role or revoke their access
179
+ try {
180
+ await client.users.updateRole('user_123', Roles.Dispatcher);
181
+ await client.users.remove('user_123');
182
+ } catch (err) {
183
+ if (err instanceof LastAdminError) {
184
+ console.warn('The organization must retain at least one administrator');
185
+ } else {
186
+ throw err;
187
+ }
188
+ }
189
+ ```
88
190
 
89
191
  ---
90
192
 
91
- ### `geo.createGeofence(name, coordinates, webhookUrl)`
193
+ ## 🛡️ GeoIdentity Module
92
194
 
93
- Crea dinámicamente una zona de monitoreo.
94
- Geo-Engine enviará un `POST` a tu webhook cuando un activo entre o salga.
195
+ The `client.geoIdentity` module creates access rules and assigns them to a user or to the entire organization:
95
196
 
96
- **Ejemplo:**
197
+ ```ts
198
+ import { polygonFromLatLng, RuleActions, SubjectTypes } from 'geo-engine-node';
97
199
 
98
- ```js
99
- // Definir polígono: Array de [Lat, Lng]
100
- const zona = [
101
- [19.42, -99.16],
102
- [19.41, -99.16],
103
- [19.41, -99.15],
104
- [19.42, -99.15]
200
+ const area = polygonFromLatLng([
201
+ [19.40, -99.20], [19.40, -99.10], [19.50, -99.10], // [lat, lng]
202
+ ]);
203
+
204
+ const rule = await client.geoIdentity.createRule({
205
+ name: 'CDMX Only',
206
+ action: RuleActions.Block,
207
+ blackIpList: ['203.0.113.0/24'],
208
+ blockTor: true,
209
+ geoLimit: area,
210
+ assignedSubjects: [{ subjectType: SubjectTypes.User, subjectId: 'user_123' }],
211
+ });
212
+
213
+ // Query, update, and delete
214
+ const rules = await client.geoIdentity.listRules({ isActive: true });
215
+ const detail = await client.geoIdentity.getRule(rule.id); // includes assignedSubjects
216
+ await client.geoIdentity.updateRule(rule.id, { isActive: false, geoLimit: null }); // null removes the geographic boundary
217
+ await client.geoIdentity.deleteRule(rule.id);
218
+
219
+ // Assign or unassign the rule
220
+ await client.geoIdentity.assignToUser(rule.id, 'user_456');
221
+ await client.geoIdentity.assignToOrganization(rule.id);
222
+ await client.geoIdentity.unassignFromUser(rule.id, 'user_456');
223
+
224
+ // Rules that apply to a user (direct, by role, or organization-wide)
225
+ const userRules = await client.geoIdentity.listUserRules('user_123');
226
+ ```
227
+
228
+ > A rule created without `assignedSubjects` applies to the entire organization. A rule must always retain at least one subject: removing the last subject throws `LastSubjectError` (deactivate or delete the rule instead).
229
+
230
+ ---
231
+
232
+ ## 🚧 Geofence Creation (PostGIS Polygons)
233
+
234
+ Create spatial zones dynamically. The SDK validates the `[latitude, longitude]` format, automatically converts it to GeoJSON `[longitude, latitude]`, and ensures the polygon is closed:
235
+
236
+ ```ts
237
+ const zoneCoordinates: [number, number][] = [
238
+ [19.4326, -99.1332],
239
+ [19.4426, -99.1332],
240
+ [19.4426, -99.1232],
105
241
  ];
106
242
 
107
- await geo.createGeofence(
108
- 'Almacén Central',
109
- zona,
110
- 'https://mi-api.com/webhooks/geofence-alert'
243
+ await client.createGeofence(
244
+ 'North Logistics Park',
245
+ zoneCoordinates,
246
+ 'https://my-api.com/webhooks/geofences'
111
247
  );
112
248
  ```
113
249
 
114
250
  ---
115
251
 
116
- ## 🧪 Desarrollo Local
252
+ ## 🔄 High-Throughput Async Batch Ingestion (`AsyncIngester`)
117
253
 
118
- Ideal para probar con tu propia instancia de Geo-Engine corriendo en Docker o Localhost.
254
+ For high-volume fleet tracking or IoT telemetry, use the in-memory queue with auto-flush:
119
255
 
120
- ```js
121
- const geo = new GeoEngine('local-key', {
122
- ingestUrl: 'http://localhost:8080',
123
- managementUrl: 'http://localhost:8081'
256
+ ```ts
257
+ import GeoEngine, { AsyncIngester } from 'geo-engine-node';
258
+
259
+ const client = new GeoEngine('geo_live_123456');
260
+
261
+ // Queue: 5000 pings buffer, flush every 100 items or every 500ms
262
+ const ingester = client.createAsyncIngester(5000, 100, 500);
263
+
264
+ const ok = ingester.enqueue({
265
+ deviceId: 'truck-45',
266
+ latitude: 19.4326,
267
+ longitude: -99.1332,
268
+ timestamp: Date.now(),
124
269
  });
270
+
271
+ if (!ok) {
272
+ console.warn('Buffer queue full or ingester stopped');
273
+ }
274
+
275
+ // On service shutdown, drain all pending items:
276
+ await ingester.stop();
277
+ client.close();
125
278
  ```
126
279
 
127
280
  ---
128
281
 
129
- ## 📄 Licencia
282
+ ## 🔧 Advanced Configuration
283
+
284
+ You can configure the client using the options object:
285
+
286
+ ```ts
287
+ const client = new GeoEngine('geo_live_123456', {
288
+ environment: 'live', // 'live' | 'test'
289
+ jwtToken: 'my.jwt.token',
290
+ timeout: 5000, // milliseconds
291
+ maxRetries: 3, // retries with exponential backoff on 429/5xx
292
+ managementUrl: 'https://management.geoengine.dev',
293
+ ingestUrl: 'https://ingest.geoengine.dev',
294
+ apiServiceUrl: 'https://api.geoengine.dev',
295
+ // Or for local/mock testing:
296
+ // baseUrl: 'http://localhost:8080',
297
+ });
298
+ ```
130
299
 
131
- MIT © Geo-Engine Team
300
+ ### Available Options
301
+
302
+ | Option | Type | Description | Default |
303
+ | :--- | :--- | :--- | :--- |
304
+ | `apiKey` | `string` | Secret authentication key | (required) |
305
+ | `environment` | `string` | Target (`'live'` or `'test'`) for the `X-Geo-Environment` header | `'live'` |
306
+ | `jwtToken` | `string` | Bearer token for authorized operations | `undefined` |
307
+ | `apiServiceUrl` | `string` | URL of the API service (Spatial, Users, and GeoIdentity) | `'https://api.geoengine.dev'` |
308
+ | `ingestUrl` | `string` | URL of the telemetry ingestion service | `'https://ingest.geoengine.dev'` |
309
+ | `managementUrl` | `string` | URL of the control plane and geofence service | `'https://management.geoengine.dev'` |
310
+ | `baseUrl` | `string` | Overrides ingest, management, and apiService endpoints together | `undefined` |
311
+ | `timeout` | `number` | Request timeout in ms (via `AbortController`) | `10000` |
312
+ | `maxRetries` | `number` | Retries with exponential backoff on transient errors | `2` |
313
+ | `batchSize` | `number` | Batch size for `AsyncIngester` | `100` |
314
+ | `flushInterval` | `number` | Flush interval for `AsyncIngester` in ms | `500` |
315
+ | `bufferSize` | `number` | Maximum queue capacity for `AsyncIngester` | `5000` |
132
316
 
317
+ ---
318
+
319
+ ## 🛡️ Typed Error Hierarchy
320
+
321
+ The SDK maps all HTTP status codes and responses into a clean error class hierarchy:
322
+
323
+ ```ts
324
+ import {
325
+ GeoEngineError,
326
+ ValidationError,
327
+ InvalidLatitudeError,
328
+ InvalidLongitudeError,
329
+ DeviceIDRequiredError,
330
+ GeofenceNotFoundError,
331
+ QuotaExceededError,
332
+ AuthenticationError,
333
+ ForbiddenError,
334
+ TimeoutError,
335
+ SpatialAPIError,
336
+ } from 'geo-engine-node';
337
+
338
+ try {
339
+ await client.spatial.validatePoint('geo-x', lat, lng);
340
+ } catch (error) {
341
+ if (error instanceof GeofenceNotFoundError) {
342
+ // 204 No Content or 404 Not Found
343
+ } else if (error instanceof QuotaExceededError) {
344
+ // 402 Payment Required or 429
345
+ } else if (error instanceof AuthenticationError) {
346
+ // 401 Unauthorized or MISSING_API_KEY
347
+ } else if (error instanceof TimeoutError) {
348
+ // Request timed out
349
+ } else if (error instanceof ValidationError) {
350
+ // Coordinate out of range [-90,90] or invalid parameter
351
+ }
352
+ }
353
+ ```
354
+
355
+ The Users and GeoIdentity modules throw `APIServiceError` (with `statusCode`, `code`, and `apiMessage`) or one of its subclasses:
356
+
357
+ | Error | API Code | When it occurs |
358
+ | :--- | :--- | :--- |
359
+ | `UserNotFoundError` | `USER_NOT_FOUND`, `USER_REVOKED` | User does not exist in the organization |
360
+ | `RuleNotFoundError` | `RULE_NOT_FOUND` | GeoIdentity rule does not exist |
361
+ | `UserAlreadyExistsError` | `USER_ALREADY_EXISTS` | Invited email already belongs to the organization |
362
+ | `InvitationPendingError` | `INVITATION_PENDING` | There is already a pending invitation for this email |
363
+ | `LastAdminError` | `LAST_ADMIN` | Operation would leave the organization without administrators |
364
+ | `LastSubjectError` | `LAST_SUBJECT` | Operation would leave the rule without assigned subjects |
365
+
366
+ Errors 401, 403, and 402 reuse `AuthenticationError`, `ForbiddenError`, and `QuotaExceededError`. Local validations throw `UserIDRequiredError`, `RuleIDRequiredError`, `RuleNameRequiredError`, `EmailRequiredError`, or `RoleRequiredError` without calling the API.
367
+
368
+ > In Users and GeoIdentity, only read requests (`GET`) are automatically retried on 429/5xx; write operations are never retried to prevent duplicate invitations or assignments.
369
+
370
+ ---
371
+
372
+ ## 🧪 Testing and Building
373
+
374
+ Run the unit and integration test suite with Vitest:
375
+
376
+ ```bash
377
+ npm run test
378
+ ```
379
+
380
+ To compile CJS and ESM outputs with TypeScript type definitions:
381
+
382
+ ```bash
383
+ npm run build
384
+ npm run typecheck
385
+ ```
386
+
387
+ ---
388
+
389
+ ## 📄 License
390
+
391
+ MIT © Geo-Engine Team