geo-engine-node 2.0.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 +35 -0
- package/LICENSE +21 -0
- package/README.es.md +397 -0
- package/Readme.md +261 -100
- package/dist/chunk-425YTEGY.js +1231 -0
- package/dist/chunk-425YTEGY.js.map +1 -0
- package/dist/chunk-A6RGK4MA.cjs +1231 -0
- package/dist/chunk-A6RGK4MA.cjs.map +1 -0
- package/dist/errors-C5S_d0Ca.d.cts +473 -0
- package/dist/errors-C5S_d0Ca.d.ts +473 -0
- package/dist/identity.cjs +196 -0
- package/dist/identity.cjs.map +1 -0
- package/dist/identity.d.cts +10 -0
- package/dist/identity.d.ts +10 -0
- package/dist/identity.js +196 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.cjs +465 -455
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +275 -134
- package/dist/index.d.ts +275 -134
- package/dist/index.js +375 -310
- package/dist/index.js.map +1 -1
- package/package.json +38 -9
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
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
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
|
+
> *Read this in English: [Readme.md](./Readme.md)*
|
|
9
|
+
|
|
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`.
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## ✨ Características
|
|
18
|
+
|
|
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`.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## 🚀 Instalación
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
npm install geo-engine-node
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
O usando Yarn / PNPM / Bun:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pnpm add geo-engine-node
|
|
41
|
+
# o
|
|
42
|
+
bun add geo-engine-node
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## ⚡ Inicio Rápido
|
|
48
|
+
|
|
49
|
+
### TypeScript / ES Modules (Recomendado)
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import GeoEngine from 'geo-engine-node';
|
|
53
|
+
|
|
54
|
+
// Inicializa con tu clave secreta de API
|
|
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);
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
await client.sendLocation('truck-01', 19.4326, -99.1332);
|
|
61
|
+
console.log('✅ Coordenada enviada con éxito');
|
|
62
|
+
} catch (error) {
|
|
63
|
+
console.error('❌ Error al enviar ubicación:', error);
|
|
64
|
+
} finally {
|
|
65
|
+
client.close();
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### CommonJS
|
|
70
|
+
|
|
71
|
+
```js
|
|
72
|
+
const GeoEngine = require('geo-engine-node');
|
|
73
|
+
|
|
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);
|
|
77
|
+
|
|
78
|
+
client.sendLocation('scooter-09', 19.4326, -99.1332)
|
|
79
|
+
.then(() => console.log('Ubicación registrada'))
|
|
80
|
+
.catch((err) => console.error(err));
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
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);
|
|
99
|
+
|
|
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
|
+
```
|
|
123
|
+
|
|
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
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
import GeoEngine, { GeofenceNotFoundError } from 'geo-engine-node';
|
|
168
|
+
|
|
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);
|
|
172
|
+
|
|
173
|
+
try {
|
|
174
|
+
const res = await client.spatial.validatePoint('geofence_123', 19.4326, -99.1332);
|
|
175
|
+
|
|
176
|
+
if (res.isInside()) {
|
|
177
|
+
console.log(`✅ El dispositivo está dentro de ${res.geofenceName} (${res.geofenceId})`);
|
|
178
|
+
} else {
|
|
179
|
+
console.log('⚠️ El dispositivo está fuera de la geocerca');
|
|
180
|
+
}
|
|
181
|
+
} catch (err) {
|
|
182
|
+
if (err instanceof GeofenceNotFoundError) {
|
|
183
|
+
console.warn('La geocerca solicitada no existe');
|
|
184
|
+
} else {
|
|
185
|
+
throw err;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
### Validación General y Constructor Fluido
|
|
191
|
+
|
|
192
|
+
```ts
|
|
193
|
+
const generalRes = await client.spatial.validateGeneral(19.4326, -99.1332);
|
|
194
|
+
|
|
195
|
+
const fluentRes = await client.spatial
|
|
196
|
+
.check(19.4326, -99.1332)
|
|
197
|
+
.inGeofence('geofence_123')
|
|
198
|
+
.execute();
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
---
|
|
202
|
+
|
|
203
|
+
## 👥 Módulo Users
|
|
204
|
+
|
|
205
|
+
```ts
|
|
206
|
+
import GeoEngine, { Roles, InvitationPendingError, LastAdminError } from 'geo-engine-node';
|
|
207
|
+
|
|
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);
|
|
211
|
+
|
|
212
|
+
const users = await client.users.list();
|
|
213
|
+
const roles = await client.users.listRoles();
|
|
214
|
+
const user = await client.users.get('user_123');
|
|
215
|
+
|
|
216
|
+
try {
|
|
217
|
+
const inv = await client.users.invite({
|
|
218
|
+
email: 'ana@acme.com',
|
|
219
|
+
role: Roles.Viewer,
|
|
220
|
+
lang: 'es', // 'es' (default) | 'en' | 'pt'
|
|
221
|
+
});
|
|
222
|
+
console.log('Enlace de invitación:', inv.inviteUrl);
|
|
223
|
+
} catch (err) {
|
|
224
|
+
if (err instanceof InvitationPendingError) {
|
|
225
|
+
console.warn('Ya existe una invitación pendiente para este email');
|
|
226
|
+
} else {
|
|
227
|
+
throw err;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
---
|
|
233
|
+
|
|
234
|
+
## 🛡️ Gestión de Reglas GeoIdentity (`client.geoIdentity`)
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
import { polygonFromLatLng, RuleActions, SubjectTypes } from 'geo-engine-node';
|
|
238
|
+
|
|
239
|
+
const area = polygonFromLatLng([
|
|
240
|
+
[19.40, -99.20], [19.40, -99.10], [19.50, -99.10],
|
|
241
|
+
]);
|
|
242
|
+
|
|
243
|
+
const rule = await client.geoIdentity.createRule({
|
|
244
|
+
name: 'Solo CDMX',
|
|
245
|
+
action: RuleActions.Block,
|
|
246
|
+
blackIpList: ['203.0.113.0/24'],
|
|
247
|
+
blockTor: true,
|
|
248
|
+
geoLimit: area,
|
|
249
|
+
assignedSubjects: [{ subjectType: SubjectTypes.User, subjectId: 'user_123' }],
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
await client.geoIdentity.updateRule(rule.id, { isActive: false, geoLimit: null });
|
|
253
|
+
await client.geoIdentity.deleteRule(rule.id);
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
---
|
|
257
|
+
|
|
258
|
+
## 🚧 Creación de Geocercas (Polígonos PostGIS)
|
|
259
|
+
|
|
260
|
+
El SDK valida el formato `[latitud, longitud]`, convierte automáticamente a GeoJSON `[longitud, latitud]` y asegura el cierre del polígono:
|
|
261
|
+
|
|
262
|
+
```ts
|
|
263
|
+
const coordenadasZona: [number, number][] = [
|
|
264
|
+
[19.4326, -99.1332],
|
|
265
|
+
[19.4426, -99.1332],
|
|
266
|
+
[19.4426, -99.1232],
|
|
267
|
+
];
|
|
268
|
+
|
|
269
|
+
await client.createGeofence(
|
|
270
|
+
'Parque Logístico Norte',
|
|
271
|
+
coordenadasZona,
|
|
272
|
+
'https://mi-api.com/webhooks/geocercas'
|
|
273
|
+
);
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
---
|
|
277
|
+
|
|
278
|
+
## 🔄 Ingesta Asíncrona en Lotes (`AsyncIngester`)
|
|
279
|
+
|
|
280
|
+
Encola coordenadas en memoria y las despacha periódicamente (una petición `sendLocation` por coordenada):
|
|
281
|
+
|
|
282
|
+
```ts
|
|
283
|
+
import GeoEngine from 'geo-engine-node';
|
|
284
|
+
|
|
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);
|
|
288
|
+
const ingester = client.createAsyncIngester(5000, 100, 500);
|
|
289
|
+
|
|
290
|
+
const ok = ingester.enqueue({
|
|
291
|
+
deviceId: 'camion-45',
|
|
292
|
+
latitude: 19.4326,
|
|
293
|
+
longitude: -99.1332,
|
|
294
|
+
timestamp: Date.now(),
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
await ingester.stop();
|
|
298
|
+
client.close();
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
---
|
|
302
|
+
|
|
303
|
+
## 🔧 Configuración Avanzada
|
|
304
|
+
|
|
305
|
+
```ts
|
|
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)
|
|
310
|
+
jwtToken: 'mi.jwt.token',
|
|
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
|
|
314
|
+
managementUrl: 'https://management.geoengine.dev',
|
|
315
|
+
ingestUrl: 'https://ingest.geoengine.dev',
|
|
316
|
+
apiServiceUrl: 'https://api.geoengine.dev',
|
|
317
|
+
});
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
### Opciones Disponibles
|
|
321
|
+
|
|
322
|
+
| Opción | Tipo | Descripción | Default |
|
|
323
|
+
| :--- | :--- | :--- | :--- |
|
|
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'` |
|
|
328
|
+
| `ingestUrl` | `string` | URL del servicio de ingestión de telemetría | `'https://ingest.geoengine.dev'` |
|
|
329
|
+
| `managementUrl` | `string` | URL del servicio de control y geocercas | `'https://management.geoengine.dev'` |
|
|
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` |
|
|
334
|
+
| `batchSize` | `number` | Tamaño de lote para `AsyncIngester` | `100` |
|
|
335
|
+
| `flushInterval` | `number` | Intervalo de vaciado de `AsyncIngester` en ms | `500` |
|
|
336
|
+
| `bufferSize` | `number` | Capacidad máxima de la cola de `AsyncIngester` | `5000` |
|
|
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
|
+
|
|
340
|
+
---
|
|
341
|
+
|
|
342
|
+
## 🛡️ Jerarquía de Errores Tipados
|
|
343
|
+
|
|
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.
|
|
345
|
+
|
|
346
|
+
```ts
|
|
347
|
+
import {
|
|
348
|
+
GeoEngineError,
|
|
349
|
+
ValidationError,
|
|
350
|
+
GeofenceNotFoundError,
|
|
351
|
+
QuotaExceededError,
|
|
352
|
+
AuthenticationError,
|
|
353
|
+
ForbiddenError,
|
|
354
|
+
TimeoutError,
|
|
355
|
+
SpatialAPIError,
|
|
356
|
+
} from 'geo-engine-node';
|
|
357
|
+
|
|
358
|
+
try {
|
|
359
|
+
await client.spatial.validatePoint('geo-x', lat, lng);
|
|
360
|
+
} catch (error) {
|
|
361
|
+
if (error instanceof GeofenceNotFoundError) {
|
|
362
|
+
// 204 No Content o 404 Not Found
|
|
363
|
+
} else if (error instanceof QuotaExceededError) {
|
|
364
|
+
// 402 Payment Required o código QUOTA_EXCEEDED
|
|
365
|
+
} else if (error instanceof AuthenticationError) {
|
|
366
|
+
// 401 Unauthorized, MISSING_API_KEY o MISSING_ORGANIZATION
|
|
367
|
+
} else if (error instanceof ForbiddenError) {
|
|
368
|
+
// 403 Forbidden
|
|
369
|
+
} else if (error instanceof TimeoutError) {
|
|
370
|
+
// Tiempo de espera agotado
|
|
371
|
+
} else if (error instanceof ValidationError) {
|
|
372
|
+
// Validación local fallida (coordenadas fuera de rango o ID faltante)
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
Los módulos Users y CRUD de GeoIdentity lanzan subclases de `APIServiceError` (`UserNotFoundError`, `RuleNotFoundError`, `UserAlreadyExistsError`, `InvitationPendingError`, `LastAdminError`, `LastSubjectError`) y solo reintentan peticiones `GET`.
|
|
378
|
+
|
|
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)`.
|
|
380
|
+
|
|
381
|
+
---
|
|
382
|
+
|
|
383
|
+
## 🧪 Pruebas y Compilación
|
|
384
|
+
|
|
385
|
+
Todas las pruebas se ejecutan localmente contra servidores `node:http` simulados (sin red real):
|
|
386
|
+
|
|
387
|
+
```bash
|
|
388
|
+
npm run typecheck
|
|
389
|
+
npm run build
|
|
390
|
+
npm test
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
---
|
|
394
|
+
|
|
395
|
+
## 📄 Licencia
|
|
396
|
+
|
|
397
|
+
MIT © Geo-Engine Team
|