@osmix/shared 0.0.1 → 0.0.6

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 (125) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +49 -19
  3. package/dist/src/assert.d.ts +24 -0
  4. package/dist/src/assert.d.ts.map +1 -0
  5. package/dist/src/assert.js +28 -0
  6. package/dist/src/assert.js.map +1 -0
  7. package/dist/src/bbox-intersects.d.ts +15 -0
  8. package/dist/src/bbox-intersects.d.ts.map +1 -0
  9. package/dist/src/bbox-intersects.js +24 -0
  10. package/dist/src/bbox-intersects.js.map +1 -0
  11. package/dist/src/bytes-to-stream.d.ts +18 -0
  12. package/dist/src/bytes-to-stream.d.ts.map +1 -0
  13. package/dist/src/bytes-to-stream.js +25 -0
  14. package/dist/src/bytes-to-stream.js.map +1 -0
  15. package/dist/src/concat-bytes.d.ts +5 -0
  16. package/dist/src/concat-bytes.d.ts.map +1 -0
  17. package/dist/src/concat-bytes.js +14 -0
  18. package/dist/src/concat-bytes.js.map +1 -0
  19. package/dist/src/coordinates.d.ts +28 -0
  20. package/dist/src/coordinates.d.ts.map +1 -0
  21. package/dist/src/coordinates.js +38 -0
  22. package/dist/src/coordinates.js.map +1 -0
  23. package/dist/src/haversine-distance.d.ts +16 -0
  24. package/dist/src/haversine-distance.d.ts.map +1 -0
  25. package/dist/src/haversine-distance.js +26 -0
  26. package/dist/src/haversine-distance.js.map +1 -0
  27. package/dist/src/lineclip.d.ts +2 -0
  28. package/dist/src/lineclip.d.ts.map +1 -0
  29. package/dist/src/lineclip.js +3 -0
  30. package/dist/src/lineclip.js.map +1 -0
  31. package/dist/src/progress.d.ts +40 -0
  32. package/dist/src/progress.d.ts.map +1 -0
  33. package/dist/src/progress.js +40 -0
  34. package/dist/src/progress.js.map +1 -0
  35. package/dist/src/relation-kind.d.ts +69 -0
  36. package/dist/src/relation-kind.d.ts.map +1 -0
  37. package/dist/src/relation-kind.js +375 -0
  38. package/dist/src/relation-kind.js.map +1 -0
  39. package/dist/src/relation-multipolygon.d.ts +43 -0
  40. package/dist/src/relation-multipolygon.d.ts.map +1 -0
  41. package/dist/src/relation-multipolygon.js +195 -0
  42. package/dist/src/relation-multipolygon.js.map +1 -0
  43. package/dist/src/stream-to-bytes.d.ts +18 -0
  44. package/dist/src/stream-to-bytes.d.ts.map +1 -0
  45. package/dist/src/stream-to-bytes.js +30 -0
  46. package/dist/src/stream-to-bytes.js.map +1 -0
  47. package/dist/src/test/fixtures.d.ts +36 -0
  48. package/dist/src/test/fixtures.d.ts.map +1 -0
  49. package/dist/src/test/fixtures.js +172 -0
  50. package/dist/src/test/fixtures.js.map +1 -0
  51. package/dist/src/throttle.d.ts +25 -0
  52. package/dist/src/throttle.d.ts.map +1 -0
  53. package/dist/src/throttle.js +34 -0
  54. package/dist/src/throttle.js.map +1 -0
  55. package/dist/src/tile.d.ts +34 -0
  56. package/dist/src/tile.d.ts.map +1 -0
  57. package/dist/src/tile.js +72 -0
  58. package/dist/src/tile.js.map +1 -0
  59. package/dist/src/transform-bytes.d.ts +24 -0
  60. package/dist/src/transform-bytes.d.ts.map +1 -0
  61. package/dist/src/transform-bytes.js +28 -0
  62. package/dist/src/transform-bytes.js.map +1 -0
  63. package/dist/src/types.d.ts +99 -0
  64. package/dist/src/types.d.ts.map +1 -0
  65. package/dist/src/types.js +9 -0
  66. package/dist/src/types.js.map +1 -0
  67. package/dist/src/utils.d.ts +30 -0
  68. package/dist/src/utils.d.ts.map +1 -0
  69. package/dist/src/utils.js +70 -0
  70. package/dist/src/utils.js.map +1 -0
  71. package/dist/src/way-is-area.d.ts +24 -0
  72. package/dist/src/way-is-area.d.ts.map +1 -0
  73. package/dist/src/way-is-area.js +104 -0
  74. package/dist/src/way-is-area.js.map +1 -0
  75. package/dist/src/zigzag.d.ts +33 -0
  76. package/dist/src/zigzag.d.ts.map +1 -0
  77. package/dist/src/zigzag.js +40 -0
  78. package/dist/src/zigzag.js.map +1 -0
  79. package/dist/test/haversine-distance.test.d.ts +2 -0
  80. package/dist/test/haversine-distance.test.d.ts.map +1 -0
  81. package/dist/test/haversine-distance.test.js +8 -0
  82. package/dist/test/haversine-distance.test.js.map +1 -0
  83. package/dist/test/relation-kind.test.d.ts +2 -0
  84. package/dist/test/relation-kind.test.d.ts.map +1 -0
  85. package/dist/test/relation-kind.test.js +367 -0
  86. package/dist/test/relation-kind.test.js.map +1 -0
  87. package/dist/test/relation-multipolygon.test.d.ts +2 -0
  88. package/dist/test/relation-multipolygon.test.d.ts.map +1 -0
  89. package/dist/test/relation-multipolygon.test.js +237 -0
  90. package/dist/test/relation-multipolygon.test.js.map +1 -0
  91. package/dist/test/utils.test.d.ts +2 -0
  92. package/dist/test/utils.test.d.ts.map +1 -0
  93. package/dist/test/utils.test.js +76 -0
  94. package/dist/test/utils.test.js.map +1 -0
  95. package/dist/test/way-is-area.test.d.ts +2 -0
  96. package/dist/test/way-is-area.test.d.ts.map +1 -0
  97. package/dist/test/way-is-area.test.js +31 -0
  98. package/dist/test/way-is-area.test.js.map +1 -0
  99. package/package.json +9 -7
  100. package/src/assert.ts +21 -1
  101. package/src/bbox-intersects.ts +30 -0
  102. package/src/bytes-to-stream.ts +17 -0
  103. package/src/coordinates.ts +45 -0
  104. package/src/haversine-distance.ts +10 -1
  105. package/src/progress.ts +55 -0
  106. package/src/relation-kind.ts +446 -0
  107. package/src/relation-multipolygon.ts +225 -0
  108. package/src/stream-to-bytes.ts +17 -0
  109. package/src/test/fixtures.ts +18 -14
  110. package/src/throttle.ts +37 -0
  111. package/src/tile.ts +89 -0
  112. package/src/transform-bytes.ts +23 -0
  113. package/src/types.ts +93 -1
  114. package/src/utils.ts +79 -0
  115. package/src/way-is-area.ts +107 -0
  116. package/src/zigzag.ts +42 -0
  117. package/test/haversine-distance.test.ts +2 -2
  118. package/test/relation-kind.test.ts +426 -0
  119. package/test/relation-multipolygon.test.ts +265 -0
  120. package/test/utils.test.ts +103 -0
  121. package/test/way-is-area.test.ts +42 -0
  122. package/tsconfig/base.json +2 -0
  123. package/tsconfig/test.json +1 -0
  124. package/src/spherical-mercator.test.ts +0 -42
  125. package/src/spherical-mercator.ts +0 -42
