@garagem-ai/site-sdk 0.6.1 → 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/src/index.ts CHANGED
@@ -11,8 +11,8 @@
11
11
  *
12
12
  * 2. Client object (binds defaults):
13
13
  *
14
- * import { createGaragemClient } from "@garagem-ai/site-sdk";
15
- * const garagem = createGaragemClient({ siteId: "abc" });
14
+ * import { createClient } from "@garagem-ai/site-sdk";
15
+ * const garagem = createClient({ siteId: "abc", publishableKey: "pk_live_…" });
16
16
  * const { listings } = await garagem.getListings();
17
17
  *
18
18
  * Works in Node, Edge runtimes, Cloudflare Workers, Bun, Deno and the
@@ -257,8 +257,13 @@ export {
257
257
  studioLeadInstruction,
258
258
  studioListingCardInstruction,
259
259
  studioListingDetailInstruction,
260
+ studioPhotoInstruction,
261
+ studioPhotoInstructionFor,
260
262
  studioSearchInstruction,
261
263
  studioSearchLandmarkInstruction,
264
+ studioPublishableKeyInstruction,
265
+ studioPhotoSearchInstruction,
266
+ isPhotoSearchOnPin,
262
267
  studioSdkPinInstruction,
263
268
  studioSiteWidthCss,
264
269
  hasShowcaseLeadsPostUrl,
@@ -267,7 +272,92 @@ export {
267
272
  } from "./studio-contract";
268
273
 
269
274
  export {
275
+ createClient,
270
276
  createGaragemClient,
271
277
  type CreateGaragemClientOptions,
272
278
  type GaragemClient,
273
279
  } from "./client";
280
+
281
+ // ---------------------------------------------------------------------------
282
+ // Photo intelligence: captions / room groups on `ListingDetail.media` and
283
+ // "imóveis com fotos parecidas" (`getSimilarByPhoto`). Self-contained block.
284
+ // ---------------------------------------------------------------------------
285
+ export type {
286
+ ListingPhotoGroup,
287
+ SimilarByPhotoItem,
288
+ SimilarByPhotoResult,
289
+ SimilarPhotoMatch,
290
+ } from "./types-photos";
291
+
292
+ export {
293
+ getSimilarByPhoto,
294
+ type GetSimilarByPhotoOptions,
295
+ } from "./fetchers-photos";
296
+
297
+ export {
298
+ PHOTO_GROUP_OTHER_KEY,
299
+ PHOTO_GROUP_OTHER_LABEL,
300
+ listingPhotoGroups,
301
+ listingVisualHighlights,
302
+ photoRoomLabel,
303
+ type ListingVisualHighlightsOptions,
304
+ } from "./listing-photos";
305
+
306
+ // ---------------------------------------------------------------------------
307
+ // Market data (requires the IPTU module — `iptu_itbi_integration`).
308
+ // Self-contained block: fetchers, headless pt-BR labels and types. Every
309
+ // helper answers `available: false` for tenants without the module.
310
+ // ---------------------------------------------------------------------------
311
+ export {
312
+ getListingMarketPosition,
313
+ getNeighborhoodSummary,
314
+ requestPriceEstimate,
315
+ type GetListingMarketPositionOptions,
316
+ type GetNeighborhoodSummaryOptions,
317
+ type RequestPriceEstimateOptions,
318
+ } from "./fetchers-market";
319
+
320
+ export { marketPositionLabel, priceBandLabel } from "./market-labels";
321
+
322
+ export type {
323
+ ListingMarketPosition,
324
+ MarketListingType,
325
+ MarketPriceBand,
326
+ MarketPropertyType,
327
+ MarketUnavailableReason,
328
+ NeighborhoodSummary,
329
+ NeighborhoodSummaryQuery,
330
+ PriceEstimate,
331
+ PriceEstimateConfidence,
332
+ PriceEstimateInput,
333
+ } from "./types-market";
334
+
335
+ export {
336
+ marketExportsAvailableAt,
337
+ studioMarketInstruction,
338
+ } from "./studio-contract";
339
+
340
+ // ---------------------------------------------------------------------------
341
+ // Photo search ("busca pelo que as fotos mostram"): search a site's catalog by
342
+ // what the public photos show and use the matched photo as the card cover.
343
+ // Self-contained block — the React hook lives on `@garagem-ai/site-sdk/react`.
344
+ // ---------------------------------------------------------------------------
345
+ export {
346
+ PHOTO_SEARCH_MIN_QUERY_LENGTH,
347
+ photoSearchUrl,
348
+ searchListingPhotos,
349
+ type SearchListingPhotosOptions,
350
+ } from "./fetchers-photo-search";
351
+ export {
352
+ MATCHED_PHOTO_COVER_MAX_DISTANCE,
353
+ applyMatchedPhotoCover,
354
+ resolveMatchedCoverPhoto,
355
+ type ApplyMatchedPhotoCoverOptions,
356
+ } from "./photo-search-cover";
357
+ export type {
358
+ ListingWithMatchedPhoto,
359
+ MatchedListingPhoto,
360
+ PhotoSearchItem,
361
+ PhotoSearchParams,
362
+ PhotoSearchResult,
363
+ } from "./types-photo-search";
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Publishable-key header and error parsing shared by the SDK fetchers.
3
+ *
4
+ * The key is an identifier (`pk_live_…`), not a secret. Foundation accepts
5
+ * it as `X-Garagem-Publishable-Key` or `Authorization: Bearer pk_live_…`.
6
+ */
7
+
8
+ export const PUBLISHABLE_KEY_HEADER = "X-Garagem-Publishable-Key";
9
+
10
+ export function publishableKeyHeaders(
11
+ publishableKey?: string | null
12
+ ): Record<string, string> {
13
+ const key = publishableKey?.trim();
14
+ if (!key) return {};
15
+ return { [PUBLISHABLE_KEY_HEADER]: key };
16
+ }
17
+
18
+ /** Merge the publishable-key header into a plain-object `fetch` init. */
19
+ export function withPublishableKeyHeader<T extends { headers?: HeadersInit }>(
20
+ init: T,
21
+ publishableKey?: string | null
22
+ ): T {
23
+ const extra = publishableKeyHeaders(publishableKey);
24
+ if (Object.keys(extra).length === 0) return init;
25
+ const current = init.headers;
26
+ const base = plainHeaders(current);
27
+ return { ...init, headers: { ...base, ...extra } };
28
+ }
29
+
30
+ function plainHeaders(
31
+ headers: HeadersInit | undefined
32
+ ): Record<string, string> {
33
+ const out: Record<string, string> = {};
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
+ // `HeadersInit` stays a union after the class/array checks in some lib
48
+ // targets. Copy string entries only so the result is always a plain record.
49
+ for (const [name, value] of Object.entries(
50
+ headers as Record<string, unknown>
51
+ )) {
52
+ if (typeof value === "string") out[name] = value;
53
+ }
54
+ return out;
55
+ }
56
+
57
+ export interface ParsedSdkErrorBody {
58
+ reason: string | null;
59
+ retryAfterSeconds: number | null;
60
+ /** Short human text from `error` or the raw body. */
61
+ summary: string;
62
+ }
63
+
64
+ function finiteNonNegative(value: unknown): number | null {
65
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
66
+ return value;
67
+ }
68
+ if (typeof value === "string" && value.trim()) {
69
+ const parsed = Number(value);
70
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed;
71
+ }
72
+ return null;
73
+ }
74
+
75
+ export function parseSdkErrorBody(text: string): ParsedSdkErrorBody {
76
+ const raw = text ? text.slice(0, 200) : "";
77
+ if (!text) {
78
+ return { reason: null, retryAfterSeconds: null, summary: "" };
79
+ }
80
+ try {
81
+ const body = JSON.parse(text) as unknown;
82
+ if (!body || typeof body !== "object") {
83
+ return { reason: null, retryAfterSeconds: null, summary: raw };
84
+ }
85
+ const record = body as Record<string, unknown>;
86
+ const reason =
87
+ typeof record.reason === "string" && record.reason ? record.reason : null;
88
+ const retryAfterSeconds = finiteNonNegative(
89
+ record.retryAfterSeconds ?? record.retryAfter
90
+ );
91
+ const errorText =
92
+ typeof record.error === "string" && record.error ? record.error : raw;
93
+ return {
94
+ reason,
95
+ retryAfterSeconds,
96
+ summary: errorText.slice(0, 200),
97
+ };
98
+ } catch {
99
+ return { reason: null, retryAfterSeconds: null, summary: raw };
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Seconds the caller should wait. The `Retry-After` header wins (delta
105
+ * seconds, or an HTTP date). Otherwise the JSON `retryAfterSeconds`.
106
+ */
107
+ export function retryAfterFromResponse(
108
+ response: { headers: { get(name: string): string | null } },
109
+ bodySeconds: number | null,
110
+ nowMs: number = Date.now()
111
+ ): number | null {
112
+ const header = response.headers.get("Retry-After")?.trim();
113
+ if (header) {
114
+ const delta = finiteNonNegative(header);
115
+ if (delta != null) return delta;
116
+ const at = Date.parse(header);
117
+ if (Number.isFinite(at)) {
118
+ return Math.max(0, Math.ceil((at - nowMs) / 1000));
119
+ }
120
+ }
121
+ return bodySeconds;
122
+ }
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
- const retryAfter = Number(response.headers.get("Retry-After") ?? "");
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
- retryAfterSeconds: Number.isFinite(retryAfter) ? retryAfter : undefined,
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
+ }