@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.
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Headless pt-BR labels for the market-data blocks. Every helper returns
3
+ * `null` when there is nothing to say (unavailable, missing numbers), so a
4
+ * component can `label && <p>{label}</p>` without re-checking `available`.
5
+ */
6
+ import type { ListingMarketPosition, MarketPriceBand } from "./types-market";
7
+
8
+ /**
9
+ * "8% abaixo da mediana do bairro" / "12% acima da mediana do bairro" /
10
+ * "Na mediana do bairro". `null` when the position is unavailable.
11
+ */
12
+ export function marketPositionLabel(
13
+ position:
14
+ | Pick<ListingMarketPosition, "available" | "percentVsMedian">
15
+ | null
16
+ | undefined
17
+ ): string | null {
18
+ if (!position?.available) return null;
19
+ const percent = position.percentVsMedian;
20
+ if (percent == null || !Number.isFinite(percent)) return null;
21
+ const rounded = Math.round(percent);
22
+ if (rounded === 0) return "Na mediana do bairro";
23
+ const magnitude = Math.abs(rounded);
24
+ return rounded < 0
25
+ ? `${magnitude}% abaixo da mediana do bairro`
26
+ : `${magnitude}% acima da mediana do bairro`;
27
+ }
28
+
29
+ const BAND_LABELS: Record<MarketPriceBand, string> = {
30
+ below_range: "Abaixo da faixa do bairro",
31
+ lower_range: "Na faixa do bairro, abaixo da mediana",
32
+ upper_range: "Na faixa do bairro, acima da mediana",
33
+ above_range: "Acima da faixa do bairro",
34
+ };
35
+
36
+ /**
37
+ * Quartile band copy. Accepts the band itself or a position; `null` when
38
+ * the band is missing or the position is unavailable.
39
+ */
40
+ export function priceBandLabel(
41
+ input:
42
+ | MarketPriceBand
43
+ | Pick<ListingMarketPosition, "available" | "band">
44
+ | null
45
+ | undefined
46
+ ): string | null {
47
+ if (!input) return null;
48
+ if (typeof input === "string") return BAND_LABELS[input] ?? null;
49
+ if (!input.available || !input.band) return null;
50
+ return BAND_LABELS[input.band] ?? null;
51
+ }
@@ -0,0 +1,90 @@
1
+ import type { Listing } from "./types";
2
+ import type {
3
+ ListingWithMatchedPhoto,
4
+ MatchedListingPhoto,
5
+ PhotoSearchItem,
6
+ PhotoSearchResult,
7
+ } from "./types-photo-search";
8
+
9
+ /**
10
+ * Largest vector distance a photo may have and still replace the cover.
11
+ * Mirrors the CRM "Foto que combina com a busca" threshold
12
+ * (`MATCHED_PHOTO_COVER_MAX_DISTANCE` in apps/foundation); keyword matches
13
+ * (`distance: null`) are exact caption / room-type matches and always win.
14
+ */
15
+ export const MATCHED_PHOTO_COVER_MAX_DISTANCE = 0.4;
16
+
17
+ export interface ApplyMatchedPhotoCoverOptions {
18
+ /** Override {@link MATCHED_PHOTO_COVER_MAX_DISTANCE}. `Infinity` accepts every match. */
19
+ maxDistance?: number;
20
+ }
21
+
22
+ /**
23
+ * The photo that replaces a card cover, or `null` to keep the card's own
24
+ * cover: keyword matches as-is, vector matches only within `maxDistance`.
25
+ */
26
+ export function resolveMatchedCoverPhoto(
27
+ photo: MatchedListingPhoto | null | undefined,
28
+ maxDistance: number = MATCHED_PHOTO_COVER_MAX_DISTANCE
29
+ ): MatchedListingPhoto | null {
30
+ if (!photo || !photo.src) return null;
31
+ if (photo.distance == null) return photo;
32
+ if (!Number.isFinite(photo.distance)) return null;
33
+ return photo.distance <= maxDistance ? photo : null;
34
+ }
35
+
36
+ function itemsOf(
37
+ photoResults:
38
+ | PhotoSearchResult
39
+ | ReadonlyArray<PhotoSearchItem>
40
+ | null
41
+ | undefined
42
+ ): ReadonlyArray<PhotoSearchItem> {
43
+ if (!photoResults) return [];
44
+ return Array.isArray(photoResults)
45
+ ? photoResults
46
+ : ((photoResults as PhotoSearchResult).items ?? []);
47
+ }
48
+
49
+ /**
50
+ * Headless mirror of the CRM cover switch: for every card whose listing has
51
+ * a photo-search match, swap `coverImage` for the matched photo and attach
52
+ * it as `matchedPhoto`. Cards without a match (or whose match is too far)
53
+ * keep their cover with `matchedPhoto: null`. Order is preserved — pass
54
+ * `result.items.map((item) => item.listing)` to render the photo-search
55
+ * page nearest-first, or the regular search page to only swap covers.
56
+ *
57
+ * @example
58
+ * const cards = applyMatchedPhotoCover(search.listings, photos.items);
59
+ * cards.map((card) => <Card model={toListingCardModel(card)} badge={card.matchedPhoto} />)
60
+ */
61
+ export function applyMatchedPhotoCover<T extends Listing>(
62
+ cards: ReadonlyArray<T>,
63
+ photoResults:
64
+ | PhotoSearchResult
65
+ | ReadonlyArray<PhotoSearchItem>
66
+ | null
67
+ | undefined,
68
+ options: ApplyMatchedPhotoCoverOptions = {}
69
+ ): Array<T & ListingWithMatchedPhoto> {
70
+ const maxDistance = options.maxDistance ?? MATCHED_PHOTO_COVER_MAX_DISTANCE;
71
+ const photoByListingId = new Map<string, MatchedListingPhoto>();
72
+ for (const item of itemsOf(photoResults)) {
73
+ const id = item?.listing?.id;
74
+ if (!id || photoByListingId.has(id)) continue;
75
+ const photo = resolveMatchedCoverPhoto(item.matchedPhoto, maxDistance);
76
+ if (photo) photoByListingId.set(id, photo);
77
+ }
78
+ return cards.map((card) => {
79
+ const photo = photoByListingId.get(card.id) ?? null;
80
+ if (!photo) return { ...card, matchedPhoto: null };
81
+ return {
82
+ ...card,
83
+ coverImage: {
84
+ src: photo.src,
85
+ alt: photo.alt || card.coverImage?.alt || card.title,
86
+ },
87
+ matchedPhoto: photo,
88
+ };
89
+ });
90
+ }
@@ -7,3 +7,11 @@ export type {
7
7
  SiteIdInput,
8
8
  UsePublicSearchOptions,
9
9
  } from "./types";
