geontfy 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +385 -2
- package/dist/index.cjs +688 -0
- package/dist/index.d.cts +203 -0
- package/dist/index.d.ts +203 -0
- package/dist/index.js +630 -0
- package/package.json +62 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,688 @@
|
|
|
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
|
+
CoverLimitError: () => CoverLimitError,
|
|
24
|
+
EARTH_RADIUS_METERS: () => EARTH_RADIUS_METERS,
|
|
25
|
+
GEOHASH_ALPHABET: () => GEOHASH_ALPHABET,
|
|
26
|
+
ancestors: () => ancestors,
|
|
27
|
+
circle: () => circle,
|
|
28
|
+
classifyCell: () => classifyCell,
|
|
29
|
+
containsPosition: () => containsPosition,
|
|
30
|
+
coverBoundedCircle: () => coverBoundedCircle2,
|
|
31
|
+
coverRegion: () => coverRegion,
|
|
32
|
+
createBoundedGeontfy: () => createBoundedGeontfy2,
|
|
33
|
+
createFcmTransport: () => createFcmTransport,
|
|
34
|
+
createGeontfy: () => createGeontfy,
|
|
35
|
+
createMemoryDedupe: () => createMemoryDedupe,
|
|
36
|
+
createNominatimProvider: () => createNominatimProvider,
|
|
37
|
+
createReceiver: () => createReceiver,
|
|
38
|
+
decodeGeohash: () => decodeGeohash,
|
|
39
|
+
dispatch: () => dispatch,
|
|
40
|
+
distanceMeters: () => distanceMeters,
|
|
41
|
+
encodeGeohash: () => encodeGeohash,
|
|
42
|
+
fromFcmData: () => fromFcmData,
|
|
43
|
+
matchesSubscription: () => matchesSubscription,
|
|
44
|
+
normalizePosition: () => normalizePosition,
|
|
45
|
+
positiveInteger: () => positiveInteger,
|
|
46
|
+
reconcileSubscriptions: () => reconcileSubscriptions,
|
|
47
|
+
subscriptionDiff: () => subscriptionDiff,
|
|
48
|
+
toFcmMessage: () => toFcmMessage,
|
|
49
|
+
validateBoundary: () => validateBoundary,
|
|
50
|
+
validateEvent: () => validateEvent,
|
|
51
|
+
validatePosition: () => validatePosition,
|
|
52
|
+
validatePrecision: () => validatePrecision,
|
|
53
|
+
validateRadius: () => validateRadius,
|
|
54
|
+
validateRegion: () => validateRegion
|
|
55
|
+
});
|
|
56
|
+
module.exports = __toCommonJS(index_exports);
|
|
57
|
+
|
|
58
|
+
// src/geohash.ts
|
|
59
|
+
var GEOHASH_ALPHABET = "0123456789bcdefghjkmnpqrstuvwxyz";
|
|
60
|
+
function validatePrecision(precision) {
|
|
61
|
+
if (!Number.isInteger(precision) || precision < 1 || precision > 12) {
|
|
62
|
+
throw new RangeError("precision must be an integer between 1 and 12");
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function validatePosition(position) {
|
|
66
|
+
if (!position || !Number.isFinite(position.lat) || !Number.isFinite(position.lon) || Math.abs(position.lat) > 90 || Math.abs(position.lon) > 180) {
|
|
67
|
+
throw new RangeError("position requires lat in [-90, 90] and lon in [-180, 180]");
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function normalizePosition(position) {
|
|
71
|
+
validatePosition(position);
|
|
72
|
+
return { lat: position.lat, lon: Math.abs(position.lat) === 90 ? 0 : position.lon === 180 ? -180 : position.lon };
|
|
73
|
+
}
|
|
74
|
+
function encodeGeohash(position, precision = 6) {
|
|
75
|
+
validatePrecision(precision);
|
|
76
|
+
const point = normalizePosition(position);
|
|
77
|
+
let west = -180, east = 180, south = -90, north = 90;
|
|
78
|
+
let result = "", value = 0;
|
|
79
|
+
for (let bit = 0; bit < precision * 5; bit++) {
|
|
80
|
+
const longitude = bit % 2 === 0;
|
|
81
|
+
const middle = longitude ? (west + east) / 2 : (south + north) / 2;
|
|
82
|
+
const upper = (longitude ? point.lon : point.lat) >= middle;
|
|
83
|
+
value = value * 2 + Number(upper);
|
|
84
|
+
if (longitude) {
|
|
85
|
+
if (upper) west = middle;
|
|
86
|
+
else east = middle;
|
|
87
|
+
} else {
|
|
88
|
+
if (upper) south = middle;
|
|
89
|
+
else north = middle;
|
|
90
|
+
}
|
|
91
|
+
if (bit % 5 === 4) {
|
|
92
|
+
result += GEOHASH_ALPHABET[value];
|
|
93
|
+
value = 0;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return result;
|
|
97
|
+
}
|
|
98
|
+
function decodeGeohash(hash) {
|
|
99
|
+
if (typeof hash !== "string" || hash.length > 12 || !/^[0123456789bcdefghjkmnpqrstuvwxyz]*$/.test(hash)) {
|
|
100
|
+
throw new TypeError("invalid geohash");
|
|
101
|
+
}
|
|
102
|
+
let west = -180, east = 180, south = -90, north = 90, index = 0;
|
|
103
|
+
for (const char of hash) {
|
|
104
|
+
const value = GEOHASH_ALPHABET.indexOf(char);
|
|
105
|
+
for (let mask = 16; mask > 0; mask >>= 1) {
|
|
106
|
+
const upper = (value & mask) !== 0;
|
|
107
|
+
if (index++ % 2 === 0) {
|
|
108
|
+
const middle = (west + east) / 2;
|
|
109
|
+
if (upper) west = middle;
|
|
110
|
+
else east = middle;
|
|
111
|
+
} else {
|
|
112
|
+
const middle = (south + north) / 2;
|
|
113
|
+
if (upper) south = middle;
|
|
114
|
+
else north = middle;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return { west, east, south, north };
|
|
119
|
+
}
|
|
120
|
+
function ancestors(hash) {
|
|
121
|
+
decodeGeohash(hash);
|
|
122
|
+
return Array.from({ length: hash.length + 1 }, (_, index) => hash.slice(0, index));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// src/geometry.ts
|
|
126
|
+
var EARTH_RADIUS_METERS = 63710088e-1;
|
|
127
|
+
var RAD = Math.PI / 180;
|
|
128
|
+
var EPS = 1e-12;
|
|
129
|
+
function circle(center, radiusMeters) {
|
|
130
|
+
validateRadius(radiusMeters);
|
|
131
|
+
return { type: "Circle", center: normalizePosition(center), radiusMeters };
|
|
132
|
+
}
|
|
133
|
+
function validateRadius(radius) {
|
|
134
|
+
if (!Number.isFinite(radius) || radius < 0 || radius > Math.PI * EARTH_RADIUS_METERS) {
|
|
135
|
+
throw new RangeError("radiusMeters must be between 0 and half the Earth circumference");
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function distanceMeters(a, b) {
|
|
139
|
+
const p = normalizePosition(a), q = normalizePosition(b);
|
|
140
|
+
const dlat = (q.lat - p.lat) * RAD, dlon = (q.lon - p.lon) * RAD;
|
|
141
|
+
const h = Math.sin(dlat / 2) ** 2 + Math.cos(p.lat * RAD) * Math.cos(q.lat * RAD) * Math.sin(dlon / 2) ** 2;
|
|
142
|
+
return 2 * EARTH_RADIUS_METERS * Math.atan2(Math.sqrt(Math.min(1, h)), Math.sqrt(Math.max(0, 1 - h)));
|
|
143
|
+
}
|
|
144
|
+
function onSegment(p, a, b) {
|
|
145
|
+
const cross = (p[0] - a[0]) * (b[1] - a[1]) - (p[1] - a[1]) * (b[0] - a[0]);
|
|
146
|
+
return Math.abs(cross) <= EPS && p[0] >= Math.min(a[0], b[0]) - EPS && p[0] <= Math.max(a[0], b[0]) + EPS && p[1] >= Math.min(a[1], b[1]) - EPS && p[1] <= Math.max(a[1], b[1]) + EPS;
|
|
147
|
+
}
|
|
148
|
+
function orientation(a, b, c) {
|
|
149
|
+
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
|
|
150
|
+
}
|
|
151
|
+
function segmentsIntersect(a, b, c, d) {
|
|
152
|
+
if (onSegment(a, c, d) || onSegment(b, c, d) || onSegment(c, a, b) || onSegment(d, a, b)) return true;
|
|
153
|
+
return orientation(a, b, c) * orientation(a, b, d) < 0 && orientation(c, d, a) * orientation(c, d, b) < 0;
|
|
154
|
+
}
|
|
155
|
+
function inRing(point, ring) {
|
|
156
|
+
let inside = false;
|
|
157
|
+
for (let i = 1; i < ring.length; i++) {
|
|
158
|
+
const a = ring[i - 1], b = ring[i];
|
|
159
|
+
if (onSegment(point, a, b)) return 0;
|
|
160
|
+
if (a[1] > point[1] !== b[1] > point[1] && point[0] < (b[0] - a[0]) * (point[1] - a[1]) / (b[1] - a[1]) + a[0]) inside = !inside;
|
|
161
|
+
}
|
|
162
|
+
return inside ? 1 : -1;
|
|
163
|
+
}
|
|
164
|
+
function inPolygon(point, rings) {
|
|
165
|
+
const outer = inRing(point, rings[0]);
|
|
166
|
+
if (outer === -1) return false;
|
|
167
|
+
if (outer === 0) return true;
|
|
168
|
+
for (const hole of rings.slice(1)) {
|
|
169
|
+
const result = inRing(point, hole);
|
|
170
|
+
if (result === 0) return true;
|
|
171
|
+
if (result === 1) return false;
|
|
172
|
+
}
|
|
173
|
+
return true;
|
|
174
|
+
}
|
|
175
|
+
function validateBoundary(boundary) {
|
|
176
|
+
if (!boundary || !["Polygon", "MultiPolygon"].includes(boundary.type) || !Array.isArray(boundary.coordinates)) {
|
|
177
|
+
throw new TypeError("expected GeoJSON Polygon or MultiPolygon");
|
|
178
|
+
}
|
|
179
|
+
const polygons = boundary.type === "Polygon" ? [boundary.coordinates] : boundary.coordinates;
|
|
180
|
+
if (!polygons.length) throw new TypeError("boundary must not be empty");
|
|
181
|
+
let vertices = 0;
|
|
182
|
+
for (const rings of polygons) {
|
|
183
|
+
if (!Array.isArray(rings) || !rings.length) throw new TypeError("polygon needs an exterior ring");
|
|
184
|
+
for (const ring of rings) {
|
|
185
|
+
if (!Array.isArray(ring) || ring.length < 4) throw new TypeError("rings need at least four coordinates");
|
|
186
|
+
vertices += ring.length;
|
|
187
|
+
if (vertices > 1e5) throw new RangeError("boundary exceeds 100000 vertices");
|
|
188
|
+
let area = 0;
|
|
189
|
+
for (let i = 0; i < ring.length; i++) {
|
|
190
|
+
const coordinate = ring[i];
|
|
191
|
+
if (!Array.isArray(coordinate) || coordinate.length !== 2) throw new TypeError("coordinates must be [longitude, latitude]");
|
|
192
|
+
validatePosition({ lon: coordinate[0], lat: coordinate[1] });
|
|
193
|
+
if (i) {
|
|
194
|
+
const previous = ring[i - 1];
|
|
195
|
+
if (Math.abs(coordinate[0] - previous[0]) > 180) throw new RangeError("split antimeridian-crossing polygons into a MultiPolygon");
|
|
196
|
+
area += previous[0] * coordinate[1] - coordinate[0] * previous[1];
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (ring[0][0] !== ring[ring.length - 1][0] || ring[0][1] !== ring[ring.length - 1][1]) throw new TypeError("rings must be closed");
|
|
200
|
+
if (area === 0) throw new TypeError("rings must have nonzero area");
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
function validateRegion(region) {
|
|
205
|
+
if (region?.type === "Circle") {
|
|
206
|
+
validatePosition(region.center);
|
|
207
|
+
validateRadius(region.radiusMeters);
|
|
208
|
+
} else validateBoundary(region);
|
|
209
|
+
}
|
|
210
|
+
function polygonContains(boundary, position) {
|
|
211
|
+
const polygons = boundary.type === "Polygon" ? [boundary.coordinates] : boundary.coordinates;
|
|
212
|
+
if (Math.abs(position.lat) === 90) {
|
|
213
|
+
return polygons.some((rings) => rings[0].some((coordinate) => coordinate[1] === position.lat));
|
|
214
|
+
}
|
|
215
|
+
const candidates = Math.abs(position.lon) === 180 ? [-180, 180] : [position.lon];
|
|
216
|
+
return candidates.some((lon) => polygons.some((rings) => inPolygon([lon, position.lat], rings)));
|
|
217
|
+
}
|
|
218
|
+
function containsPosition(region, position) {
|
|
219
|
+
validateRegion(region);
|
|
220
|
+
validatePosition(position);
|
|
221
|
+
return region.type === "Circle" ? region.radiusMeters === 0 ? distanceMeters(region.center, position) === 0 : distanceMeters(region.center, position) <= region.radiusMeters + 1e-6 : polygonContains(region, position);
|
|
222
|
+
}
|
|
223
|
+
function trigExtrema(a, b, low, high) {
|
|
224
|
+
const values = [a * Math.sin(low) + b * Math.cos(low), a * Math.sin(high) + b * Math.cos(high)];
|
|
225
|
+
const stationary = Math.atan2(a, b);
|
|
226
|
+
for (let k = -2; k <= 2; k++) {
|
|
227
|
+
const angle = stationary + k * Math.PI;
|
|
228
|
+
if (angle >= low && angle <= high) values.push(a * Math.sin(angle) + b * Math.cos(angle));
|
|
229
|
+
}
|
|
230
|
+
return [Math.min(...values), Math.max(...values)];
|
|
231
|
+
}
|
|
232
|
+
function cosineExtrema(low, high) {
|
|
233
|
+
const values = [Math.cos(low), Math.cos(high)];
|
|
234
|
+
for (let k = -2; k <= 2; k++) {
|
|
235
|
+
const angle = k * Math.PI;
|
|
236
|
+
if (angle >= low && angle <= high) values.push(Math.cos(angle));
|
|
237
|
+
}
|
|
238
|
+
return [Math.min(...values), Math.max(...values)];
|
|
239
|
+
}
|
|
240
|
+
function circleRelation(region, bounds) {
|
|
241
|
+
if (region.radiusMeters === Math.PI * EARTH_RADIUS_METERS) return "inside";
|
|
242
|
+
const lat = region.center.lat * RAD;
|
|
243
|
+
const [minCos, maxCos] = cosineExtrema((bounds.west - region.center.lon) * RAD, (bounds.east - region.center.lon) * RAD);
|
|
244
|
+
const [minDot] = trigExtrema(Math.sin(lat), Math.cos(lat) * minCos, bounds.south * RAD, bounds.north * RAD);
|
|
245
|
+
const [, maxDot] = trigExtrema(Math.sin(lat), Math.cos(lat) * maxCos, bounds.south * RAD, bounds.north * RAD);
|
|
246
|
+
const threshold = Math.cos(Math.min(Math.PI, (region.radiusMeters + 1e-6) / EARTH_RADIUS_METERS));
|
|
247
|
+
if (maxDot < threshold - 1e-14) return "outside";
|
|
248
|
+
if (minDot > threshold + 1e-14) return "inside";
|
|
249
|
+
return "partial";
|
|
250
|
+
}
|
|
251
|
+
function polygonRelation(boundary, bounds) {
|
|
252
|
+
const corners = [[bounds.west, bounds.south], [bounds.east, bounds.south], [bounds.east, bounds.north], [bounds.west, bounds.north]];
|
|
253
|
+
const polygons = boundary.type === "Polygon" ? [boundary.coordinates] : boundary.coordinates;
|
|
254
|
+
let intersects = false;
|
|
255
|
+
for (const rings of polygons) {
|
|
256
|
+
for (const ring of rings) {
|
|
257
|
+
for (let i = 1; i < ring.length; i++) {
|
|
258
|
+
const a = ring[i - 1], b = ring[i];
|
|
259
|
+
if (a[0] >= bounds.west && a[0] <= bounds.east && a[1] >= bounds.south && a[1] <= bounds.north) intersects = true;
|
|
260
|
+
for (let edge = 0; edge < 4; edge++) {
|
|
261
|
+
if (segmentsIntersect(a, b, corners[edge], corners[(edge + 1) % 4])) intersects = true;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
const inside = corners.map(([lon, lat]) => polygonContains(boundary, { lon, lat }));
|
|
267
|
+
if (intersects) return "partial";
|
|
268
|
+
if (inside.every(Boolean)) return "inside";
|
|
269
|
+
return inside.some(Boolean) ? "partial" : "outside";
|
|
270
|
+
}
|
|
271
|
+
function classifyCell(region, bounds) {
|
|
272
|
+
return region.type === "Circle" ? circleRelation(region, bounds) : polygonRelation(region, bounds);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// src/cover.ts
|
|
276
|
+
var CoverLimitError = class extends RangeError {
|
|
277
|
+
constructor(limit, maximum) {
|
|
278
|
+
super(`geohash cover exceeds ${limit}=${maximum}; reduce precision or increase the explicit budget`);
|
|
279
|
+
this.limit = limit;
|
|
280
|
+
this.maximum = maximum;
|
|
281
|
+
this.name = "CoverLimitError";
|
|
282
|
+
}
|
|
283
|
+
limit;
|
|
284
|
+
maximum;
|
|
285
|
+
};
|
|
286
|
+
function positiveInteger(value, name) {
|
|
287
|
+
if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${name} must be a positive safe integer`);
|
|
288
|
+
return value;
|
|
289
|
+
}
|
|
290
|
+
function coverRegion(region, options = {}) {
|
|
291
|
+
const precision = options.precision ?? 6;
|
|
292
|
+
const maxCells = positiveInteger(options.maxCells ?? 2048, "maxCells");
|
|
293
|
+
const maxVisited = positiveInteger(options.maxVisited ?? 1e5, "maxVisited");
|
|
294
|
+
validatePrecision(precision);
|
|
295
|
+
validateRegion(region);
|
|
296
|
+
if (region.type === "Circle" && region.radiusMeters === 0) return [encodeGeohash(region.center, precision)];
|
|
297
|
+
let visited = 0;
|
|
298
|
+
function visit(hash) {
|
|
299
|
+
if (++visited > maxVisited) throw new CoverLimitError("maxVisited", maxVisited);
|
|
300
|
+
const relation = classifyCell(region, decodeGeohash(hash));
|
|
301
|
+
if (relation === "outside") return [];
|
|
302
|
+
if (relation === "inside" || hash.length === precision) return [hash];
|
|
303
|
+
const result = [...GEOHASH_ALPHABET].flatMap((char) => visit(hash + char));
|
|
304
|
+
if (result.length === 32 && result.every((cell) => cell.length === hash.length + 1)) return [hash];
|
|
305
|
+
return result;
|
|
306
|
+
}
|
|
307
|
+
const cells = visit("");
|
|
308
|
+
if (cells.length > maxCells) throw new CoverLimitError("maxCells", maxCells);
|
|
309
|
+
return cells;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// src/routing.ts
|
|
313
|
+
function identifier(value, name) {
|
|
314
|
+
if (typeof value !== "string" || !/^[A-Za-z0-9_-]{1,80}$/.test(value)) {
|
|
315
|
+
throw new TypeError(`${name} must contain 1\u201380 ASCII letters, digits, underscores or hyphens`);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
function validateJson(value, depth = 0, seen = /* @__PURE__ */ new Set()) {
|
|
319
|
+
if (depth > 64) throw new RangeError("data exceeds 64 nesting levels");
|
|
320
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return;
|
|
321
|
+
if (typeof value === "number" && Number.isFinite(value)) return;
|
|
322
|
+
if (typeof value !== "object" || seen.has(value)) throw new TypeError("data must be finite, acyclic JSON");
|
|
323
|
+
if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
|
|
324
|
+
throw new TypeError("data must contain only plain JSON objects");
|
|
325
|
+
}
|
|
326
|
+
seen.add(value);
|
|
327
|
+
for (const item of Array.isArray(value) ? value : Object.values(value)) validateJson(item, depth + 1, seen);
|
|
328
|
+
seen.delete(value);
|
|
329
|
+
}
|
|
330
|
+
function validateEvent(event) {
|
|
331
|
+
if (!event || event.protocol !== "geontfy/1") throw new TypeError("unsupported event protocol");
|
|
332
|
+
identifier(event.namespace, "namespace");
|
|
333
|
+
identifier(event.topicId, "topicId");
|
|
334
|
+
if (typeof event.id !== "string" || event.id.length < 1 || event.id.length > 256) throw new TypeError("id must contain 1\u2013256 characters");
|
|
335
|
+
validatePrecision(event.precision);
|
|
336
|
+
if (!["publisher-region", "subscriber-region"].includes(event.mode)) throw new TypeError("invalid routing mode");
|
|
337
|
+
normalizePosition(event.position);
|
|
338
|
+
validateRadius(event.radiusMeters);
|
|
339
|
+
if (event.mode === "subscriber-region" && event.radiusMeters !== 0) throw new TypeError("subscriber-region events must be points");
|
|
340
|
+
validateJson(event.data);
|
|
341
|
+
}
|
|
342
|
+
function snapshot(value) {
|
|
343
|
+
return JSON.parse(JSON.stringify(value));
|
|
344
|
+
}
|
|
345
|
+
function createGeontfy(options = {}) {
|
|
346
|
+
const precision = options.precision ?? 6;
|
|
347
|
+
const mode = options.mode ?? "publisher-region";
|
|
348
|
+
const namespace = options.namespace ?? "geontfy";
|
|
349
|
+
const maxTopics = positiveInteger(options.maxTopics ?? 2e3, "maxTopics");
|
|
350
|
+
const coverOptions = { precision, maxCells: options.maxCells, maxVisited: options.maxVisited };
|
|
351
|
+
const boundaryProvider = options.boundaryProvider;
|
|
352
|
+
validatePrecision(precision);
|
|
353
|
+
identifier(namespace, "namespace");
|
|
354
|
+
if (!["publisher-region", "subscriber-region"].includes(mode)) throw new TypeError("invalid routing mode");
|
|
355
|
+
positiveInteger(options.maxCells ?? 2048, "maxCells");
|
|
356
|
+
positiveInteger(options.maxVisited ?? 1e5, "maxVisited");
|
|
357
|
+
function topics(topicId, cells) {
|
|
358
|
+
identifier(topicId, "topicId");
|
|
359
|
+
const result = cells.map((cell) => `${namespace}.v1.${mode}.p${precision}.${topicId}.${cell || "world"}`);
|
|
360
|
+
if (result.length > maxTopics) throw new RangeError(`plan exceeds maxTopics=${maxTopics}`);
|
|
361
|
+
return result;
|
|
362
|
+
}
|
|
363
|
+
function subscribe(topicId, target) {
|
|
364
|
+
identifier(topicId, "topicId");
|
|
365
|
+
let normalized;
|
|
366
|
+
let cells;
|
|
367
|
+
if (mode === "publisher-region") {
|
|
368
|
+
if ("type" in target) throw new TypeError("publisher-region subscribers must provide a position");
|
|
369
|
+
normalized = normalizePosition(target);
|
|
370
|
+
cells = ancestors(encodeGeohash(normalized, precision));
|
|
371
|
+
} else {
|
|
372
|
+
if (!("type" in target)) throw new TypeError("subscriber-region subscribers must provide a Circle, Polygon or MultiPolygon");
|
|
373
|
+
validateRegion(target);
|
|
374
|
+
normalized = snapshot(target);
|
|
375
|
+
cells = coverRegion(normalized, coverOptions);
|
|
376
|
+
}
|
|
377
|
+
return { namespace, precision, mode, topicId, target: normalized, cells, topics: topics(topicId, cells) };
|
|
378
|
+
}
|
|
379
|
+
function publish(input) {
|
|
380
|
+
const event = {
|
|
381
|
+
protocol: "geontfy/1",
|
|
382
|
+
namespace,
|
|
383
|
+
precision,
|
|
384
|
+
mode,
|
|
385
|
+
id: input.id,
|
|
386
|
+
topicId: input.topicId,
|
|
387
|
+
position: normalizePosition(input.position),
|
|
388
|
+
radiusMeters: input.radiusMeters ?? 0,
|
|
389
|
+
data: input.data
|
|
390
|
+
};
|
|
391
|
+
validateEvent(event);
|
|
392
|
+
const cells = mode === "publisher-region" ? coverRegion(circle(event.position, event.radiusMeters), coverOptions) : ancestors(encodeGeohash(event.position, precision));
|
|
393
|
+
return { cells, topics: topics(event.topicId, cells), event: snapshot(event) };
|
|
394
|
+
}
|
|
395
|
+
async function lookupBoundary(osmId) {
|
|
396
|
+
if (!boundaryProvider) throw new Error("configure boundaryProvider to resolve OSM boundaries");
|
|
397
|
+
const boundary = await boundaryProvider.lookup(osmId);
|
|
398
|
+
validateRegion(boundary);
|
|
399
|
+
return snapshot(boundary);
|
|
400
|
+
}
|
|
401
|
+
return { subscribe, publish, lookupBoundary };
|
|
402
|
+
}
|
|
403
|
+
function matchesSubscription(subscription, event) {
|
|
404
|
+
validateEvent(event);
|
|
405
|
+
if (subscription.namespace !== event.namespace || subscription.precision !== event.precision || subscription.mode !== event.mode || subscription.topicId !== event.topicId) return false;
|
|
406
|
+
if (subscription.mode === "publisher-region") {
|
|
407
|
+
if ("type" in subscription.target) throw new TypeError("invalid point subscription");
|
|
408
|
+
return containsPosition(circle(event.position, event.radiusMeters), subscription.target);
|
|
409
|
+
}
|
|
410
|
+
if (!("type" in subscription.target)) throw new TypeError("invalid region subscription");
|
|
411
|
+
return containsPosition(subscription.target, event.position);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// src/receiver.ts
|
|
415
|
+
function createMemoryDedupe(options = {}) {
|
|
416
|
+
const ttlMs = positiveInteger(options.ttlMs ?? 864e5, "ttlMs");
|
|
417
|
+
const maxEntries = positiveInteger(options.maxEntries ?? 1e4, "maxEntries");
|
|
418
|
+
const now = options.now ?? Date.now;
|
|
419
|
+
const entries = /* @__PURE__ */ new Map();
|
|
420
|
+
return {
|
|
421
|
+
claim(key) {
|
|
422
|
+
const time = now();
|
|
423
|
+
for (const [id, expires] of entries) {
|
|
424
|
+
if (expires <= time) entries.delete(id);
|
|
425
|
+
}
|
|
426
|
+
if (entries.has(key)) return false;
|
|
427
|
+
if (entries.size >= maxEntries) entries.delete(entries.keys().next().value);
|
|
428
|
+
entries.set(key, time + ttlMs);
|
|
429
|
+
return true;
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
function createReceiver(options = {}) {
|
|
434
|
+
const dedupe = options.dedupe ?? createMemoryDedupe();
|
|
435
|
+
return {
|
|
436
|
+
async accept(subscription, event) {
|
|
437
|
+
if (!matchesSubscription(subscription, event)) return false;
|
|
438
|
+
return dedupe.claim(JSON.stringify([event.namespace, event.mode, event.topicId, event.id]));
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// src/transport.ts
|
|
444
|
+
async function dispatch(plan, transport) {
|
|
445
|
+
const result = { succeeded: [], failed: [] };
|
|
446
|
+
for (const topic of new Set(plan.topics)) {
|
|
447
|
+
try {
|
|
448
|
+
await transport.publish(topic, plan.event);
|
|
449
|
+
result.succeeded.push(topic);
|
|
450
|
+
} catch (error) {
|
|
451
|
+
result.failed.push({ topic, error });
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
return result;
|
|
455
|
+
}
|
|
456
|
+
function subscriptionDiff(previous, next) {
|
|
457
|
+
const before = new Set(previous), after = new Set(next);
|
|
458
|
+
return {
|
|
459
|
+
subscribe: [...after].filter((topic) => !before.has(topic)),
|
|
460
|
+
unsubscribe: [...before].filter((topic) => !after.has(topic))
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
async function reconcileSubscriptions(previous, next, transport) {
|
|
464
|
+
const desired = "topics" in next ? next.topics : next;
|
|
465
|
+
const changes = subscriptionDiff(previous, desired);
|
|
466
|
+
const active = new Set(previous);
|
|
467
|
+
const failed = [];
|
|
468
|
+
for (const topic of changes.subscribe) {
|
|
469
|
+
try {
|
|
470
|
+
await transport.subscribe(topic);
|
|
471
|
+
active.add(topic);
|
|
472
|
+
} catch (error) {
|
|
473
|
+
failed.push({ topic, error, operation: "subscribe" });
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
if (!failed.length) {
|
|
477
|
+
for (const topic of changes.unsubscribe) {
|
|
478
|
+
try {
|
|
479
|
+
await transport.unsubscribe(topic);
|
|
480
|
+
active.delete(topic);
|
|
481
|
+
} catch (error) {
|
|
482
|
+
failed.push({ topic, error, operation: "unsubscribe" });
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return { active: [...active], failed };
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// src/fcm.ts
|
|
490
|
+
function toFcmMessage(topic, event) {
|
|
491
|
+
validateEvent(event);
|
|
492
|
+
if (!/^[a-zA-Z0-9\-_.~%]{1,900}$/.test(topic)) throw new TypeError("invalid FCM topic");
|
|
493
|
+
const data = { geontfy: JSON.stringify(event) };
|
|
494
|
+
if (new TextEncoder().encode(JSON.stringify(data)).byteLength > 2048) {
|
|
495
|
+
throw new RangeError("FCM topic data exceeds the conservative 2048-byte budget; send a reference to larger content");
|
|
496
|
+
}
|
|
497
|
+
return { topic, data };
|
|
498
|
+
}
|
|
499
|
+
function fromFcmData(data) {
|
|
500
|
+
if (typeof data.geontfy !== "string" || new TextEncoder().encode(data.geontfy).byteLength > 2048) {
|
|
501
|
+
throw new TypeError("missing or oversized geontfy data");
|
|
502
|
+
}
|
|
503
|
+
const event = JSON.parse(data.geontfy);
|
|
504
|
+
validateEvent(event);
|
|
505
|
+
return event;
|
|
506
|
+
}
|
|
507
|
+
function createFcmTransport(send) {
|
|
508
|
+
return { publish: (topic, event) => send(toFcmMessage(topic, event)) };
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// src/osm.ts
|
|
512
|
+
function createNominatimProvider(options) {
|
|
513
|
+
const base = new URL(options.endpoint.endsWith("/") ? options.endpoint : `${options.endpoint}/`);
|
|
514
|
+
if (!["http:", "https:"].includes(base.protocol) || base.username || base.password || base.search || base.hash) {
|
|
515
|
+
throw new TypeError("endpoint must be an HTTP(S) base URL without credentials, query or fragment");
|
|
516
|
+
}
|
|
517
|
+
if (!options.userAgent?.trim()) throw new TypeError("userAgent must identify your application and contact information");
|
|
518
|
+
const interval = options.minIntervalMs ?? 1e3;
|
|
519
|
+
if (!Number.isFinite(interval) || interval < 0) throw new RangeError("minIntervalMs must be nonnegative");
|
|
520
|
+
if (base.hostname === "nominatim.openstreetmap.org" && interval < 1e3) throw new RangeError("public Nominatim permits at most one request per second");
|
|
521
|
+
const timeout = positiveInteger(options.timeoutMs ?? 1e4, "timeoutMs");
|
|
522
|
+
const ttl = positiveInteger(options.cacheTtlMs ?? 864e5, "cacheTtlMs");
|
|
523
|
+
const maxEntries = positiveInteger(options.maxCacheEntries ?? 100, "maxCacheEntries");
|
|
524
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
525
|
+
const headers = { ...options.headers, "User-Agent": options.userAgent, Accept: "application/json" };
|
|
526
|
+
const cache = /* @__PURE__ */ new Map();
|
|
527
|
+
const pending = /* @__PURE__ */ new Map();
|
|
528
|
+
let tail = Promise.resolve();
|
|
529
|
+
let lastStart = 0;
|
|
530
|
+
const clone = (value) => JSON.parse(JSON.stringify(value));
|
|
531
|
+
async function request(osmId) {
|
|
532
|
+
const wait = Math.max(0, lastStart + interval - Date.now());
|
|
533
|
+
if (wait) await new Promise((resolve) => setTimeout(resolve, wait));
|
|
534
|
+
lastStart = Date.now();
|
|
535
|
+
const url = new URL("lookup", base);
|
|
536
|
+
url.search = new URLSearchParams({ osm_ids: osmId, format: "jsonv2", polygon_geojson: "1" }).toString();
|
|
537
|
+
const controller = new AbortController();
|
|
538
|
+
const timer = setTimeout(() => controller.abort(), timeout);
|
|
539
|
+
try {
|
|
540
|
+
const response = await fetcher(url, { headers, signal: controller.signal });
|
|
541
|
+
if (!response.ok) throw new Error(`boundary lookup failed with HTTP ${response.status}`);
|
|
542
|
+
const body = await response.json();
|
|
543
|
+
if (!Array.isArray(body) || body.length !== 1) throw new Error(`no unique boundary found for ${osmId}`);
|
|
544
|
+
const item = body[0];
|
|
545
|
+
if (item.osm_type !== (osmId[0] === "R" ? "relation" : "way") || String(item.osm_id) !== osmId.slice(1)) {
|
|
546
|
+
throw new Error("boundary response does not match requested OSM object");
|
|
547
|
+
}
|
|
548
|
+
validateBoundary(item.geojson);
|
|
549
|
+
const boundary = clone(item.geojson);
|
|
550
|
+
if (cache.size >= maxEntries) cache.delete(cache.keys().next().value);
|
|
551
|
+
cache.set(osmId, { expires: Date.now() + ttl, boundary });
|
|
552
|
+
return boundary;
|
|
553
|
+
} finally {
|
|
554
|
+
clearTimeout(timer);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
return {
|
|
558
|
+
async lookup(osmId) {
|
|
559
|
+
if (!/^[RW][1-9]\d*$/.test(osmId)) throw new TypeError("osmId must be a way or relation ID, such as R12345");
|
|
560
|
+
const cached = cache.get(osmId);
|
|
561
|
+
if (cached && cached.expires > Date.now()) return clone(cached.boundary);
|
|
562
|
+
let operation = pending.get(osmId);
|
|
563
|
+
if (!operation) {
|
|
564
|
+
operation = tail.then(() => request(osmId));
|
|
565
|
+
pending.set(osmId, operation);
|
|
566
|
+
tail = operation.then(() => void 0, () => void 0);
|
|
567
|
+
}
|
|
568
|
+
try {
|
|
569
|
+
return clone(await operation);
|
|
570
|
+
} finally {
|
|
571
|
+
pending.delete(osmId);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
// shared/coverage.js
|
|
578
|
+
var R = 63710088e-1;
|
|
579
|
+
var RAD2 = Math.PI / 180;
|
|
580
|
+
function coverBoundedCircle(core2, region, options = {}) {
|
|
581
|
+
const precision = options.precision ?? 9;
|
|
582
|
+
const maxSpillRatio = options.maxSpillRatio ?? 0.2;
|
|
583
|
+
const maxOvershootRatio = options.maxOvershootRatio ?? 0.25;
|
|
584
|
+
const maxCells = options.maxCells ?? 512;
|
|
585
|
+
core2.circle(region.center, region.radiusMeters);
|
|
586
|
+
if (!Number.isInteger(precision) || precision < 1 || precision > 12 || !Number.isInteger(maxCells) || maxCells < 1 || !Number.isFinite(maxSpillRatio) || maxSpillRatio < 0 || maxSpillRatio > 1 || !Number.isFinite(maxOvershootRatio) || maxOvershootRatio < 0 || maxOvershootRatio > 1) {
|
|
587
|
+
throw new RangeError("Invalid bounded cover options.");
|
|
588
|
+
}
|
|
589
|
+
if (region.radiusMeters === 0) throw new RangeError("Bounded circle covering requires a positive radius.");
|
|
590
|
+
const area = (hash) => {
|
|
591
|
+
const b = core2.decodeGeohash(hash);
|
|
592
|
+
return R * R * (b.east - b.west) * RAD2 * (Math.sin(b.north * RAD2) - Math.sin(b.south * RAD2));
|
|
593
|
+
};
|
|
594
|
+
const circleArea = 4 * Math.PI * R * R * Math.sin(region.radiusMeters / (2 * R)) ** 2;
|
|
595
|
+
const budget = circleArea * (1 + maxSpillRatio);
|
|
596
|
+
const expanded = core2.circle(region.center, Math.min(Math.PI * R, region.radiusMeters * (1 + maxOvershootRatio)));
|
|
597
|
+
const withinReach = (hash) => core2.classifyCell(expanded, core2.decodeGeohash(hash)) === "inside";
|
|
598
|
+
let cells = [], totalArea = 0, usedPrecision = 0;
|
|
599
|
+
for (let depth = Math.min(6, precision); depth <= precision; depth++) {
|
|
600
|
+
cells = core2.coverRegion(region, { precision: depth, maxCells: 2e4, maxVisited: 3e5 });
|
|
601
|
+
totalArea = cells.reduce((sum, hash) => sum + area(hash), 0);
|
|
602
|
+
usedPrecision = depth;
|
|
603
|
+
if (totalArea <= budget && cells.every(withinReach)) break;
|
|
604
|
+
if (depth === precision) throw new RangeError("Cannot meet spill and distance limits at this precision. Increase precision or radius.");
|
|
605
|
+
}
|
|
606
|
+
const baselineCells = cells.length;
|
|
607
|
+
while (true) {
|
|
608
|
+
const candidates = /* @__PURE__ */ new Map();
|
|
609
|
+
for (const hash of cells) {
|
|
610
|
+
const cellArea = area(hash);
|
|
611
|
+
for (let length = 0; length < hash.length; length++) {
|
|
612
|
+
const parent = hash.slice(0, length);
|
|
613
|
+
const entry = candidates.get(parent) ?? { count: 0, area: 0 };
|
|
614
|
+
entry.count++;
|
|
615
|
+
entry.area += cellArea;
|
|
616
|
+
candidates.set(parent, entry);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
let best;
|
|
620
|
+
for (const [parent, children] of candidates) {
|
|
621
|
+
if (children.count < 2) continue;
|
|
622
|
+
const added = Math.max(0, area(parent) - children.area);
|
|
623
|
+
if (totalArea + added > budget || !withinReach(parent)) continue;
|
|
624
|
+
const score = added / (children.count - 1);
|
|
625
|
+
if (!best || score < best.score || score === best.score && parent < best.parent) best = { parent, added, score };
|
|
626
|
+
}
|
|
627
|
+
if (!best) break;
|
|
628
|
+
cells = cells.filter((hash) => !hash.startsWith(best.parent));
|
|
629
|
+
cells.push(best.parent);
|
|
630
|
+
totalArea += best.added;
|
|
631
|
+
}
|
|
632
|
+
if (cells.length > maxCells) throw new RangeError(`Bounded cover exceeds ${maxCells} cells without violating spill limits.`);
|
|
633
|
+
return { cells: cells.sort(), circleArea, coveredArea: totalArea, spillRatio: Math.max(0, totalArea / circleArea - 1), usedPrecision, baselineCells };
|
|
634
|
+
}
|
|
635
|
+
function createBoundedGeontfy(core2, options = {}) {
|
|
636
|
+
const precision = options.precision ?? 9;
|
|
637
|
+
const geo = core2.createGeontfy({ precision, maxTopics: options.maxCells ?? 512 });
|
|
638
|
+
return {
|
|
639
|
+
...geo,
|
|
640
|
+
publish(input) {
|
|
641
|
+
const point = geo.publish({ ...input, radiusMeters: 0 });
|
|
642
|
+
const radiusMeters = input.radiusMeters ?? 0;
|
|
643
|
+
const coverage = coverBoundedCircle(core2, core2.circle(point.event.position, radiusMeters), { ...options, precision });
|
|
644
|
+
const prefix = geo.subscribe(input.topicId, point.event.position).topics[0].replace(/world$/, "");
|
|
645
|
+
return { cells: coverage.cells, topics: coverage.cells.map((hash) => prefix + (hash || "world")), event: { ...point.event, radiusMeters }, coverage };
|
|
646
|
+
}
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// src/bounded.ts
|
|
651
|
+
var core = { circle, classifyCell, decodeGeohash, coverRegion, createGeontfy };
|
|
652
|
+
var coverBoundedCircle2 = (region, options) => coverBoundedCircle(core, region, options);
|
|
653
|
+
var createBoundedGeontfy2 = (options) => createBoundedGeontfy(core, options);
|
|
654
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
655
|
+
0 && (module.exports = {
|
|
656
|
+
CoverLimitError,
|
|
657
|
+
EARTH_RADIUS_METERS,
|
|
658
|
+
GEOHASH_ALPHABET,
|
|
659
|
+
ancestors,
|
|
660
|
+
circle,
|
|
661
|
+
classifyCell,
|
|
662
|
+
containsPosition,
|
|
663
|
+
coverBoundedCircle,
|
|
664
|
+
coverRegion,
|
|
665
|
+
createBoundedGeontfy,
|
|
666
|
+
createFcmTransport,
|
|
667
|
+
createGeontfy,
|
|
668
|
+
createMemoryDedupe,
|
|
669
|
+
createNominatimProvider,
|
|
670
|
+
createReceiver,
|
|
671
|
+
decodeGeohash,
|
|
672
|
+
dispatch,
|
|
673
|
+
distanceMeters,
|
|
674
|
+
encodeGeohash,
|
|
675
|
+
fromFcmData,
|
|
676
|
+
matchesSubscription,
|
|
677
|
+
normalizePosition,
|
|
678
|
+
positiveInteger,
|
|
679
|
+
reconcileSubscriptions,
|
|
680
|
+
subscriptionDiff,
|
|
681
|
+
toFcmMessage,
|
|
682
|
+
validateBoundary,
|
|
683
|
+
validateEvent,
|
|
684
|
+
validatePosition,
|
|
685
|
+
validatePrecision,
|
|
686
|
+
validateRadius,
|
|
687
|
+
validateRegion
|
|
688
|
+
});
|