@garagem-ai/site-sdk 0.5.2 → 0.6.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.
Files changed (42) hide show
  1. package/README.md +16 -25
  2. package/dist/index.d.mts +296 -28
  3. package/dist/index.d.ts +296 -28
  4. package/dist/index.js +469 -53
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.mjs +458 -51
  7. package/dist/index.mjs.map +1 -1
  8. package/dist/react.d.mts +18 -60
  9. package/dist/react.d.ts +18 -60
  10. package/dist/react.js +265 -874
  11. package/dist/react.js.map +1 -1
  12. package/dist/react.mjs +246 -841
  13. package/dist/react.mjs.map +1 -1
  14. package/dist/{search-engine-4ocM0UPk.d.mts → search-engine-CtnLzmwW.d.mts} +13 -181
  15. package/dist/{search-engine-4ocM0UPk.d.ts → search-engine-CtnLzmwW.d.ts} +13 -181
  16. package/package.json +11 -13
  17. package/src/amenity-labels.ts +9 -2
  18. package/src/fetchers.ts +2 -1
  19. package/src/index.ts +20 -2
  20. package/src/internal/url.ts +1 -0
  21. package/src/leads.ts +45 -6
  22. package/src/listing-card-model.ts +4 -1
  23. package/src/listing-detail.ts +8 -2
  24. package/src/phone-countries.ts +97 -0
  25. package/src/phone.ts +431 -0
  26. package/src/presentation.ts +1 -24
  27. package/src/react/index.ts +1 -11
  28. package/src/react/public-search-snapshot.ts +165 -0
  29. package/src/react/staged-filters-mirror.ts +38 -0
  30. package/src/react/types.ts +17 -30
  31. package/src/react/use-public-search.ts +121 -42
  32. package/src/search-engine.ts +3 -0
  33. package/src/studio-contract.ts +63 -21
  34. package/src/types.ts +12 -0
  35. package/src/react/cn.ts +0 -3
  36. package/src/react/listing-card.tsx +0 -98
  37. package/src/react/listing-detail-fields.tsx +0 -119
  38. package/src/react/search-chrome.tsx +0 -29
  39. package/src/react/search.css +0 -214
  40. package/src/react/styles/index.ts +0 -1
  41. package/src/react/styles/search-chrome-css.generated.ts +0 -5
  42. package/src/react/styles/search-chrome-styles.tsx +0 -31
package/dist/react.mjs CHANGED
@@ -1,542 +1,77 @@
1
1
  "use client";
2
2
 
3
- // src/react/listing-card.tsx
4
- import Link from "next/link";
3
+ // src/react/use-public-search.ts
4
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
5
+ import { usePathname, useRouter } from "next/navigation";
5
6
 
