@brainerce/mcp-server 3.7.0 → 3.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/http.js +833 -57
- package/dist/bin/stdio.js +667 -33
- package/dist/index.d.mts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +667 -33
- package/dist/index.mjs +667 -33
- package/package.json +1 -1
package/dist/bin/http.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
// src/bin/http.ts
|
|
5
5
|
var import_node_http = require("http");
|
|
6
|
+
var import_node_crypto = require("crypto");
|
|
6
7
|
var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
|
|
7
8
|
var import_sse = require("@modelcontextprotocol/sdk/server/sse.js");
|
|
8
9
|
|
|
@@ -1155,6 +1156,8 @@ const material = getProductMetafieldValue(product, 'material');
|
|
|
1155
1156
|
|
|
1156
1157
|
**Metafield fields:** \`definitionName\` (display label), \`definitionKey\` (lookup key), \`value\`, \`type\` (IMAGE, GALLERY, URL, COLOR, BOOLEAN, DATE, DATETIME, TEXT, TEXTAREA, NUMBER, DIMENSION, WEIGHT, JSON)
|
|
1157
1158
|
|
|
1159
|
+
**Translations:** When the store has i18n enabled and \`client.setLocale()\` is active, both the \`definitionName\` (the merchant-authored label like "Warranty Info" / "\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D7\u05E8\u05D9\u05D5\u05EA") **and** free-text \`value\` come back already translated. No per-call locale param needed.
|
|
1160
|
+
|
|
1158
1161
|
### Product Customization Fields (Customer Input)
|
|
1159
1162
|
|
|
1160
1163
|
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.
|
|
@@ -1288,6 +1291,8 @@ await client.removeCoupon(cartId);
|
|
|
1288
1291
|
const totals = getCartTotals(cart); // { subtotal, discount, shipping, total }
|
|
1289
1292
|
\`\`\`
|
|
1290
1293
|
|
|
1294
|
+
> **Region-restricted coupons:** a coupon may carry \`regionIds\`. If the buyer's checkout region isn't in that list, \`applyCoupon\` / \`applyCheckoutCoupon\` reject the code even when everything else matches. Empty/omitted \`regionIds\` = valid in all regions.
|
|
1295
|
+
|
|
1291
1296
|
**On the checkout page** (after checkout session exists \u2014 ALWAYS use this when checkoutId is available):
|
|
1292
1297
|
\`\`\`typescript
|
|
1293
1298
|
// Applies to cart AND updates checkout totals in one call
|
|
@@ -1615,6 +1620,8 @@ const groups: ModifierGroup[] = product.modifierGroups ?? [];
|
|
|
1615
1620
|
|
|
1616
1621
|
**Money fields are strings.** \`priceDelta\` is \`"5.00"\` (or \`"-2.00"\` for downsell modifiers \u2014 see below). Use \`parseFloat()\` for display arithmetic; never compute the line total client-side \u2014 the server runs the free-allocation policy and returns the final \`unitPrice\` snapshot on the cart line.
|
|
1617
1622
|
|
|
1623
|
+
**Translations are automatic.** Both \`group.name\`/\`group.description\` and each \`modifier.name\`/\`modifier.description\` are overlay-resolved by the server on every read. Call \`client.setLocale('he')\` once and the modifier picker renders in Hebrew with no extra code (\`"\u05EA\u05D5\u05E1\u05E4\u05D5\u05EA"\` / \`"\u05D6\u05D9\u05EA\u05D9\u05DD"\`). See the \`i18n\` topic for the full multi-language flow.
|
|
1624
|
+
|
|
1618
1625
|
### Render: SINGLE \u2192 radio, MULTIPLE \u2192 checkbox
|
|
1619
1626
|
|
|
1620
1627
|
Walk \`groups\` and pick the input type by \`selectionType\`. Sort modifiers by \`position\`.
|
|
@@ -2016,19 +2023,24 @@ window.location.href = authorizationUrl;
|
|
|
2016
2023
|
\`\`\`typescript
|
|
2017
2024
|
const params = new URLSearchParams(window.location.search);
|
|
2018
2025
|
if (params.get('oauth_success') === 'true') {
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2026
|
+
// Single-use auth_code is exchanged for the JWT via POST \u2014 keeps the JWT
|
|
2027
|
+
// out of the URL (browser history, CDN logs, Referer header).
|
|
2028
|
+
const code = params.get('auth_code');
|
|
2029
|
+
if (code) {
|
|
2030
|
+
const result = await client.exchangeOAuthCode(code);
|
|
2031
|
+
client.setCustomerToken(result.token);
|
|
2032
|
+
localStorage.setItem('customerToken', result.token);
|
|
2033
|
+
// Optional: result.customer, result.isNewCustomer, result.redirectUrl
|
|
2024
2034
|
// Link guest cart: await client.linkCart(cartId);
|
|
2025
|
-
window.location.href = '/account';
|
|
2035
|
+
window.location.href = result.redirectUrl || '/account';
|
|
2026
2036
|
}
|
|
2027
2037
|
} else if (params.get('oauth_error')) {
|
|
2028
2038
|
// Show error: params.get('oauth_error')
|
|
2029
2039
|
}
|
|
2030
2040
|
\`\`\`
|
|
2031
2041
|
|
|
2042
|
+
> The legacy redirect format placed the JWT directly in the URL as \`?token=\`. That format is still emitted for backward compatibility, but it will be removed in the next major release \u2014 migrate to \`auth_code\` + \`exchangeOAuthCode()\` now.
|
|
2043
|
+
|
|
2032
2044
|
### Account Page (/account) \u2014 uses getMyProfile() and getMyOrders()
|
|
2033
2045
|
|
|
2034
2046
|
\`\`\`typescript
|
|
@@ -2202,9 +2214,12 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
|
|
2202
2214
|
const client = getServerClient();
|
|
2203
2215
|
client.setLocale(locale);
|
|
2204
2216
|
const product = await client.getProductBySlug(slug);
|
|
2217
|
+
// NEVER feed raw HTML into <meta name="description"> \u2014 product.description
|
|
2218
|
+
// is often rich-text HTML. Strip tags first, then truncate on a word
|
|
2219
|
+
// boundary. See buildMetaDescription() in lib/seo.ts.
|
|
2205
2220
|
return {
|
|
2206
2221
|
title: product.seoTitle || product.name,
|
|
2207
|
-
description: product.seoDescription || product.description
|
|
2222
|
+
description: product.seoDescription || buildMetaDescription(product.description) || product.name,
|
|
2208
2223
|
};
|
|
2209
2224
|
}
|
|
2210
2225
|
\`\`\`
|
|
@@ -2254,7 +2269,17 @@ overlay needed:
|
|
|
2254
2269
|
- \`variants[].name\`
|
|
2255
2270
|
- \`variant.attributes\` keys and values \u2014 \`getVariantOptions(variant)\` returns translated attribute names and option values automatically
|
|
2256
2271
|
- \`productAttributeOptions[].attribute.name\`, \`attributeOption.name\`
|
|
2257
|
-
- \`metafields[].value\`
|
|
2272
|
+
- \`metafields[].value\` (the free-text values customers submit)
|
|
2273
|
+
- \`metafields[].definition.name\`, \`metafields[].definition.description\` (the merchant-authored custom-field labels \u2014 "Warranty Info" / "\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D7\u05E8\u05D9\u05D5\u05EA")
|
|
2274
|
+
- \`modifierGroups[].name\`, \`modifierGroups[].description\` (the group label shown on the PDP \u2014 e.g. "Toppings" / "\u05EA\u05D5\u05E1\u05E4\u05D5\u05EA")
|
|
2275
|
+
- \`modifierGroups[].modifiers[].name\`, \`modifierGroups[].modifiers[].description\` (each individual modifier \u2014 e.g. "Olives" / "\u05D6\u05D9\u05EA\u05D9\u05DD")
|
|
2276
|
+
|
|
2277
|
+
**Promotional surfaces:**
|
|
2278
|
+
- \`cart.bundles[].name\`, \`cart.bundles[].description\` (the bundle's own merchant-typed label, e.g. "Lunch Combo" / "\u05D0\u05E8\u05D5\u05D7\u05EA \u05E6\u05D4\u05E8\u05D9\u05D9\u05DD")
|
|
2279
|
+
- \`cart.bundles[].offeredProducts[].name\`, \`.slug\` (each product inside the bundle \u2014 fetched fresh from \`Product.translations\`)
|
|
2280
|
+
- \`checkout.bumps[].title\`, \`checkout.bumps[].description\` (the bump headline shown at checkout \u2014 falls back to the translated product name when merchant didn't override)
|
|
2281
|
+
- \`checkout.bumps[].bumpProduct.name\`, \`.slug\` (the underlying product)
|
|
2282
|
+
- Discount-rule names/descriptions (when surfaced as banner text via \`displayConfig\`)
|
|
2258
2283
|
|
|
2259
2284
|
**Taxonomy (\`getCategories\`, \`getBrands\`, \`getTags\`):**
|
|
2260
2285
|
- \`name\` on each item
|
|
@@ -2320,11 +2345,25 @@ Because the backend already overlays everything, UI code is just:
|
|
|
2320
2345
|
|
|
2321
2346
|
### RTL handling
|
|
2322
2347
|
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2348
|
+
Resolve direction with \`client.getStoreDirection(locale)\` \u2014 it returns
|
|
2349
|
+
\`'ltr' | 'rtl'\` for any BCP-47 tag (Arabic, Hebrew, Persian, Urdu, Yiddish
|
|
2350
|
+
today; future RTL locales added by the platform are picked up automatically).
|
|
2351
|
+
Do NOT maintain your own RTL locale set.
|
|
2352
|
+
|
|
2353
|
+
\`\`\`tsx
|
|
2354
|
+
// app/[locale]/layout.tsx
|
|
2355
|
+
const dir = client.getStoreDirection(locale);
|
|
2356
|
+
return <html lang={locale} dir={dir}>...</html>;
|
|
2357
|
+
\`\`\`
|
|
2358
|
+
|
|
2359
|
+
For static rendering, \`storeInfo.i18n.defaultDirection\` carries the store's
|
|
2360
|
+
default direction, and each entry in \`storeInfo.i18n.supportedLocaleObjects\`
|
|
2361
|
+
includes its own \`direction\`.
|
|
2362
|
+
|
|
2363
|
+
Let flexbox reverse automatically once \`<html dir="rtl">\` is set. Do NOT add
|
|
2364
|
+
\`flex-row-reverse\` on top \u2014 that's a double-swap. DO swap directional icons
|
|
2365
|
+
(chevrons, arrows) manually. Use logical CSS properties (\`ms-*\`/\`me-*\`)
|
|
2366
|
+
instead of \`ml-*\`/\`mr-*\`.
|
|
2328
2367
|
|
|
2329
2368
|
### Language switcher
|
|
2330
2369
|
|
|
@@ -2342,7 +2381,9 @@ const admin = new BrainerceClient({ apiKey: 'brainerce_...' });
|
|
|
2342
2381
|
|
|
2343
2382
|
// Taxonomy: listCategories(), listBrands(), listTags(), listAttributes()
|
|
2344
2383
|
// Shipping: listShippingZones(), createZoneShippingRate()
|
|
2345
|
-
// Tax: getTaxRates(), createTaxRate()
|
|
2384
|
+
// Tax: getTaxRates(), createTaxRate() \u2014 a rate may target a tax class via taxClassId
|
|
2385
|
+
// Tax classes: getTaxClasses(), createTaxClass(), assignTaxClass(), mergeTaxClasses() (scope tax-classes:*)
|
|
2386
|
+
// Regions: getRegions(), createRegion(), setDefaultRegion(), updateRegionPaymentProviders() (scope regions:*)
|
|
2346
2387
|
// Metafields: getMetafieldDefinitions(), setProductMetafield()
|
|
2347
2388
|
// Team: getTeamMembers(), inviteTeamMember()
|
|
2348
2389
|
// Email: getEmailTemplates(), createEmailTemplate()
|
|
@@ -2350,6 +2391,13 @@ const admin = new BrainerceClient({ apiKey: 'brainerce_...' });
|
|
|
2350
2391
|
// OAuth: getOAuthProviders(), configureOAuthProvider()
|
|
2351
2392
|
\`\`\`
|
|
2352
2393
|
|
|
2394
|
+
Store-level team management (\`inviteStoreMember\`, \`updateStoreMember\`) is the
|
|
2395
|
+
canonical replacement for the deprecated account-level helpers above. The
|
|
2396
|
+
invite accepts an optional \`salesChannelIds\` (vibe-coded \`connectionId\`s,
|
|
2397
|
+
\`vc_*\`) to restrict a member to specific channels \u2014 omit or pass \`[]\` for all
|
|
2398
|
+
channels. Use \`updateStoreMemberSalesChannels(storeId, memberId, { salesChannelIds })\`
|
|
2399
|
+
to change that scope later.
|
|
2400
|
+
|
|
2353
2401
|
### Per-Channel Publishing
|
|
2354
2402
|
|
|
2355
2403
|
Categories, tags, brands, and metafield definitions are gated to specific
|
|
@@ -2381,7 +2429,70 @@ calls fail with \`404 Not Found\`.
|
|
|
2381
2429
|
|
|
2382
2430
|
The vibe-coded read endpoints (used by storefront SDK calls in \`connectionId\`
|
|
2383
2431
|
mode) automatically filter by these junction tables, so storefronts never see
|
|
2384
|
-
entities that weren't published to their site
|
|
2432
|
+
entities that weren't published to their site.
|
|
2433
|
+
|
|
2434
|
+
### Tax classes (differential tax rates)
|
|
2435
|
+
|
|
2436
|
+
Charge different rates for different product types. A \`TaxRate\` may target a
|
|
2437
|
+
class via \`taxClassId\`; a rate with \`taxClassId: null\` is the **Standard
|
|
2438
|
+
fallback**. Checkout resolves each line's class **variant \u2192 product \u2192 category
|
|
2439
|
+
\u2192 store default \u2192 null**, then picks the matching rate (Standard if none).
|
|
2440
|
+
\`rate\` is a whole percentage (\`7.25\` = 7.25%). Requires the
|
|
2441
|
+
\`tax-classes:read\` / \`tax-classes:write\` scopes.
|
|
2442
|
+
|
|
2443
|
+
\`\`\`typescript
|
|
2444
|
+
const food = await admin.createTaxClass({ name: 'Food', slug: 'food' });
|
|
2445
|
+
await admin.assignTaxClass(food.id, { productIds: ['prod_1'], categoryIds: ['cat_food'] });
|
|
2446
|
+
|
|
2447
|
+
// class-specific rate \u2014 only food lines use it; everything else uses Standard
|
|
2448
|
+
await admin.createTaxRate({ name: 'VAT (Food)', rate: 0, country: 'GB', taxClassId: food.id });
|
|
2449
|
+
|
|
2450
|
+
// delete is blocked (409) while dependents exist \u2014 merge moves FKs then deletes:
|
|
2451
|
+
await admin.mergeTaxClasses(food.id, standardClassId);
|
|
2452
|
+
\`\`\`
|
|
2453
|
+
|
|
2454
|
+
Storefront (public, no apiKey \u2014 \`storeId\` mode): \`getStoreTaxClasses()\` lists
|
|
2455
|
+
the store's classes (storefront-safe fields only) for a transparency badge.
|
|
2456
|
+
|
|
2457
|
+
### Regions (multi-currency / per-region providers)
|
|
2458
|
+
|
|
2459
|
+
A region binds countries \u2192 currency + tax-display mode + enabled payment
|
|
2460
|
+
providers. Manage them via the SDK (scopes \`regions:read\` / \`regions:write\`).
|
|
2461
|
+
\`detectRegion\` is a pure client-side helper to map a buyer's country to a
|
|
2462
|
+
region; pass the resolved \`regionId\` to \`createCheckout\` to associate the
|
|
2463
|
+
checkout with a region (recorded for reporting + provider scoping; currency
|
|
2464
|
+
follows the cart until FX price conversion lands).
|
|
2465
|
+
|
|
2466
|
+
\`\`\`typescript
|
|
2467
|
+
const eu = await admin.createRegion({
|
|
2468
|
+
name: 'EU', currency: 'EUR', countries: ['DE', 'FR'],
|
|
2469
|
+
taxInclusive: true, paymentProviderIds: ['app_inst_stripe'],
|
|
2470
|
+
});
|
|
2471
|
+
await admin.setDefaultRegion(eu.id);
|
|
2472
|
+
|
|
2473
|
+
const { data: regions } = await admin.getRegions();
|
|
2474
|
+
const region = admin.detectRegion('DE', regions); // \u2192 eu, else default, else null
|
|
2475
|
+
\`\`\`
|
|
2476
|
+
|
|
2477
|
+
Storefront (public, no apiKey \u2014 \`storeId\` mode): \`getStoreRegions()\` lists
|
|
2478
|
+
active regions, \`getStoreRegion(id)\` returns one region + its payment providers.
|
|
2479
|
+
Pair with \`detectRegion\` to pick the buyer's region for currency display.
|
|
2480
|
+
|
|
2481
|
+
\`\`\`typescript
|
|
2482
|
+
const store = new BrainerceClient({ storeId: 'store_123' });
|
|
2483
|
+
const { data: regions } = await store.getStoreRegions();
|
|
2484
|
+
const region = await store.getStoreRegion(regions[0].id);
|
|
2485
|
+
\`\`\`
|
|
2486
|
+
|
|
2487
|
+
A shipping zone can be limited to regions via \`regionIds\` \u2014 the zone is then
|
|
2488
|
+
only offered to checkouts that resolved to one of those regions. Empty/omitted =
|
|
2489
|
+
available for any region (default); each id must belong to the same store.
|
|
2490
|
+
|
|
2491
|
+
\`\`\`typescript
|
|
2492
|
+
await admin.createShippingZone({
|
|
2493
|
+
name: 'EU Express', countries: ['DE', 'FR', 'IT'], regionIds: [eu.id],
|
|
2494
|
+
});
|
|
2495
|
+
\`\`\``;
|
|
2385
2496
|
}
|
|
2386
2497
|
function getContactInquiriesSection() {
|
|
2387
2498
|
return `## Contact Inquiries & Forms (optional)
|
|
@@ -2701,6 +2812,141 @@ and a \`newsletter\` form embedded in the footer), render each form from its
|
|
|
2701
2812
|
own \`contactForms.get(key, locale)\` call. The \`formKey\` you pass to
|
|
2702
2813
|
\`createInquiry\` must match.`;
|
|
2703
2814
|
}
|
|
2815
|
+
function getContentSection() {
|
|
2816
|
+
return `## Content \u2014 typed merchant content store
|
|
2817
|
+
|
|
2818
|
+
Brainerce ships a typed content store so merchants can edit site chrome, FAQ,
|
|
2819
|
+
static pages, and inline rich-text blocks in the dashboard \u2014 without
|
|
2820
|
+
re-prompting the AI that built their storefront. Every row has a \`type\` +
|
|
2821
|
+
\`key\` + typed \`data\` payload + free-form \`customFields\`.
|
|
2822
|
+
|
|
2823
|
+
**Six content types.** Each one has a fixed \`data\` shape; the SDK's TypeScript
|
|
2824
|
+
generics keep them in lockstep:
|
|
2825
|
+
|
|
2826
|
+
| Type | Use for | \`data\` shape (abbreviated) |
|
|
2827
|
+
| -------------- | -------------------------------------- | --------------------------- |
|
|
2828
|
+
| \`FAQ\` | Q/A accordions | \`{ items: { question, answer }[] }\` |
|
|
2829
|
+
| \`FOOTER\` | Site footer (chrome) | \`{ columns, copyright?, social? }\` |
|
|
2830
|
+
| \`HEADER\` | Top nav + logo + CTA (chrome) | \`{ logo?, navItems, cta? }\` |
|
|
2831
|
+
| \`ANNOUNCEMENT\`| Banners; time-bound by \`startsAt/endsAt\` | \`{ message, severity, dismissible, ... }\` |
|
|
2832
|
+
| \`RICH_TEXT\` | Free-form HTML blocks embedded inline | \`{ html }\` |
|
|
2833
|
+
| \`PAGE\` | Static pages with slug + SEO | \`{ slug, title, html, seo? }\` |
|
|
2834
|
+
|
|
2835
|
+
Run \`get-type-definitions\` with \`domain: 'content'\` for the full interfaces.
|
|
2836
|
+
|
|
2837
|
+
### Default key
|
|
2838
|
+
|
|
2839
|
+
Every type has \`'main'\` as its universal default key. \`client.content.faq.get()\`
|
|
2840
|
+
with no arguments resolves to \`key='main'\`. Topical keys (\`'shipping'\`,
|
|
2841
|
+
\`'holiday-2026'\`, \`'about'\`) are merchant-named.
|
|
2842
|
+
|
|
2843
|
+
### Reading content (any SDK mode)
|
|
2844
|
+
|
|
2845
|
+
Public reads work in vibe-coded mode, storefront mode, and admin mode. They
|
|
2846
|
+
return \`null\` on 404 \u2014 render hard-coded fallbacks so the page never crashes
|
|
2847
|
+
when the merchant hasn't seeded yet.
|
|
2848
|
+
|
|
2849
|
+
\`\`\`ts
|
|
2850
|
+
// Single entry, default key 'main', resolved to a locale
|
|
2851
|
+
const faq = await client.content.faq.get('main', locale);
|
|
2852
|
+
if (faq) {
|
|
2853
|
+
faq.data.items.forEach(({ question, answer }) => {
|
|
2854
|
+
// Render question + sanitize(answer)
|
|
2855
|
+
});
|
|
2856
|
+
}
|
|
2857
|
+
|
|
2858
|
+
// All entries of a type
|
|
2859
|
+
const allFaqs = await client.content.faq.list(locale);
|
|
2860
|
+
|
|
2861
|
+
// Page by URL slug \u2014 for app/[slug]/page.tsx
|
|
2862
|
+
const page = await client.content.page.getBySlug(slug, locale);
|
|
2863
|
+
if (!page) notFound();
|
|
2864
|
+
\`\`\`
|
|
2865
|
+
|
|
2866
|
+
### Security \u2014 sanitize HTML before rendering
|
|
2867
|
+
|
|
2868
|
+
\`FAQ.items[i].answer\`, \`RICH_TEXT.html\`, and \`PAGE.html\` carry
|
|
2869
|
+
MERCHANT-AUTHORED HTML. The server does NOT pre-sanitize \u2014 some merchants
|
|
2870
|
+
embed iframes (e.g. YouTube) which strict sanitizers would strip. ALWAYS
|
|
2871
|
+
sanitize on the storefront before injecting:
|
|
2872
|
+
|
|
2873
|
+
\`\`\`ts
|
|
2874
|
+
// Recommended: isomorphic-dompurify
|
|
2875
|
+
import DOMPurify from 'isomorphic-dompurify';
|
|
2876
|
+
const safe = DOMPurify.sanitize(rawHtml);
|
|
2877
|
+
<div dangerouslySetInnerHTML={{ __html: safe }} />;
|
|
2878
|
+
\`\`\`
|
|
2879
|
+
|
|
2880
|
+
Skipping this is XSS.
|
|
2881
|
+
|
|
2882
|
+
### Custom fields
|
|
2883
|
+
|
|
2884
|
+
Every Content row carries a free-form \`customFields: Record<string, string>\`.
|
|
2885
|
+
Merchants add arbitrary key-value extras (\`helpEmail\`, \`phoneNumber\`,
|
|
2886
|
+
\`foundedYear\`) that you can opt into reading:
|
|
2887
|
+
|
|
2888
|
+
\`\`\`ts
|
|
2889
|
+
const faq = await client.content.faq.get('shipping');
|
|
2890
|
+
<a href={\`mailto:\${faq.customFields.helpEmail}\`}>Need help?</a>
|
|
2891
|
+
\`\`\`
|
|
2892
|
+
|
|
2893
|
+
The shape is whatever the merchant entered. Read keys you expect; ignore the rest.
|
|
2894
|
+
|
|
2895
|
+
### Locale resolution
|
|
2896
|
+
|
|
2897
|
+
All public reads accept a \`locale\` argument. The server resolves
|
|
2898
|
+
\`translations[locale]\` server-side and returns the resolved \`data\` payload \u2014
|
|
2899
|
+
the storefront does NOT need to do its own overlay. Empty / missing translations
|
|
2900
|
+
fall through to the default-locale value.
|
|
2901
|
+
|
|
2902
|
+
### Cache
|
|
2903
|
+
|
|
2904
|
+
Public reads carry \`Cache-Control: public, max-age=300, stale-while-revalidate=60\`.
|
|
2905
|
+
Merchant edits propagate within ~5 minutes. Don't layer extra client-side
|
|
2906
|
+
caching beyond Next.js's default fetch cache.
|
|
2907
|
+
|
|
2908
|
+
### Admin writes (apiKey mode)
|
|
2909
|
+
|
|
2910
|
+
\`\`\`ts
|
|
2911
|
+
const adminClient = new BrainerceClient({ apiKey: process.env.BRAINERCE_API_KEY });
|
|
2912
|
+
|
|
2913
|
+
// Create \u2014 always starts in DRAFT
|
|
2914
|
+
const faq = await adminClient.content.faq.create({
|
|
2915
|
+
key: 'shipping',
|
|
2916
|
+
name: 'Shipping FAQ',
|
|
2917
|
+
data: { items: [{ question: 'How long?', answer: 'Most orders ship in 2 days.' }] },
|
|
2918
|
+
});
|
|
2919
|
+
|
|
2920
|
+
// Update (data replaces wholesale; last-write-wins on the data field)
|
|
2921
|
+
await adminClient.content.update(faq.id, {
|
|
2922
|
+
data: { items: [{ question: 'How long?', answer: 'Updated answer.' }] },
|
|
2923
|
+
});
|
|
2924
|
+
|
|
2925
|
+
// Publish / unpublish
|
|
2926
|
+
await adminClient.content.publish(faq.id);
|
|
2927
|
+
await adminClient.content.unpublish(faq.id);
|
|
2928
|
+
|
|
2929
|
+
// Hard delete
|
|
2930
|
+
await adminClient.content.remove(faq.id);
|
|
2931
|
+
\`\`\`
|
|
2932
|
+
|
|
2933
|
+
Write operations throw if called from vibe-coded or storefront mode.
|
|
2934
|
+
|
|
2935
|
+
### Reserved key convention
|
|
2936
|
+
|
|
2937
|
+
\`'main'\` is reserved as the universal default. Don't use it for topical
|
|
2938
|
+
entries \u2014 pick a descriptive slug (\`'shipping'\`, \`'returns'\`, \`'about'\`,
|
|
2939
|
+
\`'holiday-2026'\`). The validation rule is \`^[a-z][a-z0-9-]*$\`, max 64 chars.
|
|
2940
|
+
|
|
2941
|
+
### See also
|
|
2942
|
+
|
|
2943
|
+
- \`get-business-flows\` with \`flow: 'content-bootstrap'\` for the full
|
|
2944
|
+
layout / FAQ / page recipe.
|
|
2945
|
+
- \`get-required-features\` lists each Content surface (\`site-header\`,
|
|
2946
|
+
\`site-footer\`, \`announcement-bar\`, \`faq-page\`, \`static-pages\`).
|
|
2947
|
+
- \`get-type-definitions\` with \`domain: 'content'\` for the TypeScript
|
|
2948
|
+
interfaces.`;
|
|
2949
|
+
}
|
|
2704
2950
|
function getSectionByTopic(topic, connectionId, currency) {
|
|
2705
2951
|
const cid = connectionId || "vc_YOUR_CONNECTION_ID";
|
|
2706
2952
|
const cur = currency || "USD";
|
|
@@ -2747,6 +2993,8 @@ function getSectionByTopic(topic, connectionId, currency) {
|
|
|
2747
2993
|
return getAdminApiSection();
|
|
2748
2994
|
case "inquiries":
|
|
2749
2995
|
return getContactInquiriesSection();
|
|
2996
|
+
case "content":
|
|
2997
|
+
return getContentSection();
|
|
2750
2998
|
case "all":
|
|
2751
2999
|
return [
|
|
2752
3000
|
"# Brainerce SDK \u2014 full topic dump",
|
|
@@ -2835,10 +3083,14 @@ function getSectionByTopic(topic, connectionId, currency) {
|
|
|
2835
3083
|
"",
|
|
2836
3084
|
"---",
|
|
2837
3085
|
"",
|
|
2838
|
-
getContactInquiriesSection()
|
|
3086
|
+
getContactInquiriesSection(),
|
|
3087
|
+
"",
|
|
3088
|
+
"---",
|
|
3089
|
+
"",
|
|
3090
|
+
getContentSection()
|
|
2839
3091
|
].join("\n");
|
|
2840
3092
|
default:
|
|
2841
|
-
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`;
|
|
3093
|
+
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`;
|
|
2842
3094
|
}
|
|
2843
3095
|
}
|
|
2844
3096
|
|
|
@@ -2866,6 +3118,7 @@ var GET_SDK_DOCS_SCHEMA = {
|
|
|
2866
3118
|
"i18n",
|
|
2867
3119
|
"admin",
|
|
2868
3120
|
"inquiries",
|
|
3121
|
+
"content",
|
|
2869
3122
|
"all"
|
|
2870
3123
|
]).describe("The SDK documentation topic to retrieve"),
|
|
2871
3124
|
salesChannelId: import_zod.z.string().optional().describe("Sales channel ID (starts with vc_). Used to personalize setup code."),
|
|
@@ -2897,11 +3150,11 @@ interface Product {
|
|
|
2897
3150
|
description?: string | null;
|
|
2898
3151
|
descriptionFormat?: 'text' | 'html' | 'markdown' | null;
|
|
2899
3152
|
sku: string;
|
|
2900
|
-
basePrice: string; //
|
|
2901
|
-
salePrice?: string | null;
|
|
3153
|
+
basePrice: string; // For VARIABLE products: MIN(variants.price). For SIMPLE: the parent price. parseFloat() for math.
|
|
3154
|
+
salePrice?: string | null; // For VARIABLE: MIN(variants.salePrice WHERE NOT NULL) \u2014 null iff no variant is on sale (WC is_on_sale() semantic). For SIMPLE: the parent sale price. Reliable "on sale?" check: product.salePrice !== null.
|
|
2902
3155
|
costPrice?: string | null;
|
|
2903
|
-
priceMin?: string | null; // Lowest variant price (VARIABLE products)
|
|
2904
|
-
priceMax?: string | null; // Highest variant price (VARIABLE products).
|
|
3156
|
+
priceMin?: string | null; // Lowest variant price (VARIABLE products) \u2014 same as basePrice for VARIABLE, kept for back-compat and JSON-LD range display.
|
|
3157
|
+
priceMax?: string | null; // Highest variant price (VARIABLE products). Use with priceMin for "\u20AA49 \u2013 \u20AA199" range.
|
|
2905
3158
|
priceVaries?: boolean; // true when variant prices differ \u2014 show "\u20AA49 \u2013 \u20AA199" range.
|
|
2906
3159
|
status: string;
|
|
2907
3160
|
type: 'SIMPLE' | 'VARIABLE';
|
|
@@ -3017,6 +3270,11 @@ interface ProductQueryParams {
|
|
|
3017
3270
|
metafields?: Record<string, string | string[]>;
|
|
3018
3271
|
sortBy?: 'name' | 'price' | 'createdAt';
|
|
3019
3272
|
sortOrder?: 'asc' | 'desc';
|
|
3273
|
+
// PRD \xA722: resolve DISPLAY prices for this region. When set + valid, each
|
|
3274
|
+
// product/variant gains resolvedPrice/resolvedCurrency/priceSource (additive;
|
|
3275
|
+
// basePrice/salePrice untouched). Absent/invalid region \u2192 nothing attached.
|
|
3276
|
+
// Display-only. Ignored in vibe-coded (vc_*) mode (storefront/admin paths only).
|
|
3277
|
+
regionId?: string;
|
|
3020
3278
|
}
|
|
3021
3279
|
|
|
3022
3280
|
interface SearchSuggestions {
|
|
@@ -3142,6 +3400,7 @@ interface Checkout {
|
|
|
3142
3400
|
status: CheckoutStatus;
|
|
3143
3401
|
email?: string | null;
|
|
3144
3402
|
customerId?: string | null;
|
|
3403
|
+
regionId?: string | null; // multi-region: recorded for reporting + provider scoping (currency follows the cart until FX lands)
|
|
3145
3404
|
shippingAddress?: CheckoutAddress | null;
|
|
3146
3405
|
billingAddress?: CheckoutAddress | null;
|
|
3147
3406
|
shippingRateId?: string | null;
|
|
@@ -3218,6 +3477,7 @@ interface CreateCheckoutDto {
|
|
|
3218
3477
|
cartId: string;
|
|
3219
3478
|
customerId?: string;
|
|
3220
3479
|
selectedItemIds?: string[]; // Partial checkout
|
|
3480
|
+
regionId?: string; // multi-region: associate the checkout with a region (must belong to the store; 400 if unknown)
|
|
3221
3481
|
}
|
|
3222
3482
|
|
|
3223
3483
|
// startGuestCheckout() return type \u2014 DISCRIMINATED UNION
|
|
@@ -3236,6 +3496,8 @@ interface TaxBreakdownItem {
|
|
|
3236
3496
|
name: string;
|
|
3237
3497
|
rate: number; // decimal: 0.17 = 17%
|
|
3238
3498
|
amount: number;
|
|
3499
|
+
taxClassId?: string | null; // rate's tax class (null = Standard)
|
|
3500
|
+
taxClassSlug?: string | null; // class slug for attribution (null = Standard)
|
|
3239
3501
|
}`;
|
|
3240
3502
|
var ORDERS_TYPES = `// ---- Orders ----
|
|
3241
3503
|
|
|
@@ -3293,6 +3555,7 @@ interface OrderItem {
|
|
|
3293
3555
|
// Snapshot of buyer-submitted customization values captured at checkout.
|
|
3294
3556
|
// Keyed by metafield slug. \`value\` is string[] for MULTI_SELECT / GALLERY, string otherwise.
|
|
3295
3557
|
customizations?: Record<string, { label: string; value: string | string[]; type: string }>;
|
|
3558
|
+
taxClassSlug?: string; // frozen slug of the line's resolved tax class (omitted = Standard fallback)
|
|
3296
3559
|
}
|
|
3297
3560
|
|
|
3298
3561
|
interface OrderCustomer {
|
|
@@ -3475,7 +3738,7 @@ function formatPrice(priceString: string | number | undefined | null, options?:
|
|
|
3475
3738
|
function getProductPrice(product: Pick<Product, 'basePrice' | 'salePrice'>): number;
|
|
3476
3739
|
function getProductPriceInfo(product: Pick<Product, 'basePrice' | 'salePrice' | 'discount' | 'priceMin' | 'priceVaries'>): {
|
|
3477
3740
|
price: number; originalPrice: number; isOnSale: boolean; discountAmount: number; discountPercent: number;
|
|
3478
|
-
}; //
|
|
3741
|
+
}; // For VARIABLE products, basePrice/salePrice are pre-aggregated (MIN of variants) \u2014 the helper just reads them. Use this whenever you need an "on sale?" badge or a "X% off" label.
|
|
3479
3742
|
function getVariantPrice(variant: Pick<ProductVariant, 'price' | 'salePrice'>, productBasePrice: string): number;
|
|
3480
3743
|
|
|
3481
3744
|
// Cart helpers
|
|
@@ -3858,6 +4121,245 @@ export interface ModifierValidationError {
|
|
|
3858
4121
|
// The cart line then carries:
|
|
3859
4122
|
// cart.items[i].modifiers \u2014 CartItemModifierLine[]
|
|
3860
4123
|
// cart.items[i].modifiersTotal \u2014 decimal string of the paid (non-free) deltas`;
|
|
4124
|
+
var CONTENT_TYPES = `// ---- Content (typed merchant content store) ----
|
|
4125
|
+
// Brainerce ships a typed content store so merchants can edit FAQ, footer,
|
|
4126
|
+
// header, announcements, rich text, and static pages in the dashboard
|
|
4127
|
+
// without re-prompting the AI that built the storefront. Every row has a
|
|
4128
|
+
// 'type' + 'key' + typed 'data' payload + free-form 'customFields'.
|
|
4129
|
+
//
|
|
4130
|
+
// SECURITY (read carefully):
|
|
4131
|
+
// RICH_TEXT.html, PAGE.html, and FAQ answers are MERCHANT-AUTHORED HTML.
|
|
4132
|
+
// ALWAYS sanitize with isomorphic-dompurify (or equivalent) before
|
|
4133
|
+
// injecting via dangerouslySetInnerHTML. The server does NOT pre-sanitize
|
|
4134
|
+
// because some merchants embed iframes (e.g. YouTube) which strict
|
|
4135
|
+
// sanitizers would strip; the storefront chooses the policy.
|
|
4136
|
+
//
|
|
4137
|
+
// 404 contract: client.content.<type>.get(key) returns null when no
|
|
4138
|
+
// PUBLISHED row exists. Always render a hard-coded fallback on null so
|
|
4139
|
+
// the page never crashes when the merchant hasn't seeded yet.
|
|
4140
|
+
//
|
|
4141
|
+
// Default key: every type has 'main' as its universal default. Pass no
|
|
4142
|
+
// argument to fetch the main entry; pass a custom key ('shipping',
|
|
4143
|
+
// 'holiday-2026', 'about') for topical entries.
|
|
4144
|
+
|
|
4145
|
+
export type ContentType = 'FAQ' | 'FOOTER' | 'HEADER' | 'ANNOUNCEMENT' | 'RICH_TEXT' | 'PAGE';
|
|
4146
|
+
export type ContentStatus = 'DRAFT' | 'PUBLISHED';
|
|
4147
|
+
|
|
4148
|
+
export interface FaqItem {
|
|
4149
|
+
question: string;
|
|
4150
|
+
/** Sanitized HTML \u2014 sanitize before rendering. */
|
|
4151
|
+
answer: string;
|
|
4152
|
+
}
|
|
4153
|
+
export interface FaqContent { items: FaqItem[] }
|
|
4154
|
+
|
|
4155
|
+
export interface FooterLink { label: string; url: string }
|
|
4156
|
+
export interface FooterColumn { title: string; links: FooterLink[] }
|
|
4157
|
+
export interface FooterSocialLink { platform: string; url: string } // 'instagram' | 'facebook' | 'x' | ...
|
|
4158
|
+
export interface FooterContent {
|
|
4159
|
+
columns: FooterColumn[];
|
|
4160
|
+
copyright?: string;
|
|
4161
|
+
social?: FooterSocialLink[];
|
|
4162
|
+
}
|
|
4163
|
+
|
|
4164
|
+
export interface HeaderLogo { src: string; alt: string }
|
|
4165
|
+
export interface HeaderNavItem { label: string; url: string }
|
|
4166
|
+
export interface HeaderCta { label: string; url: string }
|
|
4167
|
+
export interface HeaderContent {
|
|
4168
|
+
logo?: HeaderLogo;
|
|
4169
|
+
navItems: HeaderNavItem[];
|
|
4170
|
+
cta?: HeaderCta;
|
|
4171
|
+
}
|
|
4172
|
+
|
|
4173
|
+
export type AnnouncementSeverity = 'info' | 'warning' | 'success';
|
|
4174
|
+
export interface AnnouncementContent {
|
|
4175
|
+
message: string;
|
|
4176
|
+
severity: AnnouncementSeverity;
|
|
4177
|
+
dismissible: boolean;
|
|
4178
|
+
/** ISO 8601 \u2014 filter client-side. */
|
|
4179
|
+
startsAt?: string;
|
|
4180
|
+
endsAt?: string;
|
|
4181
|
+
ctaLabel?: string;
|
|
4182
|
+
ctaHref?: string;
|
|
4183
|
+
}
|
|
4184
|
+
|
|
4185
|
+
export interface RichTextContent {
|
|
4186
|
+
/** Raw HTML \u2014 sanitize before rendering. */
|
|
4187
|
+
html: string;
|
|
4188
|
+
}
|
|
4189
|
+
|
|
4190
|
+
export interface PageSeo {
|
|
4191
|
+
title?: string;
|
|
4192
|
+
description?: string;
|
|
4193
|
+
ogImage?: string;
|
|
4194
|
+
}
|
|
4195
|
+
export interface PageContent {
|
|
4196
|
+
/** URL slug, lower-kebab. */
|
|
4197
|
+
slug: string;
|
|
4198
|
+
title: string;
|
|
4199
|
+
/** Raw HTML \u2014 sanitize before rendering. */
|
|
4200
|
+
html: string;
|
|
4201
|
+
seo?: PageSeo;
|
|
4202
|
+
}
|
|
4203
|
+
|
|
4204
|
+
export interface ContentSummary {
|
|
4205
|
+
id: string;
|
|
4206
|
+
type: ContentType;
|
|
4207
|
+
key: string;
|
|
4208
|
+
name: string;
|
|
4209
|
+
status: ContentStatus;
|
|
4210
|
+
position: number;
|
|
4211
|
+
updatedAt: string;
|
|
4212
|
+
}
|
|
4213
|
+
|
|
4214
|
+
export interface Content<T extends ContentType = ContentType> extends ContentSummary {
|
|
4215
|
+
type: T;
|
|
4216
|
+
data: T extends 'FAQ' ? FaqContent
|
|
4217
|
+
: T extends 'FOOTER' ? FooterContent
|
|
4218
|
+
: T extends 'HEADER' ? HeaderContent
|
|
4219
|
+
: T extends 'ANNOUNCEMENT' ? AnnouncementContent
|
|
4220
|
+
: T extends 'RICH_TEXT' ? RichTextContent
|
|
4221
|
+
: T extends 'PAGE' ? PageContent
|
|
4222
|
+
: never;
|
|
4223
|
+
/** Free-form merchant-defined extras. Read keys the merchant told you to expect. */
|
|
4224
|
+
customFields: Record<string, string>;
|
|
4225
|
+
salesChannelIds: string[];
|
|
4226
|
+
}
|
|
4227
|
+
|
|
4228
|
+
// ---- SDK usage examples ----
|
|
4229
|
+
//
|
|
4230
|
+
// FAQ \u2014 render an accordion from the main FAQ (or a topical one):
|
|
4231
|
+
// const faq = await client.content.faq.get('main', locale); // 'shipping', 'returns', ...
|
|
4232
|
+
// if (faq) {
|
|
4233
|
+
// faq.data.items.forEach(({ question, answer }) => {
|
|
4234
|
+
// // Render question + sanitize(answer) \u2014 never inject raw HTML.
|
|
4235
|
+
// });
|
|
4236
|
+
// }
|
|
4237
|
+
//
|
|
4238
|
+
// Footer \u2014 server component in root layout:
|
|
4239
|
+
// const footer = await client.content.footer.get('main', locale);
|
|
4240
|
+
// if (!footer) return <Fallback />;
|
|
4241
|
+
// // Render footer.data.columns, footer.data.social, footer.data.copyright
|
|
4242
|
+
//
|
|
4243
|
+
// Header \u2014 same pattern as footer:
|
|
4244
|
+
// const header = await client.content.header.get('main', locale);
|
|
4245
|
+
//
|
|
4246
|
+
// Announcement \u2014 multiple may be active; filter by date client-side:
|
|
4247
|
+
// const announcements = await client.content.announcement.list(locale);
|
|
4248
|
+
// const now = Date.now();
|
|
4249
|
+
// const active = announcements.filter((a) => {
|
|
4250
|
+
// const startOk = !a.data.startsAt || new Date(a.data.startsAt).getTime() <= now;
|
|
4251
|
+
// const endOk = !a.data.endsAt || new Date(a.data.endsAt).getTime() >= now;
|
|
4252
|
+
// return startOk && endOk;
|
|
4253
|
+
// });
|
|
4254
|
+
//
|
|
4255
|
+
// Rich text \u2014 inline block anywhere on a page:
|
|
4256
|
+
// const block = await client.content.richText.get('about-intro', locale);
|
|
4257
|
+
// <div dangerouslySetInnerHTML={{ __html: sanitize(block.data.html) }} />
|
|
4258
|
+
//
|
|
4259
|
+
// Page \u2014 catch-all route by slug (e.g. /about, /terms, /privacy):
|
|
4260
|
+
// // app/[slug]/page.tsx
|
|
4261
|
+
// const page = await client.content.page.getBySlug(params.slug, locale);
|
|
4262
|
+
// if (!page) notFound();
|
|
4263
|
+
// // page.data.title, page.data.html, page.data.seo
|
|
4264
|
+
// return <article dangerouslySetInnerHTML={{ __html: sanitize(page.data.html) }} />;
|
|
4265
|
+
//
|
|
4266
|
+
// Custom fields \u2014 every Content row carries a free-form Record<string, string>:
|
|
4267
|
+
// const faq = await client.content.faq.get('shipping');
|
|
4268
|
+
// <a href={\`mailto:\${faq.customFields.helpEmail}\`}>Need help?</a>
|
|
4269
|
+
//
|
|
4270
|
+
// Cache \u2014 public reads carry Cache-Control: public, max-age=300,
|
|
4271
|
+
// stale-while-revalidate=60. Storefront changes propagate within ~5 min
|
|
4272
|
+
// of the merchant publishing. Do not add extra client-side caching
|
|
4273
|
+
// beyond Next.js's default fetch cache.`;
|
|
4274
|
+
var REGIONS_TYPES = `// ---- Regions & Tax Classes (Admin mode, apiKey) ----
|
|
4275
|
+
// storeId is derived from the API key \u2014 never pass it on admin calls.
|
|
4276
|
+
|
|
4277
|
+
// ---- Regions ---- (scopes: regions:read / regions:write)
|
|
4278
|
+
// A region binds countries \u2192 currency + tax-display mode + payment providers.
|
|
4279
|
+
interface Region {
|
|
4280
|
+
id: string;
|
|
4281
|
+
accountId: string;
|
|
4282
|
+
storeId: string;
|
|
4283
|
+
name: string;
|
|
4284
|
+
slug: string;
|
|
4285
|
+
currency: string; // ISO 4217, e.g. "EUR"
|
|
4286
|
+
countries: string[]; // ISO 3166-1 alpha-2, e.g. ["DE","FR"]
|
|
4287
|
+
taxInclusive: boolean; // show prices tax-inclusive in this region?
|
|
4288
|
+
automaticTaxes: boolean;
|
|
4289
|
+
isDefault: boolean; // fallback when buyer's country maps to no region
|
|
4290
|
+
isActive: boolean;
|
|
4291
|
+
paymentProviders?: RegionPaymentProvider[];
|
|
4292
|
+
createdAt: string;
|
|
4293
|
+
updatedAt: string;
|
|
4294
|
+
}
|
|
4295
|
+
|
|
4296
|
+
interface RegionPaymentProvider {
|
|
4297
|
+
id: string;
|
|
4298
|
+
regionId: string;
|
|
4299
|
+
appInstallationId: string;
|
|
4300
|
+
isEnabled: boolean;
|
|
4301
|
+
createdAt: string;
|
|
4302
|
+
}
|
|
4303
|
+
|
|
4304
|
+
interface CreateRegionDto {
|
|
4305
|
+
name: string;
|
|
4306
|
+
currency: string; // ISO 4217
|
|
4307
|
+
countries: string[]; // ISO 3166-1 alpha-2
|
|
4308
|
+
taxInclusive?: boolean;
|
|
4309
|
+
automaticTaxes?: boolean;
|
|
4310
|
+
isDefault?: boolean;
|
|
4311
|
+
paymentProviderIds?: string[]; // AppInstallation IDs to enable here
|
|
4312
|
+
}
|
|
4313
|
+
interface UpdateRegionDto extends Partial<CreateRegionDto> { isActive?: boolean }
|
|
4314
|
+
|
|
4315
|
+
// client.detectRegion(country, regions): Region | null \u2014 pure, no network.
|
|
4316
|
+
// \u2192 region whose countries includes the code, else the default region, else null.
|
|
4317
|
+
// Pass the resolved regionId to createCheckout to associate the checkout with a
|
|
4318
|
+
// region (recorded for reporting + provider scoping; currency follows the cart
|
|
4319
|
+
// until FX price conversion lands).
|
|
4320
|
+
//
|
|
4321
|
+
// Storefront (public, no apiKey \u2014 storeId mode):
|
|
4322
|
+
interface PublicRegion {
|
|
4323
|
+
id: string; name: string; slug: string; currency: string;
|
|
4324
|
+
countries: string[]; taxInclusive: boolean; isDefault: boolean;
|
|
4325
|
+
}
|
|
4326
|
+
interface PublicRegionDetail extends PublicRegion {
|
|
4327
|
+
paymentProviders: Array<{ id: string; appId: string; name: string | null }>;
|
|
4328
|
+
}
|
|
4329
|
+
// getStoreRegions(): { data: PublicRegion[] } \u2014 active regions, default first.
|
|
4330
|
+
// getStoreRegion(regionId): PublicRegionDetail \u2014 one region + its providers.
|
|
4331
|
+
|
|
4332
|
+
// ---- Tax Classes ---- (scopes: tax-classes:read / tax-classes:write)
|
|
4333
|
+
// Charge differential rates by product type. A TaxRate may target a class via
|
|
4334
|
+
// taxClassId; a rate with taxClassId=null is the Standard fallback. Per-line
|
|
4335
|
+
// resolution: variant \u2192 product \u2192 category \u2192 store default \u2192 null.
|
|
4336
|
+
interface TaxClass {
|
|
4337
|
+
id: string;
|
|
4338
|
+
accountId: string;
|
|
4339
|
+
storeId: string;
|
|
4340
|
+
name: string;
|
|
4341
|
+
slug: string; // kebab-case, unique per store
|
|
4342
|
+
description?: string | null;
|
|
4343
|
+
isDefault: boolean; // auto-applied to products without an explicit class
|
|
4344
|
+
createdAt: string;
|
|
4345
|
+
updatedAt: string;
|
|
4346
|
+
}
|
|
4347
|
+
interface CreateTaxClassDto { name: string; slug: string; description?: string; isDefault?: boolean }
|
|
4348
|
+
type UpdateTaxClassDto = Partial<CreateTaxClassDto>;
|
|
4349
|
+
// Bulk-assign a class to entities:
|
|
4350
|
+
interface AssignTaxClassDto { productIds?: string[]; variantIds?: string[]; categoryIds?: string[] }
|
|
4351
|
+
|
|
4352
|
+
// TaxRate / CreateTaxRateDto carry an optional taxClassId (null = Standard).
|
|
4353
|
+
// rate is a WHOLE PERCENTAGE (7.25 = 7.25%).
|
|
4354
|
+
//
|
|
4355
|
+
// SDK methods (admin):
|
|
4356
|
+
// Regions: getRegions(), getRegion(id), createRegion(dto), updateRegion(id, dto),
|
|
4357
|
+
// deleteRegion(id), setDefaultRegion(id), updateRegionPaymentProviders(id, ids),
|
|
4358
|
+
// addRegionCountries(id, codes), removeRegionCountry(id, code),
|
|
4359
|
+
// getRegionCompatibleProviders(id), detectRegion(country, regions)
|
|
4360
|
+
// Tax classes: getTaxClasses(), getTaxClass(id), createTaxClass(dto), updateTaxClass(id, dto),
|
|
4361
|
+
// deleteTaxClass(id), setDefaultTaxClass(id), assignTaxClass(id, dto),
|
|
4362
|
+
// mergeTaxClasses(id, targetId)`;
|
|
3861
4363
|
var TYPES_BY_DOMAIN = {
|
|
3862
4364
|
products: PRODUCTS_TYPES,
|
|
3863
4365
|
cart: CART_TYPES,
|
|
@@ -3868,7 +4370,9 @@ var TYPES_BY_DOMAIN = {
|
|
|
3868
4370
|
helpers: HELPERS_TYPES,
|
|
3869
4371
|
inquiries: INQUIRIES_TYPES,
|
|
3870
4372
|
reviews: REVIEWS_TYPES,
|
|
3871
|
-
"modifier-groups": MODIFIER_GROUPS_TYPES
|
|
4373
|
+
"modifier-groups": MODIFIER_GROUPS_TYPES,
|
|
4374
|
+
content: CONTENT_TYPES,
|
|
4375
|
+
regions: REGIONS_TYPES
|
|
3872
4376
|
};
|
|
3873
4377
|
function getTypesByDomain(domain) {
|
|
3874
4378
|
if (domain === "all") {
|
|
@@ -3899,9 +4403,12 @@ var GET_TYPE_DEFINITIONS_SCHEMA = {
|
|
|
3899
4403
|
"helpers",
|
|
3900
4404
|
"inquiries",
|
|
3901
4405
|
"reviews",
|
|
4406
|
+
"modifier-groups",
|
|
4407
|
+
"content",
|
|
4408
|
+
"regions",
|
|
3902
4409
|
"all"
|
|
3903
4410
|
]).describe(
|
|
3904
|
-
'The domain of types to retrieve. Use "helpers" for helper function signatures and common types like StoreInfo, PaginatedResponse.'
|
|
4411
|
+
'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. Use "regions" for Region / TaxClass admin types.'
|
|
3905
4412
|
)
|
|
3906
4413
|
};
|
|
3907
4414
|
async function handleGetTypeDefinitions(args) {
|
|
@@ -4448,8 +4955,10 @@ client.setLocale(locale);
|
|
|
4448
4955
|
// order bumps, search suggestions, discount banners, nudges,
|
|
4449
4956
|
// badges, order history.
|
|
4450
4957
|
|
|
4451
|
-
// For RTL
|
|
4452
|
-
//
|
|
4958
|
+
// For RTL direction, do not hardcode the locale list. Ask the SDK:
|
|
4959
|
+
// const dir = client.getStoreDirection(currentLocale); // 'ltr' | 'rtl'
|
|
4960
|
+
// document.documentElement.setAttribute('dir', dir);
|
|
4961
|
+
// (Or in React: <html dir={dir}>...</html>.)`,
|
|
4453
4962
|
"order-history-full": `// Full "My Orders" account page. Render every piece of data the server
|
|
4454
4963
|
// already returns \u2014 not just order number / total / status.
|
|
4455
4964
|
//
|
|
@@ -5541,7 +6050,7 @@ var RULES = {
|
|
|
5541
6050
|
body: `- NEVER hardcode currency, locale, or language strings. Read them from \`get-store-info\` / \`get-store-capabilities\` and use the configured values.
|
|
5542
6051
|
- NEVER format prices with \`toFixed(2)\` or custom logic. Use \`formatPrice()\` from the SDK \u2014 it honors the store's currency and locale.
|
|
5543
6052
|
- 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.
|
|
5544
|
-
- For RTL locales (\`
|
|
6053
|
+
- 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.`
|
|
5545
6054
|
},
|
|
5546
6055
|
types: {
|
|
5547
6056
|
title: "Type safety",
|
|
@@ -5589,6 +6098,7 @@ var GET_BUSINESS_FLOWS_SCHEMA = {
|
|
|
5589
6098
|
"cart-persistence",
|
|
5590
6099
|
"inventory-reservation",
|
|
5591
6100
|
"product-customization",
|
|
6101
|
+
"content-bootstrap",
|
|
5592
6102
|
"all"
|
|
5593
6103
|
]).describe('Which flow to retrieve. Use "all" to get every flow.')
|
|
5594
6104
|
};
|
|
@@ -5688,11 +6198,16 @@ Build both steps EVEN IF the store has no email provider configured today \u2014
|
|
|
5688
6198
|
});
|
|
5689
6199
|
window.location.href = authorizationUrl; // full-page redirect, NOT a popup
|
|
5690
6200
|
\`\`\`
|
|
5691
|
-
3. **On the callback page** the URL contains \`
|
|
6201
|
+
3. **On the callback page** the URL contains \`auth_code\` + \`oauth_success\` (or \`oauth_error\`) query params. Exchange the single-use code for the JWT \u2014 never read the token from the URL:
|
|
5692
6202
|
\`\`\`ts
|
|
5693
|
-
const
|
|
5694
|
-
|
|
6203
|
+
const params = new URLSearchParams(location.search);
|
|
6204
|
+
const code = params.get('auth_code');
|
|
6205
|
+
if (code) {
|
|
6206
|
+
const result = await client.exchangeOAuthCode(code);
|
|
6207
|
+
client.setCustomerToken(result.token); // then redirect to account
|
|
6208
|
+
}
|
|
5695
6209
|
\`\`\`
|
|
6210
|
+
The legacy \`?token=\` URL param is still emitted for backward compatibility but will be removed in the next major release \u2014 migrate to \`auth_code\` now.
|
|
5696
6211
|
4. **On \`oauth_error\`:** redirect to login with an error message.
|
|
5697
6212
|
|
|
5698
6213
|
Build the OAuth button region AND the callback handler even when no providers are configured. They auto-hide.`
|
|
@@ -5779,6 +6294,76 @@ Server-side guardrails that WILL reject bad requests (so validate client-side to
|
|
|
5779
6294
|
- More than 10 uploads per IP per minute \u2192 429.
|
|
5780
6295
|
|
|
5781
6296
|
Never render customization fields without also wiring the upload + metadata flow \u2014 a form that submits nothing is worse than no form at all.`
|
|
6297
|
+
},
|
|
6298
|
+
"content-bootstrap": {
|
|
6299
|
+
title: "Content Bootstrap \u2014 site chrome & static content",
|
|
6300
|
+
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\`).
|
|
6301
|
+
|
|
6302
|
+
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.
|
|
6303
|
+
\`\`\`ts
|
|
6304
|
+
const [header, footer, announcements] = await Promise.all([
|
|
6305
|
+
client.content.header.get('main', locale),
|
|
6306
|
+
client.content.footer.get('main', locale),
|
|
6307
|
+
client.content.announcement.list(locale),
|
|
6308
|
+
]);
|
|
6309
|
+
\`\`\`
|
|
6310
|
+
|
|
6311
|
+
2. **FAQ \u2014 fetch lazily on the FAQ page.** Default key is \`'main'\`; pass a topical key (\`'shipping'\`, \`'returns'\`) for sub-FAQs.
|
|
6312
|
+
\`\`\`ts
|
|
6313
|
+
const faq = await client.content.faq.get('main', locale);
|
|
6314
|
+
if (faq) {
|
|
6315
|
+
faq.data.items.forEach(({ question, answer }) => {
|
|
6316
|
+
// sanitize(answer) \u2014 see step 4
|
|
6317
|
+
});
|
|
6318
|
+
}
|
|
6319
|
+
\`\`\`
|
|
6320
|
+
|
|
6321
|
+
3. **Static pages \u2014 catch-all route by slug:**
|
|
6322
|
+
\`\`\`tsx
|
|
6323
|
+
// app/[slug]/page.tsx
|
|
6324
|
+
export default async function Page({ params }) {
|
|
6325
|
+
const page = await client.content.page.getBySlug(params.slug, locale);
|
|
6326
|
+
if (!page) notFound();
|
|
6327
|
+
return (
|
|
6328
|
+
<article dangerouslySetInnerHTML={{ __html: sanitize(page.data.html) }} />
|
|
6329
|
+
);
|
|
6330
|
+
}
|
|
6331
|
+
\`\`\`
|
|
6332
|
+
|
|
6333
|
+
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:
|
|
6334
|
+
\`\`\`ts
|
|
6335
|
+
import DOMPurify from 'isomorphic-dompurify';
|
|
6336
|
+
const safe = DOMPurify.sanitize(rawHtml);
|
|
6337
|
+
<div dangerouslySetInnerHTML={{ __html: safe }} />;
|
|
6338
|
+
\`\`\`
|
|
6339
|
+
Skipping this is XSS.
|
|
6340
|
+
|
|
6341
|
+
5. **Announcements \u2014 multiple may be active; filter by date client-side:**
|
|
6342
|
+
\`\`\`ts
|
|
6343
|
+
const now = Date.now();
|
|
6344
|
+
const visible = announcements.filter((a) => {
|
|
6345
|
+
const startOk = !a.data.startsAt || new Date(a.data.startsAt).getTime() <= now;
|
|
6346
|
+
const endOk = !a.data.endsAt || new Date(a.data.endsAt).getTime() >= now;
|
|
6347
|
+
return startOk && endOk;
|
|
6348
|
+
});
|
|
6349
|
+
\`\`\`
|
|
6350
|
+
|
|
6351
|
+
6. **RTL direction \u2014 call \`client.getStoreDirection(locale)\`:**
|
|
6352
|
+
\`\`\`tsx
|
|
6353
|
+
const dir = client.getStoreDirection(locale);
|
|
6354
|
+
<html lang={locale} dir={dir}>...</html>
|
|
6355
|
+
\`\`\`
|
|
6356
|
+
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.
|
|
6357
|
+
|
|
6358
|
+
7. **Custom fields \u2014 every Content row has free-form \`customFields: Record<string, string>\`.** Read keys the merchant told you to expect:
|
|
6359
|
+
\`\`\`ts
|
|
6360
|
+
const faq = await client.content.faq.get('shipping');
|
|
6361
|
+
<a href={\`mailto:\${faq.customFields.helpEmail}\`}>Need help?</a>
|
|
6362
|
+
\`\`\`
|
|
6363
|
+
|
|
6364
|
+
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.
|
|
6365
|
+
|
|
6366
|
+
**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.`
|
|
5782
6367
|
}
|
|
5783
6368
|
};
|
|
5784
6369
|
var FLOW_ORDER = [
|
|
@@ -5790,7 +6375,8 @@ var FLOW_ORDER = [
|
|
|
5790
6375
|
"order-confirmation",
|
|
5791
6376
|
"cart-persistence",
|
|
5792
6377
|
"inventory-reservation",
|
|
5793
|
-
"product-customization"
|
|
6378
|
+
"product-customization",
|
|
6379
|
+
"content-bootstrap"
|
|
5794
6380
|
];
|
|
5795
6381
|
async function handleGetBusinessFlows(args) {
|
|
5796
6382
|
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.";
|
|
@@ -6002,11 +6588,57 @@ var FEATURES = [
|
|
|
6002
6588
|
{
|
|
6003
6589
|
id: "i18n",
|
|
6004
6590
|
title: "Serve multiple languages with a language switcher",
|
|
6005
|
-
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
|
|
6006
|
-
sdk: "client.setLocale(locale). Read supported locales from get-store-capabilities.store.i18n.",
|
|
6591
|
+
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.",
|
|
6592
|
+
sdk: "client.setLocale(locale). client.getStoreDirection(locale) for <html dir>. Read supported locales from get-store-capabilities.store.i18n.",
|
|
6007
6593
|
mandatory: "conditional",
|
|
6008
6594
|
capabilityFlag: "i18n",
|
|
6009
6595
|
whenDisabledNote: "This store is single-language. Do not build the language switcher."
|
|
6596
|
+
},
|
|
6597
|
+
{
|
|
6598
|
+
id: "site-header",
|
|
6599
|
+
title: "Site header from merchant content (logo + nav + CTA)",
|
|
6600
|
+
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.',
|
|
6601
|
+
sdk: 'client.content.header.get("main", locale)',
|
|
6602
|
+
flowRef: "content-bootstrap",
|
|
6603
|
+
mandatory: "mandatory"
|
|
6604
|
+
},
|
|
6605
|
+
{
|
|
6606
|
+
id: "site-footer",
|
|
6607
|
+
title: "Site footer from merchant content (columns + social + copyright)",
|
|
6608
|
+
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.',
|
|
6609
|
+
sdk: 'client.content.footer.get("main", locale)',
|
|
6610
|
+
flowRef: "content-bootstrap",
|
|
6611
|
+
mandatory: "mandatory"
|
|
6612
|
+
},
|
|
6613
|
+
{
|
|
6614
|
+
id: "announcement-bar",
|
|
6615
|
+
title: "Announcement bar at the top of every page",
|
|
6616
|
+
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.",
|
|
6617
|
+
sdk: "client.content.announcement.list(locale)",
|
|
6618
|
+
flowRef: "content-bootstrap",
|
|
6619
|
+
mandatory: "conditional",
|
|
6620
|
+
capabilityFlag: "hasContent",
|
|
6621
|
+
whenDisabledNote: "Store has no published Content rows yet. Build the announcement bar anyway \u2014 it auto-hides on empty."
|
|
6622
|
+
},
|
|
6623
|
+
{
|
|
6624
|
+
id: "faq-page",
|
|
6625
|
+
title: "FAQ page rendered from merchant content",
|
|
6626
|
+
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.',
|
|
6627
|
+
sdk: 'client.content.faq.get("main", locale), client.content.faq.list(locale)',
|
|
6628
|
+
flowRef: "content-bootstrap",
|
|
6629
|
+
mandatory: "conditional",
|
|
6630
|
+
capabilityFlag: "hasContent",
|
|
6631
|
+
whenDisabledNote: "No FAQ content yet. Build /faq anyway \u2014 it auto-hides on empty."
|
|
6632
|
+
},
|
|
6633
|
+
{
|
|
6634
|
+
id: "static-pages",
|
|
6635
|
+
title: "Static pages from merchant content (About, Terms, Privacy, \u2026)",
|
|
6636
|
+
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.",
|
|
6637
|
+
sdk: "client.content.page.getBySlug(slug, locale), client.content.page.list(locale)",
|
|
6638
|
+
flowRef: "content-bootstrap",
|
|
6639
|
+
mandatory: "conditional",
|
|
6640
|
+
capabilityFlag: "hasContent",
|
|
6641
|
+
whenDisabledNote: "No static pages yet. Build the catch-all route anyway \u2014 it 404s on unknown slugs."
|
|
6010
6642
|
}
|
|
6011
6643
|
];
|
|
6012
6644
|
function isFeatureActive(feature, caps) {
|
|
@@ -6057,6 +6689,9 @@ function renderCapabilitiesSummary(caps) {
|
|
|
6057
6689
|
);
|
|
6058
6690
|
lines.push(`- Downloadable products: ${caps.features.hasDownloadableProducts ? "yes" : "no"}`);
|
|
6059
6691
|
lines.push(`- Checkout custom fields: ${caps.features.hasCheckoutCustomFields ? "yes" : "no"}`);
|
|
6692
|
+
lines.push(
|
|
6693
|
+
`- Content (FAQ/footer/header/announcements/pages): ${caps.features.hasContent ? "seeded" : "none \u2014 build chrome UI with fallbacks"}`
|
|
6694
|
+
);
|
|
6060
6695
|
lines.push(
|
|
6061
6696
|
`- Email verification: ${caps.connection.requireEmailVerification ? "required" : "not required (still build the verify-email flow)"}`
|
|
6062
6697
|
);
|
|
@@ -6385,14 +7020,149 @@ function createServer() {
|
|
|
6385
7020
|
|
|
6386
7021
|
// src/bin/http.ts
|
|
6387
7022
|
var PORT = parseInt(process.env.PORT || "3100", 10);
|
|
6388
|
-
var CORS_ORIGIN = process.env.CORS_ORIGIN || "*";
|
|
6389
7023
|
var SSE_KEEPALIVE_MS = 1e4;
|
|
6390
7024
|
var SESSION_MAX_AGE_MS = 4 * 60 * 60 * 1e3;
|
|
7025
|
+
var NODE_ENV = process.env.NODE_ENV || "development";
|
|
7026
|
+
var IS_DEV = NODE_ENV === "development";
|
|
7027
|
+
var AUTH_TOKENS = (process.env.MCP_AUTH_TOKENS || "").split(",").map((t) => t.trim()).filter((t) => t.length > 0).map((t) => Buffer.from(t, "utf8"));
|
|
7028
|
+
if (AUTH_TOKENS.length === 0 && !IS_DEV) {
|
|
7029
|
+
console.error(
|
|
7030
|
+
"FATAL: MCP_AUTH_TOKENS is not set. The MCP HTTP server must run with at least one Bearer token in non-development environments.\nMint a token (e.g., `mcp_<random>`) via the dashboard and add it (comma-separated) to MCP_AUTH_TOKENS."
|
|
7031
|
+
);
|
|
7032
|
+
process.exit(1);
|
|
7033
|
+
}
|
|
7034
|
+
if (AUTH_TOKENS.length === 0 && IS_DEV) {
|
|
7035
|
+
console.warn(
|
|
7036
|
+
"WARN: MCP_AUTH_TOKENS is not set. Running in development mode \u2014 any non-empty Bearer token will be accepted."
|
|
7037
|
+
);
|
|
7038
|
+
}
|
|
7039
|
+
var ALLOWED_ORIGINS = (process.env.MCP_ALLOWED_ORIGINS || "").split(",").map((o) => o.trim()).filter((o) => o.length > 0);
|
|
7040
|
+
var LOCALHOST_ORIGIN_RE = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/;
|
|
7041
|
+
var RATE_LIMIT_WINDOW_MS = parseInt(process.env.MCP_RATE_LIMIT_WINDOW_MS || "60000", 10);
|
|
7042
|
+
var RATE_LIMIT_MAX = parseInt(process.env.MCP_RATE_LIMIT_MAX || "60", 10);
|
|
7043
|
+
var rateBuckets = /* @__PURE__ */ new Map();
|
|
7044
|
+
var MAX_BODY_BYTES = parseInt(process.env.MCP_MAX_BODY_BYTES || String(100 * 1024), 10);
|
|
7045
|
+
function safeEqual(a, b) {
|
|
7046
|
+
if (a.length !== b.length) {
|
|
7047
|
+
const max = Math.max(a.length, b.length);
|
|
7048
|
+
const ax = Buffer.alloc(max);
|
|
7049
|
+
const bx = Buffer.alloc(max);
|
|
7050
|
+
a.copy(ax);
|
|
7051
|
+
b.copy(bx);
|
|
7052
|
+
(0, import_node_crypto.timingSafeEqual)(ax, bx);
|
|
7053
|
+
return false;
|
|
7054
|
+
}
|
|
7055
|
+
return (0, import_node_crypto.timingSafeEqual)(a, b);
|
|
7056
|
+
}
|
|
7057
|
+
function authenticate(req, res) {
|
|
7058
|
+
const header = req.headers["authorization"];
|
|
7059
|
+
if (typeof header !== "string" || !header.toLowerCase().startsWith("bearer ")) {
|
|
7060
|
+
writeJson(res, 401, {
|
|
7061
|
+
error: "Missing or malformed Authorization header. Expected: Bearer <token>."
|
|
7062
|
+
});
|
|
7063
|
+
return false;
|
|
7064
|
+
}
|
|
7065
|
+
const presented = header.slice(7).trim();
|
|
7066
|
+
if (presented.length === 0) {
|
|
7067
|
+
writeJson(res, 401, { error: "Empty Bearer token." });
|
|
7068
|
+
return false;
|
|
7069
|
+
}
|
|
7070
|
+
if (AUTH_TOKENS.length === 0 && IS_DEV) {
|
|
7071
|
+
return true;
|
|
7072
|
+
}
|
|
7073
|
+
const presentedBuf = Buffer.from(presented, "utf8");
|
|
7074
|
+
let matched = false;
|
|
7075
|
+
for (const token of AUTH_TOKENS) {
|
|
7076
|
+
if (safeEqual(presentedBuf, token)) {
|
|
7077
|
+
matched = true;
|
|
7078
|
+
}
|
|
7079
|
+
}
|
|
7080
|
+
if (!matched) {
|
|
7081
|
+
writeJson(res, 401, { error: "Invalid Bearer token." });
|
|
7082
|
+
return false;
|
|
7083
|
+
}
|
|
7084
|
+
return true;
|
|
7085
|
+
}
|
|
7086
|
+
function clientIp(req) {
|
|
7087
|
+
const xff = req.headers["x-forwarded-for"];
|
|
7088
|
+
if (typeof xff === "string" && xff.length > 0) {
|
|
7089
|
+
return xff.split(",")[0].trim();
|
|
7090
|
+
}
|
|
7091
|
+
return req.socket.remoteAddress || "unknown";
|
|
7092
|
+
}
|
|
7093
|
+
function rateLimit(req, res) {
|
|
7094
|
+
const ip = clientIp(req);
|
|
7095
|
+
const now = Date.now();
|
|
7096
|
+
const bucket = rateBuckets.get(ip);
|
|
7097
|
+
if (!bucket || bucket.resetAt <= now) {
|
|
7098
|
+
rateBuckets.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS });
|
|
7099
|
+
return true;
|
|
7100
|
+
}
|
|
7101
|
+
if (bucket.count >= RATE_LIMIT_MAX) {
|
|
7102
|
+
const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - now) / 1e3));
|
|
7103
|
+
res.setHeader("Retry-After", String(retryAfter));
|
|
7104
|
+
writeJson(res, 429, { error: "Rate limit exceeded. Try again later." });
|
|
7105
|
+
return false;
|
|
7106
|
+
}
|
|
7107
|
+
bucket.count += 1;
|
|
7108
|
+
return true;
|
|
7109
|
+
}
|
|
7110
|
+
var rateLimitGcTimer = setInterval(
|
|
7111
|
+
() => {
|
|
7112
|
+
const now = Date.now();
|
|
7113
|
+
for (const [ip, bucket] of rateBuckets) {
|
|
7114
|
+
if (bucket.resetAt <= now) rateBuckets.delete(ip);
|
|
7115
|
+
}
|
|
7116
|
+
},
|
|
7117
|
+
5 * 60 * 1e3
|
|
7118
|
+
);
|
|
7119
|
+
rateLimitGcTimer.unref();
|
|
7120
|
+
function resolveCorsOrigin(origin) {
|
|
7121
|
+
if (!origin) return null;
|
|
7122
|
+
if (ALLOWED_ORIGINS.includes(origin)) return origin;
|
|
7123
|
+
if (IS_DEV && LOCALHOST_ORIGIN_RE.test(origin)) return origin;
|
|
7124
|
+
return null;
|
|
7125
|
+
}
|
|
7126
|
+
function setCors(req, res) {
|
|
7127
|
+
const origin = typeof req.headers.origin === "string" ? req.headers.origin : void 0;
|
|
7128
|
+
const allowed = resolveCorsOrigin(origin);
|
|
7129
|
+
if (allowed) {
|
|
7130
|
+
res.setHeader("Access-Control-Allow-Origin", allowed);
|
|
7131
|
+
res.setHeader("Vary", "Origin");
|
|
7132
|
+
}
|
|
7133
|
+
res.setHeader("Access-Control-Allow-Credentials", "false");
|
|
7134
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
|
|
7135
|
+
res.setHeader(
|
|
7136
|
+
"Access-Control-Allow-Headers",
|
|
7137
|
+
"Content-Type, Accept, Authorization, Mcp-Session-Id"
|
|
7138
|
+
);
|
|
7139
|
+
res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
|
|
7140
|
+
}
|
|
7141
|
+
function writeJson(res, status, body) {
|
|
7142
|
+
if (res.headersSent) return;
|
|
7143
|
+
res.writeHead(status, { "Content-Type": "application/json" });
|
|
7144
|
+
res.end(JSON.stringify(body));
|
|
7145
|
+
}
|
|
6391
7146
|
function parseBody(req) {
|
|
6392
7147
|
return new Promise((resolve, reject) => {
|
|
6393
7148
|
const chunks = [];
|
|
6394
|
-
|
|
7149
|
+
let total = 0;
|
|
7150
|
+
let aborted = false;
|
|
7151
|
+
req.on("data", (chunk) => {
|
|
7152
|
+
if (aborted) return;
|
|
7153
|
+
total += chunk.length;
|
|
7154
|
+
if (total > MAX_BODY_BYTES) {
|
|
7155
|
+
aborted = true;
|
|
7156
|
+
const err = new Error("Request body exceeds maximum allowed size");
|
|
7157
|
+
err.statusCode = 413;
|
|
7158
|
+
reject(err);
|
|
7159
|
+
req.destroy();
|
|
7160
|
+
return;
|
|
7161
|
+
}
|
|
7162
|
+
chunks.push(chunk);
|
|
7163
|
+
});
|
|
6395
7164
|
req.on("end", () => {
|
|
7165
|
+
if (aborted) return;
|
|
6396
7166
|
if (chunks.length === 0) return resolve(void 0);
|
|
6397
7167
|
try {
|
|
6398
7168
|
resolve(JSON.parse(Buffer.concat(chunks).toString()));
|
|
@@ -6429,14 +7199,8 @@ async function main() {
|
|
|
6429
7199
|
5 * 60 * 1e3
|
|
6430
7200
|
);
|
|
6431
7201
|
cleanupTimer.unref();
|
|
6432
|
-
function setCors(res) {
|
|
6433
|
-
res.setHeader("Access-Control-Allow-Origin", CORS_ORIGIN);
|
|
6434
|
-
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
|
|
6435
|
-
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Mcp-Session-Id");
|
|
6436
|
-
res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
|
|
6437
|
-
}
|
|
6438
7202
|
const httpServer = (0, import_node_http.createServer)(async (req, res) => {
|
|
6439
|
-
setCors(res);
|
|
7203
|
+
setCors(req, res);
|
|
6440
7204
|
if (req.method === "OPTIONS") {
|
|
6441
7205
|
res.writeHead(204);
|
|
6442
7206
|
res.end();
|
|
@@ -6453,6 +7217,8 @@ async function main() {
|
|
|
6453
7217
|
);
|
|
6454
7218
|
return;
|
|
6455
7219
|
}
|
|
7220
|
+
if (!rateLimit(req, res)) return;
|
|
7221
|
+
if (!authenticate(req, res)) return;
|
|
6456
7222
|
if (req.url === "/mcp") {
|
|
6457
7223
|
try {
|
|
6458
7224
|
const server = createServer();
|
|
@@ -6465,8 +7231,7 @@ async function main() {
|
|
|
6465
7231
|
} catch (error) {
|
|
6466
7232
|
console.error("MCP request error:", error);
|
|
6467
7233
|
if (!res.headersSent) {
|
|
6468
|
-
res
|
|
6469
|
-
res.end(JSON.stringify({ error: "Internal server error" }));
|
|
7234
|
+
writeJson(res, 500, { error: "Internal server error" });
|
|
6470
7235
|
}
|
|
6471
7236
|
}
|
|
6472
7237
|
return;
|
|
@@ -6507,8 +7272,7 @@ async function main() {
|
|
|
6507
7272
|
} catch (error) {
|
|
6508
7273
|
console.error("SSE connection error:", error);
|
|
6509
7274
|
if (!res.headersSent) {
|
|
6510
|
-
res
|
|
6511
|
-
res.end(JSON.stringify({ error: "Internal server error" }));
|
|
7275
|
+
writeJson(res, 500, { error: "Internal server error" });
|
|
6512
7276
|
}
|
|
6513
7277
|
}
|
|
6514
7278
|
return;
|
|
@@ -6517,8 +7281,7 @@ async function main() {
|
|
|
6517
7281
|
const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
|
|
6518
7282
|
const sessionId = url.searchParams.get("sessionId");
|
|
6519
7283
|
if (!sessionId || !sseSessions.has(sessionId)) {
|
|
6520
|
-
res
|
|
6521
|
-
res.end(JSON.stringify({ error: "Invalid or missing sessionId" }));
|
|
7284
|
+
writeJson(res, 400, { error: "Invalid or missing sessionId" });
|
|
6522
7285
|
return;
|
|
6523
7286
|
}
|
|
6524
7287
|
try {
|
|
@@ -6526,20 +7289,23 @@ async function main() {
|
|
|
6526
7289
|
const body = await parseBody(req);
|
|
6527
7290
|
await session.transport.handlePostMessage(req, res, body);
|
|
6528
7291
|
} catch (error) {
|
|
6529
|
-
|
|
7292
|
+
const status = error && typeof error === "object" && "statusCode" in error ? error.statusCode || 500 : 500;
|
|
7293
|
+
if (status !== 500) {
|
|
7294
|
+
console.warn("SSE message rejected:", error.message);
|
|
7295
|
+
} else {
|
|
7296
|
+
console.error("SSE message error:", error);
|
|
7297
|
+
}
|
|
6530
7298
|
if (!res.headersSent) {
|
|
6531
|
-
res
|
|
6532
|
-
|
|
7299
|
+
writeJson(res, status, {
|
|
7300
|
+
error: status === 413 ? "Payload too large" : "Internal server error"
|
|
7301
|
+
});
|
|
6533
7302
|
}
|
|
6534
7303
|
}
|
|
6535
7304
|
return;
|
|
6536
7305
|
}
|
|
6537
|
-
res
|
|
6538
|
-
|
|
6539
|
-
|
|
6540
|
-
error: "Not found. Use /mcp (Streamable HTTP), /sse (legacy SSE), or /health."
|
|
6541
|
-
})
|
|
6542
|
-
);
|
|
7306
|
+
writeJson(res, 404, {
|
|
7307
|
+
error: "Not found. Use /mcp (Streamable HTTP), /sse (legacy SSE), or /health."
|
|
7308
|
+
});
|
|
6543
7309
|
});
|
|
6544
7310
|
function shutdown(signal) {
|
|
6545
7311
|
console.info(`
|
|
@@ -6567,6 +7333,16 @@ ${signal} received \u2014 shutting down gracefully...`);
|
|
|
6567
7333
|
console.info(` Streamable HTTP: http://localhost:${PORT}/mcp`);
|
|
6568
7334
|
console.info(` Legacy SSE: http://localhost:${PORT}/sse`);
|
|
6569
7335
|
console.info(` Health check: http://localhost:${PORT}/health`);
|
|
7336
|
+
console.info(
|
|
7337
|
+
` Auth tokens: ${AUTH_TOKENS.length} configured${AUTH_TOKENS.length === 0 && IS_DEV ? " (dev: any non-empty Bearer accepted)" : ""}`
|
|
7338
|
+
);
|
|
7339
|
+
console.info(
|
|
7340
|
+
` CORS: ${ALLOWED_ORIGINS.length} allow-listed origin(s)${IS_DEV ? " + localhost (dev)" : ""}`
|
|
7341
|
+
);
|
|
7342
|
+
console.info(
|
|
7343
|
+
` Rate limit: ${RATE_LIMIT_MAX} req / ${Math.round(RATE_LIMIT_WINDOW_MS / 1e3)}s per IP`
|
|
7344
|
+
);
|
|
7345
|
+
console.info(` Max body: ${MAX_BODY_BYTES} bytes`);
|
|
6570
7346
|
});
|
|
6571
7347
|
}
|
|
6572
7348
|
main().catch((error) => {
|