@happyvertical/smrt-places 0.30.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/AGENTS.md ADDED
@@ -0,0 +1,29 @@
1
+ # @happyvertical/smrt-places
2
+
3
+ Hierarchical geographic database with organic growth via geocoding integration.
4
+
5
+ ## Models
6
+
7
+ - **Place** (STI): hierarchical via `parentId`. Optional geo fields (all nullable — supports abstract places like game zones). `externalId`/`source` from geocoder. Metadata JSON.
8
+ - **PlaceAsset**: dedicated owned-asset join in `place_assets` with `relationship` and `sortOrder`.
9
+ - **PlaceType**: slug-based classification (country, city, building, zone, room, region).
10
+
11
+ ## Key Collection Methods
12
+
13
+ | Method | Purpose |
14
+ |--------|---------|
15
+ | `lookupOrCreate(query)` | DB first → geocode if not found → create. Organic growth pattern. |
16
+ | `findByCoordinates(lat, lng, threshold)` | Default 0.0001° ≈ 11m tolerance at equator |
17
+ | `searchByProximity(lat, lng, radiusKm)` | Haversine distance, sorted by proximity |
18
+ | `findWithGlobals(tenantId)` | Tenant + global (tenantId=null) places |
19
+ | `getRootPlaces()`, `getByType(slug)` | Hierarchy + type queries |
20
+ | `getAssets()` / `addAsset()` / `removeAsset()` | Owned asset helpers on both `Place` and `PlaceCollection`, backed by `place_assets` |
21
+
22
+ Hierarchy traversal: `getParent()`, `getChildren()`, `getAncestors()`, `getDescendants()`, `getHierarchy()`.
23
+
24
+ ## Gotchas
25
+
26
+ - **Geo providers**: Google Maps needs `GOOGLE_MAPS_API_KEY`; OpenStreetMap is default
27
+ - **Abstract places allowed**: lat/lng nullable — supports non-geographic locations
28
+ - **Coordinate tolerance varies by latitude**: 0.0001° ≈ 11m at equator, less at poles
29
+ - **Optional tenancy** with nullable tenantId
package/CLAUDE.md ADDED
@@ -0,0 +1 @@
1
+ @AGENTS.md
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright <2025> <Happy Vertical Corporation>
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,185 @@
1
+ # @happyvertical/smrt-places
2
+
3
+ Hierarchical place management with geocoding integration and spatial queries. Supports both real-world locations (with coordinates) and abstract places (virtual worlds, game zones).
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @happyvertical/smrt-places
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Lookup or create places with organic database growth
14
+
15
+ ```typescript
16
+ import { PlaceCollection, PlaceTypeCollection } from '@happyvertical/smrt-places';
17
+
18
+ const places = await PlaceCollection.create();
19
+ const types = await PlaceTypeCollection.create();
20
+
21
+ // DB-first lookup, geocodes and creates if not found
22
+ const place = await places.lookupOrCreate('1600 Amphitheatre Parkway, Mountain View, CA');
23
+
24
+ if (place) {
25
+ console.log(`${place.name}: ${place.latitude}, ${place.longitude}`);
26
+ console.log(`Source: ${place.source}`); // 'openstreetmap' or 'google'
27
+ }
28
+
29
+ // Build hierarchy: Country > State > City
30
+ const country = await places.create({
31
+ typeId: (await types.getOrCreate('country')).id,
32
+ name: 'United States',
33
+ countryCode: 'US',
34
+ });
35
+
36
+ const city = await places.create({
37
+ typeId: (await types.getOrCreate('city')).id,
38
+ parentId: country.id,
39
+ name: 'San Francisco',
40
+ latitude: 37.7749,
41
+ longitude: -122.4194,
42
+ });
43
+
44
+ // Hierarchy traversal
45
+ const hierarchy = await city.getHierarchy();
46
+ console.log(hierarchy.ancestors.map(p => p.name)); // ['United States']
47
+
48
+ // Proximity search (Haversine distance, sorted nearest-first)
49
+ const nearby = await places.searchByProximity(37.7749, -122.4194, 10); // 10km radius
50
+ ```
51
+
52
+ ### Discover POIs around a coordinate
53
+
54
+ `discoverNearby` composes `@happyvertical/geo`'s `findPoisNear` with the
55
+ collection's idempotent-persist logic. Each POI returned by the provider is
56
+ either reused from the local DB (matched by provider `externalId`) or
57
+ created as a fresh Place row. Repeat calls for the same area are effectively
58
+ free — the provider's own id becomes `Place.externalId`, so a second scan
59
+ doesn't duplicate anything.
60
+
61
+ ```typescript
62
+ const pois = await places.discoverNearby(53.5461, -113.4938, 250, {
63
+ geoProvider: 'openstreetmap', // default
64
+ types: ['cafe'], // optional filter — passed through to the provider
65
+ limit: 10,
66
+ });
67
+
68
+ for (const poi of pois) {
69
+ console.log(poi.name, poi.externalId);
70
+ }
71
+ ```
72
+
73
+ Requires a geo provider that implements `findPoisNear`. Throws a clear error
74
+ otherwise so callers can fall back to `lookupOrCreate` (address-level) or
75
+ switch providers.
76
+
77
+ ### Resolve POIs along a GPS track
78
+
79
+ For workflows like "what places does this drive/hike pass through?",
80
+ `resolveTrackPlaces` walks an ordered array of points, collapses close
81
+ samples into grid cells, throttles the provider between requests, and
82
+ returns the deduplicated Place rows.
83
+
84
+ ```typescript
85
+ const track = [
86
+ { lat: 53.5461, lng: -113.4938 },
87
+ { lat: 53.5465, lng: -113.4942 },
88
+ { lat: 53.5470, lng: -113.4950 },
89
+ // ...hundreds more along a route
90
+ ];
91
+
92
+ const result = await places.resolveTrackPlaces(track, {
93
+ radiusMeters: 50, // per-point POI search radius
94
+ bucketMeters: 50, // collapse points within this distance into one request
95
+ throttleMs: 1100, // ≥1s is safe for public Overpass/Nominatim
96
+ types: ['cafe', 'restaurant'],
97
+ });
98
+
99
+ console.log(`Hit ${result.requestCount} buckets, ${result.cacheHitCount} cached, ${result.places.length} distinct places`);
100
+ ```
101
+
102
+ Bucketing is the main cost-saver: a 20-minute drive at 1 Hz GPS produces
103
+ 1200 raw samples but often only 100–200 distinct 50 m cells, so the
104
+ provider only gets called 100–200 times. `throttleMs` keeps you within
105
+ Overpass/Nominatim's 1 req/sec community limit out of the box; drop it to
106
+ 100 ms or so on paid tiers.
107
+
108
+ ### Owned assets
109
+
110
+ ```typescript
111
+ import { AssetCollection } from '@happyvertical/smrt-assets';
112
+
113
+ const assets = await AssetCollection.create();
114
+ const floorplan = await assets.create({
115
+ name: 'main-hall-floorplan.png',
116
+ sourceUri: 'file:///tmp/main-hall-floorplan.png',
117
+ mimeType: 'image/png',
118
+ });
119
+
120
+ await place.addAsset(floorplan, 'floorplan');
121
+ await places.addAsset(place.id!, floorplan, 'gallery', 1);
122
+
123
+ const floorplans = await place.getAssets('floorplan');
124
+ const galleryAssets = await places.getAssets(place.id!, 'gallery');
125
+ ```
126
+
127
+ ## API
128
+
129
+ ### Models
130
+
131
+ | Export | Description |
132
+ |--------|------------|
133
+ | `Place` | Hierarchical place with optional geo fields, STI enabled |
134
+ | `PlaceType` | Slug-based classification (country, city, building, zone, room) |
135
+ | `PlaceAsset` | Dedicated owned-asset join stored in `place_assets` with `relationship` and `sortOrder` |
136
+
137
+ ### Collections
138
+
139
+ | Export | Description |
140
+ |--------|------------|
141
+ | `PlaceCollection` | CRUD + `lookupOrCreate()`, `searchByProximity()`, `findByCoordinates()`, `getRootPlaces()`, `getByType()`, `findWithGlobals()` |
142
+ | `PlaceAssetCollection` | Direct access to `place_assets` rows plus asset helper wrappers |
143
+ | `PlaceTypeCollection` | CRUD + `getOrCreate()` for idempotent type creation |
144
+
145
+ ### Types
146
+
147
+ | Export | Description |
148
+ |--------|------------|
149
+ | `GeoData` | Geographic data structure |
150
+ | `LookupOrCreateOptions` | Options for `lookupOrCreate()` |
151
+ | `PlaceHierarchy` | Hierarchy traversal result |
152
+ | `PlaceOptions` | Place creation options |
153
+ | `PlaceTypeOptions` | PlaceType creation options |
154
+
155
+ ### Utilities
156
+
157
+ | Export | Description |
158
+ |--------|------------|
159
+ | `calculateDistance` | Haversine distance between two coordinates (km) |
160
+ | `areCoordinatesNear` | Check if two coordinates are within threshold |
161
+ | `validateCoordinates` | Validate lat/lng values |
162
+ | `parseCoordinates` | Parse coordinate string to lat/lng |
163
+ | `formatCoordinates` | Format lat/lng as string |
164
+ | `generateDisplayName` | Build display name from address components |
165
+ | `locationToGeoData` | Convert location response to GeoData |
166
+ | `mapLocationTypeToPlaceType` | Map geocoder location type to PlaceType slug |
167
+ | `normalizeAddressComponents` | Normalize address components from geocoder |
168
+
169
+ ### Instance Methods (Place)
170
+
171
+ `getParent()`, `getChildren()`, `getAncestors()`, `getDescendants()`, `getHierarchy()` -- hierarchy traversal on any Place instance.
172
+
173
+ Owned asset helpers are available on both `Place` and `PlaceCollection` via
174
+ `getAssets()`, `addAsset()`, and `removeAsset()`. Common relationships include
175
+ `hero`, `floorplan`, `gallery`, and `attachment`.
176
+
177
+ ## Dependencies
178
+
179
+ | Package | Purpose |
180
+ |---------|---------|
181
+ | `@happyvertical/smrt-core` | SmrtObject/SmrtCollection base classes |
182
+ | `@happyvertical/smrt-tenancy` | Optional tenant scoping |
183
+ | `@happyvertical/geo` | Geocoding providers (OpenStreetMap, Google Maps) |
184
+ | `@happyvertical/sql` | Database operations |
185
+ | `@happyvertical/ai` | AI integration |