@garagem-ai/site-sdk 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +329 -31
- package/dist/index.d.mts +305 -44
- package/dist/index.d.ts +305 -44
- package/dist/index.js +1282 -34
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1233 -34
- package/dist/index.mjs.map +1 -1
- package/dist/react.d.mts +29 -2
- package/dist/react.d.ts +29 -2
- package/dist/react.js +639 -26
- package/dist/react.js.map +1 -1
- package/dist/react.mjs +638 -26
- package/dist/react.mjs.map +1 -1
- package/dist/{types-photo-search-OeONNDxl.d.mts → types-photo-search-D88oevZv.d.mts} +400 -1
- package/dist/{types-photo-search-OeONNDxl.d.ts → types-photo-search-D88oevZv.d.ts} +400 -1
- package/package.json +1 -1
- package/src/client.ts +23 -0
- package/src/fetchers-photos.ts +98 -0
- package/src/fetchers.ts +96 -30
- package/src/index.ts +120 -2
- package/src/internal/sdk-http.ts +122 -0
- package/src/leads.ts +34 -3
- package/src/listing-photos.ts +312 -0
- package/src/map-search.ts +487 -0
- package/src/maps.ts +743 -0
- package/src/react/index.ts +2 -0
- package/src/react/types.ts +5 -0
- package/src/react/use-map-search.ts +101 -0
- package/src/react/use-public-search.ts +23 -5
- package/src/resolve-site-id.ts +3 -0
- package/src/studio-contract.ts +120 -0
- package/src/types-maps.ts +275 -0
- package/src/types-photos.ts +46 -0
- package/src/types.ts +23 -0
package/dist/react.mjs
CHANGED
|
@@ -4,6 +4,101 @@
|
|
|
4
4
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
5
5
|
import { usePathname, useRouter } from "next/navigation";
|
|
6
6
|
|
|
7
|
+
// src/listing-path.ts
|
|
8
|
+
function listingPublicPath(listing) {
|
|
9
|
+
const composed = listing.path?.trim() ?? "";
|
|
10
|
+
if (composed.startsWith("/") && !composed.startsWith("//")) return composed;
|
|
11
|
+
const identity = listing.listingCode?.trim() || listing.id?.trim() || "";
|
|
12
|
+
if (!identity || identity === "undefined" || identity === "null") {
|
|
13
|
+
throw new TypeError("listingPublicPath: listing has no listingCode or id");
|
|
14
|
+
}
|
|
15
|
+
return `/imoveis/id-${identity}`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// src/internal/sdk-http.ts
|
|
19
|
+
var PUBLISHABLE_KEY_HEADER = "X-Garagem-Publishable-Key";
|
|
20
|
+
function publishableKeyHeaders(publishableKey) {
|
|
21
|
+
const key = publishableKey?.trim();
|
|
22
|
+
if (!key) return {};
|
|
23
|
+
return { [PUBLISHABLE_KEY_HEADER]: key };
|
|
24
|
+
}
|
|
25
|
+
function withPublishableKeyHeader(init, publishableKey) {
|
|
26
|
+
const extra = publishableKeyHeaders(publishableKey);
|
|
27
|
+
if (Object.keys(extra).length === 0) return init;
|
|
28
|
+
const current = init.headers;
|
|
29
|
+
const base = plainHeaders(current);
|
|
30
|
+
return { ...init, headers: { ...base, ...extra } };
|
|
31
|
+
}
|
|
32
|
+
function plainHeaders(headers) {
|
|
33
|
+
const out = {};
|
|
34
|
+
if (!headers) return out;
|
|
35
|
+
if (typeof Headers !== "undefined" && headers instanceof Headers) {
|
|
36
|
+
headers.forEach((value, name) => {
|
|
37
|
+
out[name] = value;
|
|
38
|
+
});
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
if (Array.isArray(headers)) {
|
|
42
|
+
for (const pair of headers) {
|
|
43
|
+
out[String(pair[0])] = String(pair[1]);
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
for (const [name, value] of Object.entries(
|
|
48
|
+
headers
|
|
49
|
+
)) {
|
|
50
|
+
if (typeof value === "string") out[name] = value;
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
function finiteNonNegative(value) {
|
|
55
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
|
|
56
|
+
return value;
|
|
57
|
+
}
|
|
58
|
+
if (typeof value === "string" && value.trim()) {
|
|
59
|
+
const parsed = Number(value);
|
|
60
|
+
if (Number.isFinite(parsed) && parsed >= 0) return parsed;
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
function parseSdkErrorBody(text) {
|
|
65
|
+
const raw = text ? text.slice(0, 200) : "";
|
|
66
|
+
if (!text) {
|
|
67
|
+
return { reason: null, retryAfterSeconds: null, summary: "" };
|
|
68
|
+
}
|
|
69
|
+
try {
|
|
70
|
+
const body = JSON.parse(text);
|
|
71
|
+
if (!body || typeof body !== "object") {
|
|
72
|
+
return { reason: null, retryAfterSeconds: null, summary: raw };
|
|
73
|
+
}
|
|
74
|
+
const record = body;
|
|
75
|
+
const reason = typeof record.reason === "string" && record.reason ? record.reason : null;
|
|
76
|
+
const retryAfterSeconds = finiteNonNegative(
|
|
77
|
+
record.retryAfterSeconds ?? record.retryAfter
|
|
78
|
+
);
|
|
79
|
+
const errorText = typeof record.error === "string" && record.error ? record.error : raw;
|
|
80
|
+
return {
|
|
81
|
+
reason,
|
|
82
|
+
retryAfterSeconds,
|
|
83
|
+
summary: errorText.slice(0, 200)
|
|
84
|
+
};
|
|
85
|
+
} catch {
|
|
86
|
+
return { reason: null, retryAfterSeconds: null, summary: raw };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function retryAfterFromResponse(response, bodySeconds, nowMs = Date.now()) {
|
|
90
|
+
const header = response.headers.get("Retry-After")?.trim();
|
|
91
|
+
if (header) {
|
|
92
|
+
const delta = finiteNonNegative(header);
|
|
93
|
+
if (delta != null) return delta;
|
|
94
|
+
const at = Date.parse(header);
|
|
95
|
+
if (Number.isFinite(at)) {
|
|
96
|
+
return Math.max(0, Math.ceil((at - nowMs) / 1e3));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return bodySeconds;
|
|
100
|
+
}
|
|
101
|
+
|
|
7
102
|
// src/internal/url.ts
|
|
8
103
|
var DEFAULT_BASE_URL = "https://app.garagem.ai";
|
|
9
104
|
function normalizeBaseUrl(baseUrl) {
|
|
@@ -22,27 +117,50 @@ async function coerceSiteId(siteId) {
|
|
|
22
117
|
}
|
|
23
118
|
|
|
24
119
|
// src/fetchers.ts
|
|
25
|
-
async function callJson(url, init, fetchImpl) {
|
|
26
|
-
const response = await fetchImpl(
|
|
120
|
+
async function callJson(url, init, fetchImpl, publishableKey) {
|
|
121
|
+
const response = await fetchImpl(
|
|
122
|
+
url,
|
|
123
|
+
withPublishableKeyHeader(init, publishableKey)
|
|
124
|
+
);
|
|
27
125
|
if (!response.ok) {
|
|
28
|
-
|
|
29
|
-
throw new GaragemSdkError(
|
|
30
|
-
`Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${text ? ` \u2014 ${text.slice(0, 200)}` : ""}`,
|
|
31
|
-
{ status: response.status, url }
|
|
32
|
-
);
|
|
126
|
+
throw await readGaragemSdkError(response, url);
|
|
33
127
|
}
|
|
34
128
|
return await response.json();
|
|
35
129
|
}
|
|
36
130
|
var GaragemSdkError = class extends Error {
|
|
37
131
|
status;
|
|
38
132
|
url;
|
|
133
|
+
/** Machine reason from the JSON body (`invalid_publishable_key`, `rate_limited`, …). */
|
|
134
|
+
reason;
|
|
135
|
+
/**
|
|
136
|
+
* Seconds to wait before retrying. Set on HTTP 429 from `Retry-After`
|
|
137
|
+
* or the body's `retryAfterSeconds`. `null` when the response has neither.
|
|
138
|
+
*/
|
|
139
|
+
retryAfter;
|
|
39
140
|
constructor(message, info) {
|
|
40
141
|
super(message);
|
|
41
142
|
this.name = "GaragemSdkError";
|
|
42
143
|
this.status = info.status;
|
|
43
144
|
this.url = info.url;
|
|
145
|
+
this.reason = info.reason ?? null;
|
|
146
|
+
this.retryAfter = info.retryAfter ?? null;
|
|
44
147
|
}
|
|
45
148
|
};
|
|
149
|
+
async function readGaragemSdkError(response, url) {
|
|
150
|
+
const text = await response.text().catch(() => "");
|
|
151
|
+
const parsed = parseSdkErrorBody(text);
|
|
152
|
+
const retryAfter = response.status === 429 ? retryAfterFromResponse(response, parsed.retryAfterSeconds) : parsed.retryAfterSeconds;
|
|
153
|
+
const detail = parsed.summary;
|
|
154
|
+
return new GaragemSdkError(
|
|
155
|
+
`Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${detail ? ` \u2014 ${detail}` : ""}`,
|
|
156
|
+
{
|
|
157
|
+
status: response.status,
|
|
158
|
+
url,
|
|
159
|
+
reason: parsed.reason,
|
|
160
|
+
retryAfter
|
|
161
|
+
}
|
|
162
|
+
);
|
|
163
|
+
}
|
|
46
164
|
async function getSearchUi(options) {
|
|
47
165
|
const { baseUrl, fetch: fetchImpl, next } = options;
|
|
48
166
|
const siteId = await coerceSiteId(options.siteId);
|
|
@@ -51,11 +169,12 @@ async function getSearchUi(options) {
|
|
|
51
169
|
return callJson(
|
|
52
170
|
url,
|
|
53
171
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
54
|
-
fetchImpl ?? fetch
|
|
172
|
+
fetchImpl ?? fetch,
|
|
173
|
+
options.publishableKey
|
|
55
174
|
);
|
|
56
175
|
}
|
|
57
176
|
async function queryListings(options) {
|
|
58
|
-
const { params, baseUrl, fetch: fetchImpl, next } = options;
|
|
177
|
+
const { params, baseUrl, fetch: fetchImpl, next, signal } = options;
|
|
59
178
|
const siteId = await coerceSiteId(options.siteId);
|
|
60
179
|
const base = normalizeBaseUrl(baseUrl);
|
|
61
180
|
const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;
|
|
@@ -68,9 +187,11 @@ async function queryListings(options) {
|
|
|
68
187
|
"Content-Type": "application/json"
|
|
69
188
|
},
|
|
70
189
|
body: JSON.stringify(params ?? {}),
|
|
71
|
-
next
|
|
190
|
+
next,
|
|
191
|
+
signal
|
|
72
192
|
},
|
|
73
|
-
fetchImpl ?? fetch
|
|
193
|
+
fetchImpl ?? fetch,
|
|
194
|
+
options.publishableKey
|
|
74
195
|
);
|
|
75
196
|
}
|
|
76
197
|
|
|
@@ -521,6 +642,19 @@ function pathFiltersToQueryFilters(pathFilters) {
|
|
|
521
642
|
}
|
|
522
643
|
|
|
523
644
|
// src/presentation.ts
|
|
645
|
+
function formatListingPrice(amount, locale = "pt-BR", currency = "BRL") {
|
|
646
|
+
if (amount == null) return "Sob consulta";
|
|
647
|
+
try {
|
|
648
|
+
return new Intl.NumberFormat(locale, {
|
|
649
|
+
style: "currency",
|
|
650
|
+
currency,
|
|
651
|
+
minimumFractionDigits: 0,
|
|
652
|
+
maximumFractionDigits: 0
|
|
653
|
+
}).format(amount);
|
|
654
|
+
} catch {
|
|
655
|
+
return `${currency} ${amount}`;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
524
658
|
function parseGroupedInteger(value) {
|
|
525
659
|
if (typeof value === "number") {
|
|
526
660
|
return Number.isFinite(value) ? Math.trunc(value) : void 0;
|
|
@@ -530,6 +664,9 @@ function parseGroupedInteger(value) {
|
|
|
530
664
|
const amount = Number.parseInt(digits, 10);
|
|
531
665
|
return Number.isFinite(amount) ? amount : void 0;
|
|
532
666
|
}
|
|
667
|
+
function listingBusinessLabel(businessType) {
|
|
668
|
+
return businessType === "rental" ? "Aluguel" : "Venda";
|
|
669
|
+
}
|
|
533
670
|
|
|
534
671
|
// src/search-engine.ts
|
|
535
672
|
var PATH_FILTER_IDS = {
|
|
@@ -808,7 +945,13 @@ function currentHref(pathname, search) {
|
|
|
808
945
|
return search ? `${pathname}?${search}` : pathname;
|
|
809
946
|
}
|
|
810
947
|
function usePublicSearch(options) {
|
|
811
|
-
const {
|
|
948
|
+
const {
|
|
949
|
+
siteId,
|
|
950
|
+
baseUrl,
|
|
951
|
+
publishableKey,
|
|
952
|
+
initial,
|
|
953
|
+
search: searchFromServer = ""
|
|
954
|
+
} = options;
|
|
812
955
|
const router = useRouter();
|
|
813
956
|
const pathname = usePathname() || "/imoveis";
|
|
814
957
|
const search = searchFromServer;
|
|
@@ -897,13 +1040,23 @@ function usePublicSearch(options) {
|
|
|
897
1040
|
}
|
|
898
1041
|
async function loadSchema() {
|
|
899
1042
|
try {
|
|
900
|
-
const nextSchema = await getSearchUi({
|
|
1043
|
+
const nextSchema = await getSearchUi({
|
|
1044
|
+
siteId: id,
|
|
1045
|
+
baseUrl,
|
|
1046
|
+
publishableKey
|
|
1047
|
+
});
|
|
901
1048
|
if (!active) return;
|
|
902
1049
|
let locations = null;
|
|
903
1050
|
if (nextSchema.locationsPath.startsWith("/")) {
|
|
904
1051
|
try {
|
|
905
1052
|
const response = await fetch(
|
|
906
|
-
`${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}
|
|
1053
|
+
`${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`,
|
|
1054
|
+
{
|
|
1055
|
+
headers: {
|
|
1056
|
+
Accept: "application/json",
|
|
1057
|
+
...publishableKeyHeaders(publishableKey)
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
907
1060
|
);
|
|
908
1061
|
if (response.ok) {
|
|
909
1062
|
locations = await response.json();
|
|
@@ -937,7 +1090,7 @@ function usePublicSearch(options) {
|
|
|
937
1090
|
return () => {
|
|
938
1091
|
active = false;
|
|
939
1092
|
};
|
|
940
|
-
}, [baseUrl, catalogId]);
|
|
1093
|
+
}, [baseUrl, catalogId, publishableKey]);
|
|
941
1094
|
useEffect(() => {
|
|
942
1095
|
if (!schema || !catalogId) return;
|
|
943
1096
|
const currentSchema = schema;
|
|
@@ -960,6 +1113,7 @@ function usePublicSearch(options) {
|
|
|
960
1113
|
const response = await queryListings({
|
|
961
1114
|
siteId: id,
|
|
962
1115
|
baseUrl,
|
|
1116
|
+
publishableKey,
|
|
963
1117
|
params: buildQueryListingsParams(
|
|
964
1118
|
pathFilters,
|
|
965
1119
|
applied,
|
|
@@ -996,7 +1150,7 @@ function usePublicSearch(options) {
|
|
|
996
1150
|
return () => {
|
|
997
1151
|
active = false;
|
|
998
1152
|
};
|
|
999
|
-
}, [pathname, search, baseUrl, schema, catalogId]);
|
|
1153
|
+
}, [pathname, search, baseUrl, schema, catalogId, publishableKey]);
|
|
1000
1154
|
const go = useCallback(
|
|
1001
1155
|
(href) => {
|
|
1002
1156
|
if (href && href !== currentHref(pathname, search)) router.push(href);
|
|
@@ -1110,9 +1264,466 @@ function usePublicSearch(options) {
|
|
|
1110
1264
|
};
|
|
1111
1265
|
}
|
|
1112
1266
|
|
|
1113
|
-
// src/react/use-
|
|
1267
|
+
// src/react/use-map-search.ts
|
|
1114
1268
|
import { useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2, useState as useState2 } from "react";
|
|
1115
1269
|
|
|
1270
|
+
// src/listing-card-model.ts
|
|
1271
|
+
function listingLocationLabel(location) {
|
|
1272
|
+
return [location.neighborhood, location.city, location.state].map((part) => part ? String(part).trim() : "").filter(Boolean).join(", ");
|
|
1273
|
+
}
|
|
1274
|
+
function toListingCardModel(listing) {
|
|
1275
|
+
const isPrivate = listing.priceVisibility === "private";
|
|
1276
|
+
const area = listing.property?.usableArea ?? listing.property?.totalArea;
|
|
1277
|
+
return {
|
|
1278
|
+
href: listingPublicPath(listing),
|
|
1279
|
+
title: listing.title,
|
|
1280
|
+
businessType: listing.businessType,
|
|
1281
|
+
businessLabel: listingBusinessLabel(listing.businessType),
|
|
1282
|
+
priceVisibility: listing.priceVisibility,
|
|
1283
|
+
price: listing.price,
|
|
1284
|
+
priceLabel: isPrivate ? "Sob consulta" : formatListingPrice(listing.price, "pt-BR", listing.currency ?? "BRL"),
|
|
1285
|
+
pricePeriod: listing.businessType === "rental" && !isPrivate && listing.price != null ? "/m\xEAs" : null,
|
|
1286
|
+
locationLabel: listingLocationLabel(listing.location || {}),
|
|
1287
|
+
propertyType: listing.property?.type ?? null,
|
|
1288
|
+
coverSrc: listing.coverImage?.src ?? null,
|
|
1289
|
+
coverAlt: listing.coverImage?.alt ?? listing.title,
|
|
1290
|
+
bedrooms: listing.property?.bedrooms ?? null,
|
|
1291
|
+
bathrooms: listing.property?.bathrooms ?? null,
|
|
1292
|
+
parkingSpaces: listing.property?.parkingSpaces ?? null,
|
|
1293
|
+
areaM2: area ?? null
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
// src/maps.ts
|
|
1298
|
+
function finite(value) {
|
|
1299
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
1300
|
+
}
|
|
1301
|
+
function listingCoordinates(listing) {
|
|
1302
|
+
const raw = listing?.location?.coordinates;
|
|
1303
|
+
const lat = finite(raw?.lat);
|
|
1304
|
+
const lng = finite(raw?.lng);
|
|
1305
|
+
if (lat == null || lng == null) return null;
|
|
1306
|
+
if (lat === 0 && lng === 0) return null;
|
|
1307
|
+
if (Math.abs(lat) > 90 || Math.abs(lng) > 180) return null;
|
|
1308
|
+
return { lat, lng };
|
|
1309
|
+
}
|
|
1310
|
+
function coordinateDecimals(value) {
|
|
1311
|
+
if (!Number.isFinite(value)) return 0;
|
|
1312
|
+
const text = Math.abs(value).toString();
|
|
1313
|
+
if (text.includes("e")) {
|
|
1314
|
+
const fixed = Math.abs(value).toFixed(12).replace(/0+$/, "");
|
|
1315
|
+
const dot2 = fixed.indexOf(".");
|
|
1316
|
+
return dot2 === -1 ? 0 : fixed.length - dot2 - 1;
|
|
1317
|
+
}
|
|
1318
|
+
const dot = text.indexOf(".");
|
|
1319
|
+
return dot === -1 ? 0 : text.length - dot - 1;
|
|
1320
|
+
}
|
|
1321
|
+
function roundTo(value, decimals) {
|
|
1322
|
+
const factor = 10 ** decimals;
|
|
1323
|
+
return Math.round(value * factor) / factor;
|
|
1324
|
+
}
|
|
1325
|
+
function coarsenCoordinates(coordinates, maxDecimals) {
|
|
1326
|
+
if (maxDecimals == null || !Number.isFinite(maxDecimals)) return coordinates;
|
|
1327
|
+
const limit = Math.max(0, Math.floor(maxDecimals));
|
|
1328
|
+
return {
|
|
1329
|
+
lat: coordinateDecimals(coordinates.lat) > limit ? roundTo(coordinates.lat, limit) : coordinates.lat,
|
|
1330
|
+
lng: coordinateDecimals(coordinates.lng) > limit ? roundTo(coordinates.lng, limit) : coordinates.lng
|
|
1331
|
+
};
|
|
1332
|
+
}
|
|
1333
|
+
function createTravelTimeCache(options = {}) {
|
|
1334
|
+
const maxEntries = Math.max(1, Math.floor(options.maxEntries ?? 200));
|
|
1335
|
+
const ttlMs = Math.max(0, options.ttlMs ?? 15 * 60 * 1e3);
|
|
1336
|
+
const entries = /* @__PURE__ */ new Map();
|
|
1337
|
+
return {
|
|
1338
|
+
get(key) {
|
|
1339
|
+
const hit = entries.get(key);
|
|
1340
|
+
if (!hit) return void 0;
|
|
1341
|
+
if (hit.expiresAt <= Date.now()) {
|
|
1342
|
+
entries.delete(key);
|
|
1343
|
+
return void 0;
|
|
1344
|
+
}
|
|
1345
|
+
entries.delete(key);
|
|
1346
|
+
entries.set(key, hit);
|
|
1347
|
+
return hit.value;
|
|
1348
|
+
},
|
|
1349
|
+
set(key, value) {
|
|
1350
|
+
entries.delete(key);
|
|
1351
|
+
entries.set(key, { value, expiresAt: Date.now() + ttlMs });
|
|
1352
|
+
while (entries.size > maxEntries) {
|
|
1353
|
+
const oldest = entries.keys().next().value;
|
|
1354
|
+
if (oldest === void 0) break;
|
|
1355
|
+
entries.delete(oldest);
|
|
1356
|
+
}
|
|
1357
|
+
},
|
|
1358
|
+
clear() {
|
|
1359
|
+
entries.clear();
|
|
1360
|
+
},
|
|
1361
|
+
get size() {
|
|
1362
|
+
return entries.size;
|
|
1363
|
+
}
|
|
1364
|
+
};
|
|
1365
|
+
}
|
|
1366
|
+
var defaultTravelTimeCache = createTravelTimeCache();
|
|
1367
|
+
|
|
1368
|
+
// src/map-search.ts
|
|
1369
|
+
var MAP_SEARCH_MAX_PAGE_SIZE = 100;
|
|
1370
|
+
var MAP_SEARCH_DEFAULT_PAGE_SIZE = 100;
|
|
1371
|
+
var MAP_SEARCH_MAX_PAGE = 1e4;
|
|
1372
|
+
var MAP_VIEWPORT_DEBOUNCE_MS = 400;
|
|
1373
|
+
var MAP_POLYGON_MAX_VERTICES = 64;
|
|
1374
|
+
function capMapPageSize(value) {
|
|
1375
|
+
if (value == null || !Number.isFinite(value) || value <= 0) {
|
|
1376
|
+
return MAP_SEARCH_DEFAULT_PAGE_SIZE;
|
|
1377
|
+
}
|
|
1378
|
+
return Math.min(MAP_SEARCH_MAX_PAGE_SIZE, Math.floor(value));
|
|
1379
|
+
}
|
|
1380
|
+
function capMapPage(value) {
|
|
1381
|
+
if (value == null || !Number.isFinite(value) || value <= 1) return 1;
|
|
1382
|
+
return Math.min(MAP_SEARCH_MAX_PAGE, Math.floor(value));
|
|
1383
|
+
}
|
|
1384
|
+
function finitePair(lat, lng) {
|
|
1385
|
+
if (typeof lat !== "number" || typeof lng !== "number") return null;
|
|
1386
|
+
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
|
|
1387
|
+
if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return null;
|
|
1388
|
+
return [lat, lng];
|
|
1389
|
+
}
|
|
1390
|
+
function isMapBounds(bounds) {
|
|
1391
|
+
if (!bounds) return false;
|
|
1392
|
+
const north = finitePair(bounds.north, bounds.east);
|
|
1393
|
+
const south = finitePair(bounds.south, bounds.west);
|
|
1394
|
+
if (!north || !south) return false;
|
|
1395
|
+
return bounds.north > bounds.south && bounds.east > bounds.west;
|
|
1396
|
+
}
|
|
1397
|
+
function isMapPolygon(polygon) {
|
|
1398
|
+
if (!Array.isArray(polygon)) return false;
|
|
1399
|
+
if (polygon.length < 3 || polygon.length > MAP_POLYGON_MAX_VERTICES + 1) {
|
|
1400
|
+
return false;
|
|
1401
|
+
}
|
|
1402
|
+
let unique = 0;
|
|
1403
|
+
let prev = null;
|
|
1404
|
+
for (const point of polygon) {
|
|
1405
|
+
if (!Array.isArray(point)) return false;
|
|
1406
|
+
const pair = finitePair(point[0], point[1]);
|
|
1407
|
+
if (!pair) return false;
|
|
1408
|
+
if (prev && prev[0] === pair[0] && prev[1] === pair[1]) continue;
|
|
1409
|
+
prev = pair;
|
|
1410
|
+
unique += 1;
|
|
1411
|
+
}
|
|
1412
|
+
if (unique >= 2 && polygon.length >= 2) {
|
|
1413
|
+
const first = finitePair(polygon[0]?.[0], polygon[0]?.[1]);
|
|
1414
|
+
const last = finitePair(
|
|
1415
|
+
polygon[polygon.length - 1]?.[0],
|
|
1416
|
+
polygon[polygon.length - 1]?.[1]
|
|
1417
|
+
);
|
|
1418
|
+
if (first && last && first[0] === last[0] && first[1] === last[1] && unique > 1) {
|
|
1419
|
+
unique -= 1;
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
return unique >= 3 && unique <= MAP_POLYGON_MAX_VERTICES;
|
|
1423
|
+
}
|
|
1424
|
+
function emptyMapSearchResult(pageSize = MAP_SEARCH_DEFAULT_PAGE_SIZE) {
|
|
1425
|
+
return {
|
|
1426
|
+
pins: [],
|
|
1427
|
+
cards: [],
|
|
1428
|
+
listings: [],
|
|
1429
|
+
page: 1,
|
|
1430
|
+
pageSize,
|
|
1431
|
+
total: 0,
|
|
1432
|
+
totalPages: 0
|
|
1433
|
+
};
|
|
1434
|
+
}
|
|
1435
|
+
function mapSearchPins(listings) {
|
|
1436
|
+
const pins = [];
|
|
1437
|
+
for (const listing of listings) {
|
|
1438
|
+
const coords = listingCoordinates(listing);
|
|
1439
|
+
if (!coords || !listing.id) continue;
|
|
1440
|
+
const src = listing.coverImage?.src;
|
|
1441
|
+
pins.push({
|
|
1442
|
+
id: listing.id,
|
|
1443
|
+
lat: coords.lat,
|
|
1444
|
+
lng: coords.lng,
|
|
1445
|
+
price: listing.price ?? null,
|
|
1446
|
+
coverImage: src ? src : null
|
|
1447
|
+
});
|
|
1448
|
+
}
|
|
1449
|
+
return pins;
|
|
1450
|
+
}
|
|
1451
|
+
function listingsResult(listings, meta, requestedPageSize) {
|
|
1452
|
+
return {
|
|
1453
|
+
pins: mapSearchPins(listings),
|
|
1454
|
+
cards: listings.map((listing) => toListingCardModel(listing)),
|
|
1455
|
+
listings,
|
|
1456
|
+
page: meta.page ?? 1,
|
|
1457
|
+
pageSize: meta.limit ?? requestedPageSize,
|
|
1458
|
+
total: meta.total ?? listings.length,
|
|
1459
|
+
totalPages: meta.totalPages ?? 0
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
function searchParams(area, options) {
|
|
1463
|
+
const params = {
|
|
1464
|
+
page: capMapPage(options.page),
|
|
1465
|
+
limit: capMapPageSize(options.pageSize)
|
|
1466
|
+
};
|
|
1467
|
+
if (options.q !== void 0) params.q = options.q;
|
|
1468
|
+
if (options.sort !== void 0) params.sort = options.sort;
|
|
1469
|
+
if (options.location !== void 0) params.location = options.location;
|
|
1470
|
+
if (options.filters) params.filters = options.filters;
|
|
1471
|
+
if (area.polygon) params.polygon = area.polygon;
|
|
1472
|
+
else if (area.bounds) params.bounds = area.bounds;
|
|
1473
|
+
return params;
|
|
1474
|
+
}
|
|
1475
|
+
async function runMapSearch(siteId, area, options) {
|
|
1476
|
+
const pageSize = capMapPageSize(options.pageSize);
|
|
1477
|
+
const result = await queryListings({
|
|
1478
|
+
siteId,
|
|
1479
|
+
params: searchParams(area, options),
|
|
1480
|
+
baseUrl: options.baseUrl,
|
|
1481
|
+
fetch: options.fetch,
|
|
1482
|
+
signal: options.signal,
|
|
1483
|
+
publishableKey: options.publishableKey,
|
|
1484
|
+
next: options.next
|
|
1485
|
+
});
|
|
1486
|
+
return listingsResult(result.listings ?? [], result, pageSize);
|
|
1487
|
+
}
|
|
1488
|
+
async function searchListingsInBounds(siteId, options) {
|
|
1489
|
+
if (!isMapBounds(options.bounds)) {
|
|
1490
|
+
throw new TypeError(
|
|
1491
|
+
"searchListingsInBounds: bounds must be a finite rectangle with north > south and east > west (no antimeridian)."
|
|
1492
|
+
);
|
|
1493
|
+
}
|
|
1494
|
+
return runMapSearch(siteId, { bounds: options.bounds }, options);
|
|
1495
|
+
}
|
|
1496
|
+
async function searchListingsInPolygon(siteId, options) {
|
|
1497
|
+
if (!isMapPolygon(options.polygon)) {
|
|
1498
|
+
throw new TypeError(
|
|
1499
|
+
`searchListingsInPolygon: polygon must be 3\u2013${MAP_POLYGON_MAX_VERTICES} finite [lat, lng] points.`
|
|
1500
|
+
);
|
|
1501
|
+
}
|
|
1502
|
+
return runMapSearch(siteId, { polygon: options.polygon }, options);
|
|
1503
|
+
}
|
|
1504
|
+
function clampZoom(zoom) {
|
|
1505
|
+
if (!Number.isFinite(zoom)) return 0;
|
|
1506
|
+
return Math.min(22, Math.max(0, zoom));
|
|
1507
|
+
}
|
|
1508
|
+
function mapClusterCellDegrees(zoom) {
|
|
1509
|
+
return 360 / 2 ** clampZoom(zoom) / 4;
|
|
1510
|
+
}
|
|
1511
|
+
function usablePin(pin) {
|
|
1512
|
+
return finitePair(pin.lat, pin.lng) !== null && !(pin.lat === 0 && pin.lng === 0);
|
|
1513
|
+
}
|
|
1514
|
+
function groupPrecision(group) {
|
|
1515
|
+
let min = 12;
|
|
1516
|
+
for (const pin of group) {
|
|
1517
|
+
min = Math.min(
|
|
1518
|
+
min,
|
|
1519
|
+
coordinateDecimals(pin.lat),
|
|
1520
|
+
coordinateDecimals(pin.lng)
|
|
1521
|
+
);
|
|
1522
|
+
}
|
|
1523
|
+
return min;
|
|
1524
|
+
}
|
|
1525
|
+
function multiCluster(key, group) {
|
|
1526
|
+
const lat = group.reduce((sum, pin) => sum + pin.lat, 0) / group.length;
|
|
1527
|
+
const lng = group.reduce((sum, pin) => sum + pin.lng, 0) / group.length;
|
|
1528
|
+
const center = coarsenCoordinates({ lat, lng }, groupPrecision(group));
|
|
1529
|
+
return {
|
|
1530
|
+
id: key,
|
|
1531
|
+
lat: center.lat,
|
|
1532
|
+
lng: center.lng,
|
|
1533
|
+
count: group.length,
|
|
1534
|
+
pinIds: group.map((pin) => pin.id),
|
|
1535
|
+
pin: null
|
|
1536
|
+
};
|
|
1537
|
+
}
|
|
1538
|
+
function singleCluster(pin) {
|
|
1539
|
+
return {
|
|
1540
|
+
id: pin.id,
|
|
1541
|
+
lat: pin.lat,
|
|
1542
|
+
lng: pin.lng,
|
|
1543
|
+
count: 1,
|
|
1544
|
+
pinIds: [pin.id],
|
|
1545
|
+
pin
|
|
1546
|
+
};
|
|
1547
|
+
}
|
|
1548
|
+
function clusterPins(pins, zoom) {
|
|
1549
|
+
if (pins.length === 0) return [];
|
|
1550
|
+
const cell = mapClusterCellDegrees(zoom);
|
|
1551
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1552
|
+
for (const pin of pins) {
|
|
1553
|
+
if (!usablePin(pin)) continue;
|
|
1554
|
+
const key = `${Math.floor(pin.lat / cell)}:${Math.floor(pin.lng / cell)}`;
|
|
1555
|
+
const list = groups.get(key);
|
|
1556
|
+
if (list) list.push(pin);
|
|
1557
|
+
else groups.set(key, [pin]);
|
|
1558
|
+
}
|
|
1559
|
+
const clusters = [];
|
|
1560
|
+
for (const [key, group] of groups) {
|
|
1561
|
+
const only = group[0];
|
|
1562
|
+
clusters.push(
|
|
1563
|
+
group.length === 1 && only ? singleCluster(only) : multiCluster(key, group)
|
|
1564
|
+
);
|
|
1565
|
+
}
|
|
1566
|
+
clusters.sort((a, b) => a.id.localeCompare(b.id));
|
|
1567
|
+
return clusters;
|
|
1568
|
+
}
|
|
1569
|
+
function describeArea(query) {
|
|
1570
|
+
if (query.polygon != null) {
|
|
1571
|
+
if (!isMapPolygon(query.polygon)) {
|
|
1572
|
+
return {
|
|
1573
|
+
kind: "invalid",
|
|
1574
|
+
message: `Map search polygon must be 3\u2013${MAP_POLYGON_MAX_VERTICES} [lat, lng] points.`
|
|
1575
|
+
};
|
|
1576
|
+
}
|
|
1577
|
+
return { kind: "polygon", polygon: query.polygon };
|
|
1578
|
+
}
|
|
1579
|
+
if (query.bounds != null) {
|
|
1580
|
+
if (!isMapBounds(query.bounds)) {
|
|
1581
|
+
return {
|
|
1582
|
+
kind: "invalid",
|
|
1583
|
+
message: "Map search bounds must be a finite rectangle with north > south and east > west."
|
|
1584
|
+
};
|
|
1585
|
+
}
|
|
1586
|
+
return { kind: "bounds", bounds: query.bounds };
|
|
1587
|
+
}
|
|
1588
|
+
return { kind: "empty" };
|
|
1589
|
+
}
|
|
1590
|
+
function isAbort(error, signal) {
|
|
1591
|
+
if (signal.aborted) return true;
|
|
1592
|
+
return error instanceof Error && error.name === "AbortError";
|
|
1593
|
+
}
|
|
1594
|
+
function asError(error) {
|
|
1595
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
1596
|
+
}
|
|
1597
|
+
function requestFromSubscription(query, signal) {
|
|
1598
|
+
const {
|
|
1599
|
+
siteId: _siteId,
|
|
1600
|
+
bounds: _bounds,
|
|
1601
|
+
polygon: _polygon,
|
|
1602
|
+
...request
|
|
1603
|
+
} = query;
|
|
1604
|
+
return { ...request, signal };
|
|
1605
|
+
}
|
|
1606
|
+
async function fetchArea(query, area, signal) {
|
|
1607
|
+
const request = requestFromSubscription(query, signal);
|
|
1608
|
+
if (area.kind === "polygon") {
|
|
1609
|
+
return searchListingsInPolygon(query.siteId, {
|
|
1610
|
+
...request,
|
|
1611
|
+
polygon: area.polygon
|
|
1612
|
+
});
|
|
1613
|
+
}
|
|
1614
|
+
return searchListingsInBounds(query.siteId, {
|
|
1615
|
+
...request,
|
|
1616
|
+
bounds: area.bounds
|
|
1617
|
+
});
|
|
1618
|
+
}
|
|
1619
|
+
function mapSearchSubscriptionKey(query) {
|
|
1620
|
+
return JSON.stringify({
|
|
1621
|
+
siteId: query.siteId,
|
|
1622
|
+
baseUrl: query.baseUrl ?? "",
|
|
1623
|
+
bounds: query.bounds ?? null,
|
|
1624
|
+
polygon: query.polygon ?? null,
|
|
1625
|
+
q: query.q ?? null,
|
|
1626
|
+
sort: query.sort ?? null,
|
|
1627
|
+
location: query.location ?? null,
|
|
1628
|
+
filters: query.filters ?? null,
|
|
1629
|
+
publishableKey: query.publishableKey ?? null,
|
|
1630
|
+
next: query.next ?? null,
|
|
1631
|
+
page: query.page ?? 1,
|
|
1632
|
+
pageSize: query.pageSize ?? MAP_SEARCH_DEFAULT_PAGE_SIZE
|
|
1633
|
+
});
|
|
1634
|
+
}
|
|
1635
|
+
function subscribeMapSearch(query, listener, options) {
|
|
1636
|
+
const area = describeArea(query);
|
|
1637
|
+
if (area.kind === "empty") {
|
|
1638
|
+
listener({ type: "empty" });
|
|
1639
|
+
return () => {
|
|
1640
|
+
};
|
|
1641
|
+
}
|
|
1642
|
+
if (area.kind === "invalid") {
|
|
1643
|
+
listener({ type: "error", error: new TypeError(area.message) });
|
|
1644
|
+
return () => {
|
|
1645
|
+
};
|
|
1646
|
+
}
|
|
1647
|
+
const controller = new AbortController();
|
|
1648
|
+
const debounceMs = options?.debounceMs ?? MAP_VIEWPORT_DEBOUNCE_MS;
|
|
1649
|
+
const timer = setTimeout(() => {
|
|
1650
|
+
listener({ type: "loading" });
|
|
1651
|
+
void fetchArea(query, area, controller.signal).then(
|
|
1652
|
+
(result) => {
|
|
1653
|
+
if (controller.signal.aborted) return;
|
|
1654
|
+
listener({ type: "ready", result });
|
|
1655
|
+
},
|
|
1656
|
+
(error) => {
|
|
1657
|
+
if (isAbort(error, controller.signal)) return;
|
|
1658
|
+
listener({ type: "error", error: asError(error) });
|
|
1659
|
+
}
|
|
1660
|
+
);
|
|
1661
|
+
}, debounceMs);
|
|
1662
|
+
return () => {
|
|
1663
|
+
clearTimeout(timer);
|
|
1664
|
+
controller.abort();
|
|
1665
|
+
};
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
// src/react/use-map-search.ts
|
|
1669
|
+
var IDLE = emptyMapSearchResult();
|
|
1670
|
+
function areaKey(options) {
|
|
1671
|
+
return JSON.stringify({
|
|
1672
|
+
search: mapSearchSubscriptionKey(options),
|
|
1673
|
+
enabled: options.enabled !== false,
|
|
1674
|
+
debounceMs: options.debounceMs ?? MAP_VIEWPORT_DEBOUNCE_MS
|
|
1675
|
+
});
|
|
1676
|
+
}
|
|
1677
|
+
function useMapSearch(options) {
|
|
1678
|
+
const [result, setResult] = useState2(IDLE);
|
|
1679
|
+
const [loading, setLoading] = useState2(false);
|
|
1680
|
+
const [error, setError] = useState2(null);
|
|
1681
|
+
const optionsRef = useRef2(options);
|
|
1682
|
+
optionsRef.current = options;
|
|
1683
|
+
const key = areaKey(options);
|
|
1684
|
+
const zoom = options.zoom ?? 14;
|
|
1685
|
+
useEffect2(() => {
|
|
1686
|
+
const current = optionsRef.current;
|
|
1687
|
+
if (current.enabled === false) {
|
|
1688
|
+
setLoading(false);
|
|
1689
|
+
return;
|
|
1690
|
+
}
|
|
1691
|
+
return subscribeMapSearch(
|
|
1692
|
+
current,
|
|
1693
|
+
(event) => {
|
|
1694
|
+
if (event.type === "empty") {
|
|
1695
|
+
setResult(emptyMapSearchResult(current.pageSize));
|
|
1696
|
+
setLoading(false);
|
|
1697
|
+
setError(null);
|
|
1698
|
+
return;
|
|
1699
|
+
}
|
|
1700
|
+
if (event.type === "loading") {
|
|
1701
|
+
setLoading(true);
|
|
1702
|
+
setError(null);
|
|
1703
|
+
return;
|
|
1704
|
+
}
|
|
1705
|
+
if (event.type === "error") {
|
|
1706
|
+
setLoading(false);
|
|
1707
|
+
setError(event.error);
|
|
1708
|
+
return;
|
|
1709
|
+
}
|
|
1710
|
+
setResult(event.result);
|
|
1711
|
+
setLoading(false);
|
|
1712
|
+
setError(null);
|
|
1713
|
+
},
|
|
1714
|
+
{ debounceMs: current.debounceMs }
|
|
1715
|
+
);
|
|
1716
|
+
}, [key]);
|
|
1717
|
+
const clusters = useMemo2(
|
|
1718
|
+
() => clusterPins(result.pins, zoom),
|
|
1719
|
+
[result.pins, zoom]
|
|
1720
|
+
);
|
|
1721
|
+
return { ...result, clusters, loading, error };
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
// src/react/use-public-photo-search.ts
|
|
1725
|
+
import { useEffect as useEffect3, useMemo as useMemo3, useRef as useRef3, useState as useState3 } from "react";
|
|
1726
|
+
|
|
1116
1727
|
// src/fetchers-photo-search.ts
|
|
1117
1728
|
var PHOTO_SEARCH_MIN_QUERY_LENGTH = 3;
|
|
1118
1729
|
var EMPTY_RESULT = {
|
|
@@ -1226,17 +1837,17 @@ function usePublicPhotoSearch(options) {
|
|
|
1226
1837
|
} = options;
|
|
1227
1838
|
const query = (options.query ?? "").trim();
|
|
1228
1839
|
const searchable = enabled && query.length >= PHOTO_SEARCH_MIN_QUERY_LENGTH;
|
|
1229
|
-
const siteIdRef =
|
|
1840
|
+
const siteIdRef = useRef3(siteId);
|
|
1230
1841
|
siteIdRef.current = siteId;
|
|
1231
1842
|
const siteIdToken = typeof siteId === "string" ? siteId : null;
|
|
1232
|
-
const fetchRef =
|
|
1843
|
+
const fetchRef = useRef3(fetchImpl);
|
|
1233
1844
|
fetchRef.current = fetchImpl;
|
|
1234
|
-
const requestRef =
|
|
1235
|
-
const [result, setResult] =
|
|
1236
|
-
const [answered, setAnswered] =
|
|
1237
|
-
const [loading, setLoading] =
|
|
1238
|
-
const [error, setError] =
|
|
1239
|
-
|
|
1845
|
+
const requestRef = useRef3(0);
|
|
1846
|
+
const [result, setResult] = useState3(EMPTY);
|
|
1847
|
+
const [answered, setAnswered] = useState3("");
|
|
1848
|
+
const [loading, setLoading] = useState3(searchable);
|
|
1849
|
+
const [error, setError] = useState3(null);
|
|
1850
|
+
useEffect3(() => {
|
|
1240
1851
|
const requestId = ++requestRef.current;
|
|
1241
1852
|
if (!searchable) {
|
|
1242
1853
|
setResult(EMPTY);
|
|
@@ -1280,7 +1891,7 @@ function usePublicPhotoSearch(options) {
|
|
|
1280
1891
|
if (timer != null) clearTimeout(timer);
|
|
1281
1892
|
};
|
|
1282
1893
|
}, [searchable, query, limit, page, baseUrl, siteIdToken, debounceMs]);
|
|
1283
|
-
const listings =
|
|
1894
|
+
const listings = useMemo3(
|
|
1284
1895
|
() => applyMatchedPhotoCover(
|
|
1285
1896
|
result.items.map((item) => item.listing),
|
|
1286
1897
|
result.items
|
|
@@ -1301,6 +1912,7 @@ function usePublicPhotoSearch(options) {
|
|
|
1301
1912
|
}
|
|
1302
1913
|
export {
|
|
1303
1914
|
PHOTO_SEARCH_DEBOUNCE_MS,
|
|
1915
|
+
useMapSearch,
|
|
1304
1916
|
usePublicPhotoSearch,
|
|
1305
1917
|
usePublicSearch
|
|
1306
1918
|
};
|