@brainerce/mcp-server 3.1.0 → 3.4.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 +910 -56
- package/dist/bin/stdio.js +910 -56
- package/dist/index.js +910 -56
- package/dist/index.mjs +910 -56
- package/package.json +1 -1
package/dist/bin/stdio.js
CHANGED
|
@@ -65,7 +65,7 @@ function getTypeQuickReference() {
|
|
|
65
65
|
| OAuth | \`provider.name\` | \`provider\` | it IS the string: \`'GOOGLE' | 'FACEBOOK' | 'GITHUB'\` |
|
|
66
66
|
| OAuth | \`oauth.url\` | \`oauth.authorizationUrl\` | |
|
|
67
67
|
| Description | \`getDescriptionContent()\` | \`{ html } | { text } | null\` | check \`'html' in content\` before use |
|
|
68
|
-
| \`smartGetCart()\` |
|
|
68
|
+
| \`smartGetCart()\` | N/A | \`cart.id\` | returns \`CartWithIncludes\` (extends \`Cart\`); pass \`{ include: [...] }\` for extras |
|
|
69
69
|
| \`startGuestCheckout()\` | always use \`.checkoutId\` | check \`result.tracked\` | discriminated union |
|
|
70
70
|
|
|
71
71
|
**Rules:**
|
|
@@ -73,8 +73,8 @@ function getTypeQuickReference() {
|
|
|
73
73
|
- CartItem/CheckoutLineItem = **NESTED** (\`item.product.name\`, \`item.unitPrice\`)
|
|
74
74
|
- OrderItem = **FLAT** (\`item.name\`, \`item.price\`, \`item.totalPrice\`, \`item.image\`)
|
|
75
75
|
- Cart has NO \`.total\` \u2014 use \`getCartTotals(cart)\`
|
|
76
|
-
- \`getCartTotals()\`
|
|
77
|
-
- \`smartGetCart()\` returns \`
|
|
76
|
+
- \`getCartTotals()\` works with server \`Cart\` (all carts are server-side now)
|
|
77
|
+
- \`smartGetCart()\` returns \`CartWithIncludes\` \u2014 always a server cart; pass \`{ include: ['recommendations', 'upgrades', 'bundles'] }\` for extras
|
|
78
78
|
- \`startGuestCheckout()\` returns discriminated union \u2014 check \`result.tracked\` before \`.checkoutId\`
|
|
79
79
|
- \`SetShippingAddressDto.email\` is **required** \u2014 always include email
|
|
80
80
|
|
|
@@ -202,7 +202,7 @@ async function startCheckout() {
|
|
|
202
202
|
6. Select shipping method \u2192 \`selectShippingMethod()\`
|
|
203
203
|
6b. (Optional) Set checkout custom fields \u2192 \`setCheckoutCustomFields()\` \u2014 surcharges auto-calculated
|
|
204
204
|
7. Create payment intent \u2192 \`createPaymentIntent()\` \u2192 returns \`{ clientSecret, provider }\`
|
|
205
|
-
8. Branch on \`provider
|
|
205
|
+
8. Branch on the **\`clientSdk.renderType\`** returned by \`createPaymentIntent()\` \u2014 NEVER hard-code by provider name. Values: \`'sdk-widget'\` (Stripe, PayPal, Grow), \`'iframe'\` (Cardcom hosted or Brainerce-hosted embed \u2014 detect via URL path), \`'redirect'\`, \`'sandbox'\`, \`'embedded-fields'\` (reserved).
|
|
206
206
|
9. **Order is created AUTOMATICALLY after payment succeeds (via webhook) \u2014 for ALL providers!**
|
|
207
207
|
|
|
208
208
|
### Checkout Page Component
|
|
@@ -305,8 +305,8 @@ function CheckoutPage() {
|
|
|
305
305
|
</div>
|
|
306
306
|
);
|
|
307
307
|
}
|
|
308
|
-
if (paymentData.
|
|
309
|
-
return <
|
|
308
|
+
if (paymentData.clientSdk?.renderType === 'iframe') {
|
|
309
|
+
return <PaymentIframe clientSecret={paymentData.clientSecret} checkoutId={paymentData.checkoutId} />;
|
|
310
310
|
}
|
|
311
311
|
if (paymentData.provider === 'paypal' && paypalClientId) {
|
|
312
312
|
return <PayPalPaymentForm clientId={paypalClientId} orderId={paymentData.clientSecret} checkoutId={paymentData.checkoutId} />;
|
|
@@ -362,26 +362,82 @@ function StripePaymentForm({ checkoutId }: { checkoutId: string }) {
|
|
|
362
362
|
}
|
|
363
363
|
\`\`\`
|
|
364
364
|
|
|
365
|
-
###
|
|
365
|
+
### Iframe-Based Providers (Cardcom, legacy Grow, etc.)
|
|
366
|
+
|
|
367
|
+
When \`clientSdk.renderType === 'iframe'\`, the payment intent returns a \`clientSecret\` which is a URL to load in an iframe. There are TWO flavors of iframe rendering you must handle:
|
|
368
|
+
|
|
369
|
+
**Flavor A \u2014 Brainerce-hosted embed (URL path contains \`/embed/\`):** The iframe loads a Brainerce-branded compact form (e.g. Cardcom OpenFields). Render it **INLINE** inside your checkout flow (next to the order summary) \u2014 NO modal, NO dark overlay. The embed page posts messages to resize itself and to request top-level navigation (e.g. for Bit express-pay buttons).
|
|
370
|
+
|
|
371
|
+
**Flavor B \u2014 Provider-hosted page (any other URL):** The iframe loads a full provider-branded page with its own header/chrome. Render inside a **modal overlay** so it doesn't fight your checkout layout.
|
|
372
|
+
|
|
373
|
+
Detect flavor by URL path \u2014 works across localhost/staging/prod without a domain list:
|
|
366
374
|
|
|
367
375
|
\`\`\`typescript
|
|
368
|
-
function
|
|
369
|
-
const [
|
|
376
|
+
function PaymentIframe({ clientSecret, checkoutId }: { clientSecret: string; checkoutId: string }) {
|
|
377
|
+
const [height, setHeight] = useState(540); // default before resize message arrives
|
|
378
|
+
const isBrainerceEmbed = (() => {
|
|
379
|
+
try { return new URL(clientSecret).pathname.includes('/embed/'); }
|
|
380
|
+
catch { return false; }
|
|
381
|
+
})();
|
|
382
|
+
|
|
383
|
+
useEffect(() => {
|
|
384
|
+
function handleMessage(e: MessageEvent) {
|
|
385
|
+
const data = e.data as { type?: string; height?: number; url?: string };
|
|
386
|
+
if (data?.type === 'brainerce:resize' && typeof data.height === 'number') {
|
|
387
|
+
setHeight(data.height);
|
|
388
|
+
}
|
|
389
|
+
if (data?.type === 'brainerce:redirect' && typeof data.url === 'string') {
|
|
390
|
+
// Top-level navigation (e.g. Bit). ALWAYS validate against an allowlist
|
|
391
|
+
// before navigating \u2014 never trust the URL blindly.
|
|
392
|
+
if (isTrustedPaymentUrl(data.url)) { window.top!.location.href = data.url; }
|
|
393
|
+
}
|
|
394
|
+
if (data?.type === 'brainerce:payment-complete') {
|
|
395
|
+
// Payment done \u2014 redirect to confirmation page which verifies server-side
|
|
396
|
+
window.location.href = \`/order-confirmation?checkout_id=\${checkoutId}\`;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
window.addEventListener('message', handleMessage);
|
|
400
|
+
return () => window.removeEventListener('message', handleMessage);
|
|
401
|
+
}, [checkoutId]);
|
|
402
|
+
|
|
403
|
+
if (isBrainerceEmbed) {
|
|
404
|
+
// Inline: part of the checkout flow, no overlay
|
|
405
|
+
return (
|
|
406
|
+
<div className="w-full">
|
|
407
|
+
<iframe
|
|
408
|
+
src={clientSecret}
|
|
409
|
+
style={{ width: '100%', height, border: 0, transition: 'height 0.2s ease-out' }}
|
|
410
|
+
title="Payment"
|
|
411
|
+
allow="payment"
|
|
412
|
+
/>
|
|
413
|
+
</div>
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// Provider-hosted page: modal overlay
|
|
370
418
|
return (
|
|
371
|
-
<div className="
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
Having trouble? <a href={paymentUrl} target="_blank" rel="noopener noreferrer" className="text-blue-600 underline">Open payment in new tab</a>
|
|
381
|
-
</p>
|
|
419
|
+
<div className="fixed inset-0 z-50 flex items-start justify-center bg-black/50 py-6 overflow-y-auto">
|
|
420
|
+
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl mx-4">
|
|
421
|
+
<iframe
|
|
422
|
+
src={clientSecret}
|
|
423
|
+
style={{ width: '100%', height: '90vh', minHeight: 700, border: 0 }}
|
|
424
|
+
title="Payment"
|
|
425
|
+
allow="payment"
|
|
426
|
+
/>
|
|
427
|
+
</div>
|
|
382
428
|
</div>
|
|
383
429
|
);
|
|
384
430
|
}
|
|
431
|
+
|
|
432
|
+
// Allowlist of origins you trust for top-level payment redirects.
|
|
433
|
+
function isTrustedPaymentUrl(url: string): boolean {
|
|
434
|
+
try {
|
|
435
|
+
const u = new URL(url);
|
|
436
|
+
if (u.protocol !== 'https:') return false;
|
|
437
|
+
// Add your provider hostnames here. Example: Cardcom for Bit express-pay.
|
|
438
|
+
return u.hostname === 'cardcom.solutions' || u.hostname.endsWith('.cardcom.solutions');
|
|
439
|
+
} catch { return false; }
|
|
440
|
+
}
|
|
385
441
|
\`\`\`
|
|
386
442
|
|
|
387
443
|
### PayPal Payment Form
|
|
@@ -651,12 +707,23 @@ const growProvider = providers.find(p => p.provider === 'grow');
|
|
|
651
707
|
const paypalProvider = providers.find(p => p.provider === 'paypal');
|
|
652
708
|
\`\`\`
|
|
653
709
|
|
|
654
|
-
Each provider has: \`id\`, \`provider\` ('stripe'
|
|
710
|
+
Each provider has: \`id\`, \`provider\` (flexible string \u2014 \`'stripe'\`, \`'grow'\`, \`'paypal'\`, \`'cardcom'\`, \`'sandbox'\`, and future providers), \`name\`, \`publicKey\`, \`stripeAccountId\` (Stripe only), \`supportedMethods\`, \`testMode\`, \`isDefault\`.
|
|
711
|
+
|
|
712
|
+
The payment intent returned from \`createPaymentIntent()\` includes a \`clientSdk\` object whose \`renderType\` tells you exactly how to render \u2014 **branch on THAT, not on the provider name**:
|
|
655
713
|
|
|
714
|
+
- \`renderType: 'sdk-widget'\` \u2014 load \`clientSdk.scriptUrl\`, mount into \`<div id={clientSdk.containerId}>\`. Used by Stripe, PayPal, Grow. The SDK paints its own form in your DOM.
|
|
715
|
+
- \`renderType: 'iframe'\` \u2014 render \`<iframe src={clientSecret}>\`. Two flavors detected by URL path:
|
|
716
|
+
- Path contains \`/embed/\` \u2192 Brainerce-hosted embed. Render **INLINE** (no modal). Listen for \`brainerce:resize\` / \`brainerce:redirect\` postMessages. Used by Cardcom (embedded mode).
|
|
717
|
+
- Any other URL \u2192 provider-hosted page. Render inside a **modal**. Used by Cardcom (hosted mode), legacy Grow iframe.
|
|
718
|
+
- \`renderType: 'redirect'\` \u2014 \`window.location.href = URL\`. Customer completes payment off-site and returns via SuccessRedirectUrl.
|
|
719
|
+
- \`renderType: 'sandbox'\` \u2014 show a "Complete Test Order" button; call \`completeGuestCheckout(checkoutId)\`. Orders are \`isTestOrder: true\`. Appears when \`sandboxPaymentsEnabled\` is true.
|
|
720
|
+
- \`renderType: 'embedded-fields'\` \u2014 reserved for future Stripe-Elements-style pattern (PCI micro-iframes for card/CVV mounted directly into the merchant form). **No provider ships this today** \u2014 handle via a "not supported yet" fallback.
|
|
721
|
+
|
|
722
|
+
Provider-specific install notes:
|
|
656
723
|
- **Stripe:** \`npm install @stripe/stripe-js @stripe/react-stripe-js\` \u2014 \`loadStripe(publicKey, { stripeAccount })\`
|
|
657
|
-
- **Grow:** No SDK \u2014 uses iframe with payment URL. Supports credit cards, Bit, Apple Pay, Google Pay.
|
|
658
724
|
- **PayPal:** \`npm install @paypal/react-paypal-js\` \u2014 \`PayPalScriptProvider\` + \`PayPalButtons\`
|
|
659
|
-
- **
|
|
725
|
+
- **Grow:** No SDK needed \u2014 JS SDK loaded via \`clientSdk.scriptUrl\`. Supports credit cards, Bit, Apple Pay, Google Pay.
|
|
726
|
+
- **Cardcom:** No SDK needed \u2014 rendering driven by \`renderType: 'iframe'\` + the inline/modal branch above. Supports credit cards, Bit (when terminal provisions it), installments, 3D Secure.`;
|
|
660
727
|
}
|
|
661
728
|
function getProductsSection(_currency) {
|
|
662
729
|
return `## Products & Variants
|
|
@@ -687,10 +754,12 @@ When \`storeInfo.i18n.enabled\` is true, call \`client.setLocale(locale)\` once
|
|
|
687
754
|
\`{ locale }\` params needed. Translated fields include: \`name\`,
|
|
688
755
|
\`description\`, \`slug\`, \`seoTitle\`, \`seoDescription\`, plus
|
|
689
756
|
\`categories[].name\`, \`brands[].name\`, \`tags[].name\`, \`variants[].name\`,
|
|
690
|
-
\`
|
|
691
|
-
\`
|
|
692
|
-
|
|
693
|
-
and
|
|
757
|
+
\`variant.attributes\` keys and values (so \`getVariantOptions()\` returns
|
|
758
|
+
translated attribute/option names), \`productAttributeOptions[].attribute.name\`/
|
|
759
|
+
\`attributeOption.name\`, \`metafields[].value\`, cart item product/variant names,
|
|
760
|
+
and recommendation/bundle/bump product names. No client-side overlay. See the
|
|
761
|
+
full \`i18n\` section (\`get-sdk-docs\` topic \`i18n\`) for the \`[locale]\` route
|
|
762
|
+
pattern, SDK setup, and the brand/tag badge examples.
|
|
694
763
|
|
|
695
764
|
### Price Display (Use SDK Helper!)
|
|
696
765
|
|
|
@@ -827,6 +896,8 @@ const material = getProductMetafieldValue(product, 'material');
|
|
|
827
896
|
|
|
828
897
|
Some products allow customers to provide input at purchase time (e.g., text on a cake, upload a logo). Check \`product.customizationFields\` and render input fields accordingly.
|
|
829
898
|
|
|
899
|
+
Merchants can also flag a \`MetafieldDefinition\` as \`appliesToAllProducts: true\` \u2014 those fields are folded into every product's \`customizationFields\` array automatically by the backend. Client code does not need to merge or union anything: always render exactly what's in \`product.customizationFields\`.
|
|
900
|
+
|
|
830
901
|
\`\`\`typescript
|
|
831
902
|
import { getProductCustomizationFields } from 'brainerce';
|
|
832
903
|
import type { ProductCustomizationField } from 'brainerce';
|
|
@@ -885,7 +956,7 @@ function getCartSection(_currency) {
|
|
|
885
956
|
### Smart Cart Methods (RECOMMENDED)
|
|
886
957
|
|
|
887
958
|
\`\`\`typescript
|
|
888
|
-
const cart = await client.smartGetCart(); // Returns
|
|
959
|
+
const cart = await client.smartGetCart(); // Returns CartWithIncludes (extends Cart)
|
|
889
960
|
await client.smartAddToCart({
|
|
890
961
|
productId: product.id,
|
|
891
962
|
variantId: selectedVariant?.id,
|
|
@@ -1016,7 +1087,19 @@ const recs = (product as any).recommendations as ProductRecommendationsResponse
|
|
|
1016
1087
|
|
|
1017
1088
|
### Cart Page Features
|
|
1018
1089
|
|
|
1019
|
-
**
|
|
1090
|
+
**Consolidated include** (fetch recommendations, upgrades, and bundles in one request):
|
|
1091
|
+
\`\`\`typescript
|
|
1092
|
+
import type { CartWithIncludes } from 'brainerce';
|
|
1093
|
+
const cart = await client.getCart(cartId, {
|
|
1094
|
+
include: ['recommendations', 'upgrades', 'bundles'],
|
|
1095
|
+
});
|
|
1096
|
+
// cart.recommendations \u2014 cross-sell recommendations
|
|
1097
|
+
// cart.upgrades \u2014 upgrade suggestions keyed by source product ID
|
|
1098
|
+
// cart.bundles \u2014 bundle offers
|
|
1099
|
+
// Also works with smartGetCart: client.smartGetCart({ include: ['recommendations', 'upgrades', 'bundles'] })
|
|
1100
|
+
\`\`\`
|
|
1101
|
+
|
|
1102
|
+
**Cross-sell recommendations** (or fetch individually for targeted refresh):
|
|
1020
1103
|
\`\`\`typescript
|
|
1021
1104
|
import type { CartRecommendationsResponse } from 'brainerce';
|
|
1022
1105
|
const cartRecs = await client.getCartRecommendations(cartId, 4);
|
|
@@ -1108,6 +1191,110 @@ Always check the flag before rendering: \`if (storeInfo?.upsell?.featureName !==
|
|
|
1108
1191
|
ProductRecommendation: \`id\`, \`name\`, \`slug\`, \`basePrice\`, \`salePrice\`, \`images\`, \`type\`, \`inventory\`, \`relationType\`, \`variants?\` (when variant selection needed).
|
|
1109
1192
|
OrderBump/CartBundleOffer: includes \`requiresVariantSelection\` (boolean) and \`lockedVariant?\` (\`{ id, name, attributes }\`).`;
|
|
1110
1193
|
}
|
|
1194
|
+
function getProductCustomizationFieldsSection() {
|
|
1195
|
+
return `## Product Customization Fields (buyer input on product page)
|
|
1196
|
+
|
|
1197
|
+
Some products let the buyer personalize them before adding to cart \u2014 engraving text, a photo upload, a color pick, a multi-select add-on list. The merchant defines these fields in the Brainerce dashboard; the storefront renders them, collects values, uploads any images, and passes everything as \`metadata\` on add-to-cart.
|
|
1198
|
+
|
|
1199
|
+
### Where the fields come from
|
|
1200
|
+
|
|
1201
|
+
They arrive **embedded on the product response** \u2014 no extra API call:
|
|
1202
|
+
|
|
1203
|
+
\`\`\`typescript
|
|
1204
|
+
import type { Product, ProductCustomizationField, MetafieldType } from 'brainerce';
|
|
1205
|
+
|
|
1206
|
+
const product = await client.getProductBySlug(slug);
|
|
1207
|
+
const fields: ProductCustomizationField[] = product.customizationFields ?? [];
|
|
1208
|
+
// fields is sorted by position. If empty, render the product page normally.
|
|
1209
|
+
\`\`\`
|
|
1210
|
+
|
|
1211
|
+
Each field has:
|
|
1212
|
+
\`\`\`typescript
|
|
1213
|
+
{
|
|
1214
|
+
definitionId: string;
|
|
1215
|
+
key: string; // stable identifier \u2014 use this as the metadata key
|
|
1216
|
+
name: string; // display label (may be localized)
|
|
1217
|
+
description?: string | null;
|
|
1218
|
+
type: MetafieldType; // 'TEXT' | 'TEXTAREA' | 'NUMBER' | 'BOOLEAN' | 'DATE' | 'DATETIME' |
|
|
1219
|
+
// 'JSON' | 'URL' | 'COLOR' | 'DIMENSION' | 'WEIGHT' |
|
|
1220
|
+
// 'IMAGE' | 'GALLERY' | 'SELECT' | 'MULTI_SELECT'
|
|
1221
|
+
required: boolean;
|
|
1222
|
+
minLength?: number | null; // chars for TEXT/TEXTAREA; array size for MULTI_SELECT
|
|
1223
|
+
maxLength?: number | null;
|
|
1224
|
+
minValue?: number | null; // NUMBER / DIMENSION / WEIGHT
|
|
1225
|
+
maxValue?: number | null;
|
|
1226
|
+
enumValues?: string[]; // required for SELECT / MULTI_SELECT
|
|
1227
|
+
defaultValue?: string | null;
|
|
1228
|
+
position: number;
|
|
1229
|
+
}
|
|
1230
|
+
\`\`\`
|
|
1231
|
+
|
|
1232
|
+
### Render one control per type
|
|
1233
|
+
|
|
1234
|
+
| type | Render as | Collected value |
|
|
1235
|
+
| --------------- | ---------------------------------------------------------- | ---------------------------- |
|
|
1236
|
+
| \`TEXT\` | \`<input type="text">\` | \`string\` |
|
|
1237
|
+
| \`TEXTAREA\` | \`<textarea>\` | \`string\` |
|
|
1238
|
+
| \`NUMBER\` | \`<input type="number">\` | \`number\` |
|
|
1239
|
+
| \`BOOLEAN\` | checkbox / switch | \`boolean\` |
|
|
1240
|
+
| \`DATE\` | \`<input type="date">\` | \`string\` (YYYY-MM-DD) |
|
|
1241
|
+
| \`DATETIME\` | \`<input type="datetime-local">\` | \`string\` (ISO 8601) |
|
|
1242
|
+
| \`URL\` | \`<input type="url">\` | \`string\` |
|
|
1243
|
+
| \`COLOR\` | \`<input type="color">\` | \`string\` (#RRGGBB) |
|
|
1244
|
+
| \`SELECT\` | \`<select>\` or radio group (use \`enumValues\`) | \`string\` (in enumValues) |
|
|
1245
|
+
| \`MULTI_SELECT\`| checkbox group (use \`enumValues\`) | \`string[]\` (every in enum) |
|
|
1246
|
+
| \`IMAGE\` | file input + upload via \`uploadCustomizationFile\` | \`string\` (URL) |
|
|
1247
|
+
| \`GALLERY\` | multi-file input + one upload per file | \`string[]\` (URLs) |
|
|
1248
|
+
| \`JSON\` | textarea; validate is parseable | \`string\` (JSON) |
|
|
1249
|
+
|
|
1250
|
+
### Upload buyer-submitted images
|
|
1251
|
+
|
|
1252
|
+
\`IMAGE\` and \`GALLERY\` require uploading before add-to-cart:
|
|
1253
|
+
|
|
1254
|
+
\`\`\`typescript
|
|
1255
|
+
const { url } = await client.uploadCustomizationFile(file);
|
|
1256
|
+
// Server rules: image/* only, max 5 MB, 10 uploads/min per IP.
|
|
1257
|
+
// Files are retained for at least 7 days; after that, if the cart never
|
|
1258
|
+
// became an order, they are automatically deleted.
|
|
1259
|
+
\`\`\`
|
|
1260
|
+
|
|
1261
|
+
### Add to cart with customization metadata
|
|
1262
|
+
|
|
1263
|
+
\`\`\`typescript
|
|
1264
|
+
// Collect values keyed by field.key \u2014 NOT by field.name or field.definitionId.
|
|
1265
|
+
const metadata: Record<string, unknown> = {
|
|
1266
|
+
engraving_text: 'Happy Birthday!', // TEXT
|
|
1267
|
+
frame_color: 'Gold', // SELECT (must be in enumValues)
|
|
1268
|
+
upload_photo: url, // IMAGE (URL from uploadCustomizationFile)
|
|
1269
|
+
addons: ['Gift wrap'], // MULTI_SELECT (always an array)
|
|
1270
|
+
};
|
|
1271
|
+
|
|
1272
|
+
await client.addToCart(cart.id, {
|
|
1273
|
+
productId: product.id,
|
|
1274
|
+
quantity: 1,
|
|
1275
|
+
metadata,
|
|
1276
|
+
});
|
|
1277
|
+
\`\`\`
|
|
1278
|
+
|
|
1279
|
+
Server validation (rejected with HTTP 400 on failure):
|
|
1280
|
+
- \`required: true\` \u2192 must be present and non-empty
|
|
1281
|
+
- \`TEXT\` / \`TEXTAREA\` \u2192 string; \`minLength\` / \`maxLength\` enforced as character count
|
|
1282
|
+
- \`NUMBER\` \u2192 \`minValue\` / \`maxValue\` enforced
|
|
1283
|
+
- \`SELECT\` \u2192 value must be one of \`enumValues\`
|
|
1284
|
+
- \`MULTI_SELECT\` \u2192 array; each element in \`enumValues\`; duplicates removed; \`minLength\` / \`maxLength\` enforced as array size
|
|
1285
|
+
- \`IMAGE\` / \`GALLERY\` \u2192 URL(s) must be from \`/customization-upload\` on this store
|
|
1286
|
+
|
|
1287
|
+
### Order snapshot
|
|
1288
|
+
|
|
1289
|
+
When the order is created, each line's customization values are snapshotted onto the order item with \`{ key, name, type, value }\` \u2014 so later edits to the field definition don't orphan old orders. The merchant dashboard shows the values on the order detail page.
|
|
1290
|
+
|
|
1291
|
+
### Common mistakes
|
|
1292
|
+
|
|
1293
|
+
- Passing values keyed by \`field.name\` instead of \`field.key\` \u2192 silently ignored (unknown key)
|
|
1294
|
+
- Sending a \`MULTI_SELECT\` as a string instead of \`string[]\` \u2192 HTTP 400
|
|
1295
|
+
- Using a raw external URL (not from \`/customization-upload\`) for \`IMAGE\` / \`GALLERY\` \u2192 HTTP 400
|
|
1296
|
+
- Assuming \`enumValues\` is present for all types \u2014 only \`SELECT\` / \`MULTI_SELECT\` require it`;
|
|
1297
|
+
}
|
|
1111
1298
|
function getInventorySection() {
|
|
1112
1299
|
return `## Inventory, Stock Display & Reservation Countdown
|
|
1113
1300
|
|
|
@@ -1364,7 +1551,50 @@ const { data: orders } = await client.getMyOrders({ page: 1, limit: 10 }); // Re
|
|
|
1364
1551
|
// \u274C WRONG \u2014 these methods don't exist!
|
|
1365
1552
|
client.getCustomerProfile();
|
|
1366
1553
|
client.getCustomerOrders();
|
|
1367
|
-
|
|
1554
|
+
\`\`\`
|
|
1555
|
+
|
|
1556
|
+
### Order history should show more than just totals
|
|
1557
|
+
|
|
1558
|
+
A useful order card includes ALL of the following when the data is present. Each section is conditional \u2014 render nothing if the field is empty.
|
|
1559
|
+
|
|
1560
|
+
| Section | Source field | Notes |
|
|
1561
|
+
|---|---|---|
|
|
1562
|
+
| Header (number, status badge, date, total) | \`order.orderNumber\`, \`order.status\`, \`order.createdAt\`, \`order.totalAmount\` | Always present. |
|
|
1563
|
+
| Line items | \`order.items[]\` | Render image, name, qty, price. |
|
|
1564
|
+
| **Per-item customizations** | \`order.items[i].customizations\` | Map of { label, value, type }. Render by \`type\` \u2014 see table below. |
|
|
1565
|
+
| **Status timeline** | \`order.statusHistory\` | \`OrderStatusChange[]\`: \`{ status, at, note? }\`. Render as a vertical list. |
|
|
1566
|
+
| **Shipping address** | \`order.shippingAddress\` | Standard \`OrderAddress\` shape. |
|
|
1567
|
+
| **Tracking** | \`order.trackingNumber\`, \`order.trackingUrl\`, \`order.carrier\`, \`order.shippedAt\`, \`order.deliveredAt\` | Link out to \`trackingUrl\` when set. |
|
|
1568
|
+
| **Payment** | \`order.paymentMethod\`, \`order.financialStatus\` | Badge \`financialStatus\` (paid / pending / refunded / partially_refunded). |
|
|
1569
|
+
| Downloads | \`order.hasDownloads\` \u2192 \`client.getOrderDownloads(id)\` | Separate call; returns \`OrderDownloadLink[]\`. |
|
|
1570
|
+
| Financial summary | \`order.subtotal\`, \`order.appliedDiscounts\`, \`order.couponCode\` + \`couponDiscount\`, \`order.shippingAmount\`, \`order.taxAmount\`, \`order.totalAmount\` | Breakdown rows + final total. |
|
|
1571
|
+
|
|
1572
|
+
#### Rendering \`order.items[i].customizations\` by type
|
|
1573
|
+
|
|
1574
|
+
The map key is the metafield slug; the value is \`{ label, value, type }\`. Dispatch by \`type\`:
|
|
1575
|
+
|
|
1576
|
+
| Type | Value | Render |
|
|
1577
|
+
|---|---|---|
|
|
1578
|
+
| \`TEXT\`, \`TEXTAREA\`, \`URL\`, \`NUMBER\`, \`SELECT\` | string | Plain text (\`URL\` \u2192 anchor). |
|
|
1579
|
+
| \`BOOLEAN\` | \`"yes"\` / \`"no"\` | \u2713 / \u2717 |
|
|
1580
|
+
| \`MULTI_SELECT\` | \`string[]\` | Comma-separated. |
|
|
1581
|
+
| \`IMAGE\` | asset URL (string) | Thumbnail linking to full-size asset. |
|
|
1582
|
+
| \`GALLERY\` | \`string[]\` of URLs | Grid of thumbnails. |
|
|
1583
|
+
| \`COLOR\` | hex string | Swatch + hex text. |
|
|
1584
|
+
| \`DATE\` | ISO-8601 | \`toLocaleDateString()\` |
|
|
1585
|
+
| \`DATETIME\` | ISO-8601 | \`toLocaleString()\` |
|
|
1586
|
+
| Unknown | any | Plain text (defensive default). |
|
|
1587
|
+
|
|
1588
|
+
The storefront scaffolded by \`create-brainerce-store\` already implements this. See \`src/components/account/order-history.tsx\` + the sibling \`order-customizations.tsx\`, \`order-status-timeline.tsx\`, \`order-shipping-block.tsx\`, \`order-payment-block.tsx\` \u2014 mirror that structure.
|
|
1589
|
+
|
|
1590
|
+
### Do NOT render
|
|
1591
|
+
|
|
1592
|
+
These fields are NOT returned to buyers by \`/customers/me/orders\`. If you see them in older examples, ignore them \u2014 they are for merchant/admin views only.
|
|
1593
|
+
|
|
1594
|
+
- \`order.accountId\`, \`order.storeId\`, \`order.customerId\` (already known on the request)
|
|
1595
|
+
- \`order.notes\` (internal merchant notes)
|
|
1596
|
+
- \`order.customFieldValues\` (order-level checkout fields \u2014 merchant concept; buyers see \`items[i].customizations\`)
|
|
1597
|
+
- \`order.appliedSurcharges\`, \`order.surchargeAmount\`, \`order.appliedRuleIds\`, \`order.downloadMeta\`, \`order.pickupLocationData\``;
|
|
1368
1598
|
}
|
|
1369
1599
|
function getOrderConfirmationSection() {
|
|
1370
1600
|
return `## Order Confirmation Page (/order-confirmation) \u2014 REQUIRED!
|
|
@@ -1534,7 +1764,8 @@ overlay needed:
|
|
|
1534
1764
|
- \`brands[].name\`
|
|
1535
1765
|
- \`tags[].name\`
|
|
1536
1766
|
- \`variants[].name\`
|
|
1537
|
-
- \`
|
|
1767
|
+
- \`variant.attributes\` keys and values \u2014 \`getVariantOptions(variant)\` returns translated attribute names and option values automatically
|
|
1768
|
+
- \`productAttributeOptions[].attribute.name\`, \`attributeOption.name\`
|
|
1538
1769
|
- \`metafields[].value\`
|
|
1539
1770
|
|
|
1540
1771
|
**Taxonomy (\`getCategories\`, \`getBrands\`, \`getTags\`):**
|
|
@@ -1543,6 +1774,10 @@ overlay needed:
|
|
|
1543
1774
|
**Cart:**
|
|
1544
1775
|
- \`items[].product.name\`, \`items[].variant.name\`
|
|
1545
1776
|
|
|
1777
|
+
**Bundles & Order Bumps:**
|
|
1778
|
+
- \`bundleProduct.name\`, \`bundleProduct.slug\`, \`bumpProduct.name\`, \`bumpProduct.slug\`
|
|
1779
|
+
- Variant names inside bundles/bumps
|
|
1780
|
+
|
|
1546
1781
|
**Checkout:**
|
|
1547
1782
|
- Line items: \`items[].product.name\`, \`items[].variant.name\`
|
|
1548
1783
|
- Discount banners, nudges, badges
|
|
@@ -1627,6 +1862,265 @@ const admin = new BrainerceClient({ apiKey: 'brainerce_...' });
|
|
|
1627
1862
|
// OAuth: getOAuthProviders(), configureOAuthProvider()
|
|
1628
1863
|
\`\`\``;
|
|
1629
1864
|
}
|
|
1865
|
+
function getContactInquiriesSection() {
|
|
1866
|
+
return `## Contact Inquiries & Forms (optional)
|
|
1867
|
+
|
|
1868
|
+
Accept messages from one or more contact forms on your storefront. The merchant
|
|
1869
|
+
configures everything in the Brainerce dashboard under **Customers \u2192 Contact
|
|
1870
|
+
Forms**; submissions land in **Customers \u2192 Inquiries** and both sides receive
|
|
1871
|
+
email notifications.
|
|
1872
|
+
|
|
1873
|
+
**IMPORTANT for AI code generators:** the merchant OWNS the form shape. Do not
|
|
1874
|
+
hardcode labels, placeholders, help text, the submit button, or the success
|
|
1875
|
+
message. Render from the schema returned by \`contactForms.get()\` so the
|
|
1876
|
+
storefront reflects whatever the merchant configures \u2014 including new fields
|
|
1877
|
+
they add later, translations they add later, and the success message they
|
|
1878
|
+
write. This is the difference between "a contact form" and "THE merchant's
|
|
1879
|
+
contact form."
|
|
1880
|
+
|
|
1881
|
+
### Two integration paths
|
|
1882
|
+
|
|
1883
|
+
1. **Simple (legacy)** \u2014 pass \`{ name, email, subject, message }\` and submit.
|
|
1884
|
+
Works out of the box, no dashboard setup needed. Backed by a lazily-seeded
|
|
1885
|
+
default form keyed \`"main"\` with five built-in fields (\`name\`, \`email\`,
|
|
1886
|
+
\`phone\`, \`subject\`, \`message\`). Choose this only for throwaway demos.
|
|
1887
|
+
2. **Flexible (recommended, default in \`npx create-brainerce-store\`)** \u2014
|
|
1888
|
+
merchants can configure multiple forms per store (e.g. \`main\`,
|
|
1889
|
+
\`newsletter\`, \`whatsapp_prechat\`), add custom fields (TEXT, TEXTAREA,
|
|
1890
|
+
EMAIL, PHONE, NUMBER, SELECT, MULTI_SELECT, CHECKBOX, URL, DATE), translate
|
|
1891
|
+
everything per locale, hide any non-essential built-in. Fetch the schema
|
|
1892
|
+
with \`contactForms.get(formKey, locale)\` and render dynamically.
|
|
1893
|
+
|
|
1894
|
+
### Simple path (legacy shape)
|
|
1895
|
+
|
|
1896
|
+
\`\`\`typescript
|
|
1897
|
+
import type { CreateInquiryInput, CreateInquiryResponse } from 'brainerce';
|
|
1898
|
+
|
|
1899
|
+
const result = await brainerce.createInquiry({
|
|
1900
|
+
name: 'Jane Doe',
|
|
1901
|
+
email: 'jane@example.com',
|
|
1902
|
+
subject: 'Question about shipping',
|
|
1903
|
+
message: 'Hi, do you ship internationally?',
|
|
1904
|
+
phone: '+1-555-0100', // optional
|
|
1905
|
+
customerId: customer?.id, // optional \u2014 link to logged-in customer
|
|
1906
|
+
metadata: { page: '/contact' }, // optional
|
|
1907
|
+
});
|
|
1908
|
+
// \u2192 { id, status: 'NEW', createdAt }
|
|
1909
|
+
\`\`\`
|
|
1910
|
+
|
|
1911
|
+
### Flexible path \u2014 end-to-end contract
|
|
1912
|
+
|
|
1913
|
+
**Endpoints:**
|
|
1914
|
+
|
|
1915
|
+
| Method | Path | Returns |
|
|
1916
|
+
| ------ | ----------------------------------------------------------------- | ------------------------------ |
|
|
1917
|
+
| GET | \`/stores/:storeId/contact-forms\` | \`ContactFormSummary[]\` |
|
|
1918
|
+
| GET | \`/stores/:storeId/contact-forms/:formKey?locale=xx\` | \`ContactFormPublic\` |
|
|
1919
|
+
| POST | \`/stores/:storeId/inquiries\` | \`CreateInquiryResponse\` |
|
|
1920
|
+
|
|
1921
|
+
All three are public (no API key). The SDK wraps them so you never call them
|
|
1922
|
+
directly \u2014 use \`brainerce.contactForms.list()\`, \`brainerce.contactForms.get()\`,
|
|
1923
|
+
and \`brainerce.createInquiry()\`.
|
|
1924
|
+
|
|
1925
|
+
\`\`\`typescript
|
|
1926
|
+
import type { ContactFormPublic } from 'brainerce';
|
|
1927
|
+
|
|
1928
|
+
// List active forms (optional \u2014 if you want a form picker or route-per-form setup)
|
|
1929
|
+
const forms = await brainerce.contactForms.list();
|
|
1930
|
+
// \u2192 [{ key: 'main', name: 'Contact us', isDefault: true }, ...]
|
|
1931
|
+
|
|
1932
|
+
// Fetch one form's schema \u2014 server pre-resolves translations for the locale
|
|
1933
|
+
// and strips every field the merchant marked isVisible=false.
|
|
1934
|
+
const form = await brainerce.contactForms.get('main', 'en');
|
|
1935
|
+
// \u2192 {
|
|
1936
|
+
// id, key, name, description?, submitButton, successMessage,
|
|
1937
|
+
// fields: [{ key, type, label, placeholder?, helpText?, isRequired,
|
|
1938
|
+
// enumValues?, validation?, defaultValue? }, ...]
|
|
1939
|
+
// }
|
|
1940
|
+
|
|
1941
|
+
// Submit a keyed payload. Unknown keys are stripped, required fields are
|
|
1942
|
+
// enforced, and every value is validated against \`validation\` server-side.
|
|
1943
|
+
await brainerce.createInquiry({
|
|
1944
|
+
formKey: 'main',
|
|
1945
|
+
fields: {
|
|
1946
|
+
email: 'jane@example.com', // built-in keys
|
|
1947
|
+
message: 'Hi...',
|
|
1948
|
+
// ...any custom keys the merchant added via the dashboard
|
|
1949
|
+
},
|
|
1950
|
+
locale: 'en', // stored on the inquiry \u2014 lets staff filter by language
|
|
1951
|
+
sourceMetadata: { page: '/contact' }, // arbitrary provenance (UTM, referrer, etc.)
|
|
1952
|
+
});
|
|
1953
|
+
\`\`\`
|
|
1954
|
+
|
|
1955
|
+
Both shapes go to the same POST endpoint and may be mixed; \`fields\` wins when
|
|
1956
|
+
both provide the same key. Unknown keys (not defined on the form schema) are
|
|
1957
|
+
stripped server-side.
|
|
1958
|
+
|
|
1959
|
+
### Dynamic rendering \u2014 reference implementation
|
|
1960
|
+
|
|
1961
|
+
Render every field type the merchant can pick. Keep this as a \`<DynamicField>\`
|
|
1962
|
+
component so the form is fully driven by \`schema.fields\`.
|
|
1963
|
+
|
|
1964
|
+
\`\`\`tsx
|
|
1965
|
+
import type { ContactFormPublic, ContactFormPublicField } from 'brainerce';
|
|
1966
|
+
|
|
1967
|
+
type FieldValue = string | string[] | boolean;
|
|
1968
|
+
|
|
1969
|
+
function defaultValueFor(f: ContactFormPublicField): FieldValue {
|
|
1970
|
+
if (f.type === 'CHECKBOX') return false;
|
|
1971
|
+
if (f.type === 'MULTI_SELECT') return [];
|
|
1972
|
+
return f.defaultValue ?? '';
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1975
|
+
function isEmpty(v: FieldValue): boolean {
|
|
1976
|
+
if (typeof v === 'string') return v.trim().length === 0;
|
|
1977
|
+
if (Array.isArray(v)) return v.length === 0;
|
|
1978
|
+
return v === false;
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1981
|
+
function DynamicField({
|
|
1982
|
+
field,
|
|
1983
|
+
value,
|
|
1984
|
+
onChange,
|
|
1985
|
+
}: {
|
|
1986
|
+
field: ContactFormPublicField;
|
|
1987
|
+
value: FieldValue;
|
|
1988
|
+
onChange: (v: FieldValue) => void;
|
|
1989
|
+
}) {
|
|
1990
|
+
const id = \`contact-\${field.key}\`;
|
|
1991
|
+
const { minLength, maxLength, min, max, pattern } = field.validation ?? {};
|
|
1992
|
+
const strVal = typeof value === 'string' ? value : '';
|
|
1993
|
+
|
|
1994
|
+
// Label \u2014 USE \`field.label\`, NEVER hardcode. Falls back to the key.
|
|
1995
|
+
const label = (
|
|
1996
|
+
<label htmlFor={id} className="mb-1.5 block text-sm font-medium">
|
|
1997
|
+
{field.label}
|
|
1998
|
+
{field.isRequired && <span aria-hidden className="text-red-500"> *</span>}
|
|
1999
|
+
</label>
|
|
2000
|
+
);
|
|
2001
|
+
const help = field.helpText ? <p className="mt-1 text-xs opacity-70">{field.helpText}</p> : null;
|
|
2002
|
+
|
|
2003
|
+
switch (field.type) {
|
|
2004
|
+
case 'TEXTAREA':
|
|
2005
|
+
return (<div>{label}<textarea id={id} required={field.isRequired} maxLength={maxLength} minLength={minLength} rows={6} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
|
|
2006
|
+
case 'EMAIL':
|
|
2007
|
+
return (<div>{label}<input id={id} type="email" required={field.isRequired} autoComplete="email" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
|
|
2008
|
+
case 'PHONE':
|
|
2009
|
+
return (<div>{label}<input id={id} type="tel" required={field.isRequired} autoComplete="tel" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
|
|
2010
|
+
case 'URL':
|
|
2011
|
+
return (<div>{label}<input id={id} type="url" required={field.isRequired} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
|
|
2012
|
+
case 'NUMBER':
|
|
2013
|
+
return (<div>{label}<input id={id} type="number" required={field.isRequired} min={min} max={max} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
|
|
2014
|
+
case 'DATE':
|
|
2015
|
+
return (<div>{label}<input id={id} type="date" required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
|
|
2016
|
+
case 'SELECT':
|
|
2017
|
+
return (<div>{label}<select id={id} required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)}><option value="">\u2014</option>{field.enumValues?.map((o) => (<option key={o.value} value={o.value}>{o.label}</option>))}</select>{help}</div>);
|
|
2018
|
+
case 'MULTI_SELECT': {
|
|
2019
|
+
const arr = Array.isArray(value) ? value : [];
|
|
2020
|
+
return (<div>{label}<div>{field.enumValues?.map((o) => { const checked = arr.includes(o.value); return (<label key={o.value}><input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked ? [...arr, o.value] : arr.filter((v) => v !== o.value))} /><span>{o.label}</span></label>); })}</div>{help}</div>);
|
|
2021
|
+
}
|
|
2022
|
+
case 'CHECKBOX':
|
|
2023
|
+
return (<div><label htmlFor={id}><input id={id} type="checkbox" required={field.isRequired} checked={value === true} onChange={(e) => onChange(e.target.checked)} /><span>{field.label}</span></label>{help}</div>);
|
|
2024
|
+
case 'TEXT':
|
|
2025
|
+
default:
|
|
2026
|
+
return (<div>{label}<input id={id} type="text" required={field.isRequired} maxLength={maxLength} minLength={minLength} pattern={pattern} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
|
|
2027
|
+
}
|
|
2028
|
+
}
|
|
2029
|
+
|
|
2030
|
+
export function ContactPage() {
|
|
2031
|
+
const [schema, setSchema] = useState<ContactFormPublic | null>(null);
|
|
2032
|
+
const [values, setValues] = useState<Record<string, FieldValue>>({});
|
|
2033
|
+
const [honeypot, setHoneypot] = useState('');
|
|
2034
|
+
const [sent, setSent] = useState(false);
|
|
2035
|
+
const [loading, setLoading] = useState(false);
|
|
2036
|
+
|
|
2037
|
+
// Read the current locale from the <html lang> attribute (or your own i18n context).
|
|
2038
|
+
const locale = typeof document !== 'undefined' ? document.documentElement.lang || undefined : undefined;
|
|
2039
|
+
|
|
2040
|
+
useEffect(() => {
|
|
2041
|
+
brainerce.contactForms.get('main', locale).then((form) => {
|
|
2042
|
+
setSchema(form);
|
|
2043
|
+
const initial: Record<string, FieldValue> = {};
|
|
2044
|
+
for (const f of form.fields) initial[f.key] = defaultValueFor(f);
|
|
2045
|
+
setValues(initial);
|
|
2046
|
+
});
|
|
2047
|
+
}, [locale]);
|
|
2048
|
+
|
|
2049
|
+
if (!schema) return null;
|
|
2050
|
+
|
|
2051
|
+
const onSubmit = async (e: React.FormEvent) => {
|
|
2052
|
+
e.preventDefault();
|
|
2053
|
+
if (loading) return;
|
|
2054
|
+
if (honeypot.trim().length > 0) { setSent(true); return; } // bot \u2192 silent success
|
|
2055
|
+
|
|
2056
|
+
setLoading(true);
|
|
2057
|
+
try {
|
|
2058
|
+
const payload: Record<string, unknown> = {};
|
|
2059
|
+
for (const f of schema.fields) {
|
|
2060
|
+
const raw = values[f.key];
|
|
2061
|
+
if (isEmpty(raw)) continue;
|
|
2062
|
+
payload[f.key] = typeof raw === 'string' ? raw.trim() : raw;
|
|
2063
|
+
}
|
|
2064
|
+
await brainerce.createInquiry({ formKey: schema.key, fields: payload, locale });
|
|
2065
|
+
setSent(true);
|
|
2066
|
+
} finally {
|
|
2067
|
+
setLoading(false);
|
|
2068
|
+
}
|
|
2069
|
+
};
|
|
2070
|
+
|
|
2071
|
+
if (sent) {
|
|
2072
|
+
// RENDER THE MERCHANT'S success message \u2014 do not hardcode.
|
|
2073
|
+
return <div>{schema.successMessage}</div>;
|
|
2074
|
+
}
|
|
2075
|
+
|
|
2076
|
+
return (
|
|
2077
|
+
<form onSubmit={onSubmit} noValidate>
|
|
2078
|
+
<h1>{schema.name}</h1>
|
|
2079
|
+
{schema.description && <p>{schema.description}</p>}
|
|
2080
|
+
|
|
2081
|
+
{/* Honeypot \u2014 must be visually hidden from humans, not from bots */}
|
|
2082
|
+
<div aria-hidden style={{ position: 'absolute', left: '-10000px', width: 0, height: 0, overflow: 'hidden' }}>
|
|
2083
|
+
<label htmlFor="contact-honeypot">Leave this field empty</label>
|
|
2084
|
+
<input id="contact-honeypot" type="text" tabIndex={-1} autoComplete="off"
|
|
2085
|
+
value={honeypot} onChange={(e) => setHoneypot(e.target.value)} />
|
|
2086
|
+
</div>
|
|
2087
|
+
|
|
2088
|
+
{schema.fields.map((field) => (
|
|
2089
|
+
<DynamicField key={field.key} field={field}
|
|
2090
|
+
value={values[field.key] ?? defaultValueFor(field)}
|
|
2091
|
+
onChange={(v) => setValues((p) => ({ ...p, [field.key]: v }))} />
|
|
2092
|
+
))}
|
|
2093
|
+
|
|
2094
|
+
<button type="submit" disabled={loading}>
|
|
2095
|
+
{loading ? '\u2026' : schema.submitButton}
|
|
2096
|
+
</button>
|
|
2097
|
+
</form>
|
|
2098
|
+
);
|
|
2099
|
+
}
|
|
2100
|
+
\`\`\`
|
|
2101
|
+
|
|
2102
|
+
### Rules
|
|
2103
|
+
|
|
2104
|
+
- **Rate limit:** 3 submissions / 60s per IP \u2014 show a friendly "try again later" message on HTTP 429.
|
|
2105
|
+
- **Honeypot:** always render a hidden field named \`honeypot\` and **never send** it. Bots fill every input; the server rejects submissions carrying a non-empty \`honeypot\`.
|
|
2106
|
+
- **Built-in keys:** \`name\`, \`email\`, \`phone\`, \`subject\`, \`message\` always exist on the default form; the legacy \`createInquiry\` shape keeps working forever.
|
|
2107
|
+
- **Max values:** each field value is capped at 10 000 chars server-side. Validate client-side before submitting using \`field.validation.maxLength\`.
|
|
2108
|
+
- **Required fields:** respect \`field.isRequired\`. The server validates too, but show \`required\` on the input for browser-level UX.
|
|
2109
|
+
- **Validation:** when \`field.validation.pattern\` is present, pass it as the input's \`pattern\` attribute; the server also enforces it. Likewise \`minLength\`/\`maxLength\`/\`min\`/\`max\`.
|
|
2110
|
+
- **Enum values:** SELECT and MULTI_SELECT always return \`enumValues\` (non-empty array). Render from \`enumValues\`, never a hardcoded list.
|
|
2111
|
+
- **Visibility:** the server strips fields with \`isVisible=false\`, so \`schema.fields\` only contains things to render.
|
|
2112
|
+
- **Origin check:** the endpoint validates \`Origin\` against the store's allowed origins. Test from your real storefront URL, not \`file://\` or localhost unless the merchant added it to allowed origins.
|
|
2113
|
+
- **Locale handling:** always pass \`locale\` to \`contactForms.get()\` and to \`createInquiry()\`. The staff inbox filters inquiries by language. Omit to fall back to the store's default language.
|
|
2114
|
+
- **Success message:** render \`schema.successMessage\` as-is. (Variable interpolation like \`{{customerName}}\` is not yet wired; any such placeholders currently render literally. Safe to use plain text.)
|
|
2115
|
+
- **Caching:** the schema GET is safe to cache per \`{storeId, formKey, locale}\`. 60 s feels live without hammering the API.
|
|
2116
|
+
|
|
2117
|
+
### Multiple forms
|
|
2118
|
+
|
|
2119
|
+
If the merchant set up more than one form (e.g. a \`main\` form on \`/contact\`
|
|
2120
|
+
and a \`newsletter\` form embedded in the footer), render each form from its
|
|
2121
|
+
own \`contactForms.get(key, locale)\` call. The \`formKey\` you pass to
|
|
2122
|
+
\`createInquiry\` must match.`;
|
|
2123
|
+
}
|
|
1630
2124
|
function getSectionByTopic(topic, connectionId, currency) {
|
|
1631
2125
|
const cid = connectionId || "vc_YOUR_CONNECTION_ID";
|
|
1632
2126
|
const cur = currency || "USD";
|
|
@@ -1653,6 +2147,8 @@ function getSectionByTopic(topic, connectionId, currency) {
|
|
|
1653
2147
|
return getDiscountsSection();
|
|
1654
2148
|
case "recommendations":
|
|
1655
2149
|
return getRecommendationsSection();
|
|
2150
|
+
case "product-customization-fields":
|
|
2151
|
+
return getProductCustomizationFieldsSection();
|
|
1656
2152
|
case "tax":
|
|
1657
2153
|
return getTaxDisplaySection(cur);
|
|
1658
2154
|
case "i18n":
|
|
@@ -1663,6 +2159,8 @@ function getSectionByTopic(topic, connectionId, currency) {
|
|
|
1663
2159
|
return getTypeQuickReference();
|
|
1664
2160
|
case "admin":
|
|
1665
2161
|
return getAdminApiSection();
|
|
2162
|
+
case "inquiries":
|
|
2163
|
+
return getContactInquiriesSection();
|
|
1666
2164
|
case "all":
|
|
1667
2165
|
return [
|
|
1668
2166
|
"# Brainerce SDK \u2014 full topic dump",
|
|
@@ -1727,6 +2225,10 @@ function getSectionByTopic(topic, connectionId, currency) {
|
|
|
1727
2225
|
"",
|
|
1728
2226
|
"---",
|
|
1729
2227
|
"",
|
|
2228
|
+
getProductCustomizationFieldsSection(),
|
|
2229
|
+
"",
|
|
2230
|
+
"---",
|
|
2231
|
+
"",
|
|
1730
2232
|
getTaxDisplaySection(cur),
|
|
1731
2233
|
"",
|
|
1732
2234
|
"---",
|
|
@@ -1735,10 +2237,14 @@ function getSectionByTopic(topic, connectionId, currency) {
|
|
|
1735
2237
|
"",
|
|
1736
2238
|
"---",
|
|
1737
2239
|
"",
|
|
1738
|
-
getAdminApiSection()
|
|
2240
|
+
getAdminApiSection(),
|
|
2241
|
+
"",
|
|
2242
|
+
"---",
|
|
2243
|
+
"",
|
|
2244
|
+
getContactInquiriesSection()
|
|
1739
2245
|
].join("\n");
|
|
1740
2246
|
default:
|
|
1741
|
-
return `Unknown topic: "${topic}". Available topics: setup, products, cart, checkout, checkout-custom-fields, payment, auth, order-confirmation, inventory, discounts, recommendations, tax, i18n, critical-rules, type-reference, admin, all`;
|
|
2247
|
+
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`;
|
|
1742
2248
|
}
|
|
1743
2249
|
}
|
|
1744
2250
|
|
|
@@ -1758,11 +2264,13 @@ var GET_SDK_DOCS_SCHEMA = {
|
|
|
1758
2264
|
"inventory",
|
|
1759
2265
|
"discounts",
|
|
1760
2266
|
"recommendations",
|
|
2267
|
+
"product-customization-fields",
|
|
1761
2268
|
"tax",
|
|
1762
2269
|
"critical-rules",
|
|
1763
2270
|
"type-reference",
|
|
1764
2271
|
"i18n",
|
|
1765
2272
|
"admin",
|
|
2273
|
+
"inquiries",
|
|
1766
2274
|
"all"
|
|
1767
2275
|
]).describe("The SDK documentation topic to retrieve"),
|
|
1768
2276
|
connectionId: import_zod.z.string().optional().describe("Vibe-coded connection ID (starts with vc_). Used to personalize setup code."),
|
|
@@ -1802,6 +2310,7 @@ interface Product {
|
|
|
1802
2310
|
brands?: Array<{ id: string; name: string }>;
|
|
1803
2311
|
tags?: string[];
|
|
1804
2312
|
metafields?: ProductMetafield[];
|
|
2313
|
+
customizationFields?: ProductCustomizationField[]; // Buyer input fields \u2014 render on PDP, send values in cart metadata. Account-wide fields (MetafieldDefinition.appliesToAllProducts=true) are folded in here automatically; no client-side merging.
|
|
1805
2314
|
productAttributeOptions?: Array<{
|
|
1806
2315
|
id: string;
|
|
1807
2316
|
attributeId: string;
|
|
@@ -1860,6 +2369,32 @@ interface ProductMetafield {
|
|
|
1860
2369
|
variantId?: string | null;
|
|
1861
2370
|
}
|
|
1862
2371
|
|
|
2372
|
+
// Metafield type enum \u2014 used by ProductCustomizationField.type
|
|
2373
|
+
type MetafieldType =
|
|
2374
|
+
| 'TEXT' | 'TEXTAREA' | 'NUMBER' | 'BOOLEAN' | 'DATE' | 'DATETIME'
|
|
2375
|
+
| 'URL' | 'COLOR' | 'DIMENSION' | 'WEIGHT' | 'JSON'
|
|
2376
|
+
| 'IMAGE' | 'GALLERY'
|
|
2377
|
+
| 'SELECT' | 'MULTI_SELECT';
|
|
2378
|
+
|
|
2379
|
+
// Customer-facing input assigned per product. Render on the PDP in the order of \`position\`.
|
|
2380
|
+
// Submit values keyed by \`key\` inside AddToCartDto.metadata.
|
|
2381
|
+
// Upload files via \`uploadCustomizationFile()\` first, then place the returned \`url\` in metadata.
|
|
2382
|
+
interface ProductCustomizationField {
|
|
2383
|
+
definitionId: string;
|
|
2384
|
+
name: string; // Label to show buyers
|
|
2385
|
+
key: string; // Use as metadata key in AddToCartDto.metadata
|
|
2386
|
+
description?: string | null; // Help text
|
|
2387
|
+
type: MetafieldType;
|
|
2388
|
+
required: boolean;
|
|
2389
|
+
minLength?: number | null; // TEXT/TEXTAREA char bounds; MULTI_SELECT array bounds
|
|
2390
|
+
maxLength?: number | null;
|
|
2391
|
+
minValue?: number | null; // NUMBER bounds
|
|
2392
|
+
maxValue?: number | null;
|
|
2393
|
+
enumValues?: string[]; // REQUIRED for SELECT / MULTI_SELECT
|
|
2394
|
+
defaultValue?: string | null;
|
|
2395
|
+
position: number; // Render order
|
|
2396
|
+
}
|
|
2397
|
+
|
|
1863
2398
|
interface ProductQueryParams {
|
|
1864
2399
|
page?: number;
|
|
1865
2400
|
limit?: number;
|
|
@@ -1943,6 +2478,7 @@ interface CartItem {
|
|
|
1943
2478
|
sku?: string | null;
|
|
1944
2479
|
image?: ProductImage | string | null;
|
|
1945
2480
|
} | null;
|
|
2481
|
+
metadata?: Record<string, unknown> | null; // Buyer-submitted customization values, keyed by ProductCustomizationField.key
|
|
1946
2482
|
createdAt: string;
|
|
1947
2483
|
updatedAt: string;
|
|
1948
2484
|
}
|
|
@@ -2007,6 +2543,9 @@ interface Checkout {
|
|
|
2007
2543
|
taxAmount: string;
|
|
2008
2544
|
taxBreakdown?: TaxBreakdown | null;
|
|
2009
2545
|
total: string;
|
|
2546
|
+
surchargeAmount: string;
|
|
2547
|
+
appliedSurcharges?: Array<{ key: string; name: string; value: unknown; amount: string }> | null;
|
|
2548
|
+
customFieldValues?: Record<string, unknown> | null;
|
|
2010
2549
|
couponCode?: string | null;
|
|
2011
2550
|
lineItems: CheckoutLineItem[]; // Use THIS for order summary, NOT cart.items!
|
|
2012
2551
|
itemCount: number;
|
|
@@ -2025,6 +2564,7 @@ interface CheckoutLineItem {
|
|
|
2025
2564
|
discountAmount: string;
|
|
2026
2565
|
product: { id: string; name: string; sku: string; images?: ProductImage[]; };
|
|
2027
2566
|
variant?: { id: string; name?: string | null; sku?: string | null; image?: ProductImage | string | null; } | null;
|
|
2567
|
+
metadata?: Record<string, unknown> | null; // Copied from CartItem.metadata \u2014 buyer customization values
|
|
2028
2568
|
}
|
|
2029
2569
|
|
|
2030
2570
|
interface CheckoutAddress {
|
|
@@ -2106,6 +2646,27 @@ interface Order {
|
|
|
2106
2646
|
billingAddress?: OrderAddress;
|
|
2107
2647
|
hasDownloads?: boolean;
|
|
2108
2648
|
createdAt: string;
|
|
2649
|
+
|
|
2650
|
+
// Payment + fulfillment
|
|
2651
|
+
paymentMethod?: string | null;
|
|
2652
|
+
financialStatus?: string | null; // "pending" | "paid" | "refunded" | "partially_refunded" | "voided"
|
|
2653
|
+
fulfillmentStatus?: string | null; // "unfulfilled" | "partial" | "fulfilled"
|
|
2654
|
+
|
|
2655
|
+
// Tracking
|
|
2656
|
+
trackingNumber?: string | null;
|
|
2657
|
+
trackingUrl?: string | null;
|
|
2658
|
+
carrier?: string | null;
|
|
2659
|
+
shippedAt?: string | null; // ISO-8601
|
|
2660
|
+
deliveredAt?: string | null; // ISO-8601
|
|
2661
|
+
|
|
2662
|
+
// Timeline of status transitions, chronological
|
|
2663
|
+
statusHistory?: OrderStatusChange[] | null;
|
|
2664
|
+
}
|
|
2665
|
+
|
|
2666
|
+
interface OrderStatusChange {
|
|
2667
|
+
status: OrderStatus;
|
|
2668
|
+
at: string; // ISO-8601
|
|
2669
|
+
note?: string | null;
|
|
2109
2670
|
}
|
|
2110
2671
|
|
|
2111
2672
|
// \u26A0\uFE0F OrderItem is FLAT \u2014 unlike CartItem which is NESTED
|
|
@@ -2119,6 +2680,9 @@ interface OrderItem {
|
|
|
2119
2680
|
unitPrice?: string; // alias
|
|
2120
2681
|
totalPrice?: string;
|
|
2121
2682
|
image?: string; // FLAT: item.image (NOT nested)
|
|
2683
|
+
// Snapshot of buyer-submitted customization values captured at checkout.
|
|
2684
|
+
// Keyed by metafield slug. \`value\` is string[] for MULTI_SELECT / GALLERY, string otherwise.
|
|
2685
|
+
customizations?: Record<string, { label: string; value: string | string[]; type: string }>;
|
|
2122
2686
|
}
|
|
2123
2687
|
|
|
2124
2688
|
interface OrderCustomer {
|
|
@@ -2340,7 +2904,129 @@ interface ProductRecommendationsResponse {
|
|
|
2340
2904
|
}
|
|
2341
2905
|
interface CartRecommendationsResponse {
|
|
2342
2906
|
recommendations: ProductRecommendation[];
|
|
2907
|
+
}
|
|
2908
|
+
|
|
2909
|
+
// Cart include types (for consolidated getCart requests)
|
|
2910
|
+
type CartIncludeOption = 'recommendations' | 'upgrades' | 'bundles';
|
|
2911
|
+
interface CartIncludeOptions {
|
|
2912
|
+
include?: CartIncludeOption[];
|
|
2913
|
+
}
|
|
2914
|
+
interface CartWithIncludes extends Cart {
|
|
2915
|
+
recommendations?: { recommendations: ProductRecommendation[] };
|
|
2916
|
+
upgrades?: { upgrades: Record<string, CartUpgradeSuggestion> };
|
|
2917
|
+
bundles?: { bundles: CartBundleOffer[] };
|
|
2918
|
+
}
|
|
2919
|
+
interface CartUpgradeSuggestion {
|
|
2920
|
+
targetProduct: ProductRecommendation;
|
|
2921
|
+
priceDelta: string;
|
|
2922
|
+
deltaPercent: number;
|
|
2923
|
+
}
|
|
2924
|
+
interface CartBundleOffer {
|
|
2925
|
+
id: string;
|
|
2926
|
+
bundleProduct: ProductRecommendation;
|
|
2927
|
+
originalPrice: string;
|
|
2928
|
+
discountedPrice: string;
|
|
2929
|
+
discountType: 'PERCENTAGE' | 'FIXED_AMOUNT';
|
|
2930
|
+
discountValue: number;
|
|
2931
|
+
requiresVariantSelection: boolean;
|
|
2932
|
+
lockedVariant?: { id: string; name?: string };
|
|
2343
2933
|
}`;
|
|
2934
|
+
var INQUIRIES_TYPES = `// ---- Contact Inquiries & Forms ----
|
|
2935
|
+
|
|
2936
|
+
// Two shapes \u2014 legacy and flexible. The two may be mixed; \`fields\` wins on key collision.
|
|
2937
|
+
interface CreateInquiryInput {
|
|
2938
|
+
// Legacy shape (still supported forever, backed by default "main" form)
|
|
2939
|
+
name?: string; // max 120 chars (if provided)
|
|
2940
|
+
email?: string; // must be valid email if provided
|
|
2941
|
+
subject?: string; // max 200 chars
|
|
2942
|
+
message?: string; // max 10000 chars
|
|
2943
|
+
phone?: string;
|
|
2944
|
+
|
|
2945
|
+
// Flexible shape
|
|
2946
|
+
formKey?: string; // defaults to "main"; merchant-defined keys e.g. "newsletter"
|
|
2947
|
+
fields?: Record<string, unknown>; // bag of values keyed by field key (built-in or custom)
|
|
2948
|
+
locale?: string; // e.g. "en", "he" \u2014 stored on the inquiry
|
|
2949
|
+
sourceMetadata?: Record<string, unknown>; // arbitrary context (e.g. { page: '/contact', campaign: 'fall-2026' })
|
|
2950
|
+
|
|
2951
|
+
// Shared
|
|
2952
|
+
customerId?: string; // link to logged-in customer
|
|
2953
|
+
metadata?: Record<string, unknown>; // deprecated alias of sourceMetadata
|
|
2954
|
+
}
|
|
2955
|
+
|
|
2956
|
+
interface CreateInquiryResponse {
|
|
2957
|
+
id: string;
|
|
2958
|
+
status: 'NEW';
|
|
2959
|
+
createdAt: string; // ISO datetime
|
|
2960
|
+
}
|
|
2961
|
+
|
|
2962
|
+
// ---- Form schema (for dynamic rendering) ----
|
|
2963
|
+
|
|
2964
|
+
type ContactFormFieldType =
|
|
2965
|
+
| 'TEXT' | 'TEXTAREA' | 'EMAIL' | 'PHONE' | 'NUMBER'
|
|
2966
|
+
| 'SELECT' | 'MULTI_SELECT' | 'CHECKBOX' | 'URL' | 'DATE';
|
|
2967
|
+
|
|
2968
|
+
interface ContactFormFieldValidation {
|
|
2969
|
+
minLength?: number;
|
|
2970
|
+
maxLength?: number;
|
|
2971
|
+
min?: number;
|
|
2972
|
+
max?: number;
|
|
2973
|
+
pattern?: string; // regex string
|
|
2974
|
+
patternMessage?: string;
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
interface ContactFormPublicField {
|
|
2978
|
+
key: string; // stable identifier, e.g. "email", "company"
|
|
2979
|
+
type: ContactFormFieldType;
|
|
2980
|
+
label: string; // already localized for the requested locale
|
|
2981
|
+
placeholder?: string; // already localized
|
|
2982
|
+
helpText?: string; // already localized
|
|
2983
|
+
isRequired: boolean;
|
|
2984
|
+
enumValues?: { value: string; label: string }[]; // present (non-empty) for SELECT / MULTI_SELECT
|
|
2985
|
+
validation?: ContactFormFieldValidation;
|
|
2986
|
+
defaultValue?: string;
|
|
2987
|
+
}
|
|
2988
|
+
|
|
2989
|
+
interface ContactFormPublic {
|
|
2990
|
+
id: string;
|
|
2991
|
+
key: string; // e.g. "main", "newsletter"
|
|
2992
|
+
name: string; // already localized \u2014 use as form heading
|
|
2993
|
+
description?: string; // already localized \u2014 use as subtitle
|
|
2994
|
+
submitButton: string; // already localized \u2014 use as submit label
|
|
2995
|
+
successMessage: string; // already localized \u2014 render after submit succeeds
|
|
2996
|
+
fields: ContactFormPublicField[]; // in display order; hidden fields already filtered out
|
|
2997
|
+
}
|
|
2998
|
+
|
|
2999
|
+
interface ContactFormSummary {
|
|
3000
|
+
key: string;
|
|
3001
|
+
name: string;
|
|
3002
|
+
isDefault: boolean;
|
|
3003
|
+
}
|
|
3004
|
+
|
|
3005
|
+
// Field-type \u2192 HTML mapping for dynamic rendering
|
|
3006
|
+
// ------------------------------------------------------------------
|
|
3007
|
+
// TEXT \u2192 <input type="text" ... pattern?={validation.pattern}>
|
|
3008
|
+
// TEXTAREA \u2192 <textarea rows={6} ...>
|
|
3009
|
+
// EMAIL \u2192 <input type="email" autoComplete="email" ...>
|
|
3010
|
+
// PHONE \u2192 <input type="tel" autoComplete="tel" ...>
|
|
3011
|
+
// NUMBER \u2192 <input type="number" min={validation.min} max={validation.max}>
|
|
3012
|
+
// URL \u2192 <input type="url" ...>
|
|
3013
|
+
// DATE \u2192 <input type="date" ...> (value is ISO yyyy-MM-dd)
|
|
3014
|
+
// SELECT \u2192 <select>{enumValues.map(...)}</select> \u2014 always rendered from enumValues
|
|
3015
|
+
// MULTI_SELECT \u2192 multiple <input type="checkbox">, value is string[]
|
|
3016
|
+
// CHECKBOX \u2192 single <input type="checkbox">, value is boolean
|
|
3017
|
+
// ------------------------------------------------------------------
|
|
3018
|
+
|
|
3019
|
+
// SDK methods
|
|
3020
|
+
// await brainerce.createInquiry(input) \u2192 POST /stores/{storeId}/inquiries
|
|
3021
|
+
// await brainerce.contactForms.list() \u2192 GET /stores/{storeId}/contact-forms
|
|
3022
|
+
// await brainerce.contactForms.get(key?, locale?) \u2192 GET /stores/{storeId}/contact-forms/{key}?locale={locale}
|
|
3023
|
+
//
|
|
3024
|
+
// Rules
|
|
3025
|
+
// - Rate limit: 3 submissions / 60s per IP \u2014 handle 429 responses gracefully
|
|
3026
|
+
// - Honeypot: always render an invisible field named \`honeypot\` and never send it
|
|
3027
|
+
// - Always pass \`locale\` \u2014 inbox filters inquiries by language, and schema labels come back translated
|
|
3028
|
+
// - Render \`schema.name\` / \`description\` / \`submitButton\` / \`successMessage\` directly \u2014 do NOT hardcode copy
|
|
3029
|
+
// - Unknown field keys are stripped server-side \u2014 safe to send extras during dev`;
|
|
2344
3030
|
var TYPES_BY_DOMAIN = {
|
|
2345
3031
|
products: PRODUCTS_TYPES,
|
|
2346
3032
|
cart: CART_TYPES,
|
|
@@ -2348,7 +3034,8 @@ var TYPES_BY_DOMAIN = {
|
|
|
2348
3034
|
orders: ORDERS_TYPES,
|
|
2349
3035
|
customers: CUSTOMERS_TYPES,
|
|
2350
3036
|
payments: PAYMENTS_TYPES,
|
|
2351
|
-
helpers: HELPERS_TYPES
|
|
3037
|
+
helpers: HELPERS_TYPES,
|
|
3038
|
+
inquiries: INQUIRIES_TYPES
|
|
2352
3039
|
};
|
|
2353
3040
|
function getTypesByDomain(domain) {
|
|
2354
3041
|
if (domain === "all") {
|
|
@@ -2369,7 +3056,17 @@ var AVAILABLE_DOMAINS = Object.keys(TYPES_BY_DOMAIN);
|
|
|
2369
3056
|
var GET_TYPE_DEFINITIONS_NAME = "get-type-definitions";
|
|
2370
3057
|
var GET_TYPE_DEFINITIONS_DESCRIPTION = "Get TypeScript type definitions from the Brainerce SDK, segmented by domain. Use this when you need to understand the exact shape of objects like Product, Cart, Checkout, Order, etc.";
|
|
2371
3058
|
var GET_TYPE_DEFINITIONS_SCHEMA = {
|
|
2372
|
-
domain: import_zod2.z.enum([
|
|
3059
|
+
domain: import_zod2.z.enum([
|
|
3060
|
+
"products",
|
|
3061
|
+
"cart",
|
|
3062
|
+
"checkout",
|
|
3063
|
+
"orders",
|
|
3064
|
+
"customers",
|
|
3065
|
+
"payments",
|
|
3066
|
+
"helpers",
|
|
3067
|
+
"inquiries",
|
|
3068
|
+
"all"
|
|
3069
|
+
]).describe(
|
|
2373
3070
|
'The domain of types to retrieve. Use "helpers" for helper function signatures and common types like StoreInfo, PaginatedResponse.'
|
|
2374
3071
|
)
|
|
2375
3072
|
};
|
|
@@ -2403,7 +3100,8 @@ var GET_CODE_EXAMPLE_SCHEMA = {
|
|
|
2403
3100
|
"coupon-apply-and-remove",
|
|
2404
3101
|
"reservation-countdown",
|
|
2405
3102
|
"search-autocomplete-debounce",
|
|
2406
|
-
"i18n-set-locale"
|
|
3103
|
+
"i18n-set-locale",
|
|
3104
|
+
"order-history-full"
|
|
2407
3105
|
]).describe("The SDK operation to get a snippet for.")
|
|
2408
3106
|
};
|
|
2409
3107
|
var SNIPPETS = {
|
|
@@ -2498,23 +3196,51 @@ const checkout = await client.getCheckout(checkoutId);
|
|
|
2498
3196
|
"checkout-payment-providers": `// Fetch configured payment providers for this checkout.
|
|
2499
3197
|
import { client } from './brainerce';
|
|
2500
3198
|
|
|
2501
|
-
const providers = await client.getPaymentProviders(
|
|
2502
|
-
//
|
|
2503
|
-
//
|
|
2504
|
-
//
|
|
2505
|
-
//
|
|
2506
|
-
//
|
|
2507
|
-
// '
|
|
2508
|
-
|
|
2509
|
-
//
|
|
2510
|
-
//
|
|
2511
|
-
|
|
3199
|
+
const { providers, hasPayments, defaultProvider } = await client.getPaymentProviders();
|
|
3200
|
+
// each provider: { id, provider, name, publicKey, supportedMethods, testMode, isDefault, clientSdk? }
|
|
3201
|
+
//
|
|
3202
|
+
// After createPaymentIntent, the response carries a clientSdk.renderType that
|
|
3203
|
+
// tells your UI how to render the payment step. The 5 possible values:
|
|
3204
|
+
//
|
|
3205
|
+
// 'sdk-widget' \u2014 Load the provider's JS SDK (scriptUrl), then mount
|
|
3206
|
+
// into a <div id={containerId}>. Used by Stripe,
|
|
3207
|
+
// PayPal, Grow. The SDK paints its own form inside
|
|
3208
|
+
// your DOM. You control layout/placement.
|
|
3209
|
+
//
|
|
3210
|
+
// 'iframe' \u2014 Render <iframe src={clientSecret}>. Two flavors:
|
|
3211
|
+
// a) URL path contains "/embed/" \u2192 Brainerce-hosted
|
|
3212
|
+
// embed page. Render INLINE in your checkout
|
|
3213
|
+
// flow. Listen for postMessage:
|
|
3214
|
+
// - 'brainerce:resize' \u2192 update iframe height
|
|
3215
|
+
// - 'brainerce:redirect' \u2192 validated top-level
|
|
3216
|
+
// navigation (e.g. Bit express-pay)
|
|
3217
|
+
// b) Any other URL \u2192 provider-hosted page. Render
|
|
3218
|
+
// inside a modal overlay (it carries its own
|
|
3219
|
+
// branding/chrome).
|
|
3220
|
+
//
|
|
3221
|
+
// 'redirect' \u2014 Full-page navigate: window.location.href = URL.
|
|
3222
|
+
// Customer leaves your site, pays on provider page,
|
|
3223
|
+
// returns via SuccessRedirectUrl.
|
|
3224
|
+
//
|
|
3225
|
+
// 'sandbox' \u2014 Test mode. Render a "Complete Test Order" button;
|
|
3226
|
+
// call completeGuestCheckout(checkoutId). Orders are
|
|
3227
|
+
// flagged isTestOrder: true. No real charge.
|
|
3228
|
+
//
|
|
3229
|
+
// 'embedded-fields' \u2014 (Reserved \u2014 not yet shipped in any provider.) PCI
|
|
3230
|
+
// micro-iframes for sensitive fields (card number,
|
|
3231
|
+
// CVV) mounted directly into the merchant form. Full
|
|
3232
|
+
// control of surrounding layout, like Stripe
|
|
3233
|
+
// Elements. Requires the provider to ship a client
|
|
3234
|
+
// SDK that exposes mount points.
|
|
3235
|
+
//
|
|
3236
|
+
// Always branch on clientSdk.renderType \u2014 NEVER hard-code by provider name.
|
|
3237
|
+
// New providers can be added without storefront changes.
|
|
2512
3238
|
|
|
2513
|
-
// If providers is empty, NO payment provider is configured and customers
|
|
2514
|
-
// cannot pay. Display a clear error \u2014 do not try to fake a checkout.
|
|
2515
3239
|
if (providers.length === 0) {
|
|
2516
3240
|
throw new Error('No payment provider configured for this store');
|
|
2517
|
-
}
|
|
3241
|
+
}
|
|
3242
|
+
|
|
3243
|
+
const active = providers[0];`,
|
|
2518
3244
|
"checkout-stripe-confirm": `// Stripe confirm flow. Requires @stripe/stripe-js and @stripe/react-stripe-js
|
|
2519
3245
|
// (or the vanilla Stripe.js browser SDK).
|
|
2520
3246
|
import { loadStripe } from '@stripe/stripe-js';
|
|
@@ -2728,12 +3454,82 @@ const locale = 'he'; // e.g., from the /[locale] route segment
|
|
|
2728
3454
|
client.setLocale(locale);
|
|
2729
3455
|
|
|
2730
3456
|
// ALL content comes back translated: products, categories, brands,
|
|
2731
|
-
// tags, variants
|
|
2732
|
-
//
|
|
3457
|
+
// tags, variants (name + attributes keys/values), metafields,
|
|
3458
|
+
// cart items, checkout line items, recommendations, bundles,
|
|
3459
|
+
// order bumps, search suggestions, discount banners, nudges,
|
|
2733
3460
|
// badges, order history.
|
|
2734
3461
|
|
|
2735
3462
|
// For RTL locales (he, ar), set the document direction.
|
|
2736
|
-
// Framework-neutral: document.documentElement.setAttribute('dir', 'rtl')
|
|
3463
|
+
// Framework-neutral: document.documentElement.setAttribute('dir', 'rtl');`,
|
|
3464
|
+
"order-history-full": `// Full "My Orders" account page. Render every piece of data the server
|
|
3465
|
+
// already returns \u2014 not just order number / total / status.
|
|
3466
|
+
//
|
|
3467
|
+
// Data you get from client.getMyOrders() (already on the wire today):
|
|
3468
|
+
// - items[].customizations \u2014 buyer's custom-field entries
|
|
3469
|
+
// - statusHistory \u2014 status timeline
|
|
3470
|
+
// - shippingAddress \u2014 name + address lines + country
|
|
3471
|
+
// - trackingNumber / trackingUrl / carrier / shippedAt / deliveredAt
|
|
3472
|
+
// - paymentMethod / financialStatus / fulfillmentStatus
|
|
3473
|
+
// - appliedDiscounts \u2014 shaped buyer-facing view
|
|
3474
|
+
// - hasDownloads \u2014 call /orders/:id/downloads to fetch
|
|
3475
|
+
//
|
|
3476
|
+
// Do NOT render: accountId, storeId, customerId, notes, customFieldValues
|
|
3477
|
+
// (merchant-internal, order-level), appliedRuleIds, appliedSurcharges,
|
|
3478
|
+
// surchargeAmount, downloadMeta (raw), pickupLocationData. The backend
|
|
3479
|
+
// does not return these to buyers \u2014 if you see them in a type, they're
|
|
3480
|
+
// an oversight; still skip them.
|
|
3481
|
+
import { client } from './brainerce';
|
|
3482
|
+
import type { Order, OrderItem, OrderStatusChange } from 'brainerce';
|
|
3483
|
+
|
|
3484
|
+
const { data: orders } = await client.getMyOrders({ page: 1, limit: 10 });
|
|
3485
|
+
|
|
3486
|
+
for (const order of orders) {
|
|
3487
|
+
// Line items + per-item customizations
|
|
3488
|
+
for (const item of order.items) {
|
|
3489
|
+
// item.image, item.productName, item.quantity, item.price
|
|
3490
|
+
if (item.customizations) {
|
|
3491
|
+
for (const [fieldId, entry] of Object.entries(item.customizations)) {
|
|
3492
|
+
// entry = { label, value, type }
|
|
3493
|
+
// Type-aware render (see account-page section in get-sdk-docs):
|
|
3494
|
+
// TEXT / TEXTAREA / URL / NUMBER / SELECT \u2014 plain text
|
|
3495
|
+
// BOOLEAN \u2014 \u2713 / \u2717
|
|
3496
|
+
// MULTI_SELECT \u2014 comma-separated
|
|
3497
|
+
// IMAGE \u2014 <img src={value}>
|
|
3498
|
+
// GALLERY \u2014 wrap grid of <img>
|
|
3499
|
+
// COLOR \u2014 swatch + hex
|
|
3500
|
+
// DATE / DATETIME \u2014 localized format
|
|
3501
|
+
}
|
|
3502
|
+
}
|
|
3503
|
+
}
|
|
3504
|
+
|
|
3505
|
+
// Status timeline \u2014 skip silently when null/empty
|
|
3506
|
+
if (order.statusHistory?.length) {
|
|
3507
|
+
for (const entry of order.statusHistory as OrderStatusChange[]) {
|
|
3508
|
+
// entry = { status, at, note? }
|
|
3509
|
+
// Render a dot + localized status label + new Date(entry.at).toLocaleString()
|
|
3510
|
+
}
|
|
3511
|
+
}
|
|
3512
|
+
|
|
3513
|
+
// Shipping + tracking
|
|
3514
|
+
if (order.shippingAddress) {
|
|
3515
|
+
// Render firstName lastName \xB7 line1 \xB7 line2 \xB7 city, region \xB7 postalCode \xB7 country
|
|
3516
|
+
}
|
|
3517
|
+
if (order.trackingNumber) {
|
|
3518
|
+
// Render carrier \xB7 trackingNumber, shippedAt/deliveredAt dates,
|
|
3519
|
+
// and an anchor to order.trackingUrl when present.
|
|
3520
|
+
}
|
|
3521
|
+
|
|
3522
|
+
// Payment
|
|
3523
|
+
if (order.paymentMethod || order.financialStatus) {
|
|
3524
|
+
// paymentMethod: 'card' | 'paypal' | 'bank_transfer' | 'cash_on_delivery' | ...
|
|
3525
|
+
// financialStatus: 'pending' | 'paid' | 'refunded' | 'partially_refunded' | 'voided'
|
|
3526
|
+
// Map financialStatus \u2192 a colored badge.
|
|
3527
|
+
}
|
|
3528
|
+
}
|
|
3529
|
+
|
|
3530
|
+
// All sections above are conditional. Absent data = section not rendered \u2014
|
|
3531
|
+
// never show empty placeholders. The create-brainerce-store template's
|
|
3532
|
+
// src/components/account/order-history.tsx is the reference implementation.`
|
|
2737
3533
|
};
|
|
2738
3534
|
async function handleGetCodeExample(args) {
|
|
2739
3535
|
const snippet = SNIPPETS[args.operation];
|
|
@@ -3199,7 +3995,7 @@ var RULES = {
|
|
|
3199
3995
|
- All prices are STRINGS in the SDK. \`parseFloat\` them before math or comparisons.
|
|
3200
3996
|
- CartItem and CheckoutLineItem are NESTED (\`item.product.name\`, \`item.unitPrice\`). OrderItem is FLAT (\`item.name\`, \`item.price\`). They are not interchangeable.
|
|
3201
3997
|
- Cart has no \`.total\` field \u2014 call \`getCartTotals(cart)\` to get \`{ subtotal, tax, shipping, discount, total }\`.
|
|
3202
|
-
- \`smartGetCart()\` returns
|
|
3998
|
+
- \`smartGetCart()\` returns \`CartWithIncludes\` (extends \`Cart\`). Pass \`{ include: ['recommendations', 'upgrades', 'bundles'] }\` to fetch extras in one request.
|
|
3203
3999
|
- \`startGuestCheckout()\` is also a discriminated union. Check \`result.tracked\` before reading \`result.checkoutId\`.`
|
|
3204
4000
|
}
|
|
3205
4001
|
};
|
|
@@ -3237,6 +4033,7 @@ var GET_BUSINESS_FLOWS_SCHEMA = {
|
|
|
3237
4033
|
"order-confirmation",
|
|
3238
4034
|
"cart-persistence",
|
|
3239
4035
|
"inventory-reservation",
|
|
4036
|
+
"product-customization",
|
|
3240
4037
|
"all"
|
|
3241
4038
|
]).describe('Which flow to retrieve. Use "all" to get every flow.')
|
|
3242
4039
|
};
|
|
@@ -3356,7 +4153,7 @@ Build the OAuth button region AND the callback handler even when no providers ar
|
|
|
3356
4153
|
- **Reads:** \`client.getCart()\` returns the current cart. Call it on mount in your cart UI and on any page that shows a cart count (header).
|
|
3357
4154
|
- **Writes:** use \`client.addToCart\`, \`client.updateCartItem\`, \`client.removeCartItem\`, \`client.applyCoupon\`, \`client.removeCoupon\`. After each mutation the SDK returns the updated cart.
|
|
3358
4155
|
- **Totals:** call \`getCartTotals(cart)\` \u2014 do NOT read \`cart.total\`. The helper understands taxes, shipping, and discounts.
|
|
3359
|
-
- **\`smartGetCart()\`** returns \`
|
|
4156
|
+
- **\`smartGetCart()\`** returns \`CartWithIncludes\` (extends \`Cart\`). All carts are server-side. Pass \`{ include: ['recommendations', 'upgrades', 'bundles'] }\` to fetch extras in one request.
|
|
3360
4157
|
- **NEVER mutate cart state outside SDK helpers.** Any hand-rolled cart update risks desync with the reservation timer and the checkout flow.`
|
|
3361
4158
|
},
|
|
3362
4159
|
"inventory-reservation": {
|
|
@@ -3370,6 +4167,54 @@ Build the OAuth button region AND the callback handler even when no providers ar
|
|
|
3370
4167
|
- **On the cart page:** show per-item availability \u2014 items that can no longer be purchased (because their reservation expired or the stock dropped) should display an "out of stock" badge and the "proceed to checkout" action should be disabled until they are removed.
|
|
3371
4168
|
|
|
3372
4169
|
The reservation strategy (\`HARD\` vs \`SOFT\`) is exposed via \`get-store-capabilities\`. A HARD reservation means the stock is physically held; a SOFT reservation just tracks intent. Your UI behaves identically either way \u2014 the SDK hides the difference.`
|
|
4170
|
+
},
|
|
4171
|
+
"product-customization": {
|
|
4172
|
+
title: "Product customization (buyer input)",
|
|
4173
|
+
body: `Products can ship with \`customizationFields: ProductCustomizationField[]\` \u2014 buyer-filled inputs (engraving text, uploaded photo, pick-a-color, etc.). If you ignore them, merchants lose the data they need to fulfill the order.
|
|
4174
|
+
|
|
4175
|
+
1. **Read the fields** from the product payload. Sort by \`position\`. If the array is empty, nothing to render.
|
|
4176
|
+
2. **Render one control per field** based on \`type\`:
|
|
4177
|
+
- \`TEXT\` / \`URL\` / \`COLOR\` / \`DIMENSION\` / \`WEIGHT\` \u2192 \`<input type="text">\` (honour \`minLength\`/\`maxLength\`)
|
|
4178
|
+
- \`TEXTAREA\` \u2192 \`<textarea>\`
|
|
4179
|
+
- \`NUMBER\` \u2192 \`<input type="number">\` (honour \`minValue\`/\`maxValue\`)
|
|
4180
|
+
- \`BOOLEAN\` \u2192 checkbox (value \`true\`/\`false\`)
|
|
4181
|
+
- \`DATE\` \u2192 \`<input type="date">\` (ISO \`YYYY-MM-DD\`)
|
|
4182
|
+
- \`DATETIME\` \u2192 \`<input type="datetime-local">\` (ISO timestamp)
|
|
4183
|
+
- \`SELECT\` \u2192 \`<select>\` populated from \`enumValues\` (value = one string)
|
|
4184
|
+
- \`MULTI_SELECT\` \u2192 checkbox group from \`enumValues\` (value = \`string[]\`)
|
|
4185
|
+
- \`IMAGE\` \u2192 file input + preview (value = one URL string)
|
|
4186
|
+
- \`GALLERY\` \u2192 multi-file input (value = \`string[]\` of URLs)
|
|
4187
|
+
- \`JSON\` \u2192 advanced; render an admin-style editor or skip unless you control the data
|
|
4188
|
+
3. **For IMAGE / GALLERY types: upload FIRST, then attach the URL.** Call \`client.uploadCustomizationFile(file)\` \u2014 it returns \`{ url }\`. Put that \`url\` string into the field value. NEVER put a \`File\` object in cart metadata.
|
|
4189
|
+
4. **Enforce \`required: true\` client-side** before add-to-cart \u2014 show a red hint, block submit. The server re-validates; you want the user to fix it before the request fails.
|
|
4190
|
+
5. **Add to cart with metadata keyed by \`field.key\`:**
|
|
4191
|
+
\`\`\`ts
|
|
4192
|
+
await client.addToCart({
|
|
4193
|
+
productId,
|
|
4194
|
+
quantity: 1,
|
|
4195
|
+
metadata: {
|
|
4196
|
+
engraving_text: 'For Mom',
|
|
4197
|
+
frame_color: 'Gold',
|
|
4198
|
+
upload_photo: photoUrl, // from uploadCustomizationFile()
|
|
4199
|
+
addons: ['Gift wrap'], // MULTI_SELECT
|
|
4200
|
+
},
|
|
4201
|
+
});
|
|
4202
|
+
\`\`\`
|
|
4203
|
+
6. **On cart / checkout UIs, surface the metadata.** \`CartItem.metadata\` and \`CheckoutLineItem.metadata\` carry the values the buyer submitted. Show them in the line-item row so the buyer can verify before paying (especially uploaded image thumbnails).
|
|
4204
|
+
7. **After the order is placed, values live on \`OrderItem.customizations\`** \u2014 a \`Record<string, { label, value, type }>\` keyed by field key. Definitions may be renamed/deleted after the order; the snapshot preserves what the buyer saw at purchase time.
|
|
4205
|
+
|
|
4206
|
+
**Apply-to-all fields.** A merchant can flag a \`MetafieldDefinition\` with \`appliesToAllProducts: true\` \u2014 the backend then includes it in every product's \`customizationFields\` array automatically, including products created after the flag was set. Your client code reads \`product.customizationFields\` as-is and never merges or unions anything \u2014 just render what's there.
|
|
4207
|
+
|
|
4208
|
+
Server-side guardrails that WILL reject bad requests (so validate client-side to avoid round-trips):
|
|
4209
|
+
- Unknown keys \u2192 rejected. Only use keys that appear in \`product.customizationFields\`.
|
|
4210
|
+
- Missing \`required\` fields \u2192 rejected.
|
|
4211
|
+
- \`SELECT\` value not in \`enumValues\` \u2192 rejected.
|
|
4212
|
+
- \`MULTI_SELECT\` value not \`string[]\` OR containing values outside \`enumValues\` \u2192 rejected.
|
|
4213
|
+
- \`IMAGE\` / \`GALLERY\` values must be URLs returned from \`/customization-upload\` on this store \u2014 pasting an external URL is rejected.
|
|
4214
|
+
- Upload > 5MB or non-image MIME \u2192 rejected by upload endpoint.
|
|
4215
|
+
- More than 10 uploads per IP per minute \u2192 429.
|
|
4216
|
+
|
|
4217
|
+
Never render customization fields without also wiring the upload + metadata flow \u2014 a form that submits nothing is worse than no form at all.`
|
|
3373
4218
|
}
|
|
3374
4219
|
};
|
|
3375
4220
|
var FLOW_ORDER = [
|
|
@@ -3380,7 +4225,8 @@ var FLOW_ORDER = [
|
|
|
3380
4225
|
"oauth",
|
|
3381
4226
|
"order-confirmation",
|
|
3382
4227
|
"cart-persistence",
|
|
3383
|
-
"inventory-reservation"
|
|
4228
|
+
"inventory-reservation",
|
|
4229
|
+
"product-customization"
|
|
3384
4230
|
];
|
|
3385
4231
|
async function handleGetBusinessFlows(args) {
|
|
3386
4232
|
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.";
|
|
@@ -3445,6 +4291,14 @@ var FEATURES = [
|
|
|
3445
4291
|
sdk: "client.getProductBySlug(slug). Helpers: getProductPriceInfo, getVariantPrice, getStockStatus, getVariantOptions, getProductSwatches, getDescriptionContent, getProductMetafieldValue.",
|
|
3446
4292
|
mandatory: "mandatory"
|
|
3447
4293
|
},
|
|
4294
|
+
{
|
|
4295
|
+
id: "product-customization-fields",
|
|
4296
|
+
title: "Render buyer-input customization fields on the product page",
|
|
4297
|
+
description: "When a product ships with `customizationFields` (engraving text, uploaded photo, picked color, date, select / multi-select), render one control per field sorted by `position`. Enforce required + enumValues + min/max client-side. For IMAGE / GALLERY, upload via client.uploadCustomizationFile() and place the returned URL in the value. Submit all values keyed by `field.key` inside addToCart({ metadata }). Show the metadata on cart / checkout rows so the buyer can verify. Build the UI anyway \u2014 it auto-hides when a product has no customization fields. NOTE: merchants can flag a definition with `appliesToAllProducts: true`; the backend folds those into every product's `customizationFields` array automatically \u2014 the client never merges or unions anything, just reads `product.customizationFields` as-is.",
|
|
4298
|
+
sdk: "product.customizationFields, client.uploadCustomizationFile(file), client.addToCart({ productId, quantity, metadata })",
|
|
4299
|
+
flowRef: "product-customization",
|
|
4300
|
+
mandatory: "mandatory"
|
|
4301
|
+
},
|
|
3448
4302
|
{
|
|
3449
4303
|
id: "cart",
|
|
3450
4304
|
title: "Manage a cart with quantity, removal, and totals",
|