@brainerce/mcp-server 3.6.0 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/http.js CHANGED
@@ -924,6 +924,175 @@ function ProductPage({ product, storeInfo }: { product: Product; storeInfo: Stor
924
924
  }
925
925
  \`\`\`
926
926
 
927
+ ### Variant Attribute Selector with Swatches (color + size **mix**)
928
+
929
+ The simple text-button picker above works, but loses the merchant-configured
930
+ **swatch metadata**. A single product often mixes one attribute that should
931
+ render as **color swatches** (e.g. \`Color\`) and another that should render
932
+ as **text buttons** (e.g. \`Size\`). The product response includes everything
933
+ you need:
934
+
935
+ - \`product.productAttributeOptions[]\` \u2014 the swatch definitions: \`attribute.name\`,
936
+ \`attribute.displayType\` (the \`AttributeDisplayType\` enum: \`DEFAULT\` | \`COLOR_SWATCH\` | \`IMAGE_SWATCH\` | \`MIXED_SWATCH\`),
937
+ \`attributeOption.name\`, \`swatchColor\` (hex), \`swatchColor2\` (hex \u2014 used for dual-color swatches
938
+ like Black & White), \`swatchImageUrl\` (for fabric / pattern thumbnails).
939
+ \`MIXED_SWATCH\` means each option in the group can independently pick image OR color
940
+ (the merchant decides per option). Treat any unrecognized value as \`DEFAULT\`.
941
+ - \`variant.attributes\` \u2014 the selected value per attribute on each variant.
942
+
943
+ Use \`getProductSwatches(product)\` to get a render-ready, grouped structure:
944
+
945
+ \`\`\`typescript
946
+ import { getProductSwatches } from 'brainerce';
947
+
948
+ const groups = getProductSwatches(product);
949
+ // [
950
+ // { attributeName: 'color', displayType: 'COLOR_SWATCH', options: [
951
+ // { name: 'Full Color', swatchColor: '#1D9435', swatchColor2: null, swatchImageUrl: null },
952
+ // { name: 'Black & White', swatchColor: '#000000', swatchColor2: '#FFFFFF', swatchImageUrl: null },
953
+ // ]},
954
+ // { attributeName: 'size', displayType: 'DEFAULT', options: [
955
+ // { name: '16" \xD7 20"' }, { name: '24" \xD7 32"' }, { name: '36" \xD7 48"' },
956
+ // ]},
957
+ // ]
958
+ \`\`\`
959
+
960
+ Render one branch per \`displayType\`. The same loop handles all-swatch, all-text,
961
+ and the mix case:
962
+
963
+ \`\`\`typescript
964
+ function VariantPicker({
965
+ product,
966
+ selections,
967
+ onSelect,
968
+ }: {
969
+ product: Product;
970
+ selections: Record<string, string>; // { color: 'Full Color', size: '24" \xD7 32"' }
971
+ onSelect: (attrName: string, value: string) => void;
972
+ }) {
973
+ const groups = getProductSwatches(product);
974
+ if (groups.length === 0) return null;
975
+
976
+ return (
977
+ <div className="space-y-4">
978
+ {groups.map((group) => (
979
+ <div key={group.attributeName}>
980
+ <label className="block mb-2 text-sm font-medium">
981
+ {group.attributeName}: <span className="text-gray-500">{selections[group.attributeName] ?? ''}</span>
982
+ </label>
983
+ <div className="flex flex-wrap gap-2">
984
+ {group.options.map((opt) => {
985
+ const isSelected = selections[group.attributeName] === opt.name;
986
+
987
+ // COLOR_SWATCH \u2014 round button; dual-color uses a 50/50 gradient.
988
+ if (group.displayType === 'COLOR_SWATCH' && opt.swatchColor) {
989
+ const bg = opt.swatchColor2
990
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
991
+ : opt.swatchColor;
992
+ return (
993
+ <button
994
+ key={opt.name}
995
+ type="button"
996
+ title={opt.name}
997
+ aria-pressed={isSelected}
998
+ onClick={() => onSelect(group.attributeName, opt.name)}
999
+ className={\`h-9 w-9 rounded-full border-2 \${isSelected ? 'border-black ring-2 ring-black/30' : 'border-gray-300 hover:border-black'}\`}
1000
+ style={{ background: bg }}
1001
+ />
1002
+ );
1003
+ }
1004
+
1005
+ // IMAGE_SWATCH \u2014 square thumbnail (fabric/pattern preview).
1006
+ if (group.displayType === 'IMAGE_SWATCH' && opt.swatchImageUrl) {
1007
+ return (
1008
+ <button
1009
+ key={opt.name}
1010
+ type="button"
1011
+ aria-pressed={isSelected}
1012
+ onClick={() => onSelect(group.attributeName, opt.name)}
1013
+ className={\`h-10 w-10 overflow-hidden rounded border-2 \${isSelected ? 'border-black' : 'border-gray-300'}\`}
1014
+ >
1015
+ <img src={opt.swatchImageUrl} alt={opt.name} className="h-full w-full object-cover" />
1016
+ </button>
1017
+ );
1018
+ }
1019
+
1020
+ // MIXED_SWATCH \u2014 each option is independently image OR color (image wins if present).
1021
+ if (group.displayType === 'MIXED_SWATCH') {
1022
+ if (opt.swatchImageUrl) {
1023
+ return (
1024
+ <button
1025
+ key={opt.name}
1026
+ type="button"
1027
+ aria-pressed={isSelected}
1028
+ onClick={() => onSelect(group.attributeName, opt.name)}
1029
+ className={\`h-10 w-10 overflow-hidden rounded border-2 \${isSelected ? 'border-black' : 'border-gray-300'}\`}
1030
+ >
1031
+ <img src={opt.swatchImageUrl} alt={opt.name} className="h-full w-full object-cover" />
1032
+ </button>
1033
+ );
1034
+ }
1035
+ if (opt.swatchColor) {
1036
+ const bg = opt.swatchColor2
1037
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
1038
+ : opt.swatchColor;
1039
+ return (
1040
+ <button
1041
+ key={opt.name}
1042
+ type="button"
1043
+ title={opt.name}
1044
+ aria-pressed={isSelected}
1045
+ onClick={() => onSelect(group.attributeName, opt.name)}
1046
+ className={\`h-9 w-9 rounded-full border-2 \${isSelected ? 'border-black ring-2 ring-black/30' : 'border-gray-300 hover:border-black'}\`}
1047
+ style={{ background: bg }}
1048
+ />
1049
+ );
1050
+ }
1051
+ // option has neither image nor color \u2192 fall through to text button below.
1052
+ }
1053
+
1054
+ // DEFAULT (or any swatch type missing its data) \u2014 plain text button.
1055
+ return (
1056
+ <button
1057
+ key={opt.name}
1058
+ type="button"
1059
+ aria-pressed={isSelected}
1060
+ onClick={() => onSelect(group.attributeName, opt.name)}
1061
+ className={\`rounded border px-3 py-1.5 text-sm \${isSelected ? 'bg-black text-white border-black' : 'border-gray-300 hover:border-black'}\`}
1062
+ >
1063
+ {opt.name}
1064
+ </button>
1065
+ );
1066
+ })}
1067
+ </div>
1068
+ </div>
1069
+ ))}
1070
+ </div>
1071
+ );
1072
+ }
1073
+ \`\`\`
1074
+
1075
+ Wire it up in the product page: keep \`selections\` in state, find the matching
1076
+ variant after each pick, and update price / image / stock from it.
1077
+
1078
+ \`\`\`typescript
1079
+ const [selections, setSelections] = useState<Record<string, string>>({});
1080
+
1081
+ const matchedVariant = useMemo(() => (
1082
+ product.variants?.find((v) =>
1083
+ Object.entries(selections).every(([k, val]) => v.attributes?.[k] === val)
1084
+ ) ?? null
1085
+ ), [product.variants, selections]);
1086
+
1087
+ // Greying-out unavailable combinations: for each candidate value, run
1088
+ // the same find() and check \`inventory.canPurchase\`. Disable the button
1089
+ // if no purchasable variant exists under that selection.
1090
+ \`\`\`
1091
+
1092
+ **i18n:** \`getProductSwatches\` returns translated \`attributeName\` and
1093
+ \`option.name\` automatically when \`client.setLocale()\` is active. No
1094
+ client-side overlay needed. Swatch colors are language-agnostic.
1095
+
927
1096
  ### Description Rendering (handles HTML vs text)
928
1097
 
929
1098
  \`\`\`typescript
@@ -1558,17 +1727,28 @@ Allergens (informational chips), scheduled availability windows, nested combos (
1558
1727
  function getProductReviewsSection() {
1559
1728
  return `## Product Reviews (\u2605 ratings + JSON-LD for SEO)
1560
1729
 
1561
- Reviews publish immediately on submit. Merchants hide individual reviews via the admin surface \u2014 no PENDING queue.
1730
+ **Purchaser-only.** Only authenticated customers who purchased the product can submit. Each customer writes one review per product and can edit/delete it. Reviews publish immediately \u2014 no PENDING queue.
1562
1731
 
1563
1732
  \`\`\`typescript
1564
- // PDP \u2014 list visible reviews
1565
- const { data, meta } = await client.listProductReviews(productId, { page: 1, limit: 20 });
1566
- data.forEach(r => render(r.authorName, r.rating, r.body, r.verifiedPurchase));
1733
+ // PDP \u2014 list visible reviews (public)
1734
+ const { data } = await getClient().listProductReviews(productId, { page: 1, limit: 20 });
1735
+
1736
+ // Decide which UI to render for the current customer
1737
+ getClient().setCustomerToken(authToken); // after login
1738
+ const { eligible, reason, myReview } = await getClient().getMyProductReview(productId);
1739
+
1740
+ if (!eligible) {
1741
+ // reason: 'no_eligible_order' | 'reviews_disabled' | 'product_not_found'
1742
+ // \u2192 "only customers who purchased this product can leave a review"
1743
+ } else if (myReview) {
1744
+ // \u2192 edit form prefilled with myReview.rating + myReview.body
1745
+ } else {
1746
+ // \u2192 submit form (rating + body only \u2014 name/email come from customer profile)
1747
+ }
1567
1748
 
1568
- // PDP \u2014 submit form
1569
- await client.submitProductReview(productId, {
1570
- authorName, authorEmail, rating: 5, body,
1571
- });
1749
+ await getClient().submitProductReview(productId, { rating: 5, body: 'Loved it!' });
1750
+ await getClient().updateMyProductReview(productId, { rating: 4, body: 'Updated.' });
1751
+ await getClient().deleteMyProductReview(productId); // can submit a new one after
1572
1752
  \`\`\`
1573
1753
 
1574
1754
  Each \`Product\` carries denormalized rollups: \`product.avgRating\`, \`product.reviewCount\`. Use these on PLP cards.
@@ -1597,9 +1777,10 @@ const productJsonLd = {
1597
1777
 
1598
1778
  ### Rules
1599
1779
  - Rating must be an integer 1-5 (DB constraint).
1600
- - Duplicate from same email \u2192 409 Conflict.
1601
- - Submit endpoint is throttled to 3 / 60s / IP \u2014 surface a friendly "please wait" on 429.
1602
- - \`verifiedPurchase\` is derived server-side from DELIVERED orders \u2014 DO NOT try to set it.
1780
+ - Customer must be logged in AND have purchased the product (\`SHIPPED+\` for physical, \`PAID+\` for downloadable).
1781
+ - One review per (productId, customerId). Duplicate submit \u2192 409 \u2014 use updateMyProductReview instead.
1782
+ - Submit throttled 3 / 60s / IP; edit/delete 5 / 60s / IP.
1783
+ - \`verifiedPurchase\` is always true for customer-submitted reviews.
1603
1784
  - Stores with \`reviewsEnabled = false\` return 403 on storefront endpoints.`;
1604
1785
  }
