@tribe-nest/forge 3.2.0 → 3.9.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.
Files changed (56) hide show
  1. package/package.json +1 -1
  2. package/src/data/queries/_tests/eventWaitlist.spec.ts +122 -0
  3. package/src/data/queries/_tests/passTransfers.spec.ts +89 -0
  4. package/src/data/queries/_tests/walletPass.spec.ts +159 -0
  5. package/src/data/queries/useCheckouts.ts +84 -1
  6. package/src/data/queries/useCoachingAvailability.ts +18 -3
  7. package/src/data/queries/useCourses.ts +42 -1
  8. package/src/data/queries/useEventWaitlist.ts +429 -0
  9. package/src/data/queries/useEvents.ts +15 -1
  10. package/src/data/queries/useMyBookings.ts +211 -0
  11. package/src/data/queries/useMyTickets.ts +154 -0
  12. package/src/data/queries/usePassTransfers.ts +318 -0
  13. package/src/data/queries/usePaymentFlow.ts +12 -0
  14. package/src/data/queries/useWalletPass.ts +236 -0
  15. package/src/data/queries/useWebsite.ts +6 -0
  16. package/src/index.ts +14 -0
  17. package/src/server/_tests/siteBootstrap.spec.ts +131 -0
  18. package/src/server/index.ts +122 -6
  19. package/src/types/diagnostics.ts +49 -0
  20. package/src/types/models.ts +66 -0
  21. package/src/ui/headless/calendar/useAddToCalendar.ts +194 -0
  22. package/src/ui/headless/checkout/_tests/bundleCoupon.spec.ts +169 -0
  23. package/src/ui/headless/checkout/bundleCoupon.ts +96 -0
  24. package/src/ui/headless/checkout/useCheckout.ts +156 -8
  25. package/src/ui/headless/coaching/useCoachingBooking.ts +53 -3
  26. package/src/ui/headless/coupon/_tests/couponFailureMessage.spec.ts +84 -0
  27. package/src/ui/headless/coupon/useCouponField.ts +164 -0
  28. package/src/ui/headless/course/useCourseCheckout.ts +113 -18
  29. package/src/ui/headless/event/useEventCheckout.ts +53 -2
  30. package/src/ui/headless/index.ts +15 -0
  31. package/src/ui/index.ts +26 -0
  32. package/src/ui/shell/PoweredBy.tsx +62 -0
  33. package/src/ui/shell/PreviewDiagnostics.tsx +80 -0
  34. package/src/ui/shell/TribeNestApp.tsx +39 -1
  35. package/src/ui/shell/diagnosticsGating.spec.ts +102 -0
  36. package/src/ui/shell/diagnosticsGating.ts +90 -0
  37. package/src/ui/shell/shellGating.spec.ts +60 -1
  38. package/src/ui/shell/shellGating.ts +47 -0
  39. package/src/ui/styled/AccountDashboard.tsx +598 -1
  40. package/src/ui/styled/AddToCalendar.tsx +104 -0
  41. package/src/ui/styled/Checkout.tsx +45 -14
  42. package/src/ui/styled/CoachingBooking.tsx +28 -8
  43. package/src/ui/styled/CoachingConfirmation.tsx +12 -0
  44. package/src/ui/styled/CourseCheckout.tsx +49 -18
  45. package/src/ui/styled/DiscountCode.tsx +206 -0
  46. package/src/ui/styled/EventConfirmation.tsx +68 -22
  47. package/src/ui/styled/EventDetail.tsx +24 -5
  48. package/src/ui/styled/EventTickets.tsx +49 -5
  49. package/src/ui/styled/EventWaitlist.tsx +448 -0
  50. package/src/ui/styled/TicketTransfer.tsx +393 -0
  51. package/src/ui/styled/WalletPassButtons.tsx +208 -0
  52. package/src/ui/styled/_tests/DiscountCode.spec.tsx +272 -0
  53. package/src/ui/styled/_tests/EventConfirmation.spec.tsx +154 -0
  54. package/src/ui/styled/_tests/WalletPassButtons.spec.tsx +223 -0
  55. package/src/utils/_tests/ticketOrderOutcome.spec.ts +126 -0
  56. package/src/utils/ticketOrderOutcome.ts +125 -0
@@ -1,7 +1,8 @@
1
- import { useState } from "react";
1
+ import { useCallback, useRef, useState } from "react";
2
2
  import { usePublicAuth } from "../../../contexts/PublicAuthContext";
