@garagem-ai/site-sdk 0.2.0 → 0.4.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/index.mjs CHANGED
@@ -18,6 +18,15 @@ function normalizeBaseUrl(baseUrl) {
18
18
  const url = baseUrl ?? DEFAULT_BASE_URL;
19
19
  return url.endsWith("/") ? url.slice(0, -1) : url;
20
20
  }
21
+ async function coerceSiteId(siteId) {
22
+ const value = await Promise.resolve(siteId);
23
+ if (typeof value !== "string" || !value.trim()) {
24
+ throw new TypeError(
25
+ "Garagem SDK: siteId must be a string. Await resolveSiteId(...) before getListings / getSearchUi / queryListings."
26
+ );
27
+ }
28
+ return value;
29
+ }
21
30
  function buildListingFiltersQuery(filters) {
22
31
  const params = new URLSearchParams();
23
32
  if (!filters) return params;
@@ -57,7 +66,8 @@ var GaragemSdkError = class extends Error {
57
66
  }
58
67
  };
59
68
  async function getListings(options) {
60
- const { siteId, filters, baseUrl, fetch: fetchImpl, next } = options;
69
+ const { filters, baseUrl, fetch: fetchImpl, next } = options;
70
+ const siteId = await coerceSiteId(options.siteId);
61
71
  const base = normalizeBaseUrl(baseUrl);
62
72
  const params = buildListingFiltersQuery(filters);
63
73
  const qs = params.size > 0 ? `?${params.toString()}` : "";
@@ -73,13 +83,8 @@ async function getListings(options) {
73
83
  };
74
84
  }
