@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
@@ -1,7 +1,4 @@
1
- import { createReadStream, createWriteStream } from "node:fs"
2
- import { readFile, writeFile } from "node:fs/promises"
3
1
  import { dirname, join, resolve } from "node:path"
4
- import { Readable, Writable } from "node:stream"
5
2
  import { fileURLToPath } from "node:url"
6
3
 
7
4
  const __dirname = dirname(fileURLToPath(import.meta.url))
@@ -20,29 +17,36 @@ export function getFixturePath(url: string) {
20
17
  /**
21
18
  * Get file from the cache folder or download it from the URL
22
19
  */
23
- export async function getFixtureFile(url: string): Promise<ArrayBuffer> {
20
+ export async function getFixtureFile(
21
+ url: string,
22
+ ): Promise<Uint8Array<ArrayBufferLike>> {
24
23
  const filePath = getFixturePath(url)
25
24
  try {
26
- const file = await readFile(filePath)
27
- return file.buffer as ArrayBuffer
25
+ const file = await Bun.file(filePath).arrayBuffer()
26
+ return new Uint8Array<ArrayBuffer>(file)
28
27
  } catch (_error) {
29
28
  const response = await fetch(url)
30
29
  const buffer = await response.arrayBuffer()
31
- await writeFile(filePath, new Uint8Array(buffer))
32
- return buffer
30
+ const data = new Uint8Array<ArrayBuffer>(buffer)
31
+ await Bun.write(filePath, data)
32
+ return data
33
33
  }
34
34
  }
35
35
 
36
36
  export function getFixtureFileReadStream(url: string) {
37
- return Readable.toWeb(
38
- createReadStream(getFixturePath(url)),
39
- ) as unknown as ReadableStream<ArrayBuffer>
37
+ return Bun.file(getFixturePath(url)).stream()
40
38
  }
41
39
 
42
40
  export function getFixtureFileWriteStream(url: string) {
43
- return Writable.toWeb(
44
- createWriteStream(getFixturePath(url)),
45
- ) as unknown as WritableStream<Uint8Array>
41
+ const incrementalWriter = Bun.file(getFixturePath(url)).writer()
42
+ return new WritableStream<Uint8Array<ArrayBufferLike>>({
43
+ write: (chunk: Uint8Array<ArrayBufferLike>) => {
44
+ incrementalWriter.write(chunk)
45
+ },
46
+ close: () => {
47
+ incrementalWriter.end()
48
+ },
49
+ })
46
50
  }
47
51
 
48
52
  export type PbfFixture = {
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Throttling utilities for rate-limiting function calls.
3
+ *
4
+ * Useful for limiting progress updates from workers or other high-frequency
5
+ * operations to avoid overwhelming the UI or logging.
6
+ *
7
+ * @module
8
+ */
9
+
10
+ /**
11
+ * Create a throttled version of a function that only executes at most
12
+ * once per `timeFrame` milliseconds.
13
+ *
14
+ * @param func - The function to throttle.
15
+ * @param timeFrame - Minimum time between calls in milliseconds.
16
+ * @returns A throttled version of the function.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * const logThrottled = throttle((msg) => console.log(msg), 1000)
21
+ * // Only logs at most once per second
22
+ * for (let i = 0; i < 1000; i++) logThrottled(`Progress: ${i}`)
23
+ * ```
24
+ */
25
+ export function throttle<T extends unknown[]>(
26
+ func: (...args: T) => void,
27
+ timeFrame: number,
28
+ ) {
29
+ let lastTime = 0
30
+ return (...args: T) => {
31
+ const now = Date.now()
32
+ if (now - lastTime >= timeFrame) {
33
+ func(...args)
34
+ lastTime = now
35
+ }
36
+ }
37
+ }
package/src/tile.ts ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * XYZ tile coordinate utilities.
3
+ *
4
+ * Provides conversions between geographic coordinates (lon/lat) and
5
+ * tile pixel coordinates for XYZ tiled map systems. Supports various
6
+ * tile sizes and zoom levels.
7
+ *
8
+ * @module
9
+ */
10
+
11
+ import { pointToTileFraction } from "@mapbox/tilebelt"
12
+ import type { GeoBbox2D, LonLat, Tile, TilePxBbox, XY } from "./types"
13
+
14
+ const RADIANS_TO_DEGREES = 180 / Math.PI
15
+
16
+ function tile2lon(x: number, z: number): number {
17
+ return (x / 2 ** z) * 360 - 180
18
+ }
19
+
20
+ function tile2lat(y: number, z: number): number {
21
+ const n = Math.PI - (2 * Math.PI * y) / 2 ** z
22
+ return RADIANS_TO_DEGREES * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)))
23
+ }
24
+
25
+ /**
26
+ * Get the geographic bounding box of a tile.
27
+ * Returns [west, south, east, north].
28
+ */
29
+ export function tileToBbox(tile: Tile): GeoBbox2D {
30
+ const [tx, ty, tz] = tile
31
+ const n = tile2lat(ty, tz)
32
+ const s = tile2lat(ty + 1, tz)
33
+ const e = tile2lon(tx + 1, tz)
34
+ const w = tile2lon(tx, tz)
35
+ return [w, s, e, n]
36
+ }
37
+
38
+ /**
39
+ * Convert a bounding box from geographic coordinates to tile pixel coordinates.
40
+ */
41
+ export function bboxToTilePx(
42
+ bbox: GeoBbox2D,
43
+ tile: Tile,
44
+ tileSize = 256,
45
+ ): TilePxBbox {
46
+ const [minX, minY] = llToTilePx([bbox[0], bbox[3]], tile, tileSize)
47
+ const [maxX, maxY] = llToTilePx([bbox[2], bbox[1]], tile, tileSize)
48
+ return [minX, minY, maxX, maxY]
49
+ }
50
+
51
+ /**
52
+ * Convert a geographic coordinate to tile pixel coordinates.
53
+ * Returns [x, y] in pixels relative to the top-left of the tile.
54
+ */
55
+ export function llToTilePx(ll: LonLat, tile: Tile, tileSize = 256): XY {
56
+ const [tx, ty, tz] = tile
57
+ const tf = pointToTileFraction(ll[0], ll[1], tz)
58
+ const x = (tf[0] - tx) * tileSize
59
+ const y = (tf[1] - ty) * tileSize
60
+ return [x, y]
61
+ }
62
+
63
+ /**
64
+ * Convert tile pixel coordinates to geographic coordinates.
65
+ */
66
+ export function tilePxToLonLat(px: XY, tile: Tile, tileSize = 256): LonLat {
67
+ const [tx, ty, tz] = tile
68
+ const lon = tile2lon(px[0] / tileSize + tx, tz)
69
+ const lat = tile2lat(px[1] / tileSize + ty, tz)
70
+ return [lon, lat]
71
+ }
72
+
73
+ /**
74
+ * Clamp a pixel coordinate to the tile bounds and round to the nearest integer. Useful for converting a floating point pixel
75
+ * coordinate to a the exact tile pixel it is contained by.
76
+ */
77
+ export function clampAndRoundPx(
78
+ px: XY,
79
+ tileSizeOrBbox: number | GeoBbox2D,
80
+ ): XY {
81
+ const [minX, minY, maxX, maxY] =
82
+ typeof tileSizeOrBbox === "number"
83
+ ? [0, 0, tileSizeOrBbox, tileSizeOrBbox]
84
+ : tileSizeOrBbox
85
+ return [
86
+ Math.max(minX, Math.min(maxX, Math.round(px[0]))),
87
+ Math.max(minY, Math.min(maxY, Math.round(px[1]))),
88
+ ]
89
+ }
@@ -1,6 +1,29 @@
1
+ /**
2
+ * Transform stream utilities.
3
+ *
4
+ * Helpers for piping byte arrays through TransformStreams (e.g., compression).
5
+ *
6
+ * @module
7
+ */
8
+
1
9
  import { bytesToStream } from "./bytes-to-stream"