3
- import { useGetCourse, useCreateCourseBooking } from "../../../data/queries/useCourses";
3
+ import { useGetCourse, useCreateCourseBooking, useUpdateCourseBooking } from "../../../data/queries/useCourses";
4
4
  import { usePaymentFlow } from "../../../data/queries/usePaymentFlow";
5
+ import { useCouponField, type CouponQuoteFn } from "../coupon/useCouponField";
5
6
  import { readAttributionRef } from "../../../utils/attribution";
6
7
  import { readLanding } from "../../../utils/landing";
7
8
 
@@ -21,8 +22,15 @@ const errMessage = (e: unknown) =>
21
22
 
22
23
  /**
23
24
  * Headless course purchase: buyer details → payment. Composes `useGetCourse`,
24
- * `useCreateCourseBooking`, `usePaymentFlow`. Free courses skip payment and
25
- * redirect to the finalise page. Finalize via `useCourseBookingFinalize`.
25
+ * `useCreateCourseBooking`, `useUpdateCourseBooking`, `usePaymentFlow`. Free
26
+ * courses skip payment and redirect to the finalise page. Finalize via
27
+ * `useCourseBookingFinalize`.
28
+ *
29
+ * `POST /public/courses/:id/bookings` takes NO coupon code — the course pillar
30
+ * accepts one only on `booking/update`, which exists to be called repeatedly and
31
+ * re-derives the gross price from the course each time. So a booking is created
32
+ * as soon as the buyer applies a code, and reused from then on. A buyer who
33
+ * never touches the discount field takes exactly the path this hook always took.
26
34
  */
