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/dist/index.js CHANGED
@@ -1,301 +1,344 @@
1
- // src/errors.ts
2
- var GeoEngineError = class extends Error {
3
- constructor(message) {
4
- super(message);
5
- this.name = "GeoEngineError";
6
- Object.setPrototypeOf(this, new.target.prototype);
7
- }
8
- };
9
- var ClientClosedError = class extends GeoEngineError {
10
- constructor(message = "geoengine: client is closed") {
11
- super(message);
12
- this.name = "ClientClosedError";
13
- }
14
- };
15
- var ValidationError = class extends GeoEngineError {
16
- constructor(message) {
17
- super(message);
18
- this.name = "ValidationError";
19
- }
20
- };
21
- var DeviceIDRequiredError = class extends ValidationError {
22
- constructor(message = "geoengine: device_id is required") {
23
- super(message);
24
- this.name = "DeviceIDRequiredError";
25
- }
26
- };
27
- var GeofenceIDRequiredError = class extends ValidationError {
28
- constructor(message = "geoengine: geofence_id is required") {
29
- super(message);
30
- this.name = "GeofenceIDRequiredError";
31
- }
32
- };
33
- var InvalidLatitudeError = class extends ValidationError {
34
- constructor(message = "geoengine: latitude must be between -90 and 90 degrees") {
35
- super(message);
36
- this.name = "InvalidLatitudeError";
37
- }
1
+ import {
2
+ APIError,
3
+ APIServiceError,
4
+ AuthenticationError,
5
+ ClientClosedError,
6
+ DeviceIDRequiredError,
7
+ EmailRequiredError,
8
+ ForbiddenError,
9
+ GeoEngineError,
10
+ GeofenceIDRequiredError,
11
+ GeofenceNotFoundError,
12
+ HttpClient,
13
+ IdentityIntegrationError,
14
+ IdentityService,
15
+ IdentityTransientError,
16
+ InvalidCoordinatesError,
17
+ InvalidLatitudeError,
18
+ InvalidLongitudeError,
19
+ InvitationPendingError,
20
+ LastAdminError,
21
+ LastSubjectError,
22
+ QuotaExceededError,
23
+ RoleRequiredError,
24
+ RuleIDRequiredError,
25
+ RuleNameRequiredError,
26
+ RuleNotFoundError,
27
+ SpatialAPIError,
28
+ TimeoutError,
29
+ UserAlreadyExistsError,
30
+ UserIDRequiredError,
31
+ UserNotFoundError,
32
+ ValidationError,
33
+ generateHMACSignature,
34
+ isTransient
35
+ } from "./chunk-425YTEGY.js";
36
+
37
+ // src/users.ts
38
+ var Roles = {
39
+ Admin: "roles/geoengine.admin",
40
+ Dispatcher: "roles/geoengine.dispatcher",
41
+ Billing: "roles/geoengine.billing",
42
+ Viewer: "roles/geoengine.viewer",
43
+ Device: "roles/geoengine.device"
38
44
  };
39
- var InvalidLongitudeError = class extends ValidationError {
40
- constructor(message = "geoengine: longitude must be between -180 and 180 degrees") {
41
- super(message);
42
- this.name = "InvalidLongitudeError";
43
- }
45
+ var UserStatus = {
46
+ Active: "active",
47
+ Pending: "pending",
48
+ Revoked: "revoked"
44
49
  };
45
- var InvalidCoordinatesError = class extends ValidationError {
46
- constructor(message = "geoengine: at least 3 coordinate pairs are required for a polygon") {
47
- super(message);
48
- this.name = "InvalidCoordinatesError";
50
+ function toUser(raw) {
51
+ return {
52
+ id: raw.id,
53
+ email: raw.email,
54
+ name: raw.name,
55
+ role: raw.role,
56
+ status: raw.status,
57
+ permissions: raw.permissions ?? [],
58
+ createdAt: raw.created_at,
59
+ lastLoginAt: raw.last_login_at
60
+ };
61
+ }
62
+ function isBlank(value) {
63
+ return typeof value !== "string" || value.trim() === "";
64
+ }
65
+ function userPath(userId, suffix = "") {
66
+ if (isBlank(userId)) {
67
+ throw new UserIDRequiredError();
49
68
  }
50
- };
51
- var APIError = class extends GeoEngineError {
52
- statusCode;
53
- constructor(statusCode, message) {
54
- super(`geoengine: API error (status ${statusCode}): ${message}`);
55
- this.name = "APIError";
56
- this.statusCode = statusCode;
69
+ return `/api/users/${encodeURIComponent(userId.trim())}${suffix}`;
70
+ }
71
+ async function apiServiceRequest(http, isClosed, method, path, body) {
72
+ if (isClosed()) {
73
+ throw new ClientClosedError();
74
+ }
75
+ return http.request({
76
+ endpoint: `${http.options.apiServiceUrl.replace(/\/+$/, "")}${path}`,
77
+ method,
78
+ body,
79
+ isApiService: true
80
+ });
81
+ }
82
+ var UsersService = class {
83
+ constructor(http, isClosed = () => false) {
84
+ this.http = http;
85
+ this.isClosed = isClosed;
57
86
  }
58
- };
59
- var SpatialAPIError = class extends APIError {
60
- code;
61
- statusText;
62
- details;
63
- constructor(statusCode, code, message, statusText, details = []) {
64
- const formattedMessage = code ? `geoengine: spatial API error (status ${statusCode}, code ${code}): ${message}` : `geoengine: spatial API error (status ${statusCode}): ${message}`;
65
- super(statusCode, formattedMessage);
66
- this.name = "SpatialAPIError";
67
- this.code = code;
68
- this.statusText = statusText;
69
- this.details = details;
87
+ http;
88
+ isClosed;
89
+ /** Returns the members of the organization. */
90
+ async list() {
91
+ const raw = await this.send("GET", "/api/users");
92
+ return (raw ?? []).map(toUser);
93
+ }
94
+ /** Returns a single member of the organization. */
95
+ async get(userId) {
96
+ return toUser(await this.send("GET", userPath(userId)));
97
+ }
98
+ /** Returns the roles available to the organization and their permissions. */
99
+ async listRoles() {
100
+ const raw = await this.send(
101
+ "GET",
102
+ "/api/users/roles"
103
+ );
104
+ return (raw ?? []).map((r) => ({ id: r.id, permissions: r.permissions ?? [] }));
70
105
  }
71
106
  /**
72
- * Returns true if the error indicates the geofence or resource was not found.
107
+ * Creates an invitation and emails it to the recipient.
108
+ * Throws InvitationPendingError if a pending invitation already exists for the email,
109
+ * and UserAlreadyExistsError if the email already belongs to the organization.
73
110
  */
74
- isNotFound() {
75
- return this.statusCode === 204 || this.statusCode === 404 || this.code === "NOT_FOUND";
111
+ async invite(req) {
112
+ if (isBlank(req?.email)) {
113
+ throw new EmailRequiredError();
114
+ }
115
+ if (isBlank(req.role)) {
116
+ throw new RoleRequiredError();
117
+ }
118
+ const raw = await this.send("POST", "/api/users/invite", {
119
+ email: req.email,
120
+ role: req.role,
121
+ inviter_name: req.inviterName || void 0,
122
+ lang: req.lang || void 0
123
+ });
124
+ return {
125
+ email: raw.email,
126
+ role: raw.role,
127
+ status: raw.status,
128
+ inviteUrl: raw.invite_url,
129
+ expiresAt: raw.expires_at
130
+ };
76
131
  }
77
132
  /**
78
- * Returns true if the error indicates quota limit was hit.
133
+ * Changes the role of a member. The new permissions apply on the user's next sign-in.
134
+ * Throws LastAdminError if the change would leave the organization without an admin.
79
135
  */
80
- isQuotaExceeded() {
81
- return this.statusCode === 402 || this.code === "QUOTA_EXCEEDED";
136
+ async updateRole(userId, role) {
137
+ if (isBlank(role)) {
138
+ throw new RoleRequiredError();
139
+ }
140
+ return toUser(await this.send("PATCH", userPath(userId, "/role"), { role }));
82
141
  }
83
142
  /**
84
- * Returns true if authentication failed.
143
+ * Revokes a member's access to the organization.
144
+ * Throws LastAdminError if the member is the last admin.
85
145
  */
86
- isUnauthorized() {
87
- return this.statusCode === 401 || this.code === "UNAUTHORIZED" || this.code === "MISSING_API_KEY" || this.code === "MISSING_ORGANIZATION";
146
+ async remove(userId) {
147
+ await this.send("DELETE", userPath(userId));
88
148
  }
89
- /**
90
- * Returns true if access to the requested resource is forbidden.
91
- */
92
- isForbidden() {
93
- return this.statusCode === 403 || this.code === "FORBIDDEN";
149
+ send(method, path, body) {
150
+ return apiServiceRequest(this.http, this.isClosed, method, path, body);
94
151
  }
95
152
  };
96
- var GeofenceNotFoundError = class extends SpatialAPIError {
97
- constructor(message = "geofence not found", statusCode = 204, details = []) {
98
- super(statusCode, "NOT_FOUND", message, "Not Found", details);
99
- this.name = "GeofenceNotFoundError";
153
+
154
+ // src/validation.ts
155
+ function validateCoordinates(lat, lng) {
156
+ if (typeof lat !== "number" || Number.isNaN(lat) || lat < -90 || lat > 90) {
157
+ throw new InvalidLatitudeError();
100
158
  }
101
- };
102
- var QuotaExceededError = class extends SpatialAPIError {
103
- constructor(message = "request quota exceeded", statusCode = 402, details = []) {
104
- super(statusCode, "QUOTA_EXCEEDED", message, "Payment Required", details);
105
- this.name = "QuotaExceededError";
159
+ if (typeof lng !== "number" || Number.isNaN(lng) || lng < -180 || lng > 180) {
160
+ throw new InvalidLongitudeError();
106
161
  }
107
- };
108
- var AuthenticationError = class extends SpatialAPIError {
109
- constructor(message = "unauthorized API request", statusCode = 401, details = []) {
110
- super(statusCode, "UNAUTHORIZED", message, "Unauthorized", details);
111
- this.name = "AuthenticationError";
162
+ }
163
+ function validateDeviceId(deviceId) {
164
+ if (!deviceId || typeof deviceId !== "string" || deviceId.trim() === "") {
165
+ throw new DeviceIDRequiredError();
112
166
  }
113
- };
114
- var ForbiddenError = class extends SpatialAPIError {
115
- constructor(message = "access forbidden", statusCode = 403, details = []) {
116
- super(statusCode, "FORBIDDEN", message, "Forbidden", details);
117
- this.name = "ForbiddenError";
167
+ return deviceId.trim();
168
+ }
169
+ function validateGeofenceId(geofenceId) {
170
+ if (!geofenceId || typeof geofenceId !== "string" || geofenceId.trim() === "") {
171
+ throw new GeofenceIDRequiredError();
118
172
  }
119
- };
120
- var TimeoutError = class extends GeoEngineError {
121
- constructor(timeoutMs) {
122
- super(`geoengine: request exceeded the timeout limit of ${timeoutMs}ms`);
123
- this.name = "TimeoutError";
173
+ return geofenceId.trim();
174
+ }
175
+ function validateAndNormalizePolygon(coordinates) {
176
+ if (!Array.isArray(coordinates) || coordinates.length < 3) {
177
+ throw new InvalidCoordinatesError();
124
178
  }
125
- };
126
-
127
- // src/crypto.ts
128
- import { createHmac } from "crypto";
129
- function generateHMACSignature(key, timestamp) {
130
- if (!key) {
131
- return "";
179
+ const polygon = [];
180
+ for (const p of coordinates) {
181
+ if (!Array.isArray(p) || p.length !== 2) {
182
+ throw new ValidationError(
183
+ `geoengine: invalid coordinate format: ${JSON.stringify(p)} (expected [lat, lng])`
184
+ );
185
+ }
186
+ const lat = p[0];
187
+ const lng = p[1];
188
+ validateCoordinates(lat, lng);
189
+ polygon.push([lng, lat]);
132
190
  }
133
- return createHmac("sha256", key).update(timestamp.toString()).digest("hex");
191
+ const first = polygon[0];
192
+ const last = polygon[polygon.length - 1];
193
+ if (first[0] !== last[0] || first[1] !== last[1]) {
194
+ polygon.push([first[0], first[1]]);
195
+ }
196
+ return polygon;
134
197
  }
135
198
 
136
- // src/http.ts
137
- var USER_AGENT = "GeoEngineNodeSDK/2.0.0";
138
- function parseHttpError(statusCode, bodyText, isSpatial = false) {
139
- let parsedErrorContainer = null;
140
- try {
141
- parsedErrorContainer = JSON.parse(bodyText);
142
- } catch {
143
- }
144
- const container = parsedErrorContainer?.error;
145
- let code = container?.status ?? "";
146
- let message = container?.message ?? parsedErrorContainer?.message ?? bodyText.trim();
147
- const details = container?.details ?? [];
148
- if (container?.details && container.details.length > 0) {
149
- for (const detail of container.details) {
150
- if (detail.reason) {
151
- code = detail.reason;
152
- break;
153
- }
154
- }
199
+ // src/geoidentity.ts
200
+ var RuleActions = {
201
+ Allow: "ALLOW",
202
+ Block: "BLOCK",
203
+ Challenge: "CHALLENGE"
204
+ };
205
+ var SubjectTypes = {
206
+ User: "USER",
207
+ Role: "ROLE",
208
+ Device: "DEVICE",
209
+ All: "ALL"
210
+ };
211
+ function toRule(raw) {
212
+ return {
213
+ id: raw.id,
214
+ orgId: raw.org_id,
215
+ name: raw.name,
216
+ description: raw.description,
217
+ priority: raw.priority ?? 0,
218
+ action: raw.action,
219
+ isActive: Boolean(raw.is_active),
220
+ whiteIpList: raw.white_ip_list ?? [],
221
+ blackIpList: raw.black_ip_list ?? [],
222
+ blockDatacenter: Boolean(raw.block_datacenter),
223
+ blockTor: Boolean(raw.block_tor),
224
+ riskAccepted: raw.risk_accepted ?? 0,
225
+ geoLimit: raw.geo_limit,
226
+ assignedSubjects: (raw.assigned_subjects ?? []).map((s) => ({
227
+ subjectType: s.subject_type,
228
+ subjectId: s.subject_id
229
+ })),
230
+ subjectsCount: raw.subjects_count ?? 0,
231
+ createdAt: raw.created_at,
232
+ updatedAt: raw.updated_at
233
+ };
234
+ }
235
+ function toWire(req) {
236
+ return {
237
+ name: req.name,
238
+ description: req.description,
239
+ priority: req.priority,
240
+ action: req.action,
241
+ is_active: req.isActive,
242
+ white_ip_list: req.whiteIpList,
243
+ black_ip_list: req.blackIpList,
244
+ block_datacenter: req.blockDatacenter,
245
+ block_tor: req.blockTor,
246
+ risk_accepted: req.riskAccepted,
247
+ geo_limit: req.geoLimit,
248
+ assigned_subjects: req.assignedSubjects?.map((s) => ({
249
+ subject_type: s.subjectType,
250
+ subject_id: s.subjectId
251
+ }))
252
+ };
253
+ }
254
+ var RULES_PATH = "/api/users/geoidentity/rules";
255
+ function rulePath(ruleId, suffix = "") {
256
+ if (typeof ruleId !== "string" || ruleId.trim() === "") {
257
+ throw new RuleIDRequiredError();
155
258
  }
156
- if (!code) {
157
- switch (statusCode) {
158
- case 204:
159
- case 404:
160
- code = "NOT_FOUND";
161
- break;
162
- case 402:
163
- code = "QUOTA_EXCEEDED";
164
- break;
165
- case 401:
166
- code = "UNAUTHORIZED";
167
- break;
168
- case 403:
169
- code = "FORBIDDEN";
170
- break;
171
- default:
172
- code = "";
259
+ return `${RULES_PATH}/${encodeURIComponent(ruleId.trim())}${suffix}`;
260
+ }
261
+ function requireUserId(userId) {
262
+ if (typeof userId !== "string" || userId.trim() === "") {
263
+ throw new UserIDRequiredError();
264
+ }
265
+ return userId.trim();
266
+ }
267
+ var GeoIdentityService = class {
268
+ constructor(http, isClosed = () => false) {
269
+ this.http = http;
270
+ this.isClosed = isClosed;
271
+ }
272
+ http;
273
+ isClosed;
274
+ /** Creates a GeoIdentity rule. */
275
+ async createRule(req) {
276
+ if (typeof req?.name !== "string" || req.name.trim() === "") {
277
+ throw new RuleNameRequiredError();
173
278
  }
279
+ return toRule(await this.send("POST", RULES_PATH, toWire(req)));
174
280
  }
175
- if (!message) {
176
- message = `HTTP ${statusCode}`;
281
+ /**
282
+ * Returns the organization's rules ordered by priority.
283
+ * Use getRule to load a rule's assigned subjects.
284
+ */
285
+ async listRules(opts = {}) {
286
+ const query = typeof opts.isActive === "boolean" ? `?is_active=${opts.isActive}` : "";
287
+ const raw = await this.send("GET", RULES_PATH + query);
288
+ return (raw ?? []).map(toRule);
177
289
  }
178
- if (statusCode === 204 || statusCode === 404 || code === "NOT_FOUND") {
179
- return new GeofenceNotFoundError(message, statusCode, details);
290
+ /** Returns a rule including its assigned subjects. */
291
+ async getRule(ruleId) {
292
+ return toRule(await this.send("GET", rulePath(ruleId)));
180
293
  }
181
- if (statusCode === 402 || code === "QUOTA_EXCEEDED") {
182
- return new QuotaExceededError(message, statusCode, details);
294
+ /** Partially updates a rule. */
295
+ async updateRule(ruleId, req) {
296
+ return toRule(await this.send("PATCH", rulePath(ruleId), toWire(req ?? {})));
183
297
  }
184
- if (statusCode === 401 || code === "UNAUTHORIZED" || code === "MISSING_API_KEY" || code === "MISSING_ORGANIZATION") {
185
- return new AuthenticationError(message, statusCode, details);
298
+ /** Deletes a rule and all of its assignments. */
299
+ async deleteRule(ruleId) {
300
+ await this.send("DELETE", rulePath(ruleId));
186
301
  }
187
- if (statusCode === 403 || code === "FORBIDDEN") {
188
- return new ForbiddenError(message, statusCode, details);
302
+ /** Applies the rule to a member of the organization. Assigning twice is a no-op. */
303
+ async assignToUser(ruleId, userId) {
304
+ return this.changeAssignment("POST", ruleId, { scope: "user", user_id: requireUserId(userId) });
189
305
  }
190
- if (isSpatial) {
191
- return new SpatialAPIError(statusCode, code, message, void 0, details);
306
+ /** Applies the rule to every member of the organization. */
307
+ async assignToOrganization(ruleId) {
308
+ return this.changeAssignment("POST", ruleId, { scope: "organization" });
192
309
  }
193
- return new APIError(statusCode, message);
194
- }
195
- var HttpClient = class {
196
- config;
197
- constructor(options = {}) {
198
- const defaultManagement = "https://management.geoengine.dev";
199
- const defaultIngest = "https://ingest.geoengine.dev";
200
- const defaultApiService = "https://api.geoengine.dev";
201
- this.config = {
202
- apiKey: options.apiKey ?? "",
203
- jwtToken: options.jwtToken,
204
- environment: options.environment ?? "live",
205
- managementUrl: options.baseUrl ?? options.managementUrl ?? defaultManagement,
206
- ingestUrl: options.baseUrl ?? options.ingestUrl ?? defaultIngest,
207
- apiServiceUrl: options.baseUrl ?? options.apiServiceUrl ?? defaultApiService,
208
- timeout: options.timeout ?? 1e4,
209
- maxRetries: options.maxRetries ?? 2,
210
- batchSize: options.batchSize ?? 100,
211
- flushInterval: options.flushInterval ?? 500,
212
- bufferSize: options.bufferSize ?? 5e3,
213
- fetch: options.fetch ?? globalThis.fetch
214
- };
310
+ /**
311
+ * Removes a user assignment from the rule.
312
+ * Throws LastSubjectError if it is the rule's only subject; deactivate or delete the rule instead.
313
+ */
314
+ async unassignFromUser(ruleId, userId) {
315
+ return this.changeAssignment("DELETE", ruleId, { scope: "user", user_id: requireUserId(userId) });
215
316
  }
216
- get options() {
217
- return this.config;
218
- }
219
- /**
220
- * Executes an HTTP request with timeout, authentication headers and exponential backoff retry.
221
- */
222
- async request(opts) {
223
- const method = opts.method ?? "POST";
224
- const timeoutMs = opts.timeout ?? this.config.timeout;
225
- const maxRetries = this.config.maxRetries;
226
- let attempt = 0;
227
- while (true) {
228
- attempt++;
229
- const controller = new globalThis.AbortController();
230
- const timeoutId = globalThis.setTimeout(() => controller.abort(), timeoutMs);
231
- const now = Date.now();
232
- const headers = {
233
- "Content-Type": "application/json",
234
- "X-API-Key": this.config.apiKey,
235
- "X-Geo-Environment": this.config.environment,
236
- "X-Request-Time": now.toString(),
237
- "X-Signature": generateHMACSignature(this.config.apiKey, now),
238
- "User-Agent": USER_AGENT
239
- };
240
- if (this.config.jwtToken) {
241
- headers["Authorization"] = `Bearer ${this.config.jwtToken}`;
242
- }
243
- try {
244
- const response = await this.config.fetch(opts.endpoint, {
245
- method,
246
- headers,
247
- body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0,
248
- signal: controller.signal
249
- });
250
- globalThis.clearTimeout(timeoutId);
251
- if (response.status === 204) {
252
- if (opts.isSpatial) {
253
- throw new GeofenceNotFoundError("geofence not found", 204);
254
- }
255
- return null;
256
- }
257
- if ((response.status === 429 || response.status >= 500) && attempt <= maxRetries) {
258
- const delay = Math.min(100 * Math.pow(2, attempt) + Math.random() * 50, 2e3);
259
- await new Promise(
260
- (resolve) => globalThis.setTimeout(() => resolve(), delay)
261
- );
262
- continue;
263
- }
264
- const responseText = await response.text();
265
- if (!response.ok) {
266
- throw parseHttpError(response.status, responseText, opts.isSpatial);
267
- }
268
- if (!responseText || responseText.trim() === "") {
269
- return null;
270
- }
271
- const json = JSON.parse(responseText);
272
- if (opts.isSpatial && typeof json === "object" && json !== null && "success" in json) {
273
- if (!json.success) {
274
- throw parseHttpError(response.status, responseText, true);
275
- }
276
- return json.data;
277
- }
278
- return json;
279
- } catch (err) {
280
- globalThis.clearTimeout(timeoutId);
281
- if (err instanceof Error && err.name === "AbortError") {
282
- throw new TimeoutError(timeoutMs);
283
- }
284
- if (err instanceof APIError) {
285
- throw err;
286
- }
287
- if (attempt <= maxRetries) {
288
- const delay = Math.min(100 * Math.pow(2, attempt) + Math.random() * 50, 2e3);
289
- await new Promise(
290
- (resolve) => globalThis.setTimeout(() => resolve(), delay)
291
- );
292
- continue;
293
- }
294
- throw err;
295
- }
296
- }
317
+ /**
318
+ * Removes the organization-wide assignment from the rule.
319
+ * Throws LastSubjectError if it is the rule's only subject.
320
+ */
321
+ async unassignFromOrganization(ruleId) {
322
+ return this.changeAssignment("DELETE", ruleId, { scope: "organization" });
323
+ }
324
+ /**
325
+ * Returns the rules that apply to a user: assigned directly, through the user's role,
326
+ * or to the whole organization.
327
+ */
328
+ async listUserRules(userId) {
329
+ const raw = await this.send("GET", userPath(userId, "/geoidentity/rules"));
330
+ return (raw ?? []).map(toRule);
331
+ }
332
+ async changeAssignment(method, ruleId, payload) {
333
+ return toRule(await this.send(method, rulePath(ruleId, "/assignments"), payload));
334
+ }
335
+ send(method, path, body) {
336
+ return apiServiceRequest(this.http, this.isClosed, method, path, body);
297
337
  }
298
338
  };
339
+ function polygonFromLatLng(coordinates) {
340
+ return { type: "Polygon", coordinates: [validateAndNormalizePolygon(coordinates)] };
341
+ }
299
342
 
300
343
  // src/ingester.ts
301
344
  import { clearInterval, setInterval } from "timers";
@@ -500,51 +543,6 @@ var SpatialGeneralResult = class {
500
543
  }
501
544
  };
502
545
 
503
- // src/validation.ts
504
- function validateCoordinates(lat, lng) {
505
- if (typeof lat !== "number" || Number.isNaN(lat) || lat < -90 || lat > 90) {
506
- throw new InvalidLatitudeError();
507
- }
508
- if (typeof lng !== "number" || Number.isNaN(lng) || lng < -180 || lng > 180) {
509
- throw new InvalidLongitudeError();
510
- }
511
- }
512
- function validateDeviceId(deviceId) {
513
- if (!deviceId || typeof deviceId !== "string" || deviceId.trim() === "") {
514
- throw new DeviceIDRequiredError();
515
- }
516
- return deviceId.trim();
517
- }
518
- function validateGeofenceId(geofenceId) {
519
- if (!geofenceId || typeof geofenceId !== "string" || geofenceId.trim() === "") {
520
- throw new GeofenceIDRequiredError();
521
- }
522
- return geofenceId.trim();
523
- }
524
- function validateAndNormalizePolygon(coordinates) {
525
- if (!Array.isArray(coordinates) || coordinates.length < 3) {
526
- throw new InvalidCoordinatesError();
527
- }
528
- const polygon = [];
529
- for (const p of coordinates) {
530
- if (!Array.isArray(p) || p.length !== 2) {
531
- throw new ValidationError(
532
- `geoengine: invalid coordinate format: ${JSON.stringify(p)} (expected [lat, lng])`
533
- );
534
- }
535
- const lat = p[0];
536
- const lng = p[1];
537
- validateCoordinates(lat, lng);
538
- polygon.push([lng, lat]);
539
- }
540
- const first = polygon[0];
541
- const last = polygon[polygon.length - 1];
542
- if (first[0] !== last[0] || first[1] !== last[1]) {
543
- polygon.push([first[0], first[1]]);
544
- }
545
- return polygon;
546
- }
547
-
548
546
  // src/spatial.ts
549
547
  var SpatialService = class {
550
548
  constructor(http) {
@@ -720,6 +718,7 @@ var GeneralGeofenceCheck = class {
720
718
 
721
719
  // src/client.ts
722
720
  var GeoEngine = class {
721
+ #apiKey;
723
722
  http;
724
723
  isClosed = false;
725
724
  /**
@@ -730,6 +729,26 @@ var GeoEngine = class {
730
729
  * Alias for spatial (to maintain exact casing compatibility with Go client.Spatial).
731
730
  */
732
731
  Spatial;
732
+ /**
733
+ * Users manages organization members, roles and invitations.
734
+ */
735
+ users;
736
+ /**
737
+ * Alias for users (matches Go client.Users).
738
+ */
739
+ Users;
740
+ /**
741
+ * GeoIdentity manages GeoIdentity access rules for users and the organization.
742
+ */
743
+ geoIdentity;
744
+ /**
745
+ * Alias for geoIdentity (matches Go client.GeoIdentity).
746
+ */
747
+ GeoIdentity;
748
+ /**
749
+ * Server-only runtime decision client for `POST /v1/evaluate`.
750
+ */
751
+ identity;
733
752
  /**
734
753
  * Initializes a new GeoEngine client instance.
735
754
  *
@@ -748,16 +767,39 @@ var GeoEngine = class {
748
767
  if (!resolvedOptions.apiKey || resolvedOptions.apiKey.trim() === "") {
749
768
  throw new ValidationError("GeoEngine: API Key es requerida.");
750
769
  }
770
+ this.#apiKey = resolvedOptions.apiKey;
751
771
  this.http = new HttpClient(resolvedOptions);
752
772
  this.spatial = new SpatialService(this.http);
753
773
  this.Spatial = this.spatial;
774
+ const isClosed = () => this.isClosed;
775
+ this.users = new UsersService(this.http, isClosed);
776
+ this.Users = this.users;
777
+ this.geoIdentity = new GeoIdentityService(this.http, isClosed);
778
+ this.GeoIdentity = this.geoIdentity;
779
+ this.identity = new IdentityService({
780
+ getBaseUrl: () => this.http.options.apiServiceUrl,
781
+ getApiKey: () => this.#apiKey,
782
+ getTimeoutMs: () => this.http.options.identityTimeoutMs,
783
+ getFetch: () => this.http.options.fetch,
784
+ isClosed
785
+ });
754
786
  }
755
787
  /**
756
- * Current configuration options.
788
+ * Current configuration options (without secret apiKey).
757
789
  */
758
790
  get options() {
759
791
  return this.http.options;
760
792
  }
793
+ toJSON() {
794
+ return {
795
+ apiKey: "[REDACTED]",
796
+ closed: this.isClosed,
797
+ options: this.http.toJSON()
798
+ };
799
+ }
800
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
801
+ return this.toJSON();
802
+ }
761
803
  /**
762
804
  * Sends device coordinates over HTTP REST.
763
805
  * Equivalent to Go's Client.SendLocation.
@@ -884,34 +926,57 @@ var GeoEngine = class {
884
926
  };
885
927
 
886
928
  // src/index.ts
887
- var index_default = GeoEngine;
929
+ var src_default = GeoEngine;
888
930
  export {
889
931
  APIError,
932
+ APIServiceError,
890
933
  AsyncIngester,
891
934
  AuthenticationError,
892
935
  GeoEngine as Client,
893
936
  ClientClosedError,
894
937
  DeviceIDRequiredError,
938
+ EmailRequiredError,
895
939
  ForbiddenError,
896
940
  GeneralGeofenceCheck,
897
941
  GeoEngine,
898
942
  GeoEngineError,
943
+ GeoIdentityService,
899
944
  GeofenceIDRequiredError,
900
945
  GeofenceNotFoundError,
946
+ IdentityIntegrationError,
947
+ IdentityService,
948
+ IdentityTransientError,
901
949
  InvalidCoordinatesError,
902
950
  InvalidLatitudeError,
903
951
  InvalidLongitudeError,
952
+ InvitationPendingError,
953
+ LastAdminError,
954
+ LastSubjectError,
904
955
  QuotaExceededError,
956
+ RoleRequiredError,
957
+ Roles,
958
+ RuleActions,
959
+ RuleIDRequiredError,
960
+ RuleNameRequiredError,
961
+ RuleNotFoundError,
905
962
  SingleGeofenceCheck,
906
963
  SpatialAPIError,
907
964
  SpatialCheckBuilder,
908
965
  SpatialGeneralResult,
909
966
  SpatialService,
910
967
  SpatialValidationResult,
968
+ SubjectTypes,
911
969
  TimeoutError,
970
+ UserAlreadyExistsError,
971
+ UserIDRequiredError,
972
+ UserNotFoundError,
973
+ UserStatus,
974
+ UsersService,
912
975
  ValidationError,
913
- index_default as default,
976
+ src_default as default,
914
977
  generateHMACSignature,
978
+ isTransient,
979
+ polygonFromLatLng,
915
980
  validateAndNormalizePolygon,
916
981
  validateCoordinates,
917
982
  validateDeviceId,