geo-engine-node 2.0.0 → 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.es.md +391 -0
- package/Readme.md +186 -83
- package/dist/index.cjs +508 -51
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +348 -1
- package/dist/index.d.ts +348 -1
- package/dist/index.js +489 -51
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.es.md
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
# 📦 Geo-Engine Node.js & TypeScript SDK
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/geo-engine-node)
|
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
|
5
|
+
[](https://www.typescriptlang.org/)
|
|
6
|
+
[](https://vitest.dev/)
|
|
7
|
+
|
|
8
|
+
> *Lee esto en Inglés: [Readme.md](./Readme.md)*
|
|
9
|
+
|
|
10
|
+
Cliente oficial e idiomático en **Node.js & TypeScript** para la plataforma **Geo-Engine**.
|
|
11
|
+
Diseñado para **alto rendimiento**, tipado estricto y paridad 1:1 con el SDK oficial de Go (`v2.1.0`). Se integra perfectamente en microservicios backend, funciones Serverless y entornos edge modernos.
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## ✨ Características
|
|
16
|
+
|
|
17
|
+
- 📍 **Ingesta en tiempo real:** Envío sub-10ms de coordenadas de telemetría por HTTP REST.
|
|
18
|
+
- 🗺️ **Módulo Spatial avanzado:** Evaluación espacial punto-en-polígono (Point-in-Polygon) de alto rendimiento (validación individual y general contra todas las geocercas).
|
|
19
|
+
- 👥 **Módulo Users:** Gestión de miembros de la organización, roles e invitaciones por correo.
|
|
20
|
+
- 🛡️ **Módulo GeoIdentity:** Reglas de acceso (listas de IPs, límites geográficos, bloqueo de Tor/datacenters) asignables a usuarios o a toda la organización.
|
|
21
|
+
- 🏗️ **Fluent Query Builder:** Sintaxis fluida `client.spatial.check(lat, lng).inGeofence(...)` para máxima legibilidad.
|
|
22
|
+
- 🚧 **Gestión de geocercas:** Creación dinámica y normalización automática de polígonos GeoJSON respaldados por PostGIS.
|
|
23
|
+
- 🔄 **AsyncIngester en segundo plano:** Cola con auto-flush por tamaño de lote e intervalo de tiempo para alta ingesta en flotas e IoT.
|
|
24
|
+
- 🛡️ **Seguridad nativa:** Generación automática de firmas HMAC-SHA256 (`X-Signature`), timestamp anti-replay y soporte para tokens JWT Bearer.
|
|
25
|
+
- 📦 **Dual Package (ESM & CommonJS):** Compatible con `import` nativo y `require()`, empaquetado con `tsup` y definiciones de tipos `.d.ts`.
|
|
26
|
+
- ⚡ **Zero dependencias en runtime:** Desarrollado sobre APIs estándar de Node.js (`fetch` nativo, `node:crypto`, `AbortController`). Compatible con Serverless y Edge (Cloudflare Workers, Next.js, Bun).
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## 🚀 Instalación
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
npm install geo-engine-node
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
O usando Yarn / PNPM / Bun:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pnpm add geo-engine-node
|
|
40
|
+
# o
|
|
41
|
+
bun add geo-engine-node
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## ⚡ Inicio Rápido
|
|
47
|
+
|
|
48
|
+
### TypeScript / ES Modules (Recomendado)
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
import GeoEngine from 'geo-engine-node';
|
|
52
|
+
|
|
53
|
+
// Inicializa con tu clave secreta de API
|
|
54
|
+
const client = new GeoEngine('geo_live_123456');
|
|
55
|
+
|
|
56
|
+
try {
|
|
57
|
+
await client.sendLocation('truck-01', 19.4326, -99.1332);
|
|
58
|
+
console.log('✅ Coordenada enviada con éxito');
|
|
59
|
+
} catch (error) {
|
|
60
|
+
console.error('❌ Error al enviar ubicación:', error);
|
|
61
|
+
} finally {
|
|
62
|
+
client.close();
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### CommonJS (Legacy)
|
|
67
|
+
|
|
68
|
+
```js
|
|
69
|
+
const GeoEngine = require('geo-engine-node');
|
|
70
|
+
|
|
71
|
+
const client = new GeoEngine('geo_live_123456');
|
|
72
|
+
|
|
73
|
+
client.sendLocation('scooter-09', 19.4326, -99.1332)
|
|
74
|
+
.then(() => console.log('Ubicación registrada'))
|
|
75
|
+
.catch((err) => console.error(err));
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## 🗺️ Módulo Spatial & Validación de Puntos
|
|
81
|
+
|
|
82
|
+
El módulo `client.spatial` conecta directamente con el servicio de API de GeoEngine para evaluar contención espacial:
|
|
83
|
+
|
|
84
|
+
### Validación contra una Geocerca Individual
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
import GeoEngine, { GeofenceNotFoundError } from 'geo-engine-node';
|
|
88
|
+
|
|
89
|
+
const client = new GeoEngine('geo_live_123456');
|
|
90
|
+
|
|
91
|
+
try {
|
|
92
|
+
const res = await client.spatial.validatePoint('geofence_123', 19.4326, -99.1332);
|
|
93
|
+
|
|
94
|
+
if (res.isInside()) {
|
|
95
|
+
console.log(`✅ El dispositivo está dentro de ${res.geofenceName} (${res.geofenceId})`);
|
|
96
|
+
} else {
|
|
97
|
+
console.log('⚠️ El dispositivo está fuera de la geocerca');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
console.log('Coordenadas:', res.coordinates()); // [19.4326, -99.1332]
|
|
101
|
+
console.log('Log formateado:', res.toString()); // [INSIDE] geofence=geofence_123 (Centro) at (19.432600, -99.133200)
|
|
102
|
+
} catch (err) {
|
|
103
|
+
if (err instanceof GeofenceNotFoundError) {
|
|
104
|
+
console.warn('La geocerca solicitada no existe');
|
|
105
|
+
} else {
|
|
106
|
+
throw err;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### Validación General (Contra Todas las Geocercas Activas)
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
const res = await client.spatial.validateGeneral(19.4326, -99.1332);
|
|
115
|
+
|
|
116
|
+
if (res.hasMatches()) {
|
|
117
|
+
console.log(`Coincide con ${res.totalMatches} geocercas:`, res.geofenceNames());
|
|
118
|
+
|
|
119
|
+
if (res.containsGeofence('CDMX Centro')) {
|
|
120
|
+
console.log('El vehículo está en CDMX Centro');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const match = res.findMatch('CDMX Centro');
|
|
124
|
+
console.log('ID encontrado:', match?.id);
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Fluent Query Builder
|
|
129
|
+
|
|
130
|
+
Para mayor legibilidad, puedes construir consultas fluidas:
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
// Validación en geocerca específica
|
|
134
|
+
const singleRes = await client.spatial
|
|
135
|
+
.check(19.4326, -99.1332)
|
|
136
|
+
.inGeofence('geofence_123')
|
|
137
|
+
.execute();
|
|
138
|
+
|
|
139
|
+
// Validación contra todas las geocercas
|
|
140
|
+
const generalRes = await client.spatial
|
|
141
|
+
.check(19.4326, -99.1332)
|
|
142
|
+
.inAllGeofences()
|
|
143
|
+
.execute();
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
---
|
|
147
|
+
|
|
148
|
+
## 👥 Módulo Users
|
|
149
|
+
|
|
150
|
+
El módulo `client.users` gestiona los miembros de la organización dueña de la API key:
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
import GeoEngine, { Roles, InvitationPendingError, LastAdminError } from 'geo-engine-node';
|
|
154
|
+
|
|
155
|
+
const client = new GeoEngine('geo_live_123456');
|
|
156
|
+
|
|
157
|
+
// Listar miembros y roles disponibles
|
|
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
|
+
// Invitar a un nuevo miembro (GeoEngine envía el correo de invitación)
|
|
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('Enlace de invitación:', inv.inviteUrl);
|
|
170
|
+
} catch (err) {
|
|
171
|
+
if (err instanceof InvitationPendingError) {
|
|
172
|
+
console.warn('Ya existe una invitación pendiente para este email');
|
|
173
|
+
} else {
|
|
174
|
+
throw err;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Cambiar el rol de un miembro o revocar su acceso
|
|
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('La organización debe conservar al menos un administrador');
|
|
185
|
+
} else {
|
|
186
|
+
throw err;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
---
|
|
192
|
+
|
|
193
|
+
## 🛡️ Módulo GeoIdentity
|
|
194
|
+
|
|
195
|
+
El módulo `client.geoIdentity` crea reglas de acceso y las asigna a un usuario o a toda la organización:
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
import { polygonFromLatLng, RuleActions, SubjectTypes } from 'geo-engine-node';
|
|
199
|
+
|
|
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: 'Solo CDMX',
|
|
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
|
+
// Consultar, actualizar y eliminar
|
|
214
|
+
const rules = await client.geoIdentity.listRules({ isActive: true });
|
|
215
|
+
const detail = await client.geoIdentity.getRule(rule.id); // incluye assignedSubjects
|
|
216
|
+
await client.geoIdentity.updateRule(rule.id, { isActive: false, geoLimit: null }); // null quita el límite geográfico
|
|
217
|
+
await client.geoIdentity.deleteRule(rule.id);
|
|
218
|
+
|
|
219
|
+
// Asignar o quitar la regla
|
|
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
|
+
// Reglas que aplican a un usuario (directas, por rol o de toda la organización)
|
|
225
|
+
const userRules = await client.geoIdentity.listUserRules('user_123');
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
> Una regla creada sin `assignedSubjects` aplica a toda la organización. Una regla siempre debe conservar al menos un sujeto: quitar el último lanza `LastSubjectError` (en su lugar, desactívala o elimínala).
|
|
229
|
+
|
|
230
|
+
---
|
|
231
|
+
|
|
232
|
+
## 🚧 Creación de Geocercas (Polígonos PostGIS)
|
|
233
|
+
|
|
234
|
+
Crea zonas espaciales dinámicamente. El SDK valida el formato `[latitud, longitud]`, convierte automáticamente a GeoJSON `[longitud, latitud]` y asegura el cierre del polígono:
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
const coordenadasZona: [number, number][] = [
|
|
238
|
+
[19.4326, -99.1332],
|
|
239
|
+
[19.4426, -99.1332],
|
|
240
|
+
[19.4426, -99.1232],
|
|
241
|
+
];
|
|
242
|
+
|
|
243
|
+
await client.createGeofence(
|
|
244
|
+
'Parque Logístico Norte',
|
|
245
|
+
coordenadasZona,
|
|
246
|
+
'https://mi-api.com/webhooks/geocercas'
|
|
247
|
+
);
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
---
|
|
251
|
+
|
|
252
|
+
## 🔄 Ingesta Asíncrona en Lotes (`AsyncIngester`)
|
|
253
|
+
|
|
254
|
+
Para telemetría masiva de flotas de vehículos o dispositivos IoT, utiliza la cola en memoria con auto-flush:
|
|
255
|
+
|
|
256
|
+
```ts
|
|
257
|
+
import GeoEngine, { AsyncIngester } from 'geo-engine-node';
|
|
258
|
+
|
|
259
|
+
const client = new GeoEngine('geo_live_123456');
|
|
260
|
+
|
|
261
|
+
// Cola: buffer 5000 pings, flush cada 100 items o cada 500ms
|
|
262
|
+
const ingester = client.createAsyncIngester(5000, 100, 500);
|
|
263
|
+
|
|
264
|
+
const ok = ingester.enqueue({
|
|
265
|
+
deviceId: 'camion-45',
|
|
266
|
+
latitude: 19.4326,
|
|
267
|
+
longitude: -99.1332,
|
|
268
|
+
timestamp: Date.now(),
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
if (!ok) {
|
|
272
|
+
console.warn('Buffer lleno o ingester detenido');
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Al apagar el servicio, drena todos los elementos pendientes:
|
|
276
|
+
await ingester.stop();
|
|
277
|
+
client.close();
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
---
|
|
281
|
+
|
|
282
|
+
## 🔧 Configuración Avanzada
|
|
283
|
+
|
|
284
|
+
Puedes configurar el cliente mediante el objeto de opciones:
|
|
285
|
+
|
|
286
|
+
```ts
|
|
287
|
+
const client = new GeoEngine('geo_live_123456', {
|
|
288
|
+
environment: 'live', // 'live' | 'test'
|
|
289
|
+
jwtToken: 'mi.jwt.token',
|
|
290
|
+
timeout: 5000, // milisegundos
|
|
291
|
+
maxRetries: 3, // reintentos con backoff exponencial ante 429/5xx
|
|
292
|
+
managementUrl: 'https://management.geoengine.dev',
|
|
293
|
+
ingestUrl: 'https://ingest.geoengine.dev',
|
|
294
|
+
apiServiceUrl: 'https://api.geoengine.dev',
|
|
295
|
+
// O para pruebas locales/mock:
|
|
296
|
+
// baseUrl: 'http://localhost:8080',
|
|
297
|
+
});
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
### Opciones Disponibles
|
|
301
|
+
|
|
302
|
+
| Opción | Tipo | Descripción | Default |
|
|
303
|
+
| :--- | :--- | :--- | :--- |
|
|
304
|
+
| `apiKey` | `string` | Clave secreta de autenticación | (requerido) |
|
|
305
|
+
| `environment` | `string` | Target (`'live'` o `'test'`) para header `X-Geo-Environment` | `'live'` |
|
|
306
|
+
| `jwtToken` | `string` | Token Bearer para operaciones autorizadas | `undefined` |
|
|
307
|
+
| `apiServiceUrl` | `string` | URL del api-service (Spatial, Users y GeoIdentity) | `'https://api.geoengine.dev'` |
|
|
308
|
+
| `ingestUrl` | `string` | URL del servicio de ingestión de telemetría | `'https://ingest.geoengine.dev'` |
|
|
309
|
+
| `managementUrl` | `string` | URL del servicio de control y geocercas | `'https://management.geoengine.dev'` |
|
|
310
|
+
| `baseUrl` | `string` | Sobrescribe ingest, management y apiService juntas | `undefined` |
|
|
311
|
+
| `timeout` | `number` | Tiempo límite de espera en ms (vía `AbortController`) | `10000` |
|
|
312
|
+
| `maxRetries` | `number` | Reintentos con backoff exponencial ante fallos transitorios | `2` |
|
|
313
|
+
| `batchSize` | `number` | Tamaño de lote para `AsyncIngester` | `100` |
|
|
314
|
+
| `flushInterval` | `number` | Intervalo de vaciado de `AsyncIngester` en ms | `500` |
|
|
315
|
+
| `bufferSize` | `number` | Capacidad máxima de la cola de `AsyncIngester` | `5000` |
|
|
316
|
+
|
|
317
|
+
---
|
|
318
|
+
|
|
319
|
+
## 🛡️ Jerarquía de Errores Tipados
|
|
320
|
+
|
|
321
|
+
El SDK mapea todos los códigos de estado y respuestas en una jerarquía clara de clases de error:
|
|
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 o 404 Not Found
|
|
343
|
+
} else if (error instanceof QuotaExceededError) {
|
|
344
|
+
// 402 Payment Required o 429
|
|
345
|
+
} else if (error instanceof AuthenticationError) {
|
|
346
|
+
// 401 Unauthorized o MISSING_API_KEY
|
|
347
|
+
} else if (error instanceof TimeoutError) {
|
|
348
|
+
// Tiempo de espera agotado
|
|
349
|
+
} else if (error instanceof ValidationError) {
|
|
350
|
+
// Coordenada fuera de rango [-90,90] o parámetro inválido
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
Los módulos Users y GeoIdentity lanzan `APIServiceError` (con `statusCode`, `code` y `apiMessage`) o una de sus subclases:
|
|
356
|
+
|
|
357
|
+
| Error | Código de la API | Cuándo ocurre |
|
|
358
|
+
| :--- | :--- | :--- |
|
|
359
|
+
| `UserNotFoundError` | `USER_NOT_FOUND`, `USER_REVOKED` | El usuario no existe en la organización |
|
|
360
|
+
| `RuleNotFoundError` | `RULE_NOT_FOUND` | La regla GeoIdentity no existe |
|
|
361
|
+
| `UserAlreadyExistsError` | `USER_ALREADY_EXISTS` | El email invitado ya pertenece a la organización |
|
|
362
|
+
| `InvitationPendingError` | `INVITATION_PENDING` | Ya hay una invitación pendiente para ese email |
|
|
363
|
+
| `LastAdminError` | `LAST_ADMIN` | La operación dejaría a la organización sin administradores |
|
|
364
|
+
| `LastSubjectError` | `LAST_SUBJECT` | La operación dejaría a la regla sin sujetos asignados |
|
|
365
|
+
|
|
366
|
+
Los errores 401, 403 y 402 reutilizan `AuthenticationError`, `ForbiddenError` y `QuotaExceededError`. Las validaciones locales lanzan `UserIDRequiredError`, `RuleIDRequiredError`, `RuleNameRequiredError`, `EmailRequiredError` o `RoleRequiredError` sin llamar a la API.
|
|
367
|
+
|
|
368
|
+
> En Users y GeoIdentity solo las lecturas (`GET`) se reintentan automáticamente ante 429/5xx; las escrituras nunca se reenvían para no duplicar invitaciones ni asignaciones.
|
|
369
|
+
|
|
370
|
+
---
|
|
371
|
+
|
|
372
|
+
## 🧪 Pruebas y Compilación
|
|
373
|
+
|
|
374
|
+
Ejecuta la suite de pruebas unitarias e integración con Vitest:
|
|
375
|
+
|
|
376
|
+
```bash
|
|
377
|
+
npm run test
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
Para compilar las salidas CJS y ESM con tipos TypeScript:
|
|
381
|
+
|
|
382
|
+
```bash
|
|
383
|
+
npm run build
|
|
384
|
+
npm run typecheck
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
---
|
|
388
|
+
|
|
389
|
+
## 📄 Licencia
|
|
390
|
+
|
|
391
|
+
MIT © Geo-Engine Team
|