@garagem-ai/site-sdk 0.6.1 → 0.8.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/react.mjs CHANGED
@@ -4,6 +4,90 @@
4
4
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
5
5
  import { usePathname, useRouter } from "next/navigation";
6
6
 
7
+ // src/internal/sdk-http.ts
8
+ var PUBLISHABLE_KEY_HEADER = "X-Garagem-Publishable-Key";
9
+ function publishableKeyHeaders(publishableKey) {
10
+ const key = publishableKey?.trim();
11
+ if (!key) return {};
12
+ return { [PUBLISHABLE_KEY_HEADER]: key };
13
+ }
14
+ function withPublishableKeyHeader(init, publishableKey) {
15
+ const extra = publishableKeyHeaders(publishableKey);
16
+ if (Object.keys(extra).length === 0) return init;
17
+ const current = init.headers;
18
+ const base = plainHeaders(current);
19
+ return { ...init, headers: { ...base, ...extra } };
20
+ }
21
+ function plainHeaders(headers) {
22
+ const out = {};
23
+ if (!headers) return out;
24
+ if (typeof Headers !== "undefined" && headers instanceof Headers) {
25
+ headers.forEach((value, name) => {
26
+ out[name] = value;
27
+ });
28
+ return out;
29
+ }
30
+ if (Array.isArray(headers)) {
31
+ for (const pair of headers) {
32
+ out[String(pair[0])] = String(pair[1]);
33
+ }
34
+ return out;
35
+ }
36
+ for (const [name, value] of Object.entries(
37
+ headers
38
+ )) {
39
+ if (typeof value === "string") out[name] = value;
40
+ }
41
+ return out;
42
+ }
43
+ function finiteNonNegative(value) {
44
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
45
+ return value;
46
+ }
47
+ if (typeof value === "string" && value.trim()) {
48
+ const parsed = Number(value);
49
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed;
50
+ }
51
+ return null;
52
+ }
53
+ function parseSdkErrorBody(text) {
54
+ const raw = text ? text.slice(0, 200) : "";
55
+ if (!text) {
56
+ return { reason: null, retryAfterSeconds: null, summary: "" };
57
+ }
58
+ try {
59
+ const body = JSON.parse(text);
60
+ if (!body || typeof body !== "object") {
61
+ return { reason: null, retryAfterSeconds: null, summary: raw };
62
+ }
63
+ const record = body;
64
+ const reason = typeof record.reason === "string" && record.reason ? record.reason : null;
65
+ const retryAfterSeconds = finiteNonNegative(
66
+ record.retryAfterSeconds ?? record.retryAfter
67
+ );
68
+ const errorText = typeof record.error === "string" && record.error ? record.error : raw;
69
+ return {
70
+ reason,
71
+ retryAfterSeconds,
72
+ summary: errorText.slice(0, 200)
73
+ };
74
+ } catch {
75
+ return { reason: null, retryAfterSeconds: null, summary: raw };
76
+ }
77
+ }
78
+ function retryAfterFromResponse(response, bodySeconds, nowMs = Date.now()) {
79
+ const header = response.headers.get("Retry-After")?.trim();
80
+ if (header) {
81
+ const delta = finiteNonNegative(header);
82
+ if (delta != null) return delta;
83
+ const at = Date.parse(header);
84
+ if (Number.isFinite(at)) {
85
+ return Math.max(0, Math.ceil((at - nowMs) / 1e3));
86
+ }
87
+ }
88
+ return bodySeconds;
89
+ }
90
+
7
91
  // src/internal/url.ts
8
92
  var DEFAULT_BASE_URL = "https://app.garagem.ai";
