@garagem-ai/site-sdk 0.5.3 → 0.6.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.
@@ -0,0 +1,165 @@
1
+ import {
2
+ canonicalizeSearchHref,
3
+ readPublicSearch,
4
+ type LocationNameTables,
5
+ } from "../search-engine";
6
+ import type { Listing, SearchUi, SearchUiDictionary } from "../types";
7
+ import type { PublicSearchSnapshot } from "./types";
8
+
9
+ type SeededPublicSearchState = {
10
+ schema: SearchUi | null;
11
+ listings: Listing[];
12
+ page: number;
13
+ total: number;
14
+ totalPages: number;
15
+ locationNames: LocationNameTables | null;
16
+ catalogId: string | null;
17
+ loading: boolean;
18
+ };
19
+
20
+ function hrefParts(href: string): { pathname: string; search: string } {
21
+ const q = href.indexOf("?");
22
+ if (q < 0) return { pathname: href, search: "" };
23
+ return { pathname: href.slice(0, q), search: href.slice(q + 1) };
24
+ }
25
+
26
+ function searchHrefKey(pathname: string, search: string): string {
27
+ const qs = search.replace(/^\?/, "");
28
+ return qs ? `${pathname}?${qs}` : pathname;
29
+ }
30
+
31
+ /**
32
+ * True when both keys encode the same logical search (same pathFilters +
33
+ * applied), including when one is a non-canonical request URL and the other is
34
+ * its `canonicalizeSearchHref` rewrite.
35
+ */
36
+ export function searchKeysRepresentSameQuery(
37
+ a: string | null,
38
+ b: string,
39
+ dictionary?: SearchUiDictionary
40
+ ): boolean {
41
+ if (a == null) return false;
42
+ if (a === b) return true;
43
+ const left = hrefParts(a);
44
+ const right = hrefParts(b);
45
+ const leftCanon =
46
+ canonicalizeSearchHref(left.pathname, left.search, dictionary) ??
47
+ searchHrefKey(left.pathname, left.search);
48
+ const rightCanon =
49
+ canonicalizeSearchHref(right.pathname, right.search, dictionary) ??
50
+ searchHrefKey(right.pathname, right.search);
51
+ return leftCanon === rightCanon;
52
+ }
53
+
54
+ /**
55
+ * Schema or rows — `total: 0` alone is not enough to specialize the heading.
56
+ * Listings without an explicit `total` still count as trusted once seeded with
57
+ * a non-zero derived count (see {@link resolveSeedTotal}).
58
+ */
59
+ export function hasTrustedSearchSnapshot(
60
+ initial?: PublicSearchSnapshot | null
61
+ ): boolean {
62
+ return Boolean(initial?.schema || initial?.listings?.length);
63
+ }
64
+
65
+ /**
66
+ * Heading count for first paint. Never default a non-empty listings seed to `0`
67
+ * — that flashes cards beside "0 imóveis" until the client refetch fills total.
68
+ */
69
+ export function resolveSeedTotal(
70
+ initial?: PublicSearchSnapshot | null
71
+ ): number {
72
+ if (typeof initial?.total === "number") return initial.total;
73
+ return initial?.listings?.length ?? 0;
74
+ }
75
+
76
+ /**
77
+ * Prefer a freshly fetched location table. Never replace a painted SSR table
78
+ * with `null` when the locations request fails or is skipped.
79
+ */
80
+ export function preferFetchedLocationNames(
81
+ previous: LocationNameTables | null,
82
+ fetched: LocationNameTables | null
83
+ ): LocationNameTables | null {
84
+ return fetched ?? previous;
85
+ }
86
+
87
+ /**
88
+ * Failed `getSearchUi` must not wipe a trusted SSR schema/toolbar. Only clear
89
+ * when we were already in a client-only loading path.
90
+ */
91
+ export function shouldClearPaintedSearchOnSchemaFailure(
92
+ keepSnapshot: boolean
93
+ ): boolean {
94
+ return !keepSnapshot;
95
+ }
96
+
97
+ /**
98
+ * Painted ownership advances only after listings successfully load for a URL.
99
+ * `canonicalizeSearchHref` must not reassign the ownership key — logical
100
+ * equivalence for rewrites is handled by {@link searchKeysRepresentSameQuery}.
101
+ * Advancing early makes a later leftover-order navigation look already-painted,
102
+ * so prior cards survive a failed `queryListings`.
103
+ */
104
+ export function shouldAdvancePaintedSearchKeyOnCanonicalize(): boolean {
105
+ return false;
106
+ }
107
+
108
+ /**
109
+ * Flip `loading` only when the visitor leaves the painted logical search.
110
+ * A canonicalize rewrite of the same query must keep the SSR heading/cards
111
+ * mounted (`if (search.loading) return null` consumers).
112
+ */
113
+ export function shouldSetLoadingOnSearchKeyChange(options: {
114
+ paintedSearchKey: string | null;
115
+ searchKey: string;
116
+ dictionary?: SearchUiDictionary;
117
+ }): boolean {
118
+ return !searchKeysRepresentSameQuery(
119
+ options.paintedSearchKey,
120
+ options.searchKey,
121
+ options.dictionary
122
+ );
123
+ }
124
+
125
+ /**
126
+ * Failed `queryListings` must not replace painted cards/count while we are
127
+ * still on the logical search the snapshot (or last successful fetch) owns —
128
+ * including after `canonicalizeSearchHref` rewrites the string form. A
129
+ * different logical search may clear — the visitor navigated away.
130
+ */
131
+ export function shouldPreservePaintedListingsOnRefetchFailure(options: {
132
+ paintedSearchKey: string | null;
133
+ searchKey: string;
134
+ dictionary?: SearchUiDictionary;
135
+ }): boolean {
136
+ return searchKeysRepresentSameQuery(
137
+ options.paintedSearchKey,
138
+ options.searchKey,
139
+ options.dictionary
140
+ );
141
+ }
142
+
143
+ /** Query text already known from the URL, so the field is filled in the SSR HTML. */
144
+ export function initialQueryDraft(
145
+ pathname: string,
146
+ search: string,
147
+ dictionary?: SearchUiDictionary
148
+ ): string {
149
+ return readPublicSearch(pathname, search, dictionary).applied.query || "";
150
+ }
151
+
152
+ export function seedPublicSearchState(
153
+ initial?: PublicSearchSnapshot | null
154
+ ): SeededPublicSearchState {
155
+ return {
156
+ schema: initial?.schema ?? null,
157
+ listings: initial?.listings ?? [],
158
+ page: initial?.page ?? 1,
159
+ total: resolveSeedTotal(initial),
160
+ totalPages: initial?.totalPages ?? 1,
161
+ locationNames: initial?.locationNames ?? null,
162
+ catalogId: initial?.catalogId ?? null,
163
+ loading: !hasTrustedSearchSnapshot(initial),
164
+ };
165
+ }
@@ -11,9 +11,26 @@ export type SiteIdInput =
11
11
  | Promise<string>
