@garagem-ai/site-sdk 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.mjs CHANGED
@@ -4,6 +4,90 @@
4
4
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
5
5
  import { usePathname, useRouter } from "next/navigation";
6
6
 
7
+ // src/internal/sdk-http.ts
8
+ var PUBLISHABLE_KEY_HEADER = "X-Garagem-Publishable-Key";
9
+ function publishableKeyHeaders(publishableKey) {
10
+ const key = publishableKey?.trim();
11
+ if (!key) return {};
12
+ return { [PUBLISHABLE_KEY_HEADER]: key };
13
+ }
14
+ function withPublishableKeyHeader(init, publishableKey) {
15
+ const extra = publishableKeyHeaders(publishableKey);
16
+ if (Object.keys(extra).length === 0) return init;
17
+ const current = init.headers;
18
+ const base = plainHeaders(current);
19
+ return { ...init, headers: { ...base, ...extra } };
20
+ }
21
+ function plainHeaders(headers) {
22
+ const out = {};
23
+ if (!headers) return out;
24
+ if (typeof Headers !== "undefined" && headers instanceof Headers) {
25
+ headers.forEach((value, name) => {
26
+ out[name] = value;
27
+ });
28
+ return out;
29
+ }
30
+ if (Array.isArray(headers)) {
31
+ for (const pair of headers) {
32
+ out[String(pair[0])] = String(pair[1]);
33
+ }
34
+ return out;
35
+ }
36
+ for (const [name, value] of Object.entries(
37
+ headers
38
+ )) {
39
+ if (typeof value === "string") out[name] = value;
40
+ }
41
+ return out;
42
+ }
43
+ function finiteNonNegative(value) {
44
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
45
+ return value;
46
+ }
47
+ if (typeof value === "string" && value.trim()) {
48
+ const parsed = Number(value);
49
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed;
50
+ }
51
+ return null;
52
+ }
53
+ function parseSdkErrorBody(text) {
54
+ const raw = text ? text.slice(0, 200) : "";
55
+ if (!text) {
56
+ return { reason: null, retryAfterSeconds: null, summary: "" };
57
+ }
58
+ try {
59
+ const body = JSON.parse(text);
60
+ if (!body || typeof body !== "object") {
61
+ return { reason: null, retryAfterSeconds: null, summary: raw };
62
+ }
63
+ const record = body;
64
+ const reason = typeof record.reason === "string" && record.reason ? record.reason : null;
65
+ const retryAfterSeconds = finiteNonNegative(
66
+ record.retryAfterSeconds ?? record.retryAfter
67
+ );
68
+ const errorText = typeof record.error === "string" && record.error ? record.error : raw;
69
+ return {
70
+ reason,
71
+ retryAfterSeconds,
72
+ summary: errorText.slice(0, 200)
73
+ };
74
+ } catch {
75
+ return { reason: null, retryAfterSeconds: null, summary: raw };
76
+ }
77
+ }
78
+ function retryAfterFromResponse(response, bodySeconds, nowMs = Date.now()) {
79
+ const header = response.headers.get("Retry-After")?.trim();
80
+ if (header) {
81
+ const delta = finiteNonNegative(header);
82
+ if (delta != null) return delta;
83
+ const at = Date.parse(header);
84
+ if (Number.isFinite(at)) {
85
+ return Math.max(0, Math.ceil((at - nowMs) / 1e3));
86
+ }
87
+ }
88
+ return bodySeconds;
89
+ }
90
+
7
91
  // src/internal/url.ts
8
92
  var DEFAULT_BASE_URL = "https://app.garagem.ai";
9
93
  function normalizeBaseUrl(baseUrl) {
@@ -22,27 +106,50 @@ async function coerceSiteId(siteId) {
22
106
  }
23
107
 
24
108
  // src/fetchers.ts
25
- async function callJson(url, init, fetchImpl) {
26
- const response = await fetchImpl(url, init);
109
+ async function callJson(url, init, fetchImpl, publishableKey) {
110
+ const response = await fetchImpl(
111
+ url,
112
+ withPublishableKeyHeader(init, publishableKey)
113
+ );
27
114
  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
- );
115
+ throw await readGaragemSdkError(response, url);
33
116
  }
34
117
  return await response.json();
35
118
  }
36
119
  var GaragemSdkError = class extends Error {
37
120
  status;
38
121
  url;
122
+ /** Machine reason from the JSON body (`invalid_publishable_key`, `rate_limited`, …). */
123
+ reason;
124
+ /**
125
+ * Seconds to wait before retrying. Set on HTTP 429 from `Retry-After`
126
+ * or the body's `retryAfterSeconds`. `null` when the response has neither.
127
+ */
128
+ retryAfter;
39
129
  constructor(message, info) {
40
130
  super(message);
41
131
  this.name = "GaragemSdkError";
42
132
  this.status = info.status;
43
133
  this.url = info.url;
134
+ this.reason = info.reason ?? null;
135
+ this.retryAfter = info.retryAfter ?? null;
44
136
  }
45
137
  };
