@garagem-ai/site-sdk 0.8.0 → 0.9.1
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 +162 -5
- package/dist/index.d.mts +142 -45
- package/dist/index.d.ts +142 -45
- package/dist/index.js +758 -6
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +718 -6
- package/dist/index.mjs.map +1 -1
- package/dist/react.d.mts +24 -2
- package/dist/react.d.ts +24 -2
- package/dist/react.js +499 -12
- package/dist/react.js.map +1 -1
- package/dist/react.mjs +498 -12
- package/dist/react.mjs.map +1 -1
- package/dist/{types-photo-search-CmGRj6my.d.mts → types-photo-search-DIoV75SN.d.mts} +375 -1
- package/dist/{types-photo-search-CmGRj6my.d.ts → types-photo-search-DIoV75SN.d.ts} +375 -1
- package/package.json +2 -2
- package/src/fetchers.ts +4 -1
- package/src/index.ts +90 -0
- package/src/map-search.ts +491 -0
- package/src/maps.ts +743 -0
- package/src/react/index.ts +2 -0
- package/src/react/use-map-search.ts +101 -0
- package/src/studio-contract.ts +67 -3
- package/src/types-maps.ts +275 -0
- package/src/types.ts +12 -0
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
|
|
@@ -2734,11 +2735,13 @@ var STUDIO_SDK_CONTRACT = {
|
|
|
2734
2735
|
* this and move that release's names from `optionalReactExports` /
|
|
2735
2736
|
* `unpublishedSearchExports` / `unpublishedPhoneExports` into the
|
|
2736
2737
|
* prompt-safe lists. Do not bump here until that tarball is on npm.
|
|
2737
|
-
* Phone mask helpers shipped in 0.6.0.
|
|
2738
|
+
* Phone mask helpers shipped in 0.6.0. Map search
|
|
2739
|
+
* (`useMapSearch`, `searchListingsInBounds`) shipped in 0.9.0 — 0.7.0
|
|
2740
|
+
* does not export them. Search filter helpers
|
|
2738
2741
|
* (`visibleSearchFilters` / `toolbarFilterIds`) shipped in 0.4.12 and
|
|
2739
2742
|
* remain on this pin.
|
|
2740
2743
|
*/
|
|
2741
|
-
minNpmVersion: "0.
|
|
2744
|
+
minNpmVersion: "0.9.0",
|
|
2742
2745
|
/** Historical: older tarballs inject card CSS when those components mount. */
|
|
2743
2746
|
selfInjectSince: "0.4.2",
|
|
2744
2747
|
chromeStrategy: "app-owned",
|
|
@@ -2751,7 +2754,8 @@ var STUDIO_SDK_CONTRACT = {
|
|
|
2751
2754
|
* throws FatalRendererError.
|
|
2752
2755
|
*/
|
|
2753
2756
|
optionalReactExports: {
|
|
2754
|
-
usePublicPhotoSearch: "0.7.0"
|
|
2757
|
+
usePublicPhotoSearch: "0.7.0",
|
|
2758
|
+
useMapSearch: "0.9.0"
|
|
2755
2759
|
},
|
|
2756
2760
|
/**
|
|
2757
2761
|
* Former `/react` chrome (including card/skeleton inject). Completeness
|
|
@@ -2860,6 +2864,28 @@ var STUDIO_SDK_CONTRACT = {
|
|
|
2860
2864
|
"searchChromeModel",
|
|
2861
2865
|
"rangeDraftFromPath"
|
|
2862
2866
|
],
|
|
2867
|
+
/**
|
|
2868
|
+
* maps.fndn.ai helpers (static map, street view, boundaries, travel
|
|
2869
|
+
* time) plus friendly map search. They ship in npm 0.9.0 (`mapsSince`).
|
|
2870
|
+
* Listing-detail map guidance stays empty: `studioMapsInstruction()`
|
|
2871
|
+
* keeps the listing contract for a later task and Studio does not
|
|
2872
|
+
* inject it. Map search is `studioMapSearchInstruction()`, and only
|
|
2873
|
+
* the site that opted into list-and-map may include that text.
|
|
2874
|
+
* `useMapSearch` is a `/react` hook in `optionalReactExports`; the
|
|
2875
|
+
* pin sentence does not name it.
|
|
2876
|
+
*/
|
|
2877
|
+
mapsSince: "0.9.0",
|
|
2878
|
+
mapsExports: [
|
|
2879
|
+
"listingStaticMapUrl",
|
|
2880
|
+
"listingStreetViewUrl",
|
|
2881
|
+
"listingStreetViewAvailable",
|
|
2882
|
+
"neighborhoodBoundaryLayer",
|
|
2883
|
+
"boundaryLayerUrl",
|
|
2884
|
+
"travelTimeFromListing",
|
|
2885
|
+
"searchListingsInBounds",
|
|
2886
|
+
"searchListingsInPolygon",
|
|
2887
|
+
"clusterPins"
|
|
2888
|
+
],
|
|
2863
2889
|
/**
|
|
2864
2890
|
* Market-data helpers (neighborhood price summary, listing market
|
|
2865
2891
|
* position, visitor price estimate, pt-BR labels). They ship in
|
|
@@ -2984,7 +3010,7 @@ function studioPublishableKeyInstruction() {
|
|
|
2984
3010
|
}
|
|
2985
3011
|
function studioSdkPinInstruction() {
|
|
2986
3012
|
const version = STUDIO_SDK_CONTRACT.minNpmVersion;
|
|
2987
|
-
const names =
|
|
3013
|
+
const names = STUDIO_SDK_CONTRACT.reactExports.join(", ");
|
|
2988
3014
|
return `In \`package.json\` set \`"@garagem-ai/site-sdk": "${version}"\` (exact). Import only these \`${STUDIO_SDK_PACKAGE}/react\` names: ${names}.`;
|
|
2989
3015
|
}
|
|
2990
3016
|
function studioLeadInstruction() {
|
|
@@ -3033,6 +3059,18 @@ function studioSearchInstruction() {
|
|
|
3033
3059
|
const libNames = STUDIO_SDK_CONTRACT.searchExports.join(", ");
|
|
3034
3060
|
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
3061
|
}
|
|
3062
|
+
function mapsExportsPublished(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
|
|
3063
|
+
return compareSemver(pin, STUDIO_SDK_CONTRACT.mapsSince) >= 0;
|
|
3064
|
+
}
|
|
3065
|
+
function studioMapsInstruction(options = {}) {
|
|
3066
|
+
if (!mapsExportsPublished(options.pin)) return "";
|
|
3067
|
+
const names = STUDIO_SDK_CONTRACT.mapsExports.join(", ");
|
|
3068
|
+
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.`;
|
|
3069
|
+
}
|
|
3070
|
+
function studioMapSearchInstruction(options = {}) {
|
|
3071
|
+
if (!mapsExportsPublished(options.pin)) return "";
|
|
3072
|
+
return `Map search on \`/imoveis\` (list and map of the same query). The list stays: keep \`usePublicSearch\` for the list, including its sort and pagination. The visitor switches on the same page. \`?modo=mapa\` is the map \u2014 read it on first paint. The list is the URL without \`modo\`; do not write \`modo=lista\` or \`modo=grade\`. Choosing the map sets \`modo=mapa\` and drops \`page\`. Choosing the list removes \`modo\`. On the map, hide sort and pagination. Do not add a map pager. The heading stays. Filters apply to both. Load Maps JS ONLY through \`<script src="https://maps.fndn.ai/sdk.js?callback=initMap" async defer />\` \u2014 never a Google key in the app, never \`NEXT_PUBLIC_GOOGLE_MAPS_API_KEY\`, never \`maps.googleapis.com\`, never \`@vis.gl/react-google-maps\`. From \`${STUDIO_SDK_PACKAGE}/react\` import useMapSearch; it fetches, debounces, and clusters. \`const map = useMapSearch({ siteId, baseUrl: GARAGEM_API_BASE, bounds, zoom, q, sort, location, filters, publishableKey })\` with the same q, sort, location, filters, and publishableKey as the list. Pass the map's current zoom on every zoom change, including after a cluster click. Changing zoom recomputes \`map.clusters\` and does not refetch; a bounds change refetches. Do not send filter_by, vector_query, or nl_query from the browser. Request page 1 and pageSize at most 100. Do not walk totalPages. Pins are the masked coordinates the API returned \u2014 plot them as returned, never geocode the street. Render \`map.clusters\` with \`google.maps.Marker\` (no map id needed), in two styles that never look alike. A cluster (\`count > 1\`) is a filled circle in the brand color with a white border and the white count as its label. A listing (\`count === 1\` with \`cluster.pin\`) is a white rounded-rectangle chip with a brand-color border, labelled with the short price in the brand color ("R$ 850 mil", "R$ 1,2 mi"; "Consulte" when the price is null or 0): \`icon: { path: "M-34,-12 h68 a6,6 0 0 1 6,6 v12 a6,6 0 0 1 -6,6 h-68 a6,6 0 0 1 -6,-6 v-12 a6,6 0 0 1 6,-6 z", fillColor: "#ffffff", fillOpacity: 1, strokeColor: brand, strokeWeight: 1.5, scale: 1, labelOrigin: new google.maps.Point(0, 0) }\`. Never draw a listing as a dot or a circle, and never without its price. Clicking a listing selects it and shows its card. Clicking a cluster opens its members: \`const members = map.pins.filter((pin) => cluster.pinIds.includes(pin.id))\`, then \`fitBounds\` a LatLngBounds of their coordinates with about 64px padding, so the listings land inside the new view and split into chips. Do not step the zoom around \`cluster.lat\`/\`cluster.lng\`: that point is approximate and the area around it can come back empty. When every member has the same coordinates, or the map is already at zoom 18, do not zoom: open a small list of those listings, each with its price and a link. Layout, top to bottom: query, heading, toolbar, then the view. On desktop the toolbar is one row: featured filters on the left, and the list/map toggle immediately beside the sort select on the right. On a narrow screen the filters stay in one horizontal scroll that does not wrap, and the toggle plus the sort sit together on the row below that scroll. On the map the sort is hidden, so the toggle keeps that place beside where the sort was. In map mode the map fills the remaining viewport height, with a minimum of about 240px. Keep the hook's 400ms viewport debounce. A drawn polygon is not required. Do not add a separate /mapa route, a regions page, or a map on the listing page. Do not call Street View or travel time inside the map search.`;
|
|
3073
|
+
}
|
|
3036
3074
|
function marketExportsAvailableAt(pin) {
|
|
3037
3075
|
return compareSemver(pin, STUDIO_SDK_CONTRACT.marketExportsSince) >= 0;
|
|
3038
3076
|
}
|
|
@@ -3083,6 +3121,13 @@ function studioCodegenContractViolations(text) {
|
|
|
3083
3121
|
violations.push(name);
|
|
3084
3122
|
}
|
|
3085
3123
|
}
|
|
3124
|
+
if (!mapsExportsPublished()) {
|
|
3125
|
+
for (const name of STUDIO_SDK_CONTRACT.mapsExports) {
|
|
3126
|
+
if (mentionsExportName(text, name) && !violations.includes(name)) {
|
|
3127
|
+
violations.push(name);
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
}
|
|
3086
3131
|
for (const name of STUDIO_SDK_CONTRACT.unpublishedPhotoExports) {
|
|
3087
3132
|
if (mentionsExportName(text, name) && !violations.includes(name)) {
|
|
3088
3133
|
violations.push(name);
|
|
@@ -3281,6 +3326,633 @@ function createGaragemClient(options = {}) {
|
|
|
3281
3326
|
}
|
|
3282
3327
|
var createClient = createGaragemClient;
|
|
3283
3328
|
|
|
3329
|
+
// src/maps.ts
|
|
3330
|
+
var DEFAULT_MAPS_BASE_URL = "https://maps.fndn.ai";
|
|
3331
|
+
var MAPS_SITE_HEADER = "X-Garagem-Site";
|
|
3332
|
+
var MAPS_MAX_IMAGE_EDGE = 640;
|
|
3333
|
+
var TRAVEL_MODES = /* @__PURE__ */ new Set([
|
|
3334
|
+
"driving",
|
|
3335
|
+
"walking",
|
|
3336
|
+
"bicycling",
|
|
3337
|
+
"transit"
|
|
3338
|
+
]);
|
|
3339
|
+
function finite(value) {
|
|
3340
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
3341
|
+
}
|
|
3342
|
+
function listingCoordinates(listing) {
|
|
3343
|
+
const raw = listing?.location?.coordinates;
|
|
3344
|
+
const lat = finite(raw?.lat);
|
|
3345
|
+
const lng = finite(raw?.lng);
|
|
3346
|
+
if (lat == null || lng == null) return null;
|
|
3347
|
+
if (lat === 0 && lng === 0) return null;
|
|
3348
|
+
if (Math.abs(lat) > 90 || Math.abs(lng) > 180) return null;
|
|
3349
|
+
return { lat, lng };
|
|
3350
|
+
}
|
|
3351
|
+
function coordinateDecimals(value) {
|
|
3352
|
+
if (!Number.isFinite(value)) return 0;
|
|
3353
|
+
const text = Math.abs(value).toString();
|
|
3354
|
+
if (text.includes("e")) {
|
|
3355
|
+
const fixed = Math.abs(value).toFixed(12).replace(/0+$/, "");
|
|
3356
|
+
const dot2 = fixed.indexOf(".");
|
|
3357
|
+
return dot2 === -1 ? 0 : fixed.length - dot2 - 1;
|
|
3358
|
+
}
|
|
3359
|
+
const dot = text.indexOf(".");
|
|
3360
|
+
return dot === -1 ? 0 : text.length - dot - 1;
|
|
3361
|
+
}
|
|
3362
|
+
function roundTo(value, decimals) {
|
|
3363
|
+
const factor = 10 ** decimals;
|
|
3364
|
+
return Math.round(value * factor) / factor;
|
|
3365
|
+
}
|
|
3366
|
+
function coarsenCoordinates(coordinates, maxDecimals) {
|
|
3367
|
+
if (maxDecimals == null || !Number.isFinite(maxDecimals)) return coordinates;
|
|
3368
|
+
const limit = Math.max(0, Math.floor(maxDecimals));
|
|
3369
|
+
return {
|
|
3370
|
+
lat: coordinateDecimals(coordinates.lat) > limit ? roundTo(coordinates.lat, limit) : coordinates.lat,
|
|
3371
|
+
lng: coordinateDecimals(coordinates.lng) > limit ? roundTo(coordinates.lng, limit) : coordinates.lng
|
|
3372
|
+
};
|
|
3373
|
+
}
|
|
3374
|
+
function maxZoomForCoordinates(coordinates) {
|
|
3375
|
+
const decimals = Math.min(
|
|
3376
|
+
coordinateDecimals(coordinates.lat),
|
|
3377
|
+
coordinateDecimals(coordinates.lng)
|
|
3378
|
+
);
|
|
3379
|
+
if (decimals >= 4) return 21;
|
|
3380
|
+
if (decimals === 3) return 16;
|
|
3381
|
+
if (decimals === 2) return 13;
|
|
3382
|
+
return 11;
|
|
3383
|
+
}
|
|
3384
|
+
function clampInt(value, fallback, min, max) {
|
|
3385
|
+
if (value == null || !Number.isFinite(value)) return fallback;
|
|
3386
|
+
return Math.min(max, Math.max(min, Math.round(value)));
|
|
3387
|
+
}
|
|
3388
|
+
function normalizeMapsBaseUrl(baseUrl) {
|
|
3389
|
+
const raw = (baseUrl ?? "").trim();
|
|
3390
|
+
if (!raw) return DEFAULT_MAPS_BASE_URL;
|
|
3391
|
+
return raw.replace(/\/+$/, "") || DEFAULT_MAPS_BASE_URL;
|
|
3392
|
+
}
|
|
3393
|
+
function siteTag(options) {
|
|
3394
|
+
const value = options?.siteId?.trim();
|
|
3395
|
+
return value ? value : null;
|
|
3396
|
+
}
|
|
3397
|
+
function mapsUrl(path, params, options) {
|
|
3398
|
+
const url = new URL(path, `${normalizeMapsBaseUrl(options?.mapsBaseUrl)}/`);
|
|
3399
|
+
for (const [key, value] of Object.entries(params)) {
|
|
3400
|
+
if (value === void 0 || value === "") continue;
|
|
3401
|
+
url.searchParams.set(key, String(value));
|
|
3402
|
+
}
|
|
3403
|
+
const site = siteTag(options);
|
|
3404
|
+
if (site) url.searchParams.set("site", site);
|
|
3405
|
+
return url.toString();
|
|
3406
|
+
}
|
|
3407
|
+
function resolveFetch(options) {
|
|
3408
|
+
const custom = options?.fetch;
|
|
3409
|
+
if (custom) return custom;
|
|
3410
|
+
const global = globalThis.fetch;
|
|
3411
|
+
if (!global) {
|
|
3412
|
+
throw new TypeError(
|
|
3413
|
+
"Garagem SDK: no fetch available. Pass `fetch` in the options."
|
|
3414
|
+
);
|
|
3415
|
+
}
|
|
3416
|
+
return global;
|
|
3417
|
+
}
|
|
3418
|
+
async function mapsFetchJson(url, options, init) {
|
|
3419
|
+
const headers = new Headers(init?.headers);
|
|
3420
|
+
headers.set("accept", "application/json");
|
|
3421
|
+
const site = siteTag(options);
|
|
3422
|
+
if (site) headers.set(MAPS_SITE_HEADER, site);
|
|
3423
|
+
try {
|
|
3424
|
+
const response = await resolveFetch(options)(url, { ...init, headers });
|
|
3425
|
+
if (!response.ok) return null;
|
|
3426
|
+
return await response.json();
|
|
3427
|
+
} catch {
|
|
3428
|
+
return null;
|
|
3429
|
+
}
|
|
3430
|
+
}
|
|
3431
|
+
function listingStaticMapUrl(listing, options = {}) {
|
|
3432
|
+
const raw = listingCoordinates(listing);
|
|
3433
|
+
if (!raw) return null;
|
|
3434
|
+
const coordinates = coarsenCoordinates(raw, options.maxDecimals);
|
|
3435
|
+
const zoomCeiling = maxZoomForCoordinates(coordinates);
|
|
3436
|
+
const zoom = Math.min(zoomCeiling, clampInt(options.zoom, 15, 1, 21));
|
|
3437
|
+
const markerColor = options.markerColor ?? "red";
|
|
3438
|
+
return mapsUrl(
|
|
3439
|
+
"/v1/static-map",
|
|
3440
|
+
{
|
|
3441
|
+
lat: coordinates.lat,
|
|
3442
|
+
lng: coordinates.lng,
|
|
3443
|
+
zoom,
|
|
3444
|
+
width: clampInt(options.width, 600, 1, MAPS_MAX_IMAGE_EDGE),
|
|
3445
|
+
height: clampInt(options.height, 300, 1, MAPS_MAX_IMAGE_EDGE),
|
|
3446
|
+
scale: options.scale === 1 ? 1 : 2,
|
|
3447
|
+
maptype: options.style,
|
|
3448
|
+
markerColor: markerColor !== "red" ? markerColor : void 0,
|
|
3449
|
+
hidePoi: options.hidePoi ? "1" : void 0
|
|
3450
|
+
},
|
|
3451
|
+
options
|
|
3452
|
+
);
|
|
3453
|
+
}
|
|
3454
|
+
function listingStreetViewUrl(listing, options = {}) {
|
|
3455
|
+
const raw = listingCoordinates(listing);
|
|
3456
|
+
if (!raw) return null;
|
|
3457
|
+
const coordinates = coarsenCoordinates(raw, options.maxDecimals);
|
|
3458
|
+
const width = clampInt(options.width, 640, 1, MAPS_MAX_IMAGE_EDGE);
|
|
3459
|
+
const height = clampInt(options.height, 640, 1, MAPS_MAX_IMAGE_EDGE);
|
|
3460
|
+
return mapsUrl(
|
|
3461
|
+
"/v1/street-view",
|
|
3462
|
+
{
|
|
3463
|
+
lat: coordinates.lat,
|
|
3464
|
+
lng: coordinates.lng,
|
|
3465
|
+
size: `${width}x${height}`,
|
|
3466
|
+
fov: clampInt(options.fov, 90, 10, 120),
|
|
3467
|
+
heading: clampInt(options.heading, 0, 0, 360),
|
|
3468
|
+
pitch: clampInt(options.pitch, 10, -90, 90)
|
|
3469
|
+
},
|
|
3470
|
+
options
|
|
3471
|
+
);
|
|
3472
|
+
}
|
|
3473
|
+
function listingStreetViewMetadataUrl(listing, options = {}) {
|
|
3474
|
+
const raw = listingCoordinates(listing);
|
|
3475
|
+
if (!raw) return null;
|
|
3476
|
+
const coordinates = coarsenCoordinates(raw, options.maxDecimals);
|
|
3477
|
+
return mapsUrl(
|
|
3478
|
+
"/v1/street-view/metadata",
|
|
3479
|
+
{ lat: coordinates.lat, lng: coordinates.lng },
|
|
3480
|
+
options
|
|
3481
|
+
);
|
|
3482
|
+
}
|
|
3483
|
+
async function listingStreetViewAvailable(listing, options = {}) {
|
|
3484
|
+
const url = listingStreetViewMetadataUrl(listing, options);
|
|
3485
|
+
if (!url) {
|
|
3486
|
+
return { available: false, status: "NO_COORDINATES", url: "" };
|
|
3487
|
+
}
|
|
3488
|
+
const data = await mapsFetchJson(url, options);
|
|
3489
|
+
const status = typeof data?.status === "string" ? data.status : "ERROR";
|
|
3490
|
+
const result = {
|
|
3491
|
+
available: status === "OK",
|
|
3492
|
+
status,
|
|
3493
|
+
url
|
|
3494
|
+
};
|
|
3495
|
+
if (typeof data?.pano_id === "string") result.panoId = data.pano_id;
|
|
3496
|
+
if (typeof data?.date === "string") result.date = data.date;
|
|
3497
|
+
return result;
|
|
3498
|
+
}
|
|
3499
|
+
function boundaryCitySlug(city) {
|
|
3500
|
+
return city.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
|
|
3501
|
+
}
|
|
3502
|
+
function boundaryLayerId(city) {
|
|
3503
|
+
const slug = boundaryCitySlug(city);
|
|
3504
|
+
return slug.endsWith("_boundaries") ? slug : `${slug}_boundaries`;
|
|
3505
|
+
}
|
|
3506
|
+
function boundaryLayerUrl(city, options = {}) {
|
|
3507
|
+
const base = normalizeMapsBaseUrl(options.mapsBaseUrl);
|
|
3508
|
+
const id = boundaryLayerId(city);
|
|
3509
|
+
const slug = id.replace(/_boundaries$/, "");
|
|
3510
|
+
switch (options.kind ?? "tilejson") {
|
|
3511
|
+
case "layer":
|
|
3512
|
+
return `${base}/v1/layers/${id}`;
|
|
3513
|
+
case "tiles":
|
|
3514
|
+
return `${base}/martin/${id}/{z}/{x}/{y}`;
|
|
3515
|
+
case "geojson":
|
|
3516
|
+
return `${base}/api/boundaries/${slug}`;
|
|
3517
|
+
default:
|
|
3518
|
+
return `${base}/martin/${id}`;
|
|
3519
|
+
}
|
|
3520
|
+
}
|
|
3521
|
+
function neighborhoodBoundaryUrl(city, neighborhood, options = {}) {
|
|
3522
|
+
const base = normalizeMapsBaseUrl(options.mapsBaseUrl);
|
|
3523
|
+
const slug = boundaryLayerId(city).replace(/_boundaries$/, "");
|
|
3524
|
+
const url = new URL(
|
|
3525
|
+
`${base}/api/boundaries/${slug}/${encodeURIComponent(neighborhood.trim())}`
|
|
3526
|
+
);
|
|
3527
|
+
if (options.source && options.source !== "listaaberta") {
|
|
3528
|
+
url.searchParams.set("source", options.source);
|
|
3529
|
+
}
|
|
3530
|
+
return url.toString();
|
|
3531
|
+
}
|
|
3532
|
+
function asNumber(value, fallback) {
|
|
3533
|
+
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
3534
|
+
}
|
|
3535
|
+
async function getBoundaryLayer(city, options = {}) {
|
|
3536
|
+
const data = await mapsFetchJson(
|
|
3537
|
+
boundaryLayerUrl(city, { ...options, kind: "layer" }),
|
|
3538
|
+
options
|
|
3539
|
+
);
|
|
3540
|
+
const layer = data?.layer;
|
|
3541
|
+
if (!data?.ok || !layer || typeof layer.id !== "string") return null;
|
|
3542
|
+
const rawSourceLayers = Array.isArray(layer.source_layers) ? layer.source_layers : [];
|
|
3543
|
+
return {
|
|
3544
|
+
id: layer.id,
|
|
3545
|
+
name: typeof layer.name === "string" ? layer.name : layer.id,
|
|
3546
|
+
description: typeof layer.description === "string" ? layer.description : "",
|
|
3547
|
+
city: typeof layer.city === "string" ? layer.city : void 0,
|
|
3548
|
+
tiles: typeof layer.tiles === "string" ? layer.tiles : "",
|
|
3549
|
+
tilejson: typeof layer.tilejson === "string" ? layer.tilejson : "",
|
|
3550
|
+
geojson: typeof layer.geojson === "string" ? layer.geojson : void 0,
|
|
3551
|
+
sourceLayers: rawSourceLayers.filter(
|
|
3552
|
+
(entry) => !!entry && typeof entry === "object"
|
|
3553
|
+
).map((entry) => ({
|
|
3554
|
+
id: String(entry.id ?? ""),
|
|
3555
|
+
label: String(entry.label ?? entry.id ?? ""),
|
|
3556
|
+
minzoom: typeof entry.minzoom === "number" ? entry.minzoom : void 0,
|
|
3557
|
+
maxzoom: typeof entry.maxzoom === "number" ? entry.maxzoom : void 0
|
|
3558
|
+
})),
|
|
3559
|
+
minzoom: asNumber(layer.minzoom, 0),
|
|
3560
|
+
maxzoom: asNumber(layer.maxzoom, 14),
|
|
3561
|
+
attribution: typeof layer.attribution === "string" ? layer.attribution : void 0,
|
|
3562
|
+
available: layer.available !== false
|
|
3563
|
+
};
|
|
3564
|
+
}
|
|
3565
|
+
function isFeature(value) {
|
|
3566
|
+
return !!value && typeof value === "object" && value.type === "Feature";
|
|
3567
|
+
}
|
|
3568
|
+
async function neighborhoodBoundaryLayer(city, neighborhood, options = {}) {
|
|
3569
|
+
const url = neighborhoodBoundaryUrl(city, neighborhood, options);
|
|
3570
|
+
const slug = boundaryLayerId(city).replace(/_boundaries$/, "");
|
|
3571
|
+
const result = {
|
|
3572
|
+
city: slug,
|
|
3573
|
+
neighborhood: neighborhood.trim(),
|
|
3574
|
+
feature: null,
|
|
3575
|
+
candidates: [],
|
|
3576
|
+
url,
|
|
3577
|
+
tiles: boundaryLayerUrl(city, { ...options, kind: "tiles" })
|
|
3578
|
+
};
|
|
3579
|
+
if (!result.neighborhood) return result;
|
|
3580
|
+
const data = await mapsFetchJson(
|
|
3581
|
+
url,
|
|
3582
|
+
options
|
|
3583
|
+
);
|
|
3584
|
+
if (!data) return result;
|
|
3585
|
+
if (isFeature(data)) {
|
|
3586
|
+
result.feature = data;
|
|
3587
|
+
result.candidates = [data];
|
|
3588
|
+
return result;
|
|
3589
|
+
}
|
|
3590
|
+
const features = Array.isArray(data.features) ? data.features.filter(isFeature) : [];
|
|
3591
|
+
result.candidates = features;
|
|
3592
|
+
const wanted = result.neighborhood.toLocaleLowerCase("pt-BR");
|
|
3593
|
+
result.feature = features.find(
|
|
3594
|
+
(feature) => typeof feature.properties?.name === "string" && feature.properties.name.toLocaleLowerCase("pt-BR") === wanted
|
|
3595
|
+
) ?? (features.length === 1 ? features[0] : null);
|
|
3596
|
+
return result;
|
|
3597
|
+
}
|
|
3598
|
+
function createTravelTimeCache(options = {}) {
|
|
3599
|
+
const maxEntries = Math.max(1, Math.floor(options.maxEntries ?? 200));
|
|
3600
|
+
const ttlMs = Math.max(0, options.ttlMs ?? 15 * 60 * 1e3);
|
|
3601
|
+
const entries = /* @__PURE__ */ new Map();
|
|
3602
|
+
return {
|
|
3603
|
+
get(key) {
|
|
3604
|
+
const hit = entries.get(key);
|
|
3605
|
+
if (!hit) return void 0;
|
|
3606
|
+
if (hit.expiresAt <= Date.now()) {
|
|
3607
|
+
entries.delete(key);
|
|
3608
|
+
return void 0;
|
|
3609
|
+
}
|
|
3610
|
+
entries.delete(key);
|
|
3611
|
+
entries.set(key, hit);
|
|
3612
|
+
return hit.value;
|
|
3613
|
+
},
|
|
3614
|
+
set(key, value) {
|
|
3615
|
+
entries.delete(key);
|
|
3616
|
+
entries.set(key, { value, expiresAt: Date.now() + ttlMs });
|
|
3617
|
+
while (entries.size > maxEntries) {
|
|
3618
|
+
const oldest = entries.keys().next().value;
|
|
3619
|
+
if (oldest === void 0) break;
|
|
3620
|
+
entries.delete(oldest);
|
|
3621
|
+
}
|
|
3622
|
+
},
|
|
3623
|
+
clear() {
|
|
3624
|
+
entries.clear();
|
|
3625
|
+
},
|
|
3626
|
+
get size() {
|
|
3627
|
+
return entries.size;
|
|
3628
|
+
}
|
|
3629
|
+
};
|
|
3630
|
+
}
|
|
3631
|
+
var defaultTravelTimeCache = createTravelTimeCache();
|
|
3632
|
+
function clearTravelTimeCache() {
|
|
3633
|
+
defaultTravelTimeCache.clear();
|
|
3634
|
+
}
|
|
3635
|
+
function travelTimeCacheKey(origin, destination, mode) {
|
|
3636
|
+
return `${origin.lat},${origin.lng}|${destination.lat},${destination.lng}|${mode}`;
|
|
3637
|
+
}
|
|
3638
|
+
function travelTimeQueryCacheKey(origin, query, mode) {
|
|
3639
|
+
return `${origin.lat},${origin.lng}|q:${query}|${mode}`;
|
|
3640
|
+
}
|
|
3641
|
+
function trimmedDestinationQuery(destination) {
|
|
3642
|
+
if (typeof destination !== "string") return null;
|
|
3643
|
+
const query = destination.trim();
|
|
3644
|
+
return query ? query : null;
|
|
3645
|
+
}
|
|
3646
|
+
function recallTravelTime(cache, key) {
|
|
3647
|
+
if (!cache) return null;
|
|
3648
|
+
const hit = cache.get(key);
|
|
3649
|
+
return hit ? { ...hit, cached: true } : null;
|
|
3650
|
+
}
|
|
3651
|
+
function rememberTravelTime(cache, keys, value) {
|
|
3652
|
+
if (!cache) return;
|
|
3653
|
+
for (const key of keys) cache.set(key, value);
|
|
3654
|
+
}
|
|
3655
|
+
function normalizeMode(mode) {
|
|
3656
|
+
return mode && TRAVEL_MODES.has(mode) ? mode : "driving";
|
|
3657
|
+
}
|
|
3658
|
+
async function resolveTravelDestination(destination, options = {}) {
|
|
3659
|
+
if (typeof destination !== "string") {
|
|
3660
|
+
const lat2 = finite(destination?.lat);
|
|
3661
|
+
const lng2 = finite(destination?.lng);
|
|
3662
|
+
return lat2 == null || lng2 == null ? null : { lat: lat2, lng: lng2 };
|
|
3663
|
+
}
|
|
3664
|
+
const query = destination.trim();
|
|
3665
|
+
if (!query) return null;
|
|
3666
|
+
const data = await mapsFetchJson(
|
|
3667
|
+
mapsUrl("/v1/geocode", { q: query }, options),
|
|
3668
|
+
options
|
|
3669
|
+
);
|
|
3670
|
+
const lat = finite(data?.latitude);
|
|
3671
|
+
const lng = finite(data?.longitude);
|
|
3672
|
+
if (!data?.ok || lat == null || lng == null) return null;
|
|
3673
|
+
return { lat, lng };
|
|
3674
|
+
}
|
|
3675
|
+
function minutesFromSeconds(seconds) {
|
|
3676
|
+
return Math.max(1, Math.round(seconds / 60));
|
|
3677
|
+
}
|
|
3678
|
+
async function travelTimeFromListing(listing, destination, options = {}) {
|
|
3679
|
+
const raw = listingCoordinates(listing);
|
|
3680
|
+
if (!raw) return null;
|
|
3681
|
+
const origin = coarsenCoordinates(raw, options.maxDecimals);
|
|
3682
|
+
const mode = normalizeMode(options.mode);
|
|
3683
|
+
const cache = options.cache === void 0 ? defaultTravelTimeCache : options.cache;
|
|
3684
|
+
const query = trimmedDestinationQuery(destination);
|
|
3685
|
+
if (typeof destination === "string" && !query) return null;
|
|
3686
|
+
if (query) {
|
|
3687
|
+
const queryHit = recallTravelTime(
|
|
3688
|
+
cache,
|
|
3689
|
+
travelTimeQueryCacheKey(origin, query, mode)
|
|
3690
|
+
);
|
|
3691
|
+
if (queryHit) return queryHit;
|
|
3692
|
+
}
|
|
3693
|
+
const target = await resolveTravelDestination(query ?? destination, options);
|
|
3694
|
+
if (!target) return null;
|
|
3695
|
+
const coordKey = travelTimeCacheKey(origin, target, mode);
|
|
3696
|
+
const stored = cache?.get(coordKey);
|
|
3697
|
+
if (stored) {
|
|
3698
|
+
if (query) {
|
|
3699
|
+
rememberTravelTime(
|
|
3700
|
+
cache,
|
|
3701
|
+
[travelTimeQueryCacheKey(origin, query, mode)],
|
|
3702
|
+
stored
|
|
3703
|
+
);
|
|
3704
|
+
}
|
|
3705
|
+
return { ...stored, cached: true };
|
|
3706
|
+
}
|
|
3707
|
+
const data = await mapsFetchJson(
|
|
3708
|
+
mapsUrl(
|
|
3709
|
+
"/v1/directions",
|
|
3710
|
+
{
|
|
3711
|
+
origin: `${origin.lat},${origin.lng}`,
|
|
3712
|
+
destination: `${target.lat},${target.lng}`,
|
|
3713
|
+
mode
|
|
3714
|
+
},
|
|
3715
|
+
options
|
|
3716
|
+
),
|
|
3717
|
+
options
|
|
3718
|
+
);
|
|
3719
|
+
const seconds = finite(data?.route?.totalTravelTime);
|
|
3720
|
+
const meters = finite(data?.route?.totalDistance);
|
|
3721
|
+
if (!data?.ok || seconds == null || meters == null) return null;
|
|
3722
|
+
const result = {
|
|
3723
|
+
minutes: minutesFromSeconds(seconds),
|
|
3724
|
+
seconds,
|
|
3725
|
+
distanceMeters: meters,
|
|
3726
|
+
distanceKm: Math.round(meters / 100) / 10,
|
|
3727
|
+
mode,
|
|
3728
|
+
origin,
|
|
3729
|
+
destination: target,
|
|
3730
|
+
cached: false
|
|
3731
|
+
};
|
|
3732
|
+
const keys = query ? [coordKey, travelTimeQueryCacheKey(origin, query, mode)] : [coordKey];
|
|
3733
|
+
rememberTravelTime(cache, keys, result);
|
|
3734
|
+
return result;
|
|
3735
|
+
}
|
|
3736
|
+
async function travelTimesFromListing(listing, destinations, options = {}) {
|
|
3737
|
+
const raw = listingCoordinates(listing);
|
|
3738
|
+
if (!raw) return null;
|
|
3739
|
+
const origin = coarsenCoordinates(raw, options.maxDecimals);
|
|
3740
|
+
const targets = destinations.map((destination) => {
|
|
3741
|
+
const lat = finite(destination?.lat);
|
|
3742
|
+
const lng = finite(destination?.lng);
|
|
3743
|
+
return lat == null || lng == null ? null : { lat, lng };
|
|
3744
|
+
}).filter((item) => item !== null);
|
|
3745
|
+
if (targets.length === 0) return [];
|
|
3746
|
+
const data = await mapsFetchJson(
|
|
3747
|
+
mapsUrl("/v1/route-matrix", {}, options),
|
|
3748
|
+
options,
|
|
3749
|
+
{
|
|
3750
|
+
method: "POST",
|
|
3751
|
+
headers: { "content-type": "application/json" },
|
|
3752
|
+
body: JSON.stringify({ origin, destinations: targets })
|
|
3753
|
+
}
|
|
3754
|
+
);
|
|
3755
|
+
if (!data?.ok || !Array.isArray(data.durations)) return null;
|
|
3756
|
+
return targets.map((destination, index) => {
|
|
3757
|
+
const seconds = finite(
|
|
3758
|
+
data.durations && data.durations[index]
|
|
3759
|
+
);
|
|
3760
|
+
if (seconds == null) return null;
|
|
3761
|
+
return { minutes: minutesFromSeconds(seconds), seconds, destination };
|
|
3762
|
+
});
|
|
3763
|
+
}
|
|
3764
|
+
|
|
3765
|
+
// src/map-search.ts
|
|
3766
|
+
var MAP_SEARCH_MAX_PAGE_SIZE = 100;
|
|
3767
|
+
var MAP_SEARCH_DEFAULT_PAGE_SIZE = 100;
|
|
3768
|
+
var MAP_SEARCH_MAX_PAGE = 1e4;
|
|
3769
|
+
var MAP_VIEWPORT_DEBOUNCE_MS = 400;
|
|
3770
|
+
var MAP_POLYGON_MAX_VERTICES = 64;
|
|
3771
|
+
function capMapPageSize(value) {
|
|
3772
|
+
if (value == null || !Number.isFinite(value) || value <= 0) {
|
|
3773
|
+
return MAP_SEARCH_DEFAULT_PAGE_SIZE;
|
|
3774
|
+
}
|
|
3775
|
+
return Math.min(MAP_SEARCH_MAX_PAGE_SIZE, Math.floor(value));
|
|
3776
|
+
}
|
|
3777
|
+
function capMapPage(value) {
|
|
3778
|
+
if (value == null || !Number.isFinite(value) || value <= 1) return 1;
|
|
3779
|
+
return Math.min(MAP_SEARCH_MAX_PAGE, Math.floor(value));
|
|
3780
|
+
}
|
|
3781
|
+
function finitePair(lat, lng) {
|
|
3782
|
+
if (typeof lat !== "number" || typeof lng !== "number") return null;
|
|
3783
|
+
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
|
|
3784
|
+
if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return null;
|
|
3785
|
+
return [lat, lng];
|
|
3786
|
+
}
|
|
3787
|
+
function isMapBounds(bounds) {
|
|
3788
|
+
if (!bounds) return false;
|
|
3789
|
+
const north = finitePair(bounds.north, bounds.east);
|
|
3790
|
+
const south = finitePair(bounds.south, bounds.west);
|
|
3791
|
+
if (!north || !south) return false;
|
|
3792
|
+
return bounds.north > bounds.south && bounds.east > bounds.west;
|
|
3793
|
+
}
|
|
3794
|
+
function isMapPolygon(polygon) {
|
|
3795
|
+
if (!Array.isArray(polygon)) return false;
|
|
3796
|
+
if (polygon.length < 3 || polygon.length > MAP_POLYGON_MAX_VERTICES + 1) {
|
|
3797
|
+
return false;
|
|
3798
|
+
}
|
|
3799
|
+
let unique = 0;
|
|
3800
|
+
let prev = null;
|
|
3801
|
+
for (const point of polygon) {
|
|
3802
|
+
if (!Array.isArray(point)) return false;
|
|
3803
|
+
const pair = finitePair(point[0], point[1]);
|
|
3804
|
+
if (!pair) return false;
|
|
3805
|
+
if (prev && prev[0] === pair[0] && prev[1] === pair[1]) continue;
|
|
3806
|
+
prev = pair;
|
|
3807
|
+
unique += 1;
|
|
3808
|
+
}
|
|
3809
|
+
if (unique >= 2 && polygon.length >= 2) {
|
|
3810
|
+
const first = finitePair(polygon[0]?.[0], polygon[0]?.[1]);
|
|
3811
|
+
const last = finitePair(
|
|
3812
|
+
polygon[polygon.length - 1]?.[0],
|
|
3813
|
+
polygon[polygon.length - 1]?.[1]
|
|
3814
|
+
);
|
|
3815
|
+
if (first && last && first[0] === last[0] && first[1] === last[1] && unique > 1) {
|
|
3816
|
+
unique -= 1;
|
|
3817
|
+
}
|
|
3818
|
+
}
|
|
3819
|
+
return unique >= 3 && unique <= MAP_POLYGON_MAX_VERTICES;
|
|
3820
|
+
}
|
|
3821
|
+
function mapSearchPins(listings) {
|
|
3822
|
+
const pins = [];
|
|
3823
|
+
for (const listing of listings) {
|
|
3824
|
+
const coords = listingCoordinates(listing);
|
|
3825
|
+
if (!coords || !listing.id) continue;
|
|
3826
|
+
const src = listing.coverImage?.src;
|
|
3827
|
+
pins.push({
|
|
3828
|
+
id: listing.id,
|
|
3829
|
+
lat: coords.lat,
|
|
3830
|
+
lng: coords.lng,
|
|
3831
|
+
price: listing.price ?? null,
|
|
3832
|
+
coverImage: src ? src : null
|
|
3833
|
+
});
|
|
3834
|
+
}
|
|
3835
|
+
return pins;
|
|
3836
|
+
}
|
|
3837
|
+
function listingsResult(listings, meta, requestedPageSize) {
|
|
3838
|
+
return {
|
|
3839
|
+
pins: mapSearchPins(listings),
|
|
3840
|
+
cards: listings.map((listing) => toListingCardModel(listing)),
|
|
3841
|
+
listings,
|
|
3842
|
+
page: meta.page ?? 1,
|
|
3843
|
+
pageSize: meta.limit ?? requestedPageSize,
|
|
3844
|
+
total: meta.total ?? listings.length,
|
|
3845
|
+
totalPages: meta.totalPages ?? 0
|
|
3846
|
+
};
|
|
3847
|
+
}
|
|
3848
|
+
function searchParams(area, options) {
|
|
3849
|
+
const params = {
|
|
3850
|
+
page: capMapPage(options.page),
|
|
3851
|
+
limit: capMapPageSize(options.pageSize)
|
|
3852
|
+
};
|
|
3853
|
+
if (options.q !== void 0) params.q = options.q;
|
|
3854
|
+
if (options.sort !== void 0) params.sort = options.sort;
|
|
3855
|
+
if (options.location !== void 0) params.location = options.location;
|
|
3856
|
+
if (options.filters) params.filters = options.filters;
|
|
3857
|
+
if (area.polygon) params.polygon = area.polygon;
|
|
3858
|
+
else if (area.bounds) params.bounds = area.bounds;
|
|
3859
|
+
return params;
|
|
3860
|
+
}
|
|
3861
|
+
async function runMapSearch(siteId, area, options) {
|
|
3862
|
+
const pageSize = capMapPageSize(options.pageSize);
|
|
3863
|
+
const result = await queryListings({
|
|
3864
|
+
siteId,
|
|
3865
|
+
params: searchParams(area, options),
|
|
3866
|
+
baseUrl: options.baseUrl,
|
|
3867
|
+
fetch: options.fetch,
|
|
3868
|
+
signal: options.signal,
|
|
3869
|
+
publishableKey: options.publishableKey,
|
|
3870
|
+
next: options.next
|
|
3871
|
+
});
|
|
3872
|
+
return listingsResult(result.listings ?? [], result, pageSize);
|
|
3873
|
+
}
|
|
3874
|
+
async function searchListingsInBounds(siteId, options) {
|
|
3875
|
+
if (!isMapBounds(options.bounds)) {
|
|
3876
|
+
throw new TypeError(
|
|
3877
|
+
"searchListingsInBounds: bounds must be a finite rectangle with north > south and east > west (no antimeridian)."
|
|
3878
|
+
);
|
|
3879
|
+
}
|
|
3880
|
+
return runMapSearch(siteId, { bounds: options.bounds }, options);
|
|
3881
|
+
}
|
|
3882
|
+
async function searchListingsInPolygon(siteId, options) {
|
|
3883
|
+
if (!isMapPolygon(options.polygon)) {
|
|
3884
|
+
throw new TypeError(
|
|
3885
|
+
`searchListingsInPolygon: polygon must be 3\u2013${MAP_POLYGON_MAX_VERTICES} finite [lat, lng] points.`
|
|
3886
|
+
);
|
|
3887
|
+
}
|
|
3888
|
+
return runMapSearch(siteId, { polygon: options.polygon }, options);
|
|
3889
|
+
}
|
|
3890
|
+
function clampZoom(zoom) {
|
|
3891
|
+
if (!Number.isFinite(zoom)) return 0;
|
|
3892
|
+
return Math.min(22, Math.max(0, zoom));
|
|
3893
|
+
}
|
|
3894
|
+
function mapClusterCellDegrees(zoom) {
|
|
3895
|
+
return 360 / 2 ** clampZoom(zoom) / 4;
|
|
3896
|
+
}
|
|
3897
|
+
function usablePin(pin) {
|
|
3898
|
+
return finitePair(pin.lat, pin.lng) !== null && !(pin.lat === 0 && pin.lng === 0);
|
|
3899
|
+
}
|
|
3900
|
+
function groupPrecision(group) {
|
|
3901
|
+
let max = 0;
|
|
3902
|
+
for (const pin of group) {
|
|
3903
|
+
max = Math.max(
|
|
3904
|
+
max,
|
|
3905
|
+
coordinateDecimals(pin.lat),
|
|
3906
|
+
coordinateDecimals(pin.lng)
|
|
3907
|
+
);
|
|
3908
|
+
}
|
|
3909
|
+
return max;
|
|
3910
|
+
}
|
|
3911
|
+
function multiCluster(key, group) {
|
|
3912
|
+
const lat = group.reduce((sum, pin) => sum + pin.lat, 0) / group.length;
|
|
3913
|
+
const lng = group.reduce((sum, pin) => sum + pin.lng, 0) / group.length;
|
|
3914
|
+
const center = coarsenCoordinates({ lat, lng }, groupPrecision(group));
|
|
3915
|
+
return {
|
|
3916
|
+
id: key,
|
|
3917
|
+
lat: center.lat,
|
|
3918
|
+
lng: center.lng,
|
|
3919
|
+
count: group.length,
|
|
3920
|
+
pinIds: group.map((pin) => pin.id),
|
|
3921
|
+
pin: null
|
|
3922
|
+
};
|
|
3923
|
+
}
|
|
3924
|
+
function singleCluster(pin) {
|
|
3925
|
+
return {
|
|
3926
|
+
id: pin.id,
|
|
3927
|
+
lat: pin.lat,
|
|
3928
|
+
lng: pin.lng,
|
|
3929
|
+
count: 1,
|
|
3930
|
+
pinIds: [pin.id],
|
|
3931
|
+
pin
|
|
3932
|
+
};
|
|
3933
|
+
}
|
|
3934
|
+
function clusterPins(pins, zoom) {
|
|
3935
|
+
if (pins.length === 0) return [];
|
|
3936
|
+
const cell = mapClusterCellDegrees(zoom);
|
|
3937
|
+
const groups = /* @__PURE__ */ new Map();
|
|
3938
|
+
for (const pin of pins) {
|
|
3939
|
+
if (!usablePin(pin)) continue;
|
|
3940
|
+
const key = `${Math.floor(pin.lat / cell)}:${Math.floor(pin.lng / cell)}`;
|
|
3941
|
+
const list = groups.get(key);
|
|
3942
|
+
if (list) list.push(pin);
|
|
3943
|
+
else groups.set(key, [pin]);
|
|
3944
|
+
}
|
|
3945
|
+
const clusters = [];
|
|
3946
|
+
for (const [key, group] of groups) {
|
|
3947
|
+
const only = group[0];
|
|
3948
|
+
clusters.push(
|
|
3949
|
+
group.length === 1 && only ? singleCluster(only) : multiCluster(key, group)
|
|
3950
|
+
);
|
|
3951
|
+
}
|
|
3952
|
+
clusters.sort((a, b) => a.id.localeCompare(b.id));
|
|
3953
|
+
return clusters;
|
|
3954
|
+
}
|
|
3955
|
+
|
|
3284
3956
|
// src/fetchers-photos.ts
|
|
3285
3957
|
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
3958
|
var HIDDEN_SIMILAR_PHOTOS = {
|
|
@@ -3800,12 +4472,19 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
|
|
|
3800
4472
|
}
|
|
3801
4473
|
export {
|
|
3802
4474
|
AMENITY_FALLBACK_LABELS,
|
|
4475
|
+
DEFAULT_MAPS_BASE_URL,
|
|
3803
4476
|
DEFAULT_PHONE_COUNTRY_CODE,
|
|
3804
4477
|
FORBIDDEN_SEARCH_QUERY_KEYS,
|
|
3805
4478
|
GaragemSdkError,
|
|
3806
4479
|
LISTING_AMENITY_TITLES,
|
|
3807
4480
|
LISTING_DESCRIPTION_CLAMP,
|
|
3808
4481
|
LeadSubmitError,
|
|
4482
|
+
MAPS_MAX_IMAGE_EDGE,
|
|
4483
|
+
MAPS_SITE_HEADER,
|
|
4484
|
+
MAP_POLYGON_MAX_VERTICES,
|
|
4485
|
+
MAP_SEARCH_DEFAULT_PAGE_SIZE,
|
|
4486
|
+
MAP_SEARCH_MAX_PAGE_SIZE,
|
|
4487
|
+
MAP_VIEWPORT_DEBOUNCE_MS,
|
|
3809
4488
|
MATCHED_PHOTO_COVER_MAX_DISTANCE,
|
|
3810
4489
|
MAX_NATIONAL_PHONE_DIGITS,
|
|
3811
4490
|
PHONE_COUNTRIES,
|
|
@@ -3822,18 +4501,28 @@ export {
|
|
|
3822
4501
|
VISIT_TIME_ZONE,
|
|
3823
4502
|
applyMatchedPhotoCover,
|
|
3824
4503
|
applyPathFilter,
|
|
4504
|
+
boundaryCitySlug,
|
|
4505
|
+
boundaryLayerId,
|
|
4506
|
+
boundaryLayerUrl,
|
|
3825
4507
|
buildQueryListingsParams,
|
|
3826
4508
|
canonicalizeSearchHref,
|
|
4509
|
+
capMapPage,
|
|
4510
|
+
capMapPageSize,
|
|
3827
4511
|
clearStagedPathFilters,
|
|
4512
|
+
clearTravelTimeCache,
|
|
4513
|
+
clusterPins,
|
|
4514
|
+
coarsenCoordinates,
|
|
3828
4515
|
coerceNpmVersion,
|
|
3829
4516
|
collapseDuplicatedBrazilianMobileNine,
|
|
3830
4517
|
compareSemver,
|
|
3831
4518
|
composeSearchPublicHref2 as composeSearchPublicHref,
|
|
3832
4519
|
composeSearchPublicPath2 as composeSearchPublicPath,
|
|
4520
|
+
coordinateDecimals,
|
|
3833
4521
|
countFacetChoices,
|
|
3834
4522
|
countOptionLabel,
|
|
3835
4523
|
createClient,
|
|
3836
4524
|
createGaragemClient,
|
|
4525
|
+
createTravelTimeCache,
|
|
3837
4526
|
defaultPhoneCountry,
|
|
3838
4527
|
displayPathLocation,
|
|
3839
4528
|
expandVisitSchedule,
|
|
@@ -3843,6 +4532,7 @@ export {
|
|
|
3843
4532
|
formatGroupedInteger,
|
|
3844
4533
|
formatListingPrice,
|
|
3845
4534
|
formatPhoneNational,
|
|
4535
|
+
getBoundaryLayer,
|
|
3846
4536
|
getCmsCollection,
|
|
3847
4537
|
getCmsCollections,
|
|
3848
4538
|
getCmsEntries,
|
|
@@ -3861,6 +4551,8 @@ export {
|
|
|
3861
4551
|
hrefForPathFilters,
|
|
3862
4552
|
hrefWithExplicitPage,
|
|
3863
4553
|
isListingDetailPath,
|
|
4554
|
+
isMapBounds,
|
|
4555
|
+
isMapPolygon,
|
|
3864
4556
|
isPhotoSearchOnPin,
|
|
3865
4557
|
isStudioPreviewHost,
|
|
3866
4558
|
isValidPhone,
|
|
@@ -3869,6 +4561,7 @@ export {
|
|
|
3869
4561
|
listingAmenityGroups,
|
|
3870
4562
|
listingBreadcrumb,
|
|
3871
4563
|
listingBusinessLabel,
|
|
4564
|
+
listingCoordinates,
|
|
3872
4565
|
listingDescriptionPreview,
|
|
3873
4566
|
listingDetailFieldsModel,
|
|
3874
4567
|
listingDetailModel,
|
|
@@ -3880,12 +4573,23 @@ export {
|
|
|
3880
4573
|
listingMediaOverlays,
|
|
3881
4574
|
listingPhotoGroups,
|
|
3882
4575
|
listingPublicPath,
|
|
4576
|
+
listingStaticMapUrl,
|
|
4577
|
+
listingStreetViewAvailable,
|
|
4578
|
+
listingStreetViewMetadataUrl,
|
|
4579
|
+
listingStreetViewUrl,
|
|
3883
4580
|
listingValues,
|
|
3884
4581
|
listingVisualHighlights,
|
|
4582
|
+
mapClusterCellDegrees,
|
|
4583
|
+
mapSearchPins,
|
|
4584
|
+
mapsExportsPublished,
|
|
3885
4585
|
marketExportsAvailableAt,
|
|
3886
4586
|
marketPositionLabel,
|
|
4587
|
+
maxZoomForCoordinates,
|
|
3887
4588
|
mergeAppliedSearchQueryIntoSearch2 as mergeAppliedSearchQueryIntoSearch,
|
|
3888
4589
|
nationalPhoneDigits,
|
|
4590
|
+
neighborhoodBoundaryLayer,
|
|
4591
|
+
neighborhoodBoundaryUrl,
|
|
4592
|
+
normalizeMapsBaseUrl,
|
|
3889
4593
|
normalizeVisitDate,
|
|
3890
4594
|
normalizeVisitTime,
|
|
3891
4595
|
paginationPages,
|
|
@@ -3911,10 +4615,13 @@ export {
|
|
|
3911
4615
|
requestPriceEstimate,
|
|
3912
4616
|
resolveMatchedCoverPhoto,
|
|
3913
4617
|
resolvePublicSiteId,
|
|
4618
|
+
resolveTravelDestination,
|
|
3914
4619
|
searchChromeModel,
|
|
3915
4620
|
searchHrefUsesLegacyFilterQuery,
|
|
3916
4621
|
searchListingPhotos,
|
|
3917
4622
|
searchListings,
|
|
4623
|
+
searchListingsInBounds,
|
|
4624
|
+
searchListingsInPolygon,
|
|
3918
4625
|
searchResultsHeading,
|
|
3919
4626
|
searchSortOptions,
|
|
3920
4627
|
serializeAppliedSearchQuery2 as serializeAppliedSearchQuery,
|
|
@@ -3927,6 +4634,8 @@ export {
|
|
|
3927
4634
|
studioLeadInstruction,
|
|
3928
4635
|
studioListingCardInstruction,
|
|
3929
4636
|
studioListingDetailInstruction,
|
|
4637
|
+
studioMapSearchInstruction,
|
|
4638
|
+
studioMapsInstruction,
|
|
3930
4639
|
studioMarketInstruction,
|
|
3931
4640
|
studioPhotoInstruction,
|
|
3932
4641
|
studioPhotoInstructionFor,
|
|
@@ -3941,6 +4650,9 @@ export {
|
|
|
3941
4650
|
toE164,
|
|
3942
4651
|
toListingCardModel,
|
|
3943
4652
|
toolbarFilterIds,
|
|
4653
|
+
travelTimeCacheKey,
|
|
4654
|
+
travelTimeFromListing,
|
|
4655
|
+
travelTimesFromListing,
|
|
3944
4656
|
truncateNationalPhoneDigits,
|
|
3945
4657
|
unavailableReactImports,
|
|
3946
4658
|
visibleSearchFilters
|