1605
1786
  function getInventorySection() {
@@ -2021,9 +2202,12 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
2021
2202
  const client = getServerClient();
2022
2203
  client.setLocale(locale);
2023
2204
  const product = await client.getProductBySlug(slug);
2205
+ // NEVER feed raw HTML into <meta name="description"> \u2014 product.description
2206
+ // is often rich-text HTML. Strip tags first, then truncate on a word
2207
+ // boundary. See buildMetaDescription() in lib/seo.ts.
2024
2208
  return {
2025
2209
  title: product.seoTitle || product.name,
2026
- description: product.seoDescription || product.description?.slice(0, 160),
2210
+ description: product.seoDescription || buildMetaDescription(product.description) || product.name,
2027
2211
  };
2028
2212
  }
2029
2213
  \`\`\`
@@ -2139,11 +2323,25 @@ Because the backend already overlays everything, UI code is just:
2139
2323
 
2140
2324
  ### RTL handling
2141
2325
 
2142
- For RTL locales (\`he\`, \`ar\`), set \`<html dir="rtl">\` in the root layout and
2143
- let flexbox reverse automatically. Do NOT add \`flex-row-reverse\` on top of
2144
- \`dir="rtl"\` \u2014 that's a double-swap. DO swap directional icons (chevrons,
2145
- arrows) manually. Use logical CSS properties (\`ms-*\`/\`me-*\`) instead of
2146
- \`ml-*\`/\`mr-*\`.
2326
+ Resolve direction with \`client.getStoreDirection(locale)\` \u2014 it returns
2327
+ \`'ltr' | 'rtl'\` for any BCP-47 tag (Arabic, Hebrew, Persian, Urdu, Yiddish
2328
+ today; future RTL locales added by the platform are picked up automatically).
2329
+ Do NOT maintain your own RTL locale set.
2330
+
2331
+ \`\`\`tsx
2332
+ // app/[locale]/layout.tsx
2333
+ const dir = client.getStoreDirection(locale);
2334
+ return <html lang={locale} dir={dir}>...</html>;
2335
+ \`\`\`
2336
+
2337
+ For static rendering, \`storeInfo.i18n.defaultDirection\` carries the store's
2338
+ default direction, and each entry in \`storeInfo.i18n.supportedLocaleObjects\`
2339
+ includes its own \`direction\`.
2340
+
2341
+ Let flexbox reverse automatically once \`<html dir="rtl">\` is set. Do NOT add
2342
+ \`flex-row-reverse\` on top \u2014 that's a double-swap. DO swap directional icons
2343
+ (chevrons, arrows) manually. Use logical CSS properties (\`ms-*\`/\`me-*\`)
2344
+ instead of \`ml-*\`/\`mr-*\`.
2147
2345
 
2148
2346
  ### Language switcher
2149
2347
 
@@ -2520,6 +2718,141 @@ and a \`newsletter\` form embedded in the footer), render each form from its
2520
2718
  own \`contactForms.get(key, locale)\` call. The \`formKey\` you pass to
2521
2719
  \`createInquiry\` must match.`;
2522
2720
  }