2
10
  import { streamToBytes } from "./stream-to-bytes"
3
11
 
12
+ /**
13
+ * Pipe a byte array through a TransformStream and return the result.
14
+ *
15
+ * Useful for applying compression/decompression or other transformations
16
+ * to byte data using the Web Streams API.
17
+ *
18
+ * @param bytes - The input bytes.
19
+ * @param transformStream - The transform to apply (e.g., CompressionStream).
20
+ * @returns A Promise resolving to the transformed bytes.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * const compressed = await transformBytes(data, new CompressionStream('gzip'))
25
+ * ```
26
+ */
4
27
  export async function transformBytes(
5
28
  bytes: Uint8Array<ArrayBuffer>,
6
29
  transformStream: TransformStream<
package/src/types.ts CHANGED
@@ -1,9 +1,23 @@
1
+ /**
2
+ * Shared type definitions used across all Osmix packages.
3
+ *
4
+ * Includes geographic primitives (LonLat, Bbox), tile coordinates,
5
+ * and core OSM entity types (Node, Way, Relation).
6
+ *
7
+ * @module
8
+ */
9
+
10
+ /** Geographic coordinate as [longitude, latitude] tuple. */
1
11
  export type LonLat = [lon: number, lat: number]
12
+ /** 2D pixel or cartesian coordinate as [x, y] tuple. */
2
13
  export type XY = [x: number, y: number]
14
+
15
+ /** Geographic coordinate as object with lon/lat properties. */
3
16
  export interface ILonLat {
4
17
  lon: number
5
18
  lat: number
6
19
  }
20
+ /** XYZ tile coordinate as [x, y, z] tuple. */
7
21
  export type Tile = [x: number, y: number, z: number]
8
22
 
9
23
  /**
@@ -13,7 +27,9 @@ export type LonLatToPixel = (ll: LonLat, zoom: number) => XY
13
27
 
14
28
  export type LonLatToTilePixel = (ll: LonLat, z: number, extent: number) => XY
15
29
 
16
- export type Rgba = [number, number, number, number] | Uint8ClampedArray
30
+ export type Rgba =
31
+ | [r: number, g: number, b: number, a: number]
32
+ | Uint8ClampedArray
17
33
 
18
34
  /**
19
35
  * A bounding box in the format [minLon, minLat, maxLon, maxLat].
@@ -25,3 +41,79 @@ export type GeoBbox2D = [
25
41
  maxLon: number,
26
42
  maxLat: number,
27
43
  ]
44
+
45
+ /**
46
+ * A pixel bounding box in the format [minX, minY, maxX, maxY]. Note: minY is north. maxY is south.
47
+ */
48
+ export type TilePxBbox = [
49
+ minX: number,
50
+ minY: number,
51
+ maxX: number,
52
+ maxY: number,
53
+ ]
54
+
55
+ /**
56
+ * Shared OSM Types
57
+ */
58
+
59
+ export type OsmEntityType = "node" | "way" | "relation"
60
+
61
+ export interface OsmInfoParsed {
62
+ version?: number
63
+ timestamp?: number
64
+ changeset?: number
65
+ uid?: number
66
+ user_sid?: number
67
+ visible?: boolean
68
+ user?: string
69
+ }
70
+
71
+ export interface OsmTags {
72
+ [key: string]: string | number
73
+ }
74
+
75
+ interface IOsmEntity {
76
+ id: number
77
+ info?: OsmInfoParsed
78
+ tags?: OsmTags
79
+ }
80
+
81
+ export interface OsmNode extends IOsmEntity, ILonLat {}
82
+
83
+ export interface OsmWay extends IOsmEntity {
84
+ // OSM IDs of the nodes that make up this way
85
+ refs: number[]
86
+ }
87
+
88
+ export interface OsmRelationMember {
89
+ type: OsmEntityType
90
+ ref: number
91
+ role?: string
92
+ }
93
+
94
+ export interface OsmRelation extends IOsmEntity {
95
+ members: OsmRelationMember[]
96
+ }
97
+
98
+ export type OsmEntity = OsmNode | OsmWay | OsmRelation
99
+
100
+ export interface OsmEntityTypeMap extends Record<OsmEntityType, IOsmEntity> {
101
+ node: OsmNode
102
+ way: OsmWay
103
+ relation: OsmRelation
104
+ }
105
+
106
+ /**
107
+ * Semantic kinds of OSM relations based on their type tag and structure.
108
+ */
109
+ export type RelationKind = "area" | "line" | "point" | "logic" | "super"
110
+
111
+ /**
112
+ * Metadata about a relation kind, including expected roles and whether member order matters.
113
+ */
114
+ export interface RelationKindMetadata {
115
+ kind: RelationKind
116
+ expectedRoles?: string[]
117
+ orderMatters: boolean
118
+ description: string
119
+ }
package/src/utils.ts ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * General OSM entity utilities.
3
+ *
4
+ * Provides type guards, equality checks, and type detection for OSM entities.
5
+ * Uses deep equality checking for tags, info, and entity-specific properties.
6
+ *
7
+ * @module
8
+ */
9
+
10
+ import { dequal } from "dequal/lite"
11
+ import type {
12
+ OsmEntity,
13
+ OsmEntityType,
14
+ OsmNode,
15
+ OsmRelation,
16
+ OsmWay,
17
+ } from "./types"
18
+
19
+ /**
20
+ * Check if two entities have equal tags and info.
21
+ */
22
+ function isTagsAndInfoEqual(a: OsmEntity, b: OsmEntity) {
23
+ return dequal(a.tags, b.tags) && dequal(a.info, b.info)
24
+ }
25
+
26
+ /** Type guard: check if entity is a Node. */
27
+ export function isNode(entity: OsmEntity): entity is OsmNode {
28
+ return "lon" in entity && "lat" in entity
29
+ }
30
+
31
+ /** Check if two nodes are equal (position, tags, and info). */
32
+ export function isNodeEqual(a: OsmNode, b: OsmNode) {
33
+ return a.lat === b.lat && a.lon === b.lon && isTagsAndInfoEqual(a, b)
34
+ }
35
+
36
+ /** Type guard: check if entity is a Way. */
37
+ export function isWay(entity: OsmEntity): entity is OsmWay {
38
+ return "refs" in entity
39
+ }
40
+
41
+ /** Type guard: check if entity is a Relation. */
42
+ export function isRelation(entity: OsmEntity): entity is OsmRelation {
43
+ return "members" in entity
44
+ }
45
+
46
+ /** Check if two ways are equal (refs, tags, and info). */
47
+ export function isWayEqual(a: OsmWay, b: OsmWay) {
48
+ return dequal(a.refs, b.refs) && isTagsAndInfoEqual(a, b)
49
+ }
50
+
51
+ /** Check if two relations are equal (members, tags, and info). */
52
+ export function isRelationEqual(a: OsmRelation, b: OsmRelation) {
53
+ return dequal(a.members, b.members) && isTagsAndInfoEqual(a, b)
54
+ }
55
+
56
+ /** Check if two entities have equal properties (type-aware comparison). */
57
+ export function entityPropertiesEqual(a: OsmEntity, b: OsmEntity) {
58
+ if (!dequal(a.tags, b.tags)) return false
59
+ if (!dequal(a.info, b.info)) return false
60
+ if (isNode(a) && isNode(b)) return isNodeEqual(a, b)
61
+ if (isWay(a) && isWay(b)) return isWayEqual(a, b)
62
+ if (isRelation(a) && isRelation(b)) return isRelationEqual(a, b)
63
+ return false
64
+ }
65
+
66
+ /** Get the entity type ("node", "way", or "relation") for an entity. */
67
+ export function getEntityType(entity: OsmEntity): OsmEntityType {
68
+ if (isNode(entity)) return "node"
69
+ if (isWay(entity)) return "way"
70
+ if (isRelation(entity)) return "relation"
71
+ throw Error("Unknown entity type")
72
+ }
73
+
74
+ /**
75
+ * Check if a relation is a multipolygon relation.
76
+ */
77
+ export function isMultipolygonRelation(relation: OsmRelation): boolean {
78
+ return relation.tags?.["type"] === "multipolygon"
79
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Area detection for OSM ways.
3
+ *
4
+ * Implements the OSM wiki heuristics for determining whether a closed way
5
+ * should be rendered as an area (polygon) or a closed linear feature.
6
+ *
7
+ * @see https://wiki.openstreetmap.org/wiki/Key:area
8
+ * @see https://wiki.openstreetmap.org/wiki/Overpass_turbo/Polygon_Features
9
+ *
10
+ * @module
11
+ */
12
+
13
+ import type { OsmWay } from "./types"
14
+
15
+ /**
16
+ * Tags that imply an area unless their value is exactly "no"
17
+ */
18
+ const IMPLIED_ANY_VALUE_BUT_NO = new Set([
19
+ "amenity",
20
+ "boundary",
21
+ "building",
22
+ "building:part",
23
+ "craft",
24
+ // "golf", Seeing a lot of golf=cartpath which is not an area
25
+ "historic",
26
+ "indoor",
27
+ "landuse",
28
+ "leisure",
29
+ "military",
30
+ "office",
31
+ "place",
32
+ "public_transport",
33
+ "ruins",
34
+ "shop",
35
+ "tourism",
36
+ ])
37
+
38
+ /**
39
+ * Tags that imply an area only for these specific values
40
+ */
41
+ const INCLUDED_VALUE_TAGS = {
42
+ barrier: new Set([
43
+ "city_wall",
44
+ "ditch",
45
+ "hedge",
46
+ "retaining_wall",
47
+ "wall",
48
+ "spikes",
49
+ ]),
50
+ highway: new Set(["services", "rest_area", "escape", "elevator"]),
51
+ power: new Set(["plant", "substation", "generator", "transformer"]),
52
+ railway: new Set(["station", "turntable", "roundhouse", "platform"]),
53
+ waterway: new Set(["riverbank", "dock", "boatyard", "dam"]),
54
+ } as const
55
+
56
+ /**
57
+ * Tags that imply an area unless the value is in this exclusion list
58
+ */
59
+ const EXCLUDED_VALUE_TAGS = {
60
+ aeroway: new Set(["no", "taxiway"]),
61
+ "area:highway": new Set(["no"]),
62
+ man_made: new Set(["no", "cutline", "embankment", "pipeline"]),
63
+ natural: new Set(["no", "coastline", "cliff", "ridge", "arete", "tree_row"]),
64
+ } as const
65
+
66
+ /**
67
+ * Determine if a way is an area based on its tags and nodes.
68
+ *
69
+ * This function implements the logic described in the OSM wiki:
70
+ * https://wiki.openstreetmap.org/wiki/Key:area
71
+ * https://wiki.openstreetmap.org/wiki/Overpass_turbo/Polygon_Features
72
+ *
73
+ * @param way - The way to check.
74
+ * @returns `true` if the way is an area, `false` otherwise.
75
+ */
76
+ export function wayIsArea(way?: OsmWay): boolean {
77
+ if (!way) return false
78
+ const { refs, tags } = way
79
+ if (refs.length < 3) return false
80
+ if (refs[0] !== refs[refs.length - 1]) return false
81
+
82
+ // End refs are equal, no tags, assume it is an area.
83
+ if (!tags || Object.keys(tags).length === 0) return true
84
+
85
+ // Explicit override
86
+ if ("area" in tags) return tags["area"] !== "no"
87
+
88
+ // Tags that count if value is NOT "no"
89
+ for (const key of IMPLIED_ANY_VALUE_BUT_NO) {
90
+ const v = tags[key]
91
+ if (v && v !== "no") return true
92
+ }
93
+
94
+ // Tags that are area only for INCLUDED values
95
+ for (const [key, included] of Object.entries(INCLUDED_VALUE_TAGS)) {
96
+ const v = tags[key]
97
+ if (v && included.has(`${v}`)) return true
98
+ }
99
+
100
+ // Tags that are area unless value is excluded
101
+ for (const [key, excluded] of Object.entries(EXCLUDED_VALUE_TAGS)) {
102
+ const v = tags[key]
103
+ if (v && !excluded.has(`${v}`)) return true
104
+ }
105
+
106
+ return false
107
+ }
package/src/zigzag.ts ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Zigzag encoding/decoding for protobuf-style varints.
3
+ *
4
+ * Zigzag encoding converts signed integers to unsigned by interleaving
5
+ * negative and positive values: 0, -1, 1, -2, 2, ... This allows efficient
6
+ * varint encoding of small negative numbers.
7
+ *
8
+ * @module
9
+ */
10
+
11
+ /**
12
+ * Zigzag encode a number using arithmetic operations.
13
+ * This supports the full safe integer range (up to Number.MAX_SAFE_INTEGER).
14
+ * Formula: n < 0 ? -2*n - 1 : 2*n
15
+ *
16
+ * Used for encoding IDs in vector tiles to convert negative IDs to positive numbers
17
+ * for unsigned varint encoding.
18
+ */
19
+ export function zigzag(num: number): number {
20
+ return num < 0 ? -2 * num - 1 : 2 * num
21
+ }
22
+
23
+ /**
24
+ * Zigzag encode using bitwise operations (for geometry deltas only).
25
+ * This is faster but limited to 32-bit signed integers.
26
+ * Used for small coordinate deltas in geometry encoding.
27
+ */
28
+ export function zigzag32(num: number): number {
29
+ return (num << 1) ^ (num >> 31)
30
+ }
31
+
32
+ /**
33
+ * Decode zigzag-encoded number back to original value.
34
+ * Zigzag encoding is used to convert negative IDs to positive numbers for unsigned varint
35
+ * encoding in vector tiles. Uses arithmetic-based decoding to support the full safe integer range.
36
+ *
37
+ * Formula: (encoded & 1) === 1 ? -(encoded + 1) / 2 : encoded / 2
38
+ */
39
+ export function decodeZigzag(encoded: number): number {
40
+ // Check if encoded is odd (negative) using bitwise, then use arithmetic
41
+ return (encoded & 1) === 1 ? -(encoded + 1) / 2 : encoded / 2
42
+ }
@@ -1,8 +1,8 @@
1
- import { assert, test } from "vitest"
1
+ import { expect, test } from "bun:test"
2
2
  import { haversineDistance } from "../src/haversine-distance"
3
3
 
4
4
  test("haversineDistance", () => {
5
5
  const p1: [number, number] = [-75.343, 39.984]
6
6
  const p2: [number, number] = [-75.534, 39.123]
7
- assert.closeTo(haversineDistance(p1, p2), 97129.2211, 0.0001)
7
+ expect(haversineDistance(p1, p2)).toBeCloseTo(97129.2211, 3)
8
8
  })