@garagem-ai/site-sdk 0.11.0 → 0.12.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/index.mjs CHANGED
@@ -437,6 +437,48 @@ async function getCmsEntry(options) {
437
437
  return data;
438
438
  }
439
439
 
440
+ // src/share.ts
441
+ async function getShareLink(options) {
442
+ const { token, password, baseUrl, fetch: fetchImpl, next } = options;
443
+ if (!token || !token.trim()) {
444
+ throw new TypeError("getShareLink: `token` is required");
445
+ }
446
+ const base = normalizeBaseUrl(baseUrl);
447
+ const url = `${base}/api/sites/share/${encodeURIComponent(token)}`;
448
+ const doFetch = fetchImpl ?? fetch;
449
+ const baseInit = password ? {
450
+ method: "POST",
451
+ headers: {
452
+ Accept: "application/json",
453
+ "Content-Type": "application/json"
454
+ },
455
+ body: JSON.stringify({ password }),
456
+ next
457
+ } : { method: "GET", headers: { Accept: "application/json" }, next };
458
+ const init = withPublishableKeyHeader(baseInit, options.publishableKey);
459
+ const response = await doFetch(url, init);
460
+ if (response.ok) {
461
+ return { ok: true, ...await response.json() };
462
+ }
463
+ const EXPECTED_STATUSES = /* @__PURE__ */ new Set([400, 401, 403, 404, 410]);
464
+ if (EXPECTED_STATUSES.has(response.status)) {
465
+ const body = await response.json().catch(() => ({}));
466
+ return {
467
+ ok: false,
468
+ status: response.status,
469
+ reason: body.reason ?? null,
470
+ message: body.error ?? "Share link unavailable",
471
+ ...body.listingCode ? { listingCode: body.listingCode } : {},
472
+ ...body.site ? { site: body.site } : {}
473
+ };
474
+ }
475
+ const text2 = await response.text().catch(() => "");
476
+ throw new GaragemSdkError(
477
+ `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${text2 ? ` \u2014 ${text2.slice(0, 200)}` : ""}`,
478
+ { status: response.status, url }
479
+ );
480
+ }
481
+
440
482
  // src/schedule.ts
441
483
  var VISIT_TIME_ZONE = "America/Sao_Paulo";
442
484
  var HHMM_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;
@@ -3042,10 +3084,11 @@ var STUDIO_SDK_CONTRACT = {
3042
3084
  * Phone mask helpers shipped in 0.6.0. Map search
3043
3085
  * (`useMapSearch`, `searchListingsInBounds`) shipped in 0.9.0 — 0.7.0
3044
3086
  * does not export them. Property registration shipped in 0.10.0.
3045
- * Search filter helpers (`visibleSearchFilters` / `toolbarFilterIds`)
3046
- * shipped in 0.4.12 and remain on this pin.
3087
+ * Weighted map buckets (`map.buckets`, clustered by the hook) shipped
3088
+ * in 0.11.0. Search filter helpers (`visibleSearchFilters` /
3089
+ * `toolbarFilterIds`) shipped in 0.4.12 and remain on this pin.
3047
3090
  */
3048
- minNpmVersion: "0.10.0",
3091
+ minNpmVersion: "0.11.0",
3049
3092
  /** Historical: older tarballs inject card CSS when those components mount. */
3050
3093
  selfInjectSince: "0.4.2",
3051
3094
  chromeStrategy: "app-owned",
@@ -3244,11 +3287,27 @@ var STUDIO_SDK_CONTRACT = {
3244
3287
  "isValidEmail",
3245
3288
  "isValidName"
3246
3289
  ],
3247
- sellerLeadSince: "0.10.0"
3290
+ sellerLeadSince: "0.10.0",
3291
+ /**
3292
+ * Share-link page (`/p/[token]`). Prompt-safe only once `minNpmVersion`
3293
+ * reaches `shareLinkSince`. Below it `studioShareLinkInstruction` prints
3294
+ * nothing and `studioCodegenContractViolations` flags `getShareLink` —
3295
+ * v0 installs the pin and copies any identifier it sees.
3296
+ */
3297
+ shareExports: ["getShareLink"],
3298
+ shareLinkSince: "0.12.0"
3248
3299
  };
3249
3300
  function isSellerLeadOnPin(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3250
3301
  return compareSemver(pin, STUDIO_SDK_CONTRACT.sellerLeadSince) >= 0;
3251
3302
  }
