DeployCode Deployment
Deploy as Services
Package and monetize MDX Functions as Services-as-Software
Deploy MDX as Services
Documentation Status: This documentation describes the planned API design for the .do platform. Code examples represent the intended interface and may not reflect the current implementation state. See roadmap for implementation status.
Package your MDX functions as monetizable Services-as-Software with built-in billing, marketplace distribution, and user management.
Overview
Deploy MDX as services to:
- Monetize Your Code - Turn functions into revenue
- Reach Customers - List in the .do marketplace
- Scale Automatically - Handle growth seamlessly
- Manage Subscriptions - Built-in billing and payments
flowchart TB
A[MDX Functions] --> B[Service Package]
B --> C[Marketplace Listing]
C --> D[User Subscribe]
D --> E[Billing Setup]
E --> F[Service Access]
F --> G[Usage Tracking]
G --> H[Metered Billing]
F --> I[API Calls]
I --> J[Rate Limiting]
J --> K[Response]
Creating a Service
Simple Service
---
title: SEO Analyzer
description: AI-powered SEO analysis and recommendations
price: $29/month
---
export interface SEOAnalysis {
score: number
issues: Array<{ type: string; severity: string; message: string }>
recommendations: string[]
metadata: {
title: string
description: string
keywords: string[]
}
}
export async function analyzeSEO(url: string): Promise<SEOAnalysis> {
// Fetch page content
const page = await $.web.fetch(url)
// Analyze with AI
const analysis = await $.ai.analyze(page.html, {
prompt: 'Analyze SEO quality and provide recommendations',
schema: SEOAnalysisSchema
})
// Check technical SEO
const technical = await checkTechnicalSEO(page)
// Generate recommendations
const recommendations = await $.ai.generateText({
prompt: 'Generate actionable SEO recommendations',
context: { analysis, technical }
})
return {
score: calculateSEOScore(analysis, technical),
issues: [...analysis.issues, ...technical.issues],
recommendations: recommendations.split('\n'),
metadata: extractMetadata(page)
}
}
export async function generateMetadata(content: string, keywords: string[]): Promise<Metadata> {
return await $.ai.generate.metadata({
content,
keywords,
optimize: 'seo'
})
}Service Definition
// service.config.ts
export default $.service({
name: 'seo-analyzer',
version: '1.0.0',
description: 'AI-powered SEO analysis and optimization',
// Import MDX functions as capabilities
capabilities: {
analyzeSEO,
generateMetadata,
},
// Define pricing
pricing: {
model: 'subscription',
plans: [
{
id: 'starter',
name: 'Starter',
price: 29,
interval: 'month',
features: ['10 URL analyses per month', 'Basic recommendations', 'Email support'],
limits: {
analyzeSEO: { calls: 10, period: 'month' },
},
},
{
id: 'pro',
name: 'Professional',
price: 99,
interval: 'month',
features: ['100 URL analyses per month', 'Advanced recommendations', 'Priority support', 'Custom reporting'],
limits: {
analyzeSEO: { calls: 100, period: 'month' },
},
},
{
id: 'enterprise',
name: 'Enterprise',
price: 499,
interval: 'month',
features: ['Unlimited analyses', 'Dedicated support', 'API access', 'Custom integrations'],
limits: {
analyzeSEO: { calls: -1 }, // unlimited
},
},
],
},
// Service metadata for marketplace
metadata: {
category: 'marketing',
tags: ['seo', 'ai', 'analytics', 'optimization'],
logo: '/assets/logo.png',
screenshots: ['/assets/screenshot1.png', '/assets/screenshot2.png'],
website: 'https://seo-analyzer.do',
documentation: 'https://docs.seo-analyzer.do',
support: '[email protected]',
},
})Usage-Based Pricing
export default $.service({
name: 'image-generator',
pricing: {
model: 'usage',
tiers: [
{ up_to: 100, price_per_unit: 0.5 },
{ up_to: 1000, price_per_unit: 0.3 },
{ above: 1000, price_per_unit: 0.2 },
],
unit: 'image',
},
})Hybrid Pricing
export default $.service({
name: 'api-service',
pricing: {
model: 'hybrid',
subscription: {
base: 49,
includes: 1000, // 1000 API calls included
unit: 'call',
},
overage: {
price_per_unit: 0.05, // $0.05 per call over limit
},
},
})Service Client
Installing a Service
// Users can install your service
const seoAnalyzer = await $.services.install('seo-analyzer', {
plan: 'pro',
})
// Use the service
const analysis = await seoAnalyzer.analyzeSEO('https://example.com')
console.log(`SEO Score: ${analysis.score}`)
console.log('Recommendations:', analysis.recommendations)Type-Safe Client
The platform generates type-safe clients:
import type { SEOAnalyzer } from '@dotdo/services/seo-analyzer'
const analyzer: SEOAnalyzer = await $.services.use('seo-analyzer')
// Full TypeScript support
const result = await analyzer.analyzeSEO('https://example.com')
// ^? SEOAnalysisService Marketplace
Listing Your Service
export default $.service({
name: 'my-service',
// Marketplace listing
listing: {
title: 'AI Content Generator',
tagline: 'Create high-quality content in seconds',
description: `
Our AI-powered content generator helps you create blog posts,
social media content, and marketing copy in seconds.
`,
benefits: ['Save 10+ hours per week', 'Generate SEO-optimized content', 'Multiple content types supported', 'Consistent brand voice'],
useCases: ['Blog post creation', 'Social media content', 'Email campaigns', 'Product descriptions'],
demo: {
enabled: true,
limits: { calls: 3 },
},
},
})Service Analytics
Track Usage
export async function analyzeSEO(url: string) {
// Track function call
await $.analytics.track('function.called', {
service: 'seo-analyzer',
function: 'analyzeSEO',
user: $.context.userId
})
const result = await performAnalysis(url)
// Track completion
await $.analytics.track('function.completed', {
service: 'seo-analyzer',
function: 'analyzeSEO',
duration: Date.now() - start,
success: true
})
return result
}Access Analytics
// Service owner dashboard
const analytics = await $.service.analytics.get('seo-analyzer', {
period: 'last_30d',
})
console.log({
activeUsers: analytics.activeUsers,
totalCalls: analytics.totalCalls,
revenue: analytics.revenue,
churnRate: analytics.churnRate,
averageCallsPerUser: analytics.avgCallsPerUser,
})User Management
Manage Subscriptions
export async function handleSubscriptionChange(event: SubscriptionEvent) {
switch (event.type) {
case 'subscription.created':
// Welcome new user
await $.email.send.message({
to: event.user.email,
template: 'welcome',
data: { plan: event.plan }
})
break
case 'subscription.upgraded':
// Thank for upgrade
await $.email.send.message({
to: event.user.email,
template: 'upgrade',
data: { newPlan: event.plan }
})
break
case 'subscription.canceled':
// Send cancellation email
await $.email.send.message({
to: event.user.email,
template: 'cancellation'
})
break
}
}Service Composition
Combine Multiple Services
export default $.service({
name: 'content-pipeline',
description: 'Complete content creation pipeline',
// Use other services
dependencies: [
'content-generator',
'image-creator',
'seo-optimizer'
],
capabilities: {
async createCompleteArticle(topic: string) {
// Generate content
const content = await $.services.use('content-generator')
.generate({ topic, length: 1500 })
// Create images
const images = await $.services.use('image-creator')
.generate({ prompts: extractImageNeeds(content) })
// Optimize for SEO
const optimized = await $.services.use('seo-optimizer')
.optimize({ content, images })
return optimized
}
},
pricing: {
model: 'subscription',
plans: [
{ name: 'Pro', price: 199, interval: 'month' }
]
}
})Webhooks
Service Events
export default $.service({
name: 'my-service',
webhooks: {
events: ['user.subscribed', 'user.upgraded', 'user.canceled', 'limit.reached', 'payment.failed'],
},
})
// Users can subscribe to events
await myService.webhook.subscribe({
url: 'https://example.com/webhook',
events: ['user.subscribed', 'limit.reached'],
})Deployment Configuration
// do.config.ts
export default {
services: [
{
name: 'seo-analyzer',
source: './services/seo-analyzer.mdx',
deployment: {
marketplace: {
enabled: true,
featured: false,
category: 'marketing',
},
api: {
rateLimit: {
free: { requests: 10, window: '1m' },
pro: { requests: 100, window: '1m' },
enterprise: { requests: 1000, window: '1m' },
},
},
billing: {
provider: 'stripe',
webhook: '/webhooks/stripe',
},
},
environment: {
STRIPE_SECRET: process.env.STRIPE_SECRET,
AI_API_KEY: process.env.AI_API_KEY,
},
},
],
}Testing Services
import { test } from 'vitest'
test('SEO analyzer returns valid analysis', async () => {
const service = await $.services.test('seo-analyzer')
const result = await service.analyzeSEO('https://example.com')
expect(result).toHaveProperty('score')
expect(result.score).toBeGreaterThanOrEqual(0)
expect(result.score).toBeLessThanOrEqual(100)
expect(result.recommendations).toBeInstanceOf(Array)
})Best Practices
Provide Great Documentation
---
title: SEO Analyzer Documentation
---
# SEO Analyzer Service
## Quick Start
\`\`\`typescript
const analyzer = await $.services.use('seo-analyzer')
const result = await analyzer.analyzeSEO('https://yoursite.com')
\`\`\`
## API Reference
### analyzeSEO(url)
Analyzes a URL for SEO quality.
**Parameters:**
- `url` (string): The URL to analyze
**Returns:**
- `SEOAnalysis`: Analysis results
**Example:**
\`\`\`typescript
const analysis = await analyzer.analyzeSEO('https://example.com')
console.log(analysis.score) // 85
\`\`\`Handle Errors Gracefully
export async function analyzeSEO(url: string) {
try {
return await performAnalysis(url)
} catch (error) {
if (error.code === 'INVALID_URL') {
throw new ValidationError('Please provide a valid URL')
}
if (error.code === 'RATE_LIMIT') {
throw new RateLimitError('Rate limit exceeded. Upgrade your plan.')
}
throw error
}
}Related Documentation
-
- Services Framework - Complete services capabilities
- Business-as-Code - Complete business services
- APIs - API deployment
- Workflows - Service workflows