@garagem-ai/site-sdk 0.2.0 → 0.3.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
@@ -152,6 +152,34 @@ async function searchListings(options) {
152
152
  fetchImpl ?? fetch
153
153
  );
154
154
  }
155
+ async function getSearchUi(options) {
156
+ const { siteId, baseUrl, fetch: fetchImpl, next } = options;
157
+ const base = normalizeBaseUrl(baseUrl);
158
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search-ui`;
159
+ return callJson(
160
+ url,
161
+ { method: "GET", headers: { Accept: "application/json" }, next },
162
+ fetchImpl ?? fetch
163
+ );
164
+ }
165
+ async function queryListings(options) {
166
+ const { siteId, params, baseUrl, fetch: fetchImpl, next } = options;
167
+ const base = normalizeBaseUrl(baseUrl);
168
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;
169
+ return callJson(
170
+ url,
171
+ {
172
+ method: "POST",
173
+ headers: {
174
+ Accept: "application/json",
175
+ "Content-Type": "application/json"
176
+ },
177
+ body: JSON.stringify(params ?? {}),
178
+ next
179
+ },
180
+ fetchImpl ?? fetch
181
+ );
182
+ }
155
183
  async function getSimilarListings(options) {
156
184
  const {
157
185
  siteId,
@@ -274,6 +302,457 @@ async function getCmsEntry(options) {
274
302
  return data;
275
303
  }
276
304
 
305
+ // ../search-url/types.ts
306
+ var SEARCH_BASE_ROUTE = "imoveis";
307
+ var MAX_PAGE = 1e4;
308
+ var MAX_LOC_GROUPS = 20;
309
+ var DEFAULT_MIN_PRICE = 0;
310
+ var DEFAULT_MAX_PRICE = 1e9;
311
+ var DEFAULT_MIN_AREA = 0;
312
+ var DEFAULT_MAX_AREA = 1e5;
313
+ var SORT_URL_TOKENS = [
314
+ "preco-asc",
315
+ "preco-desc",
316
+ "area-asc",
317
+ "area-desc"
318
+ ];
319
+
320
+ // ../search-url/slugify.ts
321
+ function slugifyForUrl(text) {
322
+ if (!text) return "";
323
+ const withDashes = text.replace(/([a-z])([A-Z])/g, "$1-$2");
324
+ return withDashes.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^\w\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").trim();
325
+ }
326
+
327
+ // ../search-url/catalog.ts
328
+ var PROPERTY_TYPE_SLUG_ALIASES = {
329
+ rural: ["chacara", "fazenda", "sitio"]
330
+ };
331
+ function buildListingTypeOptions(enabled) {
332
+ const flags = enabled ?? { sale: true, rental: true };
333
+ const out = [];
334
+ if (flags.sale !== false) {
335
+ out.push({ id: "sale", slug: "venda", label: "Venda" });
336
+ }
337
+ if (flags.rental !== false) {
338
+ out.push({ id: "rental", slug: "aluguel", label: "Aluguel" });
339
+ }
340
+ return out;
341
+ }
342
+ function emptySearchUrlDictionary() {
343
+ return {
344
+ listingTypes: buildListingTypeOptions(null),
345
+ propertyTypes: [],
346
+ propertyFeatures: [],
347
+ buildingAmenities: []
348
+ };
349
+ }
350
+ function norm(value) {
351
+ return slugifyForUrl(value) || value.toLowerCase();
352
+ }
353
+ function matchOptionId(segment, options, extraAliases) {
354
+ const n = norm(segment);
355
+ for (const option of options) {
356
+ const aliases = extraAliases?.[option.id] ?? [];
357
+ const candidates = [option.id, option.slug, option.label, ...aliases];
358
+ if (candidates.some((c) => norm(c) === n)) return option.id;
359
+ }
360
+ return null;
361
+ }
362
+ function optionSlugById(id, options) {
363
+ const option = options.find((item) => item.id === id);
364
+ return option?.slug ?? null;
365
+ }
366
+ var LISTING_TYPE_ALIASES = {
367
+ sale: ["comprar"],
368
+ rental: ["alugar"]
369
+ };
370
+
371
+ // ../search-url/path.ts
372
+ function toArray(value) {
373
+ if (value === void 0) return [];
374
+ return Array.isArray(value) ? value : [value];
375
+ }
376
+ function formatNumeric(value) {
377
+ return Array.isArray(value) ? value.join("-") : String(value);
378
+ }
379
+ function formatRange(min, max, unit) {
380
+ return `de-${min}-a-${max}-${unit}`;
381
+ }
382
+ function formatSuiteSuffix(value) {
383
+ const values = Array.isArray(value) ? value : [value];
384
+ const firstValue = values[0] ?? 0;
385
+ return firstValue === 0 || firstValue === 1 ? "suite" : "suites";
386
+ }
387
+ function composeSearchPublicPath(filters, dictionary = emptySearchUrlDictionary()) {
388
+ const segments = [];
389
+ const listingType = filters.listingType;
390
+ if (listingType) {
391
+ segments.push(
392
+ optionSlugById(listingType, dictionary.listingTypes) || slugifyForUrl(listingType)
393
+ );
394
+ }
395
+ for (const propertyType of toArray(filters.propertyType)) {
396
+ segments.push(
397
+ optionSlugById(propertyType, dictionary.propertyTypes) || slugifyForUrl(propertyType)
398
+ );
399
+ }
400
+ const location = filters.location;
401
+ if (location) {
402
+ if (location.state) segments.push(slugifyForUrl(location.state));
403
+ if (location.city) segments.push(slugifyForUrl(location.city));
404
+ if (location.neighborhood)
405
+ segments.push(slugifyForUrl(location.neighborhood));
406
+ if (location.street) segments.push(slugifyForUrl(location.street));
407
+ }
408
+ if (filters.bedrooms !== void 0) {
409
+ segments.push(`${formatNumeric(filters.bedrooms)}-quartos`);
410
+ }
411
+ if (filters.bathrooms !== void 0) {
412
+ segments.push(`${formatNumeric(filters.bathrooms)}-banheiros`);
413
+ }
414
+ if (filters.suites !== void 0) {
415
+ const suffix = formatSuiteSuffix(filters.suites);
416
+ segments.push(`${formatNumeric(filters.suites)}-${suffix}`);
417
+ }
418
+ if (filters.parkingSpots !== void 0) {
419
+ segments.push(`${formatNumeric(filters.parkingSpots)}-vagas`);
420
+ }
421
+ if (filters.price && (filters.price.min !== void 0 || filters.price.max !== void 0)) {
422
+ const min = filters.price.min ?? DEFAULT_MIN_PRICE;
423
+ const max = filters.price.max ?? DEFAULT_MAX_PRICE;
424
+ segments.push(formatRange(min, max, "reais"));
425
+ }
426
+ if (filters.area && (filters.area.min !== void 0 || filters.area.max !== void 0)) {
427
+ const min = filters.area.min ?? DEFAULT_MIN_AREA;
428
+ const max = filters.area.max ?? DEFAULT_MAX_AREA;
429
+ segments.push(formatRange(min, max, "m2"));
430
+ }
431
+ const seenAmenities = /* @__PURE__ */ new Set();
432
+ for (const id of filters.propertyFeatures ?? []) {
433
+ const slug = optionSlugById(id, dictionary.propertyFeatures) || slugifyForUrl(id);
434
+ if (!slug || seenAmenities.has(slug)) continue;
435
+ seenAmenities.add(slug);
436
+ segments.push(slug);
437
+ }
438
+ for (const id of filters.buildingAmenities ?? []) {
439
+ const slug = optionSlugById(id, dictionary.buildingAmenities) || slugifyForUrl(id);
440
+ if (!slug || seenAmenities.has(slug)) continue;
441
+ seenAmenities.add(slug);
442
+ segments.push(slug);
443
+ }
444
+ const path = segments.filter(Boolean).join("/");
445
+ return path ? `/${SEARCH_BASE_ROUTE}/${path}` : `/${SEARCH_BASE_ROUTE}`;
446
+ }
447
+ var BEDROOMS = /^(\d+(?:-\d+)*)-quartos?$/;
448
+ var BATHROOMS = /^(\d+(?:-\d+)*)-banheiros?$/;
449
+ var SUITES = /^(\d+(?:-\d+)*)-suites?$/;
450
+ var PARKING = /^(\d+(?:-\d+)*)-vagas?$/;
451
+ var PRICE = /^de-(\d+)-a-(\d+)-(reais|real)$/;
452
+ var AREA = /^de-(\d+)-a-(\d+)-(m2|m²)$/;
453
+ function parseNumericList(raw) {
454
+ return raw.split("-").map((part) => Number(part)).filter((n) => Number.isFinite(n));
455
+ }
456
+ function collapse(values) {
457
+ return values.length === 1 ? values[0] : values;
458
+ }
459
+ function parseSearchPublicPath(pathname, dictionary = emptySearchUrlDictionary()) {
460
+ const raw = pathname.split(/[?#]/)[0] ?? "";
461
+ let segments = raw.replace(/^\//, "").split("/").filter(Boolean);
462
+ if (segments[0] === SEARCH_BASE_ROUTE) segments = segments.slice(1);
463
+ if (segments.some((segment) => segment.includes("."))) return null;
464
+ if (segments.some((segment) => segment.toLowerCase().startsWith("id-"))) {
465
+ return null;
466
+ }
467
+ const filters = {};
468
+ const locationParts = [];
469
+ const propertyTypes = [];
470
+ const propertyFeatures = [];
471
+ const buildingAmenities = [];
472
+ for (const segment of segments) {
473
+ const lower = segment.toLowerCase();
474
+ const listingType = matchOptionId(
475
+ segment,
476
+ dictionary.listingTypes,
477
+ LISTING_TYPE_ALIASES
478
+ );
479
+ if (listingType && !filters.listingType) {
480
+ filters.listingType = listingType;
481
+ continue;
482
+ }
483
+ const propertyType = matchOptionId(
484
+ segment,
485
+ dictionary.propertyTypes,
486
+ PROPERTY_TYPE_SLUG_ALIASES
487
+ );
488
+ if (propertyType) {
489
+ propertyTypes.push(propertyType);
490
+ continue;
491
+ }
492
+ const bedrooms = lower.match(BEDROOMS);
493
+ if (bedrooms) {
494
+ filters.bedrooms = collapse(parseNumericList(bedrooms[1]));
495
+ continue;
496
+ }
497
+ const bathrooms = lower.match(BATHROOMS);
498
+ if (bathrooms) {
499
+ filters.bathrooms = collapse(parseNumericList(bathrooms[1]));
500
+ continue;
501
+ }
502
+ const suites = lower.match(SUITES);
503
+ if (suites) {
504
+ filters.suites = collapse(parseNumericList(suites[1]));
505
+ continue;
506
+ }
507
+ const parking = lower.match(PARKING);
508
+ if (parking) {
509
+ filters.parkingSpots = collapse(parseNumericList(parking[1]));
510
+ continue;
511
+ }
512
+ const price = lower.match(PRICE);
513
+ if (price) {
514
+ filters.price = { min: Number(price[1]), max: Number(price[2]) };
515
+ continue;
516
+ }
517
+ const area = lower.match(AREA);
518
+ if (area) {
519
+ filters.area = { min: Number(area[1]), max: Number(area[2]) };
520
+ continue;
521
+ }
522
+ const featureId = matchOptionId(segment, dictionary.propertyFeatures);
523
+ if (featureId) {
524
+ propertyFeatures.push(featureId);
525
+ continue;
526
+ }
527
+ const amenityId = matchOptionId(segment, dictionary.buildingAmenities);
528
+ if (amenityId) {
529
+ buildingAmenities.push(amenityId);
530
+ continue;
531
+ }
532
+ locationParts.push(segment);
533
+ }
534
+ if (propertyTypes.length === 1) filters.propertyType = propertyTypes[0];
535
+ else if (propertyTypes.length > 1) filters.propertyType = propertyTypes;
536
+ if (propertyFeatures.length) filters.propertyFeatures = propertyFeatures;
537
+ if (buildingAmenities.length) filters.buildingAmenities = buildingAmenities;
538
+ const location = locationFromPathLeftovers(locationParts);
539
+ if (location) filters.location = location;
540
+ return filters;
541
+ }
542
+ var PATH_STREET_PREFIX = /^(rua|r|avenida|av|alameda|al|travessa|tv|estrada|rodovia|rod)-/i;
543
+ function locationFromPathLeftovers(parts) {
544
+ if (parts.length === 0) return void 0;
545
+ if (parts.length === 1) {
546
+ const value = parts[0];
547
+ if (PATH_STREET_PREFIX.test(value)) return { street: value };
548
+ if (/^[a-z]{2}$/i.test(value)) return { state: value };
549
+ return { neighborhood: value };
550
+ }
551
+ const [state, city, neighborhood, street] = parts;
552
+ return {
553
+ ...state ? { state } : {},
554
+ ...city ? { city } : {},
555
+ ...neighborhood ? { neighborhood } : {},
556
+ ...street ? { street } : {}
557
+ };
558
+ }
559
+
560
+ // ../search-url/applied-query.ts
561
+ var SORT_SET = new Set(SORT_URL_TOKENS);
562
+ function isSortToken(value) {
563
+ return SORT_SET.has(value);
564
+ }
565
+ function normalizeAppliedSearchQuery(query) {
566
+ if (query.loc && query.loc.length > 0) {
567
+ const { query: _query, ...rest } = query;
568
+ return rest;
569
+ }
570
+ return query;
571
+ }
572
+ function parseAppliedSearchQuery(search) {
573
+ const params = search instanceof URLSearchParams ? search : new URLSearchParams(search.startsWith("?") ? search.slice(1) : search);
574
+ const result = {};
575
+ const pageRaw = params.get("page");
576
+ if (pageRaw) {
577
+ const page = Number.parseInt(pageRaw, 10);
578
+ if (Number.isFinite(page) && page > 1) {
579
+ result.page = Math.min(page, MAX_PAGE);
580
+ }
581
+ }
582
+ const sort = params.get("ordenar");
583
+ if (sort && isSortToken(sort)) result.sort = sort;
584
+ const q = params.get("q")?.trim();
585
+ if (q) result.query = q;
586
+ const loc = params.getAll("loc").map((value) => value.trim()).filter(Boolean).slice(0, MAX_LOC_GROUPS);
587
+ if (loc.length > 0) result.loc = loc;
588
+ return normalizeAppliedSearchQuery(result);
589
+ }
590
+ var APPLIED_QUERY_KEYS = ["page", "ordenar", "q", "loc"];
591
+ function serializeAppliedSearchQuery(query) {
592
+ const normalized = normalizeAppliedSearchQuery(query);
593
+ const params = new URLSearchParams();
594
+ if (normalized.page !== void 0 && normalized.page > 1) {
595
+ params.set("page", String(Math.min(normalized.page, MAX_PAGE)));
596
+ }
597
+ if (normalized.sort && isSortToken(normalized.sort)) {
598
+ params.set("ordenar", normalized.sort);
599
+ }
600
+ const text = normalized.query?.trim();
601
+ if (text) params.set("q", text);
602
+ for (const value of (normalized.loc ?? []).slice(0, MAX_LOC_GROUPS)) {
603
+ const trimmed = value.trim();
604
+ if (trimmed) params.append("loc", trimmed);
605
+ }
606
+ return params;
607
+ }
608
+ function mergeAppliedSearchQueryIntoSearch(existing, query) {
609
+ const params = existing instanceof URLSearchParams ? new URLSearchParams(existing) : new URLSearchParams(
610
+ existing.startsWith("?") ? existing.slice(1) : existing
611
+ );
612
+ for (const key of APPLIED_QUERY_KEYS) {
613
+ params.delete(key);
614
+ }
615
+ const serialized = serializeAppliedSearchQuery(query);
616
+ serialized.forEach((value, key) => {
617
+ if (key === "loc") {
618
+ params.append("loc", value);
619
+ } else {
620
+ params.set(key, value);
621
+ }
622
+ });
623
+ return params;
624
+ }
625
+ function reduceAppliedSearchQuery(prev, change) {
626
+ switch (change.type) {
627
+ case "sort": {
628
+ const next = { ...prev };
629
+ delete next.page;
630
+ if (change.sort) next.sort = change.sort;
631
+ else delete next.sort;
632
+ return normalizeAppliedSearchQuery(next);
633
+ }
634
+ case "applyFilters": {
635
+ const next = { ...prev };
636
+ delete next.page;
637
+ return normalizeAppliedSearchQuery(next);
638
+ }
639
+ case "query": {
640
+ const next = { ...prev };
641
+ delete next.page;
642
+ const trimmed = change.query.trim();
643
+ if (trimmed) {
644
+ next.query = trimmed;
645
+ delete next.loc;
646
+ } else {
647
+ delete next.query;
648
+ }
649
+ return normalizeAppliedSearchQuery(next);
650
+ }
651
+ case "loc": {
652
+ const next = { ...prev };
653
+ delete next.page;
654
+ delete next.query;
655
+ const loc = change.loc.map((value) => value.trim()).filter(Boolean).slice(0, MAX_LOC_GROUPS);
656
+ if (loc.length > 0) next.loc = loc;
657
+ else delete next.loc;
658
+ return normalizeAppliedSearchQuery(next);
659
+ }
660
+ case "page": {
661
+ const next = { ...prev };
662
+ if (change.page <= 1) delete next.page;
663
+ else next.page = Math.min(change.page, MAX_PAGE);
664
+ return normalizeAppliedSearchQuery(next);
665
+ }
666
+ default: {
667
+ const _exhaustive = change;
668
+ return _exhaustive;
669
+ }
670
+ }
671
+ }
672
+ function composeSearchPublicHref(pathname, query, existingSearch) {
673
+ const params = existingSearch ? mergeAppliedSearchQueryIntoSearch(existingSearch, query) : serializeAppliedSearchQuery(query);
674
+ const qs = params.toString();
675
+ return qs ? `${pathname}?${qs}` : pathname;
676
+ }
677
+
678
+ // src/path.ts
679
+ function composeSearchPublicPath2(filters, dictionary) {
680
+ return dictionary ? composeSearchPublicPath(filters, dictionary) : composeSearchPublicPath(filters);
681
+ }
682
+ function parseSearchPublicPath2(pathname, dictionary) {
683
+ return dictionary ? parseSearchPublicPath(pathname, dictionary) : parseSearchPublicPath(pathname);
684
+ }
685
+ function pathFiltersToQueryFilters(pathFilters) {
686
+ const result = {};
687
+ if (pathFilters.listingType !== void 0) {
688
+ result.listing_type = pathFilters.listingType;
689
+ }
690
+ if (pathFilters.propertyType !== void 0) {
691
+ result.property_type = pathFilters.propertyType;
692
+ }
693
+ if (pathFilters.bedrooms !== void 0) {
694
+ result.property_bedrooms = pathFilters.bedrooms;
695
+ }
696
+ if (pathFilters.bathrooms !== void 0) {
697
+ result.property_bathrooms = pathFilters.bathrooms;
698
+ }
699
+ if (pathFilters.suites !== void 0) {
700
+ result.property_suites = pathFilters.suites;
701
+ }
702
+ if (pathFilters.parkingSpots !== void 0) {
703
+ result.property_parking_spots = pathFilters.parkingSpots;
704
+ }
705
+ if (pathFilters.price !== void 0) {
706
+ result.price = pathFilters.price;
707
+ }
708
+ if (pathFilters.area !== void 0) {
709
+ result.property_area_total = pathFilters.area;
710
+ }
711
+ if (pathFilters.propertyFeatures !== void 0) {
712
+ result.propertyFeatures = pathFilters.propertyFeatures;
713
+ }
714
+ if (pathFilters.buildingAmenities !== void 0) {
715
+ result.buildingAmenities = pathFilters.buildingAmenities;
716
+ }
717
+ return result;
718
+ }
719
+
720
+ // src/applied-query.ts
721
+ function parseAppliedSearchQuery2(search) {
722
+ return parseAppliedSearchQuery(search);
723
+ }
724
+ function serializeAppliedSearchQuery2(query) {
725
+ return serializeAppliedSearchQuery(query);
726
+ }
727
+ function mergeAppliedSearchQueryIntoSearch2(existing, query) {
728
+ return mergeAppliedSearchQueryIntoSearch(existing, query);
729
+ }
730
+ function reduceAppliedSearchQuery2(prev, change) {
731
+ return reduceAppliedSearchQuery(prev, change);
732
+ }
733
+ function composeSearchPublicHref2(pathname, query, existingSearch) {
734
+ return composeSearchPublicHref(pathname, query, existingSearch);
735
+ }
736
+
737
+ // src/loc-params.ts
738
+ function pathLocationToFilterInput(location) {
739
+ if (!location || typeof location !== "object") return null;
740
+ const { state, city, neighborhood, street } = location;
741
+ const levels = [];
742
+ if (state) levels.push(state);
743
+ if (city) levels.push(city);
744
+ if (neighborhood) levels.push(neighborhood);
745
+ if (street) levels.push(street);
746
+ if (levels.length === 0) return null;
747
+ if (levels.length === 1) {
748
+ if (state) return { type: "state", value: state };
749
+ if (city) return { type: "city", value: city };
750
+ if (neighborhood) return { type: "neighborhood", value: neighborhood };
751
+ if (street) return { type: "street", value: street };
752
+ }
753
+ return { type: "path", value: levels.join("/") };
754
+ }
755
+
277
756
  // src/resolve-site-id.ts
278
757
  var PREVIEW_HOST_SUFFIXES = [".vusercontent.net"];
279
758
  function isStudioPreviewHost(host) {
@@ -370,6 +849,23 @@ function createGaragemClient(options = {}) {
370
849
  if (merged !== void 0) opts.next = merged;
371
850
  return searchListings(opts);
372
851
  },
852
+ async getSearchUi({ siteId, next } = {}) {
853
+ const opts = withDefaults({
854
+ siteId: resolveSiteId(siteId)
855
+ });
856
+ const merged = mergeNext(next);
857
+ if (merged !== void 0) opts.next = merged;
858
+ return getSearchUi(opts);
859
+ },
860
+ async queryListings({ params, siteId, next } = {}) {
861
+ const opts = withDefaults({
862
+ siteId: resolveSiteId(siteId)
863
+ });
864
+ if (params !== void 0) opts.params = params;
865
+ const merged = mergeNext(next);
866
+ if (merged !== void 0) opts.next = merged;
867
+ return queryListings(opts);
868
+ },
373
869
  async getSimilarListings({ listingId, limit, siteId, next }) {
374
870
  const opts = withDefaults({
375
871
  siteId: resolveSiteId(siteId),
@@ -422,6 +918,8 @@ function createGaragemClient(options = {}) {
422
918
  }
423
919
  export {
424
920
  GaragemSdkError,
921
+ composeSearchPublicHref2 as composeSearchPublicHref,
922
+ composeSearchPublicPath2 as composeSearchPublicPath,
425
923
  createGaragemClient,
426
924
  getCmsCollection,
427
925
  getCmsCollections,
@@ -429,12 +927,21 @@ export {
429
927
  getCmsEntry,
430
928
  getListing,
431
929
  getListings,
930
+ getSearchUi,
432
931
  getSimilarListings,
433
932
  getSite,
434
933
  isStudioPreviewHost,
435
934
  listingLookupKey,
436
935
  listingPublicPath,
936
+ mergeAppliedSearchQueryIntoSearch2 as mergeAppliedSearchQueryIntoSearch,
937
+ parseAppliedSearchQuery2 as parseAppliedSearchQuery,
938
+ parseSearchPublicPath2 as parseSearchPublicPath,
939
+ pathFiltersToQueryFilters,
940
+ pathLocationToFilterInput,
941
+ queryListings,
942
+ reduceAppliedSearchQuery2 as reduceAppliedSearchQuery,
437
943
  resolvePublicSiteId,
438
- searchListings
944
+ searchListings,
945
+ serializeAppliedSearchQuery2 as serializeAppliedSearchQuery
439
946
  };
440
947
  //# sourceMappingURL=index.mjs.map