2721
+ function getContentSection() {
2722
+ return `## Content \u2014 typed merchant content store
2723
+
2724
+ Brainerce ships a typed content store so merchants can edit site chrome, FAQ,
2725
+ static pages, and inline rich-text blocks in the dashboard \u2014 without
2726
+ re-prompting the AI that built their storefront. Every row has a \`type\` +
2727
+ \`key\` + typed \`data\` payload + free-form \`customFields\`.
2728
+
2729
+ **Six content types.** Each one has a fixed \`data\` shape; the SDK's TypeScript
2730
+ generics keep them in lockstep:
2731
+
2732
+ | Type | Use for | \`data\` shape (abbreviated) |
2733
+ | -------------- | -------------------------------------- | --------------------------- |
2734
+ | \`FAQ\` | Q/A accordions | \`{ items: { question, answer }[] }\` |
2735
+ | \`FOOTER\` | Site footer (chrome) | \`{ columns, copyright?, social? }\` |
2736
+ | \`HEADER\` | Top nav + logo + CTA (chrome) | \`{ logo?, navItems, cta? }\` |
2737
+ | \`ANNOUNCEMENT\`| Banners; time-bound by \`startsAt/endsAt\` | \`{ message, severity, dismissible, ... }\` |
2738
+ | \`RICH_TEXT\` | Free-form HTML blocks embedded inline | \`{ html }\` |
2739
+ | \`PAGE\` | Static pages with slug + SEO | \`{ slug, title, html, seo? }\` |
2740
+
2741
+ Run \`get-type-definitions\` with \`domain: 'content'\` for the full interfaces.
2742
+
2743
+ ### Default key
2744
+
2745
+ Every type has \`'main'\` as its universal default key. \`client.content.faq.get()\`
2746
+ with no arguments resolves to \`key='main'\`. Topical keys (\`'shipping'\`,
2747
+ \`'holiday-2026'\`, \`'about'\`) are merchant-named.
2748
+
2749
+ ### Reading content (any SDK mode)
2750
+
2751
+ Public reads work in vibe-coded mode, storefront mode, and admin mode. They
2752
+ return \`null\` on 404 \u2014 render hard-coded fallbacks so the page never crashes
2753
+ when the merchant hasn't seeded yet.
2754
+
2755
+ \`\`\`ts
2756
+ // Single entry, default key 'main', resolved to a locale
2757
+ const faq = await client.content.faq.get('main', locale);
2758
+ if (faq) {
2759
+ faq.data.items.forEach(({ question, answer }) => {
2760
+ // Render question + sanitize(answer)
2761
+ });
2762
+ }
2763
+
2764
+ // All entries of a type
2765
+ const allFaqs = await client.content.faq.list(locale);
2766
+
2767
+ // Page by URL slug \u2014 for app/[slug]/page.tsx
2768
+ const page = await client.content.page.getBySlug(slug, locale);
2769
+ if (!page) notFound();
2770
+ \`\`\`
2771
+
2772
+ ### Security \u2014 sanitize HTML before rendering
2773
+
2774
+ \`FAQ.items[i].answer\`, \`RICH_TEXT.html\`, and \`PAGE.html\` carry
2775
+ MERCHANT-AUTHORED HTML. The server does NOT pre-sanitize \u2014 some merchants
2776
+ embed iframes (e.g. YouTube) which strict sanitizers would strip. ALWAYS
2777
+ sanitize on the storefront before injecting:
2778
+
2779
+ \`\`\`ts
2780
+ // Recommended: isomorphic-dompurify
2781
+ import DOMPurify from 'isomorphic-dompurify';
2782
+ const safe = DOMPurify.sanitize(rawHtml);
2783
+ <div dangerouslySetInnerHTML={{ __html: safe }} />;
2784
+ \`\`\`
2785
+
2786
+ Skipping this is XSS.
2787
+
2788
+ ### Custom fields
2789
+
2790
+ Every Content row carries a free-form \`customFields: Record<string, string>\`.
2791
+ Merchants add arbitrary key-value extras (\`helpEmail\`, \`phoneNumber\`,
2792
+ \`foundedYear\`) that you can opt into reading:
2793
+
2794
+ \`\`\`ts
2795
+ const faq = await client.content.faq.get('shipping');
2796
+ <a href={\`mailto:\${faq.customFields.helpEmail}\`}>Need help?</a>
2797
+ \`\`\`
2798
+
2799
+ The shape is whatever the merchant entered. Read keys you expect; ignore the rest.
2800
+
2801
+ ### Locale resolution
2802
+
2803
+ All public reads accept a \`locale\` argument. The server resolves
2804
+ \`translations[locale]\` server-side and returns the resolved \`data\` payload \u2014
2805
+ the storefront does NOT need to do its own overlay. Empty / missing translations
2806
+ fall through to the default-locale value.
2807
+
2808
+ ### Cache
2809
+
2810
+ Public reads carry \`Cache-Control: public, max-age=300, stale-while-revalidate=60\`.
2811
+ Merchant edits propagate within ~5 minutes. Don't layer extra client-side
2812
+ caching beyond Next.js's default fetch cache.
2813
+
2814
+ ### Admin writes (apiKey mode)
2815
+
2816
+ \`\`\`ts
2817
+ const adminClient = new BrainerceClient({ apiKey: process.env.BRAINERCE_API_KEY });
2818
+
2819
+ // Create \u2014 always starts in DRAFT
2820
+ const faq = await adminClient.content.faq.create({
2821
+ key: 'shipping',
2822
+ name: 'Shipping FAQ',
2823
+ data: { items: [{ question: 'How long?', answer: 'Most orders ship in 2 days.' }] },
2824
+ });
2825
+
2826
+ // Update (data replaces wholesale; last-write-wins on the data field)
2827
+ await adminClient.content.update(faq.id, {
2828
+ data: { items: [{ question: 'How long?', answer: 'Updated answer.' }] },
2829
+ });
2830
+
2831
+ // Publish / unpublish
2832
+ await adminClient.content.publish(faq.id);
2833
+ await adminClient.content.unpublish(faq.id);
2834
+
2835
+ // Hard delete
2836
+ await adminClient.content.remove(faq.id);
2837
+ \`\`\`
2838
+
2839
+ Write operations throw if called from vibe-coded or storefront mode.
2840
+
2841
+ ### Reserved key convention
2842
+
2843
+ \`'main'\` is reserved as the universal default. Don't use it for topical
2844
+ entries \u2014 pick a descriptive slug (\`'shipping'\`, \`'returns'\`, \`'about'\`,
2845
+ \`'holiday-2026'\`). The validation rule is \`^[a-z][a-z0-9-]*$\`, max 64 chars.
2846
+
2847
+ ### See also
2848
+
2849
+ - \`get-business-flows\` with \`flow: 'content-bootstrap'\` for the full
2850
+ layout / FAQ / page recipe.
2851
+ - \`get-required-features\` lists each Content surface (\`site-header\`,
2852
+ \`site-footer\`, \`announcement-bar\`, \`faq-page\`, \`static-pages\`).
2853
+ - \`get-type-definitions\` with \`domain: 'content'\` for the TypeScript
2854
+ interfaces.`;
2855
+ }
2523
2856
  function getSectionByTopic(topic, connectionId, currency) {
2524
2857
  const cid = connectionId || "vc_YOUR_CONNECTION_ID";
2525
2858
  const cur = currency || "USD";
@@ -2566,6 +2899,8 @@ function getSectionByTopic(topic, connectionId, currency) {
2566
2899
  return getAdminApiSection();
2567
2900
  case "inquiries":
2568
2901
  return getContactInquiriesSection();
2902
+ case "content":
2903
+ return getContentSection();
2569
2904
  case "all":
2570
2905
  return [
2571
2906
  "# Brainerce SDK \u2014 full topic dump",
@@ -2654,10 +2989,14 @@ function getSectionByTopic(topic, connectionId, currency) {
2654
2989
  "",
2655
2990
  "---",
2656
2991
  "",
2657
- getContactInquiriesSection()
2992
+ getContactInquiriesSection(),
2993
+ "",
2994
+ "---",
2995
+ "",
2996
+ getContentSection()
2658
2997
  ].join("\n");
2659
2998
  default:
2660
- return `Unknown topic: "${topic}". Available topics: setup, products, cart, checkout, checkout-custom-fields, payment, auth, order-confirmation, inventory, discounts, recommendations, product-customization-fields, tax, i18n, critical-rules, type-reference, admin, inquiries, all`;
2999
+ return `Unknown topic: "${topic}". Available topics: setup, products, cart, checkout, checkout-custom-fields, payment, auth, order-confirmation, inventory, discounts, recommendations, product-customization-fields, tax, i18n, critical-rules, type-reference, admin, inquiries, content, all`;
2661
3000
  }
2662
3001
  }
2663
3002
 
@@ -2685,6 +3024,7 @@ var GET_SDK_DOCS_SCHEMA = {
2685
3024
  "i18n",
2686
3025
  "admin",
2687
3026
  "inquiries",
3027
+ "content",
2688
3028
  "all"
2689
3029
  ]).describe("The SDK documentation topic to retrieve"),
2690
3030
  salesChannelId: import_zod.z.string().optional().describe("Sales channel ID (starts with vc_). Used to personalize setup code."),