12
12
  | (() => string | Promise<string>);
13
13
 
14
+ export type PublicSearchSnapshot = {
15
+ schema?: SearchUi | null;
16
+ listings?: Listing[];
17
+ page?: number;
18
+ total?: number;
19
+ totalPages?: number;
20
+ locationNames?: LocationNameTables | null;
21
+ catalogId?: string | null;
22
+ };
23
+
14
24
  export type UsePublicSearchOptions = {
15
25
  siteId: SiteIdInput;
16
26
  baseUrl?: string;
27
+ /**
28
+ * Query string without `?`, from the server page's `searchParams`.
29
+ * The hook must not call Next's search-params hook: that suspends the
30
+ * tree, and Next leaves the resolved HTML in a hidden node until JS runs.
31
+ */
32
+ search?: string;
33
+ initial?: PublicSearchSnapshot;
17
34
  };
18
35
 
19
36
  export type PublicSearchState = {
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
 
3
3
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
- import { usePathname, useRouter, useSearchParams } from "next/navigation";
4
+ import { usePathname, useRouter } from "next/navigation";
5
5
 
6
6
  import { getSearchUi, queryListings } from "../fetchers";
7
7
  import { coerceSiteId, normalizeBaseUrl } from "../internal/url";
@@ -20,6 +20,16 @@ import type {
20
20
  SiteIdInput,
21
21
  UsePublicSearchOptions,
22
22
  } from "./types";
23
+ import {
24
+ hasTrustedSearchSnapshot,
25
+ initialQueryDraft,
26
+ preferFetchedLocationNames,
27
+ seedPublicSearchState,
28
+ shouldAdvancePaintedSearchKeyOnCanonicalize,
29
+ shouldClearPaintedSearchOnSchemaFailure,
30
+ shouldPreservePaintedListingsOnRefetchFailure,
31
+ shouldSetLoadingOnSearchKeyChange,
32
+ } from "./public-search-snapshot";
23
33
  import { StagedFiltersMirror } from "./staged-filters-mirror";
24
34
 
25
35
  async function resolveSiteIdInput(siteId: SiteIdInput): Promise<string> {
@@ -34,28 +44,35 @@ function currentHref(pathname: string, search: string): string {
34
44
  export function usePublicSearch(
35
45
  options: UsePublicSearchOptions
36
46
  ): PublicSearchState {
37
- const { siteId, baseUrl } = options;
47
+ const { siteId, baseUrl, initial, search: searchFromServer = "" } = options;
38
48
  const router = useRouter();
39
49
  const pathname = usePathname() || "/imoveis";
40
- const searchParams = useSearchParams();
41
- const search = searchParams.toString();
50
+ const search = searchFromServer;
51
+ const searchKey = search ? `${pathname}?${search}` : pathname;
52
+ const [seed] = useState(() => seedPublicSearchState(initial));
53
+ const keepSnapshotRef = useRef(hasTrustedSearchSnapshot(initial));
54
+ const lastSearchKeyRef = useRef(keepSnapshotRef.current ? searchKey : null);
42
55
 
43
56
  const siteIdRef = useRef(siteId);
44
57
  siteIdRef.current = siteId;
45
58
  const siteIdToken = typeof siteId === "string" ? siteId : null;
46
59
 
47
- const [catalogId, setCatalogId] = useState<string | null>(null);
48
- const [schema, setSchema] = useState<SearchUi | null>(null);
49
- const [listings, setListings] = useState<PublicSearchState["listings"]>([]);
50
- const [page, setPage] = useState(1);
51
- const [total, setTotal] = useState(0);
52
- const [totalPages, setTotalPages] = useState(1);
53
- const [loading, setLoading] = useState(true);
54
- const [qDraft, setQDraft] = useState("");
60
+ const [catalogId, setCatalogId] = useState<string | null>(seed.catalogId);
61
+ const [schema, setSchema] = useState<SearchUi | null>(seed.schema);
62
+ const [listings, setListings] = useState<PublicSearchState["listings"]>(
63
+ seed.listings
64
+ );
65
+ const [page, setPage] = useState(seed.page);
66
+ const [total, setTotal] = useState(seed.total);
67
+ const [totalPages, setTotalPages] = useState(seed.totalPages);
68
+ const [loading, setLoading] = useState(seed.loading);
69
+ const [qDraft, setQDraft] = useState(() =>
70
+ initialQueryDraft(pathname, search, initial?.schema?.dictionary)
71
+ );
55
72
  const stagedMirrorRef = useRef(new StagedFiltersMirror());
56
73
  const [staged, setStagedState] = useState<SearchPathFilters>({});
57
74
  const [locationNames, setLocationNames] = useState<LocationNameTables | null>(
58
- null
75
+ seed.locationNames
59
76
  );
60
77
 
61
78
  const replaceStaged = useCallback((next: SearchPathFilters) => {
@@ -80,7 +97,7 @@ export function usePublicSearch(
80
97
  replaceStaged({ ...parsed.pathFilters });
81
98
  }, [parsed.pathFilters, replaceStaged]);
82
99
 
83
- const locationsRef = useRef<LocationNameTables | null>(null);
100
+ const locationsRef = useRef<LocationNameTables | null>(seed.locationNames);
84
101
 
85
102
  useEffect(() => {
86
103
  if (!schema) return;
@@ -89,15 +106,24 @@ export function usePublicSearch(
89
106
  search,
90
107
  schema.dictionary
91
108
  );
92
- if (canonical) router.replace(canonical);
109
+ if (!canonical) return;
110
+ // Never reassign painted ownership here — logical equivalence for the
111
+ // rewrite is handled by searchKeysRepresentSameQuery. Advancing early
112
+ // makes a later leftover-order navigation look already-painted.
113
+ if (shouldAdvancePaintedSearchKeyOnCanonicalize()) {
114
+ lastSearchKeyRef.current = canonical;
115
+ }
116
+ router.replace(canonical);
93
117
  }, [pathname, search, schema, router]);
94
118
 
95
119
  useEffect(() => {
96
120
  let active = true;
97
- setCatalogId(null);
98
- setSchema(null);
99
- setListings([]);
100
- setLoading(true);
121
+ if (!keepSnapshotRef.current) {
122
+ setCatalogId(null);
123
+ setSchema(null);
124
+ setListings([]);
125
+ setLoading(true);
126
+ }
101
127
  resolveSiteIdInput(siteIdRef.current)
102
128
  .then((id) => {
103
129
  if (active) setCatalogId(id);
@@ -114,11 +140,13 @@ export function usePublicSearch(
114
140
  if (!catalogId) return;
115
141
  const id = catalogId;
116
142
  let active = true;
117
- locationsRef.current = null;
118
- setLocationNames(null);
119
- setSchema(null);
120
- setListings([]);
121
- setLoading(true);
143
+ if (!keepSnapshotRef.current) {
144
+ locationsRef.current = null;
145
+ setLocationNames(null);
146
+ setSchema(null);
147
+ setListings([]);
148
+ setLoading(true);
149
+ }
122
150
  async function loadSchema() {
123
151
  try {
124
152
  const nextSchema = await getSearchUi({ siteId: id, baseUrl });
@@ -137,14 +165,25 @@ export function usePublicSearch(
137
165
  }
138
166
  }
139
167
  if (!active) return;
140
- locationsRef.current = locations;
141
- setLocationNames(locations);
168
+ const nextLocations = preferFetchedLocationNames(
169
+ locationsRef.current,
170
+ locations
171
+ );
172
+ locationsRef.current = nextLocations;
173
+ setLocationNames(nextLocations);
142
174
  setSchema(nextSchema);
175
+ keepSnapshotRef.current = false;
143
176
  } catch {
144
177
  if (active) {
145
- locationsRef.current = null;
146
- setLocationNames(null);
147
- setSchema(null);
178
+ // Trusted SSR paint survives a failed getSearchUi; client-only paths clear.
179
+ if (
180
+ shouldClearPaintedSearchOnSchemaFailure(keepSnapshotRef.current)
181
+ ) {
182
+ keepSnapshotRef.current = false;
183
+ locationsRef.current = null;
184
+ setLocationNames(null);
185
+ setSchema(null);
186
+ }
148
187
  setLoading(false);
149
188
  }
150
189
  }
@@ -161,7 +200,15 @@ export function usePublicSearch(
161
200
  const id = catalogId;
162
201
  let active = true;
163
202
  async function loadListings() {
164
- setLoading(true);
203
+ if (
204
+ shouldSetLoadingOnSearchKeyChange({
205
+ paintedSearchKey: lastSearchKeyRef.current,
206
+ searchKey,
207
+ dictionary: currentSchema.dictionary,
208
+ })
209
+ ) {
210
+ setLoading(true);
211
+ }
165
212
  try {
166
213
  const { pathFilters, applied } = readPublicSearch(
167
214
  pathname,
@@ -183,15 +230,27 @@ export function usePublicSearch(
183
230
  setPage(response.page || 1);
184
231
  setTotal(response.total || 0);
185
232
  setTotalPages(response.totalPages || 1);
233
+ lastSearchKeyRef.current = searchKey;
234
+ keepSnapshotRef.current = false;
186
235
  } catch {
187
- if (active) {
236
+ if (
237
+ active &&
238
+ !shouldPreservePaintedListingsOnRefetchFailure({
239
+ paintedSearchKey: lastSearchKeyRef.current,
240
+ searchKey,
241
+ dictionary: currentSchema.dictionary,
242
+ })
243
+ ) {
188
244
  setListings([]);
189
245
  setPage(1);
190
246
  setTotal(0);
191
247
  setTotalPages(1);
248
+ keepSnapshotRef.current = false;
192
249
  }
193
250
  } finally {
194
- if (active) setLoading(false);
251
+ if (active) {
252
+ setLoading(false);
253
+ }
195
254
  }
196
255
  }
197
256
  loadListings();
@@ -18,11 +18,13 @@ export const STUDIO_SDK_CONTRACT = {
18
18
  * Exact pin for generated Studio sites. Must match a tarball already on
19
19
  * npm — v0 installs this version. After a later changeset publishes, bump
20
20
  * this and move that release's names from `optionalReactExports` /
21
- * `unpublishedSearchExports` into the prompt-safe lists. Do not bump here
22
- * until that tarball is on npm. Headless SearchPage already shipped in
23
- * 0.4.12 (`visibleSearchFilters` / `toolbarFilterIds` are on that pin).
21
+ * `unpublishedSearchExports` / `unpublishedPhoneExports` into the
22
+ * prompt-safe lists. Do not bump here until that tarball is on npm.
23
+ * Phone mask helpers shipped in 0.6.0. Search filter helpers
24
+ * (`visibleSearchFilters` / `toolbarFilterIds`) shipped in 0.4.12 and
25
+ * remain on this pin.
24
26
  */
25
- minNpmVersion: "0.4.12",
27
+ minNpmVersion: "0.6.0",
26
28
  /** Historical: older tarballs inject card CSS when those components mount. */
27
29
  selfInjectSince: "0.4.2",
28
30
  chromeStrategy: "app-owned" as const,
@@ -74,12 +76,32 @@ export const STUDIO_SDK_CONTRACT = {
74
76
  "listingBusinessLabel",
75
77
  "formatListingPrice",
76
78
  ] as const,
79
+ /**
80
+ * Prompt-safe phone helpers on `minNpmVersion` (published in 0.6.0).
81
+ */
82
+ phoneExports: [
83
+ "PHONE_COUNTRIES",
84
+ "formatPhoneNational",
85
+ "toE164",
86
+ "isValidPhone",
87
+ "parsePhoneInput",
88
+ "phoneCountrySearchValue",
89
+ "findPhoneCountry",
90
+ "remaskPhoneForCountry",
91
+ ] as const,
92
+ /**
93
+ * Headless phone helpers in git but not on `minNpmVersion`. Prompts,
94
+ * completeness, and repair text must not mention these until the pin
95
+ * bumps — v0 installs the pin and the ESM loader throws on missing
96
+ * named exports.
97
+ */
98
+ unpublishedPhoneExports: [] as const,
77
99
  amenityExports: ["listingAmenityGroups"] as const,
78
100
  /**
79
- * Names already on the pinned npm tarball (`minNpmVersion` / 0.4.12) —
80
- * safe for Studio prompts and completeness. Includes
81
- * `visibleSearchFilters` + `toolbarFilterIds` (shipped in 0.4.12). Do not
82
- * confuse with `unpublishedSearchExports` (`searchChromeModel`, …).
101
+ * Names already on the pinned npm tarball (`minNpmVersion`) — safe for
102
+ * Studio prompts and completeness. Includes `visibleSearchFilters` +
103
+ * `toolbarFilterIds` (shipped in 0.4.12). Do not confuse with
104
+ * `unpublishedSearchExports` (`searchChromeModel`, …).
83
105
  */
84
106
  searchExports: [
85
107
  "searchResultsHeading",
@@ -139,7 +161,7 @@ Every page section is two layers: (1) surface — \`section\` / header / footer
139
161
  }
140
162
 
141
163
  export function studioSearchLandmarkInstruction(): string {
142
- return `Search at \`/imoveis\` (hard rule). The page landmark is \`<main className="${STUDIO_SITE_LAYOUT.searchMainClassName}">\` with one child \`${STUDIO_SITE_LAYOUT.wrapperClassName}\`. Wire the catalog with \`usePublicSearch\` from \`${STUDIO_SDK_PACKAGE}/react\` inside \`<Suspense>\` whose fallback is the site listing-card-skeleton module. Do not wrap the search UI in \`<section>\` or a second max-width. The page owns the SEO heading as \`<div data-slot="search-heading">\`: count \`<span data-slot="search-heading-count">\` FIRST, then \`<h1 data-slot="search-heading-title">\` — never put the count inside the H1 and never put the h1 first. \`pt-4 pb-12\` is the default on that search \`<main>\` — change those values if the design needs it. Flush search (glued to the header) is allowed only with \`${STUDIO_SITE_LAYOUT.searchFlushMarker}\` on that \`<main>\`. Never add that vertical padding to home heroes or listing galleries.`;
164
+ return `Search at \`/imoveis\` (hard rule). The page landmark is \`<main className="${STUDIO_SITE_LAYOUT.searchMainClassName}">\` with one child \`${STUDIO_SITE_LAYOUT.wrapperClassName}\`. The server page awaits the catalog and renders it with \`usePublicSearch\` from \`${STUDIO_SDK_PACKAGE}/react\` (\`search\` from the page searchParams, plus \`initial\`). Do not wrap that UI in \`<Suspense>\` and do not add a route \`loading\` file. A suspended page is streamed into a hidden node and stays invisible until JavaScript runs. Do not wrap the search UI in \`<section>\` or a second max-width. The page owns the SEO heading as \`<div data-slot="search-heading">\`: count \`<span data-slot="search-heading-count">\` FIRST, then \`<h1 data-slot="search-heading-title">\` — never put the count inside the H1 and never put the h1 first. \`pt-4 pb-12\` is the default on that search \`<main>\` — change those values if the design needs it. Flush search (glued to the header) is allowed only with \`${STUDIO_SITE_LAYOUT.searchFlushMarker}\` on that \`<main>\`. Never add that vertical padding to home heroes or listing galleries.`;
143
165
  }
144
166
 
145
167
  const REACT_SDK_NAMED_IMPORT_RE =
@@ -215,12 +237,13 @@ export function studioSdkPinInstruction(): string {
215
237
 
216
238
  export function studioLeadInstruction(): string {
217
239
  const names = STUDIO_SDK_CONTRACT.leadExports.join(", ");
218
- return `Listing-detail visit/contact leads: import ${names} from \`${STUDIO_SDK_PACKAGE}\` (the main package, not \`/react\`). Call \`submitVisitLead\` / \`submitContactLead\` — never concatenate a leads webhook URL and never POST the Showcase demo leads route.`;
240
+ const phone = STUDIO_SDK_CONTRACT.phoneExports.join(", ");
241
+ return `Listing-detail visit/contact leads: import ${names} from \`${STUDIO_SDK_PACKAGE}\` (the main package, not \`/react\`). Call \`submitVisitLead\` / \`submitContactLead\` — never concatenate a leads webhook URL and never POST the Showcase demo leads route. Phone fields: import ${phone} from the same package. Display draft is \`formatPhoneNational\` (default country \`BR\`); changing country calls \`remaskPhoneForCountry\`; submit \`toE164\` and require \`isValidPhone\`. Do not invent a second mask and do not import \`@garagem/ui\` PhoneInput.`;
219
242
  }
220
243
 
221
244
  export function studioListingCardInstruction(): string {
222
245
  const names = STUDIO_SDK_CONTRACT.listingCardExports.join(", ");
223
- return `Listing card (site-wide). WRITE \`components/garagem/listing-card.tsx\` — one module for home, search results, and similar listings. Do not invent a second card. From \`${STUDIO_SDK_PACKAGE}\` import ${names}. \`const model = toListingCardModel(listing)\`. href is \`model.href\` / \`listingPublicPath(listing)\` — never \`listing.id\` or \`property.id\`. Skip the card or omit the link when href is empty (no \`href=""\`, no \`href="#"\`). Must show title (\`model.title\`) and price (\`model.priceLabel\` — “Sob consulta” when private; \`model.pricePeriod\` “/mês” when present, omit when null). Photo: \`model.coverSrc\` as img \`src\`, alt \`model.coverAlt\`; skip the img when cover is missing; an empty-photo block is allowed; never Unsplash, \`/placeholder.svg\`, or invented \`?query=\` images. Show when present, omit the line when missing: \`locationLabel\` (else \`propertyType\`), \`listingBusinessLabel\` / \`model.businessLabel\`, bedrooms, bathrooms, parkingSpaces, area via \`formatAreaM2\`. Never interpolate the listing object as a React child. Design is free (grid vs carousel vs mosaic; radius is site \`--radius\`). WRITE \`components/garagem/listing-card-skeleton.tsx\` for the search \`<Suspense>\` fallback — it should suggest the card surface, never the text “Carregando imóveis…”. Do not \`if (search.loading) return\` that skeleton inside the search client.`;
246
+ return `Listing card (site-wide). WRITE \`components/garagem/listing-card.tsx\` — one module for home, search results, and similar listings. Do not invent a second card. From \`${STUDIO_SDK_PACKAGE}\` import ${names}. \`const model = toListingCardModel(listing)\`. href is \`model.href\` / \`listingPublicPath(listing)\` — never \`listing.id\` or \`property.id\`. Skip the card or omit the link when href is empty (no \`href=""\`, no \`href="#"\`). Must show title (\`model.title\`) and price (\`model.priceLabel\` — “Sob consulta” when private; \`model.pricePeriod\` “/mês” when present, omit when null). Photo: \`model.coverSrc\` as img \`src\`, alt \`model.coverAlt\`; skip the img when cover is missing; an empty-photo block is allowed; never Unsplash, \`/placeholder.svg\`, or invented \`?query=\` images. Show when present, omit the line when missing: \`locationLabel\` (else \`propertyType\`), \`listingBusinessLabel\` / \`model.businessLabel\`, bedrooms, bathrooms, parkingSpaces, area via \`formatAreaM2\`. Never interpolate the listing object as a React child. Design is free (grid vs carousel vs mosaic; radius is site \`--radius\`). WRITE \`components/garagem/listing-card-skeleton.tsx\` only for a slot whose content is still unknown — never as a \`<Suspense>\` fallback that replaces the catalog, and never the text “Carregando imóveis…”. Do not \`if (search.loading) return\` that skeleton inside the search client.`;
224
247
  }
225
248
 
226
249
  export function studioListingDetailInstruction(): string {
@@ -235,7 +258,7 @@ export function studioAmenityInstruction(): string {
235
258
  export function studioSearchInstruction(): string {
236
259
  const reactNames = STUDIO_SDK_CONTRACT.reactExports.join(", ");
237
260
  const libNames = STUDIO_SDK_CONTRACT.searchExports.join(", ");
238
- return `Search: import ${reactNames} from \`${STUDIO_SDK_PACKAGE}/react\`. From \`${STUDIO_SDK_PACKAGE}\` import ${libNames}. Call \`const search = usePublicSearch({ siteId, baseUrl: GARAGEM_API_BASE })\` in a client component inside \`<Suspense>\` (\`useSearchParams\`). Compose the page UI in the app — do not paste a canonical search TSX. Required chrome (design is free; omit none): query (\`qDraft\` / \`setQDraft\` / form \`preventDefault\` + \`submitQuery\`), heading (count span FIRST then h1 from \`searchResultsHeading(search.pathFilters, search.schema?.dictionary, search.locationNames)\` — never \`searchResultsHeading({})\`), toolbar (\`toolbarFilterIds\` + \`applyFilter\`; range “Atualizar” on that toolbar item only) vs sheet (\`visibleSearchFilters\` extras, \`stageFilter\`, one footer \`applyStaged\`), sort (\`searchSortOptions\` + \`setSort\`; first option id is \`""\` / “Mais relevantes” — map **only** that empty id to Select sentinel \`"relevancia"\` (\`opt.id || "relevancia"\`), never \`SelectItem value=""\` and never give “Mais recentes” (\`id: "recentes"\`, \`?ordenar=recentes\`) that sentinel; on change \`setSort(id === "relevancia" ? "" : id)\` so recentes stays recentes. Closed trigger shows the option \`.label\`, never \`{search.applied.sort}\`), grid (\`listings.map\` + the site listing-card module; listing-card-skeleton is only the Suspense fallback; do not \`throw\` in that chrome), pagination (\`paginationPages\` + \`hrefWithExplicitPage\`). Never interpolate \`schema\`, \`pathFilters\`, or a filter object as a React child. \`queryListings\` key is \`params\`. The URL is the document. Count text is \`{search.total}\` only. Heading is one row; font size lives on the container and the span and h1 use \`font-size: inherit\`. Sort trigger shows the option label (“Mais relevantes” when \`ordenar\` is absent), chevron at the end, same height as the toolbar controls. Toolbar ranges open a Popover form (not DropdownMenu — Menu typeahead swallows digit keys) whose submit calls \`applyFilter\`; the popup clips and the two inputs stay inside (\`min-w-0\`, no \`w-64\`). Reset min/max drafts when the popover opens and when the applied path range changes. The sheet omits toolbar ids (price, bedrooms) so Preço is never a heading without inputs. Sheet DialogContent uses \`h-[min(640px,85dvh)]\` (not max-h alone) so the body ScrollArea can move. Tipo de imóvel, características and comodidades each use a nested ScrollArea with \`h-56 overflow-hidden\` (viewport \`h-full\`). Area is two inputs in schema order with no “Aplicar”; the footer stages then applyStaged. Never read \`staged[filter.id]\` — path keys are \`bedrooms\` / \`listingType\` / \`bathrooms\`. Bedrooms Select reads \`pathFilters.bedrooms\` so \`/imoveis/4-quartos\` checks \`"4"\` and shows the same trigger dot as price. Bathrooms and parking pressed state uses \`pathFilterHasOption\`. Limpar keeps location plus toolbar price and bedrooms via \`clearStagedPathFilters\` and \`toolbarFilterIds\`; do not call \`clearStaged\` for that button. It enables only when staged has a path filter other than location and those kept toolbar ids. Each multi-select \`stageFilter\` value is one option id, never a concatenated slug; \`checked\` uses \`pathFilterHasOption\`. Listing type does not pass the clicked id: no path value shows every checkbox checked, unchecking one stages the other option's id, and the last box stays checked. Price inputs use formatGroupedInteger. The closed price and bedrooms triggers keep the filter label plus a dot when set — never the literal range. Empty price calls applyFilter(id, undefined); never send 0 or 1000000000. Area is a plain integer (not that mask). The results button stageFilter property_area_total with both drafts, then applyStaged. Never send 0 or 100000. Count buttons pass the option id (\`"2"\`), never the label \`"2+"\`. Property type, features, and amenities render in pt-BR label order. Do not set \`[data-slot="search-sort"] { flex-direction: column }\` in a \`<style>\` tag; that selector is row so the chevron sits beside the label. Empty copy: ${JSON.stringify(SEARCH_EMPTY_COPY)}`;
261
+ return `Search: import ${reactNames} from \`${STUDIO_SDK_PACKAGE}/react\`. From \`${STUDIO_SDK_PACKAGE}\` import ${libNames}. Prefetch \`getSearchUi\` + \`queryListings\` on the server page. \`const search = usePublicSearch({ siteId, baseUrl: GARAGEM_API_BASE, search: searchFromServer, initial })\` where \`searchFromServer\` is \`new URLSearchParams(await searchParams).toString()\` — never shorthand \`{ search }\` beside \`const search =\` (temporal dead zone). Do not wrap this UI in \`<Suspense>\` and do not add a route \`loading\` file — heading and cards are ordinary elements in the document, visible with JavaScript off. Compose the page UI in the app — do not paste a canonical search TSX. Required chrome (design is free; omit none): query (\`qDraft\` / \`setQDraft\` / form \`preventDefault\` + \`submitQuery\`), heading (count span FIRST then h1 from \`searchResultsHeading(search.pathFilters, search.schema?.dictionary, search.locationNames)\` — never \`searchResultsHeading({})\`), toolbar (\`toolbarFilterIds\` + \`applyFilter\`; range “Atualizar” on that toolbar item only) vs sheet (\`visibleSearchFilters\` extras, \`stageFilter\`, one footer \`applyStaged\`), sort (\`searchSortOptions\` + \`setSort\`; first option id is \`""\` / “Mais relevantes” — map **only** that empty id to Select sentinel \`"relevancia"\` (\`opt.id || "relevancia"\`), never \`SelectItem value=""\` and never give “Mais recentes” (\`id: "recentes"\`, \`?ordenar=recentes\`) that sentinel; on change \`setSort(id === "relevancia" ? "" : id)\` so recentes stays recentes. Closed trigger shows the option \`.label\`, never \`{search.applied.sort}\`), grid (\`listings.map\` + the site listing-card module; listing-card-skeleton only for a slot whose content is still unknown, never as a Suspense fallback; do not \`throw\` in that chrome), pagination (\`paginationPages\` + \`hrefWithExplicitPage\`). Never interpolate \`schema\`, \`pathFilters\`, or a filter object as a React child. \`queryListings\` key is \`params\`. The URL is the document. Count text is \`{search.total}\` only. Heading is one row; font size lives on the container and the span and h1 use \`font-size: inherit\`. Sort trigger shows the option label (“Mais relevantes” when \`ordenar\` is absent), chevron at the end, same height as the toolbar controls. Toolbar ranges open a Popover form (not DropdownMenu — Menu typeahead swallows digit keys) whose submit calls \`applyFilter\`; the popup clips and the two inputs stay inside (\`min-w-0\`, no \`w-64\`). Reset min/max drafts when the popover opens and when the applied path range changes. The sheet omits toolbar ids (price, bedrooms) so Preço is never a heading without inputs. Sheet DialogContent uses \`h-[min(640px,85dvh)]\` (not max-h alone) so the body ScrollArea can move. Tipo de imóvel, características and comodidades each use a nested ScrollArea with \`h-56 overflow-hidden\` (viewport \`h-full\`). Area is two inputs in schema order with no “Aplicar”; the footer stages then applyStaged. Never read \`staged[filter.id]\` — path keys are \`bedrooms\` / \`listingType\` / \`bathrooms\`. Bedrooms Select reads \`pathFilters.bedrooms\` so \`/imoveis/4-quartos\` checks \`"4"\` and shows the same trigger dot as price. Bathrooms and parking pressed state uses \`pathFilterHasOption\`. Limpar keeps location plus toolbar price and bedrooms via \`clearStagedPathFilters\` and \`toolbarFilterIds\`; do not call \`clearStaged\` for that button. It enables only when staged has a path filter other than location and those kept toolbar ids. Each multi-select \`stageFilter\` value is one option id, never a concatenated slug; \`checked\` uses \`pathFilterHasOption\`. Listing type does not pass the clicked id: no path value shows every checkbox checked, unchecking one stages the other option's id, and the last box stays checked. Price inputs use formatGroupedInteger. The closed price and bedrooms triggers keep the filter label plus a dot when set — never the literal range. Empty price calls applyFilter(id, undefined); never send 0 or 1000000000. Area is a plain integer (not that mask). The results button stageFilter property_area_total with both drafts, then applyStaged. Never send 0 or 100000. Count buttons pass the option id (\`"2"\`), never the label \`"2+"\`. Property type, features, and amenities render in pt-BR label order. Do not set \`[data-slot="search-sort"] { flex-direction: column }\` in a \`<style>\` tag; that selector is row so the chevron sits beside the label. Empty copy: ${JSON.stringify(SEARCH_EMPTY_COPY)}`;
239
262
  }
240
263
 
241
264
  export function studioChromeInstruction(): string {
@@ -265,6 +288,11 @@ export function studioCodegenContractViolations(text: string): string[] {
265
288
  violations.push(name);
266
289
  }
267
290
  }
291
+ for (const name of STUDIO_SDK_CONTRACT.unpublishedPhoneExports) {
292
+ if (mentionsExportName(text, name) && !violations.includes(name)) {
293
+ violations.push(name);
294
+ }
295
+ }
268
296
  const pin = STUDIO_SDK_CONTRACT.minNpmVersion;
269
297
  const available = reactExportsAvailableAt(pin);
270
298
  for (const name of parseReactSdkNamedImports(text)) {
package/src/types.ts CHANGED
@@ -84,6 +84,8 @@ export interface Listing {
84
84
  description: string;
85
85
  businessType: ListingBusinessType;
86
86
  price: number | null;
87
+ /** ISO 4217 currency code. Defaults to BRL when absent on older payloads. */
88
+ currency?: string;
87
89
  priceVisibility: ListingPriceVisibility;
88
90
  status: string;
89
91
  featured: boolean;