@@ -0,0 +1,446 @@
1
+ /**
2
+ * Relation kind detection and geometry building.
3
+ *
4
+ * Determines the semantic type of OSM relations (area, line, point, logic, super)
5
+ * based on their type tag and member structure. Also provides utilities for
6
+ * building geometries from relation members.
7
+ *
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ LonLat,
13
+ OsmRelation,
14
+ OsmRelationMember,
15
+ OsmWay,
16
+ RelationKind,
17
+ RelationKindMetadata,
18
+ } from "./types"
19
+
20
+ /**
21
+ * Get the semantic kind of a relation based on its type tag.
22
+ * Based on [OSM relation documentation](https://wiki.openstreetmap.org/wiki/Relation):
23
+ * - Areas: multipolygon, boundary, site
24
+ * - Lines: route, waterway, multilinestring, canal
25
+ * - Points: multipoint
26
+ * - Logic: restriction, route_master, network, collection
27
+ * - [Super: relations that contain other relations](https://wiki.openstreetmap.org/wiki/Super-relation)
28
+ */
29
+ export function getRelationKind(relation: OsmRelation): RelationKind {
30
+ const typeTag = relation.tags?.["type"]
31
+ if (!typeTag || typeof typeTag !== "string") {
32
+ // If no type tag, check if it has relation members (super-relation)
33
+ if (relation.members.some((m) => m.type === "relation")) {
34
+ return "super"
35
+ }
36
+ // Default to logic for untyped relations
37
+ return "logic"
38
+ }
39
+
40
+ const normalizedType = typeTag.toLowerCase()
41
+
42
+ // Area relations
43
+ if (
44
+ normalizedType === "multipolygon" ||
45
+ normalizedType === "boundary" ||
46
+ normalizedType === "site"
47
+ ) {
48
+ return "area"
49
+ }
50
+
51
+ // Line relations
52
+ if (
53
+ normalizedType === "route" ||
54
+ normalizedType === "waterway" ||
55
+ normalizedType === "multilinestring" ||
56
+ normalizedType === "canal"
57
+ ) {
58
+ return "line"
59
+ }
60
+
61
+ // Point relations
62
+ if (normalizedType === "multipoint") {
63
+ return "point"
64
+ }
65
+
66
+ // Check for super-relation (has relation members)
67
+ if (relation.members.some((m) => m.type === "relation")) {
68
+ return "super"
69
+ }
70
+
71
+ // Default to logic for other types (restriction, route_master, network, collection, etc.)
72
+ return "logic"
73
+ }
74
+
75
+ /**
76
+ * Get metadata about a relation kind.
77
+ */
78
+ export function getRelationKindMetadata(
79
+ relation: OsmRelation,
80
+ ): RelationKindMetadata {
81
+ const kind = getRelationKind(relation)
82
+
83
+ switch (kind) {
84
+ case "area":
85
+ return {
86
+ kind: "area",
87
+ expectedRoles: ["outer", "inner"],
88
+ orderMatters: false,
89
+ description: "Area relation (multipolygon, boundary, site)",
90
+ }
91
+ case "line":
92
+ return {
93
+ kind: "line",
94
+ expectedRoles: undefined, // Routes can have various roles
95
+ orderMatters: true,
96
+ description: "Line relation (route, waterway, multilinestring)",
97
+ }
98
+ case "point":
99
+ return {
100
+ kind: "point",
101
+ expectedRoles: undefined,
102
+ orderMatters: false,
103
+ description: "Point relation (multipoint)",
104
+ }
105
+ case "super":
106
+ return {
107
+ kind: "super",
108
+ expectedRoles: undefined,
109
+ orderMatters: false,
110
+ description: "Super-relation (contains other relations)",
111
+ }
112
+ case "logic":
113
+ return {
114
+ kind: "logic",
115
+ expectedRoles: undefined,
116
+ orderMatters: false,
117
+ description:
118
+ "Logical relation (restriction, route_master, network, collection, etc.)",
119
+ }
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Check if a relation is an area relation.
125
+ */
126
+ export function isAreaRelation(relation: OsmRelation): boolean {
127
+ return getRelationKind(relation) === "area"
128
+ }
129
+
130
+ /**
131
+ * Check if a relation is a line relation.
132
+ */
133
+ export function isLineRelation(relation: OsmRelation): boolean {
134
+ return getRelationKind(relation) === "line"
135
+ }
136
+
137
+ /**
138
+ * Check if a relation is a point relation.
139
+ */
140
+ export function isPointRelation(relation: OsmRelation): boolean {
141
+ return getRelationKind(relation) === "point"
142
+ }
143
+
144
+ /**
145
+ * Check if a relation is a super-relation (contains other relations).
146
+ */
147
+ export function isSuperRelation(relation: OsmRelation): boolean {
148
+ return getRelationKind(relation) === "super"
149
+ }
150
+
151
+ /**
152
+ * Check if a relation is a logical relation (non-geometric).
153
+ */
154
+ export function isLogicRelation(relation: OsmRelation): boolean {
155
+ return getRelationKind(relation) === "logic"
156
+ }
157
+
158
+ /**
159
+ * Build MultiLineString geometry from a line relation by connecting way members.
160
+ * Orders way members using their refs and handles role-based reversal.
161
+ * Returns an array of LineString coordinates (each LineString is an array of LonLat).
162
+ */
163
+ export function buildRelationLineStrings(
164
+ relation: OsmRelation,
165
+ getWay: (wayId: number) => OsmWay | null,
166
+ getNodeCoordinates: (nodeId: number) => LonLat | undefined,
167
+ ): LonLat[][] {
168
+ const lineStrings: LonLat[][] = []
169
+ const wayMembers = relation.members.filter((m) => m.type === "way")
170
+
171
+ if (wayMembers.length === 0) return lineStrings
172
+
173
+ // Group ways by role if roles are used
174
+ const roleGroups = new Map<string, OsmRelationMember[]>()
175
+ for (const member of wayMembers) {
176
+ const role = member.role?.toLowerCase() ?? ""
177
+ if (!roleGroups.has(role)) {
178
+ roleGroups.set(role, [])
179
+ }
180
+ roleGroups.get(role)!.push(member)
181
+ }
182
+
183
+ // If no roles or single role group, process all ways together
184
+ const groupsToProcess =
185
+ roleGroups.size === 1 || !relation.members.some((m) => m.role)
186
+ ? [wayMembers]
187
+ : Array.from(roleGroups.values())
188
+
189
+ for (const group of groupsToProcess) {
190
+ // Try to connect ways into continuous linestrings
191
+ const connected = connectWaysToLineStrings(
192
+ group,
193
+ getWay,
194
+ getNodeCoordinates,
195
+ )
196
+ lineStrings.push(...connected)
197
+ }
198
+
199
+ return lineStrings
200
+ }
201
+
202
+ /**
203
+ * Connect ways that share endpoints to form continuous LineStrings.
204
+ * Returns an array of LineStrings (each is an array of LonLat coordinates).
205
+ */
206
+ function connectWaysToLineStrings(
207
+ wayMembers: OsmRelationMember[],
208
+ getWay: (wayId: number) => OsmWay | null,
209
+ getNodeCoordinates: (nodeId: number) => LonLat | undefined,
210
+ ): LonLat[][] {
211
+ if (wayMembers.length === 0) return []
212
+
213
+ const lineStrings: LonLat[][] = []
214
+ const used = new Set<number>()
215
+ const wayMap = new Map<number, OsmWay>()
216
+
217
+ // Build map of way ID to way
218
+ for (const member of wayMembers) {
219
+ const way = getWay(member.ref)
220
+ if (way) {
221
+ wayMap.set(member.ref, way)
222
+ }
223
+ }
224
+
225
+ // Build linestrings by connecting ways
226
+ for (const member of wayMembers) {
227
+ if (used.has(member.ref)) continue
228
+ const startWay = wayMap.get(member.ref)
229
+ if (!startWay || startWay.refs.length < 2) continue
230
+
231
+ const coords: LonLat[] = []
232
+ const currentWay = startWay
233
+ used.add(member.ref)
234
+
235
+ // Get coordinates for the starting way
236
+ for (const nodeId of currentWay.refs) {
237
+ const coord = getNodeCoordinates(nodeId)
238
+ if (coord) coords.push(coord)
239
+ }
240
+
241
+ // Try to extend forward
242
+ while (true) {
243
+ let found = false
244
+ const lastCoord = coords[coords.length - 1]
245
+ if (!lastCoord) break
246
+
247
+ for (const nextMember of wayMembers) {
248
+ if (used.has(nextMember.ref)) continue
249
+ const nextWay = wayMap.get(nextMember.ref)
250
+ if (!nextWay || nextWay.refs.length < 2) continue
251
+
252
+ const nextStart = getNodeCoordinates(nextWay.refs[0]!)
253
+ const nextEnd = getNodeCoordinates(
254
+ nextWay.refs[nextWay.refs.length - 1]!,
255
+ )
256
+
257
+ if (!nextStart || !nextEnd) continue
258
+
259
+ // Check if next way connects to current end
260
+ if (lastCoord[0] === nextStart[0] && lastCoord[1] === nextStart[1]) {
261
+ // Connect normally
262
+ for (let i = 1; i < nextWay.refs.length; i++) {
263
+ const nodeId = nextWay.refs[i]
264
+ if (nodeId === undefined) continue
265
+ const coord = getNodeCoordinates(nodeId)
266
+ if (coord) coords.push(coord)
267
+ }
268
+ used.add(nextMember.ref)
269
+ found = true
270
+ break
271
+ }
272
+ if (lastCoord[0] === nextEnd[0] && lastCoord[1] === nextEnd[1]) {
273
+ // Need to reverse next way
274
+ for (let i = nextWay.refs.length - 2; i >= 0; i--) {
275
+ const nodeId = nextWay.refs[i]
276
+ if (nodeId === undefined) continue
277
+ const coord = getNodeCoordinates(nodeId)
278
+ if (coord) coords.push(coord)
279
+ }
280
+ used.add(nextMember.ref)
281
+ found = true
282
+ break
283
+ }
284
+ }
285
+
286
+ if (!found) break
287
+ }
288
+
289
+ // Try to extend backward
290
+ while (true) {
291
+ let found = false
292
+ const firstCoord = coords[0]
293
+ if (!firstCoord) break
294
+
295
+ for (const prevMember of wayMembers) {
296
+ if (used.has(prevMember.ref)) continue
297
+ const prevWay = wayMap.get(prevMember.ref)
298
+ if (!prevWay || prevWay.refs.length < 2) continue
299
+
300
+ const prevStart = getNodeCoordinates(prevWay.refs[0]!)
301
+ const prevEnd = getNodeCoordinates(
302
+ prevWay.refs[prevWay.refs.length - 1]!,
303
+ )
304
+
305
+ if (!prevStart || !prevEnd) continue
306
+
307
+ // Check if prev way connects to current start
308
+ if (firstCoord[0] === prevEnd[0] && firstCoord[1] === prevEnd[1]) {
309
+ // Connect normally (prepend)
310
+ const newCoords: LonLat[] = []
311
+ for (let i = 0; i < prevWay.refs.length - 1; i++) {
312
+ const nodeId = prevWay.refs[i]
313
+ if (nodeId === undefined) continue
314
+ const coord = getNodeCoordinates(nodeId)
315
+ if (coord) newCoords.push(coord)
316
+ }
317
+ coords.unshift(...newCoords)
318
+ used.add(prevMember.ref)
319
+ found = true
320
+ break
321
+ }
322
+ if (firstCoord[0] === prevStart[0] && firstCoord[1] === prevStart[1]) {
323
+ // Need to reverse prev way (prepend reversed)
324
+ const newCoords: LonLat[] = []
325
+ for (let i = prevWay.refs.length - 1; i > 0; i--) {
326
+ const nodeId = prevWay.refs[i]
327
+ if (nodeId === undefined) continue
328
+ const coord = getNodeCoordinates(nodeId)
329
+ if (coord) newCoords.push(coord)
330
+ }
331
+ coords.unshift(...newCoords)
332
+ used.add(prevMember.ref)
333
+ found = true
334
+ break
335
+ }
336
+ }
337
+
338
+ if (!found) break
339
+ }
340
+
341
+ if (coords.length >= 2) {
342
+ lineStrings.push(coords)
343
+ }
344
+ }
345
+
346
+ return lineStrings
347
+ }
348
+
349
+ /**
350
+ * Collect point coordinates from a point relation.
351
+ * Returns an array of LonLat coordinates from node members.
352
+ */
353
+ export function collectRelationPoints(
354
+ relation: OsmRelation,
355
+ getNodeCoordinates: (nodeId: number) => LonLat | undefined,
356
+ ): LonLat[] {
357
+ const points: LonLat[] = []
358
+ for (const member of relation.members) {
359
+ if (member.type === "node") {
360
+ const coord = getNodeCoordinates(member.ref)
361
+ if (coord) {
362
+ points.push(coord)
363
+ }
364
+ }
365
+ }
366
+ return points
367
+ }
368
+
369
+ /**
370
+ * Resolve nested relation members, flattening the hierarchy with cycle detection.
371
+ * Returns all nodes, ways, and relations that are members (directly or indirectly).
372
+ * @param relation - The relation to resolve
373
+ * @param getRelation - Function to get a relation by ID
374
+ * @param maxDepth - Maximum recursion depth (default: 10)
375
+ * @param visited - Set of relation IDs already visited (for cycle detection)
376
+ */
377
+ export function resolveRelationMembers(
378
+ relation: OsmRelation,
379
+ getRelation: (relationId: number) => OsmRelation | null,
380
+ maxDepth = 10,
381
+ visited = new Set<number>(),
382
+ ): {
383
+ nodes: number[]
384
+ ways: number[]
385
+ relations: number[]
386
+ } {
387
+ const nodes = new Set<number>()
388
+ const ways = new Set<number>()
389
+ const relations = new Set<number>()
390
+
391
+ // Cycle detection or max depth reached
392
+ if (visited.has(relation.id) || maxDepth <= 0) {
393
+ return { nodes: [], ways: [], relations: [] }
394
+ }
395
+
396
+ visited.add(relation.id)
397
+
398
+ for (const member of relation.members) {
399
+ if (member.type === "node") {
400
+ if (!nodes.has(member.ref)) {
401
+ nodes.add(member.ref)
402
+ }
403
+ } else if (member.type === "way") {
404
+ if (!ways.has(member.ref)) {
405
+ ways.add(member.ref)
406
+ }
407
+ } else if (member.type === "relation") {
408
+ if (!relations.has(member.ref)) {
409
+ relations.add(member.ref)
410
+
411
+ // Recursively resolve nested relation
412
+ const nestedRelation = getRelation(member.ref)
413
+ if (nestedRelation) {
414
+ const nested = resolveRelationMembers(
415
+ nestedRelation,
416
+ getRelation,
417
+ maxDepth - 1,
418
+ visited,
419
+ )
420
+ // Merge nested results
421
+ for (const nodeId of nested.nodes) {
422
+ if (!nodes.has(nodeId)) {
423
+ nodes.add(nodeId)
424
+ }
425
+ }
426
+ for (const wayId of nested.ways) {
427
+ if (!ways.has(wayId)) {
428
+ ways.add(wayId)
429
+ }
430
+ }
431
+ for (const relId of nested.relations) {
432
+ if (!relations.has(relId)) {
433
+ relations.add(relId)
434
+ }
435
+ }
436
+ }
437
+ }
438
+ }
439
+ }
440
+
441
+ return {
442
+ nodes: Array.from(nodes),
443
+ ways: Array.from(ways),
444
+ relations: Array.from(relations),
445
+ }
446
+ }
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Multipolygon relation building utilities.
3
+ *
4
+ * Implements the OSM multipolygon relation specification to construct
5
+ * polygon geometries from way members. Handles outer/inner roles,
6
+ * way connection, and ring closure.
7
+ *
8
+ * @see https://wiki.openstreetmap.org/wiki/Relation:multipolygon
9
+ *
10
+ * @module
11
+ */
12
+
13
+ import type { LonLat, OsmRelation, OsmRelationMember, OsmWay } from "./types"
14
+
15
+ /**
16
+ * Get way members from a relation, grouped by role (outer/inner).
17
+ */
18
+ export function getWayMembersByRole(relation: OsmRelation): {
19
+ outer: OsmRelationMember[]
20
+ inner: OsmRelationMember[]
21
+ } {
22
+ const outer: OsmRelationMember[] = []
23
+ const inner: OsmRelationMember[] = []
24
+
25
+ for (const member of relation.members) {
26
+ if (member.type !== "way") continue
27
+ const role = member.role?.toLowerCase() ?? ""
28
+ if (role === "outer") {
29
+ outer.push(member)
30
+ } else if (role === "inner") {
31
+ inner.push(member)
32
+ }
33
+ }
34
+
35
+ return { outer, inner }
36
+ }
37
+
38
+ /**
39
+ * Connect ways that share endpoints to form a continuous ring.
40
+ * Returns an array of rings (each ring is an array of way IDs in order).
41
+ *
42
+ * This function handles:
43
+ * - Ways that are reversed (end matches end, or start matches start).
44
+ * - Closed ways (single ways that form a ring).
45
+ * - Disconnected chains (multiple independent rings).
46
+ */
47
+ export function connectWaysToRings(wayMembers: OsmWay[]): OsmWay[][] {
48
+ if (wayMembers.length === 0) return []
49
+
50
+ const rings: OsmWay[][] = []
51
+ const used = new Set<number>()
52
+ const wayMap = new Map<number, OsmWay>()
53
+
54
+ // Build map of way ID to member
55
+ for (const member of wayMembers) {
56
+ wayMap.set(member.id, member)
57
+ }
58
+
59
+ // Helper to reverse a way's refs
60
+ const reverseWay = (way: OsmWay): OsmWay => ({
61
+ ...way,
62
+ refs: [...way.refs].reverse(),
63
+ })
64
+
65
+ // Build rings by connecting ways
66
+ for (const startWay of wayMembers) {
67
+ if (used.has(startWay.id)) continue
68
+ if (startWay.refs.length < 2) throw Error("Way has less than 2 refs")
69
+
70
+ const ring: OsmWay[] = [startWay]
71
+ used.add(startWay.id)
72
+
73
+ let currentStart = startWay.refs[0]!
74
+ let currentEnd = startWay.refs[startWay.refs.length - 1]!
75
+
76
+ // Try to extend the ring forward
77
+ while (true) {
78
+ let found = false
79
+ for (const nextWay of wayMembers) {
80
+ if (used.has(nextWay.id)) continue
81
+ if (nextWay.refs.length < 2) throw Error("Way has less than 2 refs")
82
+ const nextStart = nextWay.refs[0]!
83
+ const nextEnd = nextWay.refs[nextWay.refs.length - 1]!
84
+
85
+ // Check if next way connects to current end
86
+ if (currentEnd === nextStart) {
87
+ ring.push(nextWay)
88
+ used.add(nextWay.id)
89
+ currentEnd = nextEnd
90
+ found = true
91
+ break
92
+ }
93
+ if (currentEnd === nextEnd) {
94
+ // Need to reverse next way
95
+ ring.push(reverseWay(nextWay))
96
+ used.add(nextWay.id)
97
+ currentEnd = nextStart
98
+ found = true
99
+ break
100
+ }
101
+ }
102
+
103
+ if (!found) break
104
+ }
105
+
106
+ // Try to extend the ring backward
107
+ currentStart = startWay.refs[0]!
108
+ currentEnd = startWay.refs[startWay.refs.length - 1]!
109
+
110
+ while (true) {
111
+ let found = false
112
+ for (const nextWay of wayMembers) {
113
+ if (used.has(nextWay.id)) continue
114
+ if (nextWay.refs.length < 2) throw Error("Way has less than 2 refs")
115
+
116
+ const nextStart = nextWay.refs[0]!
117
+ const nextEnd = nextWay.refs[nextWay.refs.length - 1]!
118
+
119
+ // Check if next way connects to current start
120
+ if (currentStart === nextEnd) {
121
+ ring.unshift(nextWay)
122
+ used.add(nextWay.id)
123
+ currentStart = nextStart
124
+ found = true
125
+ break
126
+ }
127
+ if (currentStart === nextStart) {
128
+ // Need to reverse next way
129
+ ring.unshift(reverseWay(nextWay))
130
+ used.add(nextWay.id)
131
+ currentStart = nextEnd
132
+ found = true
133
+ break
134
+ }
135
+ }
136
+
137
+ if (!found) break
138
+ }
139
+
140
+ // Only add ring if it's closed (first and last node are the same)
141
+ if (ring.length > 0) {
142
+ const firstWay = ring[0]
143
+ const lastWay = ring[ring.length - 1]
144
+ if (firstWay?.refs[0] === lastWay?.refs[lastWay.refs.length - 1]) {
145
+ rings.push(ring)
146
+ }
147
+ }
148
+ }
149
+
150
+ return rings
151
+ }
152
+
153
+ /**
154
+ * Build polygon rings from way members of a relation.
155
+ * Returns an array where each element is an array of coordinate rings (outer + inner).
156
+ *
157
+ * Based on OSM multipolygon relation specification:
158
+ * https://wiki.openstreetmap.org/wiki/Relation:multipolygon
159
+ *
160
+ * This implementation connects way members into closed rings, and then groups them
161
+ * into polygons. Currently, it associates all inner rings with every outer ring
162
+ * found in the relation, which is a simplification. A robust implementation would
163
+ * use point-in-polygon checks to strictly nest holes inside their parent outer ring.
164
+ */
165
+ export function buildRelationRings(
166
+ relation: OsmRelation,
167
+ getWay: (wayId: number) => OsmWay | null,
168
+ getNodeCoordinates: (nodeId: number) => LonLat | undefined,
169
+ ): LonLat[][][] {
170
+ const { outer, inner } = getWayMembersByRole(relation)
171
+
172
+ // Connect outer ways into rings
173
+ const outerRings = connectWaysToRings(
174
+ outer.map((m) => getWay(m.ref)).filter((w) => w !== null),
175
+ )
176
+ // Connect inner ways into rings
177
+ const innerRings = connectWaysToRings(
178
+ inner.map((m) => getWay(m.ref)).filter((w) => w !== null),
179
+ )
180
+
181
+ const wayRingToCoords = (ring: OsmWay[]): LonLat[] => {
182
+ const coords: LonLat[] = []
183
+ for (const way of ring) {
184
+ for (const nodeId of way.refs) {
185
+ const coord = getNodeCoordinates(nodeId)
186
+ if (coord) coords.push(coord)
187
+ }
188
+ }
189
+
190
+ // Ensure ring is closed
191
+ if (coords.length > 0) {
192
+ const first = coords[0]
193
+ const last = coords[coords.length - 1]
194
+ if (first && last && (first[0] !== last[0] || first[1] !== last[1])) {
195
+ coords.push([first[0], first[1]])
196
+ }
197
+ }
198
+ return coords
199
+ }
200
+
201
+ // Convert way rings to coordinate rings
202
+ const coordinateRings: LonLat[][][] = []
203
+
204
+ for (const outerRing of outerRings) {
205
+ const outerCoordinates: LonLat[] = wayRingToCoords(outerRing)
206
+
207
+ if (outerCoordinates.length >= 3) {
208
+ // Find inner rings that belong to this outer ring
209
+ const innerCoordinates: LonLat[][] = []
210
+ for (const innerRing of innerRings) {
211
+ const innerCoords: LonLat[] = wayRingToCoords(innerRing)
212
+
213
+ if (innerCoords.length >= 3) {
214
+ // TODO: do proper point-in-polygon test with https://github.com/rowanwins/point-in-polygon-hao
215
+ innerCoordinates.push(innerCoords)
216
+ }
217
+ }
218
+
219
+ // Create polygon: [outer ring, ...inner rings]
220
+ coordinateRings.push([outerCoordinates, ...innerCoordinates])
221
+ }
222
+ }
223
+
224
+ return coordinateRings
225
+ }
@@ -1,5 +1,22 @@
1
+ /**
2
+ * Stream to byte array conversion.
3
+ *
4
+ * Consumes a ReadableStream and concatenates all chunks into a single Uint8Array.
5
+ *
6
+ * @module
7
+ */
8
+
1
9
  import { concatBytes } from "./concat-bytes"
2
10
 
11
+ /**
12
+ * Consume a ReadableStream and return all data as a single Uint8Array.
13
+ *
14
+ * Reads all chunks from the stream and concatenates them.
15
+ * The stream will be fully consumed after this function returns.
16
+ *
17
+ * @param stream - The stream to consume.
18
+ * @returns A Promise resolving to the concatenated bytes.
19
+ */
3
20
  export async function streamToBytes(
4
21
  stream: ReadableStream<Uint8Array<ArrayBuffer>>,
5
22
  ): Promise<Uint8Array<ArrayBuffer>> {