@garagem-ai/site-sdk 0.4.2 → 0.4.4

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
@@ -314,6 +314,357 @@ async function getCmsEntry(options) {
314
314
  return data;
315
315
  }
316
316
 
317
+ // src/schedule.ts
318
+ var VISIT_TIME_ZONE = "America/Sao_Paulo";
319
+ var HHMM_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;
320
+ var YMD_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
321
+ var ISO_INSTANT_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
322
+ var WEEKDAY_SHORT = {
323
+ Sun: 0,
324
+ Mon: 1,
325
+ Tue: 2,
326
+ Wed: 3,
327
+ Thu: 4,
328
+ Fri: 5,
329
+ Sat: 6
330
+ };
331
+ function pad2(value) {
332
+ return String(value).padStart(2, "0");
333
+ }
334
+ function parseHHmm(value) {
335
+ const match = HHMM_RE.exec(value);
336
+ if (!match) return null;
337
+ return { hour: Number(match[1]), minute: Number(match[2]) };
338
+ }
339
+ function minutesOfDay(hhmm) {
340
+ const parsed = parseHHmm(hhmm);
341
+ if (!parsed) return null;
342
+ return parsed.hour * 60 + parsed.minute;
343
+ }
344
+ function expandVisitTimeSlots(hours) {
345
+ const start = minutesOfDay(hours.start);
346
+ const end = minutesOfDay(hours.end);
347
+ if (start == null || end == null || start > end) return [];
348
+ const slots = [];
349
+ for (let minutes = start; minutes <= end; minutes += 60) {
350
+ const hour = Math.floor(minutes / 60);
351
+ const minute = minutes % 60;
352
+ slots.push(`${pad2(hour)}:${pad2(minute)}`);
353
+ }
354
+ return slots;
355
+ }
356
+ function unionSorted(left, right) {
357
+ return Array.from(/* @__PURE__ */ new Set([...left, ...right])).sort();
358
+ }
359
+ function expandVisitSchedule(config) {
360
+ const weekendHours = config.weekend ?? (config.saturday || config.sunday ? config.weekday : null);
361
+ const weekdayTimeSlots = expandVisitTimeSlots(config.weekday);
362
+ const weekendTimeSlots = weekendHours ? expandVisitTimeSlots(weekendHours) : [];
363
+ const disabledDays = [];
364
+ if (!config.sunday) disabledDays.push(0);
365
+ if (!config.saturday) disabledDays.push(6);
366
+ return {
367
+ ...config,
368
+ weekend: weekendHours,
369
+ disabledDays,
370
+ weekdayTimeSlots,
371
+ weekendTimeSlots,
372
+ timeSlots: unionSorted(weekdayTimeSlots, weekendTimeSlots)
373
+ };
374
+ }
375
+ var STUDIO_DEFAULT_VISIT_SCHEDULE = expandVisitSchedule(
376
+ {
377
+ timeZone: VISIT_TIME_ZONE,
378
+ saturday: false,
379
+ sunday: false,
380
+ weekday: { start: "06:00", end: "22:00" },
381
+ weekend: null,
382
+ minHoursAhead: 2
383
+ }
384
+ );
385
+ function zonedParts(date, timeZone) {
386
+ const parts = new Intl.DateTimeFormat("en-US", {
387
+ timeZone,
388
+ weekday: "short",
389
+ year: "numeric",
390
+ month: "2-digit",
391
+ day: "2-digit",
392
+ hour: "2-digit",
393
+ minute: "2-digit",
394
+ hourCycle: "h23"
395
+ }).formatToParts(date);
396
+ const get = (type) => parts.find((part) => part.type === type)?.value ?? "";
397
+ const weekday = WEEKDAY_SHORT[get("weekday")] ?? 0;
398
+ return {
399
+ year: Number(get("year")),
400
+ month: Number(get("month")),
401
+ day: Number(get("day")),
402
+ hour: Number(get("hour")),
403
+ minute: Number(get("minute")),
404
+ weekday
405
+ };
406
+ }
407
+ function calendarYmd(date, timeZone) {
408
+ const parts = zonedParts(date, timeZone);
409
+ return `${parts.year}-${pad2(parts.month)}-${pad2(parts.day)}`;
410
+ }
411
+ function parseYmd(value) {
412
+ const match = YMD_RE.exec(value);
413
+ if (!match) return null;
414
+ const year = Number(match[1]);
415
+ const month = Number(match[2]);
416
+ const day = Number(match[3]);
417
+ const utc = new Date(Date.UTC(year, month - 1, day));
418
+ if (utc.getUTCFullYear() !== year || utc.getUTCMonth() !== month - 1 || utc.getUTCDate() !== day) {
419
+ return null;
420
+ }
421
+ return { year, month, day };
422
+ }
423
+ function normalizeVisitDate(date, timeZone = VISIT_TIME_ZONE) {
424
+ if (typeof date === "string") {
425
+ if (parseYmd(date)) return date;
426
+ if (!ISO_INSTANT_RE.test(date)) return null;
427
+ const instant = new Date(date);
428
+ return Number.isFinite(instant.getTime()) ? calendarYmd(instant, timeZone) : null;
429
+ }
430
+ if (date instanceof Date && Number.isFinite(date.getTime())) {
431
+ return calendarYmd(date, timeZone);
432
+ }
433
+ return null;
434
+ }
435
+ function weekdayOfYmd(ymd, timeZone) {
436
+ const parsed = parseYmd(ymd);
437
+ if (!parsed) return null;
438
+ const utcNoonish = new Date(
439
+ Date.UTC(parsed.year, parsed.month - 1, parsed.day, 15, 0, 0)
440
+ );
441
+ return zonedParts(utcNoonish, timeZone).weekday;
442
+ }
443
+ function slotsForDate(schedule, date, now = /* @__PURE__ */ new Date()) {
444
+ const timeZone = schedule.timeZone;
445
+ const ymd = normalizeVisitDate(date, timeZone);
446
+ if (!ymd) return [];
447
+ const weekday = weekdayOfYmd(ymd, timeZone);
448
+ if (weekday == null) return [];
449
+ if (weekday === 0 && !schedule.sunday) return [];
450
+ if (weekday === 6 && !schedule.saturday) return [];
451
+ const base = weekday === 0 || weekday === 6 ? schedule.weekendTimeSlots : schedule.weekdayTimeSlots;
452
+ const today = calendarYmd(now, timeZone);
453
+ if (ymd < today) return [];
454
+ if (ymd !== today) return [...base];
455
+ const nowParts = zonedParts(now, timeZone);
456
+ const cutoff = nowParts.hour * 60 + nowParts.minute + schedule.minHoursAhead * 60;
457
+ return base.filter((slot) => {
458
+ const minutes = minutesOfDay(slot);
459
+ return minutes != null && minutes >= cutoff;
460
+ });
461
+ }
462
+ function isVisitSlotAllowed(schedule, visitDate, visitTime, now = /* @__PURE__ */ new Date()) {
463
+ return slotsForDate(schedule, visitDate, now).includes(visitTime);
464
+ }
465
+
466
+ // src/leads.ts
467
+ var LeadSubmitError = class extends Error {
468
+ code;
469
+ status;
470
+ retryAfterSeconds;
471
+ constructor(message, info) {
472
+ super(message);
473
+ this.name = "LeadSubmitError";
474
+ this.code = info.code;
475
+ if (info.status != null) this.status = info.status;
476
+ if (info.retryAfterSeconds != null) {
477
+ this.retryAfterSeconds = info.retryAfterSeconds;
478
+ }
479
+ }
480
+ };
481
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
482
+ var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
483
+ var MESSAGE_MAX = 2e3;
484
+ var CONTACT_FIELDS = [
485
+ { id: "name", required: true },
486
+ { id: "email", required: false },
487
+ { id: "phone", required: false },
488
+ { id: "message", required: false }
489
+ ];
490
+ function studioDefaultLeadUi() {
491
+ return {
492
+ defaultVariant: "visit",
493
+ timeZone: "America/Sao_Paulo",
494
+ variants: {
495
+ visit: {
496
+ ctaLabel: "Agendar visita",
497
+ requireDateTime: true,
498
+ schedule: STUDIO_DEFAULT_VISIT_SCHEDULE,
499
+ fields: CONTACT_FIELDS
500
+ },
501
+ contact: {
502
+ ctaLabel: "Fale conosco",
503
+ requireDateTime: false,
504
+ whatsappPhone: null,
505
+ fields: CONTACT_FIELDS
506
+ }
507
+ }
508
+ };
509
+ }
510
+ async function getLeadUi(options) {
511
+ const siteId = await coerceSiteId(options.siteId);
512
+ const url = `${normalizeBaseUrl(options.baseUrl)}/api/sites/${encodeURIComponent(siteId)}/leads/ui`;
513
+ return callJson(
514
+ url,
515
+ {
516
+ method: "GET",
517
+ headers: { Accept: "application/json" },
518
+ next: options.next
519
+ },
520
+ options.fetch ?? fetch
521
+ );
522
+ }
523
+ function assertListingId(listingId) {
524
+ if (!UUID_RE.test(listingId.trim())) {
525
+ throw new LeadSubmitError(
526
+ "Garagem SDK: listingId must be the listing UUID, not a path or code.",
527
+ { code: "invalid_listing_id" }
528
+ );
529
+ }
530
+ }
531
+ function normalizeContact(input) {
532
+ const name = input.name.trim();
533
+ if (name.length < 2 || name.length > 200) {
534
+ throw new LeadSubmitError("Garagem SDK: name is required.", {
535
+ code: "invalid_contact"
536
+ });
537
+ }
538
+ const email = input.email?.trim() || void 0;
539
+ const phone = input.phone?.trim() || void 0;
540
+ if (!email && !phone) {
541
+ throw new LeadSubmitError("Garagem SDK: email and/or phone is required.", {
542
+ code: "invalid_contact"
543
+ });
544
+ }
545
+ if (email && !EMAIL_RE.test(email)) {
546
+ throw new LeadSubmitError("Garagem SDK: email is invalid.", {
547
+ code: "invalid_contact"
548
+ });
549
+ }
550
+ if (phone && (phone.length < 5 || phone.length > 40)) {
551
+ throw new LeadSubmitError("Garagem SDK: phone is invalid.", {
552
+ code: "invalid_contact"
553
+ });
554
+ }
555
+ const message = input.message?.trim() || void 0;
556
+ if (message && message.length > MESSAGE_MAX) {
557
+ throw new LeadSubmitError("Garagem SDK: message is too long.", {
558
+ code: "invalid_contact"
559
+ });
560
+ }
561
+ return {
562
+ name,
563
+ ...email ? { email } : {},
564
+ ...phone ? { phone } : {},
565
+ ...message ? { message } : {}
566
+ };
567
+ }
568
+ async function postSiteLead(input) {
569
+ const siteId = await coerceSiteId(input.siteId);
570
+ const base = normalizeBaseUrl(input.baseUrl);
571
+ const url = `${base}/api/webhooks/sites/${encodeURIComponent(siteId)}/leads`;
572
+ const f = input.fetch ?? fetch;
573
+ let response;
574
+ try {
575
+ response = await f(url, {
576
+ method: "POST",
577
+ headers: {
578
+ Accept: "application/json",
579
+ "Content-Type": "application/json"
580
+ },
581
+ body: JSON.stringify(input.body)
582
+ });
583
+ } catch (error) {
584
+ throw new LeadSubmitError(
585
+ error instanceof Error ? error.message : "Garagem SDK: network error.",
586
+ { code: "network" }
587
+ );
588
+ }
589
+ if (response.status === 202) {
590
+ const data = await response.json().catch(() => ({}));
591
+ const id = typeof data.id === "string" && data.id ? data.id : "";
592
+ return { ok: true, status: 202, id };
593
+ }
594
+ const retryAfter = Number(response.headers.get("Retry-After") ?? "");
595
+ if (response.status === 429) {
596
+ throw new LeadSubmitError("Garagem SDK: too many lead submissions.", {
597
+ code: "rate_limited",
598
+ status: 429,
599
+ retryAfterSeconds: Number.isFinite(retryAfter) ? retryAfter : void 0
600
+ });
601
+ }
602
+ if (response.status === 404) {
603
+ throw new LeadSubmitError("Garagem SDK: listing or site not found.", {
604
+ code: "not_found",
605
+ status: 404
606
+ });
607
+ }
608
+ throw new LeadSubmitError(
609
+ `Garagem SDK: lead submit failed (${response.status}).`,
610
+ { code: "http", status: response.status }
611
+ );
612
+ }
613
+ function leadPostContext(input) {
614
+ assertListingId(input.listingId);
615
+ return {
616
+ listingId: input.listingId.trim(),
617
+ contact: normalizeContact(input),
618
+ extras: {
619
+ ...input.visitorId ? { visitorId: input.visitorId } : {},
620
+ ...input.brokerRef ? { brokerRef: input.brokerRef } : {},
621
+ ...input.referrer ? { referrer: input.referrer } : {}
622
+ }
623
+ };
624
+ }
625
+ async function submitVisitLead(input) {
626
+ const prepared = leadPostContext(input);
627
+ const schedule = input.schedule ?? STUDIO_DEFAULT_VISIT_SCHEDULE;
628
+ const visitDate = normalizeVisitDate(input.visitDate, schedule.timeZone);
629
+ if (!visitDate || !isVisitSlotAllowed(schedule, visitDate, input.visitTime)) {
630
+ throw new LeadSubmitError(
631
+ "Garagem SDK: visitDate/visitTime is outside the published schedule.",
632
+ { code: "invalid_slot" }
633
+ );
634
+ }
635
+ return postSiteLead({
636
+ siteId: input.siteId,
637
+ baseUrl: input.baseUrl,
638
+ fetch: input.fetch,
639
+ body: {
640
+ source: "site-sdk",
641
+ leadType: "visit",
642
+ ...prepared.contact,
643
+ propertyId: prepared.listingId,
644
+ listingId: prepared.listingId,
645
+ visitDate,
646
+ visitTime: input.visitTime,
647
+ ...prepared.extras
648
+ }
649
+ });
650
+ }
651
+ async function submitContactLead(input) {
652
+ const prepared = leadPostContext(input);
653
+ return postSiteLead({
654
+ siteId: input.siteId,
655
+ baseUrl: input.baseUrl,
656
+ fetch: input.fetch,
657
+ body: {
658
+ source: "site-sdk",
659
+ leadType: "contact",
660
+ ...prepared.contact,
661
+ propertyId: prepared.listingId,
662
+ listingId: prepared.listingId,
663
+ ...prepared.extras
664
+ }
665
+ });
666
+ }
667
+
317
668
  // src/presentation.ts
