# Merchant Admin GraphQL # Merchant Admin GraphQL (`/admin/graphql`) Every xclade store exposes a dedicated **Merchant Admin GraphQL** surface at: ```http POST https://{shortId}.api.myxclade.com/admin/graphql ``` Built natively in Go (`gqlgen`), `/admin/graphql` powers the Store Admin Console (`/app`), back-office automations, ERP syncs, warehouse operations, and `@xclade/sdk` admin methods. *** ## Key Capabilities * **31 Queries & 65 Mutations** spanning catalog, pricing, WMS bins & cycle counts, orders, draft orders, fulfillments, refunds, returns, B2B quotes/approvals, analytics, ERP connections, webhooks, RBAC, and batch imports. * **Fine-Grained RBAC:** Every operation is protected by `AdminRBACGuard` and the `@requirePermission` schema directive. * **Live SSE Transport:** Supports Server-Sent Events (`transport.SSE` with 15-second keep-alive pings) alongside `POST` and `GET`. * **Higher Admin Limits:** Allows up to **16 MiB** payloads (for batch imports), depth **14**, **30** aliases, and **75** directives. * **CSRF Guard:** Always enabled on `GET` operations—send `X-Xclade-Request: true` or `X-GraphQL-Request: true`. *** ## Authentication Authenticate admin requests using any of three supported methods: 1. **Admin JWT Bearer Token** — Obtained from `adminLogin(email, password)` or `redeemAdminSso(token)`: ```http Authorization: Bearer eyJhbGciOi... ``` 2. **Merchant Secret API Key (`sk_...`)** — Ideal for server-to-server ERP/CI scripts: ```http Authorization: Bearer sk_live_... ``` 3. **Admin Session Cookie** — Automatically set for browser sessions inside `/app`. ### Sign In Example ```graphql mutation AdminLogin($email: String!, $password: String!) { adminLogin(email: $email, password: $password) } ``` ```graphql query AdminMe { adminMe { id email first_name last_name is_super_admin policies roles { id name slug is_system } } } ``` *** ## Admin Queries (`31`) ### Identity, Store Configuration & RBAC | Query | Description | | :----------------- | :--------------------------------------------------------------------------------------------------- | | `adminMe` | Fetch the authenticated admin user, assigned roles, and effective RBAC policy keys. | | `storeConfig` | Fetch store name, default currency/region/sales channel/stock location, return window, and metadata. | | `adminUsers` | List store administrator accounts and their assigned roles. | | `rbacRoles` | List custom and system RBAC roles. | | `rbacPolicies` | List available RBAC permission policies. | | `publishableKeys` | List storefront Publishable API Keys (`pk_...`) and linked sales channels. | | `salesChannels` | List configured sales channels. | | `taxRegions` | List tax regions and default rates. | | `shippingProfiles` | List fulfillment shipping profiles. | | `customerGroups` | List customer groups (including B2B contract groups). | | `vendors` | List marketplace vendors. | ### Catalog, Pricing & Effective-Price Debugger | Query | Description | | :----------------------- | :------------------------------------------------------------------------------------------------------- | | `adminProducts` | Paginated SQL-joined catalog list with variant counts, inventory totals, and filters. | | `adminPriceLists` | List sale and override price lists. | | `adminPriceListPage` | Fetch a price list with paginated variant price rows. | | `resolveEffectivePrices` | Debug exact effective price resolution for variants given currency, region, customer group, or quantity. | ### Inventory & Warehouse Management (WMS) | Query | Description | | :-------------------------------- | :---------------------------------------------------------------- | | `stockLocations` | List warehouses and fulfillment locations. | | `inventoryLevels` | Inspect stocked, reserved, and available quantities per location. | | `adminInventoryItems` | Paginated inventory items with SKU and stock summaries. | | `warehouseBins(location_id)` | List warehouse storage bins (zone, aisle, rack, shelf, capacity). | | `cycleCountSessions(location_id)` | List warehouse physical inventory cycle count sessions. | ### Orders, Customers, Analytics & Integrations | Query | Description | | :------------------------------------------- | :----------------------------------------------------------------------------------------------- | | `adminOrders` | Paginated orders & draft orders with status, channel, region, customer, and B2B company filters. | | `adminCustomers` | Searchable customer directory with account filters. | | `analyticsOverview(from, to, currency_code)` | Revenue, order count, AOV, and conversion metrics. | | `adminB2BOverview` | B2B pipeline metrics across companies, pending quotes, and approvals. | | `abandonedCartStats(days)` | Aggregate abandoned cart recovery statistics. | | `abandonedCarts(limit, offset, stage)` | List active abandoned carts by recovery stage. | | `providerConfigs` | List payment, shipping, search, and verification (e.g. ID Rabbit) provider configs. | | `erpConnections` | List configured ERP integrations (Zoho, NetSuite, etc.). | | `webhookEndpoints` | List tenant outbound webhook subscriptions. | | `adminQuery` / `adminFetchQuery` | Generic domain query dispatchers used by internal console tooling. | *** ## Admin Mutations (`65`) ### Auth, Store Setup, RBAC & Uploads * `adminLogin`, `adminLogout`, `redeemAdminSso` * `createPresignedUpload` (direct-to-S3 media upload URLs) * `updateStoreConfig`, `upsertRegion`, `upsertSalesChannel`, `upsertTaxRegion`, `upsertShippingOption` * `inviteAdminUser`, `upsertRbacRole`, `assignUserRoles` * `createPublishableKey`, `revokePublishableKey` ### Catalog, Pricing, Promotions & Search * `upsertProduct`, `deleteProduct`, `upsertCategory`, `upsertCollection`, `upsertBrand`, `upsertVendor` * `moderateReview`, `reindexSearch` (triggers full Typesense catalog reindex) * `upsertCustomerGroup`, `upsertCampaign` * `upsertPriceList`, `deletePriceList`, `upsertPromotion`, `deletePromotion` ### Inventory & Warehouse Management (WMS) * `upsertStockLocation`, `adjustInventoryLevel` * `upsertWarehouseBin`, `startCycleCountSession`, `completeCycleCountSession` ### Orders, Fulfillments, Payments, Returns & B2B Quotes * `createDraftOrder`, `convertDraftOrder` * `createOrderFulfillment`, `markFulfillmentShipped`, `markFulfillmentDelivered` * `captureOrderPayment`, `refundOrderPayment`, `cancelOrder` * `stageOrderEdit`, `confirmOrderEdit`, `receiveReturn` * `sendQuoteOffer`, `merchantRejectQuote` ### Storefront CMS, Providers, ERP & Webhooks * `updateBrandSettings`, `upsertNavigationMenu`, `upsertHeroSlider`, `updateSeoSettings`, `upsertAdvertisement`, `upsertChangelog` * `upsertProviderConfig`, `verifyProviderConfig` * `upsertErpConnection`, `triggerErpSync` * `upsertWebhookEndpoint`, `deleteWebhookEndpoint` ### High-Throughput Batch Importers * `importCategoriesBatch`, `importCollectionsBatch`, `importProductsBatch`, `importCustomersBatch`, `importOrdersBatch` * `adminMutate`, `adminFetchMutate` *** ## Using `@xclade/sdk` for Admin Operations ```ts import { createXcladeSDK } from '@xclade/sdk'; const admin = createXcladeSDK({ baseUrl: 'https://{shortId}.api.myxclade.com', apiKey: process.env.XCLADE_SECRET_KEY, // sk_live_... }); const { products, count } = await admin.graphql.listProducts({ limit: 25, offset: 0 }); const overview = await admin.graphql.analyticsOverview({ currency_code: 'usd' }); ``` See the [`@xclade/sdk` guide](/docs/sdk) for complete TypeScript SDK examples. # Agentic Commerce Protocols # Agentic Commerce Protocols Beyond GraphQL and Remote MCP, every xclade store pod ships with an isolated **Agentic Commerce** route surface built directly into Go—allowing autonomous shopping agents, LLM browsers, and AI checkout orchestrators to discover products, negotiate sessions, and settle orders safely. Inspect live protocol readiness for any store at: ```http GET https://{shortId}.api.myxclade.com/agentic/status ``` *** ## Google UCP (Universal Commerce Protocol) | Method & Path | Purpose | | :--------------------------------------------- | :--------------------------------------------------------------- | | `GET /.well-known/ucp` | UCP capability manifest and merchant profile. | | `GET /ucp/v1/products` | Paginated product catalog discovery. | | `GET /ucp/v1/products/{id}` | Single product detail with live pricing & inventory. | | `POST /ucp/v1/checkout-sessions` | Create an agentic checkout session. | | `GET /ucp/v1/checkout-sessions/{id}` | Inspect session totals, shipping, and payment state. | | `PUT /ucp/v1/checkout-sessions/{id}` | Update items, buyer email, shipping address, or shipping option. | | `POST /ucp/v1/checkout-sessions/{id}/complete` | Finalize payment and convert session into a store order. | | `POST /ucp/v1/checkout-sessions/{id}/cancel` | Cancel an open checkout session. | *** ## OpenAI ACP (Agentic Commerce Protocol) | Method & Path | Purpose | | :------------------------------------------ | :--------------------------------------------------------- | | `GET /acp/feed/products.json` | Full JSON catalog feed for agent indexing. | | `GET /acp/feed/products.jsonl` | Streaming JSONL catalog feed. | | `POST /acp/checkout_sessions` | Create an ACP checkout session. | | `GET /acp/checkout_sessions/{id}` | Fetch current ACP checkout session state. | | `POST /acp/checkout_sessions/{id}` | Update session line items, buyer details, or fulfillment. | | `POST /acp/checkout_sessions/{id}/complete` | Complete checkout with delegated payment token or mandate. | | `POST /acp/checkout_sessions/{id}/cancel` | Cancel an active ACP checkout session. | | `POST /acp/delegate_payment` | Delegated payment token vaulting / handoff. | *** ## AI Discovery, A2A & WebMCP | Method & Path | Purpose | | :------------------------------------------------------------- | :---------------------------------------------------------------------- | | `GET /llms.txt` | Concise store catalog & endpoint summary for LLM crawlers. | | `GET /llms-full.txt` | Extended machine-readable catalog & store context. | | `GET /products/{handle}.md` | Clean Markdown representation of any individual product page. | | `GET /.well-known/agent.json` & `/.well-known/agent-card.json` | Agent-to-Agent (A2A) discovery card. | | `POST /a2a` | A2A JSON-RPC task endpoint. | | `GET /agentic/webmcp.js` | Drop-in browser WebMCP script exposing storefront tools to AI browsers. | *** ## Agent Authentication & Payment Extensions The Agentic Commerce router supports modern agent trust and settlement headers out of the box: * **RFC 9421 Web Bot Auth:** Verifies `Signature`, `Signature-Input`, and `Signature-Agent` HTTP Message Signatures and returns `X-Xclade-Agent-Auth`. * **AP2 Mandates:** Accepts signed spending mandates via `X-AP2-Mandate` on UCP and ACP checkout completion. * **x402 Payment Protocol:** Supports `X-PAYMENT` and `X-Payment-Protocol: x402` when enabled in store agentic settings, returning settlement details in `X-Payment-Response`. * **Idempotency & Tracing:** Supports `Idempotency-Key`, `Request-Id`, `UCP-Agent`, and `API-Version` headers with permissive agent CORS (`OPTIONS` preflight registered on every path). # Platform Architecture # Platform Architecture xclade separates **control-plane orchestration** from **per-store runtime execution** so every merchant gets physical isolation without managing Kubernetes, databases, or CDN routing. *** ## Topology Overview ```text ┌──────────────────────────────────────────┐ │ Cloudflare / Edge Ingress │ └───────────┬──────────────────┬───────────┘ │ │ https://api.xclade.com │ │ https://{shortId}.api.myxclade.com ▼ ▼ ┌─────────────────────────────┐ ┌─────────────────────────────────┐ │ Xclade Control Plane │ │ Dedicated Store Pod (EKS) │ │ Go 1.26 · chi/v5 · pgx/v5 │ │ Go 1.26 · gqlgen · chi/v5 │ │ │ │ │ │ • Auth, Orgs, Billing │ │ • POST /graphql (Store) │ │ • Store Operator (K8s) │ │ • POST /admin/graphql (Admin) │ │ • Storefront Studio + TSX │ │ • /mcp & /mcp/store (OAuth) │ │ • Growth Studio (AWS SES) │ │ • UCP / ACP / A2A / llms.txt │ │ • Migrations & Snapshots │ │ • /webhooks/* & /app (Console) │ └──────────────┬──────────────┘ └────────────────┬────────────────┘ │ │ ┌──────────────▼──────────────┐ ┌────────────────▼────────────────┐ │ Control Plane Postgres │ │ Isolated Store Postgres DB │ │ + Dedicated Go Worker │ │ + Scoped Redis + Typesense │ └─────────────────────────────┘ └─────────────────────────────────┘ ``` *** ## Core Components ### 1. Dedicated Store Runtime (`xclade-store-backend`) Each provisioned store runs an isolated **Go 1.26** binary in its own Kubernetes namespace (`store-{uuid}`) connected to its own isolated PostgreSQL database and scoped Redis namespace: * **GraphQL Engine (`gqlgen`):** Code-generated, statically typed schemas compiled directly into the binary with zero runtime reflection overhead. * **DataLoader Batching (`graph/loaders/`):** Per-request Go batchers eliminate N+1 SQL queries across collections, categories, currencies, regions, countries, and order items. * **Two-Layer Response Cache (`XcladeResponseCache`):** Redis-backed caching on 17 allowlisted public Storefront queries, isolated by `tenantScope + salesChannels + locale + actor`, with automatic tag invalidation on mutations. * **Built-In Hardening (`XcladeGraphQLArmor`):** Enforces AST depth, alias, directive, batch, payload size, timeout, CSRF preflight, and Redis rate limits in Go middleware. * **Native Protocol Surfaces:** Ships with OAuth 2.1 Remote MCP (`/mcp`, `/mcp/store`), Agentic Commerce (Google UCP, OpenAI ACP, A2A, WebMCP, `llms.txt`), provider webhooks, and the embedded Store Admin SPA (`/app`). ### 2. Xclade Control Plane (`xclade-api` & `xclade-worker`) Mounted directly at the root of **`https://api.xclade.com`**, the Go Control Plane manages: * Organization identity, RBAC, OIDC SSO, WebAuthn Passkeys, and Stripe billing. * Automated Kubernetes store provisioning, scaling, pause/resume, release channels, and encrypted database snapshots. * **Storefront Studio:** Theme documents, AI storefront edits, secure TSX component compilation, and GitHub template registry sync. * **Growth Studio:** Email block compilation, AI campaign architect, scheduled broadcasts, A/B testing, automation flows, RFM scoring, and AWS SES delivery with mandatory verified custom sending domains. * **Dedicated Go Worker (`xclade-worker`):** Executes asynchronous catalog migrations (Shopify/BigCommerce), snapshot jobs, AI runs, and Growth Studio flow/campaign dispatch loops. ### 3. Hosted Storefront Fleet (`xclade-edge` & `xclade-storefront`) Merchants can either build their own headless frontend (Next.js, Remix, mobile) or deploy instantly onto the **Hosted Storefront Fleet**: * **`xclade-edge`** resolves incoming custom domains and `{shortId}.myxclade.com` hostnames against the Control Plane and routes traffic with automatic TLS. * **`xclade-storefront`** renders the store's `StorefrontDocument` and compiled custom TSX sections against the store pod's `/graphql` endpoint and shared Typesense instant search index. *** ## Health & Telemetry Endpoints Every store pod exposes lightweight operational probes: | Endpoint | Purpose | | :---------------------------------- | :---------------------------------------------------------------------------------------- | | `GET /health` or `GET /status` | Liveness/readiness check verifying database connectivity, engine version, and `store_id`. | | `GET /graphql/health` | Live GraphQL execution telemetry snapshot (latency and error metrics). | | `GET /agentic/status` | Live diagnostics for UCP, ACP, A2A, `llms.txt`, and Web Bot Auth readiness. | | `GET https://api.xclade.com/health` | Control Plane health check. | # Control Plane API # Control Plane API (`https://api.xclade.com`) The xclade Control Plane is a Go 1.26 HTTP API mounted **directly at the root** of `https://api.xclade.com`. **Root-Mounted Base URL:** All Control Plane routes live directly at the root of `https://api.xclade.com`—for example `https://api.xclade.com/health`, `https://api.xclade.com/status`, `https://api.xclade.com/auth/*`, and `https://api.xclade.com/orgs/*`. *** ## Authentication & Security * **Bearer JWT / Session Cookies:** Issued via `/auth/*` (supports email/password, WebAuthn Passkeys, OIDC SSO, and OAuth providers). * **CSRF Header:** Browser-originating state-changing requests include the Xclade CSRF header alongside `Allow-Credentials: true`. * **Organization & Store Isolation:** Every tenant route is scoped under `/orgs/{orgId}/...` with strict membership and RBAC checks. *** ## Core Route Groups ### Health, Status & Public Endpoints | Route | Description | | :------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------- | | `GET /health` | Control Plane liveness & Postgres connectivity check. | | `GET /status/*` | Public platform status, service monitors, and incident feeds. | | `GET /billing/*` | Public plan catalog & pricing metadata. | | `GET /storefront/public/*` | Public storefront resolution & published template metadata. | | `GET /growth/public/*` | Public unsubscribe (`/u/{token}`), open pixel (`/o/{token}.gif`), HMAC-verified click redirects (`/c/{token}`), and storefront popup/newsletter capture. | ### Identity & OAuth 2.1 | Route | Description | | :--------------------- | :--------------------------------------------------------------------------------------------------- | | `/auth/*` | Customer signup, login, email verification, password reset, MFA/Passkeys, and GitHub/OIDC callbacks. | | `/.well-known/oauth-*` | RFC 9728 Protected Resource and RFC 8414 Authorization Server discovery. | | `/oauth/*` | Control Plane OAuth 2.1 authorization, token, dynamic client registration, and revocation. | | `/mcp/*` | Control Plane Remote MCP server. | | `/zapier/*` | Native Zapier / automation triggers and actions. | ### Organizations, Stores & Infrastructure | Route | Description | | :-------------------------------------------- | :------------------------------------------------------------------------------------------------------- | | `/orgs` & `/orgs/{orgId}` | Organization management, team invitations, roles, SSO settings, and billing profile. | | `/orgs/{orgId}/billing/*` | Stripe subscriptions, payment methods, invoices, and usage-based studio billing. | | `/orgs/{orgId}/snapshots/*` | Organization-wide database backup snapshots and restore operations. | | `/orgs/{orgId}/stores` | Provision, inspect, pause/resume, upgrade, configure custom domains, and delete isolated EKS store pods. | | `/orgs/{orgId}/stores/{storeId}/migrations/*` | Streaming Shopify & BigCommerce catalog/customer/order migration jobs. | | `/orgs/{orgId}/stores/{storeId}/oauth/*` | Manage store OAuth clients and Remote MCP grants. | | `/orgs/{orgId}/stores/{storeId}/snapshots/*` | Per-store point-in-time snapshots. | ### Storefront Studio & Growth Studio | Route | Description | | :-------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `/orgs/{orgId}/stores/{storeId}/storefront/*` | Visual theme document CRUD, custom TSX component compiler, AI storefront runs, version publishing, and GitHub sync. | | `/orgs/{orgId}/stores/{storeId}/growth/*` | Email templates, live compiler preview, test emails, campaigns, A/B tests, automation flows, RFM recomputation, segments, profiles, CSV imports, autonomous agents, and custom DKIM sending domains. | | `POST /storefront/templates/publish` | CI/CD template publishing endpoint for `xclade/store-templates`. | ### Example: Check Control Plane Health ```bash curl https://api.xclade.com/health ``` ```json { "status": "ok", "timestamp": "2026-11-26T19:17:12Z" } ``` # Growth Studio (Email & Automations) # Growth Studio **Growth Studio** is xclade's built-in email marketing, automation, and customer lifecycle engine—powered by AWS SES Production (`xclade-growth`) and connected directly to your store's live catalog, orders, and brand tokens. Growth Studio is **commerce-first** for every retail/DTC store and automatically unlocks B2B wholesale blocks, segments, and reorder playbooks when a store enables its B2B suite. *** ## Mandatory Custom Sending Domains Every store **must attach and verify its own custom sending domain** (2048-bit RSA DKIM) before sending **any** Growth Studio email—including test emails, broadcast campaigns, automation flows, and AI agent proposals. Platform domains (`xclade.com`, `myxclade.com`, `mail.myxclade.com`, or any subdomain) are strictly rejected and cannot be used for tenant sending. ### Domain Setup Flow 1. Open **Growth Studio → Deliverability & DNS** in `https://app.xclade.com`. 2. Enter your brand's sending domain (recommended: a dedicated subdomain such as `mail.yourbrand.com`). 3. xclade provisions AWS SES v2 **2048-bit RSA DKIM** tokens and a custom `MAIL FROM` Return-Path (`bounces.mail.yourbrand.com`) and displays the exact CNAME, MX, and SPF TXT records. 4. Add those DNS records at your registrar/Cloudflare and click **Verify DNS**. 5. Once `dkimStatus === "success"`, test sends, broadcast campaigns, automation flows, and autonomous agent approvals unlock immediately. Attempting to dispatch without a verified custom domain returns HTTP **`412 Precondition Failed`** with error code **`custom_domain_required`**. *** ## Visual Block Email Compiler Emails are authored as structured JSON documents (`EmailDocument`) that inherit your store's live **Storefront Studio** colors, fonts, and button radius—then compile deterministically into 600px table-based HTML compatible with Gmail, Apple Mail, and Outlook alongside a clean plain-text multipart fallback. ### Available Blocks | Block Type | Purpose | | :------------------- | :---------------------------------------------------------------------------------- | | `brand-header` | Store logo image or wordmark linked to your storefront. | | `hero-banner` | Eyebrow, headline, body copy, hero image, and primary CTA button. | | `editorial-prose` | Rich multi-paragraph copy with optional bullet list. | | `product-grid` | 2-column responsive product cards pulled from your live catalog. | | `dynamic-line-items` | Hydrated cart/order line items with SKU, quantity, and formatted totals. | | `coupon-callout` | Dashed promo-code card with code display, expiry text, and checkout CTA. | | `b2b-quote-card` | *(B2B-enabled stores)* Commercial quote summary with locked total and approval CTA. | | `b2b-reorder-cta` | *(B2B-enabled stores)* Quick-order matrix & SKU replenishment callout. | | `divider` | Hairline horizontal separator. | | `compliance-footer` | Physical mailing address + one-click unsubscribe link (auto-appended if omitted). | ### Merge Tags All subject lines, preheaders, and block text support Handlebars-style merge tags with safe defaults: ```text Hi {{ profile.first_name | default: 'there' }}, your order from {{ store.name }} is waiting. ``` Common built-in variables: `store.name`, `store.url`, `store.physical_address`, `profile.first_name`, `profile.last_name`, `profile.email`, `profile.company_name`, `promo.code`, `delivery.unsubscribe_url`. *** ## Deliverability & Compliance Architecture * **RFC 8058 One-Click Unsubscribe:** Every marketing email automatically injects `List-Unsubscribe` and `List-Unsubscribe-Post: List-Unsubscribe=One-Click` MIME headers alongside a visible footer unsubscribe link. * **HMAC-Signed Click Tracking:** Outbound links are signed with HMAC-SHA256 against the delivery token to prevent open-redirect tampering (unsubscribe and `mailto:` links are never wrapped). * **Deliverability Shield:** Real-time AWS SNS webhooks (`POST https://api.xclade.com/webhooks/ses`) track deliveries, hard bounces, and spam complaints—automatically suppressing bounced/complained contacts and pausing sending if complaint thresholds are approached. * **Smart Sending Cooldown:** Configurable per-contact cooldown window prevents over-messaging subscribers across overlapping campaigns and flows. *** ## Campaigns, Flows, RFM & Growth Agents * **Broadcasts & A/B Testing:** Schedule one-off campaigns or run automated subject/content A/B tests with automatic winner selection. * **Automation Flows:** Trigger multi-step sequences on storefront events (welcome, abandoned cart, post-purchase, winback, and B2B quote follow-ups) with automatic exit conditions (e.g. exit on order placed). * **Predictive RFM & Dynamic Segments:** Deterministic Recency-Frequency-Monetary lifecycle scoring (`champions`, `loyal`, `promising`, `at_risk`, `hibernating`, plus `overdue_b2b` for B2B stores) with parameterized SQL segment evaluation. * **Autonomous Growth Agents:** Deploy recurring **Copilot** (drafts for human approval) or **Autopilot** agents governed by hard Go guardrails (max discount %, max daily sends, per-contact cooldown, and verified custom domain requirement). # Introduction import { Bot, Code2, Cpu, Globe, Layers, Mail, Palette, Server, Shield, Webhook } from 'lucide-react'; # Welcome to xclade Docs **xclade** is a cloud-native commerce platform engineered in **Go 1.26**. Every store provisions into its own dedicated Kubernetes compute pod and isolated PostgreSQL database—delivering predictable sub-50ms execution, zero noisy neighbors, and 0% transaction fees. Instead of stitching together fragile plugins, every capability is compiled directly into your store binary and exposed across four clean surfaces: * **Storefront & B2B GraphQL (`POST /graphql`)** — 53 queries and 45 mutations across 22 commerce domains with DataLoader batching, Automatic Persisted Queries, and Redis response caching. * **Merchant Admin GraphQL (`POST /admin/graphql`)** — 31 queries and 65 mutations for catalog, pricing, WMS warehouse bins & cycle counts, orders, B2B quotes/approvals, RBAC, analytics, ERP sync, and SSE. * **Remote MCP & Agentic Commerce (`/mcp`, `/mcp/store`, UCP, ACP, A2A)** — OAuth 2.1 Streamable HTTP/SSE servers for AI operations and buyer agents. * **Control Plane API (`https://api.xclade.com`)** — Root-mounted REST API for organizations, store lifecycle, snapshots, **Storefront Studio**, and **Growth Studio**. *** ## Explore the Platform } href="/docs/graphql" title="Storefront & B2B GraphQL"> Catalog, contextual pricing, carts, Stripe/Authorize.Net checkout, ID Rabbit verification, OTP login, and B2B quotes/approvals. } href="/docs/admin-graphql" title="Merchant Admin GraphQL"> Back-office queries and mutations protected by RBAC directives, WMS inventory tools, price-list debugger, and batch importers. } href="/docs/sdk" title="TypeScript SDK (@xclade/sdk)"> Zero-dependency pure GraphQL SDK v2 covering both Storefront and Admin APIs with typed error handling. } href="/docs/mcp" title="Remote MCP Servers"> Connect Claude, Cursor, Windsurf, or custom agents to 45+ Admin tools on `/mcp` or 8 buyer tools on `/mcp/store`. } href="/docs/agentic-commerce" title="Agentic Commerce"> Built-in support for Google UCP, OpenAI ACP, A2A, WebMCP, `llms.txt`, AP2 mandates, x402, and RFC 9421 Web Bot Auth. } href="/docs/storefront-studio" title="Storefront Studio & TSX"> Visual storefront builder, custom React/Tailwind section components, and Git-backed template publishing. } href="/docs/growth-studio" title="Growth Studio"> Visual email studio, AI architect, automation flows, RFM segments, and mandatory 2048-bit RSA DKIM custom sending domains. } href="/docs/control-plane" title="Control Plane API"> Root-mounted API at `https://api.xclade.com` for orgs, stores, snapshots, billing, migrations, and studios. *** ## 60-Second Quick Start ### 1. Install `@xclade/sdk` ```bash pnpm add @xclade/sdk ``` ### 2. Query your store's GraphQL endpoint Every store serves Storefront & B2B GraphQL at `https://{shortId}.api.myxclade.com/graphql`: ```ts import { createXcladeSDK } from '@xclade/sdk'; const xclade = createXcladeSDK({ baseUrl: 'https://{shortId}.api.myxclade.com', publishableKey: 'pk_live_...', }); const { products, count } = await xclade.store.listProducts({ limit: 12, currency_code: 'usd', }); ``` Or call `POST /graphql` directly with `curl`: ```bash curl -X POST https://{shortId}.api.myxclade.com/graphql \ -H "Content-Type: application/json" \ -H "X-Xclade-Publishable-Key: pk_live_..." \ -H "X-Xclade-Request: true" \ -d '{ "query": "query GetProducts($currency: String!) { products(limit: 5, pricing_context: { currency_code: $currency }) { products { id title handle variants { id sku inventory_quantity calculated_price { calculated_amount currency_code } } } count } }", "variables": { "currency": "usd" } }' ``` *** ## Service Base URLs | Surface | Base URL | Protocol | | :---------------------- | :----------------------------------------------------- | :------------------------------------------------------------------------------------------------------- | | **Control Plane API** | `https://api.xclade.com` *(root-mounted)* | JSON REST + OAuth 2.1 + Platform MCP | | **Store Backend** | `https://{shortId}.api.myxclade.com` | Go GraphQL (`/graphql`, `/admin/graphql`), Remote MCP (`/mcp`, `/mcp/store`), Agentic Commerce, Webhooks | | **Merchant Console** | `https://app.xclade.com` | Workspace, Storefront Studio, Growth Studio, Billing, Domains | | **Store Admin Console** | `https://{shortId}.api.myxclade.com/app` | Embedded Store Operations Console + GraphiQL Playground | | **Hosted Storefront** | `https://{shortId}.myxclade.com` or your custom domain | Next.js Edge Storefront Fleet | *** ## AI Coding Assistants Point Claude, Cursor, Windsurf, or Antigravity at our LLM-ready endpoints: * [`/llms.txt`](/llms.txt) — Structured table of contents * [`/llms-full.txt`](/llms-full.txt) — Complete single-file Markdown documentation bundle # Remote MCP Servers # Remote MCP Servers (`/mcp` & `/mcp/store`) Every xclade store runs two native **Model Context Protocol (MCP)** servers compiled directly into the Go store binary—protected by **OAuth 2.1** with automatic RFC 9728 / RFC 8414 discovery and Dynamic Client Registration. | Endpoint | Audience | Required Scopes | Capabilities | | :--------------- | :---------------------------------- | :---------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------- | | **`/mcp`** | Store Admins & AI Ops Agents | `mcp:read`, `mcp:write` | **45+ tools** across catalog, orders, inventory, WMS, B2B, pricing, analytics, RBAC, and direct GraphQL execution + Prompts, Resources, Tasks & MCP Apps UI | | **`/mcp/store`** | Authenticated Shoppers & B2B Buyers | `store:mcp:read`, `store:mcp:write` | **8 scoped buyer tools** for product search, personal contract pricing, orders, RFQ quotes, and checkout cart creation | *** ## Transport & Protocol Versions Both `/mcp` and `/mcp/store` support: * **Streamable HTTP** (`POST`, `GET`, `DELETE`, `OPTIONS`) with `Mcp-Session-Id` session tracking. * **Server-Sent Events (SSE)** when `Accept: text/event-stream` is sent on `GET`. * **Negotiated MCP Protocol Versions:** `2026-07-28`, `2025-11-25` *(default)*, `2025-06-18`, `2025-03-26`, and `2024-11-05`. *** ## OAuth 2.1 Discovery & Authorization Modern MCP clients (Claude Desktop, Cursor, Windsurf, Antigravity) discover OAuth endpoints automatically from the `WWW-Authenticate` header on the first unauthenticated request: | Well-Known / OAuth Endpoint | Purpose | | :---------------------------------------------------- | :--------------------------------------------------------------------- | | `GET /.well-known/oauth-protected-resource/mcp` | Protected resource metadata for Admin MCP (`/mcp`). | | `GET /.well-known/oauth-protected-resource/mcp/store` | Protected resource metadata for Buyer MCP (`/mcp/store`). | | `GET /.well-known/oauth-authorization-server` | OAuth 2.1 authorization server metadata (RFC 8414). | | `POST /oauth/register` | Dynamic Client Registration (DCR). | | `GET` / `POST /oauth/authorize` | Interactive PKCE consent screen (supports both Admin and Buyer OAuth). | | `POST /oauth/token` | Authorization code & refresh token exchange. | | `POST /oauth/revoke` | Instant token revocation. | ### Client Configuration Example ```json { "mcpServers": { "xclade-store-ops": { "url": "https://{shortId}.api.myxclade.com/mcp", "transport": "streamable-http" }, "xclade-buyer-agent": { "url": "https://{shortId}.api.myxclade.com/mcp/store", "transport": "streamable-http" } } } ``` Every MCP tool carries MCP `annotations` (`readOnlyHint`, `destructiveHint`) and runs through the same Go RBAC policy checks as `/admin/graphql`. Destructive or policy-gated operations return structured MCP elicitation metadata so the host can request human confirmation. *** ## Merchant Operations Tools (`/mcp`) ### Commerce, Orders, Inventory & Carts * `search_products`, `get_product` * `list_orders`, `get_order` * `get_inventory`, `list_stock_locations` * `list_customer_groups` * `list_abandoned_carts`, `get_abandoned_cart`, `get_abandoned_cart_stats`, `get_cart_insights`, `list_live_carts` * `import_store_batch` ### Pricing, Promotions, Analytics & RBAC * `list_price_lists`, `get_price_list`, `resolve_effective_prices` * `list_campaigns`, `get_campaign`, `list_promotions` * `get_analytics_overview`, `get_product_analytics`, `get_customer_analytics`, `get_b2b_pipeline_analytics` * `list_roles`, `list_role_policies`, `list_admin_users` ### B2B Wholesale & Warehouse Management (WMS) * `get_b2b_overview`, `list_companies`, `get_company` * `list_quotes`, `get_quote`, `create_outbound_quote`, `send_quote_offer` * `list_approvals`, `update_approval` * `list_warehouse_bins`, `list_cycle_counts` ### Schema Discovery & GraphQL Execution * `find_commerce_api`, `describe_commerce_api` * `read_admin_api`, `read_store_api`, `write_admin_api` * `execute_graphql`, `execute_store_graphql`, `execute_admin_graphql` *** ## Storefront & B2B Buyer Tools (`/mcp/store`) Authenticated shoppers and B2B company buyers can authorize personal shopping assistants on `/mcp/store` with strict account & company isolation: | Tool | Description | | :--------------------------- | :---------------------------------------------------------------------------------------- | | `store_search_products` | Search published catalog items with live availability and contextual pricing. | | `store_get_product` | Inspect full product specs, options, and variant SKUs. | | `store_get_my_pricing` | Resolve the caller's exact customer-group or B2B contract price list rates. | | `store_list_my_orders` | List orders belonging to the authenticated buyer (or their B2B company if Company Admin). | | `store_get_my_order` | Fetch line items, fulfillment tracking, and totals for a specific order. | | `store_list_my_quotes` | View active and historical B2B RFQ quotes. | | `store_request_quote` | Submit a new B2B Request-for-Quote directly from agent conversation. | | `store_create_checkout_cart` | Assemble a live cart with selected variants and return a ready-to-pay checkout link. | # TypeScript SDK (@xclade/sdk) # `@xclade/sdk` (v2.0) `@xclade/sdk` is xclade's official, **zero-dependency** pure GraphQL TypeScript SDK. It ships both ESM and CJS builds and covers both GraphQL surfaces: * **`sdk.store.*` & `sdk.client.queryStore(...)`** → Storefront & B2B Buyer GraphQL (`POST /graphql`) * **`sdk.graphql.*`, `sdk.auth.*`, `sdk.admin.*` & `sdk.client.queryAdmin(...)`** → Merchant Admin GraphQL (`POST /admin/graphql`) *** ## Installation ```bash pnpm add @xclade/sdk # or npm install @xclade/sdk ``` *** ## Storefront & B2B Setup ```ts import { createXcladeSDK } from '@xclade/sdk'; export const xclade = createXcladeSDK({ baseUrl: process.env.NEXT_PUBLIC_XCLADE_API_URL!, // https://{shortId}.api.myxclade.com publishableKey: process.env.NEXT_PUBLIC_XCLADE_PUBLISHABLE_KEY!, // pk_live_... }); ``` ### Catalog & Contextual Pricing ```ts // List products with USD contextual pricing const { products, count } = await xclade.store.listProducts({ limit: 20, offset: 0, currency_code: 'usd', }); // Fetch product by URL handle const product = await xclade.store.getProduct({ handle: 'apex-pro-kit', currency_code: 'usd', }); // Search variants directly by SKU (great for B2B quick-order matrices) const variants = await xclade.store.listProductVariants({ q: 'SKU-100', pricing_context: { currency_code: 'usd' }, }); ``` ### Cart, Promotions & Checkout ```ts const cart = await xclade.store.createCart({ region_id: 'reg_01...', email: 'buyer@company.com', }); await xclade.store.addCartLineItems(cart.id, [ { variant_id: 'variant_01...', quantity: 2 }, ]); await xclade.store.addCartPromotions(cart.id, 'SAVE15'); const options = await xclade.store.listShippingOptions(cart.id); await xclade.store.addCartShippingMethod(cart.id, options.shipping_options[0].id); const collection = await xclade.store.createPaymentCollection(cart.id); await xclade.store.initializePaymentSession(collection.id, 'pp_stripe_stripe'); const order = await xclade.store.completeCart(cart.id); ``` ### Customer Auth & B2B Wholesale ```ts // Email + password login (stores customer JWT automatically in browser storage) const auth = await xclade.store.customerLogin('buyer@company.com', 'secret'); const me = await xclade.store.customerMe(); // B2B Company, Employees, Quotes & Approvals const company = await xclade.store.myCompany(); const quote = await xclade.store.requestQuote(cart.id); await xclade.store.createQuoteMessage({ quote_id: quote.id, text: 'Can we lock Net-30 pricing on 50 units?', }); await xclade.store.acceptQuote(quote.id); // Submit cart for Company Admin / Sales Manager sign-off await xclade.store.createCartApprovals(cart.id); await xclade.store.updateApproval('appr_01...', 'approved'); ``` ### Raw Storefront GraphQL Need custom field selection or fragments? Execute raw GraphQL directly through the same authenticated client: ```ts const data = await xclade.store.query<{ siteSettings: { store_name: string } }>( `query SiteHeader { siteSettings { store_name navigation_menus { id name items { label url } } } }`, ); ``` *** ## Merchant Admin Setup ```ts import XcladeSDK, { getStoredAdminJwt, setStoredAdminJwt } from '@xclade/sdk'; export const adminSdk = new XcladeSDK({ baseUrl: 'https://{shortId}.api.myxclade.com', jwtStorageKey: 'xclade_admin_jwt', auth: { type: 'session', jwtTokenStorageKey: 'xclade_admin_jwt', }, }); const me = await adminSdk.graphql.me(); const { products, count } = await adminSdk.graphql.listProducts({ limit: 20, offset: 0 }); const overview = await adminSdk.graphql.analyticsOverview({ currency_code: 'usd' }); ``` *** ## Locale Management Switch translation locales dynamically—automatically attaches `X-Xclade-Locale` to subsequent requests: ```ts xclade.setLocale('fr-FR'); const localizedCatalog = await xclade.store.listProducts({ limit: 12, currency_code: 'eur' }); ``` *** ## Error Handling All GraphQL and transport errors surface via typed `XcladeError` / `FetchError` instances: ```ts import { XcladeError, FetchError, mapGraphQLCodeToHttpStatus } from '@xclade/sdk'; try { await xclade.store.completeCart(cartId); } catch (err) { if (err instanceof XcladeError) { console.error(err.code, err.message, err.field); if (err.code === 'IDRABBIT_VERIFICATION_REQUIRED') { // Redirect customer to ID Rabbit age/ID verification session } } else if (err instanceof FetchError) { console.error('HTTP status:', err.status, err.message); } } ``` # Headless Starter Storefront import { Download } from 'lucide-react'; # Headless Starter Storefront If you prefer hosting a bespoke Next.js storefront outside of [Storefront Studio](/docs/storefront-studio), you can clone the **xclade Store Starter** or wire `@xclade/sdk` directly into any React, Next.js, Remix, or mobile app. } href="https://github.com/xclade/businessx" title="View Starter on GitHub"> Next.js storefront wired to xclade Go GraphQL, multi-currency carts, Stripe/Authorize.Net checkout, and optional B2B quoting. *** ## Prerequisites * **Node.js** 20+ and **pnpm** * An **xclade store** provisioned in [xclade Console](https://app.xclade.com) * A **Publishable API Key** (`pk_...`) linked to your Storefront Sales Channel *** ## Setup ### 1. Clone & Install ```bash git clone https://github.com/xclade/businessx.git cd businessx pnpm install ``` ### 2. Configure Environment Variables Copy `.env.example` to `.env.local` and point it at your isolated store pod: ```bash # Your store's Go backend origin (Storefront GraphQL is served at /graphql) NEXT_PUBLIC_XCLADE_API_URL=https://{shortId}.api.myxclade.com # Publishable API Key scoping catalog, pricing & carts to your Sales Channel NEXT_PUBLIC_XCLADE_PUBLISHABLE_KEY=pk_live_... ``` Generate a Publishable API Key inside your store's Admin Console (`https://{shortId}.api.myxclade.com/app`) under **Settings → Publishable API Keys**, and add your local/production storefront origin under **Settings → Store Configuration** so dynamic CORS permits browser requests to `/graphql`. ### 3. Run Locally ```bash pnpm dev ``` *** ## Connecting with `@xclade/sdk` v2 In any custom Next.js App Router project: ```ts // lib/xclade.ts import { createXcladeSDK } from '@xclade/sdk'; export const xclade = createXcladeSDK({ baseUrl: process.env.NEXT_PUBLIC_XCLADE_API_URL!, publishableKey: process.env.NEXT_PUBLIC_XCLADE_PUBLISHABLE_KEY!, }); ``` ```tsx // app/products/page.tsx import { xclade } from '@/lib/xclade'; export default async function ProductsPage() { const { products } = await xclade.store.listProducts({ limit: 24, currency_code: 'usd', }); return ( ); } ``` *** ## Deploying to Production 1. Add your production storefront origin (e.g. `https://shop.yourbrand.com`) to your store's allowed origins in **Settings → Store Configuration** (or connect it as a custom domain in the xclade Console). 2. Set `NEXT_PUBLIC_XCLADE_API_URL` and `NEXT_PUBLIC_XCLADE_PUBLISHABLE_KEY` in Vercel or your hosting provider. 3. Deploy and verify `POST /graphql` returns `X-Cache: HIT` on repeat anonymous catalog queries. *** ## Next Steps Full Storefront and Admin SDK methods, locale switching, and typed error handling. Copy-pasteable operations for catalog, carts, ID Rabbit verification, OTP login, and B2B flows. # Storefront Studio & Templates # Storefront Studio & Templates **Storefront Studio** lets merchants design, customize, and publish production storefronts directly from `https://app.xclade.com` with zero external hosting setup—while giving engineers full code-level control via custom React + Tailwind TSX components and Git-backed templates. *** ## How It Works Every store has a canonical **`StorefrontDocument`** stored in the Control Plane and rendered live by the **Hosted Storefront Fleet** (`xclade-edge` + `xclade-storefront`): * **Design Tokens:** Brand colors, typography stacks, button radii, spacing, and dark/light surfaces—also inherited automatically by **Growth Studio** email templates. * **Navigation & Shell:** Customizable sticky headers, announcement bars, mega menus, and footers. * **Pages & Sections:** Composable home, collection, product, cart, checkout, account, and custom landing pages. * **Conditional B2B Configuration:** Enable or disable B2B wholesale registration, quick-order matrix, and RFQ quote drawers per store (`document.b2b`). * **Custom TSX Sections:** Author sandboxed React + Tailwind components compiled server-side by `xclade-api` and hydrated with the live commerce context (`@xclade/commerce`) on the storefront. *** ## Git-Backed Template Format (`xclade/store-templates`) Storefront templates live as self-contained folders under `templates//`: ```text templates/ └── atelier-noir/ ├── manifest.json # Template metadata, vertical, badge, palette, component list ├── document.json # Canonical StorefrontDocument (tokens, header, footer, pages) ├── preview.webp # Optional cover image (auto-uploaded to S3 / cdn.xclade.com) └── components/ ├── HeroEditorial.tsx └── FeatureMarquee.tsx ``` ### `manifest.json` Structure ```json { "slug": "atelier-noir", "name": "Atelier Noir", "version": "1.0.0", "vertical": "fashion", "badge": "Editorial", "tagline": "Minimal high-contrast flagship storefront", "description": "Full-bleed photography, tactile transitions, and instant faceted search.", "previewPalette": ["#0B0B0C", "#FFFFFF", "#D4AF37"], "sortOrder": 10, "coverImage": "preview.webp", "components": [ { "key": "hero-editorial", "name": "Hero Editorial", "file": "components/HeroEditorial.tsx" } ] } ``` *** ## Validation & Publishing via CI Validate template manifests, section references, links, and TSX compilation safety before publishing: ```bash # Validate all templates locally node scripts/validate.mjs # Publish a single template (or all templates) to the Control Plane XCLADE_TEMPLATE_PUBLISH_TOKEN=... node scripts/publish.mjs atelier-noir ``` Templates publish directly to the root-mounted Control Plane endpoint: ```http POST https://api.xclade.com/storefront/templates/publish ``` *** ## Bidirectional GitHub Sync Templates flow cleanly in both directions: 1. **Git → Studio:** Pushing to your connected template repository triggers `/webhooks/github/store-templates` (or manual sync from the Console) to register new template versions automatically. 2. **Live Store → Studio & Git:** After editing a storefront visually or with the Studio AI Assistant, publish a snapshot directly to a versioned release—with optional atomic commit back to GitHub. *** ## Custom Domains & Storefront Routing * Every store starts live immediately at `https://{shortId}.myxclade.com`. * Attach custom apex and `www` domains (e.g. `yourbrand.com`) from **Console → Domains**; `xclade-edge` handles domain resolution, apex/www canonicalization, and automated TLS 1.3 certificates. * Storefront Studio AI runs and theme publishes propagate immediately without redeploying the store's Go backend pod. # Webhooks & Integrations # Webhooks & Integrations xclade handles webhooks across three layers: **inbound store-pod provider webhooks**, **inbound Control Plane webhooks**, and **outbound tenant event webhooks**. *** ## 1. Store Pod Inbound Webhooks Mounted directly on every isolated store pod (`https://{shortId}.api.myxclade.com`): | Endpoint | Provider | Verification | | :----------------------------- | :--------------------- | :----------------------------------------------------------------------------------- | | `POST /webhooks/stripe` | Stripe | `Stripe-Signature` HMAC verification against the store's webhook secret. | | `POST /webhooks/authorizenet` | Authorize.Net | `X-ANET-Signature` SHA-512 HMAC verification. | | `POST /webhooks/idrabbit` | ID Rabbit | Cryptographic signature check updating cart/order identity & 21+ verification state. | | `POST /webhooks/shipstation` | ShipStation | Carrier shipment & tracking synchronization. | | `POST /webhooks/easypost` | EasyPost | Real-time carrier tracking event ingestion. | | `POST /webhooks/shippo` | Shippo | Fulfillment label & tracking updates. | | `POST /webhooks/zoho-order` | Zoho Books / Inventory | Order status and invoice sync. | | `POST /webhooks/zoho-skuvault` | Zoho / SkuVault | Warehouse stock level synchronization. | *** ## 2. Control Plane Inbound Webhooks Mounted directly at root on `https://api.xclade.com`: | Endpoint | Provider | Purpose | | :-------------------------------------- | :------------- | :-------------------------------------------------------------------------------------------------------------------------- | | `POST /webhooks/stripe` | Stripe Billing | Subscription lifecycle, invoices, and add-on entitlements. | | `POST /webhooks/ses` | AWS SNS (SES) | Cryptographically verified SNS notifications for email deliveries, bounces, complaints, opens, and clicks in Growth Studio. | | `POST /webhooks/github/storefront` | GitHub | Automatic sync for merchant repositories linked to Storefront Studio. | | `POST /webhooks/github/store-templates` | GitHub | Automatic registry updates when templates push to `xclade/store-templates`. | *** ## 3. Outbound Tenant Webhooks Subscribe your ERP, WMS, or custom microservices to store events via Merchant Admin GraphQL (`POST /admin/graphql`) or the Store Admin Console: ```graphql mutation CreateWebhook { upsertWebhookEndpoint( url: "https://erp.yourbrand.com/hooks/xclade" events: ["order.placed", "order.fulfilled", "quote.accepted", "inventory.adjusted"] enabled: true ) { id url events enabled } } ``` Inspect active endpoints with: ```graphql query ListWebhooks { webhookEndpoints { id url events enabled created_at } } ``` ### Best Practices for Webhook Receivers * **Verify signatures** before processing any payload. * **Process idempotently** using event/order IDs so retries never create duplicate ERP orders or inventory adjustments. * **Return `2xx` quickly** (under 5 seconds) and offload heavy downstream work to your own background queue. # Advanced Features # Advanced Features ## 1. Multi-Region & Multi-Currency Pricing xclade supports 135+ currencies and multi-region tax rules natively. Query available regions once at startup (cached for 30 minutes in Redis): ```graphql query StoreRegions { regions { regions { id name currency_code countries { iso_2 display_name } } } } ``` Pass the selected `region_id` when creating carts (`createCart(input: { region_id })`) and querying catalog prices (`pricing_context: { region_id }`). For authenticated B2B company buyers, customer-group override price lists automatically layer on top of base region pricing. *** ## 2. Localized Storefronts (`X-Xclade-Locale`) Fetch active store locales (cached for 60 minutes): ```graphql query ActiveLocales { locales { code name } } ``` Send `X-Xclade-Locale: fr-FR` (or call `xclade.setLocale('fr-FR')` in `@xclade/sdk`). Redis response cache keys automatically partition by locale so localized responses never collide. *** ## 3. Automatic Persisted Queries (APQ) `/graphql` enables `gqlgen`'s APQ extension (`512`-entry LRU hash cache) alongside `GET` transport: 1. Client sends a `GET /graphql` request with `extensions={"persistedQuery":{"version":1,"sha256Hash":"..."}}` and `X-Xclade-Request: true`. 2. If the hash is warm on the pod, the query executes immediately without transmitting the query string. 3. On a cache miss (`PersistedQueryNotFound`), the client retries once with both `query` and `sha256Hash` to register it. *** ## 4. ID Rabbit Age (21+) & Identity Verification Stores selling age-restricted or high-fraud goods can enforce pre-checkout verification via **ID Rabbit**: 1. Query `cartIdrabbitStatus(cart_id)` before allowing checkout submission. 2. When `required === true` and `checkout_decision !== "allow"`, invoke `createCartIdrabbitSession(cart_id, redirect_url)` and redirect the shopper to `idrabbit.verification_url`. 3. When ID Rabbit posts the signed webhook to `POST /webhooks/idrabbit`, the cart's verification state updates automatically and `completeCart(cart_id)` succeeds. 4. Attempting `completeCart` before verification completes safely returns `IDRABBIT_VERIFICATION_REQUIRED`. *** ## 5. Order Ownership Transfers Support B2B team handoffs or gift/account merges with built-in order transfer mutations: 1. `requestOrderTransfer(order_id, description)` — Generates a secure transfer token. 2. `acceptOrderTransfer(order_id, token)` or `declineOrderTransfer(order_id, token)` — Recipient accepts or declines. 3. `cancelOrderTransfer(order_id)` — Original requester or Store Admin cancels before acceptance. # Authentication & Headers # Authentication & Request Headers xclade uses a **dual-actor authentication model** (`customer` and `user`) combined with **Publishable API Keys** for sales-channel scoping. *** ## HTTP Headers Reference | Header | Accepted Alias | Purpose | | :------------------------- | :---------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------- | | `X-Xclade-Publishable-Key` | `X-Publishable-Api-Key` | Scopes catalog queries, stock availability, and new carts to the Sales Channels linked to your `pk_...` key. | | `Authorization` | — | `Bearer ` (customer or admin JWT) or `Bearer sk_...` (merchant secret API key). | | `X-Xclade-Locale` | `X-Locale` | BCP-47 locale tag (e.g. `en-US`, `fr-FR`, `de-DE`) for localized catalog responses and cache isolation. | | `X-Xclade-Request` | `X-GraphQL-Request`, `Apollo-Require-Preflight` | CSRF preflight marker required for non-browser `GET /graphql` queries in production (also satisfied when `X-Xclade-Publishable-Key` is present). | | `X-Store-Domain` | `Host` | Storefront origin domain used for tenant scope resolution when no publishable key is supplied. | *** ## Dual-Actor Authentication xclade distinguishes two principal actor types via the `ActorType` enum: * **`customer`** — Storefront shoppers and B2B company employees (default for `login`, `requestEmailOtp`, `verifyEmailOtp`, and password resets). * **`user`** — Store administrators (used for admin access on `/graphql` and `/admin/graphql`). ### 1. Email & Password Login ```graphql mutation LoginCustomer($email: String!, $password: String!) { login(email: $email, password: $password, actor_type: customer) { token expires_at status customer { id email first_name last_name } } } ``` Pass the returned JWT on subsequent requests: ```http Authorization: Bearer eyJhbGciOiJIUzI1NiIs... ``` ### 2. Passwordless 6-Digit Email OTP Dispatch a single-use 6-digit verification code and exchange it for a signed JWT bearer token: ```graphql mutation RequestOtp($email: String!) { requestEmailOtp(email: $email, actor_type: customer) { success message } } ``` ```graphql mutation VerifyOtp($email: String!, $code: String!) { verifyEmailOtp(email: $email, code: $code, actor_type: customer) { token expires_at customer { id email } } } ``` ### 3. Inspecting Active Auth State Call `authStatus` (never cached) to verify the current token or session cookie: ```graphql query CheckAuth { authStatus { authenticated actor_type customer { id email } user { id email } } } ``` ### 4. Password Reset ```graphql mutation RequestReset($email: String!) { requestPasswordReset(email: $email, actor_type: customer) { success message } } mutation CompleteReset($token: String!, $password: String!, $email: String) { resetPassword(token: $token, password: $password, email: $email, actor_type: customer) { success message } } ``` *** ## Merchant Secret API Keys (`sk_...`) For trusted server-to-server integrations, ERP bridges, or scripts, generate a secret API key in your store's Admin Console and send it as a bearer token: ```http Authorization: Bearer sk_live_... ``` Never expose `sk_...` secret keys in browser bundles or client-side code. Use `pk_...` Publishable API Keys for public storefronts and customer JWTs for authenticated shopper sessions. *** ## Cache Isolation for Authenticated Requests Whenever a request carries a valid `customer` or `user` identity—or calls a private resolver (`RequireAuth`, `RequireCustomer`, `RequireAdmin`)—the Go middleware automatically bypasses `XcladeResponseCache` and sets: ```http Cache-Control: private, no-store ``` # Best Practices # Best Practices ## 1. Separate Public Catalog Reads from Private Session Reads Because `XcladeResponseCache` only caches queries whose **every** root field is in the public allowlist and whose request is **anonymous**, avoid mixing `products` and `activeCustomerCart` or `authStatus` into the same GraphQL document. * **Good:** Issue `products` / `siteSettings` / `regions` anonymously (or cached on the server) so they hit Redis (`X-Cache: HIT`), and fetch `activeCustomerCart` / `myCompany` separately with the customer bearer token. * **Avoid:** Combining `products` and `cart` in one query—doing so forces the entire response to `Cache-Control: private, no-store`. *** ## 2. Always Supply `pricing_context` When Selecting `calculated_price` Pass at least `region_id` (recommended, since it resolves both currency and tax-inclusivity rules) or `currency_code` inside `pricing_context`: ```graphql query PricedCatalog($regionId: String!) { products(limit: 24, pricing_context: { region_id: $regionId }) { products { id title variants { id sku calculated_price { calculated_amount original_amount currency_code } } } } } ``` *** ## 3. Use `addCartLineItemsBulk` for Multi-SKU Additions For B2B quick-order matrices, CSV paste forms, and bundle add-to-cart flows, use `addCartLineItemsBulk` instead of looping `addCartLineItem`. It executes atomically in one request, avoids hitting the `150 req/min` rate limiter, and recalculates taxes/promotions once. *** ## 4. Handle Both B2C and B2B Cleanly Check `myCompany` after customer sign-in: * If `myCompany` is `null`, render the standard retail checkout flow. * If `myCompany` is present, show the customer's company name, employee spending limit, **Request a Quote** (`requestQuote`), and **Submit for Approval** (`createCartApprovals`) actions when `approval_settings` requires sign-off. *** ## 5. Refresh Payment Collections After Cart Edits Whenever a buyer edits line-item quantities, applies a promo code, or switches shipping methods after creating a payment collection, call `refreshPaymentCollection(cart_id)` before finalizing payment so the authorized amount always matches `cart.total`. *** ## 6. Keep Queries Lean and Shallow * Stay well below the depth cap (`10` on `/graphql`) and avoid circular selections (e.g. `product → variants → product → variants`). * Always paginate list queries (`limit` + `offset`) rather than requesting unbounded pages. * Include `X-Xclade-Publishable-Key` and `X-Xclade-Request: true` on every storefront request. # Changelog # Platform Changelog ## v3.0 — Native Go 1.26 Commerce Engine & Platform Expansion ### Native Go Store Runtime (`xclade-store-backend`) * Compiled the entire Storefront & Merchant Admin GraphQL engine natively into a single **Go 1.26** binary (`gqlgen` + `chi/v5` + `pgx/v5` + `go-redis/v9`). * Shipped dual GraphQL surfaces: **Storefront & B2B GraphQL** (`POST /graphql`, 53 queries, 45 mutations) and **Merchant Admin GraphQL** (`POST /admin/graphql`, 31 queries, 65 mutations + SSE subscriptions + `@requirePermission` RBAC). * Added native **Go DataLoader** SQL batching, **Automatic Persisted Queries (APQ)**, **`XcladeResponseCache`** (Redis-backed 17-field public allowlist with mutation tag invalidation), and **`XcladeGraphQLArmor`** AST guards. * Added passwordless 6-digit email OTP authentication (`requestEmailOtp`, `verifyEmailOtp`) and pre-checkout **ID Rabbit** age (21+) & identity verification (`cartIdrabbitStatus`, `createCartIdrabbitSession`). ### `@xclade/sdk` v2.0 * Released zero-dependency pure GraphQL TypeScript SDK unifying Storefront (`sdk.store.*`) and Merchant Admin (`sdk.graphql.*`, `sdk.auth.*`, `sdk.admin.*`) in one package. ### Remote MCP & Agentic Commerce * Shipped dual OAuth 2.1 Streamable HTTP/SSE Remote MCP servers on every store pod: **`/mcp`** (45+ admin commerce, B2B, WMS, pricing, analytics, and RBAC tools) and **`/mcp/store`** (8 buyer tools). * Added native **Google UCP**, **OpenAI ACP**, **A2A**, **`/llms.txt`**, **`/products/{handle}.md`**, **WebMCP**, **AP2 Mandates**, **x402**, and **RFC 9421 Web Bot Auth**. ### Storefront Studio & Growth Studio * Launched **Storefront Studio** with visual editing, sandboxed custom React/Tailwind TSX section compilation, and bidirectional GitHub template sync (`xclade/store-templates`). * Launched **Growth Studio** on AWS SES Production (`xclade-growth`) with retail-first templates, conditional B2B tools, visual block compilation, automation flows, RFM scoring, and **mandatory verified custom sending domains (2048-bit RSA DKIM)** across all sends including test emails. * Standardized the Go Control Plane cleanly at the root of **`https://api.xclade.com`**. # Client Libraries & SDK # Client Libraries & SDK ## 1. Official `@xclade/sdk` (Recommended) `@xclade/sdk` v2.0 is a zero-dependency TypeScript SDK built specifically for xclade's Go GraphQL endpoints (`/graphql` and `/admin/graphql`): ```bash pnpm add @xclade/sdk ``` ```ts import { createXcladeSDK } from '@xclade/sdk'; export const xclade = createXcladeSDK({ baseUrl: 'https://{shortId}.api.myxclade.com', publishableKey: 'pk_live_...', }); const { products } = await xclade.store.listProducts({ limit: 12, currency_code: 'usd', }); ``` See the full [`@xclade/sdk` guide](/docs/sdk) for Storefront, B2B, and Merchant Admin usage. *** ## 2. Zero-Dependency `fetch` (Next.js Server Components) ```ts export async function xcladeGraphQL( query: string, variables?: Record, options?: { token?: string; locale?: string; revalidate?: number }, ): Promise { const headers: Record = { 'Content-Type': 'application/json', 'X-Xclade-Publishable-Key': process.env.NEXT_PUBLIC_XCLADE_PUBLISHABLE_KEY!, 'X-Xclade-Request': 'true', }; if (options?.token) { headers.Authorization = `Bearer ${options.token}`; } if (options?.locale) { headers['X-Xclade-Locale'] = options.locale; } const res = await fetch(`${process.env.NEXT_PUBLIC_XCLADE_API_URL}/graphql`, { method: 'POST', headers, body: JSON.stringify({ query, variables }), next: options?.revalidate !== undefined ? { revalidate: options.revalidate } : undefined, }); const payload = await res.json(); if (payload.errors?.length) { const first = payload.errors[0]; throw new Error(`[${first.extensions?.code ?? 'GRAPHQL_ERROR'}] ${first.message}`); } return payload.data as T; } ``` *** ## 3. `urql` with Automatic Persisted Queries (APQ) xclade's Go `gqlgen` server supports **Automatic Persisted Queries (APQ)** (`512`-entry LRU hash cache) and `GET /graphql` queries for CDN caching. Always include `X-Xclade-Publishable-Key` and `X-Xclade-Request: true` so GET requests pass CSRF preflight: ```ts import { Client, cacheExchange, fetchExchange } from '@urql/core'; import { persistedExchange } from '@urql/exchange-persisted'; export const urqlClient = new Client({ url: 'https://{shortId}.api.myxclade.com/graphql', fetchOptions: () => ({ headers: { 'X-Xclade-Publishable-Key': process.env.NEXT_PUBLIC_XCLADE_PUBLISHABLE_KEY!, 'X-Xclade-Request': 'true', }, }), exchanges: [ cacheExchange, persistedExchange({ preferGetForPersistedQueries: true, }), fetchExchange, ], }); ``` *** ## 4. `graphql-request` ```ts import { GraphQLClient } from 'graphql-request'; export const gql = new GraphQLClient('https://{shortId}.api.myxclade.com/graphql', { headers: { 'X-Xclade-Publishable-Key': process.env.NEXT_PUBLIC_XCLADE_PUBLISHABLE_KEY!, 'X-Xclade-Request': 'true', }, }); ``` # Error Handling # Error Handling All GraphQL errors returned by `/graphql` and `/admin/graphql` pass through the Go `ErrorPresenter` (`graph/middleware/security.go`), ensuring consistent machine-readable `extensions.code` values and safe error masking in production. *** ## Response Format ```json { "data": null, "errors": [ { "message": "query depth 12 exceeds maximum allowed depth 10", "path": ["products"], "extensions": { "code": "QUERY_DEPTH_EXCEEDED" } } ] } ``` When a validation error targets a specific input field, `extensions.field` is included automatically. *** ## Wire Error Codes | `extensions.code` | HTTP Status | Meaning & Recommended Action | | :------------------------------- | :------------ | :---------------------------------------------------------------------------------------------------------- | | `UNAUTHENTICATED` | `200` / `401` | Missing, expired, or invalid JWT / secret key. Prompt sign-in or refresh session. | | `FORBIDDEN` | `200` / `403` | Authenticated actor lacks ownership, B2B Company Admin role, or Admin RBAC policy. | | `NOT_FOUND` | `200` / `404` | Target product, cart, order, quote, or customer does not exist in this store. | | `BAD_USER_INPUT` | `200` / `400` | Validation error on query arguments or mutation input (inspect `extensions.field`). | | `PAYMENT_AUTHORIZATION_ERROR` | `200` / `402` | Payment provider declined or failed to authorize the payment session. | | `IDRABBIT_VERIFICATION_REQUIRED` | `200` / `403` | Checkout blocked pending ID Rabbit identity/21+ verification—call `createCartIdrabbitSession`. | | `RATE_LIMIT_EXCEEDED` | `429` | Per-actor or per-IP Redis sliding-window rate limit (`150 req/min`) exceeded. Back off with jitter. | | `QUERY_DEPTH_EXCEEDED` | `200` | AST selection depth exceeded (`10` on `/graphql`, `14` on `/admin/graphql`). Flatten selection sets. | | `ALIAS_LIMIT_EXCEEDED` | `200` | Query used more aliases than allowed (`15` on `/graphql`, `30` on `/admin/graphql`). | | `DIRECTIVE_LIMIT_EXCEEDED` | `200` | Query used more directives than allowed (`50` on `/graphql`, `75` on `/admin/graphql`). | | `QUERY_TOO_LARGE` | `413` | Request body exceeded payload limit (`~105 KB` on `/graphql`, `16 MiB` on `/admin/graphql`). | | `BATCH_LIMIT_EXCEEDED` | `400` | Batched JSON array exceeded `5` operations. Split into separate requests. | | `CSRF_PREFLIGHT_REQUIRED` | `400` | `GET /graphql` request omitted a preflight header (`X-Xclade-Request: true` or `X-Xclade-Publishable-Key`). | | `INTERNAL_SERVER_ERROR` | `200` / `500` | Unexpected server error (masked in production to avoid leaking internals). | *** ## Handling Errors with `@xclade/sdk` ```ts import { XcladeError, FetchError } from '@xclade/sdk'; try { const order = await xclade.store.completeCart(cartId); } catch (err) { if (err instanceof XcladeError) { switch (err.code) { case 'IDRABBIT_VERIFICATION_REQUIRED': { const res = await xclade.store.query( `mutation($id: ID!) { createCartIdrabbitSession(cart_id: $id) { idrabbit { verification_url } } }`, { id: cartId }, ); window.location.href = res.createCartIdrabbitSession.idrabbit.verification_url; break; } case 'PAYMENT_AUTHORIZATION_ERROR': showToast('Your card could not be authorized. Please try another payment method.'); break; default: showToast(err.message); } } else if (err instanceof FetchError && err.status === 429) { showToast('Too many requests. Retrying shortly...'); } } ``` # Overview # Storefront & B2B GraphQL (`/graphql`) Every xclade store serves a strongly-typed, code-generated **Go 1.26 (`gqlgen`)** GraphQL endpoint at: ```http POST https://{shortId}.api.myxclade.com/graphql ``` Unlike legacy Node.js wrappers, the GraphQL execution layer compiles directly into your store's Go binary—delivering low memory overhead, concurrent field execution, per-request Go DataLoader batching, and predictable sub-50ms p95 latency. *** ## Core Capabilities | Capability | Implementation | | :--------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Schema Coverage** | **22 domain schema files**, **53 Queries**, and **45 Mutations** spanning DTC catalog, contextual pricing, carts, checkout, ID Rabbit verification, passwordless OTP, orders, returns, reviews, and full B2B wholesale. | | **Runtime Engine** | Native Go 1.26 + `github.com/99designs/gqlgen` + `chi/v5` + `pgx/v5` + `go-redis/v9`. | | **N+1 Prevention** | Per-request Go DataLoader batching (`graph/loaders/`) for collections, categories, product types, currencies, regions, countries, and order items. | | **Response Caching** | Built-in `XcladeResponseCache` caches 17 allowlisted public queries in Redis, isolated by tenant scope, publishable key sales channels, locale, and actor—with automatic `gql:public` tag invalidation on mutations. | | **Persisted Queries** | Automatic Persisted Queries (APQ) backed by an LRU hash cache (`512` entries) plus a `1,000`-entry parsed AST cache. | | **Security Hardening** | Built-in `XcladeGraphQLArmor` enforcing AST depth, alias, directive, batch, payload size, execution timeout, CSRF GET preflight, and Redis sliding-window rate limits. | *** ## Dual GraphQL Surfaces Every store pod exposes two cleanly separated GraphQL endpoints: * **`POST /graphql`** — Storefront, customer accounts, and B2B buyer workflows *(documented in this section)*. * **`POST /admin/graphql`** — Back-office operations, RBAC, WMS bins/cycle counts, analytics, and batch imports *(see [Merchant Admin GraphQL](/docs/admin-graphql))*. *** ## Minimal Example ```bash curl -X POST https://{shortId}.api.myxclade.com/graphql \ -H "Content-Type: application/json" \ -H "X-Xclade-Publishable-Key: pk_live_..." \ -H "X-Xclade-Request: true" \ -d '{ "query": "query Catalog($currency: String!) { products(limit: 4, pricing_context: { currency_code: $currency }) { products { id title handle variants { id sku inventory_quantity calculated_price { calculated_amount currency_code } } } count } }", "variables": { "currency": "usd" } }' ``` *** ## Next Steps Publishable keys, customer/admin JWTs, passwordless 6-digit email OTP, locale headers, and CSRF rules. Every single one of the 53 Storefront queries and 45 mutations with signatures and access levels. Schema-verified GraphQL operations ready to paste into your app or GraphiQL. Exact Go middleware caps for depth, aliases, directives, batching, payload sizes, and rate limits. # Limits & Quotas # Security Limits & Quotas All limits below reflect the exact defaults compiled into `xclade-store-backend` (`internal/platform/config/config.go`, `internal/server/router.go`, and `graph/middleware/security.go`). *** ## Limit Comparison Table | Control | Storefront (`/graphql`) | Admin (`/admin/graphql`) | Wire Error Code | | :----------------------- | :------------------------------------------------------------- | :-------------------------------- | :-------------------------------- | | **Max AST Depth** | `10` (`GRAPHQL_MAX_DEPTH`) | `14` (`GRAPHQL_MAX_DEPTH + 4`) | `QUERY_DEPTH_EXCEEDED` | | **Max Aliases** | `15` | `30` | `ALIAS_LIMIT_EXCEEDED` | | **Max Directives** | `50` | `75` | `DIRECTIVE_LIMIT_EXCEEDED` | | **Max Complexity** | `1500` (`GRAPHQL_MAX_COMPLEXITY`) | `1500` | — | | **Max Batch Size** | `5` (`GRAPHQL_MAX_BATCH`) | `5` | `BATCH_LIMIT_EXCEEDED` | | **Max Request Body** | `~105 KB` (`15,000` query + `25,000` vars + `64 KiB` buffer) | `16 MiB` (supports batch imports) | `QUERY_TOO_LARGE` (`413`) | | **Execution Timeout** | `10,000 ms` (`GRAPHQL_TIMEOUT_MS`) | `10,000 ms` | Request canceled | | **Rate Limit** | `150 req/min` per actor ID / IP (`GRAPHQL_RATE_LIMIT_PER_MIN`) | `150 req/min` per actor ID / IP | `RATE_LIMIT_EXCEEDED` (`429`) | | **Introspection (Prod)** | Disabled for anonymous/customers; allowed for Store Admins | Allowed for Store Admins | GraphQL error | | **CSRF Guard (`GET`)** | Enforced in production | Always enforced | `CSRF_PREFLIGHT_REQUIRED` (`400`) | *** ## Internal Query & Cache Capacities | Resource | Default Capacity | | :---------------------------------------------- | :-------------------------------------------------------------------- | | **Parsed AST LRU Cache** | `1,000` query documents per pod | | **Automatic Persisted Queries (APQ) LRU Cache** | `512` SHA-256 query hashes per pod | | **Default Public Response Cache TTL** | `300s` (`GRAPHQL_CACHE_TTL_SECONDS`, overridden per root query field) | | **Admin SSE Keep-Alive Ping** | `15s` | *** ## Scaling Limits Need higher sustained throughput, elevated rate budgets, or dedicated read replicas for flash drops? Upgrade your store pod tier (Mini, Startup, Scale, or Enterprise) directly from **Console → Billing & Plans** with zero downtime. # Migration Guide # Migration Guide ## 1. Upgrading from Legacy `@xclade/graphql-client` v1 to `@xclade/sdk` v2 If you built an earlier storefront against `@xclade/graphql-client` + `@xclade/types`, migrate to the unified zero-dependency **`@xclade/sdk` v2.0**: ```bash pnpm remove @xclade/graphql-client @xclade/types graphql-request pnpm add @xclade/sdk ``` ```ts // Before (v1) import { createGraphQLClient } from '@xclade/graphql-client'; // After (v2) import { createXcladeSDK } from '@xclade/sdk'; export const xclade = createXcladeSDK({ baseUrl: 'https://{shortId}.api.myxclade.com', publishableKey: 'pk_live_...', }); const { products } = await xclade.store.listProducts({ limit: 20, currency_code: 'usd', }); ``` ### Key Header & URL Updates * **Store GraphQL Endpoint:** `POST https://{shortId}.api.myxclade.com/graphql` (Storefront) and `POST https://{shortId}.api.myxclade.com/admin/graphql` (Admin). * **Control Plane Base URL:** Root-mounted directly at `https://api.xclade.com` (e.g. `https://api.xclade.com/orgs/*`, `https://api.xclade.com/health`). * **Preferred Headers:** `X-Xclade-Publishable-Key` (backwards-compatible with `X-Publishable-Api-Key`), `X-Xclade-Locale` (compatible with `X-Locale`), and `X-Xclade-Request: true` (compatible with `X-GraphQL-Request: true`). *** ## 2. Migrating from Shopify or BigCommerce xclade includes a built-in streaming migrator inside `https://app.xclade.com`: 1. Open your store in the **xclade Console → Migrations**. 2. Connect your Shopify or BigCommerce store credentials. 3. Run the streaming import for categories, collections, products (including multi-option variants & media mirrored directly to S3/CDN), customers, and historical orders. 4. For custom scripts or ERP migrations, use the high-throughput **Admin GraphQL Batch Mutations** (`importCategoriesBatch`, `importCollectionsBatch`, `importProductsBatch`, `importCustomersBatch`, `importOrdersBatch` — up to **16 MiB** per request on `/admin/graphql`). *** ## 3. Moving from Legacy REST Endpoints to Go GraphQL | Legacy REST Pattern | Native Go GraphQL Equivalent | | :------------------------------------ | :----------------------------------------------------------------------------------------------- | | `GET /store/products` | `query { products(limit: 20, pricing_context: { currency_code: "usd" }) { ... } }` on `/graphql` | | `POST /store/carts` | `mutation { createCart(input: { region_id: "..." }) { ... } }` on `/graphql` | | `POST /store/carts/:id/complete` | `mutation { completeCart(cart_id: "...") { ... } }` on `/graphql` | | `GET /admin/products` | `query { adminProducts(limit: 50) { ... } }` on `/admin/graphql` | | `POST /admin/orders/:id/fulfillments` | `mutation { createOrderFulfillment(input: { ... }) { ... } }` on `/admin/graphql` | # Performance & Caching # Performance & Caching xclade achieves sub-50ms storefront response times by combining **compiled Go execution**, **per-request DataLoader SQL batching**, **Redis response caching**, and **Automatic Persisted Queries**. *** ## 1. Go DataLoader SQL Batching Every GraphQL request hydrates a fresh set of per-request Go DataLoaders (`graph/loaders/`), collapsing nested resolver reads into single `WHERE id = ANY($1)` PostgreSQL queries for: * Collections (`ListCollectionsByIDs`) * Product Types (`ListProductTypesByIDs`) * Currencies (`ListCurrenciesByCodes`) * Regions & Countries (`ListRegionsByIDs`, `ListCountriesByRegionIDs`) * Order Line Items (`ListItemsByOrderIDs`) *** ## 2. `XcladeResponseCache` (Redis-Backed Allowlist) The Go `ResponseCacheExtension` (`graph/middleware/caching.go`) caches strictly **public, anonymous, read-only** Storefront queries in Redis. Every cache key hashes: ```text SHA-256( tenantScope | sorted(salesChannelIDs) | locale | operationName | rawQuery | variables ) ``` ### Allowlisted Public Root Queries & TTLs | Root Query Field | Redis TTL | | :---------------------------------------------------------------- | :------------- | | `locales`, `currency`, `currencies` | **60 minutes** | | `region`, `regions` | **30 minutes** | | `brand`, `brands` | **5 minutes** | | `product`, `productByHandle`, `products` | **1 minute** | | `collection`, `collectionByHandle`, `collections` | **1 minute** | | `productCategory`, `productCategoryByHandle`, `productCategories` | **1 minute** | | `siteSettings` | **1 minute** | When a single query selects multiple allowlisted root fields, the cache uses the **shortest TTL** among them. Any query containing a non-allowlisted root field (such as `cart`, `orders`, `authStatus`, `myCompany`, or `quotes`)—or any authenticated request or sensitive ID (`cart_id`, `company_id`, `customer_id`)—bypasses the cache completely and returns `Cache-Control: private, no-store`. ### Cache Headers & Automatic Invalidation * **Cache Hit:** Returns `X-Cache: HIT` and `Cache-Control: public, max-age=60, stale-while-revalidate=300`. * **Cache Miss:** Executes against Postgres, populates Redis under tag `gql:public`, and returns `X-Cache: MISS`. * **Automatic Invalidation:** Any successful mutation automatically invalidates the `gql:public` tag so catalog or CMS changes appear immediately. *** ## 3. Automatic Persisted Queries (APQ) & AST Cache * **Parsed AST LRU Cache:** Up to `1,000` parsed GraphQL documents stay hot in memory per store pod. * **APQ Hash Cache:** Clients supporting Apollo/urql APQ can send only the SHA-256 hash (`extensions.persistedQuery`) over `GET /graphql` (`512`-entry LRU cache), shrinking request payloads and enabling CDN edge caching on public catalog reads. *** ## 4. Typesense Instant Search For typo-tolerant faceted catalog search at scale, stores automatically index published products into **Typesense**. Trigger a full reindex at any time via Merchant Admin GraphQL: ```graphql mutation ReindexCatalog { reindexSearch } ``` # GraphQL Playground # GraphQL Playground xclade gives you interactive GraphQL exploration both inside your live store's Admin Console and in local development environments. *** ## 1. Embedded GraphiQL IDE (Production & Staging) Every store ships with a built-in **GraphQL Playground** inside the Store Admin Console at: ```text https://{shortId}.api.myxclade.com/app ``` Because production introspection is disabled for anonymous callers by default (`GRAPHQL_ALLOW_INTROSPECTION=false`), authenticating as a Store Admin inside `/app` automatically unlocks: * Full live schema introspection & autocomplete for all **53 Storefront queries** and **45 mutations** * Publishable API Key / Sales Channel selector * Ready-to-run query recipes for catalog, contextual pricing, carts, checkout, and B2B flows * Automatic `X-GraphQL-Request: true` header injection *** ## 2. Local Development Playgrounds When running `xclade-store-backend` in development mode (`IsDevelopment()`), the Go router automatically mounts interactive `gqlgen` playgrounds for both schemas: | Path | Target Schema | | :---------------------- | :---------------------------------------- | | `GET /playground` | Storefront & B2B GraphQL (`/graphql`) | | `GET /admin/playground` | Merchant Admin GraphQL (`/admin/graphql`) | In production, `/playground` and `/admin/playground` are intentionally omitted and unauthenticated introspection (`__schema`, `__type`) is blocked by `XcladeGraphQLArmor`. *** ## 3. Testing with `curl` or Hoppscotch / Insomnia Include your Publishable API Key and CSRF marker header: ```bash curl -X POST https://{shortId}.api.myxclade.com/graphql \ -H "Content-Type: application/json" \ -H "X-Xclade-Publishable-Key: pk_live_..." \ -H "X-Xclade-Request: true" \ -d '{"query":"query { regions { regions { id name currency_code } } }"}' ``` # Queries & Mutations # Queries & Mutations Cookbook Every query and mutation below is validated directly against `xclade-store-backend/graph/store/schema/*.graphqls`. *** ## 1. Catalog & Contextual Pricing Always pass `pricing_context` (`region_id` or `currency_code`) when selecting `calculated_price`. Authenticated B2B buyers automatically resolve contract price lists. ```graphql query GetCatalog($limit: Int = 12, $offset: Int = 0, $currency: String = "usd", $q: String) { products( limit: $limit offset: $offset filter: { q: $q, is_giftcard: false } pricing_context: { currency_code: $currency } ) { count products { id title handle thumbnail variants { id title sku inventory_quantity calculated_price { calculated_amount original_amount currency_code } } } } } ``` ### Fetch Product by Handle ```graphql query ProductDetail($handle: String!, $regionId: String!) { productByHandle(handle: $handle, pricing_context: { region_id: $regionId }) { id title description handle images { id url } options { id title values { id value } } variants { id title sku inventory_quantity calculated_price { calculated_amount original_amount currency_code } } } } ``` ### B2B Quick-Order SKU Lookup ```graphql query QuickOrderSkuSearch($q: String!, $currency: String = "usd") { productVariants( limit: 20 filter: { q: $q } pricing_context: { currency_code: $currency } ) { count variants { id sku title inventory_quantity calculated_price { calculated_amount currency_code } product { id title handle thumbnail } } } } ``` *** ## 2. Shopping Cart & Promotions ### Create Cart & Add Items in Bulk ```graphql mutation CreateCart($regionId: String!, $email: String) { createCart(input: { region_id: $regionId, email: $email }) { id currency_code total } } ``` ```graphql mutation AddItemsBulk($cartId: ID!, $items: [AddCartLineItemInput!]!) { addCartLineItemsBulk(cart_id: $cartId, items: $items) { id subtotal tax_total discount_total total items { id title variant_sku quantity unit_price total } } } ``` ### Apply Promo Codes & Recalculate Taxes ```graphql mutation ApplyPromo($cartId: ID!, $codes: [String!]!) { addCartPromotions(cart_id: $cartId, promo_codes: $codes) { id discount_total total items { id adjustments { code amount description } } } } ``` *** ## 3. Shipping, Payments & Checkout ```graphql query CartShippingOptions($cartId: ID!) { shippingOptions(cart_id: $cartId) { shipping_options { id name amount price_type } } } ``` ```graphql mutation AttachShipping($cartId: ID!, $optionId: String!) { addCartShippingMethod(cart_id: $cartId, input: { option_id: $optionId }) { id shipping_total total } } ``` ```graphql mutation InitPayment($cartId: ID!, $providerId: String!) { createPaymentCollection(cart_id: $cartId) { id } } ``` ```graphql mutation StartPaymentSession($paymentCollectionId: ID!, $providerId: String!) { initializePaymentSession( payment_collection_id: $paymentCollectionId input: { provider_id: $providerId } ) { id payment_sessions { id provider_id status data } } } ``` ```graphql mutation CompleteCheckout($cartId: ID!) { completeCart(cart_id: $cartId) { id display_id status total currency_code created_at } } ``` *** ## 4. ID Rabbit Identity & 21+ Verification Gate For age-restricted or high-risk stores with ID Rabbit enabled, inspect verification state before calling `completeCart`: ```graphql query CheckVerification($cartId: ID!) { cartIdrabbitStatus(cart_id: $cartId) { required status checkout_decision verification_url require_21_plus } } ``` ```graphql mutation StartVerification($cartId: ID!, $redirectUrl: String) { createCartIdrabbitSession(cart_id: $cartId, redirect_url: $redirectUrl) { idrabbit { status checkout_decision verification_url request_id } } } ``` *** ## 5. B2B Companies, RFQ Quotes & Cart Approvals ### Inspect Buyer Company & Submit an RFQ Quote ```graphql query MyB2BCompany { myCompany { id name status currency_code spending_limit_reset_frequency approval_settings { requires_admin_approval requires_sales_manager_approval } employees { id is_admin spending_limit customer { email first_name last_name } } } } ``` ```graphql mutation SubmitRfqQuote($cartId: ID!) { requestQuote(cart_id: $cartId) { id status draft_order_id created_at } } ``` ### Negotiate & Accept a Quote ```graphql mutation SendQuoteMessage($quoteId: ID!, $text: String!) { createQuoteMessage(quote_id: $quoteId, text: $text) { id text created_at } } mutation AcceptMerchantQuote($quoteId: ID!) { acceptQuote(id: $quoteId) { id status } } ``` ### Cart Approval Workflow ```graphql mutation RequestCartApprovals($cartId: ID!) { createCartApprovals(cart_id: $cartId) { id approvals { id type status } } } mutation ApproveCart($approvalId: ID!) { updateApproval(id: $approvalId, status: approved) { id type status } } ``` # Schema Reference # Storefront GraphQL Schema Reference Every operation below is compiled into your store's Go `gqlgen` binary and served from `POST /graphql`. For Merchant Admin operations (`POST /admin/graphql`), see [Merchant Admin GraphQL](/docs/admin-graphql). *** ## Queries (`53`) ### Catalog, Variants, Brands & Reviews (`19`) | Query Signature | Access | Description | | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------- | :---------------------------------------------------------------------------------------- | | `products(limit: Int = 50, offset: Int = 0, filter: ProductFilterInput, order: ProductOrderInput, pricing_context: PricingContextInput): ProductConnection!` | Public (cached) | List & search products with sales-channel scoping and contextual B2C/B2B variant pricing. | | `product(id: ID!, pricing_context: PricingContextInput): Product` | Public (cached) | Fetch a single product by ID. | | `productByHandle(handle: String!, pricing_context: PricingContextInput): Product` | Public (cached) | Fetch a single product by URL slug (`handle`). | | `productVariants(limit: Int = 50, offset: Int = 0, filter: ProductVariantFilterInput, pricing_context: PricingContextInput): ProductVariantConnection!` | Public (cached) | Search variants directly by SKU, product ID, or query text (ideal for B2B quick-order). | | `productVariant(id: ID!, pricing_context: PricingContextInput): ProductVariant` | Public (cached) | Fetch a single product variant by ID. | | `collections(limit: Int = 50, offset: Int = 0, filter: CollectionFilterInput, order: CollectionOrderInput, pricing_context: PricingContextInput): ProductCollectionConnection!` | Public (cached) | List merchandising collections. | | `collection(id: ID!, pricing_context: PricingContextInput): ProductCollection` | Public (cached) | Fetch a collection by ID. | | `collectionByHandle(handle: String!, pricing_context: PricingContextInput): ProductCollection` | Public (cached) | Fetch a collection by URL `handle`. | | `productCategories(limit: Int = 50, offset: Int = 0, filter: ProductCategoryFilterInput, order: ProductCategoryOrderInput, pricing_context: PricingContextInput): ProductCategoryConnection!` | Public (cached) | List hierarchical product categories (`mpath`, `parent_category`, `category_children`). | | `productCategory(id: ID!, include_descendants_tree: Boolean, include_ancestors_tree: Boolean, pricing_context: PricingContextInput): ProductCategory` | Public (cached) | Fetch a category by ID with optional ancestor/descendant tree expansion. | | `productCategoryByHandle(handle: String!, include_descendants_tree: Boolean, include_ancestors_tree: Boolean, pricing_context: PricingContextInput): ProductCategory` | Public (cached) | Fetch a category by URL `handle`. | | `productTags(limit: Int = 50, offset: Int = 0, filter: ProductTagFilterInput): ProductTagConnection!` | Public | List product tags. | | `productTag(id: ID!): ProductTag` | Public | Fetch a product tag by ID. | | `productTypes(limit: Int = 50, offset: Int = 0, filter: ProductTypeFilterInput): ProductTypeConnection!` | Public | List product taxonomy types. | | `productType(id: ID!): ProductType` | Public | Fetch a product type by ID. | | `brands(limit: Int = 50, offset: Int = 0, filter: BrandFilterInput): BrandConnection!` | Public (cached) | List product brands. | | `brand(id: ID!): Brand` | Public (cached) | Fetch a brand by ID. | | `reviews(limit: Int = 10, offset: Int = 0, filter: ReviewFilterInput, order: ReviewOrderInput): ReviewConnection!` | Public | List product reviews (storefront callers see `approved` reviews). | | `review(id: ID!): Review` | Public | Fetch a single review by ID. | ### Regions, Currencies, Locales, Promotions & Site Settings (`10`) | Query Signature | Access | Description | | :------------------------------------------------------------------------------------------------- | :-------------------- | :---------------------------------------------------------------------------------- | | `locales: [Locale!]!` | Public (cached · 60m) | List active store translation locales (`code`, `name`). | | `currencies(limit: Int = 50, offset: Int = 0, filter: CurrencyFilterInput): CurrencyConnection!` | Public (cached · 60m) | List supported ISO-4217 currencies. | | `currency(code: ID!): Currency` | Public (cached · 60m) | Fetch a currency by 3-letter ISO code (e.g. `"usd"`). | | `regions(limit: Int = 50, offset: Int = 0, filter: RegionFilterInput): RegionConnection!` | Public (cached · 30m) | List commerce regions with countries, currencies, and enabled providers. | | `region(id: ID!): Region` | Public (cached · 30m) | Fetch a region by ID. | | `siteSettings: SiteSettings!` | Public (cached · 1m) | Fetch storefront CMS brand theme, hero sliders, navigation menus, and SEO settings. | | `promotions(limit: Int = 50, offset: Int = 0, filter: PromotionFilterInput): PromotionConnection!` | Admin / Active Public | List promotions and application methods. | | `promotion(id: ID!): Promotion` | Admin / Active Public | Fetch a promotion by ID. | | `campaigns(limit: Int = 50, offset: Int = 0, filter: CampaignFilterInput): CampaignConnection!` | Store Admin | List marketing campaigns and budgets. | | `campaign(id: ID!): Campaign` | Store Admin | Fetch a marketing campaign by ID. | ### Carts, Verification, Shipping & Payments (`8`) | Query Signature | Access | Description | | :--------------------------------------------------------------------------------------------------------------- | :--------------------- | :----------------------------------------------------------------------------------------------- | | `cart(id: ID!): Cart` | Cart Holder / Customer | Fetch a cart with line items, taxes, promotions, B2B approvals, and totals. | | `activeCustomerCart: Cart` | Authenticated Customer | Retrieve the caller's most recent uncompleted cart. | | `cartIdrabbitStatus(cart_id: ID!): CartIdrabbitStatus!` | Cart Holder / Customer | Inspect pre-checkout ID Rabbit age (21+) & identity verification state for a cart. | | `shippingOptions(cart_id: ID!, is_return: Boolean, limit: Int = 50, offset: Int = 0): ShippingOptionConnection!` | Cart Holder / Customer | List eligible outbound or return shipping options for a cart. | | `calculateShippingOption(shipping_option_id: ID!, cart_id: ID!, data: JSON): CalculatedShippingOption!` | Cart Holder / Customer | Quote live carrier pricing for a `calculated` shipping option. | | `paymentCollection(id: ID!): PaymentCollection` | Owner / Store Admin | Fetch a payment collection with sessions and payments. | | `paymentProviders(region_id: ID!, limit: Int = 50, offset: Int = 0): PaymentProviderConnection!` | Public | List active payment providers & public client SDK configs for a region. | | `authorizenetConfig: AuthorizenetPublicConfig!` | Public | Public Authorize.Net Accept.js credentials (`api_login_id`, `public_client_key`, `environment`). | ### Identity, Customers, Orders & Returns (`10`) | Query Signature | Access | Description | | :------------------------------------------------------------------------------------------------------------------------- | :--------------------------------- | :----------------------------------------------------------------------------------------- | | `authStatus: AuthStatus!` | Public (never cached) | Inspect resolved authentication state (`authenticated`, `actor_type`, `user`, `customer`). | | `me: User` | Store Admin | Fetch the currently authenticated store admin user. | | `customer(id: ID): Customer` | Customer / Store Admin | Fetch authenticated customer when `id` is omitted, or customer by `id` (self/admin). | | `customers(limit: Int = 50, offset: Int = 0, filter: CustomerFilterInput, order: CustomerOrderInput): CustomerConnection!` | Store Admin | List and search customer accounts. | | `orders(limit: Int = 20, offset: Int = 0, filter: OrderFilterInput, order: OrderOrderInput): OrderConnection!` | Customer / B2B Admin / Store Admin | List orders (automatically scoped to customer, B2B company, or store). | | `order(id: ID!): Order` | Owner / B2B Admin / Store Admin | Fetch a single order with items, fulfillments, summary, and transactions. | | `returns(limit: Int = 20, offset: Int = 0, filter: ReturnFilterInput): ReturnConnection!` | Customer / Store Admin | List RMA order returns. | | `return(id: ID!): Return` | Owner / B2B Admin / Store Admin | Fetch a single order return by ID. | | `returnReasons(limit: Int = 50, offset: Int = 0, filter: ReturnReasonFilterInput): ReturnReasonConnection!` | Public | List customer return reasons. | | `returnReason(id: ID!): ReturnReason` | Public | Fetch a return reason by ID. | ### B2B Wholesale (Companies, Quotes & Approvals) (`6`) | Query Signature | Access | Description | | :---------------------------------------------------------------------------------------------------------------------- | :------------------------------ | :---------------------------------------------------------------------------- | | `myCompany: Company` | Authenticated Customer | Fetch the B2B `Company` of the authenticated buyer (`null` for B2C shoppers). | | `company(id: ID!): Company` | Company Member / Store Admin | Fetch a B2B company by ID. | | `companies(limit: Int = 20, offset: Int = 0, filter: CompanyFilterInput, order: CompanyOrderInput): CompanyConnection!` | B2B Customer / Store Admin | List B2B companies (scoped to caller's company unless Store Admin). | | `quotes(limit: Int = 20, offset: Int = 0, filter: QuoteFilterInput): QuoteConnection!` | Customer / Store Admin | List B2B RFQ quotes. | | `quote(id: ID!): Quote` | Owner / B2B Admin / Store Admin | Fetch a single B2B quote with `draft_order`, `order_change`, and `messages`. | | `approvals(limit: Int = 20, offset: Int = 0, filter: ApprovalFilterInput): ApprovalConnection!` | B2B Member / Store Admin | List B2B cart approval requests. | *** ## Mutations (`45`) ### Authentication & Customer Accounts (`10`) | Mutation Signature | Access | Description | | :------------------------------------------------------------------------------------------------------------- | :--------------------- | :--------------------------------------------------------------------------- | | `login(email: String!, password: String!, actor_type: ActorType): AuthToken!` | Public | Authenticate `customer` or `user` and issue a signed JWT bearer token. | | `requestEmailOtp(email: String!, actor_type: ActorType): PasswordResetResult!` | Public | Send a single-use 6-digit sign-in OTP code to the account's email address. | | `verifyEmailOtp(email: String!, code: String!, actor_type: ActorType): AuthToken!` | Public | Exchange a valid 6-digit email OTP code for a signed JWT bearer token. | | `requestPasswordReset(email: String!, actor_type: ActorType): PasswordResetResult!` | Public | Trigger password reset email for a customer or admin user. | | `resetPassword(token: String!, password: String!, email: String, actor_type: ActorType): PasswordResetResult!` | Public | Complete password reset using a reset token. | | `createCustomer(input: CreateCustomerInput!): Customer!` | Public | Register a B2C customer or B2B corporate buyer (when `company_name` is set). | | `updateCustomer(id: ID, input: UpdateCustomerInput!): Customer!` | Customer / Store Admin | Update customer profile fields. | | `addCustomerAddress(input: CustomerAddressInput!): CustomerAddress!` | Authenticated Customer | Add a saved shipping/billing address. | | `updateCustomerAddress(address_id: ID!, input: CustomerAddressInput!): CustomerAddress!` | Authenticated Customer | Update an existing customer address. | | `deleteCustomerAddress(address_id: ID!): DeleteResult!` | Authenticated Customer | Delete a saved customer address. | ### Carts, Verification, Checkout & Payments (`17`) | Mutation Signature | Access | Description | | :---------------------------------------------------------------------------------------------------------------- | :--------------------- | :-------------------------------------------------------------------------------------------- | | `createCart(input: CreateCartInput!): Cart!` | Public / Customer | Create a new cart (auto-linked to authenticated customer & B2B company). | | `updateCart(id: ID!, input: UpdateCartInput!): Cart!` | Cart Holder / Customer | Update cart region, email, addresses, locale, or metadata. | | `deleteCart(id: ID!): DeleteResult!` | Cart Holder / Customer | Delete an uncompleted cart. | | `addCartLineItem(cart_id: ID!, input: AddCartLineItemInput!): Cart!` | Cart Holder / Customer | Add a variant and quantity to a cart. | | `addCartLineItemsBulk(cart_id: ID!, items: [AddCartLineItemInput!]!): Cart!` | Cart Holder / Customer | Add multiple variants to a cart atomically (ideal for B2B CSV/quick-order). | | `updateCartLineItem(cart_id: ID!, line_id: ID!, input: UpdateCartLineItemInput!): Cart!` | Cart Holder / Customer | Update line item quantity or metadata. | | `removeCartLineItem(cart_id: ID!, line_id: ID!): Cart!` | Cart Holder / Customer | Remove a line item from a cart. | | `addCartShippingMethod(cart_id: ID!, input: AddCartShippingMethodInput!): Cart!` | Cart Holder / Customer | Attach a `ShippingOption` to a cart. | | `addCartPromotions(cart_id: ID!, promo_codes: [String!]!): Cart!` | Cart Holder / Customer | Apply one or more promo codes to a cart. | | `removeCartPromotions(cart_id: ID!, promo_codes: [String!]!): Cart!` | Cart Holder / Customer | Remove promo codes from a cart. | | `calculateCartTaxes(cart_id: ID!): Cart!` | Cart Holder / Customer | Explicitly recalculate item and shipping tax lines. | | `updateCartCustomer(cart_id: ID!): Cart!` | Authenticated Customer | Bind an anonymous guest cart to the authenticated customer. | | `createCartIdrabbitSession(cart_id: ID!, redirect_url: String): CartIdrabbitSessionResult!` | Cart Holder / Customer | Create or resume an ID Rabbit hosted identity/21+ verification session for a cart. | | `createPaymentCollection(cart_id: ID!): PaymentCollection!` | Cart Holder / Customer | Create or retrieve the `PaymentCollection` for a cart. | | `refreshPaymentCollection(cart_id: ID!): PaymentCollection!` | Cart Holder / Customer | Sync payment collection amount after cart total changes. | | `initializePaymentSession(payment_collection_id: ID!, input: InitializePaymentSessionInput!): PaymentCollection!` | Cart Holder / Customer | Initialize a gateway `PaymentSession` (e.g. Stripe PaymentIntent, Authorize.Net). | | `completeCart(cart_id: ID!): Order!` | Cart Holder / Customer | Authorize payment, verify ID Rabbit & B2B approvals/limits, reserve stock, and place `Order`. | ### Orders, Returns & Reviews (`6`) | Mutation Signature | Access | Description | | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------ | :------------------------------------------------------------------------- | | `requestOrderTransfer(order_id: ID!, description: String): Order!` | Customer / Store Admin | Request transferring order ownership to another customer. | | `acceptOrderTransfer(order_id: ID!, token: String!): Order!` | Token Holder / Customer | Accept an order transfer using its verification token. | | `declineOrderTransfer(order_id: ID!, token: String!): Order!` | Token Holder / Customer | Decline a pending order transfer. | | `cancelOrderTransfer(order_id: ID!): Order!` | Requester / Store Admin | Cancel a pending order transfer request. | | `requestReturn(order_id: ID!, items: [ReturnItemInput!]!, location_id: String, return_shipping: ReturnShippingInput, note: String, receive_now: Boolean): Return!` | Owner / B2B Admin / Store Admin | Submit an RMA return request for order items. | | `createReview(input: CreateReviewInput!): Review!` | Public / Customer | Submit a customer product review (created in `pending` moderation status). | ### B2B Companies, Employees, Quotes & Approvals (`12`) | Mutation Signature | Access | Description | | :---------------------------------------------------------------------------------------- | :------------------------------ | :---------------------------------------------------------------------- | | `requestQuote(cart_id: ID!): Quote!` | Authenticated Customer | Convert an active cart into a negotiable B2B RFQ `Quote`. | | `createQuoteMessage(quote_id: ID!, text: String!, item_id: String): QuoteMessage!` | Owner / B2B Admin / Store Admin | Post a message on a quote negotiation thread. | | `acceptQuote(id: ID!): Quote!` | Owner / B2B Company Admin | Accept a merchant's quoted pricing (`pending_customer` → `accepted`). | | `rejectQuote(id: ID!): Quote!` | Owner / B2B Admin / Store Admin | Reject a B2B quote proposal. | | `inviteEmployee(input: InviteEmployeeInput!): Employee!` | B2B Company Admin / Store Admin | Invite an employee to a B2B company with role & spending limit. | | `updateEmployee(id: ID!, input: UpdateEmployeeInput!): Employee!` | B2B Company Admin / Store Admin | Update an employee's `spending_limit` or `is_admin` flag. | | `removeEmployee(id: ID!): DeleteResult!` | B2B Company Admin / Store Admin | Remove an employee from a B2B company. | | `updateCompany(id: ID, input: UpdateCompanyInput!): Company!` | B2B Company Admin / Store Admin | Update B2B company details and spending-limit reset cadence. | | `updateCompanyStatus(id: ID!, status: CompanyStatus!): Company!` | Store Admin | Approve, reject, or set pending status on a B2B company. | | `updateApprovalSettings(id: ID!, input: UpdateApprovalSettingsInput!): ApprovalSettings!` | B2B Company Admin / Store Admin | Toggle `requires_admin_approval` and `requires_sales_manager_approval`. | | `createCartApprovals(cart_id: ID!): Cart!` | Authenticated B2B Customer | Submit a cart for required B2B admin / sales manager approvals. | | `updateApproval(id: ID!, status: ApprovalStatusType!): Approval!` | B2B Admin / Store Admin | Approve or reject a pending B2B cart `Approval`. | # Security Architecture # Security Architecture Security on `/graphql` and `/admin/graphql` is enforced directly in compiled Go middleware (`graph/middleware/security.go`, `context.go`, and `rbac_guard.go`). *** ## 1. `XcladeGraphQLArmor` (AST Protection) Before any resolver executes, `ArmorExtension.InterceptOperation` walks the parsed AST (including inline fragments and named fragment spreads with cycle protection) and rejects abusive queries immediately: * **Query Depth Guard:** Blocks deeply nested queries exceeding `GRAPHQL_MAX_DEPTH` (`10` on `/graphql`, `14` on `/admin/graphql`) with `QUERY_DEPTH_EXCEEDED`. * **Alias Amplification Guard:** Caps aliased fields at `15` on `/graphql` (`30` on `/admin/graphql`) with `ALIAS_LIMIT_EXCEEDED`. * **Directive Flood Guard:** Caps total directives at `50` on `/graphql` (`75` on `/admin/graphql`) with `DIRECTIVE_LIMIT_EXCEEDED`. * **Production Introspection Guard:** Blocks `__schema` and `__type` fields in production unless the caller is an authenticated Store Admin or `GRAPHQL_ALLOW_INTROSPECTION=true`. *** ## 2. HTTP Guard Middleware `GuardHTTPMiddleware` runs ahead of GraphQL parsing on every request: * **Distributed Redis Rate Limiting:** Enforces sliding-window quotas keyed by `ActorID` (when authenticated) or client IP (when anonymous). Exceeding the cap returns HTTP `429` with `RATE_LIMIT_EXCEEDED`. * **Payload Size Cap:** Wraps `r.Body` with `http.MaxBytesReader` and returns HTTP `413` (`QUERY_TOO_LARGE`) if exceeded. * **Batch Operation Cap:** Inspects JSON array batches and rejects arrays exceeding `GRAPHQL_MAX_BATCH` (`5`) with `BATCH_LIMIT_EXCEEDED`. * **CSRF Preflight Guard on `GET`:** In production (and always on `/admin/graphql`), `GET` requests not accepting `text/html` or `text/event-stream` must include at least one non-simple header (`X-Xclade-Request`, `X-GraphQL-Request`, `X-Publishable-Api-Key`, `X-Xclade-Publishable-Key`, or `Apollo-Require-Preflight`), otherwise HTTP `400` (`CSRF_PREFLIGHT_REQUIRED`) is returned. *** ## 3. Actor, Ownership & RBAC Guards Resolvers enforce strict authorization helpers at every boundary: | Guard | Enforcement | | :-------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------- | | `RequireAuth` | Requires a valid customer or admin token (rejects scoped/purpose tokens such as password-reset tokens). | | `RequireCustomer` | Restricts mutations to authenticated storefront shoppers / B2B buyers. | | `RequireOwnershipOrAdmin` | Ensures customers can only view/mutate their own orders, returns, and quotes. | | `RequireCompanyAdminOrStoreAdmin` | Restricts employee invites, spending limits, and admin cart approvals to B2B Company Admins (`Employee.is_admin = true`) or Store Admins. | | `AdminRBACGuard` & `@requirePermission` | Evaluates fine-grained RBAC role policies on every `/admin/graphql` operation. | *** ## 4. Dynamic Storefront CORS & Cache Isolation * **Dynamic CORS:** `/graphql` automatically allows configured store origins plus verified custom domains attached to the store. * **Zero Cross-Tenant or PII Cache Leakage:** `XcladeResponseCache` refuses to cache any request containing an authenticated actor, non-allowlisted root fields, or sensitive identifiers (`cart_id`, `company_id`, `customer_id`, or `cart_*` / `comp_*` / `cus_*` values) and forces `Cache-Control: private, no-store`. * **Production Error Masking:** Unexpected internal errors are masked to `"an unexpected internal error occurred"` with `INTERNAL_SERVER_ERROR` in production so stack traces and SQL details are never leaked. # Diagnostics & Support # Diagnostics & Support ## Live Diagnostic Endpoints Before opening a support ticket, inspect your store pod's built-in health and telemetry endpoints: ```bash # 1. Store pod health, engine info & database connectivity curl https://{shortId}.api.myxclade.com/health # 2. Live GraphQL execution latency & error metrics curl https://{shortId}.api.myxclade.com/graphql/health # 3. Agentic Commerce protocol readiness (UCP, ACP, A2A, llms.txt, Web Bot Auth) curl https://{shortId}.api.myxclade.com/agentic/status # 4. Control Plane health curl https://api.xclade.com/health ``` *** ## Common Troubleshooting Checklist * **Empty `calculated_price` on variants:** Ensure you passed `pricing_context: { region_id: "..." }` or `{ currency_code: "usd" }` to `products`, `product`, or `productByHandle`. * **Empty catalog results:** Verify your `X-Xclade-Publishable-Key` is linked to the same Sales Channel as your published products. * **CORS blocked in browser:** Add your storefront origin (e.g. `https://shop.yourbrand.com` or `http://localhost:3000`) under **Store Admin → Settings → Store Configuration**. * **`CSRF_PREFLIGHT_REQUIRED` on `GET /graphql`:** Add `X-Xclade-Request: true` (or `X-Xclade-Publishable-Key`). * **`custom_domain_required` (`412`) in Growth Studio:** Attach and verify your own 2048-bit RSA DKIM domain under **Growth Studio → Deliverability & DNS**. *** ## Support Channels * **Platform Status:** [xclade.com/status](https://xclade.com/status) * **Developer & Migration Support:** `support@xclade.com` * **Cloud Console:** [app.xclade.com](https://app.xclade.com) * **AI Assistant Docs Bundle:** [`/llms.txt`](/llms.txt) and [`/llms-full.txt`](/llms-full.txt)