@@ -2695,9 +3035,7 @@ var GET_SDK_DOCS_SCHEMA = {
2695
3035
  async function handleGetSdkDocs(args) {
2696
3036
  const id = args.salesChannelId ?? args.connectionId;
2697
3037
  if (!args.salesChannelId && args.connectionId) {
2698
- console.warn(
2699
- "get-sdk-docs: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
2700
- );
3038
+ console.warn("get-sdk-docs: `connectionId` is deprecated \u2014 use `salesChannelId` instead");
2701
3039
  }
2702
3040
  const content = getSectionByTopic(args.topic, id, args.currency);
2703
3041
  return {
@@ -3429,11 +3767,16 @@ interface ProductReviewAdmin extends ProductReview {
3429
3767
  updatedAt: string;
3430
3768
  }
3431
3769
 
3432
- interface SubmitProductReviewInput {
3433
- authorName: string;
3434
- authorEmail?: string; // recommended \u2014 used for guest dedupe + verified-purchase derivation
3770
+ interface WriteProductReviewInput {
3435
3771
  rating: number; // 1-5
3436
- body?: string; // optional
3772
+ body?: string; // optional, max 5000 chars
3773
+ }
3774
+
3775
+ interface MyProductReview {
3776
+ eligible: boolean;
3777
+ // Machine-readable reason when not eligible. null when eligible=true.
3778
+ reason: 'no_eligible_order' | 'reviews_disabled' | 'product_not_found' | null;
3779
+ myReview: ProductReview | null;
3437
3780
  }
3438
3781
 
3439
3782
  // Each Product carries denormalized review stats:
@@ -3674,6 +4017,156 @@ export interface ModifierValidationError {
3674
4017
  // The cart line then carries:
3675
4018
  // cart.items[i].modifiers \u2014 CartItemModifierLine[]
3676
4019
  // cart.items[i].modifiersTotal \u2014 decimal string of the paid (non-free) deltas`;
4020
+ var CONTENT_TYPES = `// ---- Content (typed merchant content store) ----
4021
+ // Brainerce ships a typed content store so merchants can edit FAQ, footer,
4022
+ // header, announcements, rich text, and static pages in the dashboard
4023
+ // without re-prompting the AI that built the storefront. Every row has a
4024
+ // 'type' + 'key' + typed 'data' payload + free-form 'customFields'.
4025
+ //
4026
+ // SECURITY (read carefully):
4027
+ // RICH_TEXT.html, PAGE.html, and FAQ answers are MERCHANT-AUTHORED HTML.
4028
+ // ALWAYS sanitize with isomorphic-dompurify (or equivalent) before
4029
+ // injecting via dangerouslySetInnerHTML. The server does NOT pre-sanitize
4030
+ // because some merchants embed iframes (e.g. YouTube) which strict
4031
+ // sanitizers would strip; the storefront chooses the policy.
4032
+ //
4033
+ // 404 contract: client.content.<type>.get(key) returns null when no
4034
+ // PUBLISHED row exists. Always render a hard-coded fallback on null so
4035
+ // the page never crashes when the merchant hasn't seeded yet.
4036
+ //
4037
+ // Default key: every type has 'main' as its universal default. Pass no
4038
+ // argument to fetch the main entry; pass a custom key ('shipping',
4039
+ // 'holiday-2026', 'about') for topical entries.
4040
+
4041
+ export type ContentType = 'FAQ' | 'FOOTER' | 'HEADER' | 'ANNOUNCEMENT' | 'RICH_TEXT' | 'PAGE';
4042
+ export type ContentStatus = 'DRAFT' | 'PUBLISHED';
4043
+
4044
+ export interface FaqItem {
4045
+ question: string;
4046
+ /** Sanitized HTML \u2014 sanitize before rendering. */
4047
+ answer: string;
4048
+ }
4049
+ export interface FaqContent { items: FaqItem[] }
4050
+
4051
+ export interface FooterLink { label: string; url: string }
4052
+ export interface FooterColumn { title: string; links: FooterLink[] }
4053
+ export interface FooterSocialLink { platform: string; url: string } // 'instagram' | 'facebook' | 'x' | ...
4054
+ export interface FooterContent {
4055
+ columns: FooterColumn[];
4056
+ copyright?: string;
4057
+ social?: FooterSocialLink[];
4058
+ }
4059
+
4060
+ export interface HeaderLogo { src: string; alt: string }
4061
+ export interface HeaderNavItem { label: string; url: string }
4062
+ export interface HeaderCta { label: string; url: string }
4063
+ export interface HeaderContent {
4064
+ logo?: HeaderLogo;
4065
+ navItems: HeaderNavItem[];
4066
+ cta?: HeaderCta;
4067
+ }
4068
+
4069
+ export type AnnouncementSeverity = 'info' | 'warning' | 'success';
4070
+ export interface AnnouncementContent {
4071
+ message: string;
4072
+ severity: AnnouncementSeverity;
4073
+ dismissible: boolean;
4074
+ /** ISO 8601 \u2014 filter client-side. */
4075
+ startsAt?: string;
4076
+ endsAt?: string;
4077
+ ctaLabel?: string;
4078
+ ctaHref?: string;
4079
+ }
4080
+
4081
+ export interface RichTextContent {
4082
+ /** Raw HTML \u2014 sanitize before rendering. */
4083
+ html: string;
4084
+ }
4085
+
4086
+ export interface PageSeo {
4087
+ title?: string;
4088
+ description?: string;
4089
+ ogImage?: string;
4090
+ }
4091
+ export interface PageContent {
4092
+ /** URL slug, lower-kebab. */
4093
+ slug: string;
4094
+ title: string;
4095
+ /** Raw HTML \u2014 sanitize before rendering. */
4096
+ html: string;
4097
+ seo?: PageSeo;
4098
+ }
4099
+
4100
+ export interface ContentSummary {
4101
+ id: string;
4102
+ type: ContentType;
4103
+ key: string;
4104
+ name: string;
4105
+ status: ContentStatus;
4106
+ position: number;
4107
+ updatedAt: string;
4108
+ }
4109
+
4110
+ export interface Content<T extends ContentType = ContentType> extends ContentSummary {
4111
+ type: T;
4112
+ data: T extends 'FAQ' ? FaqContent
4113
+ : T extends 'FOOTER' ? FooterContent
4114
+ : T extends 'HEADER' ? HeaderContent
4115
+ : T extends 'ANNOUNCEMENT' ? AnnouncementContent
4116
+ : T extends 'RICH_TEXT' ? RichTextContent
4117
+ : T extends 'PAGE' ? PageContent
4118
+ : never;
4119
+ /** Free-form merchant-defined extras. Read keys the merchant told you to expect. */
4120
+ customFields: Record<string, string>;
4121
+ salesChannelIds: string[];
4122
+ }
4123
+
4124
+ // ---- SDK usage examples ----
4125
+ //
4126
+ // FAQ \u2014 render an accordion from the main FAQ (or a topical one):
4127
+ // const faq = await client.content.faq.get('main', locale); // 'shipping', 'returns', ...
4128
+ // if (faq) {
4129
+ // faq.data.items.forEach(({ question, answer }) => {
4130
+ // // Render question + sanitize(answer) \u2014 never inject raw HTML.
4131
+ // });
4132
+ // }
4133
+ //
4134
+ // Footer \u2014 server component in root layout:
4135
+ // const footer = await client.content.footer.get('main', locale);
4136
+ // if (!footer) return <Fallback />;
4137
+ // // Render footer.data.columns, footer.data.social, footer.data.copyright
4138
+ //
4139
+ // Header \u2014 same pattern as footer:
4140
+ // const header = await client.content.header.get('main', locale);
4141
+ //
4142
+ // Announcement \u2014 multiple may be active; filter by date client-side:
4143
+ // const announcements = await client.content.announcement.list(locale);
4144
+ // const now = Date.now();
4145
+ // const active = announcements.filter((a) => {
4146
+ // const startOk = !a.data.startsAt || new Date(a.data.startsAt).getTime() <= now;
4147
+ // const endOk = !a.data.endsAt || new Date(a.data.endsAt).getTime() >= now;
4148
+ // return startOk && endOk;
4149
+ // });
4150
+ //
4151
+ // Rich text \u2014 inline block anywhere on a page:
4152
+ // const block = await client.content.richText.get('about-intro', locale);
4153
+ // <div dangerouslySetInnerHTML={{ __html: sanitize(block.data.html) }} />
4154
+ //
4155
+ // Page \u2014 catch-all route by slug (e.g. /about, /terms, /privacy):
4156
+ // // app/[slug]/page.tsx
4157
+ // const page = await client.content.page.getBySlug(params.slug, locale);
4158
+ // if (!page) notFound();
4159
+ // // page.data.title, page.data.html, page.data.seo
4160
+ // return <article dangerouslySetInnerHTML={{ __html: sanitize(page.data.html) }} />;
4161
+ //
4162
+ // Custom fields \u2014 every Content row carries a free-form Record<string, string>:
4163
+ // const faq = await client.content.faq.get('shipping');
4164
+ // <a href={\`mailto:\${faq.customFields.helpEmail}\`}>Need help?</a>
4165
+ //
4166
+ // Cache \u2014 public reads carry Cache-Control: public, max-age=300,
4167
+ // stale-while-revalidate=60. Storefront changes propagate within ~5 min
4168
+ // of the merchant publishing. Do not add extra client-side caching
4169
+ // beyond Next.js's default fetch cache.`;
3677
4170
  var TYPES_BY_DOMAIN = {
3678
4171
  products: PRODUCTS_TYPES,
3679
4172
  cart: CART_TYPES,
@@ -3684,7 +4177,8 @@ var TYPES_BY_DOMAIN = {
3684
4177
  helpers: HELPERS_TYPES,
3685
4178
  inquiries: INQUIRIES_TYPES,
3686
4179
  reviews: REVIEWS_TYPES,
3687
- "modifier-groups": MODIFIER_GROUPS_TYPES
4180
+ "modifier-groups": MODIFIER_GROUPS_TYPES,
4181
+ content: CONTENT_TYPES
3688
4182
  };
3689
4183
  function getTypesByDomain(domain) {
3690
4184
  if (domain === "all") {
@@ -3715,9 +4209,10 @@ var GET_TYPE_DEFINITIONS_SCHEMA = {
3715
4209
  "helpers",
3716
4210
  "inquiries",
3717
4211
  "reviews",
4212
+ "content",
3718
4213
  "all"
3719
4214
  ]).describe(
3720
- 'The domain of types to retrieve. Use "helpers" for helper function signatures and common types like StoreInfo, PaginatedResponse.'
4215
+ 'The domain of types to retrieve. Use "helpers" for helper function signatures and common types like StoreInfo, PaginatedResponse. Use "content" for FAQ / Footer / Header / Announcement / RichText / Page.'
3721
4216
  )
3722
4217
  };
3723
4218
  async function handleGetTypeDefinitions(args) {
@@ -3736,6 +4231,7 @@ var GET_CODE_EXAMPLE_SCHEMA = {
3736
4231
  "sdk-init",
3737
4232
  "cart-read-and-mutate",
3738
4233
  "variant-selection",
4234
+ "variant-selector-swatches",
3739
4235
  "checkout-address-and-shipping",
3740
4236
  "checkout-payment-providers",
3741
4237
  "checkout-stripe-confirm",
@@ -3805,28 +4301,148 @@ for (const item of cart.items) {
3805
4301
  const unitPrice = parseFloat(item.unitPrice); // prices are strings!
3806
4302
  }`,
3807
4303
  "variant-selection": `// Variant selection with live stock + price updates.
4304
+ // Variants expose attributes as a flat object: { color: 'Red', size: 'M' }.
4305
+ // NOT 'options' \u2014 that field does not exist on ProductVariant.
3808
4306
  import { getVariantPrice, getStockStatus, getVariantOptions } from 'brainerce';
3809
4307
  import type { Product, ProductVariant } from 'brainerce';
3810
4308
 
3811
4309
  function selectVariant(product: Product, selections: Record<string, string>) {
3812
- // selections = { Size: 'M', Color: 'Red' }
3813
- const variant = product.variants.find((v) =>
3814
- v.options.every((o) => selections[o.name] === o.value)
4310
+ // selections = { size: 'M', color: 'Red' } (keys match variant.attributes keys)
4311
+ const variant = product.variants?.find((v) =>
4312
+ Object.entries(selections).every(([k, val]) => v.attributes?.[k] === val)
3815
4313
  );
3816
4314
  if (!variant) return null;
3817
4315
 
3818
- const price = getVariantPrice(product, variant); // handles compare-at, currency
3819
- const stock = getStockStatus(variant); // 'IN_STOCK' | 'LOW_STOCK' | 'OUT_OF_STOCK'
3820
- const canPurchase = stock !== 'OUT_OF_STOCK';
4316
+ const price = getVariantPrice(variant, product.basePrice); // string, fallback-aware
4317
+ const stock = getStockStatus(variant.inventory); // 'in-stock' | 'low-stock' | 'out-of-stock' | 'unavailable'
4318
+ const canPurchase = variant.inventory?.canPurchase !== false;
3821
4319
 
3822
4320
  // Switch the main product image to the variant's image if it has one
3823
- const image = variant.image ?? product.images[0];
4321
+ const image = variant.image ?? product.images?.[0];
3824
4322
 
3825
4323
  return { variant, price, stock, canPurchase, image };
3826
4324
  }
3827
4325
 
3828
- // Build the option picker from getVariantOptions(product) \u2014 returns
3829
- // [{ name: 'Size', values: ['S','M','L'] }, ...]`,
4326
+ // Build the option picker by iterating product.variants and grouping
4327
+ // variant.attributes into { color: ['Red', 'Blue'], size: ['S','M','L'] }.
4328
+ // For each variant you can also call getVariantOptions(variant) which returns
4329
+ // the same key/value pairs as an array with translated names when setLocale() is active.
4330
+ // For swatch metadata (color hex, dual-color, image), use the
4331
+ // 'variant-selector-swatches' operation instead.`,
4332
+ "variant-selector-swatches": `// Variant picker that mixes color swatches and text buttons in one product.
4333
+ // Uses product.productAttributeOptions[] \u2014 the merchant-configured swatch
4334
+ // metadata. displayType is the AttributeDisplayType Prisma enum, one of:
4335
+ // 'DEFAULT' \u2014 plain text button
4336
+ // 'COLOR_SWATCH' \u2014 swatchColor (+ optional swatchColor2 dual-color gradient)
4337
+ // 'IMAGE_SWATCH' \u2014 swatchImageUrl thumbnail
4338
+ // 'MIXED_SWATCH' \u2014 per-option hybrid: image if swatchImageUrl is set,
4339
+ // otherwise fall back to swatchColor
4340
+ // getProductSwatches() groups options by attribute name so you can render each
4341
+ // attribute with its own displayType \u2014 a single product can have Color as
4342
+ // swatches AND Size as text buttons.
4343
+ import { getProductSwatches } from 'brainerce';
4344
+ import type { Product } from 'brainerce';
4345
+
4346
+ function VariantPicker({
4347
+ product,
4348
+ selections,
4349
+ onSelect,
4350
+ }: {
4351
+ product: Product;
4352
+ selections: Record<string, string>;
4353
+ onSelect: (attrName: string, value: string) => void;
4354
+ }) {
4355
+ const groups = getProductSwatches(product);
4356
+ // groups: [{ attributeName, displayType, options: [{ name, swatchColor, swatchColor2, swatchImageUrl }] }]
4357
+
4358
+ return (
4359
+ <>
4360
+ {groups.map((group) => (
4361
+ <div key={group.attributeName}>
4362
+ <label>{group.attributeName}: {selections[group.attributeName] ?? ''}</label>
4363
+ <div style={{ display: 'flex', gap: 8 }}>
4364
+ {group.options.map((opt) => {
4365
+ const selected = selections[group.attributeName] === opt.name;
4366
+ const onClick = () => onSelect(group.attributeName, opt.name);
4367
+
4368
+ // COLOR_SWATCH: round button. swatchColor2 = dual-color gradient.
4369
+ if (group.displayType === 'COLOR_SWATCH' && opt.swatchColor) {
4370
+ const bg = opt.swatchColor2
4371
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
4372
+ : opt.swatchColor;
4373
+ return (
4374
+ <button
4375
+ key={opt.name}
4376
+ type="button"
4377
+ title={opt.name}
4378
+ aria-pressed={selected}
4379
+ onClick={onClick}
4380
+ style={{
4381
+ width: 36,
4382
+ height: 36,
4383
+ borderRadius: '50%',
4384
+ background: bg,
4385
+ outline: selected ? '2px solid black' : 'none',
4386
+ }}
4387
+ />
4388
+ );
4389
+ }
4390
+
4391
+ // IMAGE_SWATCH: square thumbnail.
4392
+ if (group.displayType === 'IMAGE_SWATCH' && opt.swatchImageUrl) {
4393
+ return (
4394
+ <button key={opt.name} type="button" onClick={onClick} aria-pressed={selected}>
4395
+ <img src={opt.swatchImageUrl} alt={opt.name} width={40} height={40} />
4396
+ </button>
4397
+ );
4398
+ }
4399
+
4400
+ // MIXED_SWATCH: per-option hybrid (image wins if present).
4401
+ if (group.displayType === 'MIXED_SWATCH') {
4402
+ if (opt.swatchImageUrl) {
4403
+ return (
4404
+ <button key={opt.name} type="button" onClick={onClick} aria-pressed={selected}>
4405
+ <img src={opt.swatchImageUrl} alt={opt.name} width={40} height={40} />
4406
+ </button>
4407
+ );
4408
+ }
4409
+ if (opt.swatchColor) {
4410
+ const bg = opt.swatchColor2
4411
+ ? \`linear-gradient(135deg, \${opt.swatchColor} 50%, \${opt.swatchColor2} 50%)\`
4412
+ : opt.swatchColor;
4413
+ return (
4414
+ <button
4415
+ key={opt.name}
4416
+ type="button"
4417
+ title={opt.name}
4418
+ aria-pressed={selected}
4419
+ onClick={onClick}
4420
+ style={{ width: 36, height: 36, borderRadius: '50%', background: bg }}
4421
+ />
4422
+ );
4423
+ }
4424
+ }
4425
+
4426
+ // DEFAULT (or any swatch type missing its data): text button.
4427
+ return (
4428
+ <button key={opt.name} type="button" onClick={onClick} aria-pressed={selected}>
4429
+ {opt.name}
4430
+ </button>
4431
+ );
4432
+ })}
4433
+ </div>
4434
+ </div>
4435
+ ))}
4436
+ </>
4437
+ );
4438
+ }
4439
+
4440
+ // After the user picks a value, find the matching ProductVariant:
4441
+ // product.variants?.find((v) =>
4442
+ // Object.entries(selections).every(([k, val]) => v.attributes?.[k] === val)
4443
+ // )
4444
+ // Then read variant.price, variant.image, variant.inventory.canPurchase
4445
+ // to update the rest of the PDP.`,
3830
4446
  "checkout-address-and-shipping": `// Step 1-3 of the checkout flow. Never reorder or skip.
3831
4447
  import { client } from './brainerce';
3832
4448
 
@@ -4143,8 +4759,10 @@ client.setLocale(locale);
4143
4759
  // order bumps, search suggestions, discount banners, nudges,
4144
4760
  // badges, order history.
4145
4761
 
4146
- // For RTL locales (he, ar), set the document direction.
4147
- // Framework-neutral: document.documentElement.setAttribute('dir', 'rtl');`,
4762
+ // For RTL direction, do not hardcode the locale list. Ask the SDK:
4763
+ // const dir = client.getStoreDirection(currentLocale); // 'ltr' | 'rtl'
4764
+ // document.documentElement.setAttribute('dir', dir);
4765
+ // (Or in React: <html dir={dir}>...</html>.)`,
4148
4766
  "order-history-full": `// Full "My Orders" account page. Render every piece of data the server
4149
4767
  // already returns \u2014 not just order number / total / status.
4150
4768
  //
@@ -4619,21 +5237,25 @@ function renderCartItem(item: CartItem): string {
4619
5237
  function lineTotal(item: CartItem): number {
4620
5238
  return item.unitPrice * item.quantity;
4621
5239
  }`,
4622
- "product-reviews": `// PDP: list visible reviews + submit form + JSON-LD aggregateRating
4623
- import { client } from '@/lib/brainerce';
4624
- import type { Product, ProductReview, SubmitProductReviewInput } from 'brainerce';
4625
-
5240
+ "product-reviews": `// Purchaser-only reviews. Customer must be logged in AND have purchased
5241
+ // the product. The component switches between sign-in CTA / not-eligible /
5242
+ // submit form / edit form based on getMyProductReview().
5243
+ import { getClient, getServerClient } from '@/lib/brainerce';
5244
+ import { checkAuthStatus } from '@/lib/auth';
5245
+ import type { Product, ProductReview, MyProductReview } from 'brainerce';
5246
+
5247
+ // Server component \u2014 fetches existing reviews + emits JSON-LD aggregateRating.
4626
5248
  export async function ProductReviewsSection({ product }: { product: Product }) {
4627
- const { data } = await client.listProductReviews(product.id, { page: 1, limit: 20 });
5249
+ const { data } = await getServerClient().listProductReviews(product.id, { page: 1, limit: 20 });
4628
5250
 
4629
5251
  return (
4630
5252
  <section>
4631
5253
  <h2>Reviews ({product.reviewCount ?? 0})</h2>
4632
- {data.length === 0 && <p>No reviews yet \u2014 be the first.</p>}
5254
+ {data.length === 0 && <p>No reviews yet.</p>}
4633
5255
  {data.map((r) => (
4634
5256
  <article key={r.id}>
4635
5257
  <strong>{r.authorName}</strong>
4636
- {r.verifiedPurchase && <span> \xB7 Verified</span>}
5258
+ {r.verifiedPurchase && <span> \xB7 Verified purchase</span>}
4637
5259
  <div>{'\u2605'.repeat(r.rating)}{'\u2606'.repeat(5 - r.rating)}</div>
4638
5260
  {r.body && <p>{r.body}</p>}
4639
5261
  </article>
@@ -4666,42 +5288,83 @@ function productJsonLd(product: Product, url: string) {
4666
5288
 
4667
5289
  // Client-side form
4668
5290
  'use client';
4669
- import { useState } from 'react';
5291
+ import { useEffect, useState } from 'react';
5292
+
5293
+ type Stage =
5294
+ | { kind: 'loading' }
5295
+ | { kind: 'signed_out' }
5296
+ | { kind: 'not_eligible'; reason: MyProductReview['reason'] }
5297
+ | { kind: 'submit' }
5298
+ | { kind: 'edit'; review: ProductReview };
4670
5299
 
4671
5300
  function ReviewForm({ productId }: { productId: string }) {
5301
+ const [stage, setStage] = useState<Stage>({ kind: 'loading' });
4672
5302
  const [rating, setRating] = useState(5);
4673
5303
  const [body, setBody] = useState('');
4674
- const [name, setName] = useState('');
4675
- const [email, setEmail] = useState('');
4676
5304
  const [error, setError] = useState<string | null>(null);
4677
5305
 
5306
+ useEffect(() => {
5307
+ (async () => {
5308
+ const auth = await checkAuthStatus();
5309
+ if (!auth.isLoggedIn) return setStage({ kind: 'signed_out' });
5310
+ const me = await getClient().getMyProductReview(productId);
5311
+ if (!me.eligible) return setStage({ kind: 'not_eligible', reason: me.reason });
5312
+ if (me.myReview) {
5313
+ setRating(me.myReview.rating);
5314
+ setBody(me.myReview.body ?? '');
5315
+ return setStage({ kind: 'edit', review: me.myReview });
5316
+ }
5317
+ setStage({ kind: 'submit' });
5318
+ })();
5319
+ }, [productId]);
5320
+
5321
+ if (stage.kind === 'loading') return <p>Loading\u2026</p>;
5322
+ if (stage.kind === 'signed_out')
5323
+ return <p><a href="/account/login">Sign in</a> to leave a review.</p>;
5324
+ if (stage.kind === 'not_eligible')
5325
+ return <p>Only customers who purchased this product can leave a review.</p>;
5326
+
4678
5327
  async function submit(e: React.FormEvent) {
4679
5328
  e.preventDefault();
4680
5329
  setError(null);
5330
+ const client = getClient();
5331
+ const input = { rating, body: body || undefined };
4681
5332
  try {
4682
- await client.submitProductReview(productId, {
4683
- authorName: name,
4684
- authorEmail: email,
4685
- rating,
4686
- body: body || undefined,
4687
- });
5333
+ if (stage.kind === 'edit') {
5334
+ await client.updateMyProductReview(productId, input);
5335
+ } else {
5336
+ await client.submitProductReview(productId, input);
5337
+ }
4688
5338
  window.location.reload();
4689
5339
  } catch (err: any) {
4690
- if (err?.status === 409) setError("You've already reviewed this product.");
5340
+ if (err?.status === 403) setError('Only customers who purchased this product can leave a review.');
5341
+ else if (err?.status === 409) setError('You already reviewed this product.');
4691
5342
  else if (err?.status === 429) setError('Too many submissions. Please wait a moment.');
4692
- else setError('Could not submit review. Please try again.');
5343
+ else setError('Could not save your review. Please try again.');
4693
5344
  }
4694
5345
  }
4695
5346
 
5347
+ async function remove() {
5348
+ if (!confirm('Delete your review?')) return;
5349
+ await getClient().deleteMyProductReview(productId);
5350
+ window.location.reload();
5351
+ }
5352
+
4696
5353
  return (
4697
5354
  <form onSubmit={submit}>
4698
- <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Your name" required maxLength={100} />
4699
- <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" />
4700
- <select value={rating} onChange={(e) => setRating(Number(e.target.value))}>
4701
- {[5,4,3,2,1].map(n => <option key={n} value={n}>{'\u2605'.repeat(n)}</option>)}
4702
- </select>
4703
- <textarea value={body} onChange={(e) => setBody(e.target.value)} maxLength={5000} placeholder="Tell us what you think (optional)" />
4704
- <button type="submit">Submit review</button>
5355
+ <h3>{stage.kind === 'edit' ? 'Edit your review' : 'Write a review'}</h3>
5356
+ <div>
5357
+ {[1,2,3,4,5].map(n => (
5358
+ <button type="button" key={n} onClick={() => setRating(n)}>
5359
+ {n <= rating ? '\u2605' : '\u2606'}
5360
+ </button>
5361
+ ))}
5362
+ </div>
5363
+ <textarea value={body} onChange={(e) => setBody(e.target.value)} maxLength={5000} />
5364
+ <button type="submit">{stage.kind === 'edit' ? 'Save changes' : 'Submit review'}</button>
5365
+ {stage.kind === 'edit' && (
5366
+ <button type="button" onClick={remove}>Delete review</button>
5367
+ )}
4705
5368
  {error && <p role="alert">{error}</p>}
4706
5369
  </form>
4707
5370
  );
@@ -5191,7 +5854,7 @@ var RULES = {
5191
5854
  body: `- NEVER hardcode currency, locale, or language strings. Read them from \`get-store-info\` / \`get-store-capabilities\` and use the configured values.
5192
5855
  - NEVER format prices with \`toFixed(2)\` or custom logic. Use \`formatPrice()\` from the SDK \u2014 it honors the store's currency and locale.
5193
5856
  - When the store has i18n enabled (\`capabilities.store.i18n.enabled === true\`), you MUST call \`client.setLocale(locale)\` at app init and include a language switcher. All SDK reads will then return localized content automatically.
5194
- - For RTL locales (\`he\`, \`ar\`), set the document direction to RTL. Do not manually reverse flex layouts \u2014 the platform's CSS reversal handles it.`
5857
+ - For RTL direction, do NOT maintain a local list of RTL locales. Call \`client.getStoreDirection(locale)\` \u2014 it returns \`'ltr' | 'rtl'\` for any BCP-47 tag (covers Arabic, Hebrew, Persian, Urdu, Yiddish, and any future RTL locales the platform adds). Set \`<html dir={...}>\` from this value. The platform's CSS reversal handles flex layouts \u2014 do not manually swap them.`
5195
5858
  },
5196
5859
  types: {
5197
5860
  title: "Type safety",
@@ -5239,6 +5902,7 @@ var GET_BUSINESS_FLOWS_SCHEMA = {
5239
5902
  "cart-persistence",
5240
5903
  "inventory-reservation",
5241
5904
  "product-customization",
5905
+ "content-bootstrap",
5242
5906
  "all"
5243
5907
  ]).describe('Which flow to retrieve. Use "all" to get every flow.')
5244
5908
  };
@@ -5429,6 +6093,76 @@ Server-side guardrails that WILL reject bad requests (so validate client-side to
5429
6093
  - More than 10 uploads per IP per minute \u2192 429.
5430
6094
 
5431
6095
  Never render customization fields without also wiring the upload + metadata flow \u2014 a form that submits nothing is worse than no form at all.`
6096
+ },
6097
+ "content-bootstrap": {
6098
+ title: "Content Bootstrap \u2014 site chrome & static content",
6099
+ body: `Every Brainerce storefront should render merchant-defined site chrome (header, footer, announcements, FAQ, static pages) from the Content API. The merchant edits these in the Brainerce dashboard; storefronts pick up changes within ~5 minutes (public reads carry \`Cache-Control: public, max-age=300, stale-while-revalidate=60\`).
6100
+
6101
+ 1. **Fetch chrome at the root layout** (server component if Next.js). All three return \`null\` on 404 \u2014 render hard-coded fallbacks so the page never crashes when the merchant hasn't seeded yet.
6102
+ \`\`\`ts
6103
+ const [header, footer, announcements] = await Promise.all([
6104
+ client.content.header.get('main', locale),
6105
+ client.content.footer.get('main', locale),
6106
+ client.content.announcement.list(locale),
6107
+ ]);
6108
+ \`\`\`
6109
+
6110
+ 2. **FAQ \u2014 fetch lazily on the FAQ page.** Default key is \`'main'\`; pass a topical key (\`'shipping'\`, \`'returns'\`) for sub-FAQs.
6111
+ \`\`\`ts
6112
+ const faq = await client.content.faq.get('main', locale);
6113
+ if (faq) {
6114
+ faq.data.items.forEach(({ question, answer }) => {
6115
+ // sanitize(answer) \u2014 see step 4
6116
+ });
6117
+ }
6118
+ \`\`\`
6119
+
6120
+ 3. **Static pages \u2014 catch-all route by slug:**
6121
+ \`\`\`tsx
6122
+ // app/[slug]/page.tsx
6123
+ export default async function Page({ params }) {
6124
+ const page = await client.content.page.getBySlug(params.slug, locale);
6125
+ if (!page) notFound();
6126
+ return (
6127
+ <article dangerouslySetInnerHTML={{ __html: sanitize(page.data.html) }} />
6128
+ );
6129
+ }
6130
+ \`\`\`
6131
+
6132
+ 4. **SECURITY \u2014 sanitize HTML before rendering.** \`FAQ.items[i].answer\`, \`PAGE.html\`, and \`RICH_TEXT.html\` are merchant-authored HTML. The server does NOT pre-sanitize because some merchants embed iframes (e.g. YouTube). Always sanitize at the edge of your render:
6133
+ \`\`\`ts
6134
+ import DOMPurify from 'isomorphic-dompurify';
6135
+ const safe = DOMPurify.sanitize(rawHtml);
6136
+ <div dangerouslySetInnerHTML={{ __html: safe }} />;
6137
+ \`\`\`
6138
+ Skipping this is XSS.
6139
+
6140
+ 5. **Announcements \u2014 multiple may be active; filter by date client-side:**
6141
+ \`\`\`ts
6142
+ const now = Date.now();
6143
+ const visible = announcements.filter((a) => {
6144
+ const startOk = !a.data.startsAt || new Date(a.data.startsAt).getTime() <= now;
6145
+ const endOk = !a.data.endsAt || new Date(a.data.endsAt).getTime() >= now;
6146
+ return startOk && endOk;
6147
+ });
6148
+ \`\`\`
6149
+
6150
+ 6. **RTL direction \u2014 call \`client.getStoreDirection(locale)\`:**
6151
+ \`\`\`tsx
6152
+ const dir = client.getStoreDirection(locale);
6153
+ <html lang={locale} dir={dir}>...</html>
6154
+ \`\`\`
6155
+ Do NOT maintain a local RTL locale set \u2014 the SDK helper covers Arabic / Hebrew / Persian / Urdu / Yiddish today and picks up any future RTL locale automatically.
6156
+
6157
+ 7. **Custom fields \u2014 every Content row has free-form \`customFields: Record<string, string>\`.** Read keys the merchant told you to expect:
6158
+ \`\`\`ts
6159
+ const faq = await client.content.faq.get('shipping');
6160
+ <a href={\`mailto:\${faq.customFields.helpEmail}\`}>Need help?</a>
6161
+ \`\`\`
6162
+
6163
+ 8. **Cache:** public reads carry \`Cache-Control: public, max-age=300, stale-while-revalidate=60\`. Don't add extra client-side caching beyond Next.js's default fetch cache \u2014 merchants expect their edits to appear within ~5 minutes.
6164
+
6165
+ **Translations.** All public reads accept a \`locale\` argument; the server resolves \`translations[locale]\` server-side. Empty / missing overlays fall through to the default-locale value. The storefront does NOT need to do its own per-field overlay \u2014 call with the active locale and render what comes back.`
5432
6166
  }
5433
6167
  };
5434
6168
  var FLOW_ORDER = [
@@ -5440,7 +6174,8 @@ var FLOW_ORDER = [
5440
6174
  "order-confirmation",
5441
6175
  "cart-persistence",
5442
6176
  "inventory-reservation",
5443
- "product-customization"
6177
+ "product-customization",
6178
+ "content-bootstrap"
5444
6179
  ];
5445
6180
  async function handleGetBusinessFlows(args) {
5446
6181
  const header = "# Brainerce Business Flows\n\nThese sequences are framework-neutral and non-negotiable. Your framework and file layout are your choice \u2014 the order of SDK calls and the error handling is not.";
@@ -5509,9 +6244,9 @@ var FEATURES = [
5509
6244
  },
5510
6245
  {
5511
6246
  id: "product-reviews",
5512
- title: "Display + collect product reviews with stars + JSON-LD",
5513
- description: 'On the PDP show a Reviews section: list of customer reviews with star rating, author name, verified-purchase badge, body, and date. Include a submit form (name + email + 1-5 stars + optional body). On PLP cards show \u2605 avgRating and (reviewCount). Emit Product JSON-LD with aggregateRating ONLY when product.reviewCount > 0 \u2014 this is what unlocks the star rich snippet in Google. Reviews publish immediately; the merchant moderates from the admin surface. Rate-limited to 3 submits / 60s / IP. Show a friendly "you already reviewed this" message on 409.',
5514
- sdk: "client.listProductReviews(productId), client.submitProductReview(productId, { authorName, authorEmail, rating, body }). Product.avgRating + Product.reviewCount are denormalized rollups returned on every product fetch.",
6247
+ title: "Display + collect product reviews (purchaser-only) with stars + JSON-LD",
6248
+ description: 'On the PDP show a Reviews section: list of customer reviews with star rating, author name (from customer profile), verified-purchase badge, body, and date \u2014 public, no login needed. Below the list, a form that adapts to the current customer: signed-in + purchased + no review yet \u2192 submit form (rating 1-5 + optional body, no name/email \u2014 those are derived from the customer profile); signed-in + purchased + already has review \u2192 edit form prefilled with rating/body plus a delete button; signed-in but did NOT purchase \u2192 "only customers who purchased this product can leave a review"; not signed in \u2192 sign-in CTA. Eligibility: physical products require an order in SHIPPED+; downloadable products additionally accept PAID/PROCESSING. On PLP cards show \u2605 avgRating and (reviewCount). Emit Product JSON-LD with aggregateRating ONLY when product.reviewCount > 0 \u2014 this is what unlocks the star rich snippet in Google. Reviews publish immediately; merchants moderate (hide/show) from the admin surface. Rate-limited 3 submits / 60s / IP.',
6249
+ sdk: "client.listProductReviews(productId) for the public list; client.getMyProductReview(productId) for the form-state decision; client.submitProductReview / updateMyProductReview / deleteMyProductReview for the three customer actions. All four customer methods require setCustomerToken(...) after login. Product.avgRating + Product.reviewCount are denormalized rollups returned on every product fetch.",
5515
6250
  mandatory: "mandatory"
5516
6251
  },
5517
6252
  {
@@ -5652,11 +6387,57 @@ var FEATURES = [
5652
6387
  {
5653
6388
  id: "i18n",
5654
6389
  title: "Serve multiple languages with a language switcher",
5655
- description: "When i18n is enabled, the experience routes by locale, sets the SDK locale (client.setLocale), includes a language switcher in the header, and renders RTL locales (he, ar) with the correct document direction.",
5656
- sdk: "client.setLocale(locale). Read supported locales from get-store-capabilities.store.i18n.",
6390
+ description: "When i18n is enabled, the experience routes by locale, sets the SDK locale (client.setLocale), includes a language switcher in the header, and renders the correct document direction by reading client.getStoreDirection(locale) \u2014 do not hardcode an RTL locale set.",
6391
+ sdk: "client.setLocale(locale). client.getStoreDirection(locale) for <html dir>. Read supported locales from get-store-capabilities.store.i18n.",
5657
6392
  mandatory: "conditional",
5658
6393
  capabilityFlag: "i18n",
5659
6394
  whenDisabledNote: "This store is single-language. Do not build the language switcher."
6395
+ },
6396
+ {
6397
+ id: "site-header",
6398
+ title: "Site header from merchant content (logo + nav + CTA)",
6399
+ description: 'Fetch client.content.header.get("main", locale) in the root layout. Returns null when the merchant has not seeded yet \u2014 render a hard-coded fallback so the page never crashes. Renders header.data.logo, header.data.navItems[], header.data.cta if present.',
6400
+ sdk: 'client.content.header.get("main", locale)',
6401
+ flowRef: "content-bootstrap",
6402
+ mandatory: "mandatory"
6403
+ },
6404
+ {
6405
+ id: "site-footer",
6406
+ title: "Site footer from merchant content (columns + social + copyright)",
6407
+ description: 'Fetch client.content.footer.get("main", locale) in the root layout. Returns null when unseeded \u2014 render a hard-coded fallback. Render footer.data.columns[].links, footer.data.social[], footer.data.copyright.',
6408
+ sdk: 'client.content.footer.get("main", locale)',
6409
+ flowRef: "content-bootstrap",
6410
+ mandatory: "mandatory"
6411
+ },
6412
+ {
6413
+ id: "announcement-bar",
6414
+ title: "Announcement bar at the top of every page",
6415
+ description: "Fetch client.content.announcement.list(locale) in the root layout. Filter by data.startsAt / data.endsAt client-side. Render a dismissible bar when data.dismissible=true. Build the UI anyway \u2014 it auto-hides when no announcements exist.",
6416
+ sdk: "client.content.announcement.list(locale)",
6417
+ flowRef: "content-bootstrap",
6418
+ mandatory: "conditional",
6419
+ capabilityFlag: "hasContent",
6420
+ whenDisabledNote: "Store has no published Content rows yet. Build the announcement bar anyway \u2014 it auto-hides on empty."
6421
+ },
6422
+ {
6423
+ id: "faq-page",
6424
+ title: "FAQ page rendered from merchant content",
6425
+ description: 'Build /faq as an accordion fed by client.content.faq.get("main", locale). For topical FAQs, use a key parameter (shipping, returns, ...). Always sanitize answer HTML before injecting via dangerouslySetInnerHTML. Build the page anyway \u2014 it auto-hides or 404s when no FAQ rows exist.',
6426
+ sdk: 'client.content.faq.get("main", locale), client.content.faq.list(locale)',
6427
+ flowRef: "content-bootstrap",
6428
+ mandatory: "conditional",
6429
+ capabilityFlag: "hasContent",
6430
+ whenDisabledNote: "No FAQ content yet. Build /faq anyway \u2014 it auto-hides on empty."
6431
+ },
6432
+ {
6433
+ id: "static-pages",
6434
+ title: "Static pages from merchant content (About, Terms, Privacy, \u2026)",
6435
+ description: "Mount a catch-all app/[slug]/page.tsx route. Inside, call client.content.page.getBySlug(params.slug, locale). On null \u2192 notFound(). On hit, sanitize page.data.html before injecting via dangerouslySetInnerHTML. Generate <Metadata> from page.data.seo. Build the route anyway \u2014 it 404s on unknown slugs.",
6436
+ sdk: "client.content.page.getBySlug(slug, locale), client.content.page.list(locale)",
6437
+ flowRef: "content-bootstrap",
6438
+ mandatory: "conditional",
6439
+ capabilityFlag: "hasContent",
6440
+ whenDisabledNote: "No static pages yet. Build the catch-all route anyway \u2014 it 404s on unknown slugs."
5660
6441
  }
5661
6442
  ];
5662
6443
  function isFeatureActive(feature, caps) {
@@ -5707,6 +6488,7 @@ function renderCapabilitiesSummary(caps) {
5707
6488
  );
5708
6489
  lines.push(`- Downloadable products: ${caps.features.hasDownloadableProducts ? "yes" : "no"}`);
5709
6490
  lines.push(`- Checkout custom fields: ${caps.features.hasCheckoutCustomFields ? "yes" : "no"}`);
6491
+ lines.push(`- Content (FAQ/footer/header/announcements/pages): ${caps.features.hasContent ? "seeded" : "none \u2014 build chrome UI with fallbacks"}`);
5710
6492
  lines.push(
5711
6493
  `- Email verification: ${caps.connection.requireEmailVerification ? "required" : "not required (still build the verify-email flow)"}`
5712
6494
  );