@garagem-ai/site-sdk 0.8.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/dist/index.mjs CHANGED
@@ -287,7 +287,7 @@ async function getSearchUi(options) {
287
287
  );
288
288
  }
289
289
  async function queryListings(options) {
290
- const { params, baseUrl, fetch: fetchImpl, next } = options;
290
+ const { params, baseUrl, fetch: fetchImpl, next, signal } = options;
291
291
  const siteId = await coerceSiteId(options.siteId);
292
292
  const base = normalizeBaseUrl(baseUrl);
293
293
  const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;
@@ -300,7 +300,8 @@ async function queryListings(options) {
300
300
  "Content-Type": "application/json"
301
301
  },
302
302
  body: JSON.stringify(params ?? {}),
303
- next
303
+ next,
304
+ signal
304
305
  },
305
306
  fetchImpl ?? fetch,
306
307
  options.publishableKey
@@ -2860,6 +2861,27 @@ var STUDIO_SDK_CONTRACT = {
2860
2861
  "searchChromeModel",
2861
2862
  "rangeDraftFromPath"
2862
2863
  ],
2864
+ /**
2865
+ * maps.fndn.ai helpers (static map, street view, boundaries, travel
2866
+ * time) plus friendly map search. They ship in `mapsSince`;
2867
+ * `studioMapsInstruction()` is empty and these names are codegen
2868
+ * violations until `minNpmVersion` reaches that release — bump the pin
2869
+ * after the tarball is on npm and the listing guidance turns on by
2870
+ * itself. `useMapSearch` is a `/react` hook named in that same
2871
+ * instruction; it stays off `reactExports` until the pin moves.
2872
+ */
2873
+ mapsSince: "0.7.0",
2874
+ mapsExports: [
2875
+ "listingStaticMapUrl",
2876
+ "listingStreetViewUrl",
2877
+ "listingStreetViewAvailable",
2878
+ "neighborhoodBoundaryLayer",
2879
+ "boundaryLayerUrl",
2880
+ "travelTimeFromListing",
2881
+ "searchListingsInBounds",
2882
+ "searchListingsInPolygon",
2883
+ "clusterPins"
2884
+ ],
2863
2885
  /**
2864
2886
  * Market-data helpers (neighborhood price summary, listing market
2865
2887
  * position, visitor price estimate, pt-BR labels). They ship in
@@ -3033,6 +3055,14 @@ function studioSearchInstruction() {
3033
3055
  const libNames = STUDIO_SDK_CONTRACT.searchExports.join(", ");
3034
3056
  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()\` \u2014 never shorthand \`{ search }\` beside \`const search =\` (temporal dead zone). Do not wrap this UI in \`<Suspense>\` and do not add a route \`loading\` file \u2014 heading and cards are ordinary elements in the document, visible with JavaScript off. Compose the page UI in the app \u2014 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)\` \u2014 never \`searchResultsHeading({})\`), toolbar (\`toolbarFilterIds\` + \`applyFilter\`; range \u201CAtualizar\u201D on that toolbar item only) vs sheet (\`visibleSearchFilters\` extras, \`stageFilter\`, one footer \`applyStaged\`), sort (\`searchSortOptions\` + \`setSort\`; first option id is \`""\` / \u201CMais relevantes\u201D \u2014 map **only** that empty id to Select sentinel \`"relevancia"\` (\`opt.id || "relevancia"\`), never \`SelectItem value=""\` and never give \u201CMais recentes\u201D (\`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 (\u201CMais relevantes\u201D when \`ordenar\` is absent), chevron at the end, same height as the toolbar controls. Toolbar ranges open a Popover form (not DropdownMenu \u2014 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\xE7o 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\xF3vel, caracter\xEDsticas and comodidades each use a nested ScrollArea with \`h-56 overflow-hidden\` (viewport \`h-full\`). Area is two inputs in schema order with no \u201CAplicar\u201D; the footer stages then applyStaged. Never read \`staged[filter.id]\` \u2014 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 \u2014 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)}`;
3035
3057
  }
3058
+ function mapsExportsPublished(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3059
+ return compareSemver(pin, STUDIO_SDK_CONTRACT.mapsSince) >= 0;
3060
+ }
3061
+ function studioMapsInstruction(options = {}) {
3062
+ if (!mapsExportsPublished(options.pin)) return "";
3063
+ const names = STUDIO_SDK_CONTRACT.mapsExports.join(", ");
3064
+ return `Maps on listing detail: from \`${STUDIO_SDK_PACKAGE}\` import ${names}. \`listing.location.coordinates\` is already masked by the site's privacy settings (\u2248100 m by default) \u2014 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}\` \u2014 \`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" />\` \u2014 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 (\u201Cquanto tempo at\xE9\u2026\u201D): \`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 \u2014 a destination the visitor typed, or at most one fixed landmark per listing page \u2014 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 \u2014 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 \u2014 keep the debounce, do not raise the page size, and do not call travel time or Street View inside that loop.`;
3065
+ }
3036
3066
  function marketExportsAvailableAt(pin) {
3037
3067
  return compareSemver(pin, STUDIO_SDK_CONTRACT.marketExportsSince) >= 0;
3038
3068
  }
@@ -3083,6 +3113,13 @@ function studioCodegenContractViolations(text) {
3083
3113
  violations.push(name);
3084
3114
  }
3085
3115
  }
3116
+ if (!mapsExportsPublished()) {
3117
+ for (const name of STUDIO_SDK_CONTRACT.mapsExports) {
3118
+ if (mentionsExportName(text, name) && !violations.includes(name)) {
3119
+ violations.push(name);
3120
+ }
3121
+ }
3122
+ }
3086
3123
  for (const name of STUDIO_SDK_CONTRACT.unpublishedPhotoExports) {
3087
3124
  if (mentionsExportName(text, name) && !violations.includes(name)) {
3088
3125
  violations.push(name);
@@ -3281,6 +3318,633 @@ function createGaragemClient(options = {}) {
3281
3318
  }
3282
3319
  var createClient = createGaragemClient;
3283
3320
 
3321
+ // src/maps.ts
3322
+ var DEFAULT_MAPS_BASE_URL = "https://maps.fndn.ai";
3323
+ var MAPS_SITE_HEADER = "X-Garagem-Site";
3324
+ var MAPS_MAX_IMAGE_EDGE = 640;
3325
+ var TRAVEL_MODES = /* @__PURE__ */ new Set([
3326
+ "driving",
3327
+ "walking",
3328
+ "bicycling",
3329
+ "transit"
3330
+ ]);
3331
+ function finite(value) {
3332
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
3333
+ }
3334
+ function listingCoordinates(listing) {
3335
+ const raw = listing?.location?.coordinates;
3336
+ const lat = finite(raw?.lat);
3337
+ const lng = finite(raw?.lng);
3338
+ if (lat == null || lng == null) return null;
3339
+ if (lat === 0 && lng === 0) return null;
3340
+ if (Math.abs(lat) > 90 || Math.abs(lng) > 180) return null;
3341
+ return { lat, lng };
3342
+ }
3343
+ function coordinateDecimals(value) {
3344
+ if (!Number.isFinite(value)) return 0;
3345
+ const text = Math.abs(value).toString();
3346
+ if (text.includes("e")) {
3347
+ const fixed = Math.abs(value).toFixed(12).replace(/0+$/, "");
3348
+ const dot2 = fixed.indexOf(".");
3349
+ return dot2 === -1 ? 0 : fixed.length - dot2 - 1;
3350
+ }
3351
+ const dot = text.indexOf(".");
3352
+ return dot === -1 ? 0 : text.length - dot - 1;
3353
+ }
3354
+ function roundTo(value, decimals) {
3355
+ const factor = 10 ** decimals;
3356
+ return Math.round(value * factor) / factor;
3357
+ }
3358
+ function coarsenCoordinates(coordinates, maxDecimals) {
3359
+ if (maxDecimals == null || !Number.isFinite(maxDecimals)) return coordinates;
3360
+ const limit = Math.max(0, Math.floor(maxDecimals));
3361
+ return {
3362
+ lat: coordinateDecimals(coordinates.lat) > limit ? roundTo(coordinates.lat, limit) : coordinates.lat,
3363
+ lng: coordinateDecimals(coordinates.lng) > limit ? roundTo(coordinates.lng, limit) : coordinates.lng
3364
+ };
3365
+ }
3366
+ function maxZoomForCoordinates(coordinates) {
3367
+ const decimals = Math.min(
3368
+ coordinateDecimals(coordinates.lat),
3369
+ coordinateDecimals(coordinates.lng)
3370
+ );
3371
+ if (decimals >= 4) return 21;
3372
+ if (decimals === 3) return 16;
3373
+ if (decimals === 2) return 13;
3374
+ return 11;
3375
+ }
3376
+ function clampInt(value, fallback, min, max) {
3377
+ if (value == null || !Number.isFinite(value)) return fallback;
3378
+ return Math.min(max, Math.max(min, Math.round(value)));
3379
+ }
3380
+ function normalizeMapsBaseUrl(baseUrl) {
3381
+ const raw = (baseUrl ?? "").trim();
3382
+ if (!raw) return DEFAULT_MAPS_BASE_URL;
3383
+ return raw.replace(/\/+$/, "") || DEFAULT_MAPS_BASE_URL;
3384
+ }
3385
+ function siteTag(options) {
3386
+ const value = options?.siteId?.trim();
3387
+ return value ? value : null;
3388
+ }
3389
+ function mapsUrl(path, params, options) {
3390
+ const url = new URL(path, `${normalizeMapsBaseUrl(options?.mapsBaseUrl)}/`);
3391
+ for (const [key, value] of Object.entries(params)) {
3392
+ if (value === void 0 || value === "") continue;
3393
+ url.searchParams.set(key, String(value));
3394
+ }
3395
+ const site = siteTag(options);
3396
+ if (site) url.searchParams.set("site", site);
3397
+ return url.toString();
3398
+ }
3399
+ function resolveFetch(options) {
3400
+ const custom = options?.fetch;
3401
+ if (custom) return custom;
3402
+ const global = globalThis.fetch;
3403
+ if (!global) {
3404
+ throw new TypeError(
3405
+ "Garagem SDK: no fetch available. Pass `fetch` in the options."
3406
+ );
3407
+ }
3408
+ return global;
3409
+ }
3410
+ async function mapsFetchJson(url, options, init) {
3411
+ const headers = new Headers(init?.headers);
3412
+ headers.set("accept", "application/json");
3413
+ const site = siteTag(options);
3414
+ if (site) headers.set(MAPS_SITE_HEADER, site);
3415
+ try {
3416
+ const response = await resolveFetch(options)(url, { ...init, headers });
3417
+ if (!response.ok) return null;
3418
+ return await response.json();
3419
+ } catch {
3420
+ return null;
3421
+ }
3422
+ }
3423
+ function listingStaticMapUrl(listing, options = {}) {
3424
+ const raw = listingCoordinates(listing);
3425
+ if (!raw) return null;
3426
+ const coordinates = coarsenCoordinates(raw, options.maxDecimals);
3427
+ const zoomCeiling = maxZoomForCoordinates(coordinates);
3428
+ const zoom = Math.min(zoomCeiling, clampInt(options.zoom, 15, 1, 21));
3429
+ const markerColor = options.markerColor ?? "red";
3430
+ return mapsUrl(
3431
+ "/v1/static-map",
3432
+ {
3433
+ lat: coordinates.lat,
3434
+ lng: coordinates.lng,
3435
+ zoom,
3436
+ width: clampInt(options.width, 600, 1, MAPS_MAX_IMAGE_EDGE),
3437
+ height: clampInt(options.height, 300, 1, MAPS_MAX_IMAGE_EDGE),
3438
+ scale: options.scale === 1 ? 1 : 2,
3439
+ maptype: options.style,
3440
+ markerColor: markerColor !== "red" ? markerColor : void 0,
3441
+ hidePoi: options.hidePoi ? "1" : void 0
3442
+ },
3443
+ options
3444
+ );
3445
+ }
3446
+ function listingStreetViewUrl(listing, options = {}) {
3447
+ const raw = listingCoordinates(listing);
3448
+ if (!raw) return null;
3449
+ const coordinates = coarsenCoordinates(raw, options.maxDecimals);
3450
+ const width = clampInt(options.width, 640, 1, MAPS_MAX_IMAGE_EDGE);
3451
+ const height = clampInt(options.height, 640, 1, MAPS_MAX_IMAGE_EDGE);
3452
+ return mapsUrl(
3453
+ "/v1/street-view",
3454
+ {
3455
+ lat: coordinates.lat,
3456
+ lng: coordinates.lng,
3457
+ size: `${width}x${height}`,
3458
+ fov: clampInt(options.fov, 90, 10, 120),
3459
+ heading: clampInt(options.heading, 0, 0, 360),
3460
+ pitch: clampInt(options.pitch, 10, -90, 90)
3461
+ },
3462
+ options
3463
+ );
3464
+ }
3465
+ function listingStreetViewMetadataUrl(listing, options = {}) {
3466
+ const raw = listingCoordinates(listing);
3467
+ if (!raw) return null;
3468
+ const coordinates = coarsenCoordinates(raw, options.maxDecimals);
3469
+ return mapsUrl(
3470
+ "/v1/street-view/metadata",
3471
+ { lat: coordinates.lat, lng: coordinates.lng },
3472
+ options
3473
+ );
3474
+ }
3475
+ async function listingStreetViewAvailable(listing, options = {}) {
3476
+ const url = listingStreetViewMetadataUrl(listing, options);
3477
+ if (!url) {
3478
+ return { available: false, status: "NO_COORDINATES", url: "" };
3479
+ }
3480
+ const data = await mapsFetchJson(url, options);
3481
+ const status = typeof data?.status === "string" ? data.status : "ERROR";
3482
+ const result = {
3483
+ available: status === "OK",
3484
+ status,
3485
+ url
3486
+ };
3487
+ if (typeof data?.pano_id === "string") result.panoId = data.pano_id;
3488
+ if (typeof data?.date === "string") result.date = data.date;
3489
+ return result;
3490
+ }
3491
+ function boundaryCitySlug(city) {
3492
+ return city.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
3493
+ }
3494
+ function boundaryLayerId(city) {
3495
+ const slug = boundaryCitySlug(city);
3496
+ return slug.endsWith("_boundaries") ? slug : `${slug}_boundaries`;
3497
+ }
3498
+ function boundaryLayerUrl(city, options = {}) {
3499
+ const base = normalizeMapsBaseUrl(options.mapsBaseUrl);
3500
+ const id = boundaryLayerId(city);
3501
+ const slug = id.replace(/_boundaries$/, "");
3502
+ switch (options.kind ?? "tilejson") {
3503
+ case "layer":
3504
+ return `${base}/v1/layers/${id}`;
3505
+ case "tiles":
3506
+ return `${base}/martin/${id}/{z}/{x}/{y}`;
3507
+ case "geojson":
3508
+ return `${base}/api/boundaries/${slug}`;
3509
+ default:
3510
+ return `${base}/martin/${id}`;
3511
+ }
3512
+ }
3513
+ function neighborhoodBoundaryUrl(city, neighborhood, options = {}) {
3514
+ const base = normalizeMapsBaseUrl(options.mapsBaseUrl);
3515
+ const slug = boundaryLayerId(city).replace(/_boundaries$/, "");
3516
+ const url = new URL(
3517
+ `${base}/api/boundaries/${slug}/${encodeURIComponent(neighborhood.trim())}`
3518
+ );
3519
+ if (options.source && options.source !== "listaaberta") {
3520
+ url.searchParams.set("source", options.source);
3521
+ }
3522
+ return url.toString();
3523
+ }
3524
+ function asNumber(value, fallback) {
3525
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
3526
+ }
3527
+ async function getBoundaryLayer(city, options = {}) {
3528
+ const data = await mapsFetchJson(
3529
+ boundaryLayerUrl(city, { ...options, kind: "layer" }),
3530
+ options
3531
+ );
3532
+ const layer = data?.layer;
3533
+ if (!data?.ok || !layer || typeof layer.id !== "string") return null;
3534
+ const rawSourceLayers = Array.isArray(layer.source_layers) ? layer.source_layers : [];
3535
+ return {
3536
+ id: layer.id,
3537
+ name: typeof layer.name === "string" ? layer.name : layer.id,
3538
+ description: typeof layer.description === "string" ? layer.description : "",
3539
+ city: typeof layer.city === "string" ? layer.city : void 0,
3540
+ tiles: typeof layer.tiles === "string" ? layer.tiles : "",
3541
+ tilejson: typeof layer.tilejson === "string" ? layer.tilejson : "",
3542
+ geojson: typeof layer.geojson === "string" ? layer.geojson : void 0,
3543
+ sourceLayers: rawSourceLayers.filter(
3544
+ (entry) => !!entry && typeof entry === "object"
3545
+ ).map((entry) => ({
3546
+ id: String(entry.id ?? ""),
3547
+ label: String(entry.label ?? entry.id ?? ""),
3548
+ minzoom: typeof entry.minzoom === "number" ? entry.minzoom : void 0,
3549
+ maxzoom: typeof entry.maxzoom === "number" ? entry.maxzoom : void 0
3550
+ })),
3551
+ minzoom: asNumber(layer.minzoom, 0),
3552
+ maxzoom: asNumber(layer.maxzoom, 14),
3553
+ attribution: typeof layer.attribution === "string" ? layer.attribution : void 0,
3554
+ available: layer.available !== false
3555
+ };
3556
+ }
3557
+ function isFeature(value) {
3558
+ return !!value && typeof value === "object" && value.type === "Feature";
3559
+ }
3560
+ async function neighborhoodBoundaryLayer(city, neighborhood, options = {}) {
3561
+ const url = neighborhoodBoundaryUrl(city, neighborhood, options);
3562
+ const slug = boundaryLayerId(city).replace(/_boundaries$/, "");
3563
+ const result = {
3564
+ city: slug,
3565
+ neighborhood: neighborhood.trim(),
3566
+ feature: null,
3567
+ candidates: [],
3568
+ url,
3569
+ tiles: boundaryLayerUrl(city, { ...options, kind: "tiles" })
3570
+ };
3571
+ if (!result.neighborhood) return result;
3572
+ const data = await mapsFetchJson(
3573
+ url,
3574
+ options
3575
+ );
3576
+ if (!data) return result;
3577
+ if (isFeature(data)) {
3578
+ result.feature = data;
3579
+ result.candidates = [data];
3580
+ return result;
3581
+ }
3582
+ const features = Array.isArray(data.features) ? data.features.filter(isFeature) : [];
3583
+ result.candidates = features;
3584
+ const wanted = result.neighborhood.toLocaleLowerCase("pt-BR");
3585
+ result.feature = features.find(
3586
+ (feature) => typeof feature.properties?.name === "string" && feature.properties.name.toLocaleLowerCase("pt-BR") === wanted
3587
+ ) ?? (features.length === 1 ? features[0] : null);
3588
+ return result;
3589
+ }
3590
+ function createTravelTimeCache(options = {}) {
3591
+ const maxEntries = Math.max(1, Math.floor(options.maxEntries ?? 200));
3592
+ const ttlMs = Math.max(0, options.ttlMs ?? 15 * 60 * 1e3);
3593
+ const entries = /* @__PURE__ */ new Map();
3594
+ return {
3595
+ get(key) {
3596
+ const hit = entries.get(key);
3597
+ if (!hit) return void 0;
3598
+ if (hit.expiresAt <= Date.now()) {
3599
+ entries.delete(key);
3600
+ return void 0;
3601
+ }
3602
+ entries.delete(key);
3603
+ entries.set(key, hit);
3604
+ return hit.value;
3605
+ },
3606
+ set(key, value) {
3607
+ entries.delete(key);
3608
+ entries.set(key, { value, expiresAt: Date.now() + ttlMs });
3609
+ while (entries.size > maxEntries) {
3610
+ const oldest = entries.keys().next().value;
3611
+ if (oldest === void 0) break;
3612
+ entries.delete(oldest);
3613
+ }
3614
+ },
3615
+ clear() {
3616
+ entries.clear();
3617
+ },
3618
+ get size() {
3619
+ return entries.size;
3620
+ }
3621
+ };
3622
+ }
3623
+ var defaultTravelTimeCache = createTravelTimeCache();
3624
+ function clearTravelTimeCache() {
3625
+ defaultTravelTimeCache.clear();
3626
+ }
3627
+ function travelTimeCacheKey(origin, destination, mode) {
3628
+ return `${origin.lat},${origin.lng}|${destination.lat},${destination.lng}|${mode}`;
3629
+ }
3630
+ function travelTimeQueryCacheKey(origin, query, mode) {
3631
+ return `${origin.lat},${origin.lng}|q:${query}|${mode}`;
3632
+ }
3633
+ function trimmedDestinationQuery(destination) {
3634
+ if (typeof destination !== "string") return null;
3635
+ const query = destination.trim();
3636
+ return query ? query : null;
3637
+ }
3638
+ function recallTravelTime(cache, key) {
3639
+ if (!cache) return null;
3640
+ const hit = cache.get(key);
3641
+ return hit ? { ...hit, cached: true } : null;
3642
+ }
3643
+ function rememberTravelTime(cache, keys, value) {
3644
+ if (!cache) return;
3645
+ for (const key of keys) cache.set(key, value);
3646
+ }
3647
+ function normalizeMode(mode) {
3648
+ return mode && TRAVEL_MODES.has(mode) ? mode : "driving";
3649
+ }
3650
+ async function resolveTravelDestination(destination, options = {}) {
3651
+ if (typeof destination !== "string") {
3652
+ const lat2 = finite(destination?.lat);
3653
+ const lng2 = finite(destination?.lng);
3654
+ return lat2 == null || lng2 == null ? null : { lat: lat2, lng: lng2 };
3655
+ }
3656
+ const query = destination.trim();
3657
+ if (!query) return null;
3658
+ const data = await mapsFetchJson(
3659
+ mapsUrl("/v1/geocode", { q: query }, options),
3660
+ options
3661
+ );
3662
+ const lat = finite(data?.latitude);
3663
+ const lng = finite(data?.longitude);
3664
+ if (!data?.ok || lat == null || lng == null) return null;
3665
+ return { lat, lng };
3666
+ }
3667
+ function minutesFromSeconds(seconds) {
3668
+ return Math.max(1, Math.round(seconds / 60));
3669
+ }
3670
+ async function travelTimeFromListing(listing, destination, options = {}) {
3671
+ const raw = listingCoordinates(listing);
3672
+ if (!raw) return null;
3673
+ const origin = coarsenCoordinates(raw, options.maxDecimals);
3674
+ const mode = normalizeMode(options.mode);
3675
+ const cache = options.cache === void 0 ? defaultTravelTimeCache : options.cache;
3676
+ const query = trimmedDestinationQuery(destination);
3677
+ if (typeof destination === "string" && !query) return null;
3678
+ if (query) {
3679
+ const queryHit = recallTravelTime(
3680
+ cache,
3681
+ travelTimeQueryCacheKey(origin, query, mode)
3682
+ );
3683
+ if (queryHit) return queryHit;
3684
+ }
3685
+ const target = await resolveTravelDestination(query ?? destination, options);
3686
+ if (!target) return null;
3687
+ const coordKey = travelTimeCacheKey(origin, target, mode);
3688
+ const stored = cache?.get(coordKey);
3689
+ if (stored) {
3690
+ if (query) {
3691
+ rememberTravelTime(
3692
+ cache,
3693
+ [travelTimeQueryCacheKey(origin, query, mode)],
3694
+ stored
3695
+ );
3696
+ }
3697
+ return { ...stored, cached: true };
3698
+ }
3699
+ const data = await mapsFetchJson(
3700
+ mapsUrl(
3701
+ "/v1/directions",
3702
+ {
3703
+ origin: `${origin.lat},${origin.lng}`,
3704
+ destination: `${target.lat},${target.lng}`,
3705
+ mode
3706
+ },
3707
+ options
3708
+ ),
3709
+ options
3710
+ );
3711
+ const seconds = finite(data?.route?.totalTravelTime);
3712
+ const meters = finite(data?.route?.totalDistance);
3713
+ if (!data?.ok || seconds == null || meters == null) return null;
3714
+ const result = {
3715
+ minutes: minutesFromSeconds(seconds),
3716
+ seconds,
3717
+ distanceMeters: meters,
3718
+ distanceKm: Math.round(meters / 100) / 10,
3719
+ mode,
3720
+ origin,
3721
+ destination: target,
3722
+ cached: false
3723
+ };
3724
+ const keys = query ? [coordKey, travelTimeQueryCacheKey(origin, query, mode)] : [coordKey];
3725
+ rememberTravelTime(cache, keys, result);
3726
+ return result;
3727
+ }
3728
+ async function travelTimesFromListing(listing, destinations, options = {}) {
3729
+ const raw = listingCoordinates(listing);
3730
+ if (!raw) return null;
3731
+ const origin = coarsenCoordinates(raw, options.maxDecimals);
3732
+ const targets = destinations.map((destination) => {
3733
+ const lat = finite(destination?.lat);
3734
+ const lng = finite(destination?.lng);
3735
+ return lat == null || lng == null ? null : { lat, lng };
3736
+ }).filter((item) => item !== null);
3737
+ if (targets.length === 0) return [];
3738
+ const data = await mapsFetchJson(
3739
+ mapsUrl("/v1/route-matrix", {}, options),
3740
+ options,
3741
+ {
3742
+ method: "POST",
3743
+ headers: { "content-type": "application/json" },
3744
+ body: JSON.stringify({ origin, destinations: targets })
3745
+ }
3746
+ );
3747
+ if (!data?.ok || !Array.isArray(data.durations)) return null;
3748
+ return targets.map((destination, index) => {
3749
+ const seconds = finite(
3750
+ data.durations && data.durations[index]
3751
+ );
3752
+ if (seconds == null) return null;
3753
+ return { minutes: minutesFromSeconds(seconds), seconds, destination };
3754
+ });
3755
+ }
3756
+
3757
+ // src/map-search.ts
3758
+ var MAP_SEARCH_MAX_PAGE_SIZE = 100;
3759
+ var MAP_SEARCH_DEFAULT_PAGE_SIZE = 100;
3760
+ var MAP_SEARCH_MAX_PAGE = 1e4;
3761
+ var MAP_VIEWPORT_DEBOUNCE_MS = 400;
3762
+ var MAP_POLYGON_MAX_VERTICES = 64;
3763
+ function capMapPageSize(value) {
3764
+ if (value == null || !Number.isFinite(value) || value <= 0) {
3765
+ return MAP_SEARCH_DEFAULT_PAGE_SIZE;
3766
+ }
3767
+ return Math.min(MAP_SEARCH_MAX_PAGE_SIZE, Math.floor(value));
3768
+ }
3769
+ function capMapPage(value) {
3770
+ if (value == null || !Number.isFinite(value) || value <= 1) return 1;
3771
+ return Math.min(MAP_SEARCH_MAX_PAGE, Math.floor(value));
3772
+ }
3773
+ function finitePair(lat, lng) {
3774
+ if (typeof lat !== "number" || typeof lng !== "number") return null;
3775
+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
3776
+ if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return null;
3777
+ return [lat, lng];
3778
+ }
3779
+ function isMapBounds(bounds) {
3780
+ if (!bounds) return false;
3781
+ const north = finitePair(bounds.north, bounds.east);
3782
+ const south = finitePair(bounds.south, bounds.west);
3783
+ if (!north || !south) return false;
3784
+ return bounds.north > bounds.south && bounds.east > bounds.west;
3785
+ }
3786
+ function isMapPolygon(polygon) {
3787
+ if (!Array.isArray(polygon)) return false;
3788
+ if (polygon.length < 3 || polygon.length > MAP_POLYGON_MAX_VERTICES + 1) {
3789
+ return false;
3790
+ }
3791
+ let unique = 0;
3792
+ let prev = null;
3793
+ for (const point of polygon) {
3794
+ if (!Array.isArray(point)) return false;
3795
+ const pair = finitePair(point[0], point[1]);
3796
+ if (!pair) return false;
3797
+ if (prev && prev[0] === pair[0] && prev[1] === pair[1]) continue;
3798
+ prev = pair;
3799
+ unique += 1;
3800
+ }
3801
+ if (unique >= 2 && polygon.length >= 2) {
3802
+ const first = finitePair(polygon[0]?.[0], polygon[0]?.[1]);
3803
+ const last = finitePair(
3804
+ polygon[polygon.length - 1]?.[0],
3805
+ polygon[polygon.length - 1]?.[1]
3806
+ );
3807
+ if (first && last && first[0] === last[0] && first[1] === last[1] && unique > 1) {
3808
+ unique -= 1;
3809
+ }
3810
+ }
3811
+ return unique >= 3 && unique <= MAP_POLYGON_MAX_VERTICES;
3812
+ }
3813
+ function mapSearchPins(listings) {
3814
+ const pins = [];
3815
+ for (const listing of listings) {
3816
+ const coords = listingCoordinates(listing);
3817
+ if (!coords || !listing.id) continue;
3818
+ const src = listing.coverImage?.src;
3819
+ pins.push({
3820
+ id: listing.id,
3821
+ lat: coords.lat,
3822
+ lng: coords.lng,
3823
+ price: listing.price ?? null,
3824
+ coverImage: src ? src : null
3825
+ });
3826
+ }
3827
+ return pins;
3828
+ }
3829
+ function listingsResult(listings, meta, requestedPageSize) {
3830
+ return {
3831
+ pins: mapSearchPins(listings),
3832
+ cards: listings.map((listing) => toListingCardModel(listing)),
3833
+ listings,
3834
+ page: meta.page ?? 1,
3835
+ pageSize: meta.limit ?? requestedPageSize,
3836
+ total: meta.total ?? listings.length,
3837
+ totalPages: meta.totalPages ?? 0
3838
+ };
3839
+ }
3840
+ function searchParams(area, options) {
3841
+ const params = {
3842
+ page: capMapPage(options.page),
3843
+ limit: capMapPageSize(options.pageSize)
3844
+ };
3845
+ if (options.q !== void 0) params.q = options.q;
3846
+ if (options.sort !== void 0) params.sort = options.sort;
3847
+ if (options.location !== void 0) params.location = options.location;
3848
+ if (options.filters) params.filters = options.filters;
3849
+ if (area.polygon) params.polygon = area.polygon;
3850
+ else if (area.bounds) params.bounds = area.bounds;
3851
+ return params;
3852
+ }
3853
+ async function runMapSearch(siteId, area, options) {
3854
+ const pageSize = capMapPageSize(options.pageSize);
3855
+ const result = await queryListings({
3856
+ siteId,
3857
+ params: searchParams(area, options),
3858
+ baseUrl: options.baseUrl,
3859
+ fetch: options.fetch,
3860
+ signal: options.signal,
3861
+ publishableKey: options.publishableKey,
3862
+ next: options.next
3863
+ });
3864
+ return listingsResult(result.listings ?? [], result, pageSize);
3865
+ }
3866
+ async function searchListingsInBounds(siteId, options) {
3867
+ if (!isMapBounds(options.bounds)) {
3868
+ throw new TypeError(
3869
+ "searchListingsInBounds: bounds must be a finite rectangle with north > south and east > west (no antimeridian)."
3870
+ );
3871
+ }
3872
+ return runMapSearch(siteId, { bounds: options.bounds }, options);
3873
+ }
3874
+ async function searchListingsInPolygon(siteId, options) {
3875
+ if (!isMapPolygon(options.polygon)) {
3876
+ throw new TypeError(
3877
+ `searchListingsInPolygon: polygon must be 3\u2013${MAP_POLYGON_MAX_VERTICES} finite [lat, lng] points.`
3878
+ );
3879
+ }
3880
+ return runMapSearch(siteId, { polygon: options.polygon }, options);
3881
+ }
3882
+ function clampZoom(zoom) {
3883
+ if (!Number.isFinite(zoom)) return 0;
3884
+ return Math.min(22, Math.max(0, zoom));
3885
+ }
3886
+ function mapClusterCellDegrees(zoom) {
3887
+ return 360 / 2 ** clampZoom(zoom) / 4;
3888
+ }
3889
+ function usablePin(pin) {
3890
+ return finitePair(pin.lat, pin.lng) !== null && !(pin.lat === 0 && pin.lng === 0);
3891
+ }
3892
+ function groupPrecision(group) {
3893
+ let min = 12;
3894
+ for (const pin of group) {
3895
+ min = Math.min(
3896
+ min,
3897
+ coordinateDecimals(pin.lat),
3898
+ coordinateDecimals(pin.lng)
3899
+ );
3900
+ }
3901
+ return min;
3902
+ }
3903
+ function multiCluster(key, group) {
3904
+ const lat = group.reduce((sum, pin) => sum + pin.lat, 0) / group.length;
3905
+ const lng = group.reduce((sum, pin) => sum + pin.lng, 0) / group.length;
3906
+ const center = coarsenCoordinates({ lat, lng }, groupPrecision(group));
3907
+ return {
3908
+ id: key,
3909
+ lat: center.lat,
3910
+ lng: center.lng,
3911
+ count: group.length,
3912
+ pinIds: group.map((pin) => pin.id),
3913
+ pin: null
3914
+ };
3915
+ }
3916
+ function singleCluster(pin) {
3917
+ return {
3918
+ id: pin.id,
3919
+ lat: pin.lat,
3920
+ lng: pin.lng,
3921
+ count: 1,
3922
+ pinIds: [pin.id],
3923
+ pin
3924
+ };
3925
+ }
3926
+ function clusterPins(pins, zoom) {
3927
+ if (pins.length === 0) return [];
3928
+ const cell = mapClusterCellDegrees(zoom);
3929
+ const groups = /* @__PURE__ */ new Map();
3930
+ for (const pin of pins) {
3931
+ if (!usablePin(pin)) continue;
3932
+ const key = `${Math.floor(pin.lat / cell)}:${Math.floor(pin.lng / cell)}`;
3933
+ const list = groups.get(key);
3934
+ if (list) list.push(pin);
3935
+ else groups.set(key, [pin]);
3936
+ }
3937
+ const clusters = [];
3938
+ for (const [key, group] of groups) {
3939
+ const only = group[0];
3940
+ clusters.push(
3941
+ group.length === 1 && only ? singleCluster(only) : multiCluster(key, group)
3942
+ );
3943
+ }
3944
+ clusters.sort((a, b) => a.id.localeCompare(b.id));
3945
+ return clusters;
3946
+ }
3947
+
3284
3948
  // src/fetchers-photos.ts
