@zero-server/sdk 0.9.1 → 0.9.2

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.
Files changed (126) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -443
  3. package/index.js +414 -412
  4. package/lib/app.js +1172 -1172
  5. package/lib/auth/authorize.js +399 -399
  6. package/lib/auth/enrollment.js +367 -367
  7. package/lib/auth/index.js +57 -57
  8. package/lib/auth/jwt.js +731 -731
  9. package/lib/auth/oauth.js +362 -362
  10. package/lib/auth/session.js +588 -588
  11. package/lib/auth/trustedDevice.js +409 -409
  12. package/lib/auth/twoFactor.js +1150 -1150
  13. package/lib/auth/webauthn.js +946 -946
  14. package/lib/body/index.js +14 -14
  15. package/lib/body/json.js +109 -109
  16. package/lib/body/multipart.js +440 -440
  17. package/lib/body/raw.js +71 -71
  18. package/lib/body/rawBuffer.js +160 -160
  19. package/lib/body/sendError.js +25 -25
  20. package/lib/body/text.js +75 -75
  21. package/lib/body/typeMatch.js +41 -41
  22. package/lib/body/urlencoded.js +235 -235
  23. package/lib/cli.js +845 -845
  24. package/lib/cluster.js +666 -666
  25. package/lib/debug.js +372 -372
  26. package/lib/env/index.js +465 -465
  27. package/lib/errors.js +683 -683
  28. package/lib/fetch/index.js +256 -256
  29. package/lib/grpc/balancer.js +378 -378
  30. package/lib/grpc/call.js +708 -708
  31. package/lib/grpc/client.js +764 -764
  32. package/lib/grpc/codec.js +1221 -1221
  33. package/lib/grpc/credentials.js +398 -398
  34. package/lib/grpc/frame.js +262 -262
  35. package/lib/grpc/health.js +287 -287
  36. package/lib/grpc/index.js +121 -121
  37. package/lib/grpc/metadata.js +461 -461
  38. package/lib/grpc/proto.js +821 -821
  39. package/lib/grpc/reflection.js +590 -590
  40. package/lib/grpc/server.js +445 -445
  41. package/lib/grpc/status.js +118 -118
  42. package/lib/grpc/watch.js +173 -173
  43. package/lib/http/index.js +10 -10
  44. package/lib/http/request.js +727 -727
  45. package/lib/http/response.js +799 -799
  46. package/lib/lifecycle.js +557 -557
  47. package/lib/middleware/compress.js +230 -230
  48. package/lib/middleware/cookieParser.js +237 -237
  49. package/lib/middleware/cors.js +93 -93
  50. package/lib/middleware/csrf.js +137 -137
  51. package/lib/middleware/errorHandler.js +101 -101
  52. package/lib/middleware/helmet.js +175 -175
  53. package/lib/middleware/index.js +19 -17
  54. package/lib/middleware/logger.js +74 -74
  55. package/lib/middleware/rateLimit.js +88 -88
  56. package/lib/middleware/requestId.js +53 -53
  57. package/lib/middleware/static.js +326 -326
  58. package/lib/middleware/timeout.js +71 -71
  59. package/lib/middleware/validator.js +255 -255
  60. package/lib/observe/health.js +326 -326
  61. package/lib/observe/index.js +50 -50
  62. package/lib/observe/logger.js +359 -359
  63. package/lib/observe/metrics.js +805 -805
  64. package/lib/observe/tracing.js +592 -592
  65. package/lib/orm/adapters/json.js +290 -290
  66. package/lib/orm/adapters/memory.js +764 -764
  67. package/lib/orm/adapters/mongo.js +764 -764
  68. package/lib/orm/adapters/mysql.js +933 -933
  69. package/lib/orm/adapters/postgres.js +1144 -1144
  70. package/lib/orm/adapters/redis.js +1534 -1534
  71. package/lib/orm/adapters/sql-base.js +212 -212
  72. package/lib/orm/adapters/sqlite.js +858 -858
  73. package/lib/orm/audit.js +649 -649
  74. package/lib/orm/cache.js +394 -394
  75. package/lib/orm/geo.js +387 -387
  76. package/lib/orm/index.js +784 -784
  77. package/lib/orm/migrate.js +432 -432
  78. package/lib/orm/model.js +1706 -1706
  79. package/lib/orm/plugin.js +375 -375
  80. package/lib/orm/procedures.js +836 -836
  81. package/lib/orm/profiler.js +233 -233
  82. package/lib/orm/query.js +1772 -1772
  83. package/lib/orm/replicas.js +241 -241
  84. package/lib/orm/schema.js +307 -307
  85. package/lib/orm/search.js +380 -380
  86. package/lib/orm/seed/data/commerce.js +136 -136
  87. package/lib/orm/seed/data/internet.js +111 -111
  88. package/lib/orm/seed/data/locations.js +204 -204
  89. package/lib/orm/seed/data/names.js +338 -338
  90. package/lib/orm/seed/data/person.js +128 -128
  91. package/lib/orm/seed/data/phone.js +211 -211
  92. package/lib/orm/seed/data/words.js +134 -134
  93. package/lib/orm/seed/factory.js +178 -178
  94. package/lib/orm/seed/fake.js +1186 -1186
  95. package/lib/orm/seed/index.js +18 -18
  96. package/lib/orm/seed/rng.js +70 -70
  97. package/lib/orm/seed/seeder.js +124 -124
  98. package/lib/orm/seed/unique.js +68 -68
  99. package/lib/orm/snapshot.js +366 -366
  100. package/lib/orm/tenancy.js +605 -605
  101. package/lib/orm/views.js +350 -350
  102. package/lib/router/index.js +436 -436
  103. package/lib/sse/index.js +8 -8
  104. package/lib/sse/stream.js +349 -349
  105. package/lib/ws/connection.js +451 -451
  106. package/lib/ws/handshake.js +125 -125
  107. package/lib/ws/index.js +14 -14
  108. package/lib/ws/room.js +223 -223
  109. package/package.json +73 -73
  110. package/types/app.d.ts +223 -223
  111. package/types/auth.d.ts +520 -520
  112. package/types/cluster.d.ts +75 -75
  113. package/types/env.d.ts +80 -80
  114. package/types/errors.d.ts +316 -316
  115. package/types/fetch.d.ts +43 -43
  116. package/types/grpc.d.ts +432 -432
  117. package/types/index.d.ts +384 -384
  118. package/types/lifecycle.d.ts +60 -60
  119. package/types/middleware.d.ts +320 -320
  120. package/types/observe.d.ts +304 -304
  121. package/types/orm.d.ts +1887 -1887
  122. package/types/request.d.ts +109 -109
  123. package/types/response.d.ts +157 -157
  124. package/types/router.d.ts +78 -78
  125. package/types/sse.d.ts +78 -78
  126. package/types/websocket.d.ts +126 -126