75
85
  async function getListing(options) {
76
- const {
77
- siteId,
78
- listingId: rawListingId,
79
- baseUrl,
80
- fetch: fetchImpl,
81
- next
82
- } = options;
86
+ const { listingId: rawListingId, baseUrl, fetch: fetchImpl, next } = options;
87
+ const siteId = await coerceSiteId(options.siteId);
83
88
  const listingId = listingLookupKey(rawListingId ?? "");
84
89
  if (!listingId || listingId === "undefined" || listingId === "null") {
85
90
  throw new TypeError("getListing: `listingId` is required");
@@ -95,7 +100,8 @@ async function getListing(options) {
95
100
  );
96
101
  }
97
102
  async function getSite(options) {
98
- const { siteId, domain, baseUrl, fetch: fetchImpl, next } = options;
103
+ const { domain, baseUrl, fetch: fetchImpl, next } = options;
104
+ const siteId = options.siteId ? await coerceSiteId(options.siteId) : void 0;
99
105
  if (!siteId && !domain) {
100
106
  throw new TypeError(
101
107
  "getSite: provide exactly one of `siteId` or `domain`."
@@ -133,7 +139,8 @@ async function getSite(options) {
133
139
  };
134
140
  }
135
141
  async function searchListings(options) {
136
- const { siteId, params, baseUrl, fetch: fetchImpl, next } = options;
142
+ const { params, baseUrl, fetch: fetchImpl, next } = options;
143
+ const siteId = await coerceSiteId(options.siteId);
137
144
  if (!params || typeof params.q !== "string") {
138
145
  throw new TypeError(
139
146
  "Garagem SDK: searchListings requires `params.q` (Typesense query string)."
@@ -152,15 +159,45 @@ async function searchListings(options) {
152
159
  fetchImpl ?? fetch
153
160
  );
154
161
  }
162
+ async function getSearchUi(options) {
163
+ const { baseUrl, fetch: fetchImpl, next } = options;
164
+ const siteId = await coerceSiteId(options.siteId);
165
+ const base = normalizeBaseUrl(baseUrl);
166
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search-ui`;
167
+ return callJson(
168
+ url,
169
+ { method: "GET", headers: { Accept: "application/json" }, next },
170
+ fetchImpl ?? fetch
171
+ );
172
+ }
173
+ async function queryListings(options) {
174
+ const { params, baseUrl, fetch: fetchImpl, next } = options;
175
+ const siteId = await coerceSiteId(options.siteId);
176
+ const base = normalizeBaseUrl(baseUrl);
177
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;
178
+ return callJson(
179
+ url,
180
+ {
181
+ method: "POST",
182
+ headers: {
183
+ Accept: "application/json",
184
+ "Content-Type": "application/json"
185
+ },
186
+ body: JSON.stringify(params ?? {}),
187
+ next
188
+ },
189
+ fetchImpl ?? fetch
190
+ );
191
+ }
155
192
  async function getSimilarListings(options) {
156
193
  const {
157
- siteId,
158
194
  listingId: rawListingId,
159
195
  limit,
160
196
  baseUrl,
161
197
  fetch: fetchImpl,
162
198
  next
163
199
  } = options;
200
+ const siteId = await coerceSiteId(options.siteId);
164
201
  const listingId = listingLookupKey(rawListingId ?? "");
165
202
  if (!listingId || listingId === "undefined" || listingId === "null") {
166
203
  throw new TypeError("getSimilarListings: `listingId` is required");
@@ -185,7 +222,8 @@ async function getSimilarListings(options) {
185
222
  };
186
223
  }
187
224
  async function getCmsCollections(options) {
188
- const { siteId, baseUrl, fetch: fetchImpl, next } = options;
225
+ const { baseUrl, fetch: fetchImpl, next } = options;
226
+ const siteId = await coerceSiteId(options.siteId);
189
227
  const base = normalizeBaseUrl(baseUrl);
190
228
  const url = `${base}/api/sites/${encodeURIComponent(siteId)}/cms/collections`;
191
229
  const data = await callJson(
@@ -196,7 +234,8 @@ async function getCmsCollections(options) {
196
234
  return data.collections ?? [];
197
235
  }
198
236
  async function getCmsCollection(options) {
199
- const { siteId, slug, baseUrl, fetch: fetchImpl, next } = options;
237
+ const { slug, baseUrl, fetch: fetchImpl, next } = options;
238
+ const siteId = await coerceSiteId(options.siteId);
200
239
  if (!slug) {
201
240
  throw new TypeError("getCmsCollection: `slug` is required");
202
241
  }
@@ -216,7 +255,6 @@ async function getCmsCollection(options) {
216
255
  }
217
256
  async function getCmsEntries(options) {
218
257
  const {
219
- siteId,
220
258
  collection,
221
259
  limit,
222
260
  offset,
@@ -224,6 +262,7 @@ async function getCmsEntries(options) {
224
262
  fetch: fetchImpl,
225
263
  next
226
264
  } = options;
265
+ const siteId = await coerceSiteId(options.siteId);
227
266
  if (!collection) {
228
267
  throw new TypeError("getCmsEntries: `collection` is required");
229
268
  }
@@ -252,7 +291,8 @@ async function getCmsEntries(options) {
252
291
  };
253
292
  }
254
293
  async function getCmsEntry(options) {
255
- const { siteId, collection, slug, baseUrl, fetch: fetchImpl, next } = options;
294
+ const { collection, slug, baseUrl, fetch: fetchImpl, next } = options;
295
+ const siteId = await coerceSiteId(options.siteId);
256
296
  if (!collection) {
257
297
  throw new TypeError("getCmsEntry: `collection` is required");
258
298
  }
@@ -274,6 +314,805 @@ async function getCmsEntry(options) {
274
314
  return data;
275
315
  }
276
316
 
317
+ // src/presentation.ts
318
+ var SEARCH_CSS_VARS = {
319
+ cardRadius: "--garagem-listing-card-radius",
320
+ cardGap: "--garagem-listing-card-gap",
321
+ priceSize: "--garagem-listing-price-size",
322
+ mediaRatio: "--garagem-listing-media-ratio"
323
+ };
324
+ var SEARCH_CSS_RECIPE = `:root {
325
+ ${SEARCH_CSS_VARS.cardRadius}: 0.75rem;
326
+ ${SEARCH_CSS_VARS.cardGap}: 1.5rem;
327
+ ${SEARCH_CSS_VARS.priceSize}: 1.125rem;
328
+ ${SEARCH_CSS_VARS.mediaRatio}: 4 / 3;
329
+ }
330
+ `;
331
+ function formatListingPrice(amount, locale = "pt-BR", currency = "BRL") {
332
+ if (amount == null) return "Sob consulta";
333
+ try {
334
+ return new Intl.NumberFormat(locale, {
335
+ style: "currency",
336
+ currency,
337
+ minimumFractionDigits: 0,
338
+ maximumFractionDigits: 0
339
+ }).format(amount);
340
+ } catch {
341
+ return `${currency} ${amount}`;
342
+ }
343
+ }
344
+ function formatGroupedInteger(value, locale = "pt-BR") {
345
+ const digits = String(value ?? "").replace(/\D/g, "");
346
+ if (!digits) return "";
347
+ const amount = Number.parseInt(digits, 10);
348
+ if (!Number.isFinite(amount)) return "";
349
+ return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(
350
+ amount
351
+ );
352
+ }
353
+ function parseGroupedInteger(value) {
354
+ if (typeof value === "number") {
355
+ return Number.isFinite(value) ? Math.trunc(value) : void 0;
356
+ }
357
+ const digits = String(value ?? "").replace(/\D/g, "");
358
+ if (!digits) return void 0;
359
+ const amount = Number.parseInt(digits, 10);
360
+ return Number.isFinite(amount) ? amount : void 0;
361
+ }
362
+ function formatAreaM2(area) {
363
+ if (area == null || !Number.isFinite(area)) return null;
364
+ return `${area} m\xB2`;
365
+ }
366
+ function listingBusinessLabel(businessType) {
367
+ return businessType === "rental" ? "Aluguel" : "Venda";
368
+ }
369
+
370
+ // src/listing-card-model.ts
371
+ function listingLocationLabel(location) {
372
+ return [location.neighborhood, location.city, location.state].map((part) => part ? String(part).trim() : "").filter(Boolean).join(", ");
373
+ }
374
+ function toListingCardModel(listing) {
375
+ const isPrivate = listing.priceVisibility === "private";
376
+ const area = listing.property?.usableArea ?? listing.property?.totalArea;
377
+ return {
378
+ href: listingPublicPath(listing),
379
+ title: listing.title,
380
+ businessType: listing.businessType,
381
+ businessLabel: listingBusinessLabel(listing.businessType),
382
+ priceVisibility: listing.priceVisibility,
383
+ price: listing.price,
384
+ priceLabel: isPrivate ? "Sob consulta" : formatListingPrice(listing.price),
385
+ pricePeriod: listing.businessType === "rental" && !isPrivate && listing.price != null ? "/m\xEAs" : null,
386
+ locationLabel: listingLocationLabel(listing.location || {}),
387
+ propertyType: listing.property?.type ?? null,
388
+ coverSrc: listing.coverImage?.src ?? null,
389
+ coverAlt: listing.coverImage?.alt ?? listing.title,
390
+ bedrooms: listing.property?.bedrooms ?? null,
391
+ bathrooms: listing.property?.bathrooms ?? null,
392
+ parkingSpaces: listing.property?.parkingSpaces ?? null,
393
+ areaM2: area ?? null
394
+ };
395
+ }
396
+
397
+ // ../search-url/types.ts
398
+ var SEARCH_BASE_ROUTE = "imoveis";
399
+ var MAX_PAGE = 1e4;
400
+ var MAX_LOC_GROUPS = 20;
401
+ var DEFAULT_MIN_PRICE = 0;
402
+ var DEFAULT_MAX_PRICE = 1e9;
403
+ var DEFAULT_MIN_AREA = 0;
404
+ var DEFAULT_MAX_AREA = 1e5;
405
+ var SORT_URL_TOKENS = [
406
+ "preco-asc",
407
+ "preco-desc",
408
+ "area-asc",
409
+ "area-desc"
410
+ ];
411
+
412
+ // ../search-url/slugify.ts
413
+ function slugifyForUrl(text) {
414
+ if (!text) return "";
415
+ const withDashes = text.replace(/([a-z])([A-Z])/g, "$1-$2");
416
+ return withDashes.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^\w\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").trim();
417
+ }
418
+
419
+ // ../search-url/catalog.ts
420
+ var PROPERTY_TYPE_SLUG_ALIASES = {
421
+ rural: ["chacara", "fazenda", "sitio"]
422
+ };
423
+ function buildListingTypeOptions(enabled) {
424
+ const flags = enabled ?? { sale: true, rental: true };
425
+ const out = [];
426
+ if (flags.sale !== false) {
427
+ out.push({ id: "sale", slug: "venda", label: "Venda" });
428
+ }
429
+ if (flags.rental !== false) {
430
+ out.push({ id: "rental", slug: "aluguel", label: "Aluguel" });
431
+ }
432
+ return out;
433
+ }
434
+ function emptySearchUrlDictionary() {
435
+ return {
436
+ listingTypes: buildListingTypeOptions(null),
437
+ propertyTypes: [],
438
+ propertyFeatures: [],
439
+ buildingAmenities: []
440
+ };
441
+ }
442
+ function norm(value) {
443
+ return slugifyForUrl(value) || value.toLowerCase();
444
+ }
445
+ function matchOptionId(segment, options, extraAliases) {
446
+ const n = norm(segment);
447
+ for (const option of options) {
448
+ const aliases = extraAliases?.[option.id] ?? [];
449
+ const candidates = [option.id, option.slug, option.label, ...aliases];
450
+ if (candidates.some((c) => norm(c) === n)) return option.id;
451
+ }
452
+ return null;
453
+ }
454
+ function optionSlugById(id, options) {
455
+ const option = options.find((item) => item.id === id);
456
+ return option?.slug ?? null;
457
+ }
458
+ var LISTING_TYPE_ALIASES = {
459
+ sale: ["comprar"],
460
+ rental: ["alugar"]
461
+ };
462
+
463
+ // ../search-url/path.ts
464
+ function toArray(value) {
465
+ if (value === void 0) return [];
466
+ return Array.isArray(value) ? value : [value];
467
+ }
468
+ function formatNumeric(value) {
469
+ return Array.isArray(value) ? value.join("-") : String(value);
470
+ }
471
+ function formatRange(min, max, unit) {
472
+ return `de-${min}-a-${max}-${unit}`;
473
+ }
474
+ function formatSuiteSuffix(value) {
475
+ const values = Array.isArray(value) ? value : [value];
476
+ const firstValue = values[0] ?? 0;
477
+ return firstValue === 0 || firstValue === 1 ? "suite" : "suites";
478
+ }
479
+ function composeSearchPublicPath(filters, dictionary = emptySearchUrlDictionary()) {
480
+ const segments = [];
481
+ const listingType = filters.listingType;
482
+ if (listingType) {
483
+ segments.push(
484
+ optionSlugById(listingType, dictionary.listingTypes) || slugifyForUrl(listingType)
485
+ );
486
+ }
487
+ for (const propertyType of toArray(filters.propertyType)) {
488
+ segments.push(
489
+ optionSlugById(propertyType, dictionary.propertyTypes) || slugifyForUrl(propertyType)
490
+ );
491
+ }
492
+ const location = filters.location;
493
+ if (location) {
494
+ if (location.state) segments.push(slugifyForUrl(location.state));
495
+ if (location.city) segments.push(slugifyForUrl(location.city));
496
+ if (location.neighborhood)
497
+ segments.push(slugifyForUrl(location.neighborhood));
498
+ if (location.street) segments.push(slugifyForUrl(location.street));
499
+ }
500
+ if (filters.bedrooms !== void 0) {
501
+ segments.push(`${formatNumeric(filters.bedrooms)}-quartos`);
502
+ }
503
+ if (filters.bathrooms !== void 0) {
504
+ segments.push(`${formatNumeric(filters.bathrooms)}-banheiros`);
505
+ }
506
+ if (filters.suites !== void 0) {
507
+ const suffix = formatSuiteSuffix(filters.suites);
508
+ segments.push(`${formatNumeric(filters.suites)}-${suffix}`);
509
+ }
510
+ if (filters.parkingSpots !== void 0) {
511
+ segments.push(`${formatNumeric(filters.parkingSpots)}-vagas`);
512
+ }
513
+ if (filters.price && (filters.price.min !== void 0 || filters.price.max !== void 0)) {
514
+ const min = filters.price.min ?? DEFAULT_MIN_PRICE;
515
+ const max = filters.price.max ?? DEFAULT_MAX_PRICE;
516
+ segments.push(formatRange(min, max, "reais"));
517
+ }
518
+ if (filters.area && (filters.area.min !== void 0 || filters.area.max !== void 0)) {
519
+ const min = filters.area.min ?? DEFAULT_MIN_AREA;
520
+ const max = filters.area.max ?? DEFAULT_MAX_AREA;
521
+ segments.push(formatRange(min, max, "m2"));
522
+ }
523
+ const seenAmenities = /* @__PURE__ */ new Set();
524
+ for (const id of filters.propertyFeatures ?? []) {
525
+ const slug = optionSlugById(id, dictionary.propertyFeatures) || slugifyForUrl(id);
526
+ if (!slug || seenAmenities.has(slug)) continue;
527
+ seenAmenities.add(slug);
528
+ segments.push(slug);
529
+ }
530
+ for (const id of filters.buildingAmenities ?? []) {
531
+ const slug = optionSlugById(id, dictionary.buildingAmenities) || slugifyForUrl(id);
532
+ if (!slug || seenAmenities.has(slug)) continue;
533
+ seenAmenities.add(slug);
534
+ segments.push(slug);
535
+ }
536
+ const path = segments.filter(Boolean).join("/");
537
+ return path ? `/${SEARCH_BASE_ROUTE}/${path}` : `/${SEARCH_BASE_ROUTE}`;
538
+ }
539
+ var BEDROOMS = /^(\d+(?:-\d+)*)-quartos?$/;
540
+ var BATHROOMS = /^(\d+(?:-\d+)*)-banheiros?$/;
541
+ var SUITES = /^(\d+(?:-\d+)*)-suites?$/;
542
+ var PARKING = /^(\d+(?:-\d+)*)-vagas?$/;
543
+ var PRICE = /^de-(\d+)-a-(\d+)-(reais|real)$/;
544
+ var AREA = /^de-(\d+)-a-(\d+)-(m2|m²)$/;
545
+ function parseNumericList(raw) {
546
+ return raw.split("-").map((part) => Number(part)).filter((n) => Number.isFinite(n));
547
+ }
548
+ function collapse(values) {
549
+ return values.length === 1 ? values[0] : values;
550
+ }
551
+ function parseSearchPublicPath(pathname, dictionary = emptySearchUrlDictionary()) {
552
+ const raw = pathname.split(/[?#]/)[0] ?? "";
553
+ let segments = raw.replace(/^\//, "").split("/").filter(Boolean);
554
+ if (segments[0] === SEARCH_BASE_ROUTE) segments = segments.slice(1);
555
+ if (segments.some((segment) => segment.includes("."))) return null;
556
+ if (segments.some((segment) => segment.toLowerCase().startsWith("id-"))) {
557
+ return null;
558
+ }
559
+ const filters = {};
560
+ const locationParts = [];
561
+ const propertyTypes = [];
562
+ const propertyFeatures = [];
563
+ const buildingAmenities = [];
564
+ for (const segment of segments) {
565
+ const lower = segment.toLowerCase();
566
+ const listingType = matchOptionId(
567
+ segment,
568
+ dictionary.listingTypes,
569
+ LISTING_TYPE_ALIASES
570
+ );
571
+ if (listingType && !filters.listingType) {
572
+ filters.listingType = listingType;
573
+ continue;
574
+ }
575
+ const propertyType = matchOptionId(
576
+ segment,
577
+ dictionary.propertyTypes,
578
+ PROPERTY_TYPE_SLUG_ALIASES
579
+ );
580
+ if (propertyType) {
581
+ propertyTypes.push(propertyType);
582
+ continue;
583
+ }
584
+ const bedrooms = lower.match(BEDROOMS);
585
+ if (bedrooms) {
586
+ filters.bedrooms = collapse(parseNumericList(bedrooms[1]));
587
+ continue;
588
+ }
589
+ const bathrooms = lower.match(BATHROOMS);
590
+ if (bathrooms) {
591
+ filters.bathrooms = collapse(parseNumericList(bathrooms[1]));
592
+ continue;
593
+ }
594
+ const suites = lower.match(SUITES);
595
+ if (suites) {
596
+ filters.suites = collapse(parseNumericList(suites[1]));
597
+ continue;
598
+ }
599
+ const parking = lower.match(PARKING);
600
+ if (parking) {
601
+ filters.parkingSpots = collapse(parseNumericList(parking[1]));
602
+ continue;
603
+ }
604
+ const price = lower.match(PRICE);
605
+ if (price) {
606
+ filters.price = { min: Number(price[1]), max: Number(price[2]) };
607
+ continue;
608
+ }
609
+ const area = lower.match(AREA);
610
+ if (area) {
611
+ filters.area = { min: Number(area[1]), max: Number(area[2]) };
612
+ continue;
613
+ }
614
+ const featureId = matchOptionId(segment, dictionary.propertyFeatures);
615
+ if (featureId) {
616
+ propertyFeatures.push(featureId);
617
+ continue;
618
+ }
619
+ const amenityId = matchOptionId(segment, dictionary.buildingAmenities);
620
+ if (amenityId) {
621
+ buildingAmenities.push(amenityId);
622
+ continue;
623
+ }
624
+ locationParts.push(segment);
625
+ }
626
+ if (propertyTypes.length === 1) filters.propertyType = propertyTypes[0];
627
+ else if (propertyTypes.length > 1) filters.propertyType = propertyTypes;
628
+ if (propertyFeatures.length) filters.propertyFeatures = propertyFeatures;
629
+ if (buildingAmenities.length) filters.buildingAmenities = buildingAmenities;
630
+ const location = locationFromPathLeftovers(locationParts);
631
+ if (location) filters.location = location;
632
+ return filters;
633
+ }
634
+ var PATH_STREET_PREFIX = /^(rua|r|avenida|av|alameda|al|travessa|tv|estrada|rodovia|rod)-/i;
635
+ function locationFromPathLeftovers(parts) {
636
+ if (parts.length === 0) return void 0;
637
+ if (parts.length === 1) {
638
+ const value = parts[0];
639
+ if (PATH_STREET_PREFIX.test(value)) return { street: value };
640
+ if (/^[a-z]{2}$/i.test(value)) return { state: value };
641
+ return { neighborhood: value };
642
+ }
643
+ const [state, city, neighborhood, street] = parts;
644
+ return {
645
+ ...state ? { state } : {},
646
+ ...city ? { city } : {},
647
+ ...neighborhood ? { neighborhood } : {},
648
+ ...street ? { street } : {}
649
+ };
650
+ }
651
+
652
+ // ../search-url/applied-query.ts
653
+ var SORT_SET = new Set(SORT_URL_TOKENS);
654
+ function isSortToken(value) {
655
+ return SORT_SET.has(value);
656
+ }
657
+ function normalizeAppliedSearchQuery(query) {
658
+ if (query.loc && query.loc.length > 0) {
659
+ const { query: _query, ...rest } = query;
660
+ return rest;
661
+ }
662
+ return query;
663
+ }
664
+ function parseAppliedSearchQuery(search) {
665
+ const params = search instanceof URLSearchParams ? search : new URLSearchParams(search.startsWith("?") ? search.slice(1) : search);
666
+ const result = {};
667
+ const pageRaw = params.get("page");
668
+ if (pageRaw) {
669
+ const page = Number.parseInt(pageRaw, 10);
670
+ if (Number.isFinite(page) && page > 1) {
671
+ result.page = Math.min(page, MAX_PAGE);
672
+ }
673
+ }
674
+ const sort = params.get("ordenar");
675
+ if (sort && isSortToken(sort)) result.sort = sort;
676
+ const q = params.get("q")?.trim();
677
+ if (q) result.query = q;
678
+ const loc = params.getAll("loc").map((value) => value.trim()).filter(Boolean).slice(0, MAX_LOC_GROUPS);
679
+ if (loc.length > 0) result.loc = loc;
680
+ return normalizeAppliedSearchQuery(result);
681
+ }
682
+ var APPLIED_QUERY_KEYS = ["page", "ordenar", "q", "loc"];
683
+ function serializeAppliedSearchQuery(query) {
684
+ const normalized = normalizeAppliedSearchQuery(query);
685
+ const params = new URLSearchParams();
686
+ if (normalized.page !== void 0 && normalized.page > 1) {
687
+ params.set("page", String(Math.min(normalized.page, MAX_PAGE)));
688
+ }
689
+ if (normalized.sort && isSortToken(normalized.sort)) {
690
+ params.set("ordenar", normalized.sort);
691
+ }
692
+ const text = normalized.query?.trim();
693
+ if (text) params.set("q", text);
694
+ for (const value of (normalized.loc ?? []).slice(0, MAX_LOC_GROUPS)) {
695
+ const trimmed = value.trim();
696
+ if (trimmed) params.append("loc", trimmed);
697
+ }
698
+ return params;
699
+ }
700
+ function mergeAppliedSearchQueryIntoSearch(existing, query) {
701
+ const params = existing instanceof URLSearchParams ? new URLSearchParams(existing) : new URLSearchParams(
702
+ existing.startsWith("?") ? existing.slice(1) : existing
703
+ );
704
+ for (const key of APPLIED_QUERY_KEYS) {
705
+ params.delete(key);
706
+ }
707
+ const serialized = serializeAppliedSearchQuery(query);
708
+ serialized.forEach((value, key) => {
709
+ if (key === "loc") {
710
+ params.append("loc", value);
711
+ } else {
712
+ params.set(key, value);
713
+ }
714
+ });
715
+ return params;
716
+ }
717
+ function reduceAppliedSearchQuery(prev, change) {
718
+ switch (change.type) {
719
+ case "sort": {
720
+ const next = { ...prev };
721
+ delete next.page;
722
+ if (change.sort) next.sort = change.sort;
723
+ else delete next.sort;
724
+ return normalizeAppliedSearchQuery(next);
725
+ }
726
+ case "applyFilters": {
727
+ const next = { ...prev };
728
+ delete next.page;
729
+ return normalizeAppliedSearchQuery(next);
730
+ }
731
+ case "query": {
732
+ const next = { ...prev };
733
+ delete next.page;
734
+ const trimmed = change.query.trim();
735
+ if (trimmed) {
736
+ next.query = trimmed;
737
+ delete next.loc;
738
+ } else {
739
+ delete next.query;
740
+ }
741
+ return normalizeAppliedSearchQuery(next);
742
+ }
743
+ case "loc": {
744
+ const next = { ...prev };
745
+ delete next.page;
746
+ delete next.query;
747
+ const loc = change.loc.map((value) => value.trim()).filter(Boolean).slice(0, MAX_LOC_GROUPS);
748
+ if (loc.length > 0) next.loc = loc;
749
+ else delete next.loc;
750
+ return normalizeAppliedSearchQuery(next);
751
+ }
752
+ case "page": {
753
+ const next = { ...prev };
754
+ if (change.page <= 1) delete next.page;
755
+ else next.page = Math.min(change.page, MAX_PAGE);
756
+ return normalizeAppliedSearchQuery(next);
757
+ }
758
+ default: {
759
+ const _exhaustive = change;
760
+ return _exhaustive;
761
+ }
762
+ }
763
+ }
764
+ function composeSearchPublicHref(pathname, query, existingSearch) {
765
+ const params = existingSearch ? mergeAppliedSearchQueryIntoSearch(existingSearch, query) : serializeAppliedSearchQuery(query);
766
+ const qs = params.toString();
767
+ return qs ? `${pathname}?${qs}` : pathname;
768
+ }
769
+
770
+ // src/applied-query.ts
771
+ function parseAppliedSearchQuery2(search) {
772
+ return parseAppliedSearchQuery(search);
773
+ }
774
+ function serializeAppliedSearchQuery2(query) {
775
+ return serializeAppliedSearchQuery(query);
776
+ }
777
+ function mergeAppliedSearchQueryIntoSearch2(existing, query) {
778
+ return mergeAppliedSearchQueryIntoSearch(existing, query);
779
+ }
780
+ function reduceAppliedSearchQuery2(prev, change) {
781
+ return reduceAppliedSearchQuery(prev, change);
782
+ }
783
+ function composeSearchPublicHref2(pathname, query, existingSearch) {
784
+ return composeSearchPublicHref(pathname, query, existingSearch);
785
+ }
786
+
787
+ // src/loc-params.ts
788
+ function pathLocationToFilterInput(location) {
789
+ if (!location || typeof location !== "object") return null;
790
+ const { state, city, neighborhood, street } = location;
791
+ const levels = [];
792
+ if (state) levels.push(state);
793
+ if (city) levels.push(city);
794
+ if (neighborhood) levels.push(neighborhood);
795
+ if (street) levels.push(street);
796
+ if (levels.length === 0) return null;
797
+ if (levels.length === 1) {
798
+ if (state) return { type: "state", value: state };
799
+ if (city) return { type: "city", value: city };
800
+ if (neighborhood) return { type: "neighborhood", value: neighborhood };
801
+ if (street) return { type: "street", value: street };
802
+ }
803
+ return { type: "path", value: levels.join("/") };
804
+ }
805
+
806
+ // src/path.ts
807
+ function composeSearchPublicPath2(filters, dictionary) {
808
+ return dictionary ? composeSearchPublicPath(filters, dictionary) : composeSearchPublicPath(filters);
809
+ }
810
+ function parseSearchPublicPath2(pathname, dictionary) {
811
+ return dictionary ? parseSearchPublicPath(pathname, dictionary) : parseSearchPublicPath(pathname);
812
+ }
813
+ function pathFiltersToQueryFilters(pathFilters) {
814
+ const result = {};
815
+ if (pathFilters.listingType !== void 0) {
816
+ result.listing_type = pathFilters.listingType;
817
+ }
818
+ if (pathFilters.propertyType !== void 0) {
819
+ result.property_type = pathFilters.propertyType;
820
+ }
821
+ if (pathFilters.bedrooms !== void 0) {
822
+ result.property_bedrooms = pathFilters.bedrooms;
823
+ }
824
+ if (pathFilters.bathrooms !== void 0) {
825
+ result.property_bathrooms = pathFilters.bathrooms;
826
+ }
827
+ if (pathFilters.suites !== void 0) {
828
+ result.property_suites = pathFilters.suites;
829
+ }
830
+ if (pathFilters.parkingSpots !== void 0) {
831
+ result.property_parking_spots = pathFilters.parkingSpots;
832
+ }
833
+ if (pathFilters.price !== void 0) {
834
+ result.price = pathFilters.price;
835
+ }
836
+ if (pathFilters.area !== void 0) {
837
+ result.property_area_total = pathFilters.area;
838
+ }
839
+ if (pathFilters.propertyFeatures !== void 0) {
840
+ result.propertyFeatures = pathFilters.propertyFeatures;
841
+ }
842
+ if (pathFilters.buildingAmenities !== void 0) {
843
+ result.buildingAmenities = pathFilters.buildingAmenities;
844
+ }
845
+ return result;
846
+ }
847
+
848
+ // src/search-engine.ts
849
+ var PATH_FILTER_IDS = {
850
+ listing_type: "listingType",
851
+ property_type: "propertyType",
852
+ property_bedrooms: "bedrooms",
853
+ property_bathrooms: "bathrooms",
854
+ property_suites: "suites",
855
+ property_parking_spots: "parkingSpots",
856
+ price: "price",
857
+ property_area_total: "area",
858
+ propertyFeatures: "propertyFeatures",
859
+ buildingAmenities: "buildingAmenities"
860
+ };
861
+ var FORBIDDEN_SEARCH_QUERY_KEYS = [
862
+ "tipo",
863
+ "quartos",
864
+ "tipo-imovel",
865
+ "banheiros",
866
+ "vagas"
867
+ ];
868
+ var SEARCH_SORT_RELEVANCE = {
869
+ id: "",
870
+ label: "Mais relevantes"
871
+ };
872
+ function searchSortOptions(sorts) {
873
+ const fromApi = (sorts || []).filter((sort) => sort.id);
874
+ return [
875
+ { id: SEARCH_SORT_RELEVANCE.id, label: SEARCH_SORT_RELEVANCE.label },
876
+ ...fromApi
877
+ ];
878
+ }
879
+ var TOOLBAR_PRIMARY_FILTER_IDS = [
880
+ "price",
881
+ "property_bedrooms"
882
+ ];
883
+ var HIDDEN_FILTER_IDS = /* @__PURE__ */ new Set(["property_suites"]);
884
+ function toFiniteNumber(value) {
885
+ if (value === "" || value == null) return void 0;
886
+ const n = Number(value);
887
+ return Number.isFinite(n) ? n : void 0;
888
+ }
889
+ function pathnameOnly(pathname) {
890
+ return String(pathname || "").split(/[?#]/)[0] || "/";
891
+ }
892
+ function isListingDetailPath(pathname) {
893
+ const parts = pathnameOnly(pathname).split("/").filter(Boolean);
894
+ const last = parts[parts.length - 1] || "";
895
+ return last.toLowerCase().startsWith("id-");
896
+ }
897
+ function readPublicSearch(pathname, search, dictionary) {
898
+ const pathFilters = parseSearchPublicPath2(pathnameOnly(pathname), dictionary) || {};
899
+ const applied = parseAppliedSearchQuery2(search || "");
900
+ return { pathFilters, applied };
901
+ }
902
+ function lookupDisplay(table, slug) {
903
+ if (!slug || !table) return slug;
904
+ return table[slug] || table[String(slug).toLowerCase()] || slug;
905
+ }
906
+ function displayPathLocation(location, values) {
907
+ if (!location) return null;
908
+ const table = values || {};
909
+ return {
910
+ state: lookupDisplay(table.states, location.state),
911
+ city: lookupDisplay(table.cities, location.city),
912
+ neighborhood: lookupDisplay(table.neighborhoods, location.neighborhood),
913
+ street: lookupDisplay(table.streets, location.street)
914
+ };
915
+ }
916
+ function buildQueryListingsParams(pathFilters, applied, schema, locationValues) {
917
+ const filters = pathFiltersToQueryFilters(pathFilters || {});
918
+ const locations = [];
919
+ const displayed = displayPathLocation(pathFilters?.location, locationValues);
920
+ const pathLoc = displayed ? pathLocationToFilterInput(displayed) : null;
921
+ if (pathLoc) locations.push(pathLoc);
922
+ for (const value of applied?.loc || []) {
923
+ locations.push({ type: "loc", value });
924
+ }
925
+ const params = {
926
+ page: applied?.page || 1,
927
+ limit: schema?.defaultLimit || 12,
928
+ filters
929
+ };
930
+ if (applied?.sort) params.sort = applied.sort;
931
+ const hasLocation = locations.length > 0;
932
+ if (applied?.query && !hasLocation) params.q = applied.query;
933
+ if (hasLocation) params.location = locations;
934
+ return params;
935
+ }
936
+ function applyPathFilter(pathFilters, filterId, value) {
937
+ const next = { ...pathFilters || {} };
938
+ const key = PATH_FILTER_IDS[filterId];
939
+ if (!key) return next;
940
+ if (value === "" || value == null) {
941
+ delete next[key];
942
+ return next;
943
+ }
944
+ if (key === "price" || key === "area") {
945
+ const range = value || {};
946
+ const parse = key === "price" ? parseGroupedInteger : toFiniteNumber;
947
+ const min = parse(range.min);
948
+ const max = parse(range.max);
949
+ if (min == null && max == null) {
950
+ delete next[key];
951
+ return next;
952
+ }
953
+ next[key] = {
954
+ ...min != null ? { min } : {},
955
+ ...max != null ? { max } : {}
956
+ };
957
+ return next;
958
+ }
959
+ if (key === "propertyFeatures" || key === "buildingAmenities") {
960
+ const current = Array.isArray(next[key]) ? [...next[key]] : [];
961
+ const id = String(value);
962
+ const i = current.indexOf(id);
963
+ if (i >= 0) current.splice(i, 1);
964
+ else current.push(id);
965
+ if (current.length) next[key] = current;
966
+ else delete next[key];
967
+ return next;
968
+ }
969
+ if (key === "propertyType") {
970
+ const id = String(value);
971
+ const current = Array.isArray(next.propertyType) ? [...next.propertyType] : next.propertyType ? [String(next.propertyType)] : [];
972
+ const i = current.indexOf(id);
973
+ if (i >= 0) current.splice(i, 1);
974
+ else current.push(id);
975
+ if (current.length === 0) delete next.propertyType;
976
+ else if (current.length === 1) next.propertyType = current[0];
977
+ else next.propertyType = current;
978
+ return next;
979
+ }
980
+ if (key === "listingType") {
981
+ const id = String(value);
982
+ if (next.listingType === id) delete next.listingType;
983
+ else next.listingType = id;
984
+ return next;
985
+ }
986
+ if (key === "bedrooms" || key === "bathrooms" || key === "suites" || key === "parkingSpots") {
987
+ const n = Number(value);
988
+ if (!Number.isFinite(n)) {
989
+ delete next[key];
990
+ return next;
991
+ }
992
+ if (next[key] === n) delete next[key];
993
+ else next[key] = n;
994
+ return next;
995
+ }
996
+ return next;
997
+ }
998
+ function pathFilterValue(pathFilters, filterId) {
999
+ const key = PATH_FILTER_IDS[filterId];
1000
+ const value = pathFilters && key ? pathFilters[key] : void 0;
1001
+ if (value == null) return "";
1002
+ if (Array.isArray(value)) return value[0] != null ? String(value[0]) : "";
1003
+ if (typeof value === "object") return "";
1004
+ return String(value);
1005
+ }
1006
+ function pathFilterHasOption(pathFilters, filterId, optionId) {
1007
+ const key = PATH_FILTER_IDS[filterId];
1008
+ const value = pathFilters && key ? pathFilters[key] : void 0;
1009
+ if (value == null) return false;
1010
+ if (Array.isArray(value)) return value.map(String).includes(optionId);
1011
+ if (typeof value === "object") return false;
1012
+ return String(value) === optionId;
1013
+ }
1014
+ function publicSearchHref(pathFilters, applied, dictionary, existingSearch) {
1015
+ const pathname = composeSearchPublicPath2(pathFilters || {}, dictionary);
1016
+ return composeSearchPublicHref2(pathname, applied || {}, existingSearch);
1017
+ }
1018
+ function hrefForPathFilters(pathname, search, dictionary, nextPathFilters) {
1019
+ const { applied } = readPublicSearch(pathname, search, dictionary);
1020
+ const nextApplied = reduceAppliedSearchQuery2(applied, {
1021
+ type: "applyFilters"
1022
+ });
1023
+ return publicSearchHref(nextPathFilters, nextApplied, dictionary, search);
1024
+ }
1025
+ function hrefForAppliedChange(pathname, search, dictionary, change) {
1026
+ const { pathFilters, applied } = readPublicSearch(
1027
+ pathname,
1028
+ search,
1029
+ dictionary
1030
+ );
1031
+ let nextPath = pathFilters;
1032
+ if (change && change.type === "query") {
1033
+ nextPath = { ...pathFilters };
1034
+ delete nextPath.location;
1035
+ }
1036
+ const nextApplied = reduceAppliedSearchQuery2(applied, change);
1037
+ return publicSearchHref(nextPath, nextApplied, dictionary, search);
1038
+ }
1039
+ function currentSearchHref(pathname, search) {
1040
+ const path = pathnameOnly(pathname);
1041
+ const qs = search.replace(/^\?/, "");
1042
+ return qs ? `${path}?${qs}` : path;
1043
+ }
1044
+ function canonicalizeSearchHref(pathname, search, dictionary) {
1045
+ const { pathFilters, applied } = readPublicSearch(
1046
+ pathname,
1047
+ search,
1048
+ dictionary
1049
+ );
1050
+ const href = publicSearchHref(pathFilters, applied, dictionary, search);
1051
+ if (href === currentSearchHref(pathname, search)) return null;
1052
+ return href;
1053
+ }
1054
+ function searchHrefUsesLegacyFilterQuery(href) {
1055
+ const query = href.split("?")[1] || "";
1056
+ const params = new URLSearchParams(query);
1057
+ return FORBIDDEN_SEARCH_QUERY_KEYS.some((key) => params.has(key));
1058
+ }
1059
+ function clearStagedPathFilters(current, keepFilterIds = []) {
1060
+ const next = current.location ? { location: current.location } : {};
1061
+ for (const id of keepFilterIds) {
1062
+ const key = PATH_FILTER_IDS[id];
1063
+ if (!key || key === "location") continue;
1064
+ const value = current[key];
1065
+ if (value != null) Object.assign(next, { [key]: value });
1066
+ }
1067
+ return next;
1068
+ }
1069
+ function visibleSearchFilters(schema) {
1070
+ if (!schema?.filters) return [];
1071
+ return schema.filters.filter((filter) => {
1072
+ if (HIDDEN_FILTER_IDS.has(filter.id)) return false;
1073
+ if (filter.id === "listing_type" && (filter.options?.length ?? 0) <= 1) {
1074
+ return false;
1075
+ }
1076
+ return true;
1077
+ });
1078
+ }
1079
+ function toolbarFilterIds(schema) {
1080
+ const visible = new Set(visibleSearchFilters(schema).map((f) => f.id));
1081
+ return TOOLBAR_PRIMARY_FILTER_IDS.filter((id) => visible.has(id));
1082
+ }
1083
+ function countOptionLabel(option) {
1084
+ const label = String(option?.label ?? "");
1085
+ if (/^[1-9]\d*$/.test(label)) return `${label}+`;
1086
+ return label;
1087
+ }
1088
+ function countFacetChoices(options) {
1089
+ const list = options || [];
1090
+ const zero = list.find((o) => o.id === "0" || o.label === "Studio");
1091
+ const isStudio = Boolean(
1092
+ zero && /studio/i.test(String(zero.label)) && zero.id === "0"
1093
+ );
1094
+ const max = isStudio ? 3 : 4;
1095
+ const out = [];
1096
+ if (zero) out.push({ id: zero.id, label: countOptionLabel(zero) });
1097
+ for (let n = 1; n <= max; n += 1) {
1098
+ const option = list.find((o) => o.id === String(n));
1099
+ out.push({
1100
+ id: String(n),
1101
+ label: countOptionLabel(option || { label: String(n) })
1102
+ });
1103
+ }
1104
+ return out;
1105
+ }
1106
+ function paginationPages(currentPage, totalPages, padding) {
1107
+ if (totalPages < 1) return [];
1108
+ const current = Math.min(Math.max(1, currentPage), totalPages);
1109
+ const start = Math.max(1, current - padding);
1110
+ const end = Math.min(totalPages, current + padding);
1111
+ const pages = [];
1112
+ for (let i = start; i <= end; i += 1) pages.push(i);
1113
+ return pages;
1114
+ }
1115
+
277
1116
  // src/resolve-site-id.ts
278
1117
  var PREVIEW_HOST_SUFFIXES = [".vusercontent.net"];
279
1118
  function isStudioPreviewHost(host) {
@@ -370,6 +1209,23 @@ function createGaragemClient(options = {}) {
370
1209
  if (merged !== void 0) opts.next = merged;
371
1210
  return searchListings(opts);
372
1211
  },
1212
+ async getSearchUi({ siteId, next } = {}) {
1213
+ const opts = withDefaults({
1214
+ siteId: resolveSiteId(siteId)
1215
+ });
1216
+ const merged = mergeNext(next);
1217
+ if (merged !== void 0) opts.next = merged;
1218
+ return getSearchUi(opts);
1219
+ },
1220
+ async queryListings({ params, siteId, next } = {}) {
1221
+ const opts = withDefaults({
1222
+ siteId: resolveSiteId(siteId)
1223
+ });
1224
+ if (params !== void 0) opts.params = params;
1225
+ const merged = mergeNext(next);
1226
+ if (merged !== void 0) opts.next = merged;
1227
+ return queryListings(opts);
1228
+ },
373
1229
  async getSimilarListings({ listingId, limit, siteId, next }) {
374
1230
  const opts = withDefaults({
375
1231
  siteId: resolveSiteId(siteId),
@@ -421,20 +1277,62 @@ function createGaragemClient(options = {}) {
421
1277
  };
422
1278
  }
423
1279
  export {
1280
+ FORBIDDEN_SEARCH_QUERY_KEYS,
424
1281
  GaragemSdkError,
1282
+ SEARCH_CSS_RECIPE,
1283
+ SEARCH_CSS_VARS,
1284
+ SEARCH_SORT_RELEVANCE,
1285
+ TOOLBAR_PRIMARY_FILTER_IDS,
1286
+ applyPathFilter,
1287
+ buildQueryListingsParams,
1288
+ canonicalizeSearchHref,
1289
+ clearStagedPathFilters,
1290
+ composeSearchPublicHref2 as composeSearchPublicHref,
1291
+ composeSearchPublicPath2 as composeSearchPublicPath,
1292
+ countFacetChoices,
1293
+ countOptionLabel,
425
1294
  createGaragemClient,
1295
+ displayPathLocation,
1296
+ formatAreaM2,
1297
+ formatGroupedInteger,
1298
+ formatListingPrice,
426
1299
  getCmsCollection,
427
1300
  getCmsCollections,
428
1301
  getCmsEntries,
429
1302
  getCmsEntry,
430
1303
  getListing,
431
1304
  getListings,
1305
+ getSearchUi,
432
1306
  getSimilarListings,
433
1307
  getSite,
1308
+ hrefForAppliedChange,
1309
+ hrefForPathFilters,
1310
+ isListingDetailPath,
434
1311
  isStudioPreviewHost,
1312
+ listingBusinessLabel,
1313
+ listingLocationLabel,
435
1314
  listingLookupKey,
436
1315
  listingPublicPath,
1316
+ mergeAppliedSearchQueryIntoSearch2 as mergeAppliedSearchQueryIntoSearch,
1317
+ paginationPages,
1318
+ parseAppliedSearchQuery2 as parseAppliedSearchQuery,
1319
+ parseGroupedInteger,
1320
+ parseSearchPublicPath2 as parseSearchPublicPath,
1321
+ pathFilterHasOption,
1322
+ pathFilterValue,
1323
+ pathFiltersToQueryFilters,
1324
+ pathLocationToFilterInput,
1325
+ publicSearchHref,
1326
+ queryListings,
1327
+ readPublicSearch,
1328
+ reduceAppliedSearchQuery2 as reduceAppliedSearchQuery,
437
1329
  resolvePublicSiteId,
438
- searchListings
1330
+ searchHrefUsesLegacyFilterQuery,
1331
+ searchListings,
1332
+ searchSortOptions,
1333
+ serializeAppliedSearchQuery2 as serializeAppliedSearchQuery,
1334
+ toListingCardModel,
1335
+ toolbarFilterIds,
1336
+ visibleSearchFilters
439
1337
  };
440
1338
  //# sourceMappingURL=index.mjs.map