3303
+ function isShareLinkOnPin(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3304
+ return compareSemver(pin, STUDIO_SDK_CONTRACT.shareLinkSince) >= 0;
3305
+ }
3306
+ function studioShareLinkInstruction(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3307
+ if (!isShareLinkOnPin(pin)) return "";
3308
+ const name = STUDIO_SDK_CONTRACT.shareExports[0];
3309
+ return `Share links (\`/p/[token]\`): add a server page \`app/p/[token]/page.tsx\`. Read \`token\` from the route params and \`const result = await ${name}({ token, baseUrl: GARAGEM_API_BASE })\`. When \`result.ok\` is false and \`result.reason\` is \`password_required\` or \`password_invalid\`, render a password form and submit \`getShareLink({ token, password, baseUrl: GARAGEM_API_BASE })\`. For \`not_found\`, \`inactive\`, or \`expired\`, say the link is no longer available \u2014 do not render a generic framework 404. When \`result.ok\` and \`result.listing\` is set, render that listing with the same listing-detail module \`/imoveis\` already uses (\`listingDetailModel\` and the site gallery). Do not invent a second listing layout and do not proxy the page to another host.`;
3310
+ }
3252
3311
  function studioSellerLeadSdkInstruction(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3253
3312
  if (!isSellerLeadOnPin(pin)) return "";
3254
3313
  const names = STUDIO_SDK_CONTRACT.sellerLeadExports.join(", ");
@@ -3402,11 +3461,21 @@ function studioMapsInstruction(options = {}) {
3402
3461
  const names = STUDIO_SDK_CONTRACT.mapsExports.join(", ");
3403
3462
  return `Maps on listing detail: from \`${STUDIO_SDK_PACKAGE}\` import ${names}. \`listing.location.coordinates\` is already masked by the site's privacy settings (\u2248100 m by default) \u2014 pass the listing object as-is; never un-mask, never re-geocode the street address to get a sharper point, never add decimals (\`maxDecimals\` can only coarsen). Always pass \`siteId\` (the resolved site id / publishable key) so maps.fndn.ai meters the site. Static map: \`const mapSrc = listingStaticMapUrl(listing, { width: 640, height: 320, zoom: 15, style: "roadmap", siteId })\` then \`{mapSrc ? <img src={mapSrc} alt={model.location.label} /> : null}\` \u2014 \`null\` means no coordinates, so omit the block (never a placeholder image). Zoom is capped by the coordinate precision (16 on the default mask); do not work around it. Street View: on the server page \`const sv = await listingStreetViewAvailable(listing, { siteId })\` (metadata is free), and only when \`sv.available\` render \`<img src={listingStreetViewUrl(listing, { width: 640, height: 400, siteId })} alt="Street View" />\` \u2014 the image is billed per load. Neighbourhood outline on an interactive map: load Maps JS ONLY through \`<script src="https://maps.fndn.ai/sdk.js?callback=initMap" async defer />\` (never a Google key in the app, never \`NEXT_PUBLIC_GOOGLE_MAPS_API_KEY\`); in \`initMap\` do \`const outline = await neighborhoodBoundaryLayer(listing.location.city, listing.location.neighborhood, { siteId })\` and \`if (outline.feature) map.data.addGeoJson(outline.feature)\`; with MapLibre the vector source url is \`boundaryLayerUrl(listing.location.city)\`. Travel time (\u201Cquanto tempo at\xE9\u2026\u201D): \`const trip = await travelTimeFromListing(listing, destination, { mode: "driving", siteId })\` gives \`{ minutes, distanceKm }\` or \`null\` (hide the row). Every uncached call is a billed Google Directions request: call it on demand \u2014 a destination the visitor typed, or at most one fixed landmark per listing page \u2014 never per listing card, never inside a search loop, keep the SDK cache on (default 15 min LRU, \`cache: null\` only in tests), and do not re-run it on every render.`;
3404
3463
  }
3464
+ var MAP_CLUSTER_MEMBERS_CLICK = "`const members = map.pins.filter((pin) => cluster.pinIds.includes(pin.id))`, then `fitBounds` a LatLngBounds of their coordinates with about 64px padding, so the listings land inside the new view and split into chips.";
3465
+ var MAP_CLUSTER_SAME_POINT = "When every member has the same coordinates, or the map is already at zoom 18, do not zoom: open a small list of those listings, each with its price and a link.";
3466
+ function studioMapClusterClickInstruction(buckets) {
3467
+ if (!buckets) {
3468
+ return `Clicking a cluster opens its members: ${MAP_CLUSTER_MEMBERS_CLICK} Do not step the zoom around \`cluster.lat\`/\`cluster.lng\`: that point is approximate and the area around it can come back empty. ${MAP_CLUSTER_SAME_POINT}`;
3469
+ }
3470
+ return `Clicking a cluster depends on \`cluster.pinIds\`. A cluster with members (\`cluster.pinIds.length > 0\`) opens them: ${MAP_CLUSTER_MEMBERS_CLICK} For such a cluster do not step the zoom around \`cluster.lat\`/\`cluster.lng\`: that point is approximate and the area around it can come back empty. ${MAP_CLUSTER_SAME_POINT} A cluster with empty \`pinIds\` is a bucket and has no members to fit: on click center the map on \`cluster.lat\`/\`cluster.lng\` and zoom in two levels \u2014 the next viewport search returns finer buckets or the listings themselves.`;
3471
+ }
3405
3472
  function studioMapSearchInstruction(options = {}) {
3406
3473
  if (!mapsExportsPublished(options.pin)) return "";
3407
3474
  const pin = options.pin ?? STUDIO_SDK_CONTRACT.minNpmVersion;
3408
- const buckets = compareSemver(pin, STUDIO_SDK_CONTRACT.mapBucketsSince) >= 0 ? " When the matches do not fit on one page, the hook builds `map.clusters` from location buckets whose counts add up to `map.total`; render them as they come and never fetch or merge more pages. A cluster with empty `pinIds` is a bucket: draw it as a cluster, and on click center the map on `cluster.lat`/`cluster.lng` and zoom in two levels \u2014 the next viewport search returns finer buckets or the listings themselves." : "";
3409
- return `Map search on \`/imoveis\` (list and map of the same query). The list stays: keep \`usePublicSearch\` for the list, including its sort and pagination. The visitor switches on the same page. \`?modo=mapa\` is the map \u2014 read it on first paint. The list is the URL without \`modo\`; do not write \`modo=lista\` or \`modo=grade\`. Choosing the map sets \`modo=mapa\` and drops \`page\`. Choosing the list removes \`modo\`. On the map, hide sort and pagination. Do not add a map pager. The heading stays. Filters apply to both. Load Maps JS ONLY through \`<script src="https://maps.fndn.ai/sdk.js?callback=initMap" async defer />\` \u2014 never a Google key in the app, never \`NEXT_PUBLIC_GOOGLE_MAPS_API_KEY\`, never \`maps.googleapis.com\`, never \`@vis.gl/react-google-maps\`. From \`${STUDIO_SDK_PACKAGE}/react\` import useMapSearch; it fetches, debounces, and clusters. \`const map = useMapSearch({ siteId, baseUrl: GARAGEM_API_BASE, bounds, zoom, q, sort, location, filters, publishableKey })\` with the same q, sort, location, filters, and publishableKey as the list. Pass the map's current zoom on every zoom change, including after a cluster click. Changing zoom recomputes \`map.clusters\` and does not refetch; a bounds change refetches. Do not send filter_by, vector_query, or nl_query from the browser. Request page 1 and pageSize at most 100. Do not walk totalPages. Pins are the masked coordinates the API returned \u2014 plot them as returned, never geocode the street. Render \`map.clusters\` with \`google.maps.Marker\` (no map id needed), in two styles that never look alike. A cluster (\`count > 1\`) is a filled circle in the brand color with a white border and the white count as its label. A listing (\`count === 1\` with \`cluster.pin\`) is a white rounded-rectangle chip with a brand-color border, labelled with the short price in the brand color ("R$ 850 mil", "R$ 1,2 mi"; "Consulte" when the price is null or 0): \`icon: { path: "M-34,-12 h68 a6,6 0 0 1 6,6 v12 a6,6 0 0 1 -6,6 h-68 a6,6 0 0 1 -6,-6 v-12 a6,6 0 0 1 6,-6 z", fillColor: "#ffffff", fillOpacity: 1, strokeColor: brand, strokeWeight: 1.5, scale: 1, labelOrigin: new google.maps.Point(0, 0) }\`. Never draw a listing as a dot or a circle, and never without its price. Clicking a listing selects it and shows its card. The card content is \`toListingCardModel(map.listings.find((listing) => listing.id === pin.id))\` and shows, in order: a large cover (\`coverSrc\`, aspect 4/3, full card width), title, \`priceLabel\`, \`locationLabel\`, then the facts that are present: \`bedrooms\` quartos, \`bathrooms\` banheiros, \`parkingSpaces\` vagas, \`areaM2\` m\xB2. Title and price alone are incomplete. On a wide screen the card opens next to its pin, never at the bottom of the map, where it falls below the viewport when the page is scrolled. Use one \`google.maps.InfoWindow\` and open it on the clicked marker: \`infoWindow.open({ map: googleMap, anchor: marker })\`. Its content is a div that React fills with \`createPortal\`. The InfoWindow pans the map so the card is in view. On a narrow screen the same card sits in a bottom sheet across the map width. Dismissing it leaves the pins. While \`map.loading\` the map is \`aria-busy\` with a visible progress indicator and the previous pins stay mounted. Clicking a cluster opens its members: \`const members = map.pins.filter((pin) => cluster.pinIds.includes(pin.id))\`, then \`fitBounds\` a LatLngBounds of their coordinates with about 64px padding, so the listings land inside the new view and split into chips. Do not step the zoom around \`cluster.lat\`/\`cluster.lng\`: that point is approximate and the area around it can come back empty. When every member has the same coordinates, or the map is already at zoom 18, do not zoom: open a small list of those listings, each with its price and a link. Layout, top to bottom: query, heading, toolbar, then the view. Lista and Mapa are icon buttons with the site tooltip and \`aria-label\` \u201CLista\u201D / \u201CMapa\u201D, not icon-plus-text. On desktop the toolbar is one row: featured filters on the left, and the list/map toggle immediately beside the sort select on the right. On a narrow screen the filters stay in one horizontal scroll that does not wrap, and the toggle plus the sort sit together on the row below that scroll. That row fits the viewport and never widens the page; sort may truncate. On the map the sort is hidden, so the toggle keeps that place beside where the sort was. In map mode the map fills the remaining viewport height, with a minimum of about 240px. Keep the hook's 400ms viewport debounce. A drawn polygon is not required. Do not add a separate /mapa route, a regions page, or a map on the listing page. Do not call Street View or travel time inside the map search.${buckets}`;
3475
+ const hasBuckets = compareSemver(pin, STUDIO_SDK_CONTRACT.mapBucketsSince) >= 0;
3476
+ const buckets = hasBuckets ? " When the matches do not fit on one page, the hook builds `map.clusters` from location buckets whose counts add up to `map.total`; render them as they come and never fetch or merge more pages. Draw a bucket like any other cluster." : "";
3477
+ const clusterClick = studioMapClusterClickInstruction(hasBuckets);
3478
+ return `Map search on \`/imoveis\` (list and map of the same query). The list stays: keep \`usePublicSearch\` for the list, including its sort and pagination. The visitor switches on the same page. \`?modo=mapa\` is the map \u2014 read it on first paint. The list is the URL without \`modo\`; do not write \`modo=lista\` or \`modo=grade\`. Choosing the map sets \`modo=mapa\` and drops \`page\`. Choosing the list removes \`modo\`. On the map, hide sort and pagination. Do not add a map pager. The heading stays. Filters apply to both. Load Maps JS ONLY through \`<script src="https://maps.fndn.ai/sdk.js?callback=initMap" async defer />\` \u2014 never a Google key in the app, never \`NEXT_PUBLIC_GOOGLE_MAPS_API_KEY\`, never \`maps.googleapis.com\`, never \`@vis.gl/react-google-maps\`. From \`${STUDIO_SDK_PACKAGE}/react\` import useMapSearch; it fetches, debounces, and clusters. \`const map = useMapSearch({ siteId, baseUrl: GARAGEM_API_BASE, bounds, zoom, q, sort, location, filters, publishableKey })\` with the same q, sort, location, filters, and publishableKey as the list. Pass the map's current zoom on every zoom change, including after a cluster click. Changing zoom recomputes \`map.clusters\` and does not refetch; a bounds change refetches. Do not send filter_by, vector_query, or nl_query from the browser. Request page 1 and pageSize at most 100. Do not walk totalPages. Pins are the masked coordinates the API returned \u2014 plot them as returned, never geocode the street. Render \`map.clusters\` with \`google.maps.Marker\` (no map id needed), in two styles that never look alike. A cluster (\`count > 1\`) is a filled circle in the brand color with a white border and the white count as its label. A listing (\`count === 1\` with \`cluster.pin\`) is a white rounded-rectangle chip with a brand-color border, labelled with the short price in the brand color ("R$ 850 mil", "R$ 1,2 mi"; "Consulte" when the price is null or 0): \`icon: { path: "M-34,-12 h68 a6,6 0 0 1 6,6 v12 a6,6 0 0 1 -6,6 h-68 a6,6 0 0 1 -6,-6 v-12 a6,6 0 0 1 6,-6 z", fillColor: "#ffffff", fillOpacity: 1, strokeColor: brand, strokeWeight: 1.5, scale: 1, labelOrigin: new google.maps.Point(0, 0) }\`. Never draw a listing as a dot or a circle, and never without its price. Clicking a listing selects it and shows its card. The card content is \`toListingCardModel(map.listings.find((listing) => listing.id === pin.id))\` and shows, in order: a large cover (\`coverSrc\`, aspect 4/3, full card width), title, \`priceLabel\`, \`locationLabel\`, then the facts that are present: \`bedrooms\` quartos, \`bathrooms\` banheiros, \`parkingSpaces\` vagas, \`areaM2\` m\xB2. Title and price alone are incomplete. On a wide screen the card opens next to its pin, never at the bottom of the map, where it falls below the viewport when the page is scrolled. Use one \`google.maps.InfoWindow\` and open it on the clicked marker: \`infoWindow.open({ map: googleMap, anchor: marker })\`. Its content is a div that React fills with \`createPortal\`. The InfoWindow pans the map so the card is in view. On a narrow screen the same card sits in a bottom sheet across the map width. Dismissing it leaves the pins. While \`map.loading\` the map is \`aria-busy\` with a visible progress indicator and the previous pins stay mounted. ${clusterClick} Layout, top to bottom: query, heading, toolbar, then the view. Lista and Mapa are icon buttons with the site tooltip and \`aria-label\` \u201CLista\u201D / \u201CMapa\u201D, not icon-plus-text. On desktop the toolbar is one row: featured filters on the left, and the list/map toggle immediately beside the sort select on the right. On a narrow screen the filters stay in one horizontal scroll that does not wrap, and the toggle plus the sort sit together on the row below that scroll. That row fits the viewport and never widens the page; sort may truncate. On the map the sort is hidden, so the toggle keeps that place beside where the sort was. In map mode the map fills the remaining viewport height, with a minimum of about 240px. Keep the hook's 400ms viewport debounce. A drawn polygon is not required. Do not add a separate /mapa route, a regions page, or a map on the listing page. Do not call Street View or travel time inside the map search.${buckets}`;
3410
3479
  }
3411
3480
  function marketExportsAvailableAt(pin) {
3412
3481
  return compareSemver(pin, STUDIO_SDK_CONTRACT.marketExportsSince) >= 0;
@@ -3484,6 +3553,13 @@ function studioCodegenContractViolations(text2) {
3484
3553
  }
3485
3554
  }
3486
3555
  }