3285
3949
  var MEDIA_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3286
3950
  var HIDDEN_SIMILAR_PHOTOS = {
@@ -3800,12 +4464,19 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
3800
4464
  }
3801
4465
  export {
3802
4466
  AMENITY_FALLBACK_LABELS,
4467
+ DEFAULT_MAPS_BASE_URL,
3803
4468
  DEFAULT_PHONE_COUNTRY_CODE,
3804
4469
  FORBIDDEN_SEARCH_QUERY_KEYS,
3805
4470
  GaragemSdkError,
3806
4471
  LISTING_AMENITY_TITLES,
3807
4472
  LISTING_DESCRIPTION_CLAMP,
3808
4473
  LeadSubmitError,
4474
+ MAPS_MAX_IMAGE_EDGE,
4475
+ MAPS_SITE_HEADER,
4476
+ MAP_POLYGON_MAX_VERTICES,
4477
+ MAP_SEARCH_DEFAULT_PAGE_SIZE,
4478
+ MAP_SEARCH_MAX_PAGE_SIZE,
4479
+ MAP_VIEWPORT_DEBOUNCE_MS,
3809
4480
  MATCHED_PHOTO_COVER_MAX_DISTANCE,
3810
4481
  MAX_NATIONAL_PHONE_DIGITS,
3811
4482
  PHONE_COUNTRIES,
@@ -3822,18 +4493,28 @@ export {
3822
4493
  VISIT_TIME_ZONE,
3823
4494
  applyMatchedPhotoCover,
3824
4495
  applyPathFilter,
4496
+ boundaryCitySlug,
4497
+ boundaryLayerId,
4498
+ boundaryLayerUrl,
3825
4499
  buildQueryListingsParams,
3826
4500
  canonicalizeSearchHref,
4501
+ capMapPage,
4502
+ capMapPageSize,
3827
4503
  clearStagedPathFilters,
4504
+ clearTravelTimeCache,
4505
+ clusterPins,
4506
+ coarsenCoordinates,
3828
4507
  coerceNpmVersion,
3829
4508
  collapseDuplicatedBrazilianMobileNine,
3830
4509
  compareSemver,
3831
4510
  composeSearchPublicHref2 as composeSearchPublicHref,
3832
4511
  composeSearchPublicPath2 as composeSearchPublicPath,
4512
+ coordinateDecimals,
3833
4513
  countFacetChoices,
3834
4514
  countOptionLabel,
3835
4515
  createClient,
3836
4516
  createGaragemClient,
4517
+ createTravelTimeCache,
3837
4518
  defaultPhoneCountry,
3838
4519
  displayPathLocation,
3839
4520
  expandVisitSchedule,
@@ -3843,6 +4524,7 @@ export {
3843
4524
  formatGroupedInteger,
3844
4525
  formatListingPrice,
3845
4526
  formatPhoneNational,
4527
+ getBoundaryLayer,
3846
4528
  getCmsCollection,
3847
4529
  getCmsCollections,
3848
4530
  getCmsEntries,
@@ -3861,6 +4543,8 @@ export {
3861
4543
  hrefForPathFilters,
3862
4544
  hrefWithExplicitPage,
3863
4545
  isListingDetailPath,
4546
+ isMapBounds,
4547
+ isMapPolygon,
3864
4548
  isPhotoSearchOnPin,
3865
4549
  isStudioPreviewHost,
3866
4550
  isValidPhone,
@@ -3869,6 +4553,7 @@ export {
3869
4553
  listingAmenityGroups,
3870
4554
  listingBreadcrumb,
3871
4555
  listingBusinessLabel,
4556
+ listingCoordinates,
3872
4557
  listingDescriptionPreview,
3873
4558
  listingDetailFieldsModel,
3874
4559
  listingDetailModel,
@@ -3880,12 +4565,23 @@ export {
3880
4565
  listingMediaOverlays,
3881
4566
  listingPhotoGroups,
3882
4567
  listingPublicPath,
4568
+ listingStaticMapUrl,
4569
+ listingStreetViewAvailable,
4570
+ listingStreetViewMetadataUrl,
4571
+ listingStreetViewUrl,
3883
4572
  listingValues,
3884
4573
  listingVisualHighlights,
4574
+ mapClusterCellDegrees,
4575
+ mapSearchPins,
4576
+ mapsExportsPublished,
3885
4577
  marketExportsAvailableAt,
3886
4578
  marketPositionLabel,
4579
+ maxZoomForCoordinates,
3887
4580
  mergeAppliedSearchQueryIntoSearch2 as mergeAppliedSearchQueryIntoSearch,
3888
4581
  nationalPhoneDigits,
4582
+ neighborhoodBoundaryLayer,
4583
+ neighborhoodBoundaryUrl,
4584
+ normalizeMapsBaseUrl,
3889
4585
  normalizeVisitDate,
3890
4586
  normalizeVisitTime,
3891
4587
  paginationPages,
@@ -3911,10 +4607,13 @@ export {
3911
4607
  requestPriceEstimate,
3912
4608
  resolveMatchedCoverPhoto,
3913
4609
  resolvePublicSiteId,
4610
+ resolveTravelDestination,
3914
4611
  searchChromeModel,
3915
4612
  searchHrefUsesLegacyFilterQuery,
3916
4613
  searchListingPhotos,
3917
4614
  searchListings,
4615
+ searchListingsInBounds,
4616
+ searchListingsInPolygon,
3918
4617
  searchResultsHeading,
3919
4618
  searchSortOptions,
3920
4619
  serializeAppliedSearchQuery2 as serializeAppliedSearchQuery,
@@ -3927,6 +4626,7 @@ export {
3927
4626
  studioLeadInstruction,
3928
4627
  studioListingCardInstruction,
3929
4628
  studioListingDetailInstruction,
4629
+ studioMapsInstruction,
3930
4630
  studioMarketInstruction,
3931
4631
  studioPhotoInstruction,
3932
4632
  studioPhotoInstructionFor,
@@ -3941,6 +4641,9 @@ export {
3941
4641
  toE164,
3942
4642
  toListingCardModel,
3943
4643
  toolbarFilterIds,
4644
+ travelTimeCacheKey,
4645
+ travelTimeFromListing,
4646
+ travelTimesFromListing,
3944
4647
  truncateNationalPhoneDigits,
3945
4648
  unavailableReactImports,
3946
4649
  visibleSearchFilters