138
+ async function readGaragemSdkError(response, url) {
139
+ const text = await response.text().catch(() => "");
140
+ const parsed = parseSdkErrorBody(text);
141
+ const retryAfter = response.status === 429 ? retryAfterFromResponse(response, parsed.retryAfterSeconds) : parsed.retryAfterSeconds;
142
+ const detail = parsed.summary;
143
+ return new GaragemSdkError(
144
+ `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${detail ? ` \u2014 ${detail}` : ""}`,
145
+ {
146
+ status: response.status,
147
+ url,
148
+ reason: parsed.reason,
149
+ retryAfter
150
+ }
151
+ );
152
+ }
46
153
  async function getSearchUi(options) {
47
154
  const { baseUrl, fetch: fetchImpl, next } = options;
48
155
  const siteId = await coerceSiteId(options.siteId);
@@ -51,7 +158,8 @@ async function getSearchUi(options) {
51
158
  return callJson(
52
159
  url,
53
160
  { method: "GET", headers: { Accept: "application/json" }, next },
54
- fetchImpl ?? fetch
161
+ fetchImpl ?? fetch,
162
+ options.publishableKey
55
163
  );
56
164
  }
57
165
  async function queryListings(options) {
@@ -70,7 +178,8 @@ async function queryListings(options) {
70
178
  body: JSON.stringify(params ?? {}),
71
179
  next
72
180
  },
73
- fetchImpl ?? fetch
181
+ fetchImpl ?? fetch,
182
+ options.publishableKey
74
183
  );
75
184
  }
76
185
 
@@ -808,7 +917,13 @@ function currentHref(pathname, search) {
808
917
  return search ? `${pathname}?${search}` : pathname;
809
918
  }
810
919
  function usePublicSearch(options) {
811
- const { siteId, baseUrl, initial, search: searchFromServer = "" } = options;
920
+ const {
921
+ siteId,
922
+ baseUrl,
923
+ publishableKey,
924
+ initial,
925
+ search: searchFromServer = ""
926
+ } = options;
812
927
  const router = useRouter();
813
928
  const pathname = usePathname() || "/imoveis";
814
929
  const search = searchFromServer;
@@ -897,13 +1012,23 @@ function usePublicSearch(options) {
897
1012
  }
898
1013
  async function loadSchema() {
899
1014
  try {
900
- const nextSchema = await getSearchUi({ siteId: id, baseUrl });
1015
+ const nextSchema = await getSearchUi({
1016
+ siteId: id,
1017
+ baseUrl,
1018
+ publishableKey
1019
+ });
901
1020
  if (!active) return;
902
1021
  let locations = null;
903
1022
  if (nextSchema.locationsPath.startsWith("/")) {
904
1023
  try {
905
1024
  const response = await fetch(
906
- `${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`
1025
+ `${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`,
1026
+ {
1027
+ headers: {
1028
+ Accept: "application/json",
1029
+ ...publishableKeyHeaders(publishableKey)
1030
+ }
1031
+ }
907
1032
  );
908
1033
  if (response.ok) {
909
1034
  locations = await response.json();
@@ -937,7 +1062,7 @@ function usePublicSearch(options) {
937
1062
  return () => {
938
1063
  active = false;
939
1064
  };
940
- }, [baseUrl, catalogId]);
1065
+ }, [baseUrl, catalogId, publishableKey]);
941
1066
  useEffect(() => {
942
1067
  if (!schema || !catalogId) return;
943
1068
  const currentSchema = schema;
@@ -960,6 +1085,7 @@ function usePublicSearch(options) {
960
1085
  const response = await queryListings({
961
1086
  siteId: id,
962
1087
  baseUrl,
1088
+ publishableKey,
963
1089
  params: buildQueryListingsParams(
964
1090
  pathFilters,
965
1091
  applied,
@@ -996,7 +1122,7 @@ function usePublicSearch(options) {
996
1122
  return () => {
997
1123
  active = false;
998
1124
  };
999
- }, [pathname, search, baseUrl, schema, catalogId]);
1125
+ }, [pathname, search, baseUrl, schema, catalogId, publishableKey]);
1000
1126
  const go = useCallback(
1001
1127
  (href) => {
1002
1128
  if (href && href !== currentHref(pathname, search)) router.push(href);