3556
+ if (!isShareLinkOnPin()) {
3557
+ for (const name of STUDIO_SDK_CONTRACT.shareExports) {
3558
+ if (mentionsExportName(text2, name) && !violations.includes(name)) {
3559
+ violations.push(name);
3560
+ }
3561
+ }
3562
+ }
3487
3563
  const pin = STUDIO_SDK_CONTRACT.minNpmVersion;
3488
3564
  if (!marketExportsAvailableAt(pin)) {
3489
3565
  for (const name of STUDIO_SDK_CONTRACT.marketExports) {
@@ -4895,6 +4971,7 @@ export {
4895
4971
  getListings,
4896
4972
  getNeighborhoodSummary,
4897
4973
  getSearchUi,
4974
+ getShareLink,
4898
4975
  getSimilarByPhoto,
4899
4976
  getSimilarListings,
4900
4977
  getSite,
@@ -4907,6 +4984,7 @@ export {
4907
4984
  isMapPolygon,
4908
4985
  isPhotoSearchOnPin,
4909
4986
  isSellerLeadOnPin,
4987
+ isShareLinkOnPin,
4910
4988
  isStudioPreviewHost,
4911
4989
  isValidEmail,
4912
4990
  isValidName,
@@ -5002,6 +5080,7 @@ export {
5002
5080
  studioSearchInstruction,
5003
5081
  studioSearchLandmarkInstruction,
5004
5082
  studioSellerLeadSdkInstruction,
5083
+ studioShareLinkInstruction,
5005
5084
  studioSiteWidthCss,
5006
5085
  submitContactLead,
5007
5086
  submitSellerLead,