geo-engine-node 2.1.0 → 3.0.0-rc.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,35 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [3.0.0-rc.1] - 2026-11-24
8
+
9
+ Release candidate, published under the npm `next` dist-tag. The GeoIdentity module is **experimental**: its `/v1/evaluate` contract is a draft and it is not recommended for production.
10
+
11
+ ### BREAKING
12
+
13
+ - **`client.options.apiKey` no longer exists** (it is also removed from the `HttpClientConfig` type). The key is stored in a private field and redacted in `util.inspect`, `JSON.stringify` and error messages. *Migration:* keep the key in your own variable (for example `process.env.GEOENGINE_API_KEY`) instead of reading it back from `client.options`.
14
+ - **Service URLs must use `https`** (`baseUrl`, `managementUrl`, `ingestUrl`, `apiServiceUrl`), except loopback (`localhost`, `127.0.0.1`, `::1`). Otherwise the constructor throws `ValidationError` before any request. *Migration:* point staging/test environments to an https URL or to a loopback address.
15
+ - **Redirects are no longer followed** (`redirect: 'manual'`): a 3xx response now reaches your code as an error instead of being followed silently, so credentials cannot be forwarded to another origin. *Migration:* configure the final URL directly.
16
+ - **Minimum Node.js is 20** (`engines.node >=20.0.0`); the CI matrix is Node 20 and 22.
17
+ - Identity types `Location`, `Context` and `Subject` are exported as `IdentityLocation`, `IdentityContext` and `IdentitySubject` (no aliases).
18
+
19
+ ### Security
20
+
21
+ - Error messages from legacy routes no longer include the API key or the JWT, even if the server echoes them in the response body.
22
+ - Published sourcemaps no longer contain absolute local paths.
23
+
24
+ ### Added
25
+ - Server-only GeoIdentity runtime evaluation via `client.identity.evaluate({ scope, subject, context })` against `POST /v1/evaluate`, using `Authorization: Bearer <apiKey>` and automatic `X-Request-Id` propagation.
26
+ - New subpath export `geo-engine-node/identity` (ESM & CJS) providing Express/Connect-compatible `identityGuard({ client, scope, getSubject, getContext, failOpen, ... })` with mandatory `failOpen`, `CHALLENGE` handling, synthetic fallback decisions (`meta.source = 'sdk_fallback'`), and browser runtime protection.
27
+ - Typed identity errors `IdentityTransientError`, `IdentityIntegrationError`, and `isTransient(err)`, with 500ms default total deadline and single jittered retry for transient failures (including `Retry-After` handling on 429).
28
+ - Security hardening: moved `apiKey` to a private `#` field, removed it from `client.options`, and redacted secrets in `util.inspect`, `JSON.stringify`, and error messages.
29
+ - Repository hygiene: `LICENSE` (MIT, Copyright (c) 2026 Geo-Engine Team), CI and security workflows, Dependabot, `CODEOWNERS`, `SECURITY.md`, and a tag-triggered release workflow publishing with npm trusted publishing (provenance).
30
+
31
+ ### Changed
32
+ - Build uses code splitting so `.` and `./identity` share a single set of error classes per format; `IdentityIntegrationError instanceof GeoEngineError` is now `true` within each format. Identity errors expose a stable `err.code` (`IDENTITY_TRANSIENT`, `IDENTITY_INTEGRATION`), which is the contract across ESM and CJS (classes are not shared between formats).
33
+ - Server error bodies are scrubbed of the API key and JWT before becoming error messages; tests assert that no secret appears in `JSON.stringify`, `util.inspect` or messages of clients and errors.
34
+ - `User-Agent` version is injected from `package.json` at build time.
35
+ - Updated `Readme.md` and `README.es.md`: identity docs, `failOpen` semantics, aligned retry/error/HMAC/runtime notes; examples read the key from `process.env.GEOENGINE_API_KEY` with an explicit check.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Geo-Engine Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.es.md CHANGED
@@ -3,27 +3,28 @@
3
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
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
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/)
6
+ [![Tests](https://img.shields.io/badge/Tests-Vitest%20%2B%20node%3Atest-green.svg)](https://vitest.dev/)
7
7
 
8
- > *Lee esto en Inglés: [Readme.md](./Readme.md)*
8
+ > *Read this in English: [Readme.md](./Readme.md)*
9
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.
10
+ Cliente oficial en **Node.js & TypeScript** para la plataforma **Geo-Engine** (`v3.0.0-rc.1`).
11
+
12
+ > ⚠️ **Release candidate / experimental:** `v3.0.0-rc.1` se publica bajo la etiqueta `next` (`npm install geo-engine-node@next`). El módulo GeoIdentity (`client.identity`, `geo-engine-node/identity`) es **experimental**: su contrato (`/v1/evaluate`) está en **borrador** y **no se recomienda en producción**. Es una versión mayor con cambios incompatibles; consulta [CHANGELOG.md](./CHANGELOG.md) para las notas de migración.
13
+ Diseñado con tipado estricto en TypeScript, cero dependencias en runtime e integración del lado del servidor en Node.js `>=20`.
12
14
 
13
15
  ---
14
16
 
15
17
  ## ✨ Características
16
18
 
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).
19
+ - 📍 **Ingesta de Telemetría:** Envío de coordenadas por HTTP REST (`sendLocation`) y cola en segundo plano `AsyncIngester`.
20
+ - 🗺️ **Módulo Spatial:** Evaluación punto-en-polígono (geocerca individual y validación general contra todas las geocercas activas) más constructor fluido `client.spatial.check(lat, lng)`.
21
+ - 👥 **Módulo Users:** Gestión de miembros de la organización, roles e invitaciones por correo (`client.users`).
22
+ - 🛡️ **Reglas y Evaluación GeoIdentity:** CRUD de reglas (`client.geoIdentity`) y evaluación de decisiones en servidor mediante `client.identity.evaluate(...)` y `geo-engine-node/identity` (`identityGuard`).
23
+ - 🚧 **Gestión de Geocercas:** Creación y normalización automática de polígonos GeoJSON respaldados por PostGIS (`createGeofence`).
24
+ - 📦 **Dual Package (ESM & CommonJS):** Compatible con `import` nativo y `require()`, empaquetado con `tsup` y definiciones `.d.ts` / `.d.cts`.
25
+ - ⚡ **Cero dependencias en runtime:** Construido sobre APIs estándar de Node.js (`fetch`, `node:crypto`, `node:timers`, `AbortController`) para entornos de servidor Node.js `>=20`.
26
+
27
+ > **Nota de Runtime:** El SDK importa `node:crypto` y `node:timers`, por lo que está pensado para **servidores Node.js** (no es compatible con navegadores ni entornos edge sin capa de compatibilidad de Node). La `apiKey` secreta se almacena en un campo privado `#` y no se expone en `client.options`, `JSON.stringify` ni `util.inspect`.
27
28
 
28
29
  ---
29
30
 
@@ -51,7 +52,9 @@ bun add geo-engine-node
51
52
  import GeoEngine from 'geo-engine-node';
52
53
 
53
54
  // Inicializa con tu clave secreta de API
54
- const client = new GeoEngine('geo_live_123456');
55
+ const apiKey = process.env.GEOENGINE_API_KEY;
56
+ if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
57
+ const client = new GeoEngine(apiKey);
55
58
 
56
59
  try {
57
60
  await client.sendLocation('truck-01', 19.4326, -99.1332);
@@ -63,12 +66,14 @@ try {
63
66
  }
64
67
  ```
65
68
 
66
- ### CommonJS (Legacy)
69
+ ### CommonJS
67
70
 
68
71
  ```js
69
72
  const GeoEngine = require('geo-engine-node');
70
73
 
71
- const client = new GeoEngine('geo_live_123456');
74
+ const apiKey = process.env.GEOENGINE_API_KEY;
75
+ if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
76
+ const client = new GeoEngine(apiKey);
72
77
 
73
78
  client.sendLocation('scooter-09', 19.4326, -99.1332)
74
79
  .then(() => console.log('Ubicación registrada'))
@@ -77,16 +82,93 @@ client.sendLocation('scooter-09', 19.4326, -99.1332)
77
82
 
78
83
  ---
79
84
 
80
- ## 🗺️ Módulo Spatial & Validación de Puntos
85
+ ## 🛡️ Evaluación GeoIdentity en Tiempo de Ejecución (`/v1/evaluate` e `identityGuard`)
86
+
87
+ > [!IMPORTANT]
88
+ > **Solo servidor y llave secreta:** `POST /v1/evaluate` autentica únicamente con `Authorization: Bearer <llave_secreta>` y **no** admite CORS desde navegadores. Nunca expongas la API key ni importes `geo-engine-node/identity` en código de navegador (si `window` está definido, el módulo lanza un error inmediato).
89
+
90
+ ### Evaluación Directa (`client.identity.evaluate`)
91
+
92
+ ```ts
93
+ import GeoEngine from 'geo-engine-node';
94
+ import { IdentityTransientError, IdentityIntegrationError, isTransient } from 'geo-engine-node/identity';
95
+
96
+ const apiKey = process.env.GEOENGINE_API_KEY;
97
+ if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
98
+ const client = new GeoEngine(apiKey);
81
99
 
82
- El módulo `client.spatial` conecta directamente con el servicio de API de GeoEngine para evaluar contención espacial:
100
+ try {
101
+ const decision = await client.identity.evaluate({
102
+ scope: 'login',
103
+ subject: { user_id: 'user_2abc123', roles: ['admin'], device_id: 'dev_9f8e7d' },
104
+ context: {
105
+ ip: '203.0.113.42',
106
+ location: { lat: 28.6353, lng: -106.0889, accuracy_m: 25, source: 'device' },
107
+ },
108
+ });
109
+
110
+ if (decision.decision === 'BLOCK') {
111
+ // Bloquear acceso
112
+ } else if (decision.decision === 'CHALLENGE') {
113
+ // Solicitar verificación adicional (step-up)
114
+ }
115
+ } catch (err) {
116
+ if (isTransient(err)) {
117
+ // Red, timeout, 5xx o 429 tras el plazo de 500ms y un reintento
118
+ } else if (err instanceof IdentityIntegrationError) {
119
+ // 400, 401, 403 de borde, 404, 422 o respuesta inesperada (NO aplicar failOpen)
120
+ }
121
+ }
122
+ ```
83
123
 
84
- ### Validación contra una Geocerca Individual
124
+ ### Middleware Express / Connect (`identityGuard`)
125
+
126
+ ```ts
127
+ import GeoEngine from 'geo-engine-node';
128
+ import { identityGuard } from 'geo-engine-node/identity';
129
+
130
+ const apiKey = process.env.GEOENGINE_API_KEY;
131
+ if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
132
+ const client = new GeoEngine(apiKey);
133
+
134
+ app.post(
135
+ '/login',
136
+ identityGuard({
137
+ client,
138
+ scope: 'login',
139
+ failOpen: false, // OBLIGATORIO: true permite ante fallo transitorio, false bloquea (403)
140
+ getSubject: (req) => ({ user_id: req.body.userId, device_id: req.headers['x-device-id'] as string }),
141
+ getContext: (req) => ({
142
+ ip: req.ip,
143
+ location: req.body.location, // Si falta y el scope tiene reglas geográficas, el motor puede bloquear con `location_missing`
144
+ }),
145
+ onChallenge: async (decision, _req, res) => {
146
+ res.status(403).json({ error: 'challenge_required', hint: decision.challenge?.hint ?? 'step_up' });
147
+ },
148
+ onIntegrationError: (err) => {
149
+ console.error('Error de integración GeoIdentity:', err);
150
+ },
151
+ }),
152
+ loginHandler
153
+ );
154
+ ```
155
+
156
+ - **`failOpen` (obligatorio, sin valor por defecto):** aplica **solo** ante errores transitorios (`timeout`, `network`, `server_error`, `rate_limited`) o un valor de `decision` desconocido (`unknown_decision`). En ese caso entrega a `onDecision` una decisión sintética con `fallback: true`, `fallback_reason` y `meta.source = 'sdk_fallback'`.
157
+ - **Errores de integración nunca aplican `failOpen`:** `400`, `401`, `403` (incluido `403` de borde sin `problem+json`), `404`, `422`, parámetros locales inválidos o respuestas con forma inesperada llaman a `onIntegrationError` y responden `500` (`{ error: 'internal_error' }`).
158
+ - **`CHALLENGE`:** llama a `onChallenge` si se configura; si falta, responde `403` con `{ error: 'challenge_required', hint: 'step_up' }` y nunca llama a `next()`.
159
+ - **`context.location`:** si el scope evalúa condiciones geográficas y no se envía `location`, `/v1/evaluate` responde HTTP `200` con la señal `location_missing` (puede bloquear como decisión normal, no como error).
160
+ - **Plazo y reintentos:** `evaluate` aplica un plazo total por defecto de `500 ms` (`identityTimeoutMs` o `timeoutMs` por llamada) y como máximo 1 reintento con jitter ante fallos transitorios (respetando `Retry-After` si cabe en el plazo restante), reutilizando el mismo `X-Request-Id`.
161
+
162
+ ---
163
+
164
+ ## 🗺️ Módulo Spatial & Validación de Puntos
85
165
 
86
166
  ```ts
87
167
  import GeoEngine, { GeofenceNotFoundError } from 'geo-engine-node';
88
168
 
89
- const client = new GeoEngine('geo_live_123456');
169
+ const apiKey = process.env.GEOENGINE_API_KEY;
170
+ if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
171
+ const client = new GeoEngine(apiKey);
90
172
 
91
173
  try {
92
174
  const res = await client.spatial.validatePoint('geofence_123', 19.4326, -99.1332);
@@ -96,9 +178,6 @@ try {
96
178
  } else {
97
179
  console.log('⚠️ El dispositivo está fuera de la geocerca');
98
180
  }
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
181
  } catch (err) {
103
182
  if (err instanceof GeofenceNotFoundError) {
104
183
  console.warn('La geocerca solicitada no existe');
@@ -108,58 +187,32 @@ try {
108
187
  }
109
188
  ```
110
189
 
111
- ### Validación General (Contra Todas las Geocercas Activas)
190
+ ### Validación General y Constructor Fluido
112
191
 
113
192
  ```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
- ```
193
+ const generalRes = await client.spatial.validateGeneral(19.4326, -99.1332);
127
194
 
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
195
+ const fluentRes = await client.spatial
135
196
  .check(19.4326, -99.1332)
136
197
  .inGeofence('geofence_123')
137
198
  .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
199
  ```
145
200
 
146
201
  ---
147
202
 
148
203
  ## 👥 Módulo Users
149
204
 
150
- El módulo `client.users` gestiona los miembros de la organización dueña de la API key:
151
-
152
205
  ```ts
153
206
  import GeoEngine, { Roles, InvitationPendingError, LastAdminError } from 'geo-engine-node';
154
207
 
155
- const client = new GeoEngine('geo_live_123456');
208
+ const apiKey = process.env.GEOENGINE_API_KEY;
209
+ if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
210
+ const client = new GeoEngine(apiKey);
156
211
 
157
- // Listar miembros y roles disponibles
158
212
  const users = await client.users.list();
159
213
  const roles = await client.users.listRoles();
160
214
  const user = await client.users.get('user_123');
161
215
 
162
- // Invitar a un nuevo miembro (GeoEngine envía el correo de invitación)
163
216
  try {
164
217
  const inv = await client.users.invite({
165
218
  email: 'ana@acme.com',
@@ -174,31 +227,17 @@ try {
174
227
  throw err;
175
228
  }
176
229
  }
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
230
  ```
190
231
 
191
232
  ---
192
233
 
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:
234
+ ## 🛡️ Gestión de Reglas GeoIdentity (`client.geoIdentity`)
196
235
 
197
236
  ```ts
198
237
  import { polygonFromLatLng, RuleActions, SubjectTypes } from 'geo-engine-node';
199
238
 
200
239
  const area = polygonFromLatLng([
201
- [19.40, -99.20], [19.40, -99.10], [19.50, -99.10], // [lat, lng]
240
+ [19.40, -99.20], [19.40, -99.10], [19.50, -99.10],
202
241
  ]);
203
242
 
204
243
  const rule = await client.geoIdentity.createRule({
@@ -210,28 +249,15 @@ const rule = await client.geoIdentity.createRule({
210
249
  assignedSubjects: [{ subjectType: SubjectTypes.User, subjectId: 'user_123' }],
211
250
  });
212
251
 
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
252
+ await client.geoIdentity.updateRule(rule.id, { isActive: false, geoLimit: null });
217
253
  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
254
  ```
227
255
 
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
256
  ---
231
257
 
232
258
  ## 🚧 Creación de Geocercas (Polígonos PostGIS)
233
259
 
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:
260
+ El SDK valida el formato `[latitud, longitud]`, convierte automáticamente a GeoJSON `[longitud, latitud]` y asegura el cierre del polígono:
235
261
 
236
262
  ```ts
237
263
  const coordenadasZona: [number, number][] = [
@@ -251,14 +277,14 @@ await client.createGeofence(
251
277
 
252
278
  ## 🔄 Ingesta Asíncrona en Lotes (`AsyncIngester`)
253
279
 
254
- Para telemetría masiva de flotas de vehículos o dispositivos IoT, utiliza la cola en memoria con auto-flush:
280
+ Encola coordenadas en memoria y las despacha periódicamente (una petición `sendLocation` por coordenada):
255
281
 
256
282
  ```ts
257
- import GeoEngine, { AsyncIngester } from 'geo-engine-node';
258
-
259
- const client = new GeoEngine('geo_live_123456');
283
+ import GeoEngine from 'geo-engine-node';
260
284
 
261
- // Cola: buffer 5000 pings, flush cada 100 items o cada 500ms
285
+ const apiKey = process.env.GEOENGINE_API_KEY;
286
+ if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
287
+ const client = new GeoEngine(apiKey);
262
288
  const ingester = client.createAsyncIngester(5000, 100, 500);
263
289
 
264
290
  const ok = ingester.enqueue({
@@ -268,11 +294,6 @@ const ok = ingester.enqueue({
268
294
  timestamp: Date.now(),
269
295
  });
270
296
 
271
- if (!ok) {
272
- console.warn('Buffer lleno o ingester detenido');
273
- }
274
-
275
- // Al apagar el servicio, drena todos los elementos pendientes:
276
297
  await ingester.stop();
277
298
  client.close();
278
299
  ```
@@ -281,19 +302,18 @@ client.close();
281
302
 
282
303
  ## 🔧 Configuración Avanzada
283
304
 
284
- Puedes configurar el cliente mediante el objeto de opciones:
285
-
286
305
  ```ts
287
- const client = new GeoEngine('geo_live_123456', {
288
- environment: 'live', // 'live' | 'test'
306
+ const apiKey = process.env.GEOENGINE_API_KEY;
307
+ if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
308
+ const client = new GeoEngine(apiKey, {
309
+ environment: 'live', // 'live' | 'test' (cabecera X-Geo-Environment en rutas legadas)
289
310
  jwtToken: 'mi.jwt.token',
290
- timeout: 5000, // milisegundos
291
- maxRetries: 3, // reintentos con backoff exponencial ante 429/5xx
311
+ timeout: 5000, // milisegundos para rutas legadas
312
+ identityTimeoutMs: 500, // plazo total para client.identity.evaluate en ms
313
+ maxRetries: 2, // reintentos en rutas legadas
292
314
  managementUrl: 'https://management.geoengine.dev',
293
315
  ingestUrl: 'https://ingest.geoengine.dev',
294
316
  apiServiceUrl: 'https://api.geoengine.dev',
295
- // O para pruebas locales/mock:
296
- // baseUrl: 'http://localhost:8080',
297
317
  });
298
318
  ```
299
319
 
@@ -301,32 +321,32 @@ const client = new GeoEngine('geo_live_123456', {
301
321
 
302
322
  | Opción | Tipo | Descripción | Default |
303
323
  | :--- | :--- | :--- | :--- |
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'` |
324
+ | `apiKey` | `string` | Clave secreta de autenticación (almacenada en privado; no expuesta en `client.options`) | (requerido) |
325
+ | `environment` | `string` | Target (`'live'` o `'test'`) en cabecera `X-Geo-Environment` de rutas legadas | `'live'` |
326
+ | `jwtToken` | `string` | Token Bearer opcional en rutas legadas | `undefined` |
327
+ | `apiServiceUrl` | `string` | URL del api-service (Spatial, Users, GeoIdentity y `/v1/evaluate`) | `'https://api.geoengine.dev'` |
308
328
  | `ingestUrl` | `string` | URL del servicio de ingestión de telemetría | `'https://ingest.geoengine.dev'` |
309
329
  | `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` |
330
+ | `baseUrl` | `string` | Sobrescribe ingest, management y apiService juntas. Debe ser `https` (`http` solo para `localhost`, `127.0.0.1` o `::1`); si no, el constructor lanza `ValidationError`. Nunca se siguen redirecciones. | `undefined` |
331
+ | `timeout` | `number` | Tiempo límite en ms para rutas legadas (`AbortController`) | `10000` |
332
+ | `identityTimeoutMs` | `number` | Plazo total en ms para `client.identity.evaluate` (incluye reintento) | `500` |
333
+ | `maxRetries` | `number` | Reintentos exponenciales (`429`, `5xx`, red) en rutas legadas (solo `GET` en `users`/`geoIdentity`) | `2` |
313
334
  | `batchSize` | `number` | Tamaño de lote para `AsyncIngester` | `100` |
314
335
  | `flushInterval` | `number` | Intervalo de vaciado de `AsyncIngester` en ms | `500` |
315
336
  | `bufferSize` | `number` | Capacidad máxima de la cola de `AsyncIngester` | `5000` |
316
337
 
338
+ > **Autenticación legada vs `/v1/evaluate`:** Las rutas legadas envían `X-API-Key`, `X-Geo-Environment`, `X-Request-Time` y `X-Signature` (HMAC-SHA256 del timestamp usando `apiKey`, más `Authorization: Bearer` si se configura `jwtToken`). `/v1/evaluate` envía **únicamente** `Authorization: Bearer <apiKey>` y `X-Request-Id`.
339
+
317
340
  ---
318
341
 
319
342
  ## 🛡️ Jerarquía de Errores Tipados
320
343
 
321
- El SDK mapea todos los códigos de estado y respuestas en una jerarquía clara de clases de error:
344
+ > `err.code` es el contrato estable entre formatos: los builds ESM y CJS incluyen cada uno sus propias clases de error (por eso `instanceof` no funciona entre formatos), pero los valores de `code` son idénticos.
322
345
 
323
346
  ```ts
324
347
  import {
325
348
  GeoEngineError,
326
349
  ValidationError,
327
- InvalidLatitudeError,
328
- InvalidLongitudeError,
329
- DeviceIDRequiredError,
330
350
  GeofenceNotFoundError,
331
351
  QuotaExceededError,
332
352
  AuthenticationError,
@@ -341,47 +361,33 @@ try {
341
361
  if (error instanceof GeofenceNotFoundError) {
342
362
  // 204 No Content o 404 Not Found
343
363
  } else if (error instanceof QuotaExceededError) {
344
- // 402 Payment Required o 429
364
+ // 402 Payment Required o código QUOTA_EXCEEDED
345
365
  } else if (error instanceof AuthenticationError) {
346
- // 401 Unauthorized o MISSING_API_KEY
366
+ // 401 Unauthorized, MISSING_API_KEY o MISSING_ORGANIZATION
367
+ } else if (error instanceof ForbiddenError) {
368
+ // 403 Forbidden
347
369
  } else if (error instanceof TimeoutError) {
348
370
  // Tiempo de espera agotado
349
371
  } else if (error instanceof ValidationError) {
350
- // Coordenada fuera de rango [-90,90] o parámetro inválido
372
+ // Validación local fallida (coordenadas fuera de rango o ID faltante)
351
373
  }
352
374
  }
353
375
  ```
354
376
 
355
- Los módulos Users y GeoIdentity lanzan `APIServiceError` (con `statusCode`, `code` y `apiMessage`) o una de sus subclases:
377
+ Los módulos Users y CRUD de GeoIdentity lanzan subclases de `APIServiceError` (`UserNotFoundError`, `RuleNotFoundError`, `UserAlreadyExistsError`, `InvitationPendingError`, `LastAdminError`, `LastSubjectError`) y solo reintentan peticiones `GET`.
356
378
 
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.
379
+ GeoIdentity `/v1/evaluate` lanza `IdentityTransientError` (red, timeout, `5xx`, `429`) o `IdentityIntegrationError` (`400`, `401`, `403` incluido el `403` de borde, `404`, `422`, payload o configuración inválida) y exporta `isTransient(err)`.
369
380
 
370
381
  ---
371
382
 
372
383
  ## 🧪 Pruebas y Compilación
373
384
 
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:
385
+ Todas las pruebas se ejecutan localmente contra servidores `node:http` simulados (sin red real):
381
386
 
382
387
  ```bash
383
- npm run build
384
388
  npm run typecheck
389
+ npm run build
390
+ npm test
385
391
  ```
386
392
 
387
393
  ---