@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.
@@ -1,6 +1,8 @@
1
1
  "use client";
2
2
 
3
3
  export { usePublicSearch } from "./use-public-search";
4
+ export { useMapSearch } from "./use-map-search";
5
+ export type { UseMapSearchOptions, UseMapSearchResult } from "./use-map-search";
4
6
  export type {
5
7
  PublicSearchSnapshot,
6
8
  PublicSearchState,
@@ -24,6 +24,11 @@ export type PublicSearchSnapshot = {
24
24
  export type UsePublicSearchOptions = {
25
25
  siteId: SiteIdInput;
26
26
  baseUrl?: string;
27
+ /**
28
+ * Site publishable key (`pk_live_…`). Sent on schema, location, and
29
+ * listing requests. Not a secret. Omit it to stay on the anonymous budget.
30
+ */
31
+ publishableKey?: string;
27
32
  /**
28
33
  * Query string without `?`, from the server page's `searchParams`.
29
34
  * The hook must not call Next's search-params hook: that suspends the
@@ -0,0 +1,101 @@
1
+ "use client";
2
+
3
+ import { useEffect, useMemo, useRef, useState } from "react";
4
+
5
+ import {
6
+ clusterPins,
7
+ emptyMapSearchResult,
8
+ MAP_VIEWPORT_DEBOUNCE_MS,
9
+ mapSearchSubscriptionKey,
10
+ subscribeMapSearch,
11
+ type MapSearchResult,
12
+ type MapSearchSubscription,
13
+ } from "../map-search";
14
+ import type { MapBounds, MapPinCluster, MapPolygon } from "../types-maps";
15
+
16
+ export interface UseMapSearchOptions extends Omit<
17
+ MapSearchSubscription,
18
+ "bounds" | "polygon"
19
+ > {
20
+ bounds?: MapBounds | null;
21
+ polygon?: MapPolygon | null;
22
+ /** Grid zoom for `clusterPins`. Changing it does not refetch. Default 14. */
23
+ zoom?: number;
24
+ /** Set false to keep the last result without fetching. */
25
+ enabled?: boolean;
26
+ /** Default 400, matching Foundation's map viewport debounce. */
27
+ debounceMs?: number;
28
+ }
29
+
30
+ export interface UseMapSearchResult extends MapSearchResult {
31
+ clusters: MapPinCluster[];
32
+ loading: boolean;
33
+ error: Error | null;
34
+ }
35
+
36
+ const IDLE: MapSearchResult = emptyMapSearchResult();
37
+
38
+ function areaKey(options: UseMapSearchOptions): string {
39
+ return JSON.stringify({
40
+ search: mapSearchSubscriptionKey(options),
41
+ enabled: options.enabled !== false,
42
+ debounceMs: options.debounceMs ?? MAP_VIEWPORT_DEBOUNCE_MS,
43
+ });
44
+ }
45
+
46
+ /**
47
+ * Search listings as the map moves. Debounces, aborts the previous request,
48
+ * and clusters the masked pins for the current zoom without another search.
49
+ * Disabling keeps the last result and settles `loading`: abort is not an event.
50
+ */
51
+ export function useMapSearch(options: UseMapSearchOptions): UseMapSearchResult {
52
+ const [result, setResult] = useState<MapSearchResult>(IDLE);
53
+ const [loading, setLoading] = useState(false);
54
+ const [error, setError] = useState<Error | null>(null);
55
+ const optionsRef = useRef(options);
56
+ optionsRef.current = options;
57
+ const key = areaKey(options);
58
+ const zoom = options.zoom ?? 14;
59
+
60
+ useEffect(() => {
61
+ const current = optionsRef.current;
62
+ if (current.enabled === false) {
63
+ // The previous subscription's abort is ignored, and this effect does
64
+ // not start a replacement search, so nothing else can clear `loading`.
65
+ setLoading(false);
66
+ return;
67
+ }
68
+ return subscribeMapSearch(
69
+ current,
70
+ (event) => {
71
+ if (event.type === "empty") {
72
+ setResult(emptyMapSearchResult(current.pageSize));
73
+ setLoading(false);
74
+ setError(null);
75
+ return;
76
+ }
77
+ if (event.type === "loading") {
78
+ setLoading(true);
79
+ setError(null);
80
+ return;
81
+ }
82
+ if (event.type === "error") {
83
+ setLoading(false);
84
+ setError(event.error);
85
+ return;
86
+ }
87
+ setResult(event.result);
88
+ setLoading(false);
89
+ setError(null);
90
+ },
91
+ { debounceMs: current.debounceMs }
92
+ );
93
+ }, [key]);
94
+
95
+ const clusters = useMemo(
96
+ () => clusterPins(result.pins, zoom),
97
+ [result.pins, zoom]
98
+ );
99
+
100
+ return { ...result, clusters, loading, error };
101
+ }
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
4
  import { usePathname, useRouter } from "next/navigation";
5
5
 
6
6
  import { getSearchUi, queryListings } from "../fetchers";
7
+ import { publishableKeyHeaders } from "../internal/sdk-http";
7
8
  import { coerceSiteId, normalizeBaseUrl } from "../internal/url";
8
9
  import {
9
10
  applyPathFilter,
@@ -44,7 +45,13 @@ function currentHref(pathname: string, search: string): string {
44
45
  export function usePublicSearch(
45
46
  options: UsePublicSearchOptions
46
47
  ): PublicSearchState {
47
- const { siteId, baseUrl, initial, search: searchFromServer = "" } = options;
48
+ const {
49
+ siteId,
50
+ baseUrl,
51
+ publishableKey,
52
+ initial,
53
+ search: searchFromServer = "",
54
+ } = options;
48
55
  const router = useRouter();
49
56
  const pathname = usePathname() || "/imoveis";
50
57
  const search = searchFromServer;
@@ -149,13 +156,23 @@ export function usePublicSearch(
149
156
  }
150
157
  async function loadSchema() {
151
158
  try {
152
- const nextSchema = await getSearchUi({ siteId: id, baseUrl });
159
+ const nextSchema = await getSearchUi({
160
+ siteId: id,
161
+ baseUrl,
162
+ publishableKey,
163
+ });
153
164
  if (!active) return;
154
165
  let locations: LocationNameTables | null = null;
155
166
  if (nextSchema.locationsPath.startsWith("/")) {
156
167
  try {
157
168
  const response = await fetch(
158
- `${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`
169
+ `${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`,
170
+ {
171
+ headers: {
172
+ Accept: "application/json",
173
+ ...publishableKeyHeaders(publishableKey),
174
+ },
175
+ }
159
176
  );
160
177
  if (response.ok) {
161
178
  locations = (await response.json()) as LocationNameTables;
@@ -192,7 +209,7 @@ export function usePublicSearch(
192
209
  return () => {
193
210
  active = false;
194
211
  };
195
- }, [baseUrl, catalogId]);
212
+ }, [baseUrl, catalogId, publishableKey]);
196
213
 
197
214
  useEffect(() => {
198
215
  if (!schema || !catalogId) return;
@@ -218,6 +235,7 @@ export function usePublicSearch(
218
235
  const response = await queryListings({
219
236
  siteId: id,
220
237
  baseUrl,
238
+ publishableKey,
221
239
  params: buildQueryListingsParams(
222
240
  pathFilters,
223
241
  applied,
@@ -257,7 +275,7 @@ export function usePublicSearch(
257
275
  return () => {
258
276
  active = false;
259
277
  };
260
- }, [pathname, search, baseUrl, schema, catalogId]);
278
+ }, [pathname, search, baseUrl, schema, catalogId, publishableKey]);
261
279
 
262
280
  const go = useCallback(
263
281
  (href: string) => {
@@ -7,6 +7,8 @@ export interface ResolvePublicSiteIdOptions {
7
7
  fallback?: string | null;
8
8
  baseUrl?: string;
9
9
  fetch?: FetchLike;
10
+ /** Forwarded to `getSite` when the live host is resolved. */
11
+ publishableKey?: string;
10
12
  }
11
13
 
12
14
  /** v0 in-chat preview only. Published Studio sites often live on `*.vercel.app`. */
@@ -38,6 +40,7 @@ export async function resolvePublicSiteId(
38
40
  domain: host,
39
41
  baseUrl: options.baseUrl,
40
42
  fetch: options.fetch,
43
+ publishableKey: options.publishableKey,
41
44
  });
42
45
  if (site?.id) return site.id;
43
46
  throw new GaragemSdkError(
@@ -99,6 +99,29 @@ export const STUDIO_SDK_CONTRACT = {
99
99
  */
100
100
  unpublishedPhoneExports: [] as const,
101
101
  amenityExports: ["listingAmenityGroups"] as const,
102
+ /**
103
+ * Prompt-safe photo helpers on `minNpmVersion`. Empty until the release
104
+ * that carries `getSimilarByPhoto` / `listingPhotoGroups` /
105
+ * `listingVisualHighlights` is on npm; then bump the pin, move the names
106
+ * here from `unpublishedPhotoExports`, and `studioPhotoInstruction()`
107
+ * starts teaching the gallery-by-room, highlight chips, and
108
+ * "imóveis com fotos parecidas" blocks. The caption-based `media[].alt` /
109
+ * `media[].caption` fields are API data (not tarball exports) and are
110
+ * documented regardless of the pin.
111
+ */
112
+ photoExports: [] as const,
113
+ /**
114
+ * Photo helpers in the repo but not on `minNpmVersion`. Prompts,
115
+ * completeness, and repair text must not mention these until the pin
116
+ * bumps — v0 installs the pin and the ESM loader throws on missing named
117
+ * exports.
118
+ */
119
+ unpublishedPhotoExports: [
120
+ "getSimilarByPhoto",
121
+ "listingPhotoGroups",
122
+ "listingVisualHighlights",
123
+ "photoRoomLabel",
124
+ ] as const,
102
125
  /**
103
126
  * Names already on the pinned npm tarball (`minNpmVersion`) — safe for
104
127
  * Studio prompts and completeness. Includes `visibleSearchFilters` +
@@ -123,6 +146,27 @@ export const STUDIO_SDK_CONTRACT = {
123
146
  "searchChromeModel",
124
147
  "rangeDraftFromPath",
125
148
  ] as const,
149
+ /**
150
+ * maps.fndn.ai helpers (static map, street view, boundaries, travel
151
+ * time) plus friendly map search. They ship in `mapsSince`;
152
+ * `studioMapsInstruction()` is empty and these names are codegen
153
+ * violations until `minNpmVersion` reaches that release — bump the pin
154
+ * after the tarball is on npm and the listing guidance turns on by
155
+ * itself. `useMapSearch` is a `/react` hook named in that same
156
+ * instruction; it stays off `reactExports` until the pin moves.
157
+ */
158
+ mapsSince: "0.7.0",
159
+ mapsExports: [
160
+ "listingStaticMapUrl",
161
+ "listingStreetViewUrl",
162
+ "listingStreetViewAvailable",
163
+ "neighborhoodBoundaryLayer",
164
+ "boundaryLayerUrl",
165
+ "travelTimeFromListing",
166
+ "searchListingsInBounds",
167
+ "searchListingsInPolygon",
168
+ "clusterPins",
169
+ ] as const,
126
170
  /**
127
171
  * Market-data helpers (neighborhood price summary, listing market
128
172
  * position, visitor price estimate, pt-BR labels). They ship in
@@ -270,6 +314,17 @@ export function unavailableReactImports(source: string, pin: string): string[] {
270
314
  return missing;
271
315
  }
272
316
 
317
+ /**
318
+ * Studio copy for the public site API key. Names only exports that already
319
+ * exist on `minNpmVersion` (`createGaragemClient`, `GaragemSdkError`,
320
+ * `usePublicSearch`, the lead helpers). `publishableKey` is an extra option
321
+ * older tarballs ignore, so generated sites keep working before this SDK
322
+ * version is published.
323
+ */
324
+ export function studioPublishableKeyInstruction(): string {
325
+ return `Public site API key (optional, backwards compatible). \`publishableKey\` (\`pk_live_…\`) is not a secret. Create or rotate it in Garagem at Configurações → Sites → the site → API pública (route \`/configuracoes/sites/[siteId]\`, section API pública (SDK)). Pass it to \`createGaragemClient({ siteId, baseUrl: GARAGEM_API_BASE, publishableKey })\` or on each call: \`getListings\`, \`getListing\`, \`getSite\`, \`getSearchUi\`, \`queryListings\`, \`searchListings\`, the CMS helpers, \`getLeadUi\`, \`submitVisitLead\`, \`submitContactLead\`, and \`usePublicSearch\`. The SDK sends header \`X-Garagem-Publishable-Key\` (a Bearer token that starts with \`pk_live_\` is also accepted). Omitting the key still succeeds. Once a site has a key, anonymous traffic uses the stricter per-IP budget (listings/search 30/min, detail 60/min, config 30/min). A site with no key uses the looser anonymous budget (120 / 300 / 120). With the key, budgets are listings/search 600/min, detail 1200/min, config 300/min. Window is 60 seconds. Success and 429 responses carry \`RateLimit-Limit\`, \`RateLimit-Remaining\`, \`RateLimit-Reset\`, and \`RateLimit-Policy\`. HTTP 401 throws \`GaragemSdkError\` with \`status\` 401 and \`reason\` \`invalid_publishable_key\` (wrong key). HTTP 403 has \`reason\` \`origin_not_allowed\` when the site's origin allowlist rejects the browser Origin or Referer. HTTP 429 has \`reason\` \`rate_limited\` and \`retryAfter\` seconds (same value as the \`Retry-After\` header). \`LeadSubmitError\` uses \`code\` \`rate_limited\` or \`unauthorized\`, and \`retryAfter\` / \`retryAfterSeconds\` on 429. A public constant next to \`GARAGEM_API_BASE\` is the right place for the key. Do not invent a second header name.`;
326
+ }
327
+
273
328
  export function studioSdkPinInstruction(): string {
274
329
  const version = STUDIO_SDK_CONTRACT.minNpmVersion;
275
330
  const names = [...reactExportsAvailableAt(version)].join(", ");
@@ -292,6 +347,41 @@ export function studioListingDetailInstruction(): string {
292
347
  return `Listing detail: import ${names} from \`${STUDIO_SDK_PACKAGE}\`. Render \`listingDetailModel\` leaves: \`model.facts[].label\` / \`.text\`, \`model.values[].label\` / \`.text\`, \`model.location.label\` / \`model.location.mapsHref\`, breadcrumb \`.href\` (search prefixes of \`listing.path\`). The preço / sob consulta entry is the primary value; condomínio and IPTU are secondary and omitted when missing. \`model.description\` is the complete string — do not slice. A collapsed disclosure uses a container (max-height or overflow), not a cut of the string. Never interpolate \`model.location\`, \`model.facts\`, \`model.values\`, \`model.breadcrumb\`, or \`model.mediaOverlays\` as a React child. Video/tour: \`model.mediaOverlays\` as hash links (\`#video\` / \`#tour\`); player src is \`embedSrc\`; fullscreen overlay closes with browser back; omit when that overlay is absent. Do not key the page on \`location.hash\`. Similar listings: \`getSimilarListings({ siteId, listingId, baseUrl })\` plus the site listing-card module; hide the section when empty. Do not invent a local recommendation loop.`;
293
348
  }
294
349
 
350
+ /**
351
+ * Listing-detail photo intelligence, gated on the published pin. The base
352
+ * sentence (caption-based `alt` / optional `caption` on gallery photos) is
353
+ * API data and always applies; each helper block appears only when its
354
+ * export is in `published` (see `STUDIO_SDK_CONTRACT.photoExports`).
355
+ */
356
+ export function studioPhotoInstructionFor(
357
+ published: readonly string[]
358
+ ): string {
359
+ const has = (name: string) => published.includes(name);
360
+ const parts = [
361
+ `Gallery photo text: \`item.alt\` on \`listing.media\` is the photo caption when the platform analyzed it (else "<title> - Foto N") — always pass it as the img alt. \`item.caption\` is optional: show it as the slide / overlay caption when present and omit the element when absent. Never invent captions or room names in generated source.`,
362
+ ];
363
+ if (has("listingPhotoGroups")) {
364
+ parts.push(
365
+ `Gallery by room: \`const groups = listingPhotoGroups(listing)\` from \`${STUDIO_SDK_PACKAGE}\` returns \`{ key, label, photos }[]\` (pt-BR labels such as "Sala", "Quartos", "Cozinha"; "Outras fotos" last). Use it only inside the fullscreen photo overlay (room tabs or section headings over the thumbnail strip) — the page carousel stays one flat section. Render \`group.label\` and \`group.photos.length\`; when \`groups.length <= 1\` render the flat strip without headings. Never read \`item.roomType\` / \`item.sceneType\` directly to build sections and never hardcode room names.`
366
+ );
367
+ }
368
+ if (has("listingVisualHighlights")) {
369
+ parts.push(
370
+ `Visual highlights: \`const highlights = listingVisualHighlights(listing, { limit: 6 })\` returns deduped strings ("piso de madeira", "vista livre"). Render them as small chips (site tokens, \`--radius\`) under the gallery or beside the facts, one chip per string, and omit the block when the array is empty. Do not merge them with \`listingAmenityGroups\` and do not read \`item.features\` directly.`
371
+ );
372
+ }
373
+ if (has("getSimilarByPhoto")) {
374
+ parts.push(
375
+ `Imóveis com fotos parecidas: on the server page, pick the first image item of \`listing.media\` and \`await getSimilarByPhoto(siteId, listing.id, photo.id, { limit: 6, baseUrl: GARAGEM_API_BASE })\` from \`${STUDIO_SDK_PACKAGE}\` (positional ids; \`listing.id\` is the UUID, never the path). The result is \`{ available, items }\`: when \`available === false\` (tenant without image search, or \`photo.id\` is not a media UUID such as the \`image-N\` / \`external-N\` gallery keys — that returns locally and does not throw) render nothing — no heading, no empty state; when \`items.length === 0\` also render nothing. Otherwise a section titled "Imóveis com fotos parecidas" with the site listing-card module (\`toListingCardModel(item.listing)\`), using \`item.matchedPhoto.src\` / \`item.matchedPhoto.alt\` as that card's photo. Keep \`getSimilarListings\` as the default similar carousel; this section is additional, below it. Wrap the call in try/catch and treat an error like \`available: false\`.`
376
+ );
377
+ }
378
+ return parts.join(" ");
379
+ }
380
+
381
+ export function studioPhotoInstruction(): string {
382
+ return studioPhotoInstructionFor(STUDIO_SDK_CONTRACT.photoExports);
383
+ }
384
+
295
385
  export function studioAmenityInstruction(): string {
296
386
  return `Listing amenities: Portuguese labels from \`listingAmenityGroups(listing, dictionary)\` (pass the dictionary from \`getSearchUi()\` so section titles follow Campos). Each group is \`{ title, labels: string[] }\` — render \`group.title\` and \`group.labels.map((label) => …)\` and hide a group when \`group.labels.length === 0\`. Do not hardcode section titles. Never print amenity ids, never invent a local label map, and never title a section "Comodidades da unidade".`;
297
387
  }
@@ -302,6 +392,24 @@ export function studioSearchInstruction(): string {
302
392
  return `Search: import ${reactNames} from \`${STUDIO_SDK_PACKAGE}/react\`. From \`${STUDIO_SDK_PACKAGE}\` import ${libNames}. Prefetch \`getSearchUi\` + \`queryListings\` on the server page. \`const search = usePublicSearch({ siteId, baseUrl: GARAGEM_API_BASE, search: searchFromServer, initial })\` where \`searchFromServer\` is \`new URLSearchParams(await searchParams).toString()\` — never shorthand \`{ search }\` beside \`const search =\` (temporal dead zone). Do not wrap this UI in \`<Suspense>\` and do not add a route \`loading\` file — heading and cards are ordinary elements in the document, visible with JavaScript off. Compose the page UI in the app — do not paste a canonical search TSX. Required chrome (design is free; omit none): query (\`qDraft\` / \`setQDraft\` / form \`preventDefault\` + \`submitQuery\`), heading (count span FIRST then h1 from \`searchResultsHeading(search.pathFilters, search.schema?.dictionary, search.locationNames)\` — never \`searchResultsHeading({})\`), toolbar (\`toolbarFilterIds\` + \`applyFilter\`; range “Atualizar” on that toolbar item only) vs sheet (\`visibleSearchFilters\` extras, \`stageFilter\`, one footer \`applyStaged\`), sort (\`searchSortOptions\` + \`setSort\`; first option id is \`""\` / “Mais relevantes” — map **only** that empty id to Select sentinel \`"relevancia"\` (\`opt.id || "relevancia"\`), never \`SelectItem value=""\` and never give “Mais recentes” (\`id: "recentes"\`, \`?ordenar=recentes\`) that sentinel; on change \`setSort(id === "relevancia" ? "" : id)\` so recentes stays recentes. Closed trigger shows the option \`.label\`, never \`{search.applied.sort}\`), grid (\`listings.map\` + the site listing-card module; listing-card-skeleton only for a slot whose content is still unknown, never as a Suspense fallback; do not \`throw\` in that chrome), pagination (\`paginationPages\` + \`hrefWithExplicitPage\`). Never interpolate \`schema\`, \`pathFilters\`, or a filter object as a React child. \`queryListings\` key is \`params\`. The URL is the document. Count text is \`{search.total}\` only. Heading is one row; font size lives on the container and the span and h1 use \`font-size: inherit\`. Sort trigger shows the option label (“Mais relevantes” when \`ordenar\` is absent), chevron at the end, same height as the toolbar controls. Toolbar ranges open a Popover form (not DropdownMenu — Menu typeahead swallows digit keys) whose submit calls \`applyFilter\`; the popup clips and the two inputs stay inside (\`min-w-0\`, no \`w-64\`). Reset min/max drafts when the popover opens and when the applied path range changes. The sheet omits toolbar ids (price, bedrooms) so Preço is never a heading without inputs. Sheet DialogContent uses \`h-[min(640px,85dvh)]\` (not max-h alone) so the body ScrollArea can move. Tipo de imóvel, características and comodidades each use a nested ScrollArea with \`h-56 overflow-hidden\` (viewport \`h-full\`). Area is two inputs in schema order with no “Aplicar”; the footer stages then applyStaged. Never read \`staged[filter.id]\` — path keys are \`bedrooms\` / \`listingType\` / \`bathrooms\`. Bedrooms Select reads \`pathFilters.bedrooms\` so \`/imoveis/4-quartos\` checks \`"4"\` and shows the same trigger dot as price. Bathrooms and parking pressed state uses \`pathFilterHasOption\`. Limpar keeps location plus toolbar price and bedrooms via \`clearStagedPathFilters\` and \`toolbarFilterIds\`; do not call \`clearStaged\` for that button. It enables only when staged has a path filter other than location and those kept toolbar ids. Each multi-select \`stageFilter\` value is one option id, never a concatenated slug; \`checked\` uses \`pathFilterHasOption\`. Listing type does not pass the clicked id: no path value shows every checkbox checked, unchecking one stages the other option's id, and the last box stays checked. Price inputs use formatGroupedInteger. The closed price and bedrooms triggers keep the filter label plus a dot when set — never the literal range. Empty price calls applyFilter(id, undefined); never send 0 or 1000000000. Area is a plain integer (not that mask). The results button stageFilter property_area_total with both drafts, then applyStaged. Never send 0 or 100000. Count buttons pass the option id (\`"2"\`), never the label \`"2+"\`. Property type, features, and amenities render in pt-BR label order. Do not set \`[data-slot="search-sort"] { flex-direction: column }\` in a \`<style>\` tag; that selector is row so the chevron sits beside the label. Empty copy: ${JSON.stringify(SEARCH_EMPTY_COPY)}`;
303
393
  }
304
394
 
395
+ /** Whether the Studio pin already carries the maps helpers. */
396
+ export function mapsExportsPublished(
397
+ pin: string = STUDIO_SDK_CONTRACT.minNpmVersion
398
+ ): boolean {
399
+ return compareSemver(pin, STUDIO_SDK_CONTRACT.mapsSince) >= 0;
400
+ }
401
+
402
+ /**
403
+ * Listing-detail maps guidance. Empty while the pinned tarball predates
404
+ * `mapsSince`, because v0 copies every identifier it reads and the preview
405
+ * ESM loader throws on a missing named export.
406
+ */
407
+ export function studioMapsInstruction(options: { pin?: string } = {}): string {
408
+ if (!mapsExportsPublished(options.pin)) return "";
409
+ const names = STUDIO_SDK_CONTRACT.mapsExports.join(", ");
410
+ return `Maps on listing detail: from \`${STUDIO_SDK_PACKAGE}\` import ${names}. \`listing.location.coordinates\` is already masked by the site's privacy settings (≈100 m by default) — pass the listing object as-is; never un-mask, never re-geocode the street address to get a sharper point, never add decimals (\`maxDecimals\` can only coarsen). Always pass \`siteId\` (the resolved site id / publishable key) so maps.fndn.ai meters the site. Static map: \`const mapSrc = listingStaticMapUrl(listing, { width: 640, height: 320, zoom: 15, style: "roadmap", siteId })\` then \`{mapSrc ? <img src={mapSrc} alt={model.location.label} /> : null}\` — \`null\` means no coordinates, so omit the block (never a placeholder image). Zoom is capped by the coordinate precision (16 on the default mask); do not work around it. Street View: on the server page \`const sv = await listingStreetViewAvailable(listing, { siteId })\` (metadata is free), and only when \`sv.available\` render \`<img src={listingStreetViewUrl(listing, { width: 640, height: 400, siteId })} alt="Street View" />\` — the image is billed per load. Neighbourhood outline on an interactive map: load Maps JS ONLY through \`<script src="https://maps.fndn.ai/sdk.js?callback=initMap" async defer />\` (never a Google key in the app, never \`NEXT_PUBLIC_GOOGLE_MAPS_API_KEY\`); in \`initMap\` do \`const outline = await neighborhoodBoundaryLayer(listing.location.city, listing.location.neighborhood, { siteId })\` and \`if (outline.feature) map.data.addGeoJson(outline.feature)\`; with MapLibre the vector source url is \`boundaryLayerUrl(listing.location.city)\`. Travel time (“quanto tempo até…”): \`const trip = await travelTimeFromListing(listing, destination, { mode: "driving", siteId })\` gives \`{ minutes, distanceKm }\` or \`null\` (hide the row). Every uncached call is a billed Google Directions request: call it on demand — a destination the visitor typed, or at most one fixed landmark per listing page — never per listing card, never inside a search loop, keep the SDK cache on (default 15 min LRU, \`cache: null\` only in tests), and do not re-run it on every render. Map search (search page: search as the map moves, or draw an area): searchListingsInBounds(siteId, { bounds: { north, south, east, west }, zoom, q, sort, location, filters, page, pageSize, publishableKey }) and searchListingsInPolygon(siteId, { polygon: [[lat, lng], ...], q, sort, location, filters, page, pageSize, publishableKey }). Polygon points are [lat, lng], not GeoJSON. The server builds the allowlisted coordinates geo filter from those numbers; do not send a raw filter string from the browser. Pins are { id, lat, lng, price, coverImage } copied from the listings the API returned — masked pins, plot them as returned, never geocode the street to sharpen one. clusterPins(pins, zoom) is the headless grid: one pin keeps its coordinates, a group centroid is rounded back to the coarsest pin. The React hook useMapSearch (on the /react entry, next to usePublicSearch) debounces viewport changes by 400ms, cancels the stale request, caps pageSize at 100, and returns those pins plus cards from toListingCardModel. Pass the same q, sort, location, filters, and publishableKey as the list (queryListings / usePublicSearch). Dropping them pins listings outside the active query or spends the anonymous listings budget. Cost: every viewport change is a search call — keep the debounce, do not raise the page size, and do not call travel time or Street View inside that loop.`;
411
+ }
412
+
305
413
  /** True when the pinned tarball ships the market-data helpers. */
306
414
  export function marketExportsAvailableAt(pin: string): boolean {
307
415
  return compareSemver(pin, STUDIO_SDK_CONTRACT.marketExportsSince) >= 0;
@@ -380,6 +488,18 @@ export function studioCodegenContractViolations(text: string): string[] {
380
488
  violations.push(name);
381
489
  }
382
490
  }
491
+ if (!mapsExportsPublished()) {
492
+ for (const name of STUDIO_SDK_CONTRACT.mapsExports) {
493
+ if (mentionsExportName(text, name) && !violations.includes(name)) {
494
+ violations.push(name);
495
+ }
496
+ }
497
+ }
498
+ for (const name of STUDIO_SDK_CONTRACT.unpublishedPhotoExports) {
499
+ if (mentionsExportName(text, name) && !violations.includes(name)) {
500
+ violations.push(name);
501
+ }
502
+ }
383
503
  if (!isPhotoSearchOnPin()) {
384
504
  for (const name of STUDIO_SDK_CONTRACT.photoSearchExports) {
385
505
  if (mentionsExportName(text, name) && !violations.includes(name)) {
@@ -0,0 +1,275 @@
1
+ /**
2
+ * Types for the maps.fndn.ai helpers (`./maps`). Everything here works on
3
+ * the coordinates the public listings API already returns — those are
4
+ * masked per site (≈100 m by default) and the helpers never add precision.
5
+ */
6
+
7
+ import type { FetchLike } from "./fetchers";
8
+
9
+ /** `{ lat, lng }` pair as returned on `listing.location.coordinates`. */
10
+ export interface MapsCoordinates {
11
+ lat: number;
12
+ lng: number;
13
+ }
14
+
15
+ /**
16
+ * Anything carrying a public listing location: `Listing`, `ListingDetail`,
17
+ * a card model, or a bare `{ location: { coordinates } }`.
18
+ */
19
+ export type ListingWithLocation =
20
+ | {
21
+ location?: { coordinates?: MapsCoordinates | null } | null;
22
+ }
23
+ | null
24
+ | undefined;
25
+
26
+ export interface MapsBaseOptions {
27
+ /** maps.fndn.ai origin. Defaults to `https://maps.fndn.ai`. */
28
+ mapsBaseUrl?: string;
29
+ /**
30
+ * Site id (or publishable key) used to meter this site's usage on
31
+ * maps.fndn.ai. Sent as the `site` query param on image URLs and as the
32
+ * `X-Garagem-Site` header on fetches. Optional today; it only labels
33
+ * metrics and the per-site rate limit, it is not authentication.
34
+ */
35
+ siteId?: string;
36
+ }
37
+
38
+ export interface MapsFetchOptions extends MapsBaseOptions {
39
+ /** Override the fetch implementation (testing, edge runtimes, retries). */
40
+ fetch?: FetchLike;
41
+ }
42
+
43
+ /** Google Static Maps map type. `style` is the SDK-facing alias. */
44
+ export type StaticMapStyle = "roadmap" | "satellite" | "terrain" | "hybrid";
45
+
46
+ export interface StaticMapOptions extends MapsBaseOptions {
47
+ /** Pixels, 1–640 (Google Static Maps ceiling). Default 600. */
48
+ width?: number;
49
+ /** Pixels, 1–640. Default 300. */
50
+ height?: number;
51
+ /**
52
+ * 1–21. Default 15. Capped by the coordinate precision the API applied:
53
+ * a ≈100 m masked point is never rendered above zoom 16, so the pin does
54
+ * not pretend to know the exact building. See `maxZoomForCoordinates`.
55
+ */
56
+ zoom?: number;
57
+ /** 1 or 2 (retina). Default 2. */
58
+ scale?: 1 | 2;
59
+ /** Map style. Default roadmap. */
60
+ style?: StaticMapStyle;
61
+ /** Marker color (Google color name or `0xRRGGBB`). Default red. */
62
+ markerColor?: string;
63
+ /** Hide points of interest. Default false. */
64
+ hidePoi?: boolean;
65
+ /**
66
+ * Max decimal places to send. Only ever *reduces* precision (e.g. send
67
+ * 2 decimals ≈ 1 km for a neighbourhood teaser); it cannot recover
68
+ * precision the API removed.
69
+ */
70
+ maxDecimals?: number;
71
+ }
72
+
73
+ export interface StreetViewOptions extends MapsBaseOptions {
74
+ /** Pixels, 1–640. Default 640. */
75
+ width?: number;
76
+ /** Pixels, 1–640. Default 640. */
77
+ height?: number;
78
+ /** Field of view in degrees, 10–120. Default 90. */
79
+ fov?: number;
80
+ /** Compass heading 0–360. Default 0. */
81
+ heading?: number;
82
+ /** Camera pitch -90–90. Default 10. */
83
+ pitch?: number;
84
+ /** See `StaticMapOptions.maxDecimals`. */
85
+ maxDecimals?: number;
86
+ }
87
+
88
+ export interface StreetViewAvailabilityOptions extends MapsFetchOptions {
89
+ /** See `StaticMapOptions.maxDecimals`. */
90
+ maxDecimals?: number;
91
+ }
92
+
93
+ export interface StreetViewAvailability {
94
+ /** `true` when Google has a panorama near the (masked) coordinates. */
95
+ available: boolean;
96
+ /** Google metadata status: `OK`, `ZERO_RESULTS`, `ERROR`, … */
97
+ status: string;
98
+ /** Panorama id when available. */
99
+ panoId?: string;
100
+ /** Capture date (`YYYY-MM`) when available. */
101
+ date?: string;
102
+ /** maps.fndn.ai metadata URL that was queried. */
103
+ url: string;
104
+ }
105
+
106
+ /** Cities with boundary layers on maps.fndn.ai. Other slugs pass through. */
107
+ export type BoundaryCity = "sao_paulo" | "rio_de_janeiro" | (string & {});
108
+
109
+ export type BoundaryLayerUrlKind =
110
+ /** `GET /v1/layers/:id` — layer descriptor JSON. */
111
+ | "layer"
112
+ /** TileJSON for MapLibre `addSource({ type: "vector", url })`. */
113
+ | "tilejson"
114
+ /** `{z}/{x}/{y}` vector tile template. */
115
+ | "tiles"
116
+ /** Whole-city GeoJSON FeatureCollection. */
117
+ | "geojson";
118
+
119
+ export interface BoundaryLayerOptions extends MapsBaseOptions {
120
+ kind?: BoundaryLayerUrlKind;
121
+ }
122
+
123
+ export interface BoundarySourceLayer {
124
+ id: string;
125
+ label: string;
126
+ minzoom?: number;
127
+ maxzoom?: number;
128
+ }
129
+
130
+ /** Subset of the maps.fndn.ai `/v1/layers/:id` descriptor the SDK exposes. */
131
+ export interface BoundaryLayer {
132
+ id: string;
133
+ name: string;
134
+ description: string;
135
+ city?: string;
136
+ /** `{z}/{x}/{y}` template. */
137
+ tiles: string;
138
+ tilejson: string;
139
+ /** Whole-city GeoJSON, when published. */
140
+ geojson?: string;
141
+ sourceLayers: BoundarySourceLayer[];
142
+ minzoom: number;
143
+ maxzoom: number;
144
+ attribution?: string;
145
+ available: boolean;
146
+ }
147
+
148
+ /** Minimal GeoJSON shapes so the SDK does not depend on `@types/geojson`. */
149
+ export interface BoundaryGeometry {
150
+ type: string;
151
+ coordinates: unknown;
152
+ }
153
+
154
+ export interface BoundaryFeature {
155
+ type: "Feature";
156
+ properties: Record<string, unknown> & { name?: string; level?: string };
157
+ geometry: BoundaryGeometry | null;
158
+ [key: string]: unknown;
159
+ }
160
+
161
+ export interface BoundaryFeatureCollection {
162
+ type: "FeatureCollection";
163
+ features: BoundaryFeature[];
164
+ count?: number;
165
+ source?: string;
166
+ }
167
+
168
+ export interface NeighborhoodBoundaryOptions extends MapsFetchOptions {
169
+ /**
170
+ * Boundary dataset. Default `listaaberta` (SP districts / RJ
171
+ * neighbourhoods with IPTU stats); `osm` covers more cities.
172
+ */
173
+ source?: "listaaberta" | "osm" | "all";
174
+ }
175
+
176
+ export interface NeighborhoodBoundary {
177
+ city: string;
178
+ neighborhood: string;
179
+ /** The matched outline, or `null` when nothing matched. */
180
+ feature: BoundaryFeature | null;
181
+ /** Every candidate when the name matched more than one feature. */
182
+ candidates: BoundaryFeature[];
183
+ /** GeoJSON URL that was queried (safe to pass to MapLibre `data`). */
184
+ url: string;
185
+ /** Vector tile template for the city's boundary layer. */
186
+ tiles: string;
187
+ }
188
+
189
+ export type TravelMode = "driving" | "walking" | "bicycling" | "transit";
190
+
191
+ /** Coordinates, or a free-text address geocoded on maps.fndn.ai first. */
192
+ export type TravelDestination = MapsCoordinates | string;
193
+
194
+ export interface TravelTimeOptions extends MapsFetchOptions {
195
+ /** Default `driving`. */
196
+ mode?: TravelMode;
197
+ /** Client-side cache. Defaults to a module-level LRU; pass `null` to skip. */
198
+ cache?: TravelTimeCache | null;
199
+ /** See `StaticMapOptions.maxDecimals`. */
200
+ maxDecimals?: number;
201
+ }
202
+
203
+ export interface TravelTime {
204
+ /** Rounded travel time in minutes (minimum 1 when a route exists). */
205
+ minutes: number;
206
+ seconds: number;
207
+ distanceMeters: number;
208
+ /** Distance rounded to one decimal. */
209
+ distanceKm: number;
210
+ mode: TravelMode;
211
+ origin: MapsCoordinates;
212
+ destination: MapsCoordinates;
213
+ /** `true` when served from the client-side cache. */
214
+ cached: boolean;
215
+ }
216
+
217
+ export interface TravelTimesOptions extends MapsFetchOptions {
218
+ /** See `StaticMapOptions.maxDecimals`. */
219
+ maxDecimals?: number;
220
+ }
221
+
222
+ /** One route-matrix element; `null` when Google found no route. */
223
+ export interface TravelTimeElement {
224
+ minutes: number;
225
+ seconds: number;
226
+ destination: MapsCoordinates;
227
+ }
228
+
229
+ export interface TravelTimeCacheOptions {
230
+ /** Default 200 entries. */
231
+ maxEntries?: number;
232
+ /** Default 15 minutes. */
233
+ ttlMs?: number;
234
+ }
235
+
236
+ export interface TravelTimeCache {
237
+ get(key: string): TravelTime | undefined;
238
+ set(key: string, value: TravelTime): void;
239
+ clear(): void;
240
+ readonly size: number;
241
+ }
242
+
243
+ // ---------------------------------------------------------------------------
244
+ // Map search (friendly public listings route, not raw Typesense)
245
+ // ---------------------------------------------------------------------------
246
+
247
+ /** Viewport rectangle in degrees. `east` must be greater than `west`. */
248
+ export interface MapBounds {
249
+ north: number;
250
+ south: number;
251
+ east: number;
252
+ west: number;
253
+ }
254
+
255
+ /** `[lat, lng]` vertices. Not GeoJSON `[lng, lat]`. */
256
+ export type MapPolygon = Array<[number, number]>;
257
+
258
+ /** Pin plotted from a public listing. Coordinates are already masked. */
259
+ export interface MapPin {
260
+ id: string;
261
+ lat: number;
262
+ lng: number;
263
+ price: number | null;
264
+ coverImage: string | null;
265
+ }
266
+
267
+ /** One grid cell. `count === 1` keeps the pin's own coordinates. */
268
+ export interface MapPinCluster {
269
+ id: string;
270
+ lat: number;
271
+ lng: number;
272
+ count: number;
273
+ pinIds: string[];
274
+ pin: MapPin | null;
275
+ }