@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/README.md +169 -28
- package/dist/index.d.mts +178 -4
- package/dist/index.d.ts +178 -4
- package/dist/index.js +538 -32
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +528 -32
- package/dist/index.mjs.map +1 -1
- package/dist/react.d.mts +6 -1
- package/dist/react.d.ts +6 -1
- package/dist/react.js +140 -14
- package/dist/react.js.map +1 -1
- package/dist/react.mjs +140 -14
- package/dist/react.mjs.map +1 -1
- package/dist/{types-photo-search-OeONNDxl.d.mts → types-photo-search-CmGRj6my.d.mts} +25 -0
- package/dist/{types-photo-search-OeONNDxl.d.ts → types-photo-search-CmGRj6my.d.ts} +25 -0
- package/package.json +1 -1
- package/src/client.ts +23 -0
- package/src/fetchers-photos.ts +98 -0
- package/src/fetchers.ts +92 -29
- package/src/index.ts +31 -2
- package/src/internal/sdk-http.ts +122 -0
- package/src/leads.ts +34 -3
- package/src/listing-photos.ts +312 -0
- package/src/react/types.ts +5 -0
- package/src/react/use-public-search.ts +23 -5
- package/src/resolve-site-id.ts +3 -0
- package/src/studio-contract.ts +74 -0
- package/src/types-photos.ts +46 -0
- package/src/types.ts +11 -0
package/src/leads.ts
CHANGED
|
@@ -4,6 +4,11 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import { callJson, type FetchLike } from "./fetchers";
|
|
7
|
+
import {
|
|
8
|
+
parseSdkErrorBody,
|
|
9
|
+
publishableKeyHeaders,
|
|
10
|
+
retryAfterFromResponse,
|
|
11
|
+
} from "./internal/sdk-http";
|
|
7
12
|
import { coerceSiteId, normalizeBaseUrl } from "./internal/url";
|
|
8
13
|
import { isValidPhone, toE164 } from "./phone";
|
|
9
14
|
import { resolvePublicSiteId } from "./resolve-site-id";
|
|
@@ -48,6 +53,8 @@ export type GetLeadUiOptions = {
|
|
|
48
53
|
baseUrl?: string;
|
|
49
54
|
fetch?: FetchLike;
|
|
50
55
|
next?: RequestNextOptions;
|
|
56
|
+
/** Site publishable key (`pk_live_…`). Not a secret. */
|
|
57
|
+
publishableKey?: string;
|
|
51
58
|
};
|
|
52
59
|
|
|
53
60
|
function browserHost(): string {
|
|
@@ -63,6 +70,7 @@ async function resolveLeadSiteId(input: {
|
|
|
63
70
|
siteId?: unknown;
|
|
64
71
|
baseUrl?: string;
|
|
65
72
|
fetch?: FetchLike;
|
|
73
|
+
publishableKey?: string;
|
|
66
74
|
}): Promise<string> {
|
|
67
75
|
try {
|
|
68
76
|
return await coerceSiteId(input.siteId);
|
|
@@ -73,6 +81,7 @@ async function resolveLeadSiteId(input: {
|
|
|
73
81
|
host,
|
|
74
82
|
baseUrl: input.baseUrl,
|
|
75
83
|
fetch: input.fetch,
|
|
84
|
+
publishableKey: input.publishableKey,
|
|
76
85
|
});
|
|
77
86
|
}
|
|
78
87
|
}
|
|
@@ -88,6 +97,8 @@ type LeadSubmitBase = LeadContact & {
|
|
|
88
97
|
siteId?: string | Promise<string>;
|
|
89
98
|
baseUrl?: string;
|
|
90
99
|
fetch?: FetchLike;
|
|
100
|
+
/** Site publishable key (`pk_live_…`). Not a secret. */
|
|
101
|
+
publishableKey?: string;
|
|
91
102
|
listingId: string;
|
|
92
103
|
/**
|
|
93
104
|
* Active listing modality (`sale` | `rental` | `rent`). Always pass
|
|
@@ -115,6 +126,7 @@ export type LeadSubmitErrorCode =
|
|
|
115
126
|
| "invalid_listing_id"
|
|
116
127
|
| "invalid_contact"
|
|
117
128
|
| "invalid_slot"
|
|
129
|
+
| "unauthorized"
|
|
118
130
|
| "rate_limited"
|
|
119
131
|
| "not_found"
|
|
120
132
|
| "http"
|
|
@@ -124,6 +136,8 @@ export class LeadSubmitError extends Error {
|
|
|
124
136
|
readonly code: LeadSubmitErrorCode;
|
|
125
137
|
readonly status?: number;
|
|
126
138
|
readonly retryAfterSeconds?: number;
|
|
139
|
+
/** Seconds to wait. Same value as `retryAfterSeconds`; `null` when unset. */
|
|
140
|
+
readonly retryAfter: number | null;
|
|
127
141
|
|
|
128
142
|
constructor(
|
|
129
143
|
message: string,
|
|
@@ -140,6 +154,7 @@ export class LeadSubmitError extends Error {
|
|
|
140
154
|
if (info.retryAfterSeconds != null) {
|
|
141
155
|
this.retryAfterSeconds = info.retryAfterSeconds;
|
|
142
156
|
}
|
|
157
|
+
this.retryAfter = info.retryAfterSeconds ?? null;
|
|
143
158
|
}
|
|
144
159
|
}
|
|
145
160
|
|
|
@@ -187,7 +202,8 @@ export async function getLeadUi(options: GetLeadUiOptions): Promise<LeadUi> {
|
|
|
187
202
|
headers: { Accept: "application/json" },
|
|
188
203
|
next: options.next,
|
|
189
204
|
},
|
|
190
|
-
options.fetch ?? fetch
|
|
205
|
+
options.fetch ?? fetch,
|
|
206
|
+
options.publishableKey
|
|
191
207
|
);
|
|
192
208
|
}
|
|
193
209
|
|
|
@@ -286,6 +302,7 @@ async function postSiteLead(input: {
|
|
|
286
302
|
siteId?: string | Promise<string>;
|
|
287
303
|
baseUrl?: string;
|
|
288
304
|
fetch?: FetchLike;
|
|
305
|
+
publishableKey?: string;
|
|
289
306
|
body: SiteSdkLeadBody;
|
|
290
307
|
}): Promise<LeadSubmitResult> {
|
|
291
308
|
const siteId = await resolveLeadSiteId(input);
|
|
@@ -299,6 +316,7 @@ async function postSiteLead(input: {
|
|
|
299
316
|
headers: {
|
|
300
317
|
Accept: "application/json",
|
|
301
318
|
"Content-Type": "application/json",
|
|
319
|
+
...publishableKeyHeaders(input.publishableKey),
|
|
302
320
|
},
|
|
303
321
|
body: JSON.stringify(input.body),
|
|
304
322
|
});
|
|
@@ -317,12 +335,23 @@ async function postSiteLead(input: {
|
|
|
317
335
|
return { ok: true, status: 202, id };
|
|
318
336
|
}
|
|
319
337
|
|
|
320
|
-
|
|
338
|
+
if (response.status === 401) {
|
|
339
|
+
throw new LeadSubmitError("Garagem SDK: invalid publishable key.", {
|
|
340
|
+
code: "unauthorized",
|
|
341
|
+
status: 401,
|
|
342
|
+
});
|
|
343
|
+
}
|
|
321
344
|
if (response.status === 429) {
|
|
345
|
+
const text = await response.text().catch(() => "");
|
|
346
|
+
const parsed = parseSdkErrorBody(text);
|
|
347
|
+
const retryAfter = retryAfterFromResponse(
|
|
348
|
+
response,
|
|
349
|
+
parsed.retryAfterSeconds
|
|
350
|
+
);
|
|
322
351
|
throw new LeadSubmitError("Garagem SDK: too many lead submissions.", {
|
|
323
352
|
code: "rate_limited",
|
|
324
353
|
status: 429,
|
|
325
|
-
|
|
354
|
+
...(retryAfter != null ? { retryAfterSeconds: retryAfter } : {}),
|
|
326
355
|
});
|
|
327
356
|
}
|
|
328
357
|
if (response.status === 404) {
|
|
@@ -383,6 +412,7 @@ export async function submitVisitLead(
|
|
|
383
412
|
siteId: input.siteId,
|
|
384
413
|
baseUrl: input.baseUrl,
|
|
385
414
|
fetch: input.fetch,
|
|
415
|
+
publishableKey: input.publishableKey,
|
|
386
416
|
body: {
|
|
387
417
|
source: "site-sdk",
|
|
388
418
|
leadType: "visit",
|
|
@@ -404,6 +434,7 @@ export async function submitContactLead(
|
|
|
404
434
|
siteId: input.siteId,
|
|
405
435
|
baseUrl: input.baseUrl,
|
|
406
436
|
fetch: input.fetch,
|
|
437
|
+
publishableKey: input.publishableKey,
|
|
407
438
|
body: {
|
|
408
439
|
source: "site-sdk",
|
|
409
440
|
leadType: "contact",
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Headless photo helpers for the listing detail.
|
|
3
|
+
*
|
|
4
|
+
* `listingPhotoGroups` turns the gallery into "Sala (3) · Quartos (4) ·
|
|
5
|
+
* Cozinha (2)" sections from the per-photo `roomType`; `listingVisualHighlights`
|
|
6
|
+
* surfaces the visual features the analysis named most often. Both are pure
|
|
7
|
+
* and only read `ListingDetail.media`.
|
|
8
|
+
*/
|
|
9
|
+
import type { ListingMedia } from "./types";
|
|
10
|
+
import type { ListingPhotoGroup } from "./types-photos";
|
|
11
|
+
|
|
12
|
+
export const PHOTO_GROUP_OTHER_KEY = "outros";
|
|
13
|
+
export const PHOTO_GROUP_OTHER_LABEL = "Outras fotos";
|
|
14
|
+
|
|
15
|
+
function normalizeRoomLabel(value: string): string {
|
|
16
|
+
return value
|
|
17
|
+
.normalize("NFD")
|
|
18
|
+
.replace(/[̀-ͯ]/g, "")
|
|
19
|
+
.toLowerCase()
|
|
20
|
+
.replace(/[^a-z0-9]+/g, " ")
|
|
21
|
+
.trim();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Synonym groups mirrored from the platform's room matching, each with the
|
|
26
|
+
* pt-BR label the site shows. Members are already normalized.
|
|
27
|
+
*/
|
|
28
|
+
const ROOM_GROUPS: ReadonlyArray<{
|
|
29
|
+
key: string;
|
|
30
|
+
label: string;
|
|
31
|
+
members: readonly string[];
|
|
32
|
+
}> = [
|
|
33
|
+
{
|
|
34
|
+
key: "fachada",
|
|
35
|
+
label: "Fachada",
|
|
36
|
+
members: [
|
|
37
|
+
"fachada",
|
|
38
|
+
"exterior",
|
|
39
|
+
"frente",
|
|
40
|
+
"facade",
|
|
41
|
+
"fachada do predio",
|
|
42
|
+
"predio",
|
|
43
|
+
"building exterior",
|
|
44
|
+
"area externa do predio",
|
|
45
|
+
],
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
key: "sala",
|
|
49
|
+
label: "Sala",
|
|
50
|
+
members: [
|
|
51
|
+
"sala",
|
|
52
|
+
"sala de estar",
|
|
53
|
+
"living",
|
|
54
|
+
"estar",
|
|
55
|
+
"sala de tv",
|
|
56
|
+
"living room",
|
|
57
|
+
"sala de estar e jantar",
|
|
58
|
+
"sala integrada",
|
|
59
|
+
],
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
key: "sala de jantar",
|
|
63
|
+
label: "Sala de jantar",
|
|
64
|
+
members: ["sala de jantar", "jantar", "dining room", "copa jantar"],
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
key: "cozinha",
|
|
68
|
+
label: "Cozinha",
|
|
69
|
+
members: [
|
|
70
|
+
"cozinha",
|
|
71
|
+
"copa",
|
|
72
|
+
"copa cozinha",
|
|
73
|
+
"cozinha americana",
|
|
74
|
+
"kitchen",
|
|
75
|
+
],
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
key: "quarto",
|
|
79
|
+
label: "Quartos",
|
|
80
|
+
members: [
|
|
81
|
+
"quarto",
|
|
82
|
+
"dormitorio",
|
|
83
|
+
"suite",
|
|
84
|
+
"suite master",
|
|
85
|
+
"quarto de casal",
|
|
86
|
+
"quarto de solteiro",
|
|
87
|
+
"quarto infantil",
|
|
88
|
+
"bedroom",
|
|
89
|
+
"master bedroom",
|
|
90
|
+
],
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
key: "banheiro",
|
|
94
|
+
label: "Banheiros",
|
|
95
|
+
members: [
|
|
96
|
+
"banheiro",
|
|
97
|
+
"lavabo",
|
|
98
|
+
"wc",
|
|
99
|
+
"toalete",
|
|
100
|
+
"bathroom",
|
|
101
|
+
"banheiro social",
|
|
102
|
+
"banheiro da suite",
|
|
103
|
+
],
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
key: "varanda",
|
|
107
|
+
label: "Varanda",
|
|
108
|
+
members: ["varanda", "sacada", "terraco", "balcony", "terrace"],
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
key: "area gourmet",
|
|
112
|
+
label: "Área gourmet",
|
|
113
|
+
members: [
|
|
114
|
+
"area gourmet",
|
|
115
|
+
"varanda gourmet",
|
|
116
|
+
"espaco gourmet",
|
|
117
|
+
"churrasqueira",
|
|
118
|
+
"gourmet",
|
|
119
|
+
"terraco gourmet",
|
|
120
|
+
],
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
key: "closet",
|
|
124
|
+
label: "Closet",
|
|
125
|
+
members: ["closet", "closet da suite", "walk in closet"],
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
key: "escritorio",
|
|
129
|
+
label: "Escritório",
|
|
130
|
+
members: ["escritorio", "home office", "office"],
|
|
131
|
+
},
|
|
132
|
+
{
|
|
133
|
+
key: "area de servico",
|
|
134
|
+
label: "Área de serviço",
|
|
135
|
+
members: ["area de servico", "lavanderia", "laundry", "servico"],
|
|
136
|
+
},
|
|
137
|
+
{ key: "despensa", label: "Despensa", members: ["despensa", "pantry"] },
|
|
138
|
+
{
|
|
139
|
+
key: "corredor",
|
|
140
|
+
label: "Corredor",
|
|
141
|
+
members: ["corredor", "circulacao", "hallway"],
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
key: "hall",
|
|
145
|
+
label: "Hall",
|
|
146
|
+
members: [
|
|
147
|
+
"hall",
|
|
148
|
+
"hall de entrada",
|
|
149
|
+
"entrada",
|
|
150
|
+
"recepcao",
|
|
151
|
+
"lobby",
|
|
152
|
+
"portaria",
|
|
153
|
+
],
|
|
154
|
+
},
|
|
155
|
+
{
|
|
156
|
+
key: "garagem",
|
|
157
|
+
label: "Garagem",
|
|
158
|
+
members: [
|
|
159
|
+
"garagem",
|
|
160
|
+
"vaga",
|
|
161
|
+
"vagas",
|
|
162
|
+
"estacionamento",
|
|
163
|
+
"garage",
|
|
164
|
+
"vaga de garagem",
|
|
165
|
+
],
|
|
166
|
+
},
|
|
167
|
+
{
|
|
168
|
+
key: "piscina",
|
|
169
|
+
label: "Piscina",
|
|
170
|
+
members: ["piscina", "pool", "piscina do condominio"],
|
|
171
|
+
},
|
|
172
|
+
{
|
|
173
|
+
key: "academia",
|
|
174
|
+
label: "Academia",
|
|
175
|
+
members: ["academia", "fitness", "gym", "espaco fitness"],
|
|
176
|
+
},
|
|
177
|
+
{
|
|
178
|
+
key: "salao de festas",
|
|
179
|
+
label: "Salão de festas",
|
|
180
|
+
members: ["salao de festas", "festas", "salao", "party room"],
|
|
181
|
+
},
|
|
182
|
+
{
|
|
183
|
+
key: "playground",
|
|
184
|
+
label: "Playground",
|
|
185
|
+
members: ["playground", "brinquedoteca", "espaco kids"],
|
|
186
|
+
},
|
|
187
|
+
{
|
|
188
|
+
key: "jardim",
|
|
189
|
+
label: "Jardim",
|
|
190
|
+
members: ["jardim", "quintal", "area externa", "garden", "backyard"],
|
|
191
|
+
},
|
|
192
|
+
{
|
|
193
|
+
key: "vista",
|
|
194
|
+
label: "Vista",
|
|
195
|
+
members: ["vista", "view", "vista da varanda"],
|
|
196
|
+
},
|
|
197
|
+
{
|
|
198
|
+
key: "planta",
|
|
199
|
+
label: "Planta",
|
|
200
|
+
members: ["planta", "planta baixa", "floorplan", "floor plan"],
|
|
201
|
+
},
|
|
202
|
+
];
|
|
203
|
+
|
|
204
|
+
const GROUP_BY_MEMBER = new Map<string, { key: string; label: string }>();
|
|
205
|
+
for (const group of ROOM_GROUPS) {
|
|
206
|
+
for (const member of group.members) {
|
|
207
|
+
GROUP_BY_MEMBER.set(member, { key: group.key, label: group.label });
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Labels the analysis uses when it saw nothing to classify. */
|
|
212
|
+
const NON_ROOM_LABELS = new Set(["", "outro", "outros", "other", "unknown"]);
|
|
213
|
+
|
|
214
|
+
function capitalize(value: string): string {
|
|
215
|
+
return value.charAt(0).toUpperCase() + value.slice(1);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Group key + pt-BR label for a photo `roomType`. Unknown rooms keep their
|
|
220
|
+
* own (capitalized) label; empty / "other" values go to `Outras fotos`.
|
|
221
|
+
*/
|
|
222
|
+
export function photoRoomLabel(roomType: string | null | undefined): {
|
|
223
|
+
key: string;
|
|
224
|
+
label: string;
|
|
225
|
+
} {
|
|
226
|
+
const raw = (roomType ?? "").trim();
|
|
227
|
+
const normalized = normalizeRoomLabel(raw);
|
|
228
|
+
if (NON_ROOM_LABELS.has(normalized)) {
|
|
229
|
+
return { key: PHOTO_GROUP_OTHER_KEY, label: PHOTO_GROUP_OTHER_LABEL };
|
|
230
|
+
}
|
|
231
|
+
const known = GROUP_BY_MEMBER.get(normalized);
|
|
232
|
+
if (known) return known;
|
|
233
|
+
return { key: normalized, label: capitalize(raw) };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function isPhoto(item: ListingMedia): boolean {
|
|
237
|
+
return (item.type || "image") === "image" && typeof item.src === "string";
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Gallery photos grouped by room, in first-appearance order with `Outras
|
|
242
|
+
* fotos` last. Videos and tours are skipped. A listing with no analysis at
|
|
243
|
+
* all yields a single `Outras fotos` group (or `[]` when it has no photos),
|
|
244
|
+
* so callers can fall back to the flat gallery when `groups.length <= 1`.
|
|
245
|
+
*/
|
|
246
|
+
export function listingPhotoGroups(listing: {
|
|
247
|
+
media?: ListingMedia[] | null;
|
|
248
|
+
}): ListingPhotoGroup[] {
|
|
249
|
+
const groups = new Map<string, ListingPhotoGroup>();
|
|
250
|
+
const photos = [...(listing.media ?? [])]
|
|
251
|
+
.filter(isPhoto)
|
|
252
|
+
.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
|
|
253
|
+
for (const photo of photos) {
|
|
254
|
+
const { key, label } = photoRoomLabel(photo.roomType);
|
|
255
|
+
const group = groups.get(key);
|
|
256
|
+
if (group) {
|
|
257
|
+
group.photos.push(photo);
|
|
258
|
+
} else {
|
|
259
|
+
groups.set(key, { key, label, photos: [photo] });
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
const ordered = [...groups.values()];
|
|
263
|
+
const otherIndex = ordered.findIndex((g) => g.key === PHOTO_GROUP_OTHER_KEY);
|
|
264
|
+
if (otherIndex >= 0 && otherIndex !== ordered.length - 1) {
|
|
265
|
+
const [other] = ordered.splice(otherIndex, 1);
|
|
266
|
+
ordered.push(other!);
|
|
267
|
+
}
|
|
268
|
+
return ordered;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export interface ListingVisualHighlightsOptions {
|
|
272
|
+
/** Max highlights to return. Default 8. */
|
|
273
|
+
limit?: number;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Distinct visual highlights across the gallery, most frequent first (ties
|
|
278
|
+
* keep gallery order). Case- and accent-insensitive dedupe; the first
|
|
279
|
+
* spelling seen wins.
|
|
280
|
+
*/
|
|
281
|
+
export function listingVisualHighlights(
|
|
282
|
+
listing: { media?: ListingMedia[] | null },
|
|
283
|
+
options?: ListingVisualHighlightsOptions
|
|
284
|
+
): string[] {
|
|
285
|
+
const limit = Math.max(0, Math.floor(options?.limit ?? 8));
|
|
286
|
+
if (limit === 0) return [];
|
|
287
|
+
const counts = new Map<
|
|
288
|
+
string,
|
|
289
|
+
{ text: string; count: number; seen: number }
|
|
290
|
+
>();
|
|
291
|
+
let seen = 0;
|
|
292
|
+
for (const item of listing.media ?? []) {
|
|
293
|
+
if (!isPhoto(item) || !Array.isArray(item.features)) continue;
|
|
294
|
+
for (const feature of item.features) {
|
|
295
|
+
if (typeof feature !== "string") continue;
|
|
296
|
+
const text = feature.trim();
|
|
297
|
+
if (!text) continue;
|
|
298
|
+
const key = normalizeRoomLabel(text);
|
|
299
|
+
if (!key) continue;
|
|
300
|
+
const entry = counts.get(key);
|
|
301
|
+
if (entry) {
|
|
302
|
+
entry.count += 1;
|
|
303
|
+
} else {
|
|
304
|
+
counts.set(key, { text, count: 1, seen: seen++ });
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return [...counts.values()]
|
|
309
|
+
.sort((a, b) => b.count - a.count || a.seen - b.seen)
|
|
310
|
+
.slice(0, limit)
|
|
311
|
+
.map((entry) => entry.text);
|
|
312
|
+
}
|
package/src/react/types.ts
CHANGED
|
@@ -24,6 +24,11 @@ export type PublicSearchSnapshot = {
|
|
|
24
24
|
export type UsePublicSearchOptions = {
|
|
25
25
|
siteId: SiteIdInput;
|
|
26
26
|
baseUrl?: string;
|
|
27
|
+
/**
|
|
28
|
+
* Site publishable key (`pk_live_…`). Sent on schema, location, and
|
|
29
|
+
* listing requests. Not a secret. Omit it to stay on the anonymous budget.
|
|
30
|
+
*/
|
|
31
|
+
publishableKey?: string;
|
|
27
32
|
/**
|
|
28
33
|
* Query string without `?`, from the server page's `searchParams`.
|
|
29
34
|
* The hook must not call Next's search-params hook: that suspends the
|
|
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
|
4
4
|
import { usePathname, useRouter } from "next/navigation";
|
|
5
5
|
|
|
6
6
|
import { getSearchUi, queryListings } from "../fetchers";
|
|
7
|
+
import { publishableKeyHeaders } from "../internal/sdk-http";
|
|
7
8
|
import { coerceSiteId, normalizeBaseUrl } from "../internal/url";
|
|
8
9
|
import {
|
|
9
10
|
applyPathFilter,
|
|
@@ -44,7 +45,13 @@ function currentHref(pathname: string, search: string): string {
|
|
|
44
45
|
export function usePublicSearch(
|
|
45
46
|
options: UsePublicSearchOptions
|
|
46
47
|
): PublicSearchState {
|
|
47
|
-
const {
|
|
48
|
+
const {
|
|
49
|
+
siteId,
|
|
50
|
+
baseUrl,
|
|
51
|
+
publishableKey,
|
|
52
|
+
initial,
|
|
53
|
+
search: searchFromServer = "",
|
|
54
|
+
} = options;
|
|
48
55
|
const router = useRouter();
|
|
49
56
|
const pathname = usePathname() || "/imoveis";
|
|
50
57
|
const search = searchFromServer;
|
|
@@ -149,13 +156,23 @@ export function usePublicSearch(
|
|
|
149
156
|
}
|
|
150
157
|
async function loadSchema() {
|
|
151
158
|
try {
|
|
152
|
-
const nextSchema = await getSearchUi({
|
|
159
|
+
const nextSchema = await getSearchUi({
|
|
160
|
+
siteId: id,
|
|
161
|
+
baseUrl,
|
|
162
|
+
publishableKey,
|
|
163
|
+
});
|
|
153
164
|
if (!active) return;
|
|
154
165
|
let locations: LocationNameTables | null = null;
|
|
155
166
|
if (nextSchema.locationsPath.startsWith("/")) {
|
|
156
167
|
try {
|
|
157
168
|
const response = await fetch(
|
|
158
|
-
`${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}
|
|
169
|
+
`${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`,
|
|
170
|
+
{
|
|
171
|
+
headers: {
|
|
172
|
+
Accept: "application/json",
|
|
173
|
+
...publishableKeyHeaders(publishableKey),
|
|
174
|
+
},
|
|
175
|
+
}
|
|
159
176
|
);
|
|
160
177
|
if (response.ok) {
|
|
161
178
|
locations = (await response.json()) as LocationNameTables;
|
|
@@ -192,7 +209,7 @@ export function usePublicSearch(
|
|
|
192
209
|
return () => {
|
|
193
210
|
active = false;
|
|
194
211
|
};
|
|
195
|
-
}, [baseUrl, catalogId]);
|
|
212
|
+
}, [baseUrl, catalogId, publishableKey]);
|
|
196
213
|
|
|
197
214
|
useEffect(() => {
|
|
198
215
|
if (!schema || !catalogId) return;
|
|
@@ -218,6 +235,7 @@ export function usePublicSearch(
|
|
|
218
235
|
const response = await queryListings({
|
|
219
236
|
siteId: id,
|
|
220
237
|
baseUrl,
|
|
238
|
+
publishableKey,
|
|
221
239
|
params: buildQueryListingsParams(
|
|
222
240
|
pathFilters,
|
|
223
241
|
applied,
|
|
@@ -257,7 +275,7 @@ export function usePublicSearch(
|
|
|
257
275
|
return () => {
|
|
258
276
|
active = false;
|
|
259
277
|
};
|
|
260
|
-
}, [pathname, search, baseUrl, schema, catalogId]);
|
|
278
|
+
}, [pathname, search, baseUrl, schema, catalogId, publishableKey]);
|
|
261
279
|
|
|
262
280
|
const go = useCallback(
|
|
263
281
|
(href: string) => {
|
package/src/resolve-site-id.ts
CHANGED
|
@@ -7,6 +7,8 @@ export interface ResolvePublicSiteIdOptions {
|
|
|
7
7
|
fallback?: string | null;
|
|
8
8
|
baseUrl?: string;
|
|
9
9
|
fetch?: FetchLike;
|
|
10
|
+
/** Forwarded to `getSite` when the live host is resolved. */
|
|
11
|
+
publishableKey?: string;
|
|
10
12
|
}
|
|
11
13
|
|
|
12
14
|
/** v0 in-chat preview only. Published Studio sites often live on `*.vercel.app`. */
|
|
@@ -38,6 +40,7 @@ export async function resolvePublicSiteId(
|
|
|
38
40
|
domain: host,
|
|
39
41
|
baseUrl: options.baseUrl,
|
|
40
42
|
fetch: options.fetch,
|
|
43
|
+
publishableKey: options.publishableKey,
|
|
41
44
|
});
|
|
42
45
|
if (site?.id) return site.id;
|
|
43
46
|
throw new GaragemSdkError(
|
package/src/studio-contract.ts
CHANGED
|
@@ -99,6 +99,29 @@ export const STUDIO_SDK_CONTRACT = {
|
|
|
99
99
|
*/
|
|
100
100
|
unpublishedPhoneExports: [] as const,
|
|
101
101
|
amenityExports: ["listingAmenityGroups"] as const,
|
|
102
|
+
/**
|
|
103
|
+
* Prompt-safe photo helpers on `minNpmVersion`. Empty until the release
|
|
104
|
+
* that carries `getSimilarByPhoto` / `listingPhotoGroups` /
|
|
105
|
+
* `listingVisualHighlights` is on npm; then bump the pin, move the names
|
|
106
|
+
* here from `unpublishedPhotoExports`, and `studioPhotoInstruction()`
|
|
107
|
+
* starts teaching the gallery-by-room, highlight chips, and
|
|
108
|
+
* "imóveis com fotos parecidas" blocks. The caption-based `media[].alt` /
|
|
109
|
+
* `media[].caption` fields are API data (not tarball exports) and are
|
|
110
|
+
* documented regardless of the pin.
|
|
111
|
+
*/
|
|
112
|
+
photoExports: [] as const,
|
|
113
|
+
/**
|
|
114
|
+
* Photo helpers in the repo but not on `minNpmVersion`. Prompts,
|
|
115
|
+
* completeness, and repair text must not mention these until the pin
|
|
116
|
+
* bumps — v0 installs the pin and the ESM loader throws on missing named
|
|
117
|
+
* exports.
|
|
118
|
+
*/
|
|
119
|
+
unpublishedPhotoExports: [
|
|
120
|
+
"getSimilarByPhoto",
|
|
121
|
+
"listingPhotoGroups",
|
|
122
|
+
"listingVisualHighlights",
|
|
123
|
+
"photoRoomLabel",
|
|
124
|
+
] as const,
|
|
102
125
|
/**
|
|
103
126
|
* Names already on the pinned npm tarball (`minNpmVersion`) — safe for
|
|
104
127
|
* Studio prompts and completeness. Includes `visibleSearchFilters` +
|
|
@@ -270,6 +293,17 @@ export function unavailableReactImports(source: string, pin: string): string[] {
|
|
|
270
293
|
return missing;
|
|
271
294
|
}
|
|
272
295
|
|
|
296
|
+
/**
|
|
297
|
+
* Studio copy for the public site API key. Names only exports that already
|
|
298
|
+
* exist on `minNpmVersion` (`createGaragemClient`, `GaragemSdkError`,
|
|
299
|
+
* `usePublicSearch`, the lead helpers). `publishableKey` is an extra option
|
|
300
|
+
* older tarballs ignore, so generated sites keep working before this SDK
|
|
301
|
+
* version is published.
|
|
302
|
+
*/
|
|
303
|
+
export function studioPublishableKeyInstruction(): string {
|
|
304
|
+
return `Public site API key (optional, backwards compatible). \`publishableKey\` (\`pk_live_…\`) is not a secret. Create or rotate it in Garagem at Configurações → Sites → the site → API pública (route \`/configuracoes/sites/[siteId]\`, section API pública (SDK)). Pass it to \`createGaragemClient({ siteId, baseUrl: GARAGEM_API_BASE, publishableKey })\` or on each call: \`getListings\`, \`getListing\`, \`getSite\`, \`getSearchUi\`, \`queryListings\`, \`searchListings\`, the CMS helpers, \`getLeadUi\`, \`submitVisitLead\`, \`submitContactLead\`, and \`usePublicSearch\`. The SDK sends header \`X-Garagem-Publishable-Key\` (a Bearer token that starts with \`pk_live_\` is also accepted). Omitting the key still succeeds. Once a site has a key, anonymous traffic uses the stricter per-IP budget (listings/search 30/min, detail 60/min, config 30/min). A site with no key uses the looser anonymous budget (120 / 300 / 120). With the key, budgets are listings/search 600/min, detail 1200/min, config 300/min. Window is 60 seconds. Success and 429 responses carry \`RateLimit-Limit\`, \`RateLimit-Remaining\`, \`RateLimit-Reset\`, and \`RateLimit-Policy\`. HTTP 401 throws \`GaragemSdkError\` with \`status\` 401 and \`reason\` \`invalid_publishable_key\` (wrong key). HTTP 403 has \`reason\` \`origin_not_allowed\` when the site's origin allowlist rejects the browser Origin or Referer. HTTP 429 has \`reason\` \`rate_limited\` and \`retryAfter\` seconds (same value as the \`Retry-After\` header). \`LeadSubmitError\` uses \`code\` \`rate_limited\` or \`unauthorized\`, and \`retryAfter\` / \`retryAfterSeconds\` on 429. A public constant next to \`GARAGEM_API_BASE\` is the right place for the key. Do not invent a second header name.`;
|
|
305
|
+
}
|
|
306
|
+
|
|
273
307
|
export function studioSdkPinInstruction(): string {
|
|
274
308
|
const version = STUDIO_SDK_CONTRACT.minNpmVersion;
|
|
275
309
|
const names = [...reactExportsAvailableAt(version)].join(", ");
|
|
@@ -292,6 +326,41 @@ export function studioListingDetailInstruction(): string {
|
|
|
292
326
|
return `Listing detail: import ${names} from \`${STUDIO_SDK_PACKAGE}\`. Render \`listingDetailModel\` leaves: \`model.facts[].label\` / \`.text\`, \`model.values[].label\` / \`.text\`, \`model.location.label\` / \`model.location.mapsHref\`, breadcrumb \`.href\` (search prefixes of \`listing.path\`). The preço / sob consulta entry is the primary value; condomínio and IPTU are secondary and omitted when missing. \`model.description\` is the complete string — do not slice. A collapsed disclosure uses a container (max-height or overflow), not a cut of the string. Never interpolate \`model.location\`, \`model.facts\`, \`model.values\`, \`model.breadcrumb\`, or \`model.mediaOverlays\` as a React child. Video/tour: \`model.mediaOverlays\` as hash links (\`#video\` / \`#tour\`); player src is \`embedSrc\`; fullscreen overlay closes with browser back; omit when that overlay is absent. Do not key the page on \`location.hash\`. Similar listings: \`getSimilarListings({ siteId, listingId, baseUrl })\` plus the site listing-card module; hide the section when empty. Do not invent a local recommendation loop.`;
|
|
293
327
|
}
|
|
294
328
|
|
|
329
|
+
/**
|
|
330
|
+
* Listing-detail photo intelligence, gated on the published pin. The base
|
|
331
|
+
* sentence (caption-based `alt` / optional `caption` on gallery photos) is
|
|
332
|
+
* API data and always applies; each helper block appears only when its
|
|
333
|
+
* export is in `published` (see `STUDIO_SDK_CONTRACT.photoExports`).
|
|
334
|
+
*/
|
|
335
|
+
export function studioPhotoInstructionFor(
|
|
336
|
+
published: readonly string[]
|
|
337
|
+
): string {
|
|
338
|
+
const has = (name: string) => published.includes(name);
|
|
339
|
+
const parts = [
|
|
340
|
+
`Gallery photo text: \`item.alt\` on \`listing.media\` is the photo caption when the platform analyzed it (else "<title> - Foto N") — always pass it as the img alt. \`item.caption\` is optional: show it as the slide / overlay caption when present and omit the element when absent. Never invent captions or room names in generated source.`,
|
|
341
|
+
];
|
|
342
|
+
if (has("listingPhotoGroups")) {
|
|
343
|
+
parts.push(
|
|
344
|
+
`Gallery by room: \`const groups = listingPhotoGroups(listing)\` from \`${STUDIO_SDK_PACKAGE}\` returns \`{ key, label, photos }[]\` (pt-BR labels such as "Sala", "Quartos", "Cozinha"; "Outras fotos" last). Use it only inside the fullscreen photo overlay (room tabs or section headings over the thumbnail strip) — the page carousel stays one flat section. Render \`group.label\` and \`group.photos.length\`; when \`groups.length <= 1\` render the flat strip without headings. Never read \`item.roomType\` / \`item.sceneType\` directly to build sections and never hardcode room names.`
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
if (has("listingVisualHighlights")) {
|
|
348
|
+
parts.push(
|
|
349
|
+
`Visual highlights: \`const highlights = listingVisualHighlights(listing, { limit: 6 })\` returns deduped strings ("piso de madeira", "vista livre"). Render them as small chips (site tokens, \`--radius\`) under the gallery or beside the facts, one chip per string, and omit the block when the array is empty. Do not merge them with \`listingAmenityGroups\` and do not read \`item.features\` directly.`
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
if (has("getSimilarByPhoto")) {
|
|
353
|
+
parts.push(
|
|
354
|
+
`Imóveis com fotos parecidas: on the server page, pick the first image item of \`listing.media\` and \`await getSimilarByPhoto(siteId, listing.id, photo.id, { limit: 6, baseUrl: GARAGEM_API_BASE })\` from \`${STUDIO_SDK_PACKAGE}\` (positional ids; \`listing.id\` is the UUID, never the path). The result is \`{ available, items }\`: when \`available === false\` (tenant without image search, or \`photo.id\` is not a media UUID such as the \`image-N\` / \`external-N\` gallery keys — that returns locally and does not throw) render nothing — no heading, no empty state; when \`items.length === 0\` also render nothing. Otherwise a section titled "Imóveis com fotos parecidas" with the site listing-card module (\`toListingCardModel(item.listing)\`), using \`item.matchedPhoto.src\` / \`item.matchedPhoto.alt\` as that card's photo. Keep \`getSimilarListings\` as the default similar carousel; this section is additional, below it. Wrap the call in try/catch and treat an error like \`available: false\`.`
|
|
355
|
+
);
|
|
356
|
+
}
|
|
357
|
+
return parts.join(" ");
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
export function studioPhotoInstruction(): string {
|
|
361
|
+
return studioPhotoInstructionFor(STUDIO_SDK_CONTRACT.photoExports);
|
|
362
|
+
}
|
|
363
|
+
|
|
295
364
|
export function studioAmenityInstruction(): string {
|
|
296
365
|
return `Listing amenities: Portuguese labels from \`listingAmenityGroups(listing, dictionary)\` (pass the dictionary from \`getSearchUi()\` so section titles follow Campos). Each group is \`{ title, labels: string[] }\` — render \`group.title\` and \`group.labels.map((label) => …)\` and hide a group when \`group.labels.length === 0\`. Do not hardcode section titles. Never print amenity ids, never invent a local label map, and never title a section "Comodidades da unidade".`;
|
|
297
366
|
}
|
|
@@ -380,6 +449,11 @@ export function studioCodegenContractViolations(text: string): string[] {
|
|
|
380
449
|
violations.push(name);
|
|
381
450
|
}
|
|
382
451
|
}
|
|
452
|
+
for (const name of STUDIO_SDK_CONTRACT.unpublishedPhotoExports) {
|
|
453
|
+
if (mentionsExportName(text, name) && !violations.includes(name)) {
|
|
454
|
+
violations.push(name);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
383
457
|
if (!isPhotoSearchOnPin()) {
|
|
384
458
|
for (const name of STUDIO_SDK_CONTRACT.photoSearchExports) {
|
|
385
459
|
if (mentionsExportName(text, name) && !violations.includes(name)) {
|