9
93
  function normalizeBaseUrl(baseUrl) {
@@ -22,27 +106,50 @@ async function coerceSiteId(siteId) {
22
106
  }
23
107
 
24
108
  // src/fetchers.ts
25
- async function callJson(url, init, fetchImpl) {
26
- const response = await fetchImpl(url, init);
109
+ async function callJson(url, init, fetchImpl, publishableKey) {
110
+ const response = await fetchImpl(
111
+ url,
112
+ withPublishableKeyHeader(init, publishableKey)
113
+ );
27
114
  if (!response.ok) {
28
- const text = await response.text().catch(() => "");
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
- );
115
+ throw await readGaragemSdkError(response, url);
33
116
  }
34
117
  return await response.json();
35
118
  }
36
119
  var GaragemSdkError = class extends Error {
37
120
  status;
38
121
  url;
122
+ /** Machine reason from the JSON body (`invalid_publishable_key`, `rate_limited`, …). */
123
+ reason;
124
+ /**
125
+ * Seconds to wait before retrying. Set on HTTP 429 from `Retry-After`
126
+ * or the body's `retryAfterSeconds`. `null` when the response has neither.
127
+ */
128
+ retryAfter;
39
129
  constructor(message, info) {
40
130
  super(message);
41
131
  this.name = "GaragemSdkError";
42
132
  this.status = info.status;
43
133
  this.url = info.url;
134
+ this.reason = info.reason ?? null;
135
+ this.retryAfter = info.retryAfter ?? null;
44
136
  }
45
137
  };
138
+ async function readGaragemSdkError(response, url) {
139
+ const text = await response.text().catch(() => "");
140
+ const parsed = parseSdkErrorBody(text);
141
+ const retryAfter = response.status === 429 ? retryAfterFromResponse(response, parsed.retryAfterSeconds) : parsed.retryAfterSeconds;
142
+ const detail = parsed.summary;
143
+ return new GaragemSdkError(
144
+ `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${detail ? ` \u2014 ${detail}` : ""}`,
145
+ {
146
+ status: response.status,
147
+ url,
148
+ reason: parsed.reason,
149
+ retryAfter
150
+ }
151
+ );
152
+ }
46
153
  async function getSearchUi(options) {
47
154
  const { baseUrl, fetch: fetchImpl, next } = options;
48
155
  const siteId = await coerceSiteId(options.siteId);
@@ -51,7 +158,8 @@ async function getSearchUi(options) {
51
158
  return callJson(
52
159
  url,
53
160
  { method: "GET", headers: { Accept: "application/json" }, next },
54
- fetchImpl ?? fetch
161
+ fetchImpl ?? fetch,
162
+ options.publishableKey
55
163
  );
56
164
  }
57
165
  async function queryListings(options) {
@@ -70,7 +178,8 @@ async function queryListings(options) {
70
178
  body: JSON.stringify(params ?? {}),
71
179
  next
72
180
  },
73
- fetchImpl ?? fetch
181
+ fetchImpl ?? fetch,
182
+ options.publishableKey
74
183
  );
75
184
  }
76
185
 
@@ -808,7 +917,13 @@ function currentHref(pathname, search) {
808
917
  return search ? `${pathname}?${search}` : pathname;
809
918
  }
810
919
  function usePublicSearch(options) {
811
- const { siteId, baseUrl, initial, search: searchFromServer = "" } = options;
920
+ const {
921
+ siteId,
922
+ baseUrl,
923
+ publishableKey,
924
+ initial,
925
+ search: searchFromServer = ""
926
+ } = options;
812
927
  const router = useRouter();
813
928
  const pathname = usePathname() || "/imoveis";
814
929
  const search = searchFromServer;
@@ -897,13 +1012,23 @@ function usePublicSearch(options) {
897
1012
  }
898
1013
  async function loadSchema() {
899
1014
  try {
900
- const nextSchema = await getSearchUi({ siteId: id, baseUrl });
1015
+ const nextSchema = await getSearchUi({
1016
+ siteId: id,
1017
+ baseUrl,
1018
+ publishableKey
1019
+ });
901
1020
  if (!active) return;
902
1021
  let locations = null;
903
1022
  if (nextSchema.locationsPath.startsWith("/")) {
904
1023
  try {
905
1024
  const response = await fetch(
906
- `${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`
1025
+ `${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`,
1026
+ {
1027
+ headers: {
1028
+ Accept: "application/json",
1029
+ ...publishableKeyHeaders(publishableKey)
1030
+ }
1031
+ }
907
1032
  );
908
1033
  if (response.ok) {
909
1034
  locations = await response.json();
@@ -937,7 +1062,7 @@ function usePublicSearch(options) {
937
1062
  return () => {
938
1063
  active = false;
939
1064
  };
940
- }, [baseUrl, catalogId]);
1065
+ }, [baseUrl, catalogId, publishableKey]);
941
1066
  useEffect(() => {
942
1067
  if (!schema || !catalogId) return;
943
1068
  const currentSchema = schema;
@@ -960,6 +1085,7 @@ function usePublicSearch(options) {
960
1085
  const response = await queryListings({
961
1086
  siteId: id,
962
1087
  baseUrl,
1088
+ publishableKey,
963
1089
  params: buildQueryListingsParams(
964
1090
  pathFilters,
965
1091
  applied,
@@ -996,7 +1122,7 @@ function usePublicSearch(options) {
996
1122
  return () => {
997
1123
  active = false;
998
1124
  };
999
- }, [pathname, search, baseUrl, schema, catalogId]);
1125
+ }, [pathname, search, baseUrl, schema, catalogId, publishableKey]);
1000
1126
  const go = useCallback(
1001
1127
  (href) => {
1002
1128
  if (href && href !== currentHref(pathname, search)) router.push(href);
@@ -1109,7 +1235,199 @@ function usePublicSearch(options) {
1109
1235
  locationNames
1110
1236
  };
1111
1237
  }
1238
+
1239
+ // src/react/use-public-photo-search.ts
1240
+ import { useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2, useState as useState2 } from "react";
1241
+
1242
+ // src/fetchers-photo-search.ts
1243
+ var PHOTO_SEARCH_MIN_QUERY_LENGTH = 3;
1244
+ var EMPTY_RESULT = {
1245
+ available: true,
1246
+ items: [],
1247
+ total: 0,
1248
+ page: 1,
1249
+ limit: 12
1250
+ };
1251
+ function positiveInt(value) {
1252
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 1) {
1253
+ return null;
1254
+ }
1255
+ return Math.floor(value);
1256
+ }
1257
+ function photoSearchUrl(siteId, params, baseUrl) {
1258
+ const search = new URLSearchParams();
1259
+ search.set("q", params.q.trim());
1260
+ const limit = positiveInt(params.limit);
1261
+ if (limit != null) search.set("limit", String(limit));
1262
+ const page = positiveInt(params.page);
1263
+ if (page != null) search.set("page", String(page));
1264
+ return `${normalizeBaseUrl(baseUrl)}/api/sites/${encodeURIComponent(
1265
+ siteId
1266
+ )}/search/photos?${search.toString()}`;
1267
+ }
1268
+ async function searchListingPhotos(siteId, params, options = {}) {
1269
+ const q = (params?.q ?? "").trim();
1270
+ const limit = positiveInt(params?.limit) ?? EMPTY_RESULT.limit;
1271
+ if (q.length < PHOTO_SEARCH_MIN_QUERY_LENGTH) {
1272
+ return { ...EMPTY_RESULT, limit, page: positiveInt(params?.page) ?? 1 };
1273
+ }
1274
+ const resolvedSiteId = await coerceSiteId(siteId);
1275
+ const url = photoSearchUrl(resolvedSiteId, { ...params, q }, options.baseUrl);
1276
+ const data = await callJson(
1277
+ url,
1278
+ {
1279
+ method: "GET",
1280
+ headers: { Accept: "application/json" },
1281
+ next: options.next
1282
+ },
1283
+ options.fetch ?? fetch
1284
+ );
1285
+ const items = Array.isArray(data.items) ? data.items : [];
1286
+ return {
1287
+ available: data.available !== false,
1288
+ items,
1289
+ total: typeof data.total === "number" ? data.total : items.length,
1290
+ page: typeof data.page === "number" ? data.page : positiveInt(params.page) ?? 1,
1291
+ limit: typeof data.limit === "number" ? data.limit : limit
1292
+ };
1293
+ }
1294
+
1295
+ // src/photo-search-cover.ts
1296
+ var MATCHED_PHOTO_COVER_MAX_DISTANCE = 0.4;
1297
+ function resolveMatchedCoverPhoto(photo, maxDistance = MATCHED_PHOTO_COVER_MAX_DISTANCE) {
1298
+ if (!photo || !photo.src) return null;
1299
+ if (photo.distance == null) return photo;
1300
+ if (!Number.isFinite(photo.distance)) return null;
1301
+ return photo.distance <= maxDistance ? photo : null;
1302
+ }
1303
+ function itemsOf(photoResults) {
1304
+ if (!photoResults) return [];
1305
+ return Array.isArray(photoResults) ? photoResults : photoResults.items ?? [];
1306
+ }
1307
+ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
1308
+ const maxDistance = options.maxDistance ?? MATCHED_PHOTO_COVER_MAX_DISTANCE;
1309
+ const photoByListingId = /* @__PURE__ */ new Map();
1310
+ for (const item of itemsOf(photoResults)) {
1311
+ const id = item?.listing?.id;
1312
+ if (!id || photoByListingId.has(id)) continue;
1313
+ const photo = resolveMatchedCoverPhoto(item.matchedPhoto, maxDistance);
1314
+ if (photo) photoByListingId.set(id, photo);
1315
+ }
1316
+ return cards.map((card) => {
1317
+ const photo = photoByListingId.get(card.id) ?? null;
1318
+ if (!photo) return { ...card, matchedPhoto: null };
1319
+ return {
1320
+ ...card,
1321
+ coverImage: {
1322
+ src: photo.src,
1323
+ alt: photo.alt || card.coverImage?.alt || card.title
1324
+ },
1325
+ matchedPhoto: photo
1326
+ };
1327
+ });
1328
+ }
1329
+
1330
+ // src/react/use-public-photo-search.ts
1331
+ var PHOTO_SEARCH_DEBOUNCE_MS = 400;
1332
+ var EMPTY = {
1333
+ available: true,
1334
+ items: [],
1335
+ total: 0,
1336
+ page: 1,
1337
+ limit: 12
1338
+ };
1339
+ async function resolveSiteIdInput2(siteId) {
1340
+ const value = typeof siteId === "function" ? siteId() : siteId;
1341
+ return coerceSiteId(value);
1342
+ }
1343
+ function usePublicPhotoSearch(options) {
1344
+ const {
1345
+ siteId,
1346
+ baseUrl,
1347
+ limit,
1348
+ page,
1349
+ enabled = true,
1350
+ debounceMs = PHOTO_SEARCH_DEBOUNCE_MS,
1351
+ fetch: fetchImpl
1352
+ } = options;
1353
+ const query = (options.query ?? "").trim();
1354
+ const searchable = enabled && query.length >= PHOTO_SEARCH_MIN_QUERY_LENGTH;
1355
+ const siteIdRef = useRef2(siteId);
1356
+ siteIdRef.current = siteId;
1357
+ const siteIdToken = typeof siteId === "string" ? siteId : null;
1358
+ const fetchRef = useRef2(fetchImpl);
1359
+ fetchRef.current = fetchImpl;
1360
+ const requestRef = useRef2(0);
1361
+ const [result, setResult] = useState2(EMPTY);
1362
+ const [answered, setAnswered] = useState2("");
1363
+ const [loading, setLoading] = useState2(searchable);
1364
+ const [error, setError] = useState2(null);
1365
+ useEffect2(() => {
1366
+ const requestId = ++requestRef.current;
1367
+ if (!searchable) {
1368
+ setResult(EMPTY);
1369
+ setAnswered("");
1370
+ setLoading(false);
1371
+ setError(null);
1372
+ return;
1373
+ }
1374
+ setLoading(true);
1375
+ let active = true;
1376
+ let timer = null;
1377
+ const run = () => {
1378
+ void (async () => {
1379
+ try {
1380
+ const id = await resolveSiteIdInput2(siteIdRef.current);
1381
+ const next = await searchListingPhotos(
1382
+ id,
1383
+ { q: query, limit, page },
1384
+ { baseUrl, fetch: fetchRef.current }
1385
+ );
1386
+ if (!active || requestId !== requestRef.current) return;
1387
+ setResult(next);
1388
+ setAnswered(query);
1389
+ setError(null);
1390
+ } catch (caught) {
1391
+ if (!active || requestId !== requestRef.current) return;
1392
+ setResult(EMPTY);
1393
+ setAnswered(query);
1394
+ setError(
1395
+ caught instanceof Error ? caught : new Error(String(caught))
1396
+ );
1397
+ } finally {
1398
+ if (active && requestId === requestRef.current) setLoading(false);
1399
+ }
1400
+ })();
1401
+ };
1402
+ if (debounceMs <= 0) run();
1403
+ else timer = setTimeout(run, debounceMs);
1404
+ return () => {
1405
+ active = false;
1406
+ if (timer != null) clearTimeout(timer);
1407
+ };
1408
+ }, [searchable, query, limit, page, baseUrl, siteIdToken, debounceMs]);
1409
+ const listings = useMemo2(
1410
+ () => applyMatchedPhotoCover(
1411
+ result.items.map((item) => item.listing),
1412
+ result.items
1413
+ ),
1414
+ [result.items]
1415
+ );
1416
+ return {
1417
+ available: result.available,
1418
+ items: result.items,
1419
+ listings,
1420
+ total: result.total,
1421
+ page: result.page,
1422
+ limit: result.limit,
1423
+ loading,
1424
+ error,
1425
+ query: answered
1426
+ };
1427
+ }
1112
1428
  export {
1429
+ PHOTO_SEARCH_DEBOUNCE_MS,
1430
+ usePublicPhotoSearch,
1113
1431
  usePublicSearch
1114
1432
  };
1115
1433
  //# sourceMappingURL=react.mjs.map