318
669
  var SEARCH_CSS_VARS = {
319
670
  cardRadius: "--garagem-listing-card-radius",
@@ -1206,10 +1557,10 @@ var STUDIO_SDK_CONTRACT = {
1206
1557
  /**
1207
1558
  * Exact pin for generated Studio sites. Must be ≥ `selfInjectSince` so
1208
1559
  * prompts that skip the layout chrome tag match the tarball v0 installs.
1209
- * This PR’s changeset publishes that tarball as 0.4.2 — do not generate
1560
+ * This PR’s changeset publishes that tarball as 0.4.3 — do not generate
1210
1561
  * against this floor until Version Packages is on npm.
1211
1562
  */
1212
- minNpmVersion: "0.4.2",
1563
+ minNpmVersion: "0.4.3",
1213
1564
  /** First release where ListingCard and ResultsSkeleton inject the sheet. */
1214
1565
  selfInjectSince: "0.4.2",
1215
1566
  chromeStrategy: "self-inject",
@@ -1230,9 +1581,24 @@ var STUDIO_SDK_CONTRACT = {
1230
1581
  SearchPageFallback: "0.4.1",
1231
1582
  SearchChromeStyles: "0.4.1"
1232
1583
  },
1233
- forbiddenImports: ["@garagem-ai/site-sdk/react/search.css"]
1584
+ forbiddenImports: ["@garagem-ai/site-sdk/react/search.css"],
1585
+ leadStrategy: "visit-default",
1586
+ leadExports: [
1587
+ "getLeadUi",
1588
+ "submitVisitLead",
1589
+ "submitContactLead",
1590
+ "slotsForDate",
1591
+ "expandVisitSchedule",
1592
+ "expandVisitTimeSlots",
1593
+ "isVisitSlotAllowed",
1594
+ "STUDIO_DEFAULT_VISIT_SCHEDULE"
1595
+ ]
1234
1596
  };
1235
1597
  var REACT_SDK_NAMED_IMPORT_RE = /(?:^|[\n;])\s*import\s+(?!type\b)(?:type\s+)?\{([^}]+)\}\s+from\s+['"]@garagem-ai\/site-sdk\/react['"]/g;
1598
+ var SHOWCASE_LEADS_POST_URL_RE = /\/api\/sites\/[^\s"']*\/leads(?!\/ui)/;
1599
+ function hasShowcaseLeadsPostUrl(text) {
1600
+ return SHOWCASE_LEADS_POST_URL_RE.test(text);
1601
+ }
1236
1602
  function coerceNpmVersion(raw) {
1237
1603
  if (typeof raw !== "string") return null;
1238
1604
  const match = raw.trim().match(/(\d+)\.(\d+)\.(\d+)/);
@@ -1287,6 +1653,10 @@ function studioSdkPinInstruction() {
1287
1653
  const names = STUDIO_SDK_CONTRACT.reactExports.join(", ");
1288
1654
  return `In \`package.json\` set \`"@garagem-ai/site-sdk": "${version}"\` (exact). Import only these \`${STUDIO_SDK_PACKAGE}/react\` names: ${names}.`;
1289
1655
  }
1656
+ function studioLeadInstruction() {
1657
+ const names = STUDIO_SDK_CONTRACT.leadExports.join(", ");
1658
+ return `Listing-detail visit/contact leads: import ${names} from \`${STUDIO_SDK_PACKAGE}\` (the main package, not \`/react\`). Call \`submitVisitLead\` / \`submitContactLead\` \u2014 never concatenate a leads webhook URL and never POST the Showcase demo leads route.`;
1659
+ }
1290
1660
  function studioChromeInstruction() {
1291
1661
  const injectors = compareSemver(
1292
1662
  STUDIO_SDK_CONTRACT.minNpmVersion,
@@ -1306,6 +1676,12 @@ function studioCodegenContractViolations(text) {
1306
1676
  violations.push(name);
1307
1677
  }
1308
1678
  }
1679
+ if (hasShowcaseLeadsPostUrl(text)) {
1680
+ violations.push("showcase-leads-url");
1681
+ }
1682
+ if (/\btype\s*=\s*["']date["']/.test(text)) {
1683
+ violations.push("native-date-input");
1684
+ }
1309
1685
  return violations;
1310
1686
  }
1311
1687
 
@@ -1437,18 +1813,45 @@ function createGaragemClient(options = {}) {
1437
1813
  const merged = mergeNext(next);
1438
1814
  if (merged !== void 0) opts.next = merged;
1439
1815
  return getCmsEntry(opts);
1816
+ },
1817
+ async getLeadUi({ siteId, next } = {}) {
1818
+ const opts = withDefaults({
1819
+ siteId: resolveSiteId(siteId)
1820
+ });
1821
+ const merged = mergeNext(next);
1822
+ if (merged !== void 0) opts.next = merged;
1823
+ return getLeadUi(opts);
1824
+ },
1825
+ async submitVisitLead(args) {
1826
+ return submitVisitLead(
1827
+ withDefaults({
1828
+ ...args,
1829
+ siteId: resolveSiteId(args.siteId)
1830
+ })
1831
+ );
1832
+ },
1833
+ async submitContactLead(args) {
1834
+ return submitContactLead(
1835
+ withDefaults({
1836
+ ...args,
1837
+ siteId: resolveSiteId(args.siteId)
1838
+ })
1839
+ );
1440
1840
  }
1441
1841
  };
1442
1842
  }
1443
1843
  export {
1444
1844
  FORBIDDEN_SEARCH_QUERY_KEYS,
1445
1845
  GaragemSdkError,
1846
+ LeadSubmitError,
1446
1847
  SEARCH_CSS_RECIPE,
1447
1848
  SEARCH_CSS_VARS,
1448
1849
  SEARCH_SORT_RELEVANCE,
1850
+ STUDIO_DEFAULT_VISIT_SCHEDULE,
1449
1851
  STUDIO_SDK_CONTRACT,
1450
1852
  STUDIO_SDK_PACKAGE,
1451
1853
  TOOLBAR_PRIMARY_FILTER_IDS,
1854
+ VISIT_TIME_ZONE,
1452
1855
  applyPathFilter,
1453
1856
  buildQueryListingsParams,
1454
1857
  canonicalizeSearchHref,
@@ -1461,6 +1864,8 @@ export {
1461
1864
  countOptionLabel,
1462
1865
  createGaragemClient,
1463
1866
  displayPathLocation,
1867
+ expandVisitSchedule,
1868
+ expandVisitTimeSlots,
1464
1869
  formatAreaM2,
1465
1870
  formatGroupedInteger,
1466
1871
  formatListingPrice,
@@ -1468,21 +1873,25 @@ export {
1468
1873
  getCmsCollections,
1469
1874
  getCmsEntries,
1470
1875
  getCmsEntry,
1876
+ getLeadUi,
1471
1877
  getListing,
1472
1878
  getListings,
1473
1879
  getSearchUi,
1474
1880
  getSimilarListings,
1475
1881
  getSite,
1882
+ hasShowcaseLeadsPostUrl,
1476
1883
  hrefForAppliedChange,
1477
1884
  hrefForPathFilters,
1478
1885
  hrefWithExplicitPage,
1479
1886
  isListingDetailPath,
1480
1887
  isStudioPreviewHost,
1888
+ isVisitSlotAllowed,
1481
1889
  listingBusinessLabel,
1482
1890
  listingLocationLabel,
1483
1891
  listingLookupKey,
1484
1892
  listingPublicPath,
1485
1893
  mergeAppliedSearchQueryIntoSearch2 as mergeAppliedSearchQueryIntoSearch,
1894
+ normalizeVisitDate,
1486
1895
  paginationPages,
1487
1896
  parseAppliedSearchQuery2 as parseAppliedSearchQuery,
1488
1897
  parseGroupedInteger,
@@ -1502,9 +1911,14 @@ export {
1502
1911
  searchResultsHeading,
1503
1912
  searchSortOptions,
1504
1913
  serializeAppliedSearchQuery2 as serializeAppliedSearchQuery,
1914
+ slotsForDate,
1505
1915
  studioChromeInstruction,
1506
1916
  studioCodegenContractViolations,
1917
+ studioDefaultLeadUi,
1918
+ studioLeadInstruction,
1507
1919
  studioSdkPinInstruction,
1920
+ submitContactLead,
1921
+ submitVisitLead,
1508
1922
  toListingCardModel,
1509
1923
  toolbarFilterIds,
1510
1924
  unavailableReactImports,