package/lib/orm/geo.js CHANGED
@@ -1,387 +1,387 @@
1
- /**
2
- * @module orm/geo
3
- * @description Geo-spatial query support for the ORM.
4
- * Provides distance calculations, bounding box queries,
5
- * radius searches, and GeoJSON support.
6
- * Works with in-memory adapters using Haversine formula;
7
- * SQL adapters can use native spatial extensions (PostGIS, MySQL spatial).
8
- *
9
- * @section Geo-Spatial Queries
10
- *
11
- * @example
12
- * const { GeoQuery } = require('@zero-server/sdk');
13
- *
14
- * // Create a geo query helper for a model
15
- * const geo = new GeoQuery(Store, {
16
- * latField: 'latitude',
17
- * lngField: 'longitude',
18
- * });
19
- *
20
- * // Find stores within 10km of a point
21
- * const nearby = await geo.near(40.7128, -74.0060, { radius: 10 });
22
- *
23
- * // Find stores within a bounding box
24
- * const inBox = await geo.within({
25
- * north: 40.8, south: 40.6,
26
- * east: -73.9, west: -74.1,
27
- * });
28
- */
29
-
30
- const log = require('../debug')('zero:orm:geo');
31
-
32
- // -- Constants --------------------------------------------
33
-
34
- /**
35
- * Earth's radius in kilometres.
36
- * @const {number}
37
- */
38
- const EARTH_RADIUS_KM = 6371;
39
-
40
- /**
41
- * Earth's radius in miles.
42
- * @const {number}
43
- */
44
- const EARTH_RADIUS_MI = 3959;
45
-
46
- // -- GeoQuery class ---------------------------------------
47
-
48
- /**
49
- * Geo-spatial query builder for ORM models.
50
- * Provides distance-based searches, bounding box queries,
51
- * and GeoJSON conversion utilities.
52
- */
53
- class GeoQuery
54
- {
55
- /**
56
- * @constructor
57
- * @param {typeof Model} ModelClass - Model class with location data.
58
- * @param {object} options - Configuration options.
59
- * @param {string} options.latField - Column name for latitude.
60
- * @param {string} options.lngField - Column name for longitude.
61
- * @param {string} [options.unit='km'] - Distance unit: 'km' or 'mi'.
62
- */
63
- constructor(ModelClass, options = {})
64
- {
65
- if (!ModelClass) throw new Error('GeoQuery requires a Model class');
66
- if (!options.latField) throw new Error('GeoQuery requires latField option');
67
- if (!options.lngField) throw new Error('GeoQuery requires lngField option');
68
-
69
- /** @type {typeof Model} */
70
- this._model = ModelClass;
71
-
72
- /** @type {string} Latitude column name. */
73
- this._latField = options.latField;
74
-
75
- /** @type {string} Longitude column name. */
76
- this._lngField = options.lngField;
77
-
78
- /** @type {string} Distance unit. */
79
- this._unit = options.unit || 'km';
80
- }
81
-
82
- /**
83
- * Find records near a geographic point.
84
- * Uses Haversine formula for distance calculation.
85
- *
86
- * @param {number} lat - Latitude of the center point.
87
- * @param {number} lng - Longitude of the center point.
88
- * @param {object} [options] - Search options.
89
- * @param {number} [options.radius] - Maximum distance (in configured unit).
90
- * @param {number} [options.limit] - Maximum number of results.
91
- * @param {number} [options.offset] - Skip N results.
92
- * @param {object} [options.where] - Additional WHERE conditions.
93
- * @param {string} [options.unit] - Override distance unit ('km' or 'mi').
94
- * @param {boolean} [options.includeDistance=true] - Add `_distance` property to results.
95
- * @returns {Promise<Array<object>>} Records sorted by distance, with `_distance` property.
96
- *
97
- * @example
98
- * // Find 5 nearest stores within 25km
99
- * const stores = await geo.near(40.7128, -74.0060, {
100
- * radius: 25,
101
- * limit: 5,
102
- * });
103
- * stores[0]._distance // => 1.23 (km)
104
- */
105
- async near(lat, lng, options = {})
106
- {
107
- lat = Number(lat);
108
- lng = Number(lng);
109
- if (!Number.isFinite(lat) || !Number.isFinite(lng))
110
- {
111
- throw new Error('lat and lng must be finite numbers');
112
- }
113
-
114
- const {
115
- radius,
116
- limit,
117
- offset = 0,
118
- where = {},
119
- unit = this._unit,
120
- includeDistance = true,
121
- } = options;
122
-
123
- if (radius !== undefined && (!Number.isFinite(Number(radius)) || Number(radius) < 0))
124
- {
125
- throw new Error('radius must be a non-negative finite number');
126
- }
127
-
128
- const adapter = this._model._adapter;
129
- if (!adapter) throw new Error('Model is not registered with a database');
130
-
131
- // Use adapter-native geo search if available
132
- if (typeof adapter.geoNear === 'function')
133
- {
134
- return adapter.geoNear(this._model.table, this._latField, this._lngField, lat, lng, {
135
- radius, limit, offset, where, unit, model: this._model,
136
- });
137
- }
138
-
139
- // Fallback: in-memory Haversine calculation
140
- return this._memoryNear(lat, lng, { radius, limit, offset, where, unit, includeDistance });
141
- }
142
-
143
- /**
144
- * Find records within a bounding box.
145
- *
146
- * @param {object} bounds - Bounding box coordinates.
147
- * @param {number} bounds.north - Northern latitude boundary.
148
- * @param {number} bounds.south - Southern latitude boundary.
149
- * @param {number} bounds.east - Eastern longitude boundary.
150
- * @param {number} bounds.west - Western longitude boundary.
151
- * @param {object} [options] - Query options.
152
- * @param {number} [options.limit] - Maximum results.
153
- * @param {object} [options.where] - Additional WHERE conditions.
154
- * @returns {Promise<Array<object>>} Records within the bounding box.
155
- *
156
- * @example
157
- * const stores = await geo.within({
158
- * north: 40.8, south: 40.6,
159
- * east: -73.9, west: -74.1,
160
- * });
161
- */
162
- async within(bounds, options = {})
163
- {
164
- if (!bounds || !Number.isFinite(bounds.north) || !Number.isFinite(bounds.south) ||
165
- !Number.isFinite(bounds.east) || !Number.isFinite(bounds.west))
166
- {
167
- throw new Error('within() requires bounds with north, south, east, and west as finite numbers');
168
- }
169
-
170
- const { limit, where = {} } = options;
171
-
172
- let q = this._model.query()
173
- .where(this._latField, '>=', bounds.south)
174
- .where(this._latField, '<=', bounds.north)
175
- .where(this._lngField, '>=', bounds.west)
176
- .where(this._lngField, '<=', bounds.east);
177
-
178
- if (Object.keys(where).length) q = q.where(where);
179
- if (limit) q = q.limit(limit);
180
-
181
- return q.exec();
182
- }
183
-
184
- /**
185
- * Calculate the distance between two geographic points.
186
- * Uses the Haversine formula.
187
- *
188
- * @param {number} lat1 - Latitude of point 1.
189
- * @param {number} lng1 - Longitude of point 1.
190
- * @param {number} lat2 - Latitude of point 2.
191
- * @param {number} lng2 - Longitude of point 2.
192
- * @param {string} [unit] - Distance unit ('km' or 'mi'). Defaults to configured unit.
193
- * @returns {number} Distance between the two points.
194
- *
195
- * @example
196
- * const dist = geo.distance(40.7128, -74.0060, 34.0522, -118.2437);
197
- * // => 3944.42 (km)
198
- */
199
- distance(lat1, lng1, lat2, lng2, unit)
200
- {
201
- return GeoQuery.haversine(lat1, lng1, lat2, lng2, unit || this._unit);
202
- }
203
-
204
- /**
205
- * Calculate the Haversine distance between two points.
206
- *
207
- * @param {number} lat1 - Latitude of point 1 (degrees).
208
- * @param {number} lng1 - Longitude of point 1 (degrees).
209
- * @param {number} lat2 - Latitude of point 2 (degrees).
210
- * @param {number} lng2 - Longitude of point 2 (degrees).
211
- * @param {string} [unit='km'] - Distance unit: 'km' or 'mi'.
212
- * @returns {number} Distance in the specified unit.
213
- */
214
- static haversine(lat1, lng1, lat2, lng2, unit = 'km')
215
- {
216
- const R = unit === 'mi' ? EARTH_RADIUS_MI : EARTH_RADIUS_KM;
217
- const toRad = (deg) => deg * (Math.PI / 180);
218
-
219
- const dLat = toRad(lat2 - lat1);
220
- const dLng = toRad(lng2 - lng1);
221
-
222
- const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
223
- Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
224
- Math.sin(dLng / 2) * Math.sin(dLng / 2);
225
-
226
- const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
227
- return R * c;
228
- }
229
-
230
- /**
231
- * Convert a record to GeoJSON Point feature.
232
- *
233
- * @param {object} record - Model instance or plain object.
234
- * @param {object} [options] - Configuration options.
235
- * @param {string[]} [options.properties] - Fields to include in GeoJSON properties.
236
- * @returns {object} GeoJSON Feature object.
237
- *
238
- * @example
239
- * const feature = geo.toGeoJSON(store);
240
- * // => { type: 'Feature', geometry: { type: 'Point', coordinates: [-74.006, 40.7128] }, properties: { ... } }
241
- */
242
- toGeoJSON(record, options = {})
243
- {
244
- const lat = record[this._latField];
245
- const lng = record[this._lngField];
246
-
247
- const properties = {};
248
- const propFields = options.properties;
249
- if (propFields)
250
- {
251
- for (const f of propFields)
252
- {
253
- if (record[f] !== undefined) properties[f] = record[f];
254
- }
255
- }
256
- else
257
- {
258
- // Include all non-geo fields
259
- const data = record.toJSON ? record.toJSON() : { ...record };
260
- for (const [k, v] of Object.entries(data))
261
- {
262
- if (k !== this._latField && k !== this._lngField)
263
- {
264
- properties[k] = v;
265
- }
266
- }
267
- }
268
-
269
- return {
270
- type: 'Feature',
271
- geometry: {
272
- type: 'Point',
273
- coordinates: [lng, lat], // GeoJSON is [lng, lat]
274
- },
275
- properties,
276
- };
277
- }
278
-
279
- /**
280
- * Convert multiple records to a GeoJSON FeatureCollection.
281
- *
282
- * @param {Array<object>} records - Array of model instances or plain objects.
283
- * @param {object} [options] - Configuration options.
284
- * @param {string[]} [options.properties] - Fields to include in each feature's properties.
285
- * @returns {object} GeoJSON FeatureCollection.
286
- *
287
- * @example
288
- * const collection = geo.toGeoJSONCollection(stores);
289
- * // => { type: 'FeatureCollection', features: [...] }
290
- */
291
- toGeoJSONCollection(records, options = {})
292
- {
293
- return {
294
- type: 'FeatureCollection',
295
- features: records.map(r => this.toGeoJSON(r, options)),
296
- };
297
- }
298
-
299
- /**
300
- * Create a model instance from a GeoJSON Feature.
301
- *
302
- * @param {object} feature - GeoJSON Feature with Point geometry.
303
- * @returns {object} Plain data object ready for Model.create().
304
- *
305
- * @example
306
- * const data = geo.fromGeoJSON(feature);
307
- * const store = await Store.create(data);
308
- */
309
- fromGeoJSON(feature)
310
- {
311
- if (!feature || feature.type !== 'Feature' || !feature.geometry)
312
- {
313
- throw new Error('Invalid GeoJSON Feature');
314
- }
315
- if (feature.geometry.type !== 'Point')
316
- {
317
- throw new Error('Only Point geometry is supported');
318
- }
319
-
320
- const [lng, lat] = feature.geometry.coordinates;
321
- const data = { ...feature.properties };
322
- data[this._latField] = lat;
323
- data[this._lngField] = lng;
324
- return data;
325
- }
326
-
327
- /**
328
- * Check if a point is within a given radius of a center point.
329
- *
330
- * @param {number} lat - Point latitude.
331
- * @param {number} lng - Point longitude.
332
- * @param {number} centerLat - Center latitude.
333
- * @param {number} centerLng - Center longitude.
334
- * @param {number} radius - Radius to check.
335
- * @param {string} [unit] - Distance unit.
336
- * @returns {boolean} True if the point is within the radius.
337
- */
338
- isWithinRadius(lat, lng, centerLat, centerLng, radius, unit)
339
- {
340
- const dist = this.distance(lat, lng, centerLat, centerLng, unit);
341
- return dist <= radius;
342
- }
343
-
344
- /**
345
- * In-memory near search with Haversine distance.
346
- * @param {number} lat - Center latitude.
347
- * @param {number} lng - Center longitude.
348
- * @param {object} options - Search options.
349
- * @returns {Promise<Array>} Sorted results with _distance.
350
- * @private
351
- */
352
- async _memoryNear(lat, lng, options = {})
353
- {
354
- const { radius, limit, offset = 0, where = {}, unit = this._unit, includeDistance = true } = options;
355
-
356
- let q = this._model.query();
357
- if (Object.keys(where).length) q = q.where(where);
358
- const allRows = await q.exec();
359
-
360
- const scored = [];
361
- for (const row of allRows)
362
- {
363
- const rowLat = row[this._latField];
364
- const rowLng = row[this._lngField];
365
- if (rowLat == null || rowLng == null) continue;
366
-
367
- const dist = GeoQuery.haversine(lat, lng, rowLat, rowLng, unit);
368
-
369
- if (radius !== undefined && dist > radius) continue;
370
-
371
- const data = row.toJSON ? row.toJSON() : { ...row };
372
- if (includeDistance) data._distance = Math.round(dist * 100) / 100;
373
- scored.push({ data, dist });
374
- }
375
-
376
- // Sort by distance
377
- scored.sort((a, b) => a.dist - b.dist);
378
-
379
- let results = scored.map(s => s.data);
380
- if (offset) results = results.slice(offset);
381
- if (limit) results = results.slice(0, limit);
382
-
383
- return results;
384
- }
385
- }
386
-
387
- module.exports = { GeoQuery, EARTH_RADIUS_KM, EARTH_RADIUS_MI };
1
+ /**
2
+ * @module orm/geo
3
+ * @description Geo-spatial query support for the ORM.
4
+ * Provides distance calculations, bounding box queries,
5
+ * radius searches, and GeoJSON support.
6
+ * Works with in-memory adapters using Haversine formula;
7
+ * SQL adapters can use native spatial extensions (PostGIS, MySQL spatial).
8
+ *
9
+ * @section Geo-Spatial Queries
10
+ *
11
+ * @example
12
+ * const { GeoQuery } = require('@zero-server/sdk');
13
+ *
14
+ * // Create a geo query helper for a model
15
+ * const geo = new GeoQuery(Store, {
16
+ * latField: 'latitude',
17
+ * lngField: 'longitude',
18
+ * });
19
+ *
20
+ * // Find stores within 10km of a point
21
+ * const nearby = await geo.near(40.7128, -74.0060, { radius: 10 });
22
+ *
23
+ * // Find stores within a bounding box
24
+ * const inBox = await geo.within({
25
+ * north: 40.8, south: 40.6,
26
+ * east: -73.9, west: -74.1,
27
+ * });
28
+ */
29
+
30
+ const log = require('../debug')('zero:orm:geo');
31
+
32
+ // -- Constants --------------------------------------------
33
+
34
+ /**
35
+ * Earth's radius in kilometres.
36
+ * @const {number}
37
+ */
38
+ const EARTH_RADIUS_KM = 6371;
39
+
40
+ /**
41
+ * Earth's radius in miles.
42
+ * @const {number}
43
+ */
44
+ const EARTH_RADIUS_MI = 3959;
45
+
46
+ // -- GeoQuery class ---------------------------------------
47
+
48
+ /**
49
+ * Geo-spatial query builder for ORM models.
50
+ * Provides distance-based searches, bounding box queries,
51
+ * and GeoJSON conversion utilities.
52
+ */
53
+ class GeoQuery
54
+ {
55
+ /**
56
+ * @constructor
57
+ * @param {typeof Model} ModelClass - Model class with location data.
58
+ * @param {object} options - Configuration options.
59
+ * @param {string} options.latField - Column name for latitude.
60
+ * @param {string} options.lngField - Column name for longitude.
61
+ * @param {string} [options.unit='km'] - Distance unit: 'km' or 'mi'.
62
+ */
63
+ constructor(ModelClass, options = {})
64
+ {
65
+ if (!ModelClass) throw new Error('GeoQuery requires a Model class');
66
+ if (!options.latField) throw new Error('GeoQuery requires latField option');
67
+ if (!options.lngField) throw new Error('GeoQuery requires lngField option');
68
+
69
+ /** @type {typeof Model} */
70
+ this._model = ModelClass;
71
+
72
+ /** @type {string} Latitude column name. */
73
+ this._latField = options.latField;
74
+
75
+ /** @type {string} Longitude column name. */
76
+ this._lngField = options.lngField;
77
+
78
+ /** @type {string} Distance unit. */
79
+ this._unit = options.unit || 'km';
80
+ }
81
+
82
+ /**
83
+ * Find records near a geographic point.
84
+ * Uses Haversine formula for distance calculation.
85
+ *
86
+ * @param {number} lat - Latitude of the center point.
87
+ * @param {number} lng - Longitude of the center point.
88
+ * @param {object} [options] - Search options.
89
+ * @param {number} [options.radius] - Maximum distance (in configured unit).
90
+ * @param {number} [options.limit] - Maximum number of results.
91
+ * @param {number} [options.offset] - Skip N results.
92
+ * @param {object} [options.where] - Additional WHERE conditions.
93
+ * @param {string} [options.unit] - Override distance unit ('km' or 'mi').
94
+ * @param {boolean} [options.includeDistance=true] - Add `_distance` property to results.
95
+ * @returns {Promise<Array<object>>} Records sorted by distance, with `_distance` property.
96
+ *
97
+ * @example
98
+ * // Find 5 nearest stores within 25km
99
+ * const stores = await geo.near(40.7128, -74.0060, {
100
+ * radius: 25,
101
+ * limit: 5,
102
+ * });
103
+ * stores[0]._distance // => 1.23 (km)
104
+ */
105
+ async near(lat, lng, options = {})
106
+ {
107
+ lat = Number(lat);
108
+ lng = Number(lng);
109
+ if (!Number.isFinite(lat) || !Number.isFinite(lng))
110
+ {
111
+ throw new Error('lat and lng must be finite numbers');
112
+ }
113
+
114
+ const {
115
+ radius,
116
+ limit,
117
+ offset = 0,
118
+ where = {},
119
+ unit = this._unit,
120
+ includeDistance = true,
121
+ } = options;
122
+
123
+ if (radius !== undefined && (!Number.isFinite(Number(radius)) || Number(radius) < 0))
124
+ {
125
+ throw new Error('radius must be a non-negative finite number');
126
+ }
127
+
128
+ const adapter = this._model._adapter;
129
+ if (!adapter) throw new Error('Model is not registered with a database');
130
+
131
+ // Use adapter-native geo search if available
132
+ if (typeof adapter.geoNear === 'function')
133
+ {
134
+ return adapter.geoNear(this._model.table, this._latField, this._lngField, lat, lng, {
135
+ radius, limit, offset, where, unit, model: this._model,
136
+ });
137
+ }
138
+
139
+ // Fallback: in-memory Haversine calculation
140
+ return this._memoryNear(lat, lng, { radius, limit, offset, where, unit, includeDistance });
141
+ }
142
+
143
+ /**
144
+ * Find records within a bounding box.
145
+ *
146
+ * @param {object} bounds - Bounding box coordinates.
147
+ * @param {number} bounds.north - Northern latitude boundary.
148
+ * @param {number} bounds.south - Southern latitude boundary.
149
+ * @param {number} bounds.east - Eastern longitude boundary.
150
+ * @param {number} bounds.west - Western longitude boundary.
151
+ * @param {object} [options] - Query options.
152
+ * @param {number} [options.limit] - Maximum results.
153
+ * @param {object} [options.where] - Additional WHERE conditions.
154
+ * @returns {Promise<Array<object>>} Records within the bounding box.
155
+ *
156
+ * @example
157
+ * const stores = await geo.within({
158
+ * north: 40.8, south: 40.6,
159
+ * east: -73.9, west: -74.1,
160
+ * });
161
+ */
162
+ async within(bounds, options = {})
163
+ {
164
+ if (!bounds || !Number.isFinite(bounds.north) || !Number.isFinite(bounds.south) ||
165
+ !Number.isFinite(bounds.east) || !Number.isFinite(bounds.west))
166
+ {
167
+ throw new Error('within() requires bounds with north, south, east, and west as finite numbers');
168
+ }
169
+
170
+ const { limit, where = {} } = options;
171
+
172
+ let q = this._model.query()
173
+ .where(this._latField, '>=', bounds.south)
174
+ .where(this._latField, '<=', bounds.north)
175
+ .where(this._lngField, '>=', bounds.west)
176
+ .where(this._lngField, '<=', bounds.east);
177
+
178
+ if (Object.keys(where).length) q = q.where(where);
179
+ if (limit) q = q.limit(limit);
180
+
181
+ return q.exec();
182
+ }
183
+
184
+ /**
185
+ * Calculate the distance between two geographic points.
186
+ * Uses the Haversine formula.
187
+ *
188
+ * @param {number} lat1 - Latitude of point 1.
189
+ * @param {number} lng1 - Longitude of point 1.
190
+ * @param {number} lat2 - Latitude of point 2.
191
+ * @param {number} lng2 - Longitude of point 2.
192
+ * @param {string} [unit] - Distance unit ('km' or 'mi'). Defaults to configured unit.
193
+ * @returns {number} Distance between the two points.
194
+ *
195
+ * @example
196
+ * const dist = geo.distance(40.7128, -74.0060, 34.0522, -118.2437);
197
+ * // => 3944.42 (km)
198
+ */
199
+ distance(lat1, lng1, lat2, lng2, unit)
200
+ {
201
+ return GeoQuery.haversine(lat1, lng1, lat2, lng2, unit || this._unit);
202
+ }
203
+
204
+ /**
205
+ * Calculate the Haversine distance between two points.
206
+ *
207
+ * @param {number} lat1 - Latitude of point 1 (degrees).
208
+ * @param {number} lng1 - Longitude of point 1 (degrees).
209
+ * @param {number} lat2 - Latitude of point 2 (degrees).
210
+ * @param {number} lng2 - Longitude of point 2 (degrees).
211
+ * @param {string} [unit='km'] - Distance unit: 'km' or 'mi'.
212
+ * @returns {number} Distance in the specified unit.
213
+ */
214
+ static haversine(lat1, lng1, lat2, lng2, unit = 'km')
215
+ {
216
+ const R = unit === 'mi' ? EARTH_RADIUS_MI : EARTH_RADIUS_KM;
217
+ const toRad = (deg) => deg * (Math.PI / 180);
218
+
219
+ const dLat = toRad(lat2 - lat1);
220
+ const dLng = toRad(lng2 - lng1);
221
+
222
+ const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
223
+ Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
224
+ Math.sin(dLng / 2) * Math.sin(dLng / 2);
225
+
226
+ const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
227
+ return R * c;
228
+ }
229
+
230
+ /**
231
+ * Convert a record to GeoJSON Point feature.
232
+ *
233
+ * @param {object} record - Model instance or plain object.
234
+ * @param {object} [options] - Configuration options.
235
+ * @param {string[]} [options.properties] - Fields to include in GeoJSON properties.
236
+ * @returns {object} GeoJSON Feature object.
237
+ *
238
+ * @example
239
+ * const feature = geo.toGeoJSON(store);
240
+ * // => { type: 'Feature', geometry: { type: 'Point', coordinates: [-74.006, 40.7128] }, properties: { ... } }
241
+ */
242
+ toGeoJSON(record, options = {})
243
+ {
244
+ const lat = record[this._latField];
245
+ const lng = record[this._lngField];
246
+
247
+ const properties = {};
248
+ const propFields = options.properties;
249
+ if (propFields)
250
+ {
251
+ for (const f of propFields)
252
+ {
253
+ if (record[f] !== undefined) properties[f] = record[f];
254
+ }
255
+ }
256
+ else
257
+ {
258
+ // Include all non-geo fields
259
+ const data = record.toJSON ? record.toJSON() : { ...record };
260
+ for (const [k, v] of Object.entries(data))
261
+ {
262
+ if (k !== this._latField && k !== this._lngField)
263
+ {
264
+ properties[k] = v;
265
+ }
266
+ }
267
+ }
268
+
269
+ return {
270
+ type: 'Feature',
271
+ geometry: {
272
+ type: 'Point',
273
+ coordinates: [lng, lat], // GeoJSON is [lng, lat]
274
+ },
275
+ properties,
276
+ };
277
+ }
278
+
279
+ /**
280
+ * Convert multiple records to a GeoJSON FeatureCollection.
281
+ *
282
+ * @param {Array<object>} records - Array of model instances or plain objects.
283
+ * @param {object} [options] - Configuration options.
284
+ * @param {string[]} [options.properties] - Fields to include in each feature's properties.
285
+ * @returns {object} GeoJSON FeatureCollection.
286
+ *
287
+ * @example
288
+ * const collection = geo.toGeoJSONCollection(stores);
289
+ * // => { type: 'FeatureCollection', features: [...] }
290
+ */
291
+ toGeoJSONCollection(records, options = {})
292
+ {
293
+ return {
294
+ type: 'FeatureCollection',
295
+ features: records.map(r => this.toGeoJSON(r, options)),
296
+ };
297
+ }
298
+
299
+ /**
300
+ * Create a model instance from a GeoJSON Feature.
301
+ *
302
+ * @param {object} feature - GeoJSON Feature with Point geometry.
303
+ * @returns {object} Plain data object ready for Model.create().
304
+ *
305
+ * @example
306
+ * const data = geo.fromGeoJSON(feature);
307
+ * const store = await Store.create(data);
308
+ */
309
+ fromGeoJSON(feature)
310
+ {
311
+ if (!feature || feature.type !== 'Feature' || !feature.geometry)
312
+ {
313
+ throw new Error('Invalid GeoJSON Feature');
314
+ }
315
+ if (feature.geometry.type !== 'Point')
316
+ {
317
+ throw new Error('Only Point geometry is supported');
318
+ }
319
+
320
+ const [lng, lat] = feature.geometry.coordinates;
321
+ const data = { ...feature.properties };
322
+ data[this._latField] = lat;
323
+ data[this._lngField] = lng;
324
+ return data;
325
+ }
326
+
327
+ /**
328
+ * Check if a point is within a given radius of a center point.
329
+ *
330
+ * @param {number} lat - Point latitude.
331
+ * @param {number} lng - Point longitude.
332
+ * @param {number} centerLat - Center latitude.
333
+ * @param {number} centerLng - Center longitude.
334
+ * @param {number} radius - Radius to check.
335
+ * @param {string} [unit] - Distance unit.
336
+ * @returns {boolean} True if the point is within the radius.
337
+ */
338
+ isWithinRadius(lat, lng, centerLat, centerLng, radius, unit)
339
+ {
340
+ const dist = this.distance(lat, lng, centerLat, centerLng, unit);
341
+ return dist <= radius;
342
+ }
343
+
344
+ /**
345
+ * In-memory near search with Haversine distance.
346
+ * @param {number} lat - Center latitude.
347
+ * @param {number} lng - Center longitude.
348
+ * @param {object} options - Search options.
349
+ * @returns {Promise<Array>} Sorted results with _distance.
350
+ * @private
351
+ */
352
+ async _memoryNear(lat, lng, options = {})
353
+ {
354
+ const { radius, limit, offset = 0, where = {}, unit = this._unit, includeDistance = true } = options;
355
+
356
+ let q = this._model.query();
357
+ if (Object.keys(where).length) q = q.where(where);
358
+ const allRows = await q.exec();
359
+
360
+ const scored = [];
361
+ for (const row of allRows)
362
+ {
363
+ const rowLat = row[this._latField];
364
+ const rowLng = row[this._lngField];
365
+ if (rowLat == null || rowLng == null) continue;
366
+
367
+ const dist = GeoQuery.haversine(lat, lng, rowLat, rowLng, unit);
368
+
369
+ if (radius !== undefined && dist > radius) continue;
370
+
371
+ const data = row.toJSON ? row.toJSON() : { ...row };
372
+ if (includeDistance) data._distance = Math.round(dist * 100) / 100;
373
+ scored.push({ data, dist });
374
+ }
375
+
376
+ // Sort by distance
377
+ scored.sort((a, b) => a.dist - b.dist);
378
+
379
+ let results = scored.map(s => s.data);
380
+ if (offset) results = results.slice(offset);
381
+ if (limit) results = results.slice(0, limit);
382
+
383
+ return results;
384
+ }
385
+ }
386
+
387
+ module.exports = { GeoQuery, EARTH_RADIUS_KM, EARTH_RADIUS_MI };