@garagem-ai/site-sdk 0.12.1 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.mjs CHANGED
@@ -4,197 +4,6 @@
4
4
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
5
5
  import { usePathname, useRouter } from "next/navigation";
6
6
 
7
- // src/listing-path.ts
8
- function listingPublicPath(listing) {
9
- const composed = listing.path?.trim() ?? "";
10
- if (composed.startsWith("/") && !composed.startsWith("//")) return composed;
11
- const identity = listing.listingCode?.trim() || listing.id?.trim() || "";
12
- if (!identity || identity === "undefined" || identity === "null") {
13
- throw new TypeError("listingPublicPath: listing has no listingCode or id");
14
- }
15
- return `/imoveis/id-${identity}`;
16
- }
17
-
18
- // src/internal/sdk-http.ts
19
- var PUBLISHABLE_KEY_HEADER = "X-Garagem-Publishable-Key";
20
- function publishableKeyHeaders(publishableKey) {
21
- const key = publishableKey?.trim();
22
- if (!key) return {};
23
- return { [PUBLISHABLE_KEY_HEADER]: key };
24
- }
25
- function withPublishableKeyHeader(init, publishableKey) {
26
- const extra = publishableKeyHeaders(publishableKey);
27
- if (Object.keys(extra).length === 0) return init;
28
- const current = init.headers;
29
- const base = plainHeaders(current);
30
- return { ...init, headers: { ...base, ...extra } };
31
- }
32
- function plainHeaders(headers) {
33
- const out = {};
34
- if (!headers) return out;
35
- if (typeof Headers !== "undefined" && headers instanceof Headers) {
36
- headers.forEach((value, name) => {
37
- out[name] = value;
38
- });
39
- return out;
40
- }
41
- if (Array.isArray(headers)) {
42
- for (const pair of headers) {
43
- out[String(pair[0])] = String(pair[1]);
44
- }
45
- return out;
46
- }
47
- for (const [name, value] of Object.entries(
48
- headers
49
- )) {
50
- if (typeof value === "string") out[name] = value;
51
- }
52
- return out;
53
- }
54
- function finiteNonNegative(value) {
55
- if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
56
- return value;
57
- }
58
- if (typeof value === "string" && value.trim()) {
59
- const parsed = Number(value);
60
- if (Number.isFinite(parsed) && parsed >= 0) return parsed;
61
- }
62
- return null;
63
- }
64
- function parseSdkErrorBody(text) {
65
- const raw = text ? text.slice(0, 200) : "";
66
- if (!text) {
67
- return { reason: null, retryAfterSeconds: null, summary: "" };
68
- }
69
- try {
70
- const body = JSON.parse(text);
71
- if (!body || typeof body !== "object") {
72
- return { reason: null, retryAfterSeconds: null, summary: raw };
73
- }
74
- const record = body;
75
- const reason = typeof record.reason === "string" && record.reason ? record.reason : null;
76
- const retryAfterSeconds = finiteNonNegative(
77
- record.retryAfterSeconds ?? record.retryAfter
78
- );
79
- const errorText = typeof record.error === "string" && record.error ? record.error : raw;
80
- return {
81
- reason,
82
- retryAfterSeconds,
83
- summary: errorText.slice(0, 200)
84
- };
85
- } catch {
86
- return { reason: null, retryAfterSeconds: null, summary: raw };
87
- }
88
- }
89
- function retryAfterFromResponse(response, bodySeconds, nowMs = Date.now()) {
90
- const header = response.headers.get("Retry-After")?.trim();
91
- if (header) {
92
- const delta = finiteNonNegative(header);
93
- if (delta != null) return delta;
94
- const at = Date.parse(header);
95
- if (Number.isFinite(at)) {
96
- return Math.max(0, Math.ceil((at - nowMs) / 1e3));
97
- }
98
- }
99
- return bodySeconds;
100
- }
101
-
102
- // src/internal/url.ts
103
- var DEFAULT_BASE_URL = "https://app.garagem.ai";
104
- function normalizeBaseUrl(baseUrl) {
105
- const url = baseUrl ?? DEFAULT_BASE_URL;
106
- return url.endsWith("/") ? url.slice(0, -1) : url;
107
- }
108
- async function coerceSiteId(siteId) {
109
- const raw = typeof siteId === "function" ? siteId() : siteId;
110
- const value = await Promise.resolve(raw);
111
- if (typeof value !== "string" || !value.trim()) {
112
- throw new TypeError(
113
- "Garagem SDK: siteId must be a string. Await resolveSiteId(...) before getListings / getSearchUi / queryListings."
114
- );
115
- }
116
- return value;
117
- }
118
-
119
- // src/fetchers.ts
120
- async function callJson(url, init, fetchImpl, publishableKey) {
121
- const response = await fetchImpl(
122
- url,
123
- withPublishableKeyHeader(init, publishableKey)
124
- );
125
- if (!response.ok) {
126
- throw await readGaragemSdkError(response, url);
127
- }
128
- return await response.json();
129
- }
130
- var GaragemSdkError = class extends Error {
131
- status;
132
- url;
133
- /** Machine reason from the JSON body (`invalid_publishable_key`, `rate_limited`, …). */
134
- reason;
135
- /**
136
- * Seconds to wait before retrying. Set on HTTP 429 from `Retry-After`
137
- * or the body's `retryAfterSeconds`. `null` when the response has neither.
138
- */
139
- retryAfter;
140
- constructor(message, info) {
141
- super(message);
142
- this.name = "GaragemSdkError";
143
- this.status = info.status;
144
- this.url = info.url;
145
- this.reason = info.reason ?? null;
146
- this.retryAfter = info.retryAfter ?? null;
147
- }
148
- };
149
- async function readGaragemSdkError(response, url) {
150
- const text = await response.text().catch(() => "");
151
- const parsed = parseSdkErrorBody(text);
152
- const retryAfter = response.status === 429 ? retryAfterFromResponse(response, parsed.retryAfterSeconds) : parsed.retryAfterSeconds;
153
- const detail = parsed.summary;
154
- return new GaragemSdkError(
155
- `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${detail ? ` \u2014 ${detail}` : ""}`,
156
- {
157
- status: response.status,
158
- url,
159
- reason: parsed.reason,
160
- retryAfter
161
- }
162
- );
163
- }
164
- async function getSearchUi(options) {
165
- const { baseUrl, fetch: fetchImpl, next } = options;
166
- const siteId = await coerceSiteId(options.siteId);
167
- const base = normalizeBaseUrl(baseUrl);
168
- const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search-ui`;
169
- return callJson(
170
- url,
171
- { method: "GET", headers: { Accept: "application/json" }, next },
172
- fetchImpl ?? fetch,
173
- options.publishableKey
174
- );
175
- }
176
- async function queryListings(options) {
177
- const { params, baseUrl, fetch: fetchImpl, next, signal } = options;
178
- const siteId = await coerceSiteId(options.siteId);
179
- const base = normalizeBaseUrl(baseUrl);
180
- const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;
181
- return callJson(
182
- url,
183
- {
184
- method: "POST",
185
- headers: {
186
- Accept: "application/json",
187
- "Content-Type": "application/json"
188
- },
189
- body: JSON.stringify(params ?? {}),
190
- next,
191
- signal
192
- },
193
- fetchImpl ?? fetch,
194
- options.publishableKey
195
- );
196
- }
197
-
198
7
  // ../search-url/types.ts
199
8
  var SEARCH_BASE_ROUTE = "imoveis";
200
9
  var MAX_PAGE = 1e4;
@@ -795,6 +604,16 @@ function applyPathFilter(pathFilters, filterId, value) {
795
604
  }
796
605
  return next;
797
606
  }
607
+ function changedPathFilters(current, next) {
608
+ const changed = [];
609
+ for (const [filterId, key] of Object.entries(PATH_FILTER_IDS)) {
610
+ const before = current?.[key];
611
+ const after = next?.[key];
612
+ if (JSON.stringify(before) === JSON.stringify(after)) continue;
613
+ changed.push({ filterId, value: after });
614
+ }
615
+ return changed;
616
+ }
798
617
  function publicSearchHref(pathFilters, applied, dictionary, existingSearch) {
799
618
  const pathname = composeSearchPublicPath2(pathFilters || {}, dictionary);
800
619
  return composeSearchPublicHref2(pathname, applied || {}, existingSearch);
@@ -848,6 +667,265 @@ function clearStagedPathFilters(current, keepFilterIds = []) {
848
667
  return next;
849
668
  }
850
669
 
670
+ // src/analytics.ts
671
+ var SITE_ANALYTICS_EVENT = "garagem:site-event";
672
+ function emitSiteEvent(event, properties) {
673
+ if (typeof window === "undefined") return;
674
+ window.dispatchEvent(
675
+ new CustomEvent(SITE_ANALYTICS_EVENT, { detail: { event, properties } })
676
+ );
677
+ }
678
+ function catalogBusinessType(value) {
679
+ return value === "sale" || value === "rental" ? value : void 0;
680
+ }
681
+ function minOf(value) {
682
+ if (!Array.isArray(value)) return value;
683
+ return value.length ? Math.min(...value) : void 0;
684
+ }
685
+ function trackSearchResults(input) {
686
+ const { pathFilters, applied, listingIds, page } = input;
687
+ const location = displayPathLocation(
688
+ pathFilters.location,
689
+ input.locationNames
690
+ );
691
+ emitSiteEvent("property_search", {
692
+ query: applied.query || void 0,
693
+ business_type: catalogBusinessType(pathFilters.listingType),
694
+ property_type: pathFilters.propertyType,
695
+ location_city: location?.city,
696
+ location_neighborhood: location?.neighborhood,
697
+ min_price: pathFilters.price?.min,
698
+ max_price: pathFilters.price?.max,
699
+ min_bedrooms: minOf(pathFilters.bedrooms),
700
+ min_area: pathFilters.area?.min,
701
+ max_area: pathFilters.area?.max,
702
+ result_count: input.total,
703
+ page,
704
+ sort_by: applied.sort || void 0
705
+ });
706
+ if (!listingIds.length) return;
707
+ emitSiteEvent("listings_impressed", {
708
+ property_ids: listingIds,
709
+ impression_count: listingIds.length,
710
+ source: "search",
711
+ page
712
+ });
713
+ }
714
+ function filterValue(value) {
715
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
716
+ return value;
717
+ }
718
+ if (Array.isArray(value)) return value.map(String);
719
+ if (value && typeof value === "object") {
720
+ const { min, max } = value;
721
+ return `${min ?? ""}-${max ?? ""}`;
722
+ }
723
+ return "";
724
+ }
725
+ function trackFilterApplied(filterId, value) {
726
+ emitSiteEvent("filter_applied", {
727
+ filter_name: filterId,
728
+ filter_value: filterValue(value),
729
+ ...value == null ? { filter_action: "clear" } : {}
730
+ });
731
+ }
732
+ function trackStagedFiltersApplied(current, staged) {
733
+ for (const { filterId, value } of changedPathFilters(current, staged)) {
734
+ trackFilterApplied(filterId, value);
735
+ }
736
+ }
737
+
738
+ // src/listing-path.ts
739
+ function listingPublicPath(listing) {
740
+ const composed = listing.path?.trim() ?? "";
741
+ if (composed.startsWith("/") && !composed.startsWith("//")) return composed;
742
+ const identity = listing.listingCode?.trim() || listing.id?.trim() || "";
743
+ if (!identity || identity === "undefined" || identity === "null") {
744
+ throw new TypeError("listingPublicPath: listing has no listingCode or id");
745
+ }
746
+ return `/imoveis/id-${identity}`;
747
+ }
748
+
749
+ // src/internal/sdk-http.ts
750
+ var PUBLISHABLE_KEY_HEADER = "X-Garagem-Publishable-Key";
751
+ function publishableKeyHeaders(publishableKey) {
752
+ const key = publishableKey?.trim();
753
+ if (!key) return {};
754
+ return { [PUBLISHABLE_KEY_HEADER]: key };
755
+ }
756
+ function withPublishableKeyHeader(init, publishableKey) {
757
+ const extra = publishableKeyHeaders(publishableKey);
758
+ if (Object.keys(extra).length === 0) return init;
759
+ const current = init.headers;
760
+ const base = plainHeaders(current);
761
+ return { ...init, headers: { ...base, ...extra } };
762
+ }
763
+ function plainHeaders(headers) {
764
+ const out = {};
765
+ if (!headers) return out;
766
+ if (typeof Headers !== "undefined" && headers instanceof Headers) {
767
+ headers.forEach((value, name) => {
768
+ out[name] = value;
769
+ });
770
+ return out;
771
+ }
772
+ if (Array.isArray(headers)) {
773
+ for (const pair of headers) {
774
+ out[String(pair[0])] = String(pair[1]);
775
+ }
776
+ return out;
777
+ }
778
+ for (const [name, value] of Object.entries(
779
+ headers
780
+ )) {
781
+ if (typeof value === "string") out[name] = value;
782
+ }
783
+ return out;
784
+ }
785
+ function finiteNonNegative(value) {
786
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
787
+ return value;
788
+ }
789
+ if (typeof value === "string" && value.trim()) {
790
+ const parsed = Number(value);
791
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed;
792
+ }
793
+ return null;
794
+ }
795
+ function parseSdkErrorBody(text) {
796
+ const raw = text ? text.slice(0, 200) : "";
797
+ if (!text) {
798
+ return { reason: null, retryAfterSeconds: null, summary: "" };
799
+ }
800
+ try {
801
+ const body = JSON.parse(text);
802
+ if (!body || typeof body !== "object") {
803
+ return { reason: null, retryAfterSeconds: null, summary: raw };
804
+ }
805
+ const record = body;
806
+ const reason = typeof record.reason === "string" && record.reason ? record.reason : null;
807
+ const retryAfterSeconds = finiteNonNegative(
808
+ record.retryAfterSeconds ?? record.retryAfter
809
+ );
810
+ const errorText = typeof record.error === "string" && record.error ? record.error : raw;
811
+ return {
812
+ reason,
813
+ retryAfterSeconds,
814
+ summary: errorText.slice(0, 200)
815
+ };
816
+ } catch {
817
+ return { reason: null, retryAfterSeconds: null, summary: raw };
818
+ }
819
+ }
820
+ function retryAfterFromResponse(response, bodySeconds, nowMs = Date.now()) {
821
+ const header = response.headers.get("Retry-After")?.trim();
822
+ if (header) {
823
+ const delta = finiteNonNegative(header);
824
+ if (delta != null) return delta;
825
+ const at = Date.parse(header);
826
+ if (Number.isFinite(at)) {
827
+ return Math.max(0, Math.ceil((at - nowMs) / 1e3));
828
+ }
829
+ }
830
+ return bodySeconds;
831
+ }
832
+
833
+ // src/internal/url.ts
834
+ var DEFAULT_BASE_URL = "https://app.garagem.ai";
835
+ function normalizeBaseUrl(baseUrl) {
836
+ const url = baseUrl ?? DEFAULT_BASE_URL;
837
+ return url.endsWith("/") ? url.slice(0, -1) : url;
838
+ }
839
+ async function coerceSiteId(siteId) {
840
+ const raw = typeof siteId === "function" ? siteId() : siteId;
841
+ const value = await Promise.resolve(raw);
842
+ if (typeof value !== "string" || !value.trim()) {
843
+ throw new TypeError(
844
+ "Garagem SDK: siteId must be a string. Await resolveSiteId(...) before getListings / getSearchUi / queryListings."
845
+ );
846
+ }
847
+ return value;
848
+ }
849
+
850
+ // src/fetchers.ts
851
+ async function callJson(url, init, fetchImpl, publishableKey) {
852
+ const response = await fetchImpl(
853
+ url,
854
+ withPublishableKeyHeader(init, publishableKey)
855
+ );
856
+ if (!response.ok) {
857
+ throw await readGaragemSdkError(response, url);
858
+ }
859
+ return await response.json();
860
+ }
861
+ var GaragemSdkError = class extends Error {
862
+ status;
863
+ url;
864
+ /** Machine reason from the JSON body (`invalid_publishable_key`, `rate_limited`, …). */
865
+ reason;
866
+ /**
867
+ * Seconds to wait before retrying. Set on HTTP 429 from `Retry-After`
868
+ * or the body's `retryAfterSeconds`. `null` when the response has neither.
869
+ */
870
+ retryAfter;
871
+ constructor(message, info) {
872
+ super(message);
873
+ this.name = "GaragemSdkError";
874
+ this.status = info.status;
875
+ this.url = info.url;
876
+ this.reason = info.reason ?? null;
877
+ this.retryAfter = info.retryAfter ?? null;
878
+ }
879
+ };
880
+ async function readGaragemSdkError(response, url) {
881
+ const text = await response.text().catch(() => "");
882
+ const parsed = parseSdkErrorBody(text);
883
+ const retryAfter = response.status === 429 ? retryAfterFromResponse(response, parsed.retryAfterSeconds) : parsed.retryAfterSeconds;
884
+ const detail = parsed.summary;
885
+ return new GaragemSdkError(
886
+ `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${detail ? ` \u2014 ${detail}` : ""}`,
887
+ {
888
+ status: response.status,
889
+ url,
890
+ reason: parsed.reason,
891
+ retryAfter
892
+ }
893
+ );
894
+ }
895
+ async function getSearchUi(options) {
896
+ const { baseUrl, fetch: fetchImpl, next } = options;
897
+ const siteId = await coerceSiteId(options.siteId);
898
+ const base = normalizeBaseUrl(baseUrl);
899
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search-ui`;
900
+ return callJson(
901
+ url,
902
+ { method: "GET", headers: { Accept: "application/json" }, next },
903
+ fetchImpl ?? fetch,
904
+ options.publishableKey
905
+ );
906
+ }
907
+ async function queryListings(options) {
908
+ const { params, baseUrl, fetch: fetchImpl, next, signal } = options;
909
+ const siteId = await coerceSiteId(options.siteId);
910
+ const base = normalizeBaseUrl(baseUrl);
911
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;
912
+ return callJson(
913
+ url,
914
+ {
915
+ method: "POST",
916
+ headers: {
917
+ Accept: "application/json",
918
+ "Content-Type": "application/json"
919
+ },
920
+ body: JSON.stringify(params ?? {}),
921
+ next,
922
+ signal
923
+ },
924
+ fetchImpl ?? fetch,
925
+ options.publishableKey
926
+ );
927
+ }
928
+
851
929
  // src/react/public-search-snapshot.ts