10
+
11
+ // --- Photo search ("busca pelo que as fotos mostram") ----------------------
12
+ export {
13
+ PHOTO_SEARCH_DEBOUNCE_MS,
14
+ usePublicPhotoSearch,
15
+ type PublicPhotoSearchState,
16
+ type UsePublicPhotoSearchOptions,
17
+ } from "./use-public-photo-search";
@@ -24,6 +24,11 @@ export type PublicSearchSnapshot = {
24
24
  export type UsePublicSearchOptions = {
25
25
  siteId: SiteIdInput;
26
26
  baseUrl?: string;
27
+ /**
28
+ * Site publishable key (`pk_live_…`). Sent on schema, location, and
29
+ * listing requests. Not a secret. Omit it to stay on the anonymous budget.
30
+ */
31
+ publishableKey?: string;
27
32
  /**
28
33
  * Query string without `?`, from the server page's `searchParams`.
29
34
  * The hook must not call Next's search-params hook: that suspends the
@@ -0,0 +1,165 @@
1
+ "use client";
2
+
3
+ import { useEffect, useMemo, useRef, useState } from "react";
4
+
5
+ import type { FetchLike } from "../fetchers";
6
+ import {
7
+ PHOTO_SEARCH_MIN_QUERY_LENGTH,
8
+ searchListingPhotos,
9
+ } from "../fetchers-photo-search";
10
+ import { coerceSiteId } from "../internal/url";
11
+ import { applyMatchedPhotoCover } from "../photo-search-cover";
12
+ import type {
13
+ ListingWithMatchedPhoto,
14
+ PhotoSearchItem,
15
+ PhotoSearchResult,
16
+ } from "../types-photo-search";
17
+ import type { SiteIdInput } from "./types";
18
+
19
+ /** Same debounce as the CRM "Foto que combina com a busca" evidence lane. */
20
+ export const PHOTO_SEARCH_DEBOUNCE_MS = 400;
21
+
22
+ export type UsePublicPhotoSearchOptions = {
23
+ siteId: SiteIdInput;
24
+ baseUrl?: string;
25
+ /**
26
+ * The text to search by (usually the main search box). The hook trims it,
27
+ * debounces requests and ignores responses that arrive out of order.
28
+ */
29
+ query: string;
30
+ /** Listings per page (API default 12, cap 24). */
31
+ limit?: number;
32
+ /** 1-based page. */
33
+ page?: number;
34
+ /** `false` pauses the hook and clears its results (e.g. a hidden panel). */
35
+ enabled?: boolean;
36
+ /** Milliseconds to wait after the last `query` change. Default 400. */
37
+ debounceMs?: number;
38
+ /** Override the fetch implementation (testing, retries). */
39
+ fetch?: FetchLike;
40
+ };
41
+
42
+ export type PublicPhotoSearchState = {
43
+ /** `false` once the API says the tenant has no photo search: hide the UI. */
44
+ available: boolean;
45
+ /** Nearest-first matches, each with its card and matched photo. */
46
+ items: PhotoSearchItem[];
47
+ /** `items` as cards with the matched photo already applied as cover. */
48
+ listings: ListingWithMatchedPhoto[];
49
+ total: number;
50
+ page: number;
51
+ limit: number;
52
+ /** A request is in flight (or scheduled by the debounce). */
53
+ loading: boolean;
54
+ error: Error | null;
55
+ /** The trimmed query the current `items` answer (`""` before the first result). */
56
+ query: string;
57
+ };
58
+
59
+ const EMPTY: PhotoSearchResult = {
60
+ available: true,
61
+ items: [],
62
+ total: 0,
63
+ page: 1,
64
+ limit: 12,
65
+ };
66
+
67
+ async function resolveSiteIdInput(siteId: SiteIdInput): Promise<string> {
68
+ const value = typeof siteId === "function" ? siteId() : siteId;
69
+ return coerceSiteId(value);
70
+ }
71
+
72
+ export function usePublicPhotoSearch(
73
+ options: UsePublicPhotoSearchOptions
74
+ ): PublicPhotoSearchState {
75
+ const {
76
+ siteId,
77
+ baseUrl,
78
+ limit,
79
+ page,
80
+ enabled = true,
81
+ debounceMs = PHOTO_SEARCH_DEBOUNCE_MS,
82
+ fetch: fetchImpl,
83
+ } = options;
84
+ const query = (options.query ?? "").trim();
85
+ const searchable = enabled && query.length >= PHOTO_SEARCH_MIN_QUERY_LENGTH;
86
+
87
+ const siteIdRef = useRef(siteId);
88
+ siteIdRef.current = siteId;
89
+ const siteIdToken = typeof siteId === "string" ? siteId : null;
90
+ const fetchRef = useRef(fetchImpl);
91
+ fetchRef.current = fetchImpl;
92
+ const requestRef = useRef(0);
93
+
94
+ const [result, setResult] = useState<PhotoSearchResult>(EMPTY);
95
+ const [answered, setAnswered] = useState("");
96
+ const [loading, setLoading] = useState(searchable);
97
+ const [error, setError] = useState<Error | null>(null);
98
+
99
+ useEffect(() => {
100
+ const requestId = ++requestRef.current;
101
+ if (!searchable) {
102
+ setResult(EMPTY);
103
+ setAnswered("");
104
+ setLoading(false);
105
+ setError(null);
106
+ return;
107
+ }
108
+ setLoading(true);
109
+ let active = true;
110
+ let timer: ReturnType<typeof setTimeout> | null = null;
111
+ const run = () => {
112
+ void (async () => {
113
+ try {
114
+ const id = await resolveSiteIdInput(siteIdRef.current);
115
+ const next = await searchListingPhotos(
116
+ id,
117
+ { q: query, limit, page },
118
+ { baseUrl, fetch: fetchRef.current }
119
+ );
120
+ if (!active || requestId !== requestRef.current) return;
121
+ setResult(next);
122
+ setAnswered(query);
123
+ setError(null);
124
+ } catch (caught) {
125
+ if (!active || requestId !== requestRef.current) return;
126
+ setResult(EMPTY);
127
+ setAnswered(query);
128
+ setError(
129
+ caught instanceof Error ? caught : new Error(String(caught))
130
+ );
131
+ } finally {
132
+ if (active && requestId === requestRef.current) setLoading(false);
133
+ }
134
+ })();
135
+ };
136
+ // `0` means no wait. A zero-delay timer still yields a macrotask.
137
+ if (debounceMs <= 0) run();
138
+ else timer = setTimeout(run, debounceMs);
139
+ return () => {
140
+ active = false;
141
+ if (timer != null) clearTimeout(timer);
142
+ };
143
+ }, [searchable, query, limit, page, baseUrl, siteIdToken, debounceMs]);
144
+
145
+ const listings = useMemo(
146
+ () =>
147
+ applyMatchedPhotoCover(
148
+ result.items.map((item) => item.listing),
149
+ result.items
150
+ ),
151
+ [result.items]
152
+ );
153
+
154
+ return {
155
+ available: result.available,
156
+ items: result.items,
157
+ listings,
158
+ total: result.total,
159
+ page: result.page,
160
+ limit: result.limit,
161
+ loading,
162
+ error,
163
+ query: answered,
164
+ };
165
+ }
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
4
  import { usePathname, useRouter } from "next/navigation";
5
5
 
6
6
  import { getSearchUi, queryListings } from "../fetchers";
7
+ import { publishableKeyHeaders } from "../internal/sdk-http";
7
8
  import { coerceSiteId, normalizeBaseUrl } from "../internal/url";
8
9
  import {
9
10
  applyPathFilter,
@@ -44,7 +45,13 @@ function currentHref(pathname: string, search: string): string {
44
45
  export function usePublicSearch(
45
46
  options: UsePublicSearchOptions
46
47
  ): PublicSearchState {
47
- const { siteId, baseUrl, initial, search: searchFromServer = "" } = options;
48
+ const {
49
+ siteId,
50
+ baseUrl,
51
+ publishableKey,
52
+ initial,
53
+ search: searchFromServer = "",
54
+ } = options;
48
55
  const router = useRouter();
49
56
  const pathname = usePathname() || "/imoveis";
50
57
  const search = searchFromServer;
@@ -149,13 +156,23 @@ export function usePublicSearch(
149
156
  }
150
157
  async function loadSchema() {
151
158
  try {
152
- const nextSchema = await getSearchUi({ siteId: id, baseUrl });
159
+ const nextSchema = await getSearchUi({
160
+ siteId: id,
161
+ baseUrl,
162
+ publishableKey,
163
+ });
153
164
  if (!active) return;
154
165
  let locations: LocationNameTables | null = null;
155
166
  if (nextSchema.locationsPath.startsWith("/")) {
156
167
  try {
157
168
  const response = await fetch(
158
- `${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`
169
+ `${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`,
170
+ {
171
+ headers: {
172
+ Accept: "application/json",
173
+ ...publishableKeyHeaders(publishableKey),
174
+ },
175
+ }
159
176
  );
160
177
  if (response.ok) {
161
178
  locations = (await response.json()) as LocationNameTables;
@@ -192,7 +209,7 @@ export function usePublicSearch(
192
209
  return () => {
193
210
  active = false;
194
211
  };
195
- }, [baseUrl, catalogId]);
212
+ }, [baseUrl, catalogId, publishableKey]);
196
213
 
197
214
  useEffect(() => {
198
215
  if (!schema || !catalogId) return;
@@ -218,6 +235,7 @@ export function usePublicSearch(
218
235
  const response = await queryListings({
219
236
  siteId: id,
220
237
  baseUrl,
238
+ publishableKey,
221
239
  params: buildQueryListingsParams(
222
240
  pathFilters,
223
241
  applied,
@@ -257,7 +275,7 @@ export function usePublicSearch(
257
275
  return () => {
258
276
  active = false;
259
277
  };
260
- }, [pathname, search, baseUrl, schema, catalogId]);
278
+ }, [pathname, search, baseUrl, schema, catalogId, publishableKey]);
261
279
 
262
280
  const go = useCallback(
263
281
  (href: string) => {
@@ -7,6 +7,8 @@ export interface ResolvePublicSiteIdOptions {
7
7
  fallback?: string | null;
8
8
  baseUrl?: string;
9
9
  fetch?: FetchLike;
10
+ /** Forwarded to `getSite` when the live host is resolved. */
11
+ publishableKey?: string;
10
12
  }
11
13
 
12
14
  /** v0 in-chat preview only. Published Studio sites often live on `*.vercel.app`. */
@@ -38,6 +40,7 @@ export async function resolvePublicSiteId(
38
40
  domain: host,
39
41
  baseUrl: options.baseUrl,
40
42
  fetch: options.fetch,
43
+ publishableKey: options.publishableKey,
41
44
  });
42
45
  if (site?.id) return site.id;
43
46
  throw new GaragemSdkError(