@garagem-ai/site-sdk 0.7.0 → 0.9.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/README.md CHANGED
@@ -54,25 +54,27 @@ raw escape hatch when you need full control.
54
54
 
55
55
  ### Friendly layer (recommended for most use cases)
56
56
 
57
- | API | Description |
58
- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
59
- | `getListings({ siteId, filters?, next? })` | Paginated listings for a site, with simple `filters` (`city`, `businessType`, `propertyType`, `neighborhood`, `minPrice`, `maxPrice`, `limit`, `offset`) |
60
- | `getListing({ siteId, listingId, next? })` | Full detail of a single listing |
61
- | `getSimilarListings({ siteId, listingId, limit?, next? })` | Similar listings carousel (same card shape as `getListings`) |
62
- | `getSite({ siteId? \| domain?, next? })` | Public site profile (returns `null` if unknown) |
63
- | `getCmsCollections({ siteId })` | List CMS collections |
64
- | `getCmsCollection({ siteId, slug })` | One CMS collection schema |
65
- | `getCmsEntries({ siteId, collection, limit?, offset? })` | Published CMS entries only |
66
- | `getCmsEntry({ siteId, collection, slug })` | One published CMS entry |
67
- | `getSearchUi({ siteId, next? })` | Tenant search schema (filters, slugs) |
68
- | `getLeadUi({ siteId, next? })` | Visit-default lead dialog schema (weekday hours, Sat/Sun flags) |
69
- | `submitVisitLead({ siteId, listingId, … })` | POST a visit lead (`listing.id` UUID; civil `visitDate` or `Date`/ISO instant normalized in the schedule timezone) |
70
- | `submitContactLead({ siteId, listingId, … })` | POST a contact lead (no date/time) |
71
- | `slotsForDate` / `normalizeVisitDate` / `expandVisitSchedule` | Pure schedule helpers (`America/Sao_Paulo`, default Mon–Fri 06:00–22:00) |
72
- | `listingDetailModel(listing)` | Listing-detail blocks: breadcrumb, location + Maps href, `description` string + toggle label, video/tour overlays. Studio pages map `facts` / `values` via `.label` / `.text` leaves. |
73
- | `listingDetailFieldsModel(listing, dictionary?)` | Facts, values, and amenity groups that are safe to render: every row has a real label + text; missing condo/IPTU/empty groups are omitted. |
74
- | `listingAmenityGroups(listing, dictionary?)` | Unit / building amenity labels (`Comodidades`, `Comodidades do condomínio`). Reads `propertyFeatures` + `buildingAmenities` (works when `building` is null). Tenant `getSearchUi().dictionary` first, then the SDK fallback. Studio pages call this helper directly. |
75
- | `resolvePublicSiteId({ host?, fallback? })` | Preview uses `fallback` (`GARAGEM_SITE_ID`); live hosts resolve via `getSite({ domain })` |
57
+ | API | Description |
58
+ | ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
59
+ | `getListings({ siteId, filters?, next? })` | Paginated listings for a site, with simple `filters` (`city`, `businessType`, `propertyType`, `neighborhood`, `minPrice`, `maxPrice`, `limit`, `offset`) |
60
+ | `getListing({ siteId, listingId, next? })` | Full detail of a single listing |
61
+ | `getSimilarListings({ siteId, listingId, limit?, next? })` | Similar listings carousel (same card shape as `getListings`) |
62
+ | `getSimilarByPhoto(siteId, listingId, mediaId, options?)` | "Imóveis com fotos parecidas": listings whose public photos look like one gallery photo. `available: false` when the tenant has no image search — hide the block. |
63
+ | `listingPhotoGroups(listing)` / `listingVisualHighlights(listing)` | Gallery grouped by room (`Sala`, `Quartos`, `Cozinha`, … from each photo's `roomType`) and the deduped visual highlights the photo analysis named most often. |
64
+ | `getSite({ siteId? \| domain?, next? })` | Public site profile (returns `null` if unknown) |
65
+ | `getCmsCollections({ siteId })` | List CMS collections |
66
+ | `getCmsCollection({ siteId, slug })` | One CMS collection schema |
67
+ | `getCmsEntries({ siteId, collection, limit?, offset? })` | Published CMS entries only |
68
+ | `getCmsEntry({ siteId, collection, slug })` | One published CMS entry |
69
+ | `getSearchUi({ siteId, next? })` | Tenant search schema (filters, slugs) |
70
+ | `getLeadUi({ siteId, next? })` | Visit-default lead dialog schema (weekday hours, Sat/Sun flags) |
71
+ | `submitVisitLead({ siteId, listingId, … })` | POST a visit lead (`listing.id` UUID; civil `visitDate` or `Date`/ISO instant normalized in the schedule timezone) |
72
+ | `submitContactLead({ siteId, listingId, … })` | POST a contact lead (no date/time) |
73
+ | `slotsForDate` / `normalizeVisitDate` / `expandVisitSchedule` | Pure schedule helpers (`America/Sao_Paulo`, default Mon–Fri 06:00–22:00) |
74
+ | `listingDetailModel(listing)` | Listing-detail blocks: breadcrumb, location + Maps href, `description` string + toggle label, video/tour overlays. Studio pages map `facts` / `values` via `.label` / `.text` leaves. |
75
+ | `listingDetailFieldsModel(listing, dictionary?)` | Facts, values, and amenity groups that are safe to render: every row has a real label + text; missing condo/IPTU/empty groups are omitted. |
76
+ | `listingAmenityGroups(listing, dictionary?)` | Unit / building amenity labels (`Comodidades`, `Comodidades do condomínio`). Reads `propertyFeatures` + `buildingAmenities` (works when `building` is null). Tenant `getSearchUi().dictionary` first, then the SDK fallback. Studio pages call this helper directly. |
77
+ | `resolvePublicSiteId({ host?, fallback? })` | Preview uses `fallback` (`GARAGEM_SITE_ID`); live hosts resolve via `getSite({ domain })` |
76
78
 
77
79
  ### Advanced layer (when the friendly one isn't enough)
78
80
 
@@ -82,13 +84,15 @@ raw escape hatch when you need full control.
82
84
 
83
85
  ### Cross-cutting
84
86
 
85
- | API | Description |
86
- | ------------------------------ | ----------------------------------------------------- |
87
- | `createGaragemClient(options)` | Pre-bind `baseUrl`, `siteId`, `fetch`, `next` |
88
- | `GaragemSdkError` | Thrown on non-2xx responses; carries `status` + `url` |
87
+ | API | Description |
88
+ | -------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
89
+ | `createGaragemClient(options)` / `createClient(options)` | Pre-bind `baseUrl`, `siteId`, `publishableKey`, `fetch`, `next` |
90
+ | `GaragemSdkError` | Thrown on non-2xx responses; `status`, `url`, `reason`, `retryAfter` (seconds, set on 429) |
89
91
 
90
92
  All fetchers accept:
91
93
 
94
+ - `publishableKey` — optional `pk_live_…` from the site's API pública
95
+ settings. See [Publishable keys & rate limits](#publishable-keys--rate-limits).
92
96
  - `baseUrl` — data fetchers default to `https://app.garagem.ai`; `getSite`
93
97
  defaults to `https://cdn.fndn.ai/site` so production resolution traverses the
94
98
  tenant-locator edge. Override for a custom proxy or staging.
@@ -174,6 +178,91 @@ export default async function ListingPage({
174
178
  }
175
179
  ```
176
180
 
181
+ ## Photo captions, room groups and "imóveis com fotos parecidas"
182
+
183
+ Every photo on `getListing().media` carries the platform's photo analysis when
184
+ the tenant has it: `caption` (AI caption, falling back to the broker's own
185
+ description), `roomType`, `sceneType`, `features`, and an `alt` built from the
186
+ caption. Nothing here calls a model at request time — it is read with the
187
+ listing and cached like the rest of the detail. Photos without analysis keep
188
+ the generic `"<title> - Foto N"` alt and omit the other fields.
189
+
190
+ ```tsx
191
+ import {
192
+ getListing,
193
+ getSimilarByPhoto,
194
+ listingPhotoGroups,
195
+ listingVisualHighlights,
196
+ } from "@garagem-ai/site-sdk";
197
+
198
+ export default async function ListingPage({
199
+ params,
200
+ }: {
201
+ params: Promise<{ id: string }>;
202
+ }) {
203
+ const { id } = await params;
204
+ const siteId = process.env.GARAGEM_SITE_ID!;
205
+ const listing = await getListing({ siteId, listingId: id });
206
+
207
+ // "Sala (3) · Quartos (4) · Cozinha (2)" — pt-BR labels, `Outras fotos` last.
208
+ // With no analysis at all you get a single `Outras fotos` group: keep the
209
+ // flat gallery when `groups.length <= 1`.
210
+ const groups = listingPhotoGroups(listing);
211
+ // ["piso de madeira", "pé-direito alto", "vista livre"]
212
+ const highlights = listingVisualHighlights(listing, { limit: 6 });
213
+
214
+ // Listings whose public photos look like the cover photo.
215
+ const cover = listing.media.find((m) => m.type === "image");
216
+ const similar = cover
217
+ ? await getSimilarByPhoto(siteId, listing.id, cover.id, {
218
+ limit: 6,
219
+ next: { revalidate: 300 },
220
+ })
221
+ : { available: false, items: [] };
222
+
223
+ return (
224
+ <>
225
+ <ul>
226
+ {highlights.map((h) => (
227
+ <li key={h}>{h}</li>
228
+ ))}
229
+ </ul>
230
+ {groups.map((group) => (
231
+ <section key={group.key}>
232
+ <h2>
233
+ {group.label} ({group.photos.length})
234
+ </h2>
235
+ {group.photos.map((photo) => (
236
+ <img key={photo.id} src={photo.src} alt={photo.alt} />
237
+ ))}
238
+ </section>
239
+ ))}
240
+ {similar.available && similar.items.length > 0 && (
241
+ <section>
242
+ <h2>Imóveis com fotos parecidas</h2>
243
+ {similar.items.map(({ listing: l, matchedPhoto }) => (
244
+ <a key={l.id} href={l.path}>
245
+ <img src={matchedPhoto.src} alt={matchedPhoto.alt} />
246
+ {l.title}
247
+ </a>
248
+ ))}
249
+ </section>
250
+ )}
251
+ </>
252
+ );
253
+ }
254
+ ```
255
+
256
+ `getSimilarByPhoto` returns `{ available, items }`. `available` is `false`
257
+ when the site's tenant has not enabled image search, and when `photo.id` is
258
+ not a media UUID — `getListing` uses `image-N` when Typesense has no id for
259
+ that photo and `external-N` for video or tour. That returns locally, without
260
+ a request, so the example above hides the section instead of throwing. Items
261
+ are `{ listing, matchedPhoto: { id, src, alt, caption, distance } }` with the
262
+ same card shape as `getListings`. Only public photos of public, active
263
+ listings are compared; the reference listing (and its sale/rental twin) is
264
+ never returned. `limit` defaults to 6 and caps at 12.
265
+
177
266
  ## CMS example
178
267
 
179
268
  ```tsx
@@ -290,23 +379,231 @@ Works wherever `fetch` is available:
290
379
  - Edge runtime (Vercel Edge, Cloudflare Workers, Deno)
291
380
  - Browsers (use carefully — see "Public keys" below)
292
381
 
293
- ## Public keys & rate limiting (roadmap)
382
+ ## Maps (static map, street view, boundaries, travel time)
383
+
384
+ Helpers for `maps.fndn.ai`, the Garagem maps façade. They only use the
385
+ coordinates the public API already returns for a listing — those are
386
+ masked per site (≈100 m by default) and the helpers **never add precision**
387
+ (`maxDecimals` can only coarsen further). Pass `siteId` so usage is metered
388
+ per site on `maps.fndn.ai` (it is a label, not auth).
389
+
390
+ ```ts
391
+ import {
392
+ listingStaticMapUrl,
393
+ listingStreetViewAvailable,
394
+ listingStreetViewUrl,
395
+ } from "@garagem-ai/site-sdk";
396
+
397
+ const listing = await getListing({ siteId, listingId });
398
+
399
+ // <img src={...}> — zoom is capped by the coordinate precision (16 for the
400
+ // default ≈100 m mask), so the pin never pretends to know the exact door.
401
+ const map = listingStaticMapUrl(listing, {
402
+ width: 640,
403
+ height: 320,
404
+ zoom: 15,
405
+ style: "roadmap",
406
+ siteId,
407
+ });
408
+
409
+ // Metadata is free on Google's side; the image is billed. Check first.
410
+ const sv = await listingStreetViewAvailable(listing, { siteId });
411
+ const street = sv.available
412
+ ? listingStreetViewUrl(listing, { width: 640, height: 400, siteId })
413
+ : null;
414
+ ```
415
+
416
+ ### Neighbourhood outline on an interactive map
417
+
418
+ `boundaryLayerUrl(city)` returns the TileJSON for a city's boundary layer
419
+ (`sao_paulo`, `rio_de_janeiro`; other cities fall back to OSM data via
420
+ `source: "osm"`). `neighborhoodBoundaryLayer(city, name)` resolves one
421
+ outline as GeoJSON. With the Maps JS loader (`https://maps.fndn.ai/sdk.js`,
422
+ which injects the browser key for you — never ship your own Google key):
423
+
424
+ ```tsx
425
+ import { neighborhoodBoundaryLayer } from "@garagem-ai/site-sdk";
426
+
427
+ // <script src="https://maps.fndn.ai/sdk.js?callback=initMap" async defer />
428
+ window.initMap = async () => {
429
+ const map = new google.maps.Map(el, { center, zoom: 14 });
430
+ const outline = await neighborhoodBoundaryLayer(
431
+ "São Paulo",
432
+ "Vila Madalena",
433
+ {
434
+ siteId,
435
+ }
436
+ );
437
+ if (outline.feature) {
438
+ map.data.addGeoJson(outline.feature);
439
+ map.data.setStyle({ fillOpacity: 0.08, strokeWeight: 2 });
440
+ }
441
+ };
442
+ ```
443
+
444
+ With MapLibre, use the vector tiles instead of GeoJSON for the whole city:
445
+
446
+ ```ts
447
+ map.addSource("sp", { type: "vector", url: boundaryLayerUrl("sao_paulo") });
448
+ map.addLayer({
449
+ id: "districts",
450
+ type: "line",
451
+ source: "sp",
452
+ "source-layer": "district", // see getBoundaryLayer(city).sourceLayers
453
+ });
454
+ ```
455
+
456
+ ### Travel time
457
+
458
+ ```ts
459
+ import { travelTimeFromListing } from "@garagem-ai/site-sdk";
460
+
461
+ const t = await travelTimeFromListing(listing, "Av. Paulista, 1000", {
462
+ mode: "transit", // driving (default) | walking | bicycling | transit
463
+ siteId,
464
+ });
465
+ // t → { minutes: 19, distanceKm: 5.2, cached: false, … } | null
466
+ ```
467
+
468
+ **Cost:** each uncached call is one Google Directions request on the shared
469
+ key (≈US$5 per 1 000 at list price; a free-text destination adds a
470
+ Nominatim geocode, which is free). Results are cached in-process for 15
471
+ minutes (200 entries, LRU) keyed by origin + destination + mode; pass
472
+ `cache: null` to opt out or `createTravelTimeCache({ ttlMs, maxEntries })`
473
+ to tune it. `travelTimesFromListing(listing, [...])` fans out to the Route
474
+ Matrix (≈US$5 per 1 000 elements, driving only, no distance). Call these
475
+ from a server component or route handler, not per card render.
476
+
477
+ ### Map search
478
+
479
+ Viewport and drawn-area search go through the friendly listings route
480
+ (`POST /api/sites/{siteId}/search/listings`). The SDK sends `bounds` or
481
+ `polygon` as numbers. The server builds one allowlisted
482
+ `coordinates:(lat,lng,…)` filter (the public index field — a rectangle is
483
+ the same clockwise polygon Foundation's map uses). Callers never send a
484
+ raw Typesense filter. A drawn polygon wins over the viewport.
485
+
486
+ ```ts
487
+ import {
488
+ searchListingsInBounds,
489
+ searchListingsInPolygon,
490
+ clusterPins,
491
+ } from "@garagem-ai/site-sdk";
492
+
493
+ const area = await searchListingsInBounds(siteId, {
494
+ bounds: { north: -23.5, south: -23.6, east: -46.6, west: -46.7 },
495
+ zoom: 14, // clustering hint only — not sent to the server
496
+ q: "varanda",
497
+ sort: "preco-asc",
498
+ location: { type: "neighborhood", value: "pinheiros" },
499
+ filters: { listing_type: "sale" },
500
+ publishableKey: "pk_live_…",
501
+ pageSize: 100, // capped at 100, the friendly-route maximum
502
+ });
503
+ // area.pins → { id, lat, lng, price, coverImage }[]
504
+ // area.cards → listing card models for the same page
505
+
506
+ const drawn = await searchListingsInPolygon(siteId, {
507
+ polygon: [
508
+ [-23.5, -46.7],
509
+ [-23.5, -46.6],
510
+ [-23.6, -46.6],
511
+ ], // [lat, lng], not GeoJSON [lng, lat]
512
+ filters: { listing_type: "sale" },
513
+ });
514
+
515
+ const clusters = clusterPins(area.pins, 14);
516
+ ```
517
+
518
+ Pins copy `listing.location.coordinates` exactly as the API returned them.
519
+ Those coordinates are already masked (≈100 m by default). Do not geocode
520
+ the street to sharpen a pin, and do not add decimals. `clusterPins` keeps
521
+ a lone pin's coordinates and rounds a group centroid back to the coarsest
522
+ pin in the cell. `pageSize` above 100 is clamped. A rectangle that crosses
523
+ the antimeridian (`east <= west`) is rejected.
524
+
525
+ `useMapSearch` (from `@garagem-ai/site-sdk/react`) debounces viewport
526
+ changes by 400ms — the same pause as Foundation's `/imoveis` map — aborts
527
+ the previous request, and returns `{ pins, cards, clusters }`. Changing
528
+ zoom only reclusters. **Every viewport change is a search call.** Do not
529
+ fire one per mousemove, do not raise the page size, and do not call travel
530
+ time or Street View from that loop.
531
+
532
+ ## Publishable keys & rate limits
533
+
534
+ Calls to `/api/sites/{siteId}/*` stay anonymous when you pass no key. A
535
+ **publishable key** (`pk_live_…`) is not a secret: it ships in the browser
536
+ bundle and only tells Foundation which site to meter. Create or rotate it
537
+ in Garagem at **Configurações → Sites → the site → API pública**
538
+ (`/configuracoes/sites/[siteId]`). Copy it into the client:
539
+
540
+ ```ts
541
+ import { createClient } from "@garagem-ai/site-sdk";
542
+
543
+ export const garagem = createClient({
544
+ siteId: process.env.NEXT_PUBLIC_GARAGEM_SITE_ID,
545
+ publishableKey: process.env.NEXT_PUBLIC_GARAGEM_PUBLISHABLE_KEY,
546
+ });
547
+ ```
294
548
 
295
- Today every fetcher is anonymous. As the SDK approaches public launch we'll
296
- add **publishable keys** with per-tenant rate limits and a domain allowlist —
297
- no breaking changes to the call sites, just an additional `publishableKey`
298
- option on `createGaragemClient`.
549
+ `createClient` is an alias of `createGaragemClient`. The same
550
+ `publishableKey` option exists on every fetcher (`getListings`,
551
+ `getListing`, `getSite`, `getSearchUi`, `queryListings`, `searchListings`,
552
+ the CMS helpers, `getLeadUi`, `submitVisitLead`, `submitContactLead`),
553
+ on `usePublicSearch`, and on map search (`searchListingsInBounds`,
554
+ `searchListingsInPolygon`, `useMapSearch`). The SDK sends it as
555
+ `X-Garagem-Publishable-Key`. A viewport search that omits the key spends
556
+ the anonymous listings budget. Pass the same `q`, `sort`, and `location`
557
+ as the list, or the pins will not match the active query.
558
+ `Authorization: Bearer pk_live_…` is accepted too. A blank value is treated
559
+ as no key.
560
+
561
+ ### Compatibility
562
+
563
+ | Request | Result |
564
+ | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
565
+ | Site has no key, request has no key | Served. Anonymous per-IP budget. |
566
+ | Site has a key, request has no key | Served. Stricter anonymous per-IP budget (older bundles keep working). |
567
+ | Request key matches this site | Served. Shared per-site budget. |
568
+ | Request key is present but wrong | **401** `GaragemSdkError` with `reason: "invalid_publishable_key"`. A key never opens another site. |
569
+ | Browser `Origin` / `Referer` not on the site allowlist | **403** `reason: "origin_not_allowed"`. Empty allowlist means any origin. Requests with neither header (server-to-server, RSC) are not origin-checked. |
570
+ | Budget exceeded | **429** `reason: "rate_limited"`. `error.retryAfter` is seconds (also the `Retry-After` header). |
571
+
572
+ Lead POST (`submitVisitLead` / `submitContactLead`) throws `LeadSubmitError`
573
+ instead: `code: "unauthorized"` on 401, `code: "rate_limited"` on 429, with
574
+ `retryAfter` and `retryAfterSeconds`.
575
+
576
+ ### Defaults (hits per 60 seconds)
577
+
578
+ | Bucket | With key | No key configured | Key configured, request omitted it |
579
+ | ------------------------------------------------------------------------ | -------: | ----------------: | ---------------------------------: |
580
+ | `listings` (index, CMS entry lists) | 600 | 120 | 30 |
581
+ | `search` | 600 | 120 | 30 |
582
+ | `detail` (listing, similar, CMS entry) | 1200 | 300 | 60 |
583
+ | `config` (search UI, lead UI, locations, public config, CMS collections) | 300 | 120 | 30 |
584
+
585
+ Responses include `RateLimit-Limit`, `RateLimit-Remaining`,
586
+ `RateLimit-Reset`, and `RateLimit-Policy` (`{limit};w=60`). `Retry-After`
587
+ is added on a deny. The limiter is shared across Foundation instances in
588
+ the cell (cell-local Valkey). If that cache is down, the same window is
589
+ enforced in memory on the instance that handled the request.
590
+
591
+ First-party traffic from the Garagem site proxy is exempt. Set
592
+ `PUBLIC_SITE_RATE_LIMIT_MODE=observe` to count without denying, or `off`
593
+ to skip metering. Key and origin checks still run in both modes.
299
594
 
300
595
  ## Search UI (`@garagem-ai/site-sdk/react`)
301
596
 
302
597
  Headless URL/search helpers live on the main entry (`readPublicSearch`,
303
598
  `hrefForPathFilters`, `toListingCardModel`, …). The React adapter is a
304
599
  separate subpath — peer `react` + `next` — and exports `usePublicSearch`
305
- only. Card, skeleton, and search chrome markup belong in the app.
600
+ and `useMapSearch`. Card, skeleton, and search chrome markup belong in the app.
306
601
 
307
602
  Studio codegen follows `STUDIO_SDK_CONTRACT`: pin
308
603
  `@garagem-ai/site-sdk` to `minNpmVersion` and import only
309
- `reactExports` (`usePublicSearch`). Do **not** import npm CSS
604
+ `reactExports` (`usePublicSearch`). `useMapSearch` is for hand-written
605
+ sites today; Studio prompts name it only once the pin reaches `mapsSince`
606
+ (0.7.0), together with the other maps helpers. Do **not** import npm CSS
310
607
  (`@garagem-ai/site-sdk/react/search.css`).
311
608
 
312
609
  ```tsx
@@ -378,7 +675,8 @@ resolve locally and do not hit the API.
378
675
  ## What's NOT in this release
379
676
 
380
677
  - CMS writes / drafts (editor + CMS worker only).
381
- - Typesense / InstantSearch helpers.
678
+ - Raw Typesense / InstantSearch adapters. Map viewport search uses the
679
+ friendly listings route described above.
382
680
  - LiveSession / lead submission helpers.
383
681
 
384
682
  All of these will land additively; the v0.2 surface above will not break.