6
- // src/presentation.ts
7
- var SEARCH_CSS_VARS = {
8
- cardRadius: "--garagem-listing-card-radius",
9
- cardGap: "--garagem-listing-card-gap",
10
- priceSize: "--garagem-listing-price-size",
11
- mediaRatio: "--garagem-listing-media-ratio",
12
- controlHeight: "--garagem-search-control-height",
13
- iconSize: "--garagem-search-icon-size",
14
- skeleton: "--garagem-skeleton"
15
- };
16
- var SEARCH_CSS_RECIPE = `:root {
17
- ${SEARCH_CSS_VARS.cardRadius}: 0.75rem;
18
- ${SEARCH_CSS_VARS.cardGap}: 1.5rem;
19
- ${SEARCH_CSS_VARS.priceSize}: 1.125rem;
20
- ${SEARCH_CSS_VARS.mediaRatio}: 4 / 3;
21
- ${SEARCH_CSS_VARS.controlHeight}: 2.75rem;
22
- ${SEARCH_CSS_VARS.iconSize}: 1.25rem;
23
- ${SEARCH_CSS_VARS.skeleton}: var(--muted, #e7e5e4);
24
- }
25
- `;
26
- function formatListingPrice(amount, locale = "pt-BR", currency = "BRL") {
27
- if (amount == null) return "Sob consulta";
28
- try {
29
- return new Intl.NumberFormat(locale, {
30
- style: "currency",
31
- currency,
32
- minimumFractionDigits: 0,
33
- maximumFractionDigits: 0
34
- }).format(amount);
35
- } catch {
36
- return `${currency} ${amount}`;
37
- }
7
+ // src/internal/url.ts
8
+ var DEFAULT_BASE_URL = "https://app.garagem.ai";
9
+ function normalizeBaseUrl(baseUrl) {
10
+ const url = baseUrl ?? DEFAULT_BASE_URL;
11
+ return url.endsWith("/") ? url.slice(0, -1) : url;
38
12
  }
39
- function parseGroupedInteger(value) {
40
- if (typeof value === "number") {
41
- return Number.isFinite(value) ? Math.trunc(value) : void 0;
13
+ async function coerceSiteId(siteId) {
14
+ const raw = typeof siteId === "function" ? siteId() : siteId;
15
+ const value = await Promise.resolve(raw);
16
+ if (typeof value !== "string" || !value.trim()) {
17
+ throw new TypeError(
18
+ "Garagem SDK: siteId must be a string. Await resolveSiteId(...) before getListings / getSearchUi / queryListings."
19
+ );
42
20
  }
43
- const digits = String(value ?? "").replace(/\D/g, "");
44
- if (!digits) return void 0;
45
- const amount = Number.parseInt(digits, 10);
46
- return Number.isFinite(amount) ? amount : void 0;
47
- }
48
- function formatAreaM2(area) {
49
- if (area == null || !Number.isFinite(area)) return null;
50
- return `${area} m\xB2`;
51
- }
52
- function listingBusinessLabel(businessType) {
53
- return businessType === "rental" ? "Aluguel" : "Venda";
21
+ return value;
54
22
  }
55
23
 
56
- // src/listing-path.ts
57
- function listingPublicPath(listing) {
58
- const composed = listing.path?.trim() ?? "";
59
- if (composed.startsWith("/") && !composed.startsWith("//")) return composed;
60
- const identity = listing.listingCode?.trim() || listing.id?.trim() || "";
61
- if (!identity || identity === "undefined" || identity === "null") {
62
- throw new TypeError("listingPublicPath: listing has no listingCode or id");
24
+ // src/fetchers.ts
25
+ async function callJson(url, init, fetchImpl) {
26
+ const response = await fetchImpl(url, init);
27
+ 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
+ );
63
33
  }
64
- return `/imoveis/id-${identity}`;
65
- }
66
-
67
- // src/listing-card-model.ts
68
- function listingLocationLabel(location) {
69
- return [location.neighborhood, location.city, location.state].map((part) => part ? String(part).trim() : "").filter(Boolean).join(", ");
70
- }
71
- function toListingCardModel(listing) {
72
- const isPrivate = listing.priceVisibility === "private";
73
- const area = listing.property?.usableArea ?? listing.property?.totalArea;
74
- return {
75
- href: listingPublicPath(listing),
76
- title: listing.title,
77
- businessType: listing.businessType,
78
- businessLabel: listingBusinessLabel(listing.businessType),
79
- priceVisibility: listing.priceVisibility,
80
- price: listing.price,
81
- priceLabel: isPrivate ? "Sob consulta" : formatListingPrice(listing.price),
82
- pricePeriod: listing.businessType === "rental" && !isPrivate && listing.price != null ? "/m\xEAs" : null,
83
- locationLabel: listingLocationLabel(listing.location || {}),
84
- propertyType: listing.property?.type ?? null,
85
- coverSrc: listing.coverImage?.src ?? null,
86
- coverAlt: listing.coverImage?.alt ?? listing.title,
87
- bedrooms: listing.property?.bedrooms ?? null,
88
- bathrooms: listing.property?.bathrooms ?? null,
89
- parkingSpaces: listing.property?.parkingSpaces ?? null,
90
- areaM2: area ?? null
91
- };
92
- }
93
-
94
- // src/react/cn.ts
95
- function cn(...parts) {
96
- return parts.filter(Boolean).join(" ");
34
+ return await response.json();
97
35
  }
98
-
99
- // src/react/styles/search-chrome-styles.tsx
100
- import { useLayoutEffect } from "react";
101
-
102
- // src/react/styles/search-chrome-css.generated.ts
103
- var SEARCH_CHROME_CSS_VERSION = "0.5.2";
104
- var SEARCH_CHROME_CSS = ':root{--garagem-listing-card-radius:0.75rem;--garagem-listing-card-gap:1.5rem;--garagem-listing-price-size:1.125rem;--garagem-listing-media-ratio:4 / 3;--garagem-skeleton:var(--muted,#e7e5e4)}[data-slot="search-grid"],[data-slot="search-skeleton"]{display:grid;grid-template-columns:1fr;gap:var(--garagem-listing-card-gap)}@media (min-width:640px){[data-slot="search-grid"],[data-slot="search-skeleton"]{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width:1024px){[data-slot="search-grid"],[data-slot="search-skeleton"]{grid-template-columns:repeat(3,minmax(0,1fr))}}[data-slot="listing-card"]{overflow:hidden;border-radius:var(--garagem-listing-card-radius);border:1px solid var(--border,#e4e4e7);background:var(--card,var(--background,#fff))}[data-slot="listing-card-price-row"]{display:inline-flex;align-items:baseline;gap:0.25rem}[data-slot="listing-card-price"]{font-size:var(--garagem-listing-price-size);font-weight:600}[data-slot="listing-card-period"]{font-size:0.75rem;color:var(--muted-foreground,#737373)}[data-slot="listing-card-link"]{display:block;color:inherit;text-decoration:none;cursor:pointer}[data-slot="listing-card-media"]{position:relative;width:100%;overflow:hidden;background:var(--muted,#f5f5f4);aspect-ratio:var(--garagem-listing-media-ratio)}[data-slot="listing-card-media"] img{height:100%;width:100%;object-fit:cover;transition:transform 0.3s}[data-slot="listing-card"]:hover [data-slot="listing-card-media"] img{transform:scale(1.05)}@media (prefers-reduced-motion:reduce){[data-slot="listing-card-media"] img{transition:none}[data-slot="listing-card"]:hover [data-slot="listing-card-media"] img{transform:none}}[data-slot="listing-card-empty"]{display:flex;height:100%;width:100%;align-items:center;justify-content:center;font-size:0.75rem;color:var(--muted-foreground,#737373)}[data-slot="listing-card-cta"]{margin-top:0.75rem}[data-slot="listing-card-badge"]{position:absolute;left:0.75rem;top:0.75rem;border-radius:999px;background:color-mix(in srgb,var(--background,#fff) 90%,transparent);padding:0.25rem 0.5rem;font-size:0.75rem;font-weight:500}[data-slot="listing-card-body"]{padding:1rem}[data-slot="listing-card-title"]{display:-webkit-box;margin-top:0.25rem;overflow:hidden;-webkit-box-orient:vertical;-webkit-line-clamp:1;font-size:0.875rem;font-weight:500}[data-slot="listing-card-location"]{margin-top:0.125rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:0.75rem;color:var(--muted-foreground,#737373)}[data-slot="listing-card-features"]{display:flex;flex-wrap:wrap;margin-top:0.75rem;gap:0.25rem 1rem;padding:0;list-style:none;font-size:0.75rem;color:var(--muted-foreground,#737373)}[data-slot="search-skeleton-block"]{animation:garagem-search-pulse 1.2s ease-in-out infinite;background:var(--garagem-skeleton);border-radius:0.375rem}[data-slot="search-skeleton-card"]{overflow:hidden;border-radius:var(--garagem-listing-card-radius);border:1px solid var(--border,#e4e4e7)}[data-slot="search-skeleton-body"]{display:flex;flex-direction:column;gap:0.5rem;padding:1rem}[data-slot="search-skeleton-block"][data-kind="media"]{aspect-ratio:var(--garagem-listing-media-ratio)}[data-slot="search-skeleton-block"][data-kind="line-lg"]{height:1.25rem;width:50%}[data-slot="search-skeleton-block"][data-kind="line-md"]{height:1rem;width:75%}[data-slot="search-skeleton-block"][data-kind="line-sm"]{height:0.75rem;width:66.666667%}[data-slot="search-skeleton-block"][data-kind="detail-media"]{max-width:45rem;aspect-ratio:4 / 3}[data-slot="search-skeleton-block"][data-kind="detail-title"]{width:66.666667%;height:2rem;margin-top:1.5rem}@media (prefers-reduced-motion:reduce){[data-slot="search-skeleton-block"]{animation:none}}@keyframes garagem-search-pulse{50%{opacity:0.55}}';
105
-
106
- // src/react/styles/search-chrome-styles.tsx
107
- var STYLE_ID = `garagem-search-chrome-${SEARCH_CHROME_CSS_VERSION}`;
108
- function injectSearchChromeOnce() {
109
- if (typeof document === "undefined") return;
110
- if (document.getElementById(STYLE_ID)) return;
111
- const el = document.createElement("style");
112
- el.id = STYLE_ID;
113
- el.textContent = SEARCH_CHROME_CSS;
114
- document.head.appendChild(el);
115
- }
116
- function SearchChromeStyles() {
117
- if (typeof document !== "undefined") {
118
- injectSearchChromeOnce();
36
+ var GaragemSdkError = class extends Error {
37
+ status;
38
+ url;
39
+ constructor(message, info) {
40
+ super(message);
41
+ this.name = "GaragemSdkError";
42
+ this.status = info.status;
43
+ this.url = info.url;
119
44
  }
120
- useLayoutEffect(() => {
121
- injectSearchChromeOnce();
122
- }, []);
123
- return null;
124
- }
125
-
126
- // src/react/listing-card.tsx
127
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
128
- function isListing(value) {
129
- return "priceVisibility" in value && "businessType" in value && "title" in value;
130
- }
131
- function ListingCard({
132
- listing,
133
- href,
134
- className,
135
- classNames,
136
- slots,
137
- style
138
- }) {
139
- const model = isListing(listing) ? toListingCardModel(listing) : listing;
140
- const target = href ?? model.href;
141
- const areaLabel = formatAreaM2(model.areaM2);
142
- return /* @__PURE__ */ jsxs(Fragment, { children: [
143
- /* @__PURE__ */ jsx(SearchChromeStyles, {}),
144
- /* @__PURE__ */ jsx(
145
- "article",
146
- {
147
- "data-slot": "listing-card",
148
- className: cn(className, classNames?.root),
149
- style,
150
- children: /* @__PURE__ */ jsxs(Link, { href: target, "data-slot": "listing-card-link", children: [
151
- /* @__PURE__ */ jsxs("div", { "data-slot": "listing-card-media", className: classNames?.media, children: [
152
- slots?.media ?? (model.coverSrc ? /* @__PURE__ */ jsx("img", { src: model.coverSrc, alt: model.coverAlt }) : /* @__PURE__ */ jsx("div", { "data-slot": "listing-card-empty", children: "Sem foto" })),
153
- slots?.badge ?? /* @__PURE__ */ jsx(
154
- "span",
155
- {
156
- "data-slot": "listing-card-badge",
157
- className: classNames?.badge,
158
- children: model.businessLabel
159
- }
160
- )
161
- ] }),
162
- /* @__PURE__ */ jsxs("div", { "data-slot": "listing-card-body", className: classNames?.body, children: [
163
- /* @__PURE__ */ jsxs("div", { "data-slot": "listing-card-price-row", children: [
164
- /* @__PURE__ */ jsx("p", { "data-slot": "listing-card-price", className: classNames?.price, children: model.priceLabel }),
165
- model.pricePeriod ? /* @__PURE__ */ jsx("span", { "data-slot": "listing-card-period", children: model.pricePeriod }) : null
166
- ] }),
167
- /* @__PURE__ */ jsx("h3", { "data-slot": "listing-card-title", className: classNames?.title, children: model.title }),
168
- /* @__PURE__ */ jsx(
169
- "p",
170
- {
171
- "data-slot": "listing-card-location",
172
- className: classNames?.location,
173
- children: model.locationLabel || model.propertyType || ""
174
- }
175
- ),
176
- /* @__PURE__ */ jsxs(
177
- "ul",
178
- {
179
- "data-slot": "listing-card-features",
180
- className: classNames?.features,
181
- children: [
182
- model.bedrooms != null ? /* @__PURE__ */ jsxs("li", { children: [
183
- model.bedrooms,
184
- " quartos"
185
- ] }) : null,
186
- model.bathrooms != null ? /* @__PURE__ */ jsxs("li", { children: [
187
- model.bathrooms,
188
- " banheiros"
189
- ] }) : null,
190
- model.parkingSpaces != null ? /* @__PURE__ */ jsxs("li", { children: [
191
- model.parkingSpaces,
192
- " vagas"
193
- ] }) : null,
194
- areaLabel ? /* @__PURE__ */ jsx("li", { children: areaLabel }) : null
195
- ]
196
- }
197
- ),
198
- slots?.cta ? /* @__PURE__ */ jsx("div", { "data-slot": "listing-card-cta", className: classNames?.cta, children: slots.cta }) : null
199
- ] })
200
- ] })
201
- }
202
- )
203
- ] });
204
- }
205
-
206
- // src/amenity-labels.ts
207
- var LISTING_AMENITY_TITLES = {
208
- unit: "Comodidades",
209
- building: "Comodidades do condom\xEDnio"
210
45
  };
211
- var AMENITY_FALLBACK_LABELS = {
212
- // ==================== PROPERTY FEATURES ====================
213
- // Amenities
214
- arCondicionado: "Ar condicionado",
215
- banheira: "Banheira",
216
- carregadorEletrico: "Carregador el\xE9trico",
217
- churrasqueira: "Churrasqueira",
218
- chuveiroGas: "Chuveiro a g\xE1s",
219
- chuveiroEletrico: "Chuveiro el\xE9trico",
220
- energiaSolar: "Energia solar",
221
- fechaduraDigital: "Fechadura digital",
222
- fechaduraEletronica: "Fechadura eletr\xF4nica",
223
- geradorEletrico: "Gerador el\xE9trico",
224
- gesso: "Gesso",
225
- hidromassagem: "Hidromassagem",
226
- lareira: "Lareira",
227
- ofuro: "Ofur\xF4",
228
- spa: "Spa",
229
- painelSolar: "Painel solar",
230
- portaoEletronico: "Port\xE3o eletr\xF4nico",
231
- sistemaAlarme: "Sistema de alarme",
232
- homeTheater: "Home theater",
233
- adega: "Adega",
234
- split: "Split",
235
- arCentral: "Ar central",
236
- esperaSplit: "Espera para split",
237
- vistaMar: "Vista para o mar",
238
- vistaPanoramica: "Vista panor\xE2mica",
239
- aguaQuente: "\xC1gua quente",
240
- reformado: "Reformado",
241
- tvCabo: "TV a cabo",
242
- gradeado: "Gradeado",
243
- antenaParabolica: "Antena parab\xF3lica",
244
- aquecimento: "Aquecimento",
245
- aquecimentoEletrico: "Aquecimento el\xE9trico",
246
- aquecimentoCentral: "Aquecimento central",
247
- cercaEletrica: "Cerca el\xE9trica",
248
- monitoramento: "Monitoramento",
249
- vigiaInterno: "Vigia interno",
250
- vigiaExterno: "Vigia externo",
251
- alarme: "Alarme",
252
- agua: "\xC1gua",
253
- redeEsgoto: "Rede de esgoto",
254
- pavimentacao: "Pavimenta\xE7\xE3o",
255
- energiaEletrica: "Energia el\xE9trica",
256
- // Furniture
257
- mobiliado: "Mobiliado",
258
- armarioEmbutido: "Arm\xE1rio embutido",
259
- armarioEmbutidoQuarto: "Arm\xE1rio embutido quarto",
260
- armarioCozinha: "Arm\xE1rio cozinha",
261
- armarioBanheiro: "Arm\xE1rio banheiro",
262
- cozinhaPlanejada: "Cozinha planejada",
263
- fogao: "Fog\xE3o",
264
- fornoPizza: "Forno de pizza",
265
- freezer: "Freezer",
266
- dormitorioComArmario: "Dormit\xF3rio com arm\xE1rio",
267
- semiMobiliado: "Semi mobiliado",
268
- salaArmarios: "Sala com arm\xE1rios",
269
- // Structure
270
- piscina: "Piscina",
271
- piscinaAquecida: "Piscina aquecida",
272
- piscinaCoberta: "Piscina coberta",
273
- poco: "Po\xE7o",
274
- pocoArtesiano: "Po\xE7o artesiano",
275
- bar: "Bar",
276
- jardim: "Jardim",
277
- lago: "Lago",
278
- lavabo: "Lavabo",
279
- quintal: "Quintal",
280
- solarium: "Solarium",
281
- quartoServico: "Quarto de servi\xE7o",
282
- varanda: "Varanda",
283
- varandaFechadaVidro: "Varanda fechada com vidro",
284
- varandaGourmet: "Varanda gourmet",
285
- banheiroServico: "Banheiro de servi\xE7o",
286
- areaServico: "\xC1rea de servi\xE7o",
287
- cinema: "Cinema",
288
- closet: "Closet",
289
- cozinhaAmericana: "Cozinha americana",
290
- cozinhaGourmet: "Cozinha gourmet",
291
- despensa: "Despensa",
292
- escritorio: "Escrit\xF3rio",
293
- edicula: "Ed\xEDcula",
294
- horta: "Horta",
295
- sacada: "Sacada",
296
- salaJantar: "Sala de jantar",
297
- cozinha: "Cozinha",
298
- banheiroSocial: "Banheiro social",
299
- terraco: "Terra\xE7o",
300
- copa: "Copa",
301
- suiteMaster: "Su\xEDte master",
302
- wcEmpregada: "WC empregada",
303
- dependenciaEmpregada: "Depend\xEAncia de empregada",
304
- dependenciadeEmpregada: "Depend\xEAncia empregada",
305
- salaTv: "Sala de TV",
306
- copaCozinha: "Copa cozinha",
307
- sacadaComChurrasqueira: "Sacada com churrasqueira",
308
- hallPrivativo: "Hall privativo",
309
- estarIntimo: "Estar \xEDntimo",
310
- livingHall: "Living hall",
311
- piscinaInterna: "Piscina interna",
312
- deck: "Deck",
313
- jardimInverno: "Jardim de inverno",
314
- rouparia: "Rouparia",
315
- living: "Living",
316
- familyRoom: "Family room",
317
- salafitness: "Sala fitness",
318
- salaEstar: "Sala de estar",
319
- mezanino: "Mezanino",
320
- pisoElevado: "Piso elevado",
321
- entradaServicoIndependente: "Entrada de servi\xE7o independente",
322
- forro: "Forro",
323
- vitrine: "Vitrine",
324
- banheiroAuxiliar: "Banheiro auxiliar",
325
- gabinete: "Gabinete",
326
- quadraTenisPrivativa: "Quadra de t\xEAnis privativa",
327
- porao: "Por\xE3o",
328
- sotao: "S\xF3t\xE3o",
329
- patio: "P\xE1tio",
330
- canaletasNoRodape: "Canaletas no rodap\xE9",
331
- // Accessibility
332
- barraApoioVaso: "Barra de apoio vaso",
333
- barraApoioChuveiro: "Barra de apoio chuveiro",
334
- entradaSemDegrau: "Entrada sem degrau",
335
- rampasAcesso: "Rampas de acesso",
336
- vagaDeficientes: "Vaga para deficientes",
337
- // Flooring
338
- cimentoQueimado: "Cimento queimado",
339
- madeira: "Madeira",
340
- pisoFrio: "Piso frio",
341
- laminado: "Laminado",
342
- vinilico: "Vin\xEDlico",
343
- porcelanato: "Porcelanato",
344
- // ==================== BUILDING FEATURES ====================
345
- // Amenities
346
- elevador: "Elevador",
347
- bicicletario: "Biciclet\xE1rio",
348
- carregadorEletronico: "Carregador eletr\xF4nico",
349
- concierge: "Concierge",
350
- coworking: "Coworking",
351
- deposito: "Dep\xF3sito",
352
- lavanderia: "Lavanderia",
353
- petPlace: "Pet place",
354
- recebimentoEncomendas: "Recebimento de encomendas",
355
- salaReuniao: "Sala de reuni\xE3o",
356
- salaoFestas: "Sal\xE3o de festas",
357
- valet: "Valet",
358
- garagemCoberta: "Garagem coberta",
359
- elevadorServico: "Elevador de servi\xE7o",
360
- // Leisure
361
- academia: "Academia",
362
- campoFutebol: "Campo de futebol",
363
- espacoGourmet: "Espa\xE7o gourmet",
364
- piscinaInfantil: "Piscina infantil",
365
- pistaCaminhada: "Pista de caminhada",
366
- playground: "Playground",
367
- quadraPoliesportiva: "Quadra poliesportiva",
368
- quadraTenis: "Quadra de t\xEAnis",
369
- salaJogos: "Sala de jogos",
370
- salaVapor: "Sala de vapor",
371
- sauna: "Sauna",
372
- // Security
373
- circuitoTv: "Circuito fechado de TV",
374
- controleAcessoEletronico: "Controle de acesso eletr\xF4nico",
375
- interfone: "Interfone",
376
- portaria24h: "Portaria 24h",
377
- porteiroFisico: "Porteiro f\xEDsico",
378
- seguranca24h: "Seguran\xE7a 24h",
379
- segurancaPatrimonial: "Seguran\xE7a patrimonial",
380
- condominioFechado: "Condom\xEDnio fechado",
381
- // Accessibility
382
- banheiroAcessivel: "Banheiro acess\xEDvel",
383
- elevadorAcessivel: "Elevador acess\xEDvel",
384
- pisoTatil: "Piso t\xE1til",
385
- // ==================== CANONICAL HAS*/IS* KEYS ====================
386
- has24hConcierge: "Portaria 24h",
387
- has24hSecurity: "Seguran\xE7a 24h",
388
- hasAccessRamps: "Rampas de acesso",
389
- hasAccessibleBathroom: "Banheiro acess\xEDvel",
390
- hasAccessibleElevator: "Elevador acess\xEDvel",
391
- hasAirConditioning: "Ar condicionado",
392
- hasAlarmSystem: "Sistema de alarme",
393
- hasBalcony: "Varanda",
394
- hasBikeStorage: "Biciclet\xE1rio",
395
- hasBuiltInWardrobe: "Arm\xE1rio embutido",
396
- hasCCTV: "CFTV",
397
- hasCloset: "Closet",
398
- hasConcierge: "Portaria",
399
- hasControlledAccess: "Condom\xEDnio fechado",
400
- hasCoworking: "Coworking",
401
- hasDisabledParking: "Vaga para deficientes",
402
- hasElectricCharger: "Carregador eletr\xF4nico",
403
- hasElectronicGate: "Port\xE3o eletr\xF4nico",
404
- hasElevator: "Elevador",
405
- hasFireplace: "Lareira",
406
- hasGarden: "Jardim",
407
- hasGasShower: "Chuveiro a g\xE1s",
408
- hasGenerator: "Gerador",
409
- hasGourmetBalcony: "Varanda gourmet",
410
- hasGourmetKitchen: "Cozinha gourmet",
411
- hasGrill: "Churrasqueira",
412
- hasGuestParking: "Estacionamento para visitantes",
413
- hasGym: "Academia",
414
- hasHeating: "Aquecimento",
415
- hasHomeOffice: "Home office",
416
- hasIntercom: "Interfone",
417
- hasJacuzzi: "Hidromassagem",
418
- hasKidsPool: "Piscina infantil",
419
- hasLaundry: "Lavanderia",
420
- hasMeetingRoom: "Sala de reuni\xE3o",
421
- hasOffice: "Escrit\xF3rio",
422
- hasOpenKitchen: "Cozinha americana",
423
- hasPackageReceival: "Recebimento de encomendas",
424
- hasPantry: "Despensa",
425
- hasParkingGarage: "Garagem coberta",
426
- hasPartySaloon: "Sal\xE3o de festas",
427
- hasPetArea: "Pet place",
428
- hasPipedGas: "G\xE1s encanado",
429
- hasPlayground: "Playground",
430
- hasPowderRoom: "Lavabo",
431
- hasPrivatePool: "Piscina privativa",
432
- hasSauna: "Sauna",
433
- hasSecurity: "Seguran\xE7a",
434
- hasServiceArea: "\xC1rea de servi\xE7o",
435
- hasSolarPanel: "Painel solar",
436
- hasSpa: "Spa",
437
- hasSportsCourt: "Quadra de esportes",
438
- hasStepFreeEntrance: "Entrada sem degrau",
439
- hasStorage: "Dep\xF3sito",
440
- hasSwimmingPool: "Piscina",
441
- hasTennisCourt: "Quadra de t\xEAnis",
442
- hasValetParking: "Valet",
443
- homeOffice: "Home office",
444
- isPetFriendly: "Pet friendly",
445
- isFurnished: "Mobiliado",
446
- isPartiallyFurnished: "Semi-mobiliado",
447
- petFriendly: "Pet friendly",
448
- piscinaPrivativa: "Piscina privativa",
449
- pisoLaminado: "Piso laminado",
450
- pisoMadeira: "Piso de madeira",
451
- pisoPorcelanato: "Piso porcelanato",
452
- quadraEsportes: "Quadra de esportes",
453
- rooftop: "Rooftop",
454
- suite: "Su\xEDte",
455
- triplex: "Triplex",
456
- duplex: "Duplex",
457
- cobertura: "Cobertura",
458
- forroGesso: "Forro de gesso",
459
- gerador: "Gerador",
460
- armariosCozinha: "Arm\xE1rios na cozinha",
461
- armariosQuarto: "Arm\xE1rios nos quartos",
462
- cftv: "CFTV"
463
- };
464
- function lookupLabel(id, options) {
465
- const fromDictionary = options?.find((option) => option.id === id)?.label;
466
- if (fromDictionary?.trim()) return fromDictionary.trim();
467
- return AMENITY_FALLBACK_LABELS[id];
468
- }
469
- function labelAmenities(ids, dictionary) {
470
- if (!ids?.length) return [];
471
- const labels = [];
472
- const seen = /* @__PURE__ */ new Set();
473
- for (const id of ids) {
474
- if (!id) continue;
475
- const label = lookupLabel(id, dictionary);
476
- if (!label || seen.has(label)) continue;
477
- seen.add(label);
478
- labels.push(label);
479
- }
480
- return labels.sort((a, b) => a.localeCompare(b, "pt-BR"));
481
- }
482
- function presentIds(ids) {
483
- return (ids ?? []).filter((id) => Boolean(id));
484
- }
485
- function buildingIdsFromMergedAmenities(listing, unitIds) {
486
- if (!listing.amenities || listing.propertyFeatures == null) return [];
487
- const unitCounts = /* @__PURE__ */ new Map();
488
- for (const id of unitIds) {
489
- unitCounts.set(id, (unitCounts.get(id) ?? 0) + 1);
490
- }
491
- return listing.amenities.filter((id) => {
492
- if (!id) return false;
493
- const count = unitCounts.get(id);
494
- if (count === void 0 || count === 0) return true;
495
- unitCounts.set(id, count - 1);
496
- return false;
497
- });
498
- }
499
- function unitAmenityIds(listing) {
500
- if (listing.propertyFeatures != null) {
501
- return presentIds(listing.propertyFeatures);
502
- }
503
- const building = new Set(
504
- listing.building?.amenities ?? listing.buildingAmenities ?? []
46
+ async function getSearchUi(options) {
47
+ const { baseUrl, fetch: fetchImpl, next } = options;
48
+ const siteId = await coerceSiteId(options.siteId);
49
+ const base = normalizeBaseUrl(baseUrl);
50
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search-ui`;
51
+ return callJson(
52
+ url,
53
+ { method: "GET", headers: { Accept: "application/json" }, next },
54
+ fetchImpl ?? fetch
505
55
  );
506
- return (listing.amenities ?? []).filter((id) => id && !building.has(id));
507
56
  }
508
- function buildingAmenityIds(listing) {
509
- if (listing.building != null && listing.building.amenities != null) {
510
- return presentIds(listing.building.amenities);
511
- }
512
- if (listing.buildingAmenities != null) {
513
- return presentIds(listing.buildingAmenities);
514
- }
515
- return buildingIdsFromMergedAmenities(listing, unitAmenityIds(listing));
516
- }
517
- function listingAmenityGroups(listing, dictionary) {
518
- const groups = [];
519
- const unitIds = unitAmenityIds(listing);
520
- const unitLabels = labelAmenities(unitIds, dictionary?.propertyFeatures);
521
- if (unitLabels.length > 0) {
522
- groups.push({
523
- key: "unit",
524
- title: LISTING_AMENITY_TITLES.unit,
525
- labels: unitLabels
526
- });
527
- }
528
- const buildingLabels = labelAmenities(
529
- buildingAmenityIds(listing),
530
- dictionary?.buildingAmenities
57
+ async function queryListings(options) {
58
+ const { params, baseUrl, fetch: fetchImpl, next } = options;
59
+ const siteId = await coerceSiteId(options.siteId);
60
+ const base = normalizeBaseUrl(baseUrl);
61
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;
62
+ return callJson(
63
+ url,
64
+ {
65
+ method: "POST",
66
+ headers: {
67
+ Accept: "application/json",
68
+ "Content-Type": "application/json"
69
+ },
70
+ body: JSON.stringify(params ?? {}),
71
+ next
72
+ },
73
+ fetchImpl ?? fetch
531
74
  );
532
- if (buildingLabels.length > 0) {
533
- groups.push({
534
- key: "building",
535
- title: LISTING_AMENITY_TITLES.building,
536
- labels: buildingLabels
537
- });
538
- }
539
- return groups;
540
75
  }
541
76
 
542
77
  // ../search-url/types.ts
@@ -548,6 +83,7 @@ var DEFAULT_MAX_PRICE = 1e9;
548
83
  var DEFAULT_MIN_AREA = 0;
549
84
  var DEFAULT_MAX_AREA = 1e5;
550
85
  var SORT_URL_TOKENS = [
86
+ "recentes",
551
87
  "preco-asc",
552
88
  "preco-desc",
553
89
  "area-asc",
@@ -984,6 +520,17 @@ function pathFiltersToQueryFilters(pathFilters) {
984
520
  return result;
985
521
  }
986
522
 
523
+ // src/presentation.ts
524
+ function parseGroupedInteger(value) {
525
+ if (typeof value === "number") {
526
+ return Number.isFinite(value) ? Math.trunc(value) : void 0;
527
+ }
528
+ const digits = String(value ?? "").replace(/\D/g, "");
529
+ if (!digits) return void 0;
530
+ const amount = Number.parseInt(digits, 10);
531
+ return Number.isFinite(amount) ? amount : void 0;
532
+ }
533
+
987
534
  // src/search-engine.ts
988
535
  var PATH_FILTER_IDS = {
989
536
  listing_type: "listingType",
@@ -1005,6 +552,11 @@ function toFiniteNumber(value) {
1005
552
  function pathnameOnly(pathname) {
1006
553
  return String(pathname || "").split(/[?#]/)[0] || "/";
1007
554
  }
555
+ function isListingDetailPath(pathname) {
556
+ const parts = pathnameOnly(pathname).split("/").filter(Boolean);
557
+ const last = parts[parts.length - 1] || "";
558
+ return last.toLowerCase().startsWith("id-");
559
+ }
1008
560
  function readPublicSearch(pathname, search, dictionary) {
1009
561
  const pathFilters = parseSearchPublicPath2(pathnameOnly(pathname), dictionary) || {};
1010
562
  const applied = parseAppliedSearchQuery2(search || "");
@@ -1137,6 +689,8 @@ function currentSearchHref(pathname, search) {
1137
689
  return qs ? `${path}?${qs}` : path;
1138
690
  }
1139
691
  function canonicalizeSearchHref(pathname, search, dictionary) {
692
+ if (pathname.includes("/api/v0-preview/")) return null;
693
+ if (isListingDetailPath(pathname)) return null;
1140
694
  const { pathFilters, applied } = readPublicSearch(
1141
695
  pathname,
1142
696
  search,
@@ -1157,294 +711,93 @@ function clearStagedPathFilters(current, keepFilterIds = []) {
1157
711
  return next;
1158
712
  }
1159
713
 
1160
- // src/listing-detail.ts
1161
- function finiteNumber(value) {
1162
- if (typeof value === "number" && Number.isFinite(value)) return value;
1163
- if (typeof value === "string" && value.trim() !== "") {
1164
- const parsed = Number(value);
1165
- if (Number.isFinite(parsed)) return parsed;
1166
- }
1167
- return null;
714
+ // src/react/public-search-snapshot.ts
715
+ function hrefParts(href) {
716
+ const q = href.indexOf("?");
717
+ if (q < 0) return { pathname: href, search: "" };
718
+ return { pathname: href.slice(0, q), search: href.slice(q + 1) };
1168
719
  }
1169
- function positiveCount(value) {
1170
- const amount = finiteNumber(value);
1171
- return amount != null && amount > 0 ? amount : null;
720
+ function searchHrefKey(pathname, search) {
721
+ const qs = search.replace(/^\?/, "");
722
+ return qs ? `${pathname}?${qs}` : pathname;
1172
723
  }
1173
- function formatFloorFact(value) {
1174
- if (typeof value === "number" && Number.isFinite(value)) {
1175
- return value === 0 ? "T\xE9rreo" : String(value);
1176
- }
1177
- if (typeof value !== "string") return null;
1178
- const trimmed = value.trim();
1179
- if (!trimmed) return null;
1180
- const parsed = Number(trimmed);
1181
- if (Number.isFinite(parsed) && trimmed === String(parsed)) {
1182
- return parsed === 0 ? "T\xE9rreo" : trimmed;
1183
- }
1184
- return trimmed;
724
+ function searchKeysRepresentSameQuery(a, b, dictionary) {
725
+ if (a == null) return false;
726
+ if (a === b) return true;
727
+ const left = hrefParts(a);
728
+ const right = hrefParts(b);
729
+ const leftCanon = canonicalizeSearchHref(left.pathname, left.search, dictionary) ?? searchHrefKey(left.pathname, left.search);
730
+ const rightCanon = canonicalizeSearchHref(right.pathname, right.search, dictionary) ?? searchHrefKey(right.pathname, right.search);
731
+ return leftCanon === rightCanon;
1185
732
  }
1186
- function listingValues(listing) {
1187
- const values = [
1188
- {
1189
- key: "price",
1190
- label: "Pre\xE7o",
1191
- text: listing.priceVisibility === "private" ? "Sob consulta" : formatListingPrice(listing.price)
1192
- }
1193
- ];
1194
- const condoFee = positiveCount(listing.property?.condoFee);
1195
- if (condoFee != null) {
1196
- values.push({
1197
- key: "condoFee",
1198
- label: "Condom\xEDnio",
1199
- text: formatListingPrice(condoFee)
1200
- });
1201
- }
1202
- const propertyTax = positiveCount(listing.property?.propertyTax);
1203
- if (propertyTax != null) {
1204
- values.push({
1205
- key: "propertyTax",
1206
- label: "IPTU",
1207
- text: formatListingPrice(propertyTax)
1208
- });
1209
- }
1210
- return values;
733
+ function hasTrustedSearchSnapshot(initial) {
734
+ return Boolean(initial?.schema || initial?.listings?.length);
1211
735
  }
1212
- function listingFacts(listing) {
1213
- const property = listing.property ?? {};
1214
- const facts = [];
1215
- const area = formatAreaM2(
1216
- positiveCount(property.usableArea) ?? positiveCount(property.totalArea)
1217
- );
1218
- if (area) facts.push({ key: "area", label: "\xC1rea", text: area });
1219
- const bedrooms = positiveCount(property.bedrooms);
1220
- if (bedrooms != null) {
1221
- facts.push({
1222
- key: "bedrooms",
1223
- label: "Dormit\xF3rios",
1224
- text: String(bedrooms)
1225
- });
1226
- }
1227
- const suites = positiveCount(property.suites);
1228
- if (suites != null) {
1229
- facts.push({ key: "suites", label: "Su\xEDtes", text: String(suites) });
1230
- }
1231
- const parking = positiveCount(property.parkingSpaces);
1232
- if (parking != null) {
1233
- facts.push({ key: "parkingSpaces", label: "Vagas", text: String(parking) });
1234
- }
1235
- const rooms = positiveCount(property.rooms);
1236
- if (rooms != null) {
1237
- facts.push({ key: "rooms", label: "Salas", text: String(rooms) });
1238
- }
1239
- const floorText = formatFloorFact(property.floor);
1240
- if (floorText) {
1241
- facts.push({ key: "floor", label: "Andar", text: floorText });
1242
- }
1243
- return facts;
736
+ function resolveSeedTotal(initial) {
737
+ if (typeof initial?.total === "number") return initial.total;
738
+ return initial?.listings?.length ?? 0;
1244
739
  }
1245
-
1246
- // src/listing-detail-fields.ts
1247
- function visibleText(value) {
1248
- if (typeof value !== "string") return null;
1249
- const trimmed = value.trim();
1250
- if (!trimmed || trimmed === "undefined" || trimmed === "null") return null;
1251
- return trimmed;
1252
- }
1253
- function visibleRows(rows) {
1254
- return rows.filter((row) => {
1255
- const label = visibleText(row.label);
1256
- const text = visibleText(row.text);
1257
- return label != null && text != null;
1258
- });
740
+ function preferFetchedLocationNames(previous, fetched) {
741
+ return fetched ?? previous;
1259
742
  }
1260
- function listingDetailFieldsModel(listing, dictionary) {
1261
- return {
1262
- facts: visibleRows(listingFacts(listing)),
1263
- values: visibleRows(listingValues(listing)),
1264
- amenityGroups: listingAmenityGroups(listing, dictionary).map((group) => ({
1265
- ...group,
1266
- labels: group.labels.map((label) => visibleText(label)).filter((label) => label != null)
1267
- })).filter((group) => group.labels.length > 0)
1268
- };
743
+ function shouldClearPaintedSearchOnSchemaFailure(keepSnapshot) {
744
+ return !keepSnapshot;
1269
745
  }
1270
-
1271
- // src/react/listing-detail-fields.tsx
1272
- import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
1273
- function ListingDetailFields({
1274
- listing,
1275
- dictionary,
1276
- className,
1277
- classNames,
1278
- style
1279
- }) {
1280
- const model = listingDetailFieldsModel(listing, dictionary ?? void 0);
1281
- if (model.facts.length === 0 && model.values.length === 0 && model.amenityGroups.length === 0) {
1282
- return null;
1283
- }
1284
- return /* @__PURE__ */ jsxs2(
1285
- "div",
1286
- {
1287
- "data-slot": "listing-detail-fields",
1288
- className: cn(className, classNames?.root),
1289
- style,
1290
- children: [
1291
- model.facts.length > 0 ? /* @__PURE__ */ jsx2("ul", { "data-slot": "listing-facts", className: classNames?.facts, children: model.facts.map((fact) => /* @__PURE__ */ jsxs2(
1292
- "li",
1293
- {
1294
- "data-slot": "listing-fact",
1295
- "data-key": fact.key,
1296
- className: classNames?.fact,
1297
- children: [
1298
- /* @__PURE__ */ jsx2("span", { "data-slot": "listing-fact-label", children: fact.label }),
1299
- /* @__PURE__ */ jsx2("span", { "data-slot": "listing-fact-text", children: fact.text })
1300
- ]
1301
- },
1302
- fact.key
1303
- )) }) : null,
1304
- model.values.length > 0 ? /* @__PURE__ */ jsx2("dl", { "data-slot": "listing-values", className: classNames?.values, children: model.values.map((value) => /* @__PURE__ */ jsxs2(
1305
- "div",
1306
- {
1307
- "data-slot": "listing-value",
1308
- "data-key": value.key,
1309
- className: classNames?.value,
1310
- children: [
1311
- /* @__PURE__ */ jsx2("dt", { "data-slot": "listing-value-label", children: value.label }),
1312
- /* @__PURE__ */ jsx2("dd", { "data-slot": "listing-value-text", children: value.text })
1313
- ]
1314
- },
1315
- value.key
1316
- )) }) : null,
1317
- model.amenityGroups.map((group) => /* @__PURE__ */ jsxs2(
1318
- "section",
1319
- {
1320
- "data-slot": "listing-amenities",
1321
- "data-key": group.key,
1322
- className: classNames?.amenityGroup,
1323
- children: [
1324
- /* @__PURE__ */ jsx2(
1325
- "h2",
1326
- {
1327
- "data-slot": "listing-amenities-title",
1328
- className: classNames?.amenityTitle,
1329
- children: group.title
1330
- }
1331
- ),
1332
- /* @__PURE__ */ jsx2(
1333
- "ul",
1334
- {
1335
- "data-slot": "listing-amenities-list",
1336
- className: classNames?.amenityList,
1337
- children: group.labels.map((label) => /* @__PURE__ */ jsx2(
1338
- "li",
1339
- {
1340
- "data-slot": "listing-amenity-label",
1341
- className: classNames?.amenityLabel,
1342
- children: label
1343
- },
1344
- label
1345
- ))
1346
- }
1347
- )
1348
- ]
1349
- },
1350
- group.key
1351
- ))
1352
- ]
1353
- }
746
+ function shouldAdvancePaintedSearchKeyOnCanonicalize() {
747
+ return false;
748
+ }
749
+ function shouldSetLoadingOnSearchKeyChange(options) {
750
+ return !searchKeysRepresentSameQuery(
751
+ options.paintedSearchKey,
752
+ options.searchKey,
753
+ options.dictionary
1354
754
  );
1355
755
  }
1356
-
1357
- // src/react/search-chrome.tsx
1358
- import { Fragment as Fragment2, jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
1359
- function ResultsSkeleton({
1360
- className
1361
- }) {
1362
- return /* @__PURE__ */ jsxs3(Fragment2, { children: [
1363
- /* @__PURE__ */ jsx3(SearchChromeStyles, {}),
1364
- /* @__PURE__ */ jsx3("div", { "data-slot": "search-skeleton", className, children: Array.from({ length: 6 }, (_, i) => /* @__PURE__ */ jsxs3("div", { "data-slot": "search-skeleton-card", children: [
1365
- /* @__PURE__ */ jsx3("div", { "data-slot": "search-skeleton-block", "data-kind": "media" }),
1366
- /* @__PURE__ */ jsxs3("div", { "data-slot": "search-skeleton-body", children: [
1367
- /* @__PURE__ */ jsx3("div", { "data-slot": "search-skeleton-block", "data-kind": "line-lg" }),
1368
- /* @__PURE__ */ jsx3("div", { "data-slot": "search-skeleton-block", "data-kind": "line-md" }),
1369
- /* @__PURE__ */ jsx3("div", { "data-slot": "search-skeleton-block", "data-kind": "line-sm" })
1370
- ] })
1371
- ] }, i)) })
1372
- ] });
756
+ function shouldPreservePaintedListingsOnRefetchFailure(options) {
757
+ return searchKeysRepresentSameQuery(
758
+ options.paintedSearchKey,
759
+ options.searchKey,
760
+ options.dictionary
761
+ );
1373
762
  }
1374
-
1375
- // src/react/use-public-search.ts
1376
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
1377
- import { usePathname, useRouter, useSearchParams } from "next/navigation";
1378
-
1379
- // src/internal/url.ts
1380
- var DEFAULT_BASE_URL = "https://app.garagem.ai";
1381
- function normalizeBaseUrl(baseUrl) {
1382
- const url = baseUrl ?? DEFAULT_BASE_URL;
1383
- return url.endsWith("/") ? url.slice(0, -1) : url;
763
+ function initialQueryDraft(pathname, search, dictionary) {
764
+ return readPublicSearch(pathname, search, dictionary).applied.query || "";
1384
765
  }
1385
- async function coerceSiteId(siteId) {
1386
- const raw = typeof siteId === "function" ? siteId() : siteId;
1387
- const value = await Promise.resolve(raw);
1388
- if (typeof value !== "string" || !value.trim()) {
1389
- throw new TypeError(
1390
- "Garagem SDK: siteId must be a string. Await resolveSiteId(...) before getListings / getSearchUi / queryListings."
1391
- );
1392
- }
1393
- return value;
766
+ function seedPublicSearchState(initial) {
767
+ return {
768
+ schema: initial?.schema ?? null,
769
+ listings: initial?.listings ?? [],
770
+ page: initial?.page ?? 1,
771
+ total: resolveSeedTotal(initial),
772
+ totalPages: initial?.totalPages ?? 1,
773
+ locationNames: initial?.locationNames ?? null,
774
+ catalogId: initial?.catalogId ?? null,
775
+ loading: !hasTrustedSearchSnapshot(initial)
776
+ };
1394
777
  }
1395
778
 
1396
- // src/fetchers.ts
1397
- async function callJson(url, init, fetchImpl) {
1398
- const response = await fetchImpl(url, init);
1399
- if (!response.ok) {
1400
- const text = await response.text().catch(() => "");
1401
- throw new GaragemSdkError(
1402
- `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${text ? ` \u2014 ${text.slice(0, 200)}` : ""}`,
1403
- { status: response.status, url }
1404
- );
779
+ // src/react/staged-filters-mirror.ts
780
+ var StagedFiltersMirror = class {
781
+ current;
782
+ constructor(initial = {}) {
783
+ this.current = initial;
1405
784
  }
1406
- return await response.json();
1407
- }
1408
- var GaragemSdkError = class extends Error {
1409
- status;
1410
- url;
1411
- constructor(message, info) {
1412
- super(message);
1413
- this.name = "GaragemSdkError";
1414
- this.status = info.status;
1415
- this.url = info.url;
785
+ get value() {
786
+ return this.current;
787
+ }
788
+ replace(next) {
789
+ this.current = next;
790
+ return this.current;
791
+ }
792
+ stage(filterId, value) {
793
+ this.current = applyPathFilter(this.current, filterId, value);
794
+ return this.current;
795
+ }
796
+ clear(keepFilterIds = []) {
797
+ this.current = clearStagedPathFilters(this.current, keepFilterIds);
798
+ return this.current;
1416
799
  }
1417
800
  };
1418
- async function getSearchUi(options) {
1419
- const { baseUrl, fetch: fetchImpl, next } = options;
1420
- const siteId = await coerceSiteId(options.siteId);
1421
- const base = normalizeBaseUrl(baseUrl);
1422
- const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search-ui`;
1423
- return callJson(
1424
- url,
1425
- { method: "GET", headers: { Accept: "application/json" }, next },
1426
- fetchImpl ?? fetch
1427
- );
1428
- }
1429
- async function queryListings(options) {
1430
- const { params, baseUrl, fetch: fetchImpl, next } = options;
1431
- const siteId = await coerceSiteId(options.siteId);
1432
- const base = normalizeBaseUrl(baseUrl);
1433
- const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;
1434
- return callJson(
1435
- url,
1436
- {
1437
- method: "POST",
1438
- headers: {
1439
- Accept: "application/json",
1440
- "Content-Type": "application/json"
1441
- },
1442
- body: JSON.stringify(params ?? {}),
1443
- next
1444
- },
1445
- fetchImpl ?? fetch
1446
- );
1447
- }
1448
801
 
1449
802
  // src/react/use-public-search.ts
1450
803
  async function resolveSiteIdInput(siteId) {
@@ -1455,26 +808,38 @@ function currentHref(pathname, search) {
1455
808
  return search ? `${pathname}?${search}` : pathname;
1456
809
  }
1457
810
  function usePublicSearch(options) {
1458
- const { siteId, baseUrl } = options;
811
+ const { siteId, baseUrl, initial, search: searchFromServer = "" } = options;
1459
812
  const router = useRouter();
1460
813
  const pathname = usePathname() || "/imoveis";
1461
- const searchParams = useSearchParams();
1462
- const search = searchParams.toString();
814
+ const search = searchFromServer;
815
+ const searchKey = search ? `${pathname}?${search}` : pathname;
816
+ const [seed] = useState(() => seedPublicSearchState(initial));
817
+ const keepSnapshotRef = useRef(hasTrustedSearchSnapshot(initial));
818
+ const lastSearchKeyRef = useRef(keepSnapshotRef.current ? searchKey : null);
1463
819
  const siteIdRef = useRef(siteId);
1464
820
  siteIdRef.current = siteId;
1465
821
  const siteIdToken = typeof siteId === "string" ? siteId : null;
1466
- const [catalogId, setCatalogId] = useState(null);
1467
- const [schema, setSchema] = useState(null);
1468
- const [listings, setListings] = useState([]);
1469
- const [page, setPage] = useState(1);
1470
- const [total, setTotal] = useState(0);
1471
- const [totalPages, setTotalPages] = useState(1);
1472
- const [loading, setLoading] = useState(true);
1473
- const [qDraft, setQDraft] = useState("");
1474
- const [staged, setStaged] = useState({});
822
+ const [catalogId, setCatalogId] = useState(seed.catalogId);
823
+ const [schema, setSchema] = useState(seed.schema);
824
+ const [listings, setListings] = useState(
825
+ seed.listings
826
+ );
827
+ const [page, setPage] = useState(seed.page);
828
+ const [total, setTotal] = useState(seed.total);
829
+ const [totalPages, setTotalPages] = useState(seed.totalPages);
830
+ const [loading, setLoading] = useState(seed.loading);
831
+ const [qDraft, setQDraft] = useState(
832
+ () => initialQueryDraft(pathname, search, initial?.schema?.dictionary)
833
+ );
834
+ const stagedMirrorRef = useRef(new StagedFiltersMirror());
835
+ const [staged, setStagedState] = useState({});
1475
836
  const [locationNames, setLocationNames] = useState(
1476
- null
837
+ seed.locationNames
1477
838
  );
839
+ const replaceStaged = useCallback((next) => {
840
+ stagedMirrorRef.current.replace(next);
841
+ setStagedState(next);
842
+ }, []);
1478
843
  const parsed = useMemo(
1479
844
  () => readPublicSearch(pathname, search, schema?.dictionary),
1480
845
  [pathname, search, schema?.dictionary]
@@ -1483,12 +848,12 @@ function usePublicSearch(options) {
1483
848
  setQDraft(parsed.applied.query || "");
1484
849
  }, [parsed.applied.query]);
1485
850
  const resetStagedFromUrl = useCallback(() => {
1486
- setStaged({ ...parsed.pathFilters });
1487
- }, [parsed.pathFilters]);
851
+ replaceStaged({ ...parsed.pathFilters });
852
+ }, [parsed.pathFilters, replaceStaged]);
1488
853
  useEffect(() => {
1489
- setStaged({ ...parsed.pathFilters });
1490
- }, [parsed.pathFilters]);
1491
- const locationsRef = useRef(null);
854
+ replaceStaged({ ...parsed.pathFilters });
855
+ }, [parsed.pathFilters, replaceStaged]);
856
+ const locationsRef = useRef(seed.locationNames);
1492
857
  useEffect(() => {
1493
858
  if (!schema) return;
1494
859
  const canonical = canonicalizeSearchHref(
@@ -1496,14 +861,20 @@ function usePublicSearch(options) {
1496
861
  search,
1497
862
  schema.dictionary
1498
863
  );
1499
- if (canonical) router.replace(canonical);
864
+ if (!canonical) return;
865
+ if (shouldAdvancePaintedSearchKeyOnCanonicalize()) {
866
+ lastSearchKeyRef.current = canonical;
867
+ }
868
+ router.replace(canonical);
1500
869
  }, [pathname, search, schema, router]);
1501
870
  useEffect(() => {
1502
871
  let active = true;
1503
- setCatalogId(null);
1504
- setSchema(null);
1505
- setListings([]);
1506
- setLoading(true);
872
+ if (!keepSnapshotRef.current) {
873
+ setCatalogId(null);
874
+ setSchema(null);
875
+ setListings([]);
876
+ setLoading(true);
877
+ }
1507
878
  resolveSiteIdInput(siteIdRef.current).then((id) => {
1508
879
  if (active) setCatalogId(id);
1509
880
  }).catch(() => {
@@ -1517,11 +888,13 @@ function usePublicSearch(options) {
1517
888
  if (!catalogId) return;
1518
889
  const id = catalogId;
1519
890
  let active = true;
1520
- locationsRef.current = null;
1521
- setLocationNames(null);
1522
- setSchema(null);
1523
- setListings([]);
1524
- setLoading(true);
891
+ if (!keepSnapshotRef.current) {
892
+ locationsRef.current = null;
893
+ setLocationNames(null);
894
+ setSchema(null);
895
+ setListings([]);
896
+ setLoading(true);
897
+ }
1525
898
  async function loadSchema() {
1526
899
  try {
1527
900
  const nextSchema = await getSearchUi({ siteId: id, baseUrl });
@@ -1540,14 +913,22 @@ function usePublicSearch(options) {
1540
913
  }
1541
914
  }
1542
915
  if (!active) return;
1543
- locationsRef.current = locations;
1544
- setLocationNames(locations);
916
+ const nextLocations = preferFetchedLocationNames(
917
+ locationsRef.current,
918
+ locations
919
+ );
920
+ locationsRef.current = nextLocations;
921
+ setLocationNames(nextLocations);
1545
922
  setSchema(nextSchema);
923
+ keepSnapshotRef.current = false;
1546
924
  } catch {
1547
925
  if (active) {
1548
- locationsRef.current = null;
1549
- setLocationNames(null);
1550
- setSchema(null);
926
+ if (shouldClearPaintedSearchOnSchemaFailure(keepSnapshotRef.current)) {
927
+ keepSnapshotRef.current = false;
928
+ locationsRef.current = null;
929
+ setLocationNames(null);
930
+ setSchema(null);
931
+ }
1551
932
  setLoading(false);
1552
933
  }
1553
934
  }
@@ -1563,7 +944,13 @@ function usePublicSearch(options) {
1563
944
  const id = catalogId;
1564
945
  let active = true;
1565
946
  async function loadListings() {
1566
- setLoading(true);
947
+ if (shouldSetLoadingOnSearchKeyChange({
948
+ paintedSearchKey: lastSearchKeyRef.current,
949
+ searchKey,
950
+ dictionary: currentSchema.dictionary
951
+ })) {
952
+ setLoading(true);
953
+ }
1567
954
  try {
1568
955
  const { pathFilters, applied } = readPublicSearch(
1569
956
  pathname,
@@ -1585,15 +972,24 @@ function usePublicSearch(options) {
1585
972
  setPage(response.page || 1);
1586
973
  setTotal(response.total || 0);
1587
974
  setTotalPages(response.totalPages || 1);
975
+ lastSearchKeyRef.current = searchKey;
976
+ keepSnapshotRef.current = false;
1588
977
  } catch {
1589
- if (active) {
978
+ if (active && !shouldPreservePaintedListingsOnRefetchFailure({
979
+ paintedSearchKey: lastSearchKeyRef.current,
980
+ searchKey,
981
+ dictionary: currentSchema.dictionary
982
+ })) {
1590
983
  setListings([]);
1591
984
  setPage(1);
1592
985
  setTotal(0);
1593
986
  setTotalPages(1);
987
+ keepSnapshotRef.current = false;
1594
988
  }
1595
989
  } finally {
1596
- if (active) setLoading(false);
990
+ if (active) {
991
+ setLoading(false);
992
+ }
1597
993
  }
1598
994
  }
1599
995
  loadListings();
@@ -1621,15 +1017,28 @@ function usePublicSearch(options) {
1621
1017
  },
1622
1018
  [go, pathname, search, schema, parsed.pathFilters]
1623
1019
  );
1020
+ const setStaged = useCallback(
1021
+ (next) => {
1022
+ replaceStaged(next);
1023
+ },
1024
+ [replaceStaged]
1025
+ );
1624
1026
  const stageFilter = useCallback((filterId, value) => {
1625
- setStaged((current) => applyPathFilter(current, filterId, value));
1027
+ setStagedState(stagedMirrorRef.current.stage(filterId, value));
1626
1028
  }, []);
1627
1029
  const applyStaged = useCallback(() => {
1628
1030
  if (!schema) return;
1629
- go(hrefForPathFilters(pathname, search, schema.dictionary, staged));
1630
- }, [go, pathname, search, schema, staged]);
1031
+ go(
1032
+ hrefForPathFilters(
1033
+ pathname,
1034
+ search,
1035
+ schema.dictionary,
1036
+ stagedMirrorRef.current.value
1037
+ )
1038
+ );
1039
+ }, [go, pathname, search, schema]);
1631
1040
  const clearStaged = useCallback(() => {
1632
- setStaged((current) => clearStagedPathFilters(current));
1041
+ setStagedState(stagedMirrorRef.current.clear());
1633
1042
  }, []);
1634
1043
  const submitQuery = useCallback(() => {
1635
1044
  if (!schema) return;
@@ -1701,10 +1110,6 @@ function usePublicSearch(options) {
1701
1110
  };
1702
1111
  }
1703
1112
  export {
1704
- ListingCard,
1705
- ListingDetailFields,
1706
- ResultsSkeleton,
1707
- SearchChromeStyles,
1708
1113
  usePublicSearch
1709
1114
  };
1710
1115
  //# sourceMappingURL=react.mjs.map