852
930
  function hrefParts(href) {
853
931
  const q = href.indexOf("?");
@@ -897,6 +975,13 @@ function shouldPreservePaintedListingsOnRefetchFailure(options) {
897
975
  options.dictionary
898
976
  );
899
977
  }
978
+ function shouldTrackSearchResults(options) {
979
+ return !searchKeysRepresentSameQuery(
980
+ options.trackedSearchKey,
981
+ options.searchKey,
982
+ options.dictionary
983
+ );
984
+ }
900
985
  function initialQueryDraft(pathname, search, dictionary) {
901
986
  return readPublicSearch(pathname, search, dictionary).applied.query || "";
902
987
  }
@@ -997,6 +1082,7 @@ function usePublicSearch(options) {
997
1082
  replaceStaged({ ...parsed.pathFilters });
998
1083
  }, [parsed.pathFilters, replaceStaged]);
999
1084
  const locationsRef = useRef(seed.locationNames);
1085
+ const trackedSearchKeyRef = useRef(null);
1000
1086
  useEffect(() => {
1001
1087
  if (!schema) return;
1002
1088
  const canonical = canonicalizeSearchHref(
@@ -1122,6 +1208,21 @@ function usePublicSearch(options) {
1122
1208
  )
1123
1209
  });
1124
1210
  if (!active) return;
1211
+ if (shouldTrackSearchResults({
1212
+ trackedSearchKey: trackedSearchKeyRef.current,
1213
+ searchKey,
1214
+ dictionary: currentSchema.dictionary
1215
+ })) {
1216
+ trackedSearchKeyRef.current = searchKey;
1217
+ trackSearchResults({
1218
+ pathFilters,
1219
+ applied,
1220
+ locationNames: locationsRef.current,
1221
+ listingIds: (response.listings || []).map((listing) => listing.id),
1222
+ total: response.total || 0,
1223
+ page: response.page || 1
1224
+ });
1225
+ }
1125
1226
  setListings(response.listings || []);
1126
1227
  setPage(response.page || 1);
1127
1228
  setTotal(response.total || 0);
@@ -1160,6 +1261,7 @@ function usePublicSearch(options) {
1160
1261
  const applyFilter = useCallback(
1161
1262
  (filterId, value) => {
1162
1263
  if (!schema) return;
1264
+ trackFilterApplied(filterId, value);
1163
1265
  go(
1164
1266
  hrefForPathFilters(
1165
1267
  pathname,
@@ -1182,6 +1284,10 @@ function usePublicSearch(options) {
1182
1284
  }, []);
1183
1285
  const applyStaged = useCallback(() => {
1184
1286
  if (!schema) return;
1287
+ trackStagedFiltersApplied(
1288
+ parsed.pathFilters,
1289
+ stagedMirrorRef.current.value
1290
+ );
1185
1291
  go(
1186
1292
  hrefForPathFilters(
1187
1293
  pathname,
@@ -1190,7 +1296,7 @@ function usePublicSearch(options) {
1190
1296
  stagedMirrorRef.current.value
1191
1297
  )
1192
1298
  );
1193
- }, [go, pathname, search, schema]);
1299
+ }, [go, pathname, search, schema, parsed.pathFilters]);
1194
1300
  const clearStaged = useCallback(() => {
1195
1301
  setStagedState(stagedMirrorRef.current.clear());
1196
1302
  }, []);