@shopkit/ai-store-builder
v0.1.1
Published
AI-powered store builder agent for merchant onboarding and customization
Maintainers
Readme
@shopkit/ai-store-builder
AI-powered store builder agent for merchant onboarding and customization. Built on Claude (Anthropic) with a comprehensive tool system for managing Shopify storefronts.
Features
- AI-Powered Agent: Claude-based agent for natural language store customization
- Merchant Onboarding: Scrape existing Shopify stores and migrate to your platform
- Page Builder Tools: Add, update, remove sections and widgets
- Theme Tools: Customize colors, typography, and spacing
- Data Tools: Fetch products and collections from Shopify Storefront API
- Browser Automation: Puppeteer-powered scraping with resource pooling
- Type Safety: Comprehensive Zod validation for all tool inputs
- Production Ready: Race condition prevention, resource cleanup, error handling
Installation
bun add @shopkit/ai-store-builder
# or
npm install @shopkit/ai-store-builderPeer Dependencies
The following peer dependencies are optional depending on your use case:
# For image optimization during asset migration
bun add sharp
# For S3 asset hosting
bun add @aws-sdk/client-s3
# For Shopify Storefront API integration
bun add @shopkit/data-layerQuick Start
import { StoreAgent, configure } from '@shopkit/ai-store-builder';
// Option 1: Configure programmatically (recommended)
configure({
anthropic: {
apiKey: 'sk-ant-xxx',
},
shopify: {
storeDomain: 'mystore.myshopify.com',
storefrontAccessToken: 'xxx',
},
paths: {
themesBasePath: 'src/themes',
},
});
// Option 2: Use environment variables (see below)
// Create an agent for a merchant
const agent = new StoreAgent('my-store');
// Chat with the agent
const response = await agent.chat('Add a hero banner section at the top of the homepage');
console.log(response);
// Clean up when done
await agent.dispose();Configuration
Programmatic Configuration (Recommended)
The configure() function allows you to set all configuration in code, which is more flexible and testable:
import { configure, resetConfig } from '@shopkit/ai-store-builder';
configure({
// Anthropic API settings
anthropic: {
apiKey: 'sk-ant-xxx', // Required
model: 'claude-sonnet-4-20250514', // Optional (default)
maxTokens: 4096, // Optional (default)
},
// Shopify Storefront API settings (for data tools)
shopify: {
storeDomain: 'mystore.myshopify.com', // Required for data tools
storefrontAccessToken: 'xxx', // Required for data tools
apiVersion: '2024-04', // Optional (default)
},
// File paths
paths: {
themesBasePath: 'apps/myapp/src/themes', // Default: apps/wellversed/src/themes
widgetsManifestPath: 'apps/myapp/src/widgets/.generated/manifest.ts',
publicAssetsPath: 'public', // Default: public
},
});
// Reset configuration (useful for testing)
resetConfig();Environment Variables (Fallback)
If not configured programmatically, the package will fall back to environment variables:
# Anthropic API
ANTHROPIC_API_KEY=sk-ant-...
# Shopify Storefront API
SHOPIFY_STORE_DOMAIN=mystore.myshopify.com
SHOPIFY_STOREFRONT_ACCESS_TOKEN=xxxxx
SHOPIFY_API_VERSION=2024-04
# File paths
THEMES_BASE_PATH=apps/wellversed/src/themes
WIDGETS_MANIFEST_PATH=apps/wellversed/src/widgets/.generated/manifest.ts
PUBLIC_ASSETS_PATH=publicConfiguration Priority
The package checks configuration in this order:
- Programmatic config via
configure() - Environment variables
- Default values
Checking Configuration Status
import { isShopifyConfigured, isAnthropicConfigured, getConfig } from '@shopkit/ai-store-builder';
// Check if services are configured
if (!isShopifyConfigured()) {
console.warn('Shopify not configured - data tools will not work');
}
if (!isAnthropicConfigured()) {
throw new Error('Anthropic API key required');
}
// Get current config
const config = getConfig();API Reference
StoreAgent
The main class for interacting with the AI store builder.
import { StoreAgent } from '@shopkit/ai-store-builder';
const agent = new StoreAgent(merchantName?: string, apiKey?: string);
// Send a message and get a response
const response = await agent.chat(message: string);
// Get current state
const state = agent.getState();
// Update state
agent.setState({ merchantName: 'new-name' });
// Set current template being edited
agent.setCurrentTemplate('product'); // 'home' | 'product' | 'collection'
// Get chat history
const history = agent.getChatHistory();
// Clear conversation
agent.clearHistory();
// Check processing status
const isProcessing = agent.isAgentProcessing();
// Clean up resources
await agent.dispose();BrowserPool
Manages Puppeteer browser instances with automatic cleanup.
import { BrowserPool, getBrowserPool, shutdownGlobalPool } from '@shopkit/ai-store-builder';
// Get global singleton pool
const pool = getBrowserPool();
// Or create a custom pool
const customPool = new BrowserPool({
maxInstances: 3, // Max concurrent browsers
acquireTimeout: 30000, // Timeout waiting for browser
pageTimeout: 30000, // Default page timeout
});
// Safe browser usage with automatic cleanup
const result = await pool.withBrowser(async (browser) => {
const page = await browser.newPage();
await page.goto('https://example.com');
return await page.content();
});
// Safe page usage with automatic cleanup
const content = await pool.withPage(async (page) => {
await page.goto('https://example.com');
return await page.content();
}, { viewport: { width: 1920, height: 1080 } });
// Get pool statistics
const stats = pool.getStats();
// { totalInstances, availableInstances, inUseInstances, waitingRequests }
// Shutdown
await pool.shutdown(); // Graceful
await pool.forceShutdown(); // Immediate
await shutdownGlobalPool(); // Global singletonAvailable Tools
The agent has access to 24+ tools organized by category:
Page Tools
add_section- Add a new section to the pageadd_widget- Add a widget to a sectionupdate_widget- Update widget settingsremove_widget- Remove a widgetremove_section- Remove a sectionreorder_sections- Change section ordermove_widget- Move widget between sections
Theme Tools
update_theme_colors- Update color tokensupdate_theme_typography- Update typography settingsupdate_theme_spacing- Update spacing values
Data Tools
get_products- Fetch products from Shopifyget_collections- Fetch collections from Shopifyadd_data_source- Add data source to page config
State Tools
get_page_config- Get current page configurationget_theme_config- Get current theme configurationlist_widgets- List available widget typessave_changes- Save changes to files
Browser Tools
execute_browser_script- Run JavaScript in browser contextcapture_screenshots- Capture multi-breakpoint screenshotscapture_hover_states- Capture element hover statesextract_css_values- Extract computed CSS valuesanalyze_mobile_menu- Analyze mobile menu structure
Onboarding Tools
scrape_store- Scrape existing Shopify storeanalyze_design- Analyze scraped designimport_products- Import products via Admin APIimport_collections- Import collections via Admin APImigrate_assets- Download and migrate assetscreate_merchant- Create merchant folder structure
Tool Input Validation
All tool inputs are validated using Zod schemas:
import { validateToolInput, toolSchemas } from '@shopkit/ai-store-builder';
// Validate input
const result = validateToolInput('add_section', {
name: 'Hero',
position: 0,
layout: 'full',
});
if (result.success) {
console.log('Valid input:', result.data);
} else {
console.log('Validation errors:', result.errors);
}
// Access individual schemas
import { addSectionSchema, hexColorSchema } from '@shopkit/ai-store-builder';
const colorResult = hexColorSchema.safeParse('#19a9f0');Types
import type {
// State types
MerchantState,
OnboardingProgress,
ChatMessage,
ToolCall,
ToolResult,
// Config types
PageConfig,
SectionConfig,
WidgetConfig,
ThemeConfig,
// Tool input types
AddSectionInput,
AddWidgetInput,
UpdateThemeColorsInput,
// ... and more
// Browser types
ScreenshotResult,
HoverStateResult,
CssValuesResult,
// Asset types
ExtractedIcon,
ExtractedImage,
AssetExtractionResult,
} from '@shopkit/ai-store-builder';Example: Complete Page Building Workflow
import { StoreAgent } from '@shopkit/ai-store-builder';
async function buildStorePage() {
const agent = new StoreAgent('my-store');
try {
// 1. Set up theme
await agent.chat(`
Update the theme colors to:
- Primary: #19a9f0
- Secondary: #ff5733
- Background: #ffffff
`);
// 2. Add hero section
await agent.chat('Add a hero banner section at position 0 with full width layout');
// 3. Add hero widget
await agent.chat(`
Add a HeroBanner widget to the hero section with:
- Title: "Welcome to Our Store"
- Subtitle: "Discover amazing products"
- CTA: "Shop Now"
`);
// 4. Add products section
await agent.chat('Add a Featured Products section below the hero');
// 5. Add product grid
await agent.chat(`
Add a ProductGrid widget to the featured products section
showing 8 products in a 4-column layout
`);
// 6. Save changes
await agent.chat('Save all changes');
console.log('Page built successfully!');
} finally {
await agent.dispose();
}
}Testing
# Run tests
bun test
# Run with coverage
bun test:coverage
# Run in watch mode
bun test:watch
# Run with UI
bun test:uiArchitecture
@shopkit/ai-store-builder/
├── src/
│ ├── agent/
│ │ ├── store-agent.ts # Main agent class
│ │ ├── system-prompt.ts # System prompt builder
│ │ └── pixel-perfect-prompt.ts
│ ├── tools/
│ │ ├── index.ts # Tool registry & executor
│ │ ├── page-tools.ts # Page modification tools
│ │ ├── theme-tools.ts # Theme modification tools
│ │ ├── data-tools.ts # Data fetching tools
│ │ ├── state-tools.ts # State management tools
│ │ ├── browser-tools.ts # Browser automation tools
│ │ ├── asset-tools.ts # Asset extraction tools
│ │ └── onboarding-tools.ts # Onboarding tools
│ ├── services/
│ │ ├── browser-pool.ts # Browser instance pooling
│ │ └── scraper.ts # Website scraper
│ ├── types/
│ │ ├── index.ts # Type definitions
│ │ └── validation.ts # Zod schemas
│ └── index.ts # Public exportsLicense
MIT