27
35
  export function useCourseCheckout(slug?: string, opts: UseCourseCheckoutOptions = {}) {
28
36
  const { user } = usePublicAuth();
@@ -30,6 +38,7 @@ export function useCourseCheckout(slug?: string, opts: UseCourseCheckoutOptions
30
38
  const { data: course, isLoading } = useGetCourse(slug);
31
39
  const courseId = course?.id;
32
40
  const createBooking = useCreateCourseBooking(courseId);
41
+ const updateBooking = useUpdateCourseBooking(courseId);
33
42
  const flow = usePaymentFlow({ path: `/public/courses/${courseId}/start-payment`, autoStart: false });
34
43
 
35
44
  const [step, setStep] = useState<CourseCheckoutStep>("details");
@@ -39,10 +48,58 @@ export function useCourseCheckout(slug?: string, opts: UseCourseCheckoutOptions
39
48
  const [questionnaire, setQuestionnaire] = useState<unknown>(undefined);
40
49
  const [returnUrl, setReturnUrl] = useState("");
41
50
  const [error, setError] = useState<string | null>(null);
51
+ /** The booking created for quoting, reused so a code never mints a second one. */
52
+ const bookingIdRef = useRef<string | null>(null);
42
53
 
43
54
  const finalisePath =
44
55
  opts.finalisePath ?? ((s, bookingId) => `/i/courses/${s}/finalise?bookingId=${bookingId}`);
45
56
 
57
+ const requireBuyerDetails = () => {
58
+ if (!firstName.trim() || !lastName.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
59
+ throw new Error("Enter your name and a valid email before applying a code.");
60
+ }
61
+ };
62
+
63
+ /** Create the booking once; every later call reuses it. */
64
+ const ensureBooking = async (): Promise<string> => {
65
+ if (bookingIdRef.current) return bookingIdRef.current;
66
+ const created = await createBooking.mutateAsync({
67
+ email,
68
+ firstName,
69
+ lastName,
70
+ questionnaire,
71
+ attributionRefId: readAttributionRef() ?? undefined,
72
+ ...(readLanding() ?? {}),
73
+ });
74
+ bookingIdRef.current = created.bookingId;
75
+ return created.bookingId;
76
+ };
77
+
78
+ /**
79
+ * `confirmIfFree` is false here on purpose: quoting a code must never be able
80
+ * to complete an enrollment. Only "Continue" confirms.
81
+ */
82
+ const quoteCoupon: CouponQuoteFn = useCallback(
83
+ async (code) => {
84
+ if (!courseId) throw new Error("This course is not available.");
85
+ requireBuyerDetails();
86
+ const bookingId = await ensureBooking();
87
+ return updateBooking.mutateAsync({
88
+ bookingId,
89
+ email,
90
+ firstName,
91
+ lastName,
92
+ confirmIfFree: false,
93
+ questionnaire,
94
+ couponCode: code ?? undefined,
95
+ });
96
+ },
97
+ // `createBooking`/`updateBooking` are stable react-query mutation objects.
98
+ // eslint-disable-next-line react-hooks/exhaustive-deps
99
+ [courseId, firstName, lastName, email, questionnaire],
100
+ );
101
+ const coupon = useCouponField(quoteCoupon);
102
+
46
103
  const continueToPayment = async () => {
47
104
  setError(null);
48
105
  if (!slug || !courseId) return;
@@ -51,27 +108,56 @@ export function useCourseCheckout(slug?: string, opts: UseCourseCheckoutOptions
51
108
  return;
52
109
  }
53
110
  try {
54
- const data = await createBooking.mutateAsync({
55
- email,
56
- firstName,
57
- lastName,
58
- questionnaire,
59
- attributionRefId: readAttributionRef() ?? undefined,
60
- ...(readLanding() ?? {}),
61
- });
111
+ // A discount can only be recorded through `booking/update`, so any buyer
112
+ // who touched the code field settles through that endpoint. Everyone else
113
+ // keeps the original create-only path, unchanged.
114
+ const usesCoupon = !!coupon.submittedCode || !!bookingIdRef.current;
115
+ let bookingId: string;
116
+ let isFree: boolean;
117
+
118
+ if (usesCoupon) {
119
+ bookingId = await ensureBooking();
120
+ const updated = await updateBooking.mutateAsync({
121
+ bookingId,
122
+ email,
123
+ firstName,
124
+ lastName,
125
+ confirmIfFree: true,
126
+ questionnaire,
127
+ couponCode: coupon.submittedCode,
128
+ });
129
+ coupon.record(updated);
130
+ isFree = updated.isConfirmed;
131
+ } else {
132
+ const data = await createBooking.mutateAsync({
133
+ email,
134
+ firstName,
135
+ lastName,
136
+ questionnaire,
137
+ attributionRefId: readAttributionRef() ?? undefined,
138
+ ...(readLanding() ?? {}),
139
+ });
140
+ bookingIdRef.current = data.bookingId;
141
+ bookingId = data.bookingId;
142
+ isFree = !!data.isFree;
143
+ }
144
+
62
145
  const origin = typeof window !== "undefined" ? window.location.origin : "";
63
- const ru = `${origin}${finalisePath(slug, data.bookingId)}`;
146
+ const ru = `${origin}${finalisePath(slug, bookingId)}`;
64
147
  setReturnUrl(ru);
65
- if (data.isFree) {
66
- if (opts.onComplete) opts.onComplete({ slug, bookingId: data.bookingId });
148
+ if (isFree) {
149
+ if (opts.onComplete) opts.onComplete({ slug, bookingId });
67
150
  else if (typeof window !== "undefined") window.location.href = ru;
68
151
  return;
69
152
  }
70
- const result = await flow.start({ bookingId: data.bookingId, returnUrl: ru });
153
+ const result = await flow.start({ bookingId, returnUrl: ru });
71
154
  if (result.provider && result.provider !== "stripe") return;
72
155
  setStep("payment");
73
156
  } catch (e) {
74
- setError(errMessage(e));
157
+ // With a code entered, the API's rejection reason belongs at the field the
158
+ // buyer used, not in the generic error slot.
159
+ if (coupon.submittedCode) coupon.fail(e);
160
+ else setError(errMessage(e));
75
161
  }
76
162
  };
77
163
 
@@ -90,10 +176,19 @@ export function useCourseCheckout(slug?: string, opts: UseCourseCheckoutOptions
90
176
  setQuestionnaire,
91
177
  continueToPayment,
92
178
  clientSecret: flow.clientSecret,
179
+ // The booking quote WINS over start-payment: every `continueToPayment`
180
+ // re-quotes before starting the payment, and applying or removing a code
181
+ // re-quotes again — so the quote is never staler, and preferring the
182
+ // payment result would leave a removed discount on screen.
183
+ totalAmount: coupon.quote?.totalAmount ?? flow.result?.totalAmount ?? (course ? Number(course.price) : undefined),
184
+ /** GROSS course price, before any discount. */
185
+ subTotal: coupon.quote?.subTotal ?? (course ? Number(course.price) : undefined),
186
+ /** Discount code state + the server's quote. See `useCouponField`. */
187
+ coupon,
93
188
  /** Authoritative sales-tax quote from start-payment (display only). */
94
189
  taxQuote: flow.result?.taxQuote ?? null,
95
190
  returnUrl,
96
- isProcessing: createBooking.isPending || flow.isStarting,
191
+ isProcessing: createBooking.isPending || updateBooking.isPending || flow.isStarting,
97
192
  error,
98
193
  };
99
194
  }
@@ -3,6 +3,7 @@ import { usePublicAuth } from "../../../contexts/PublicAuthContext";
3
3
  import { useCart } from "../../../contexts/CartContext";
4
4
  import { useEvent, useCreateEventOrder } from "../../../data/queries/useEvents";
5
5
  import { usePaymentFlow } from "../../../data/queries/usePaymentFlow";
6
+ import { useCouponField } from "../coupon/useCouponField";
6
7
  import { readAttributionRef } from "../../../utils/attribution";
7
8
  import { readLanding } from "../../../utils/landing";
8
9
 
@@ -47,6 +48,19 @@ export function useEventCheckout(slug?: string, opts: UseEventCheckoutOptions =
47
48
  const [returnUrl, setReturnUrl] = useState("");
48
49
  const [error, setError] = useState<string | null>(null);
49
50
 
51
+ /**
52
+ * Discount code — STAGED, not quoted.
53
+ *
54
+ * Tickets have no apply-coupon endpoint and no quote endpoint: `POST
55
+ * /public/events/:id/orders` is what redeems a code, and it creates the order
56
+ * row. Pricing a code by calling it would leave a real abandoned order (and a
57
+ * released inventory hold) behind every keystroke, so no quote function is
58
+ * passed here. The code rides along on `continueToPayment`, and the order
59
+ * response — which carries `subTotal`, `discountAmount` and every applied
60
+ * coupon — is recorded as the quote.
61
+ */
62
+ const coupon = useCouponField();
63
+
50
64
  const totalAmount = useMemo(() => {
51
65
  if (!event) return 0;
52
66
  return event.tickets.reduce((sum, t) => sum + t.price * (selectedTickets[t.id] ?? 0), 0);
@@ -124,9 +138,19 @@ export function useEventCheckout(slug?: string, opts: UseEventCheckoutOptions =
124
138
  firstName,
125
139
  lastName,
126
140
  questionnaire,
141
+ couponCode: coupon.submittedCode,
127
142
  attributionRefId: readAttributionRef() ?? undefined,
128
143
  ...(readLanding() ?? {}),
129
144
  });
145
+ // What the server actually charged and why — including any AUTOMATIC
146
+ // discount the buyer never asked for, which nothing else would reveal.
147
+ coupon.record({
148
+ subTotal: data.subTotal ?? data.totalAmount ?? totalAmount,
149
+ totalAmount: data.totalAmount ?? totalAmount,
150
+ discountAmount: data.discountAmount ?? 0,
151
+ couponId: data.couponId ?? null,
152
+ appliedCoupons: data.appliedCoupons ?? [],
153
+ });
130
154
  const origin = typeof window !== "undefined" ? window.location.origin : "";
131
155
  const ru = `${origin}${finalisePath(slug, data.orderId)}`;
132
156
  setReturnUrl(ru);
@@ -141,10 +165,29 @@ export function useEventCheckout(slug?: string, opts: UseEventCheckoutOptions =
141
165
  if (result.provider && result.provider !== "stripe") return; // Paystack redirected
142
166
  setStep("payment");
143
167
  } catch (e) {
144
- setError(errMessage(e));
168
+ // A refused code fails the whole request, so with one entered the message
169
+ // belongs next to the field the buyer just used. The message is the API's
170
+ // own — "This coupon has expired", "…does not reach this coupon's minimum
171
+ // spend" — never a house "invalid code" that hides which it was.
172
+ if (coupon.submittedCode) coupon.fail(e);
173
+ else setError(errMessage(e));
145
174
  }
146
175
  };
147
176
 
177
+ /**
178
+ * Drop the code and go back to re-enter details. There is nothing to un-apply
179
+ * server-side: the order was created WITH the discount and is simply left
180
+ * behind, exactly as pressing "Back" already does. The next
181
+ * `continueToPayment` creates a fresh, undiscounted order.
182
+ */
183
+ const clearCoupon = () => {
184
+ coupon.reset();
185
+ // The started payment described the DISCOUNTED order; leaving it would keep
186
+ // the reduced total on screen after the discount is gone.
187
+ flow.reset();
188
+ setStep("details");
189
+ };
190
+
148
191
  return {
149
192
  event,
150
193
  isLoading,
@@ -153,7 +196,15 @@ export function useEventCheckout(slug?: string, opts: UseEventCheckoutOptions =
153
196
  selectedTickets,
154
197
  setTicketQty,
155
198
  ticketCount,
156
- totalAmount: flow.result?.totalAmount ?? totalAmount,
199
+ // The server's figure wins the moment there is one: start-payment first,
200
+ // then the order response (which is already net of any discount), and only
201
+ // the locally summed ticket prices before either exists.
202
+ totalAmount: flow.result?.totalAmount ?? coupon.quote?.totalAmount ?? totalAmount,
203
+ /** GROSS ticket total, before any discount. */
204
+ subTotal: coupon.quote?.subTotal ?? totalAmount,
205
+ /** Discount code state + the server's quote. See `useCouponField`. */
206
+ coupon,
207
+ clearCoupon,
157
208
  /** Authoritative sales-tax quote from start-payment (display only). */
158
209
  taxQuote: flow.result?.taxQuote ?? null,
159
210
  firstName,
@@ -23,6 +23,13 @@ export { useSignupForm, type UseSignupFormOptions } from "./auth/useSignupForm";
23
23
  // Flow primitives (Part A2) — multi-step purchase/booking/subscribe/chat flows,
24
24
  // each composed from the data hooks so a creator can rebuild any page.
25
25
  export { useEventCheckout, type UseEventCheckoutOptions, type EventCheckoutStep } from "./event/useEventCheckout";
26
+ export {
27
+ useCouponField,
28
+ apiErrorMessage,
29
+ couponFailureMessage,
30
+ type CouponField,
31
+ type CouponQuoteFn,
32
+ } from "./coupon/useCouponField";
26
33
  export { useCourseCheckout, type UseCourseCheckoutOptions, type CourseCheckoutStep } from "./course/useCourseCheckout";
27
34
  export {
28
35
  useCoachingBooking,
@@ -43,6 +50,14 @@ export { useMessageThread, type UseMessageThreadResult } from "./chat/useMessage
43
50
  export { useChatAttachmentUpload, type PendingAttachment } from "./chat/useChatAttachmentUpload";
44
51
  export { attachmentKind, formatBytes, type AttachmentKind } from "./chat/attachmentKind";
45
52
  export { useCookieConsent, type UseCookieConsentResult } from "./consent/useCookieConsent";
53
+ export {
54
+ useAddToCalendar,
55
+ buildAddToCalendarLinks,
56
+ toUtcBasic,
57
+ stripHtml,
58
+ type AddToCalendarInput,
59
+ type AddToCalendarLinks,
60
+ } from "./calendar/useAddToCalendar";
46
61
 
47
62
  export { usePodcastPlayer, type UsePodcastPlayerOptions, type PodcastPlayerState } from "./podcast/usePodcastPlayer";
48
63
 
package/src/ui/index.ts CHANGED
@@ -45,6 +45,12 @@ export {
45
45
  export { DonationButton, type DonationButtonProps } from "./styled/DonationButton";
46
46
  export { OfferButton, type OfferButtonProps } from "./styled/OfferButton";
47
47
  export { Checkout, type CheckoutProps } from "./styled/Checkout";
48
+ export {
49
+ DiscountCodeField,
50
+ type DiscountCodeFieldProps,
51
+ DiscountSummaryLines,
52
+ type DiscountSummaryLinesProps,
53
+ } from "./styled/DiscountCode";
48
54
  export { MembershipCheckout, type MembershipCheckoutProps } from "./styled/MembershipCheckout";
49
55
  export { ForgeStripePayment } from "./payment/ForgeStripePayment";
50
56
  export { Cart, type CartProps } from "./styled/Cart";
@@ -66,7 +72,10 @@ export { MembershipTiers, type MembershipTiersProps } from "./styled/MembershipT
66
72
  export { EventsList, type EventsListProps } from "./styled/EventsList";
67
73
  export { EventTickets, type EventTicketsProps } from "./styled/EventTickets";
68
74
  export { EventCountdown, type EventCountdownProps } from "./styled/EventCountdown";
75
+ export { EventWaitlist, type EventWaitlistProps, formatCountdown } from "./styled/EventWaitlist";
69
76
  export { EventDetail, type EventDetailProps } from "./styled/EventDetail";
77
+ export { AddToCalendar, type AddToCalendarProps } from "./styled/AddToCalendar";
78
+ export { WalletPassButtons, type WalletPassButtonsProps } from "./styled/WalletPassButtons";
70
79
  export { CoachingBooking, type CoachingBookingProps } from "./styled/CoachingBooking";
71
80
  export { CoachingDetail, type CoachingDetailProps } from "./styled/CoachingDetail";
72
81
  export { CourseCheckout, type CourseCheckoutProps } from "./styled/CourseCheckout";
@@ -78,6 +87,12 @@ export { SignupForm, type SignupFormProps } from "./styled/SignupForm";
78
87
  export { ForgotPasswordForm, type ForgotPasswordFormProps } from "./styled/ForgotPasswordForm";
79
88
  export { ResetPasswordForm, type ResetPasswordFormProps } from "./styled/ResetPasswordForm";
80
89
  export { AccountDashboard, type AccountDashboardProps, type AccountTabKey, ACCOUNT_TABS } from "./styled/AccountDashboard";
90
+ export {
91
+ TicketTransferPanel,
92
+ type TicketTransferPanelProps,
93
+ ClaimTicketTransfer,
94
+ type ClaimTicketTransferProps,
95
+ } from "./styled/TicketTransfer";
81
96
  export { AudioPlayer, type AudioPlayerProps } from "./styled/AudioPlayer";
82
97
  export { ForgeAnalytics, type ForgeAnalyticsProps } from "./analytics/ForgeAnalytics";
83
98
  export { PageMetaPixel, usePageMetaPixel, type PageMetaPixelProps } from "./analytics/PageMetaPixel";
@@ -134,6 +149,17 @@ export { PwaRegistration, type PwaRegistrationProps } from "./styled/PwaRegistra
134
149
  export { InstallBanner, type InstallBannerProps } from "./styled/InstallBanner";
135
150
  // The single root component — providers + audio + analytics + PWA + consent in one.
136
151
  export { TribeNestApp, type TribeNestAppProps } from "./shell/TribeNestApp";
152
+ // The SSR-bootstrap failure banner + its gating. Exported so a bespoke shell that
153
+ // doesn't use <TribeNestApp> can still fail loudly instead of silently rendering
154
+ // Forge's defaults when the API is unreachable.
155
+ export { PreviewDiagnostics } from "./shell/PreviewDiagnostics";
156
+ export {
157
+ previewDiagnosticsEnabled,
158
+ resolvePreviewDiagnostics,
159
+ previewDiagnosticsMessage,
160
+ type PreviewDiagnosticsMessage,
161
+ } from "./shell/diagnosticsGating";
162
+ export type { ApiProbeResult, ForgeSsrDiagnostics, SsrFetchFailure } from "../types/diagnostics";
137
163
  export { PushOptIn, type PushOptInProps } from "./styled/PushOptIn";
138
164
 
139
165
  // Community (forum) styled blocks.
@@ -0,0 +1,62 @@
1
+ import { useForge } from "../../provider/ForgeProvider";
2
+ import { useThemeTokens } from "../theme/ForgeThemeProvider";
3
+ import { poweredByHref } from "./shellGating";
4
+
5
+ export interface PoweredByProps {
6
+ /** Live released build only — see `shellPoweredByEnabled`. */
7
+ enabled?: boolean;
8
+ }
9
+
10
+ /**
11
+ * The "Powered by TribeNest" line every released site and app carries.
12
+ *
13
+ * Rendered by `TribeNestApp` after the page tree, so it lands BELOW the tenant's
14
+ * own footer and needs no edit to the tenant-owned `__root.tsx` — a Forge bump
15
+ * distributes it to every existing site. Both starters (`apps/site-starter` and
16
+ * `apps/app-starter`) wrap in `TribeNestApp`, so websites and mini-apps are
17
+ * covered by the same component.
18
+ *
19
+ * Deliberately NOT a prop on `TribeNestApp`: the tenant owns `__root.tsx`, so an
20
+ * opt-out prop is an opt-out. Removal is a server-side decision instead —
21
+ * `siteConfig.hideTribeNestBadge`, which is how a white-label plan entitlement
22
+ * will switch it off without waiting for a Forge release to propagate.
23
+ *
24
+ * Styled from theme tokens and kept in the normal document flow (not fixed), so
25
+ * it inherits the site's palette and never collides with the pinned AudioPlayer.
26
+ */
27
+ export function PoweredBy({ enabled = true }: PoweredByProps) {
28
+ const t = useThemeTokens();
29
+ const { subdomain, profileId, appId } = useForge();
30
+ if (!enabled) return null;
31
+ // Tagged from the identity ForgeProvider was built with — see `poweredByHref`.
32
+ const href = poweredByHref({ subdomain, profileId, appId });
33
+ return (
34
+ <div
35
+ style={{
36
+ display: "flex",
37
+ justifyContent: "center",
38
+ padding: "14px 16px",
39
+ borderTop: `1px solid ${t.border}`,
40
+ background: t.background,
41
+ }}
42
+ >
43
+ <a
44
+ href={href}
45
+ target="_blank"
46
+ // nofollow: the same link on every site we host is exactly the pattern
47
+ // Google reads as a link scheme. Drop it if the SEO value is judged
48
+ // worth that risk — it is a one-word change.
49
+ rel="noopener noreferrer nofollow"
50
+ style={{
51
+ fontSize: 12,
52
+ lineHeight: 1,
53
+ color: t.muted,
54
+ textDecoration: "none",
55
+ letterSpacing: 0.2,
56
+ }}
57
+ >
58
+ Powered by <span style={{ fontWeight: 600 }}>TribeNest</span>
59
+ </a>
60
+ </div>
61
+ );
62
+ }
@@ -0,0 +1,80 @@
1
+ import { useState } from "react";
2
+ import type { ForgeSsrDiagnostics } from "../../types/diagnostics";
3
+ import { previewDiagnosticsMessage } from "./diagnosticsGating";
4
+
5
+ /**
6
+ * The loud failure. Rendered by `<TribeNestApp>` in the builder preview and on
7
+ * review Workers — never on the live published site (see
8
+ * `previewDiagnosticsEnabled`).
9
+ *
10
+ * EVERY COLOR HERE IS A LITERAL, on purpose. This banner announces that the
11
+ * theme could not be fetched, so it cannot itself be themed: `var(--forge-*)`
12
+ * would resolve to the very fallbacks it is warning about, and on a dark-ish
13
+ * default it could render invisible. It is also the one component that must
14
+ * survive a totally broken render, so it takes nothing from context.
15
+ */
16
+ export function PreviewDiagnostics({ diagnostics }: { diagnostics: ForgeSsrDiagnostics }) {
17
+ const [open, setOpen] = useState(false);
18
+ const msg = previewDiagnosticsMessage(diagnostics);
19
+
20
+ return (
21
+ <div
22
+ role="alert"
23
+ style={{
24
+ position: "fixed",
25
+ top: 0,
26
+ left: 0,
27
+ right: 0,
28
+ // Above anything a site can reasonably stack, including sticky navs.
29
+ zIndex: 2147483000,
30
+ background: "#7f1d1d",
31
+ color: "#fef2f2",
32
+ borderBottom: "1px solid #dc2626",
33
+ fontFamily:
34
+ 'ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',
35
+ fontSize: 13,
36
+ lineHeight: 1.45,
37
+ boxShadow: "0 2px 12px rgba(0,0,0,0.35)",
38
+ }}
39
+ >
40
+ <div style={{ maxWidth: 900, margin: "0 auto", padding: "10px 14px" }}>
41
+ <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
42
+ <span aria-hidden style={{ fontSize: 15, lineHeight: 1.3 }}>
43
+ ⚠️
44
+ </span>
45
+ <div style={{ flex: 1, minWidth: 0 }}>
46
+ <strong style={{ fontWeight: 700 }}>{msg.title}</strong>
47
+ <div style={{ marginTop: 3, color: "#fecaca" }}>{msg.consequence}</div>
48
+ </div>
49
+ <button
50
+ type="button"
51
+ onClick={() => setOpen((v) => !v)}
52
+ aria-expanded={open}
53
+ style={{
54
+ flexShrink: 0,
55
+ background: "transparent",
56
+ border: "1px solid #f87171",
57
+ borderRadius: 6,
58
+ color: "#fef2f2",
59
+ cursor: "pointer",
60
+ fontSize: 12,
61
+ padding: "3px 9px",
62
+ }}
63
+ >
64
+ {open ? "Hide" : "Details"}
65
+ </button>
66
+ </div>
67
+
68
+ {open && (
69
+ <ul style={{ margin: "9px 0 0", padding: "0 0 0 26px", color: "#fecaca" }}>
70
+ {msg.details.map((line) => (
71
+ <li key={line} style={{ marginTop: 2, wordBreak: "break-word" }}>
72
+ {line}
73
+ </li>
74
+ ))}
75
+ </ul>
76
+ )}
77
+ </div>
78
+ </div>
79
+ );
80
+ }
@@ -6,7 +6,12 @@ import { PwaRegistration } from "../styled/PwaRegistration";
6
6
  import { InstallBanner } from "../styled/InstallBanner";
7
7
  import { CookieConsent } from "../styled/CookieConsent";
8
8
  import { useThemeTokens } from "../theme/ForgeThemeProvider";
9
- import { shellPwaEnabled } from "./shellGating";
9
+ import { useInitialSiteConfig } from "../../provider/SiteConfigProvider";
10
+ import { PoweredBy } from "./PoweredBy";
11
+ import { PreviewDiagnostics } from "./PreviewDiagnostics";
12
+ import { shellPoweredByEnabled, shellPwaEnabled } from "./shellGating";
13
+ import { previewDiagnosticsEnabled, resolvePreviewDiagnostics } from "./diagnosticsGating";
14
+ import type { ForgeSsrDiagnostics } from "../../types/diagnostics";
10
15
  import { captureAttributionRefFromUrl, readAttributionRef } from "../../utils/attribution";
11
16
  import { captureLandingFromUrl, postLandingBeacon } from "../../utils/landing";
12
17
 
@@ -36,6 +41,13 @@ export interface TribeNestAppProps extends Omit<ForgeProviderProps, "children">
36
41
  state?: "draft" | "published";
37
42
  /** Href for the client-injected manifest link fallback. */
38
43
  manifestHref?: string;
44
+ /**
45
+ * What failed while bootstrapping this render, from `fetchSiteBootstrap`.
46
+ * Surfaced as a banner in the editor preview / review Workers only. Optional:
47
+ * a shell that still calls `fetchContentDocument`/`fetchSiteConfig` separately
48
+ * gets a less detailed banner inferred from a null `initialSiteConfig`.
49
+ */
50
+ diagnostics?: ForgeSsrDiagnostics | null;
39
51
  /** Turn individual shell concerns off (all default on). */
40
52
  analytics?: boolean;
41
53
  pwa?: boolean;
@@ -65,6 +77,15 @@ function PwaHeadClient({ enabled, manifestHref }: { enabled: boolean; manifestHr
65
77
  return null;
66
78
  }
67
79
 
80
+ // Reads the server-supplied site config, so the white-label entitlement can turn
81
+ // the badge off without a Forge release. Must live INSIDE ForgeProvider (that is
82
+ // what mounts SiteConfigProvider), hence a component rather than a call in the
83
+ // TribeNestApp body.
84
+ function PoweredByGate({ editable, state }: { editable?: boolean; state?: "draft" | "published" }) {
85
+ const siteConfig = useInitialSiteConfig();
86
+ return <PoweredBy enabled={shellPoweredByEnabled({ editable, state, hideBadge: siteConfig?.hideTribeNestBadge })} />;
87
+ }
88
+
68
89
  /**
69
90
  * The single root component for a TribeNest code website. Wrap the page tree once
70
91
  * — it owns the whole provider tree (via `ForgeProvider`) PLUS the global shell
@@ -89,6 +110,7 @@ export function TribeNestApp({
89
110
  editable,
90
111
  state,
91
112
  manifestHref = "/manifest.webmanifest",
113
+ diagnostics,
92
114
  analytics = true,
93
115
  pwa = true,
94
116
  cookieConsent = true,
@@ -97,9 +119,25 @@ export function TribeNestApp({
97
119
  // Register the SW + offer install only on the live published site — never in
98
120
  // the HMR editor or on a preview-<versionId>.* review Worker (state="draft").
99
121
  const pwaEnabled = shellPwaEnabled({ pwa, editable, state });
122
+ // A failed SSR bootstrap renders a complete-looking page built entirely from
123
+ // fallbacks — indistinguishable from an unconfigured site. Say so, where the
124
+ // people who can fix it are looking.
125
+ const ssrFailure = previewDiagnosticsEnabled({ editable, state })
126
+ ? resolvePreviewDiagnostics({
127
+ diagnostics,
128
+ profileId: forgeProps.profileId,
129
+ siteConfig: forgeProps.initialSiteConfig,
130
+ apiUrl: forgeProps.apiUrl,
131
+ })
132
+ : null;
100
133
  return (
101
134
  <ForgeProvider editable={editable} {...forgeProps}>
135
+ {/* First in the tree: it must render even if everything below it doesn't. */}
136
+ {ssrFailure && <PreviewDiagnostics diagnostics={ssrFailure} />}
102
137
  {children}
138
+ {/* "Powered by TribeNest" — last in the page flow, so it sits below the
139
+ tenant's own footer. Released builds only (live + published). */}
140
+ <PoweredByGate editable={editable} state={state} />
103
141
  {/* Global playback bar — self-pins to the viewport bottom, renders nothing
104
142
  until a track loads. */}
105
143
  <AudioPlayer />