geo-engine-node 1.1.3 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1432 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ APIError: () => APIError,
24
+ APIServiceError: () => APIServiceError,
25
+ AsyncIngester: () => AsyncIngester,
26
+ AuthenticationError: () => AuthenticationError,
27
+ Client: () => GeoEngine,
28
+ ClientClosedError: () => ClientClosedError,
29
+ DeviceIDRequiredError: () => DeviceIDRequiredError,
30
+ EmailRequiredError: () => EmailRequiredError,
31
+ ForbiddenError: () => ForbiddenError,
32
+ GeneralGeofenceCheck: () => GeneralGeofenceCheck,
33
+ GeoEngine: () => GeoEngine,
34
+ GeoEngineError: () => GeoEngineError,
35
+ GeoIdentityService: () => GeoIdentityService,
36
+ GeofenceIDRequiredError: () => GeofenceIDRequiredError,
37
+ GeofenceNotFoundError: () => GeofenceNotFoundError,
38
+ InvalidCoordinatesError: () => InvalidCoordinatesError,
39
+ InvalidLatitudeError: () => InvalidLatitudeError,
40
+ InvalidLongitudeError: () => InvalidLongitudeError,
41
+ InvitationPendingError: () => InvitationPendingError,
42
+ LastAdminError: () => LastAdminError,
43
+ LastSubjectError: () => LastSubjectError,
44
+ QuotaExceededError: () => QuotaExceededError,
45
+ RoleRequiredError: () => RoleRequiredError,
46
+ Roles: () => Roles,
47
+ RuleActions: () => RuleActions,
48
+ RuleIDRequiredError: () => RuleIDRequiredError,
49
+ RuleNameRequiredError: () => RuleNameRequiredError,
50
+ RuleNotFoundError: () => RuleNotFoundError,
51
+ SingleGeofenceCheck: () => SingleGeofenceCheck,
52
+ SpatialAPIError: () => SpatialAPIError,
53
+ SpatialCheckBuilder: () => SpatialCheckBuilder,
54
+ SpatialGeneralResult: () => SpatialGeneralResult,
55
+ SpatialService: () => SpatialService,
56
+ SpatialValidationResult: () => SpatialValidationResult,
57
+ SubjectTypes: () => SubjectTypes,
58
+ TimeoutError: () => TimeoutError,
59
+ UserAlreadyExistsError: () => UserAlreadyExistsError,
60
+ UserIDRequiredError: () => UserIDRequiredError,
61
+ UserNotFoundError: () => UserNotFoundError,
62
+ UserStatus: () => UserStatus,
63
+ UsersService: () => UsersService,
64
+ ValidationError: () => ValidationError,
65
+ default: () => index_default,
66
+ generateHMACSignature: () => generateHMACSignature,
67
+ polygonFromLatLng: () => polygonFromLatLng,
68
+ validateAndNormalizePolygon: () => validateAndNormalizePolygon,
69
+ validateCoordinates: () => validateCoordinates,
70
+ validateDeviceId: () => validateDeviceId,
71
+ validateGeofenceId: () => validateGeofenceId
72
+ });
73
+ module.exports = __toCommonJS(index_exports);
74
+
75
+ // src/errors.ts
76
+ var GeoEngineError = class extends Error {
77
+ constructor(message) {
78
+ super(message);
79
+ this.name = "GeoEngineError";
80
+ Object.setPrototypeOf(this, new.target.prototype);
81
+ }
82
+ };
83
+ var ClientClosedError = class extends GeoEngineError {
84
+ constructor(message = "geoengine: client is closed") {
85
+ super(message);
86
+ this.name = "ClientClosedError";
87
+ }
88
+ };
89
+ var ValidationError = class extends GeoEngineError {
90
+ constructor(message) {
91
+ super(message);
92
+ this.name = "ValidationError";
93
+ }
94
+ };
95
+ var DeviceIDRequiredError = class extends ValidationError {
96
+ constructor(message = "geoengine: device_id is required") {
97
+ super(message);
98
+ this.name = "DeviceIDRequiredError";
99
+ }
100
+ };
101
+ var GeofenceIDRequiredError = class extends ValidationError {
102
+ constructor(message = "geoengine: geofence_id is required") {
103
+ super(message);
104
+ this.name = "GeofenceIDRequiredError";
105
+ }
106
+ };
107
+ var InvalidLatitudeError = class extends ValidationError {
108
+ constructor(message = "geoengine: latitude must be between -90 and 90 degrees") {
109
+ super(message);
110
+ this.name = "InvalidLatitudeError";
111
+ }
112
+ };
113
+ var InvalidLongitudeError = class extends ValidationError {
114
+ constructor(message = "geoengine: longitude must be between -180 and 180 degrees") {
115
+ super(message);
116
+ this.name = "InvalidLongitudeError";
117
+ }
118
+ };
119
+ var InvalidCoordinatesError = class extends ValidationError {
120
+ constructor(message = "geoengine: at least 3 coordinate pairs are required for a polygon") {
121
+ super(message);
122
+ this.name = "InvalidCoordinatesError";
123
+ }
124
+ };
125
+ var APIError = class extends GeoEngineError {
126
+ statusCode;
127
+ constructor(statusCode, message) {
128
+ super(`geoengine: API error (status ${statusCode}): ${message}`);
129
+ this.name = "APIError";
130
+ this.statusCode = statusCode;
131
+ }
132
+ };
133
+ var SpatialAPIError = class extends APIError {
134
+ code;
135
+ statusText;
136
+ details;
137
+ constructor(statusCode, code, message, statusText, details = []) {
138
+ const formattedMessage = code ? `geoengine: spatial API error (status ${statusCode}, code ${code}): ${message}` : `geoengine: spatial API error (status ${statusCode}): ${message}`;
139
+ super(statusCode, formattedMessage);
140
+ this.name = "SpatialAPIError";
141
+ this.code = code;
142
+ this.statusText = statusText;
143
+ this.details = details;
144
+ }
145
+ /**
146
+ * Returns true if the error indicates the geofence or resource was not found.
147
+ */
148
+ isNotFound() {
149
+ return this.statusCode === 204 || this.statusCode === 404 || this.code === "NOT_FOUND";
150
+ }
151
+ /**
152
+ * Returns true if the error indicates quota limit was hit.
153
+ */
154
+ isQuotaExceeded() {
155
+ return this.statusCode === 402 || this.code === "QUOTA_EXCEEDED";
156
+ }
157
+ /**
158
+ * Returns true if authentication failed.
159
+ */
160
+ isUnauthorized() {
161
+ return this.statusCode === 401 || this.code === "UNAUTHORIZED" || this.code === "MISSING_API_KEY" || this.code === "MISSING_ORGANIZATION";
162
+ }
163
+ /**
164
+ * Returns true if access to the requested resource is forbidden.
165
+ */
166
+ isForbidden() {
167
+ return this.statusCode === 403 || this.code === "FORBIDDEN";
168
+ }
169
+ };
170
+ var GeofenceNotFoundError = class extends SpatialAPIError {
171
+ constructor(message = "geofence not found", statusCode = 204, details = []) {
172
+ super(statusCode, "NOT_FOUND", message, "Not Found", details);
173
+ this.name = "GeofenceNotFoundError";
174
+ }
175
+ };
176
+ var QuotaExceededError = class extends SpatialAPIError {
177
+ constructor(message = "request quota exceeded", statusCode = 402, details = []) {
178
+ super(statusCode, "QUOTA_EXCEEDED", message, "Payment Required", details);
179
+ this.name = "QuotaExceededError";
180
+ }
181
+ };
182
+ var AuthenticationError = class extends SpatialAPIError {
183
+ constructor(message = "unauthorized API request", statusCode = 401, details = []) {
184
+ super(statusCode, "UNAUTHORIZED", message, "Unauthorized", details);
185
+ this.name = "AuthenticationError";
186
+ }
187
+ };
188
+ var ForbiddenError = class extends SpatialAPIError {
189
+ constructor(message = "access forbidden", statusCode = 403, details = []) {
190
+ super(statusCode, "FORBIDDEN", message, "Forbidden", details);
191
+ this.name = "ForbiddenError";
192
+ }
193
+ };
194
+ var TimeoutError = class extends GeoEngineError {
195
+ constructor(timeoutMs) {
196
+ super(`geoengine: request exceeded the timeout limit of ${timeoutMs}ms`);
197
+ this.name = "TimeoutError";
198
+ }
199
+ };
200
+ var UserIDRequiredError = class extends ValidationError {
201
+ constructor(message = "geoengine: user_id is required") {
202
+ super(message);
203
+ this.name = "UserIDRequiredError";
204
+ }
205
+ };
206
+ var RuleIDRequiredError = class extends ValidationError {
207
+ constructor(message = "geoengine: rule_id is required") {
208
+ super(message);
209
+ this.name = "RuleIDRequiredError";
210
+ }
211
+ };
212
+ var RuleNameRequiredError = class extends ValidationError {
213
+ constructor(message = "geoengine: rule name is required") {
214
+ super(message);
215
+ this.name = "RuleNameRequiredError";
216
+ }
217
+ };
218
+ var EmailRequiredError = class extends ValidationError {
219
+ constructor(message = "geoengine: email is required") {
220
+ super(message);
221
+ this.name = "EmailRequiredError";
222
+ }
223
+ };
224
+ var RoleRequiredError = class extends ValidationError {
225
+ constructor(message = "geoengine: role is required") {
226
+ super(message);
227
+ this.name = "RoleRequiredError";
228
+ }
229
+ };
230
+ var APIServiceError = class extends APIError {
231
+ /** Machine-readable reason, e.g. "USER_NOT_FOUND". Empty when the API sent none. */
232
+ code;
233
+ /** Message returned by the API, without the SDK prefix. */
234
+ apiMessage;
235
+ details;
236
+ constructor(statusCode, code, message, details = []) {
237
+ super(statusCode, message);
238
+ this.message = code ? `geoengine: api-service error (status ${statusCode}, code ${code}): ${message}` : `geoengine: api-service error (status ${statusCode}): ${message}`;
239
+ this.name = "APIServiceError";
240
+ this.code = code;
241
+ this.apiMessage = message;
242
+ this.details = details;
243
+ }
244
+ };
245
+ var UserNotFoundError = class extends APIServiceError {
246
+ constructor(message = "user not found in organization", statusCode = 404, code = "USER_NOT_FOUND", details = []) {
247
+ super(statusCode, code, message, details);
248
+ this.name = "UserNotFoundError";
249
+ }
250
+ };
251
+ var RuleNotFoundError = class extends APIServiceError {
252
+ constructor(message = "geoidentity rule not found", statusCode = 404, code = "RULE_NOT_FOUND", details = []) {
253
+ super(statusCode, code, message, details);
254
+ this.name = "RuleNotFoundError";
255
+ }
256
+ };
257
+ var UserAlreadyExistsError = class extends APIServiceError {
258
+ constructor(message = "user already belongs to the organization", statusCode = 409, code = "USER_ALREADY_EXISTS", details = []) {
259
+ super(statusCode, code, message, details);
260
+ this.name = "UserAlreadyExistsError";
261
+ }
262
+ };
263
+ var InvitationPendingError = class extends APIServiceError {
264
+ constructor(message = "a pending invitation already exists for this email", statusCode = 409, code = "INVITATION_PENDING", details = []) {
265
+ super(statusCode, code, message, details);
266
+ this.name = "InvitationPendingError";
267
+ }
268
+ };
269
+ var LastAdminError = class extends APIServiceError {
270
+ constructor(message = "organization must keep at least one admin", statusCode = 409, code = "LAST_ADMIN", details = []) {
271
+ super(statusCode, code, message, details);
272
+ this.name = "LastAdminError";
273
+ }
274
+ };
275
+ var LastSubjectError = class extends APIServiceError {
276
+ constructor(message = "rule must keep at least one assigned subject", statusCode = 409, code = "LAST_SUBJECT", details = []) {
277
+ super(statusCode, code, message, details);
278
+ this.name = "LastSubjectError";
279
+ }
280
+ };
281
+
282
+ // src/users.ts
283
+ var Roles = {
284
+ Admin: "roles/geoengine.admin",
285
+ Dispatcher: "roles/geoengine.dispatcher",
286
+ Billing: "roles/geoengine.billing",
287
+ Viewer: "roles/geoengine.viewer",
288
+ Device: "roles/geoengine.device"
289
+ };
290
+ var UserStatus = {
291
+ Active: "active",
292
+ Pending: "pending",
293
+ Revoked: "revoked"
294
+ };
295
+ function toUser(raw) {
296
+ return {
297
+ id: raw.id,
298
+ email: raw.email,
299
+ name: raw.name,
300
+ role: raw.role,
301
+ status: raw.status,
302
+ permissions: raw.permissions ?? [],
303
+ createdAt: raw.created_at,
304
+ lastLoginAt: raw.last_login_at
305
+ };
306
+ }
307
+ function isBlank(value) {
308
+ return typeof value !== "string" || value.trim() === "";
309
+ }
310
+ function userPath(userId, suffix = "") {
311
+ if (isBlank(userId)) {
312
+ throw new UserIDRequiredError();
313
+ }
314
+ return `/api/users/${encodeURIComponent(userId.trim())}${suffix}`;
315
+ }
316
+ async function apiServiceRequest(http, isClosed, method, path, body) {
317
+ if (isClosed()) {
318
+ throw new ClientClosedError();
319
+ }
320
+ return http.request({
321
+ endpoint: `${http.options.apiServiceUrl.replace(/\/+$/, "")}${path}`,
322
+ method,
323
+ body,
324
+ isApiService: true
325
+ });
326
+ }
327
+ var UsersService = class {
328
+ constructor(http, isClosed = () => false) {
329
+ this.http = http;
330
+ this.isClosed = isClosed;
331
+ }
332
+ http;
333
+ isClosed;
334
+ /** Returns the members of the organization. */
335
+ async list() {
336
+ const raw = await this.send("GET", "/api/users");
337
+ return (raw ?? []).map(toUser);
338
+ }
339
+ /** Returns a single member of the organization. */
340
+ async get(userId) {
341
+ return toUser(await this.send("GET", userPath(userId)));
342
+ }
343
+ /** Returns the roles available to the organization and their permissions. */
344
+ async listRoles() {
345
+ const raw = await this.send(
346
+ "GET",
347
+ "/api/users/roles"
348
+ );
349
+ return (raw ?? []).map((r) => ({ id: r.id, permissions: r.permissions ?? [] }));
350
+ }
351
+ /**
352
+ * Creates an invitation and emails it to the recipient.
353
+ * Throws InvitationPendingError if a pending invitation already exists for the email,
354
+ * and UserAlreadyExistsError if the email already belongs to the organization.
355
+ */
356
+ async invite(req) {
357
+ if (isBlank(req?.email)) {
358
+ throw new EmailRequiredError();
359
+ }
360
+ if (isBlank(req.role)) {
361
+ throw new RoleRequiredError();
362
+ }
363
+ const raw = await this.send("POST", "/api/users/invite", {
364
+ email: req.email,
365
+ role: req.role,
366
+ inviter_name: req.inviterName || void 0,
367
+ lang: req.lang || void 0
368
+ });
369
+ return {
370
+ email: raw.email,
371
+ role: raw.role,
372
+ status: raw.status,
373
+ inviteUrl: raw.invite_url,
374
+ expiresAt: raw.expires_at
375
+ };
376
+ }
377
+ /**
378
+ * Changes the role of a member. The new permissions apply on the user's next sign-in.
379
+ * Throws LastAdminError if the change would leave the organization without an admin.
380
+ */
381
+ async updateRole(userId, role) {
382
+ if (isBlank(role)) {
383
+ throw new RoleRequiredError();
384
+ }
385
+ return toUser(await this.send("PATCH", userPath(userId, "/role"), { role }));
386
+ }
387
+ /**
388
+ * Revokes a member's access to the organization.
389
+ * Throws LastAdminError if the member is the last admin.
390
+ */
391
+ async remove(userId) {
392
+ await this.send("DELETE", userPath(userId));
393
+ }
394
+ send(method, path, body) {
395
+ return apiServiceRequest(this.http, this.isClosed, method, path, body);
396
+ }
397
+ };
398
+
399
+ // src/validation.ts
400
+ function validateCoordinates(lat, lng) {
401
+ if (typeof lat !== "number" || Number.isNaN(lat) || lat < -90 || lat > 90) {
402
+ throw new InvalidLatitudeError();
403
+ }
404
+ if (typeof lng !== "number" || Number.isNaN(lng) || lng < -180 || lng > 180) {
405
+ throw new InvalidLongitudeError();
406
+ }
407
+ }
408
+ function validateDeviceId(deviceId) {
409
+ if (!deviceId || typeof deviceId !== "string" || deviceId.trim() === "") {
410
+ throw new DeviceIDRequiredError();
411
+ }
412
+ return deviceId.trim();
413
+ }
414
+ function validateGeofenceId(geofenceId) {
415
+ if (!geofenceId || typeof geofenceId !== "string" || geofenceId.trim() === "") {
416
+ throw new GeofenceIDRequiredError();
417
+ }
418
+ return geofenceId.trim();
419
+ }
420
+ function validateAndNormalizePolygon(coordinates) {
421
+ if (!Array.isArray(coordinates) || coordinates.length < 3) {
422
+ throw new InvalidCoordinatesError();
423
+ }
424
+ const polygon = [];
425
+ for (const p of coordinates) {
426
+ if (!Array.isArray(p) || p.length !== 2) {
427
+ throw new ValidationError(
428
+ `geoengine: invalid coordinate format: ${JSON.stringify(p)} (expected [lat, lng])`
429
+ );
430
+ }
431
+ const lat = p[0];
432
+ const lng = p[1];
433
+ validateCoordinates(lat, lng);
434
+ polygon.push([lng, lat]);
435
+ }
436
+ const first = polygon[0];
437
+ const last = polygon[polygon.length - 1];
438
+ if (first[0] !== last[0] || first[1] !== last[1]) {
439
+ polygon.push([first[0], first[1]]);
440
+ }
441
+ return polygon;
442
+ }
443
+
444
+ // src/geoidentity.ts
445
+ var RuleActions = {
446
+ Allow: "ALLOW",
447
+ Block: "BLOCK",
448
+ Challenge: "CHALLENGE"
449
+ };
450
+ var SubjectTypes = {
451
+ User: "USER",
452
+ Role: "ROLE",
453
+ Device: "DEVICE",
454
+ All: "ALL"
455
+ };
456
+ function toRule(raw) {
457
+ return {
458
+ id: raw.id,
459
+ orgId: raw.org_id,
460
+ name: raw.name,
461
+ description: raw.description,
462
+ priority: raw.priority ?? 0,
463
+ action: raw.action,
464
+ isActive: Boolean(raw.is_active),
465
+ whiteIpList: raw.white_ip_list ?? [],
466
+ blackIpList: raw.black_ip_list ?? [],
467
+ blockDatacenter: Boolean(raw.block_datacenter),
468
+ blockTor: Boolean(raw.block_tor),
469
+ riskAccepted: raw.risk_accepted ?? 0,
470
+ geoLimit: raw.geo_limit,
471
+ assignedSubjects: (raw.assigned_subjects ?? []).map((s) => ({
472
+ subjectType: s.subject_type,
473
+ subjectId: s.subject_id
474
+ })),
475
+ subjectsCount: raw.subjects_count ?? 0,
476
+ createdAt: raw.created_at,
477
+ updatedAt: raw.updated_at
478
+ };
479
+ }
480
+ function toWire(req) {
481
+ return {
482
+ name: req.name,
483
+ description: req.description,
484
+ priority: req.priority,
485
+ action: req.action,
486
+ is_active: req.isActive,
487
+ white_ip_list: req.whiteIpList,
488
+ black_ip_list: req.blackIpList,
489
+ block_datacenter: req.blockDatacenter,
490
+ block_tor: req.blockTor,
491
+ risk_accepted: req.riskAccepted,
492
+ geo_limit: req.geoLimit,
493
+ assigned_subjects: req.assignedSubjects?.map((s) => ({
494
+ subject_type: s.subjectType,
495
+ subject_id: s.subjectId
496
+ }))
497
+ };
498
+ }
499
+ var RULES_PATH = "/api/users/geoidentity/rules";
500
+ function rulePath(ruleId, suffix = "") {
501
+ if (typeof ruleId !== "string" || ruleId.trim() === "") {
502
+ throw new RuleIDRequiredError();
503
+ }
504
+ return `${RULES_PATH}/${encodeURIComponent(ruleId.trim())}${suffix}`;
505
+ }
506
+ function requireUserId(userId) {
507
+ if (typeof userId !== "string" || userId.trim() === "") {
508
+ throw new UserIDRequiredError();
509
+ }
510
+ return userId.trim();
511
+ }
512
+ var GeoIdentityService = class {
513
+ constructor(http, isClosed = () => false) {
514
+ this.http = http;
515
+ this.isClosed = isClosed;
516
+ }
517
+ http;
518
+ isClosed;
519
+ /** Creates a GeoIdentity rule. */
520
+ async createRule(req) {
521
+ if (typeof req?.name !== "string" || req.name.trim() === "") {
522
+ throw new RuleNameRequiredError();
523
+ }
524
+ return toRule(await this.send("POST", RULES_PATH, toWire(req)));
525
+ }
526
+ /**
527
+ * Returns the organization's rules ordered by priority.
528
+ * Use getRule to load a rule's assigned subjects.
529
+ */
530
+ async listRules(opts = {}) {
531
+ const query = typeof opts.isActive === "boolean" ? `?is_active=${opts.isActive}` : "";
532
+ const raw = await this.send("GET", RULES_PATH + query);
533
+ return (raw ?? []).map(toRule);
534
+ }
535
+ /** Returns a rule including its assigned subjects. */
536
+ async getRule(ruleId) {
537
+ return toRule(await this.send("GET", rulePath(ruleId)));
538
+ }
539
+ /** Partially updates a rule. */
540
+ async updateRule(ruleId, req) {
541
+ return toRule(await this.send("PATCH", rulePath(ruleId), toWire(req ?? {})));
542
+ }
543
+ /** Deletes a rule and all of its assignments. */
544
+ async deleteRule(ruleId) {
545
+ await this.send("DELETE", rulePath(ruleId));
546
+ }
547
+ /** Applies the rule to a member of the organization. Assigning twice is a no-op. */
548
+ async assignToUser(ruleId, userId) {
549
+ return this.changeAssignment("POST", ruleId, { scope: "user", user_id: requireUserId(userId) });
550
+ }
551
+ /** Applies the rule to every member of the organization. */
552
+ async assignToOrganization(ruleId) {
553
+ return this.changeAssignment("POST", ruleId, { scope: "organization" });
554
+ }
555
+ /**
556
+ * Removes a user assignment from the rule.
557
+ * Throws LastSubjectError if it is the rule's only subject; deactivate or delete the rule instead.
558
+ */
559
+ async unassignFromUser(ruleId, userId) {
560
+ return this.changeAssignment("DELETE", ruleId, { scope: "user", user_id: requireUserId(userId) });
561
+ }
562
+ /**
563
+ * Removes the organization-wide assignment from the rule.
564
+ * Throws LastSubjectError if it is the rule's only subject.
565
+ */
566
+ async unassignFromOrganization(ruleId) {
567
+ return this.changeAssignment("DELETE", ruleId, { scope: "organization" });
568
+ }
569
+ /**
570
+ * Returns the rules that apply to a user: assigned directly, through the user's role,
571
+ * or to the whole organization.
572
+ */
573
+ async listUserRules(userId) {
574
+ const raw = await this.send("GET", userPath(userId, "/geoidentity/rules"));
575
+ return (raw ?? []).map(toRule);
576
+ }
577
+ async changeAssignment(method, ruleId, payload) {
578
+ return toRule(await this.send(method, rulePath(ruleId, "/assignments"), payload));
579
+ }
580
+ send(method, path, body) {
581
+ return apiServiceRequest(this.http, this.isClosed, method, path, body);
582
+ }
583
+ };
584
+ function polygonFromLatLng(coordinates) {
585
+ return { type: "Polygon", coordinates: [validateAndNormalizePolygon(coordinates)] };
586
+ }
587
+
588
+ // src/crypto.ts
589
+ var import_node_crypto = require("crypto");
590
+ function generateHMACSignature(key, timestamp) {
591
+ if (!key) {
592
+ return "";
593
+ }
594
+ return (0, import_node_crypto.createHmac)("sha256", key).update(timestamp.toString()).digest("hex");
595
+ }
596
+
597
+ // src/http.ts
598
+ var USER_AGENT = "GeoEngineNodeSDK/2.1.0";
599
+ function parseHttpError(statusCode, bodyText, isSpatial = false) {
600
+ let parsedErrorContainer = null;
601
+ try {
602
+ parsedErrorContainer = JSON.parse(bodyText);
603
+ } catch {
604
+ }
605
+ const container = parsedErrorContainer?.error;
606
+ let code = container?.status ?? "";
607
+ let message = container?.message ?? parsedErrorContainer?.message ?? bodyText.trim();
608
+ const details = container?.details ?? [];
609
+ if (container?.details && container.details.length > 0) {
610
+ for (const detail of container.details) {
611
+ if (detail.reason) {
612
+ code = detail.reason;
613
+ break;
614
+ }
615
+ }
616
+ }
617
+ if (!code) {
618
+ switch (statusCode) {
619
+ case 204:
620
+ case 404:
621
+ code = "NOT_FOUND";
622
+ break;
623
+ case 402:
624
+ code = "QUOTA_EXCEEDED";
625
+ break;
626
+ case 401:
627
+ code = "UNAUTHORIZED";
628
+ break;
629
+ case 403:
630
+ code = "FORBIDDEN";
631
+ break;
632
+ default:
633
+ code = "";
634
+ }
635
+ }
636
+ if (!message) {
637
+ message = `HTTP ${statusCode}`;
638
+ }
639
+ if (statusCode === 204 || statusCode === 404 || code === "NOT_FOUND") {
640
+ return new GeofenceNotFoundError(message, statusCode, details);
641
+ }
642
+ if (statusCode === 402 || code === "QUOTA_EXCEEDED") {
643
+ return new QuotaExceededError(message, statusCode, details);
644
+ }
645
+ if (statusCode === 401 || code === "UNAUTHORIZED" || code === "MISSING_API_KEY" || code === "MISSING_ORGANIZATION") {
646
+ return new AuthenticationError(message, statusCode, details);
647
+ }
648
+ if (statusCode === 403 || code === "FORBIDDEN") {
649
+ return new ForbiddenError(message, statusCode, details);
650
+ }
651
+ if (isSpatial) {
652
+ return new SpatialAPIError(statusCode, code, message, void 0, details);
653
+ }
654
+ return new APIError(statusCode, message);
655
+ }
656
+ function parseApiServiceError(statusCode, bodyText) {
657
+ let parsed = null;
658
+ try {
659
+ parsed = JSON.parse(bodyText);
660
+ } catch {
661
+ }
662
+ const container = parsed && typeof parsed === "object" ? parsed.error : void 0;
663
+ const details = Array.isArray(container?.details) ? container.details : [];
664
+ let code = "";
665
+ let message = "";
666
+ if (container && typeof container === "object") {
667
+ code = container.status ?? "";
668
+ message = container.message ?? "";
669
+ const withReason = details.find((d) => d?.reason);
670
+ if (withReason?.reason) {
671
+ code = withReason.reason;
672
+ }
673
+ } else {
674
+ message = bodyText.trim();
675
+ }
676
+ if (!message) {
677
+ message = `HTTP ${statusCode}`;
678
+ }
679
+ switch (code) {
680
+ case "USER_NOT_FOUND":
681
+ case "USER_REVOKED":
682
+ return new UserNotFoundError(message, statusCode, code, details);
683
+ case "RULE_NOT_FOUND":
684
+ return new RuleNotFoundError(message, statusCode, code, details);
685
+ case "USER_ALREADY_EXISTS":
686
+ return new UserAlreadyExistsError(message, statusCode, code, details);
687
+ case "INVITATION_PENDING":
688
+ return new InvitationPendingError(message, statusCode, code, details);
689
+ case "LAST_ADMIN":
690
+ return new LastAdminError(message, statusCode, code, details);
691
+ case "LAST_SUBJECT":
692
+ return new LastSubjectError(message, statusCode, code, details);
693
+ case "QUOTA_EXCEEDED":
694
+ return new QuotaExceededError(message, statusCode, details);
695
+ case "MISSING_API_KEY":
696
+ case "MISSING_ORGANIZATION":
697
+ return new AuthenticationError(message, statusCode, details);
698
+ }
699
+ switch (statusCode) {
700
+ case 401:
701
+ return new AuthenticationError(message, statusCode, details);
702
+ case 403:
703
+ return new ForbiddenError(message, statusCode, details);
704
+ case 402:
705
+ return new QuotaExceededError(message, statusCode, details);
706
+ }
707
+ return new APIServiceError(statusCode, code, message, details);
708
+ }
709
+ var HttpClient = class {
710
+ config;
711
+ constructor(options = {}) {
712
+ const defaultManagement = "https://management.geoengine.dev";
713
+ const defaultIngest = "https://ingest.geoengine.dev";
714
+ const defaultApiService = "https://api.geoengine.dev";
715
+ this.config = {
716
+ apiKey: options.apiKey ?? "",
717
+ jwtToken: options.jwtToken,
718
+ environment: options.environment ?? "live",
719
+ managementUrl: options.baseUrl ?? options.managementUrl ?? defaultManagement,
720
+ ingestUrl: options.baseUrl ?? options.ingestUrl ?? defaultIngest,
721
+ apiServiceUrl: options.baseUrl ?? options.apiServiceUrl ?? defaultApiService,
722
+ timeout: options.timeout ?? 1e4,
723
+ maxRetries: options.maxRetries ?? 2,
724
+ batchSize: options.batchSize ?? 100,
725
+ flushInterval: options.flushInterval ?? 500,
726
+ bufferSize: options.bufferSize ?? 5e3,
727
+ fetch: options.fetch ?? globalThis.fetch
728
+ };
729
+ }
730
+ get options() {
731
+ return this.config;
732
+ }
733
+ /**
734
+ * Executes an HTTP request with timeout, authentication headers and exponential backoff retry.
735
+ */
736
+ async request(opts) {
737
+ const method = opts.method ?? "POST";
738
+ const timeoutMs = opts.timeout ?? this.config.timeout;
739
+ const maxRetries = opts.isApiService && method !== "GET" ? 0 : this.config.maxRetries;
740
+ let attempt = 0;
741
+ while (true) {
742
+ attempt++;
743
+ const controller = new globalThis.AbortController();
744
+ const timeoutId = globalThis.setTimeout(() => controller.abort(), timeoutMs);
745
+ const now = Date.now();
746
+ const headers = {
747
+ ...opts.isApiService ? { Accept: "application/json" } : { "Content-Type": "application/json" },
748
+ "X-API-Key": this.config.apiKey,
749
+ "X-Geo-Environment": this.config.environment,
750
+ "X-Request-Time": now.toString(),
751
+ "X-Signature": generateHMACSignature(this.config.apiKey, now),
752
+ "User-Agent": USER_AGENT
753
+ };
754
+ if (opts.isApiService && opts.body !== void 0) {
755
+ headers["Content-Type"] = "application/json";
756
+ }
757
+ if (this.config.jwtToken) {
758
+ headers["Authorization"] = `Bearer ${this.config.jwtToken}`;
759
+ }
760
+ try {
761
+ const response = await this.config.fetch(opts.endpoint, {
762
+ method,
763
+ headers,
764
+ body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0,
765
+ signal: controller.signal
766
+ });
767
+ globalThis.clearTimeout(timeoutId);
768
+ if (response.status === 204) {
769
+ if (opts.isSpatial) {
770
+ throw new GeofenceNotFoundError("geofence not found", 204);
771
+ }
772
+ return null;
773
+ }
774
+ if ((response.status === 429 || response.status >= 500) && attempt <= maxRetries) {
775
+ const delay = Math.min(100 * Math.pow(2, attempt) + Math.random() * 50, 2e3);
776
+ await new Promise(
777
+ (resolve) => globalThis.setTimeout(() => resolve(), delay)
778
+ );
779
+ continue;
780
+ }
781
+ const responseText = await response.text();
782
+ if (!response.ok) {
783
+ throw opts.isApiService ? parseApiServiceError(response.status, responseText) : parseHttpError(response.status, responseText, opts.isSpatial);
784
+ }
785
+ if (!responseText || responseText.trim() === "") {
786
+ return null;
787
+ }
788
+ const json = JSON.parse(responseText);
789
+ if ((opts.isSpatial || opts.isApiService) && typeof json === "object" && json !== null && "success" in json) {
790
+ if (!json.success) {
791
+ throw opts.isApiService ? parseApiServiceError(response.status, responseText) : parseHttpError(response.status, responseText, true);
792
+ }
793
+ return json.data;
794
+ }
795
+ return json;
796
+ } catch (err) {
797
+ globalThis.clearTimeout(timeoutId);
798
+ if (err instanceof Error && err.name === "AbortError") {
799
+ throw new TimeoutError(timeoutMs);
800
+ }
801
+ if (err instanceof APIError) {
802
+ throw err;
803
+ }
804
+ if (attempt <= maxRetries) {
805
+ const delay = Math.min(100 * Math.pow(2, attempt) + Math.random() * 50, 2e3);
806
+ await new Promise(
807
+ (resolve) => globalThis.setTimeout(() => resolve(), delay)
808
+ );
809
+ continue;
810
+ }
811
+ throw err;
812
+ }
813
+ }
814
+ }
815
+ };
816
+
817
+ // src/ingester.ts
818
+ var import_node_timers = require("timers");
819
+ var AsyncIngester = class {
820
+ client;
821
+ bufferSize;
822
+ batchSize;
823
+ intervalMs;
824
+ queue = [];
825
+ inFlightPromises = /* @__PURE__ */ new Set();
826
+ timer = null;
827
+ isClosed = false;
828
+ constructor(client, bufferSize = 5e3, batchSize = 100, flushIntervalMs = 500) {
829
+ this.client = client;
830
+ this.bufferSize = bufferSize;
831
+ this.batchSize = batchSize;
832
+ this.intervalMs = flushIntervalMs;
833
+ this.timer = (0, import_node_timers.setInterval)(() => {
834
+ void this.flush();
835
+ }, this.intervalMs);
836
+ if (this.timer && typeof this.timer.unref === "function") {
837
+ this.timer.unref();
838
+ }
839
+ }
840
+ /**
841
+ * Non-blockingly appends a location ping to the ingestion buffer queue.
842
+ *
843
+ * @param ping Location ping object
844
+ * @returns true if successfully queued, false if queue is full or ingester is stopped
845
+ */
846
+ enqueue(ping) {
847
+ if (!ping || this.isClosed) {
848
+ return false;
849
+ }
850
+ if (this.queue.length >= this.bufferSize) {
851
+ return false;
852
+ }
853
+ this.queue.push(ping);
854
+ if (this.queue.length >= this.batchSize) {
855
+ void this.flush();
856
+ }
857
+ return true;
858
+ }
859
+ /**
860
+ * Flushes current queued batch of location telemetry items.
861
+ */
862
+ async flush() {
863
+ if (this.queue.length === 0) {
864
+ return;
865
+ }
866
+ const batch = this.queue.splice(0, this.batchSize);
867
+ if (batch.length === 0) {
868
+ return;
869
+ }
870
+ const flushPromise = Promise.all(
871
+ batch.map(
872
+ (item) => this.client.sendLocation(item.deviceId, item.latitude, item.longitude).catch(() => {
873
+ })
874
+ )
875
+ ).finally(() => {
876
+ this.inFlightPromises.delete(flushPromise);
877
+ });
878
+ this.inFlightPromises.add(flushPromise);
879
+ await flushPromise;
880
+ }
881
+ /**
882
+ * Drains all remaining pending items, halts worker timer, and releases resources.
883
+ * Safe to call multiple times.
884
+ */
885
+ async stop() {
886
+ if (this.isClosed) {
887
+ return;
888
+ }
889
+ this.isClosed = true;
890
+ if (this.timer) {
891
+ (0, import_node_timers.clearInterval)(this.timer);
892
+ this.timer = null;
893
+ }
894
+ while (this.queue.length > 0) {
895
+ await this.flush();
896
+ }
897
+ if (this.inFlightPromises.size > 0) {
898
+ await Promise.all(Array.from(this.inFlightPromises));
899
+ }
900
+ }
901
+ };
902
+
903
+ // src/models.ts
904
+ var SpatialValidationResult = class {
905
+ inside;
906
+ geofenceId;
907
+ geofenceName;
908
+ latitude;
909
+ longitude;
910
+ constructor(data) {
911
+ this.inside = Boolean(data.inside);
912
+ this.geofenceId = data.geofence_id ?? data.geofenceId ?? "";
913
+ this.geofenceName = data.geofence_name ?? data.geofenceName;
914
+ this.latitude = data.latitude;
915
+ this.longitude = data.longitude;
916
+ }
917
+ /**
918
+ * Returns true if the coordinate is inside the geofence.
919
+ */
920
+ isInside() {
921
+ return this.inside;
922
+ }
923
+ /**
924
+ * Returns true if the coordinate is outside the geofence.
925
+ */
926
+ isOutside() {
927
+ return !this.inside;
928
+ }
929
+ /**
930
+ * Returns latitude and longitude as a [latitude, longitude] tuple.
931
+ */
932
+ coordinates() {
933
+ return [this.latitude, this.longitude];
934
+ }
935
+ /**
936
+ * Formats the result into a clean, human-readable log string matching Go's String().
937
+ */
938
+ toString() {
939
+ const status = this.inside ? "INSIDE" : "OUTSIDE";
940
+ const name = this.geofenceName || "unnamed";
941
+ return `[${status}] geofence=${this.geofenceId} (${name}) at (${this.latitude.toFixed(6)}, ${this.longitude.toFixed(6)})`;
942
+ }
943
+ };
944
+ var SpatialGeneralResult = class {
945
+ inside;
946
+ totalMatches;
947
+ matchedGeofences;
948
+ latitude;
949
+ longitude;
950
+ constructor(data) {
951
+ this.inside = Boolean(data.inside);
952
+ this.totalMatches = data.total_matches ?? data.totalMatches ?? (data.matched_geofences?.length ?? data.matchedGeofences?.length ?? 0);
953
+ this.matchedGeofences = data.matched_geofences ?? data.matchedGeofences ?? [];
954
+ this.latitude = data.latitude;
955
+ this.longitude = data.longitude;
956
+ }
957
+ /**
958
+ * Returns true if the coordinate falls inside at least one geofence.
959
+ */
960
+ isInside() {
961
+ return this.inside;
962
+ }
963
+ /**
964
+ * Returns true if one or more geofences matched the point.
965
+ */
966
+ hasMatches() {
967
+ return this.totalMatches > 0;
968
+ }
969
+ /**
970
+ * Returns the first matched geofence, or null if no matches found.
971
+ */
972
+ firstMatch() {
973
+ return this.matchedGeofences[0] ?? null;
974
+ }
975
+ /**
976
+ * Returns all matched geofence IDs as a string array.
977
+ */
978
+ geofenceIds() {
979
+ return this.matchedGeofences.map((m) => m.id);
980
+ }
981
+ /**
982
+ * Returns all matched geofence names as a string array.
983
+ */
984
+ geofenceNames() {
985
+ return this.matchedGeofences.map((m) => m.name);
986
+ }
987
+ /**
988
+ * Checks whether a specific geofence ID or name is among the matches.
989
+ */
990
+ containsGeofence(idOrName) {
991
+ return this.findMatch(idOrName) !== null;
992
+ }
993
+ /**
994
+ * Searches for a matched geofence by ID or name and returns it if found, or null.
995
+ */
996
+ findMatch(idOrName) {
997
+ for (const match of this.matchedGeofences) {
998
+ if (match.id === idOrName || match.name === idOrName) {
999
+ return match;
1000
+ }
1001
+ }
1002
+ return null;
1003
+ }
1004
+ /**
1005
+ * Returns latitude and longitude as a [latitude, longitude] tuple.
1006
+ */
1007
+ coordinates() {
1008
+ return [this.latitude, this.longitude];
1009
+ }
1010
+ /**
1011
+ * Formats the result into a clean, human-readable log string matching Go's String().
1012
+ */
1013
+ toString() {
1014
+ const status = this.inside ? "INSIDE" : "OUTSIDE";
1015
+ const names = this.geofenceNames().join(", ");
1016
+ return `[${status}] matches=${this.totalMatches} (${names}) at (${this.latitude.toFixed(6)}, ${this.longitude.toFixed(6)})`;
1017
+ }
1018
+ };
1019
+
1020
+ // src/spatial.ts
1021
+ var SpatialService = class {
1022
+ constructor(http) {
1023
+ this.http = http;
1024
+ }
1025
+ http;
1026
+ /**
1027
+ * Convenience method to check if coordinates fall within a specific geofence.
1028
+ *
1029
+ * @param geofenceId Unique identifier of the geofence
1030
+ * @param lat Decimal latitude [-90, 90]
1031
+ * @param lng Decimal longitude [-180, 180]
1032
+ * @returns SpatialValidationResult
1033
+ */
1034
+ async validatePoint(geofenceId, lat, lng) {
1035
+ const validId = validateGeofenceId(geofenceId);
1036
+ validateCoordinates(lat, lng);
1037
+ return this.validateLocation({
1038
+ geofenceId: validId,
1039
+ latitude: lat,
1040
+ longitude: lng
1041
+ });
1042
+ }
1043
+ /**
1044
+ * Checks if coordinates fall inside the specified geofence using the api-service.
1045
+ *
1046
+ * @param req SpatialValidationRequest containing geofenceId, latitude, and longitude
1047
+ * @returns SpatialValidationResult
1048
+ */
1049
+ async validateLocation(req) {
1050
+ const validId = validateGeofenceId(req.geofenceId);
1051
+ validateCoordinates(req.latitude, req.longitude);
1052
+ const endpoint = `${this.http.options.apiServiceUrl.replace(/\/+$/, "")}/api/spatial/validate`;
1053
+ const payload = {
1054
+ geofence_id: validId,
1055
+ latitude: req.latitude,
1056
+ longitude: req.longitude
1057
+ };
1058
+ const rawData = await this.http.request({
1059
+ endpoint,
1060
+ method: "POST",
1061
+ body: payload,
1062
+ isSpatial: true
1063
+ });
1064
+ return new SpatialValidationResult(rawData);
1065
+ }
1066
+ /**
1067
+ * Checks whether coordinates intersect any geofence belonging to the organization.
1068
+ *
1069
+ * @param lat Decimal latitude [-90, 90]
1070
+ * @param lng Decimal longitude [-180, 180]
1071
+ * @returns SpatialGeneralResult
1072
+ */
1073
+ async validateGeneral(lat, lng) {
1074
+ validateCoordinates(lat, lng);
1075
+ return this.validateGeneralLocation({
1076
+ latitude: lat,
1077
+ longitude: lng
1078
+ });
1079
+ }
1080
+ /**
1081
+ * Checks whether coordinates intersect any geofence using the api-service.
1082
+ *
1083
+ * @param req SpatialGeneralRequest containing latitude and longitude
1084
+ * @returns SpatialGeneralResult
1085
+ */
1086
+ async validateGeneralLocation(req) {
1087
+ validateCoordinates(req.latitude, req.longitude);
1088
+ const endpoint = `${this.http.options.apiServiceUrl.replace(/\/+$/, "")}/api/spatial/validate-general`;
1089
+ const payload = {
1090
+ latitude: req.latitude,
1091
+ longitude: req.longitude
1092
+ };
1093
+ const rawData = await this.http.request({
1094
+ endpoint,
1095
+ method: "POST",
1096
+ body: payload,
1097
+ isSpatial: true
1098
+ });
1099
+ return new SpatialGeneralResult(rawData);
1100
+ }
1101
+ /**
1102
+ * Initializes a fluent query builder for spatial coordinate validation.
1103
+ *
1104
+ * @param lat Decimal latitude
1105
+ * @param lng Decimal longitude
1106
+ * @returns SpatialCheckBuilder
1107
+ */
1108
+ check(lat, lng) {
1109
+ return new SpatialCheckBuilder(this, lat, lng);
1110
+ }
1111
+ };
1112
+ var SpatialCheckBuilder = class {
1113
+ constructor(service, lat, lng) {
1114
+ this.service = service;
1115
+ this.lat = lat;
1116
+ this.lng = lng;
1117
+ }
1118
+ service;
1119
+ lat;
1120
+ lng;
1121
+ /**
1122
+ * Configures validation targeting a specific geofence ID.
1123
+ */
1124
+ inGeofence(geofenceId) {
1125
+ return new SingleGeofenceCheck(this.service, geofenceId, this.lat, this.lng);
1126
+ }
1127
+ /**
1128
+ * Configures validation against all organization geofences.
1129
+ */
1130
+ inAllGeofences() {
1131
+ return new GeneralGeofenceCheck(this.service, this.lat, this.lng);
1132
+ }
1133
+ };
1134
+ var SingleGeofenceCheck = class {
1135
+ constructor(service, geofenceId, lat, lng) {
1136
+ this.service = service;
1137
+ this.geofenceId = geofenceId;
1138
+ this.lat = lat;
1139
+ this.lng = lng;
1140
+ }
1141
+ service;
1142
+ geofenceId;
1143
+ lat;
1144
+ lng;
1145
+ /**
1146
+ * Performs the single geofence spatial query.
1147
+ */
1148
+ async execute() {
1149
+ return this.service.validatePoint(this.geofenceId, this.lat, this.lng);
1150
+ }
1151
+ /**
1152
+ * Alias for execute().
1153
+ */
1154
+ async executeSingle() {
1155
+ return this.execute();
1156
+ }
1157
+ /**
1158
+ * Alias for execute().
1159
+ */
1160
+ async validate() {
1161
+ return this.execute();
1162
+ }
1163
+ };
1164
+ var GeneralGeofenceCheck = class {
1165
+ constructor(service, lat, lng) {
1166
+ this.service = service;
1167
+ this.lat = lat;
1168
+ this.lng = lng;
1169
+ }
1170
+ service;
1171
+ lat;
1172
+ lng;
1173
+ /**
1174
+ * Performs the general spatial query against all organization geofences.
1175
+ */
1176
+ async execute() {
1177
+ return this.service.validateGeneral(this.lat, this.lng);
1178
+ }
1179
+ /**
1180
+ * Alias for execute().
1181
+ */
1182
+ async executeGeneral() {
1183
+ return this.execute();
1184
+ }
1185
+ /**
1186
+ * Alias for execute().
1187
+ */
1188
+ async validate() {
1189
+ return this.execute();
1190
+ }
1191
+ };
1192
+
1193
+ // src/client.ts
1194
+ var GeoEngine = class {
1195
+ http;
1196
+ isClosed = false;
1197
+ /**
1198
+ * Spatial provides point-in-polygon querying and geofence validation capabilities.
1199
+ */
1200
+ spatial;
1201
+ /**
1202
+ * Alias for spatial (to maintain exact casing compatibility with Go client.Spatial).
1203
+ */
1204
+ Spatial;
1205
+ /**
1206
+ * Users manages organization members, roles and invitations.
1207
+ */
1208
+ users;
1209
+ /**
1210
+ * Alias for users (matches Go client.Users).
1211
+ */
1212
+ Users;
1213
+ /**
1214
+ * GeoIdentity manages GeoIdentity access rules for users and the organization.
1215
+ */
1216
+ geoIdentity;
1217
+ /**
1218
+ * Alias for geoIdentity (matches Go client.GeoIdentity).
1219
+ */
1220
+ GeoIdentity;
1221
+ /**
1222
+ * Initializes a new GeoEngine client instance.
1223
+ *
1224
+ * @param apiKey Your GeoEngine API Key (required)
1225
+ * @param options Optional configuration parameters
1226
+ */
1227
+ constructor(apiKeyOrOptions, maybeOptions = {}) {
1228
+ let resolvedOptions;
1229
+ if (typeof apiKeyOrOptions === "string") {
1230
+ resolvedOptions = { ...maybeOptions, apiKey: apiKeyOrOptions };
1231
+ } else if (typeof apiKeyOrOptions === "object" && apiKeyOrOptions !== null) {
1232
+ resolvedOptions = { ...apiKeyOrOptions };
1233
+ } else {
1234
+ resolvedOptions = {};
1235
+ }
1236
+ if (!resolvedOptions.apiKey || resolvedOptions.apiKey.trim() === "") {
1237
+ throw new ValidationError("GeoEngine: API Key es requerida.");
1238
+ }
1239
+ this.http = new HttpClient(resolvedOptions);
1240
+ this.spatial = new SpatialService(this.http);
1241
+ this.Spatial = this.spatial;
1242
+ const isClosed = () => this.isClosed;
1243
+ this.users = new UsersService(this.http, isClosed);
1244
+ this.Users = this.users;
1245
+ this.geoIdentity = new GeoIdentityService(this.http, isClosed);
1246
+ this.GeoIdentity = this.geoIdentity;
1247
+ }
1248
+ /**
1249
+ * Current configuration options.
1250
+ */
1251
+ get options() {
1252
+ return this.http.options;
1253
+ }
1254
+ /**
1255
+ * Sends device coordinates over HTTP REST.
1256
+ * Equivalent to Go's Client.SendLocation.
1257
+ *
1258
+ * @param deviceId Unique vehicle/device identifier
1259
+ * @param lat Decimal latitude
1260
+ * @param lng Decimal longitude
1261
+ */
1262
+ async sendLocation(deviceId, lat, lng) {
1263
+ if (this.isClosed) {
1264
+ throw new ClientClosedError();
1265
+ }
1266
+ const validId = validateDeviceId(deviceId);
1267
+ const payload = {
1268
+ device_id: validId,
1269
+ latitude: lat,
1270
+ longitude: lng,
1271
+ timestamp: Math.floor(Date.now() / 1e3)
1272
+ };
1273
+ const endpoint = `${this.http.options.ingestUrl.replace(/\/+$/, "")}/ingest`;
1274
+ await this.http.request({
1275
+ endpoint,
1276
+ method: "POST",
1277
+ body: payload
1278
+ });
1279
+ }
1280
+ /**
1281
+ * Creates a spatial geofence polygon in PostGIS via the management REST API.
1282
+ * Automatically validates and closes the polygon ring.
1283
+ * Equivalent to Go's Client.CreateGeofence.
1284
+ *
1285
+ * @param name Geofence name
1286
+ * @param coordinates Array of [latitude, longitude] pairs (at least 3 coordinates)
1287
+ * @param webhookUrl Optional webhook URL triggered upon enter/exit
1288
+ */
1289
+ async createGeofence(name, coordinates, webhookUrl) {
1290
+ if (this.isClosed) {
1291
+ throw new ClientClosedError();
1292
+ }
1293
+ if (!name || typeof name !== "string" || name.trim() === "") {
1294
+ throw new ValidationError("geoengine: name is required");
1295
+ }
1296
+ const polygon = validateAndNormalizePolygon(coordinates);
1297
+ const payload = {
1298
+ name: name.trim(),
1299
+ webhook_url: webhookUrl,
1300
+ geojson: {
1301
+ type: "Polygon",
1302
+ coordinates: [polygon]
1303
+ }
1304
+ };
1305
+ const endpoint = `${this.http.options.managementUrl.replace(/\/+$/, "")}/geofences`;
1306
+ return this.http.request({
1307
+ endpoint,
1308
+ method: "POST",
1309
+ body: payload
1310
+ });
1311
+ }
1312
+ // --- Spatial Validation Direct Shortcuts ---
1313
+ /**
1314
+ * Validates if coordinates fall within a geofence by ID via the Spatial service.
1315
+ * Shortcut matching Go's Client.ValidateSpatialPoint.
1316
+ */
1317
+ async validateSpatialPoint(geofenceId, lat, lng) {
1318
+ if (this.isClosed) {
1319
+ throw new ClientClosedError();
1320
+ }
1321
+ return this.spatial.validatePoint(geofenceId, lat, lng);
1322
+ }
1323
+ /**
1324
+ * Validates if coordinates fall within a geofence via the Spatial service.
1325
+ * Shortcut matching Go's Client.ValidateSpatialLocation.
1326
+ */
1327
+ async validateSpatialLocation(req) {
1328
+ if (this.isClosed) {
1329
+ throw new ClientClosedError();
1330
+ }
1331
+ return this.spatial.validateLocation(req);
1332
+ }
1333
+ /**
1334
+ * Validates coordinates against all active geofences via the Spatial service.
1335
+ * Shortcut matching Go's Client.ValidateSpatialGeneral.
1336
+ */
1337
+ async validateSpatialGeneral(lat, lng) {
1338
+ if (this.isClosed) {
1339
+ throw new ClientClosedError();
1340
+ }
1341
+ return this.spatial.validateGeneral(lat, lng);
1342
+ }
1343
+ /**
1344
+ * Validates coordinates against all active geofences via the Spatial service.
1345
+ * Shortcut matching Go's Client.ValidateSpatialGeneralLocation.
1346
+ */
1347
+ async validateSpatialGeneralLocation(req) {
1348
+ if (this.isClosed) {
1349
+ throw new ClientClosedError();
1350
+ }
1351
+ return this.spatial.validateGeneralLocation(req);
1352
+ }
1353
+ /**
1354
+ * Instantiates a new AsyncIngester connected to this client.
1355
+ * Matches Go NewAsyncIngester.
1356
+ *
1357
+ * @param bufferSize Queue buffer capacity (default: options.bufferSize ?? 5000)
1358
+ * @param batchSize Batch size before flushing (default: options.batchSize ?? 100)
1359
+ * @param flushIntervalMs Flush interval in ms (default: options.flushInterval ?? 500)
1360
+ */
1361
+ createAsyncIngester(bufferSize, batchSize, flushIntervalMs) {
1362
+ return new AsyncIngester(
1363
+ this,
1364
+ bufferSize ?? this.http.options.bufferSize,
1365
+ batchSize ?? this.http.options.batchSize,
1366
+ flushIntervalMs ?? this.http.options.flushInterval
1367
+ );
1368
+ }
1369
+ /**
1370
+ * Closes the client, marking it inactive. Idempotent.
1371
+ * Subsequent requests will throw ClientClosedError.
1372
+ * Equivalent to Go's Client.Close.
1373
+ */
1374
+ close() {
1375
+ this.isClosed = true;
1376
+ }
1377
+ };
1378
+
1379
+ // src/index.ts
1380
+ var index_default = GeoEngine;
1381
+ // Annotate the CommonJS export names for ESM import in node:
1382
+ 0 && (module.exports = {
1383
+ APIError,
1384
+ APIServiceError,
1385
+ AsyncIngester,
1386
+ AuthenticationError,
1387
+ Client,
1388
+ ClientClosedError,
1389
+ DeviceIDRequiredError,
1390
+ EmailRequiredError,
1391
+ ForbiddenError,
1392
+ GeneralGeofenceCheck,
1393
+ GeoEngine,
1394
+ GeoEngineError,
1395
+ GeoIdentityService,
1396
+ GeofenceIDRequiredError,
1397
+ GeofenceNotFoundError,
1398
+ InvalidCoordinatesError,
1399
+ InvalidLatitudeError,
1400
+ InvalidLongitudeError,
1401
+ InvitationPendingError,
1402
+ LastAdminError,
1403
+ LastSubjectError,
1404
+ QuotaExceededError,
1405
+ RoleRequiredError,
1406
+ Roles,
1407
+ RuleActions,
1408
+ RuleIDRequiredError,
1409
+ RuleNameRequiredError,
1410
+ RuleNotFoundError,
1411
+ SingleGeofenceCheck,
1412
+ SpatialAPIError,
1413
+ SpatialCheckBuilder,
1414
+ SpatialGeneralResult,
1415
+ SpatialService,
1416
+ SpatialValidationResult,
1417
+ SubjectTypes,
1418
+ TimeoutError,
1419
+ UserAlreadyExistsError,
1420
+ UserIDRequiredError,
1421
+ UserNotFoundError,
1422
+ UserStatus,
1423
+ UsersService,
1424
+ ValidationError,
1425
+ generateHMACSignature,
1426
+ polygonFromLatLng,
1427
+ validateAndNormalizePolygon,
1428
+ validateCoordinates,
1429
+ validateDeviceId,
1430
+ validateGeofenceId
1431
+ });
1432
+ //# sourceMappingURL=index.cjs.map