$ - Semantic Context Proxy
Complete guide to the $ semantic proxy for creating Schema.org types and event patterns in the .do platform
The $ semantic context proxy is the foundation of semantic programming on the .do platform. It provides a unified interface for creating Schema.org vocabulary types, defining event patterns, and building semantic triples using the intuitive $.Subject.predicate.Object syntax.
Overview
The $ proxy leverages JavaScript's Proxy API to enable natural semantic path construction with full type safety. It comes from the GraphDL library and is the cornerstone of Business-as-Code on the .do platform.
Key Capabilities
- Semantic Type Creation - Create Schema.org vocabulary objects
- Event Pattern Definition - Define event patterns for handlers
- Triple Pattern Construction - Build RDF-style semantic triples
- Type Safety - Full TypeScript inference for all Schema.org types
- Infinite Composition - Nest and compose semantic paths arbitrarily
Type Signatures
interface PathProxy {
readonly path: string
toString(): string
valueOf(): string
readonly [key: string]: PathProxy
}
const $: PathProxy & {
[Subject: string]: PathProxy & {
[predicate: string]: PathProxy & {
[Object: string]: PathProxy
}
}
}How It Works
The $ proxy dynamically constructs semantic paths as you access properties:
// Each property access extends the path
$.Person // "$.Person"
$.Person.worksFor // "$.Person.worksFor"
$.Person.worksFor.Organization // "$.Person.worksFor.Organization"
// Conversion to string
String($.Order.created) // "$.Order.created"
$.Payment.succeeded.toString() // "$.Payment.succeeded"The proxy pattern means you get infinite semantic vocabulary without defining every possible combination.
Basic Usage
Creating Semantic Types
The $ proxy can be called as a function to create typed objects:
// Create a Person
const person = $.Person({
name: 'Alice Johnson',
email: '[email protected]',
jobTitle: 'Software Engineer',
})
// Create an Organization
const company = $.Organization({
name: 'Acme Corporation',
legalName: 'Acme Corp Inc.',
url: 'https://acme.com',
industry: 'Technology',
})
// Create a Product
const product = $.Product({
name: 'Smart Widget',
description: 'An intelligent widget for your home',
price: 99.99,
currency: 'USD',
})Event Patterns
Use semantic triples as event patterns:
// Define event patterns
$.Order.created // Order creation events
$.Payment.succeeded // Payment success events
$.User.email.verified // Email verification events
$.Product.inventory.updated // Inventory update events
$.Shipment.status.changed // Shipment status changesThese patterns are used with on() and send() primitives:
// Subscribe to events
on($.Order.created, async (order) => {
console.log('New order received:', order.id)
})
// Publish events
await send($.Payment.succeeded, {
orderId: 'ord_123',
amount: 99.99,
currency: 'USD',
})Schema.org Type Catalog
The $ proxy provides access to the complete Schema.org vocabulary (817 types, 1,518 properties). Here are the most commonly used types:
Core Business Types
Person
Represents an individual person.
const person = $.Person({
name: 'John Doe',
givenName: 'John',
familyName: 'Doe',
email: '[email protected]',
telephone: '+1-555-0123',
jobTitle: 'Product Manager',
image: 'https://example.com/photo.jpg',
})Common Properties:
name- Full namegivenName- First namefamilyName- Last nameemail- Email addresstelephone- Phone numberjobTitle- Job titleworksFor- Employer (Organization)address- Physical addressbirthDate- Date of birth
Organization
Represents a company, institution, or organization.
const org = $.Organization({
name: 'Tech Innovations Inc',
legalName: 'Tech Innovations Incorporated',
url: 'https://techinnovations.com',
email: '[email protected]',
telephone: '+1-555-0100',
foundingDate: '2015-03-15',
address: {
streetAddress: '123 Innovation Drive',
addressLocality: 'San Francisco',
addressRegion: 'CA',
postalCode: '94103',
addressCountry: 'US',
},
})Common Properties:
name- Organization namelegalName- Legal business nameurl- Website URLemail- Contact emailtelephone- Contact phoneaddress- Physical addressfoundingDate- Date foundedlogo- Logo image URLemployees- Employee count or list
Business
Represents a local business with physical location.
const business = $.Business({
name: 'Main Street Coffee',
description: 'Artisan coffee shop in downtown',
address: {
streetAddress: '456 Main Street',
addressLocality: 'Portland',
addressRegion: 'OR',
postalCode: '97201',
},
telephone: '+1-555-0200',
openingHours: 'Mo-Fr 07:00-19:00, Sa-Su 08:00-17:00',
priceRange: '$$',
geo: {
latitude: 45.5231,
longitude: -122.6765,
},
})Commerce Types
Product
Represents a product or service offering.
const product = $.Product({
name: 'Ergonomic Office Chair',
description: 'Professional ergonomic chair with lumbar support',
sku: 'CHAIR-ERG-001',
brand: $.Brand({ name: 'ErgoMax' }),
image: 'https://example.com/chair.jpg',
offers: $.Offer({
price: 399.99,
priceCurrency: 'USD',
availability: 'https://schema.org/InStock',
seller: $.Organization({ name: 'Office Supply Co' }),
}),
aggregateRating: {
ratingValue: 4.5,
reviewCount: 127,
},
})Common Properties:
name- Product namedescription- Product descriptionsku- Stock keeping unitbrand- Brand (Brand or Organization)offers- Offer with pricingimage- Product image URLcategory- Product categoryaggregateRating- Review ratings
Order
Represents a customer order.
const order = $.Order({
orderNumber: 'ORD-2024-001',
orderDate: new Date(),
orderStatus: 'https://schema.org/OrderProcessing',
customer: $.Person({
name: 'Jane Smith',
email: '[email protected]',
}),
orderedItem: [
$.OrderItem({
orderQuantity: 2,
orderedItem: $.Product({
name: 'Laptop Stand',
sku: 'STAND-001',
}),
}),
],
totalPrice: 149.98,
priceCurrency: 'USD',
billingAddress: {
streetAddress: '789 Oak Avenue',
addressLocality: 'Seattle',
addressRegion: 'WA',
postalCode: '98101',
},
})Common Properties:
orderNumber- Order identifierorderDate- Order dateorderStatus- Order status URLcustomer- Customer (Person)orderedItem- Order itemstotalPrice- Total pricepaymentMethod- Payment methodbillingAddress- Billing addressconfirmationNumber- Confirmation number
Invoice
Represents a billing invoice.
const invoice = $.Invoice({
identifier: 'INV-2024-001',
referencesOrder: $.Order({ orderNumber: 'ORD-2024-001' }),
customer: $.Person({ name: 'John Customer' }),
totalPaymentDue: {
price: 1250.0,
priceCurrency: 'USD',
},
paymentDueDate: '2024-02-15',
paymentStatus: 'https://schema.org/PaymentDue',
billingPeriod: '2024-01',
accountId: 'ACCT-12345',
})Offer
Represents a product or service offer with pricing.
const offer = $.Offer({
price: 49.99,
priceCurrency: 'USD',
availability: 'https://schema.org/InStock',
priceValidUntil: '2024-12-31',
seller: $.Organization({ name: 'Best Electronics' }),
itemCondition: 'https://schema.org/NewCondition',
warranty: $.WarrantyPromise({
durationOfWarranty: {
value: 2,
unitCode: 'ANN',
},
}),
})Event Types
Event
Represents a scheduled event.
const event = $.Event({
name: 'Tech Conference 2024',
description: 'Annual technology conference',
startDate: '2024-06-15T09:00:00Z',
endDate: '2024-06-17T18:00:00Z',
location: $.Place({
name: 'Convention Center',
address: {
addressLocality: 'Austin',
addressRegion: 'TX',
},
}),
organizer: $.Organization({ name: 'Tech Events Inc' }),
offers: $.Offer({
price: 299,
priceCurrency: 'USD',
url: 'https://techconf.example.com/register',
}),
})Common Properties:
name- Event namedescription- Event descriptionstartDate- Start date/timeendDate- End date/timelocation- Event location (Place)organizer- Organizer (Person or Organization)performer- Performersoffers- Ticket offerseventStatus- Event status
Action
Represents a generic action.
const action = $.Action({
name: 'Process Payment',
actionStatus: 'https://schema.org/CompletedActionStatus',
agent: $.Person({ name: 'Payment Processor' }),
object: $.Order({ orderNumber: 'ORD-123' }),
result: $.PaymentChargeSpecification({
amount: 99.99,
currency: 'USD',
}),
startTime: '2024-01-15T10:30:00Z',
endTime: '2024-01-15T10:30:05Z',
})Content Types
Article
Represents an article or blog post.
const article = $.Article({
headline: 'Getting Started with Semantic Business-as-Code',
description: 'Learn how to use the .do platform for semantic programming',
author: $.Person({
name: 'Tech Writer',
url: 'https://example.com/author/tech-writer',
}),
datePublished: '2024-01-15',
dateModified: '2024-01-20',
image: 'https://example.com/article-image.jpg',
articleBody: 'Full article content here...',
keywords: ['semantic-web', 'business-as-code', 'schema.org'],
publisher: $.Organization({ name: 'Tech Blog' }),
})Common Properties:
headline- Article titledescription- Article summaryauthor- Author (Person or Organization)datePublished- Publication datearticleBody- Full article textimage- Featured imagekeywords- Article keywordspublisher- Publisher
CreativeWork
Represents creative content (base type for Article, Video, etc.).
const work = $.CreativeWork({
name: 'Tutorial Video Series',
description: 'Complete video tutorial on semantic programming',
creator: $.Person({ name: 'Content Creator' }),
dateCreated: '2024-01-10',
license: 'https://creativecommons.org/licenses/by/4.0/',
keywords: ['tutorial', 'programming', 'video'],
thumbnailUrl: 'https://example.com/thumbnail.jpg',
})Location Types
Place
Represents a physical location.
const place = $.Place({
name: 'Golden Gate Park',
description: 'Large urban park in San Francisco',
address: {
streetAddress: '501 Stanyan Street',
addressLocality: 'San Francisco',
addressRegion: 'CA',
postalCode: '94117',
addressCountry: 'US',
},
geo: {
latitude: 37.7694,
longitude: -122.4862,
},
openingHours: 'Mo-Su 05:00-00:00',
telephone: '+1-555-0300',
})Common Properties:
name- Place namedescription- Place descriptionaddress- Physical addressgeo- Geographic coordinatesopeningHours- Opening hourstelephone- Contact phonephoto- Place photos
Integration with Other Primitives
Integration with db
Use semantic types when creating database records:
// Create customer with semantic type
const customer = await db.create(
'customers',
$.Person({
name: 'Sarah Johnson',
email: '[email protected]',
telephone: '+1-555-0123',
})
)
// Create order with nested semantic types
const order = await db.create(
'orders',
$.Order({
orderNumber: 'ORD-2024-123',
customer: $.Person({ id: customer.id }),
orderedItem: [
$.OrderItem({
orderQuantity: 1,
orderedItem: $.Product({ name: 'Laptop', sku: 'LAP-001' }),
}),
],
totalPrice: 1299.99,
priceCurrency: 'USD',
})
)
// Query with semantic filters
const activeOrders = await db.list('orders', {
where: {
orderStatus: 'https://schema.org/OrderProcessing',
},
})Integration with on and send
Define event patterns and handlers:
// Subscribe to order events
on($.Order.created, async (order) => {
console.log('Processing new order:', order.orderNumber)
// Send confirmation email
await send($.Email.send, {
to: order.customer.email,
subject: 'Order Confirmation',
template: 'order-confirmation',
data: { order },
})
// Trigger fulfillment workflow
await send($.Fulfillment.start, {
orderId: order.id,
items: order.orderedItem,
})
})
// Payment processing
on($.Payment.succeeded, async (payment) => {
// Update order status
await db.update('orders', payment.orderId, {
orderStatus: 'https://schema.org/OrderPaymentDue',
paymentStatus: 'https://schema.org/PaymentComplete',
})
// Send receipt
await send($.Receipt.send, {
orderId: payment.orderId,
amount: payment.amount,
})
})
// Inventory updates
on($.Product.inventory.updated, async (update) => {
const product = await db.get('products', update.productId)
if (product.inventory < 10) {
await send($.Alert.lowInventory, {
productId: product.id,
productName: product.name,
currentInventory: product.inventory,
})
}
})Integration with ai
Use schemas for structured AI generation:
import { registerSchema } from 'sdk.do'
import { z } from 'zod'
// Register custom schema
registerSchema(
'BusinessPlan',
z.object({
executiveSummary: z.string(),
marketAnalysis: z.string(),
products: z.array(
z.object({
name: z.string(),
description: z.string(),
pricing: z.number(),
})
),
financialProjections: z.object({
year1Revenue: z.number(),
year1Expenses: z.number(),
breakEvenMonth: z.number(),
}),
})
)
// Generate with semantic context
const plan = await ai.generate({
prompt: 'Create a business plan for a coffee shop in Portland',
schema: $.BusinessPlan,
model: 'claude-sonnet-4.5',
})
// Type-safe access
console.log(plan.executiveSummary)
console.log(plan.financialProjections.year1Revenue)
// Store with semantic type
await db.create(
'business-plans',
$.CreativeWork({
name: 'Portland Coffee Shop Business Plan',
creator: $.Person({ name: 'AI Assistant' }),
text: JSON.stringify(plan),
})
)Advanced Patterns
Nested Semantic Composition
Build complex nested structures:
const complexOrder = $.Order({
orderNumber: 'ORD-2024-456',
orderDate: new Date(),
customer: $.Person({
name: 'Emily Davis',
email: '[email protected]',
address: $.PostalAddress({
streetAddress: '123 Elm Street',
addressLocality: 'Portland',
addressRegion: 'OR',
postalCode: '97201',
}),
}),
seller: $.Organization({
name: 'Tech Supplies Inc',
url: 'https://techsupplies.example.com',
}),
orderedItem: [
$.OrderItem({
orderQuantity: 2,
orderedItem: $.Product({
name: 'USB-C Cable',
brand: $.Brand({ name: 'CablePro' }),
offers: $.Offer({
price: 12.99,
priceCurrency: 'USD',
}),
}),
}),
$.OrderItem({
orderQuantity: 1,
orderedItem: $.Product({
name: 'Wireless Mouse',
brand: $.Brand({ name: 'MouseTech' }),
offers: $.Offer({
price: 29.99,
priceCurrency: 'USD',
}),
}),
}),
],
totalPrice: 55.97,
priceCurrency: 'USD',
paymentMethod: $.PaymentMethod({
name: 'Credit Card',
identifier: '****1234',
}),
})Event-Driven E-Commerce Workflow
Complete order processing workflow:
// Order creation
on($.Order.created, async (order) => {
// Validate inventory
for (const item of order.orderedItem) {
const product = await db.get('products', item.orderedItem.id)
if (product.inventory < item.orderQuantity) {
await send($.Order.cancelled, {
orderId: order.id,
reason: 'insufficient_inventory',
product: product.name,
})
return
}
}
// Reserve inventory
await send($.Inventory.reserve, {
orderId: order.id,
items: order.orderedItem,
})
// Send confirmation
await send($.Email.send, {
to: order.customer.email,
subject: 'Order Confirmed',
template: 'order-confirmation',
data: { order },
})
})
// Payment processing
on($.Payment.requested, async (payment) => {
try {
const result = await api.proxy('stripe', '/v1/charges', {
method: 'POST',
body: {
amount: Math.round(payment.amount * 100),
currency: payment.currency.toLowerCase(),
customer: payment.customerId,
},
})
await send($.Payment.succeeded, {
orderId: payment.orderId,
amount: payment.amount,
transactionId: result.id,
})
} catch (error) {
await send($.Payment.failed, {
orderId: payment.orderId,
error: error.message,
})
}
})
// Fulfillment
on($.Payment.succeeded, async (payment) => {
const order = await db.get('orders', payment.orderId)
await send($.Fulfillment.start, {
orderId: order.id,
shippingAddress: order.customer.address,
})
await db.update('orders', order.id, {
orderStatus: 'https://schema.org/OrderProcessing',
})
})
// Shipping
on($.Fulfillment.shipped, async (fulfillment) => {
await db.update('orders', fulfillment.orderId, {
orderStatus: 'https://schema.org/OrderInTransit',
})
const order = await db.get('orders', fulfillment.orderId)
await send($.Email.send, {
to: order.customer.email,
subject: 'Order Shipped',
template: 'order-shipped',
data: {
order,
trackingNumber: fulfillment.trackingNumber,
carrier: fulfillment.carrier,
},
})
})CRM System with Semantic Types
Customer relationship management:
// New lead registration
on($.Lead.created, async (lead) => {
// Create person record
const person = await db.create(
'people',
$.Person({
name: lead.name,
email: lead.email,
telephone: lead.phone,
jobTitle: lead.jobTitle,
worksFor: $.Organization({ name: lead.company }),
})
)
// Send welcome email
await send($.Email.send, {
to: person.email,
subject: 'Welcome!',
template: 'lead-welcome',
})
// Schedule follow-up
await send($.Task.schedule, {
name: 'Follow up with lead',
assignee: lead.assignedTo,
dueDate: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000), // 2 days
})
})
// Lead qualification
on($.Lead.qualified, async (lead) => {
// Convert to opportunity
const opportunity = await db.create(
'opportunities',
$.Opportunity({
name: `${lead.company} - ${lead.product}`,
accountId: lead.accountId,
amount: lead.estimatedValue,
closeDate: lead.expectedCloseDate,
stage: 'Qualification',
})
)
// Notify sales team
await send($.Notification.send, {
type: 'new_opportunity',
recipients: ['[email protected]'],
data: { opportunity },
})
})
// Deal closed
on($.Opportunity.won, async (opportunity) => {
// Create customer
const customer = await db.create(
'customers',
$.Organization({
name: opportunity.accountName,
industry: opportunity.industry,
numberOfEmployees: opportunity.employeeCount,
})
)
// Send welcome package
await send($.Email.send, {
to: opportunity.contactEmail,
subject: 'Welcome to Our Family!',
template: 'customer-welcome',
data: { customer },
})
// Schedule onboarding
await send($.Event.schedule, {
name: 'Customer Onboarding',
startDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
attendees: [opportunity.contactEmail, '[email protected]'],
})
})Content Management System
Blog and content workflow:
// Article draft created
on($.Article.draft.created, async (draft) => {
const article = await db.create(
'articles',
$.Article({
headline: draft.headline,
articleBody: draft.content,
author: $.Person({ id: draft.authorId }),
dateCreated: new Date(),
articleSection: draft.category,
keywords: draft.tags,
})
)
// Assign to editor
await send($.Task.assign, {
type: 'review_article',
assignee: draft.editorId,
articleId: article.id,
})
})
// Article published
on($.Article.published, async (article) => {
// Update article status
await db.update('articles', article.id, {
datePublished: new Date(),
})
// Generate social media posts
const socialPost = await ai.generate({
prompt: `Create an engaging social media post for this article: ${article.headline}`,
schema: $.SocialMediaPosting,
model: 'gpt-5',
})
// Schedule social posts
await send($.SocialMedia.schedule, {
content: socialPost.text,
platforms: ['twitter', 'linkedin'],
scheduledTime: new Date(Date.now() + 60 * 60 * 1000), // 1 hour
})
// Notify subscribers
const subscribers = await db.list('subscribers', {
where: { interests: { contains: article.articleSection } },
})
for (const subscriber of subscribers) {
await send($.Email.send, {
to: subscriber.email,
subject: `New Article: ${article.headline}`,
template: 'new-article',
data: { article },
})
}
})Common Pitfalls and Solutions
1. Forgetting to Call $ as a Function
Wrong:
// This creates a path, not an object
const person = $.PersonCorrect:
// Call it as a function to create an object
const person = $.Person({ name: 'Alice' })2. Mixing Path Construction with Object Creation
Wrong:
// Can't mix path construction with object creation
const path = $.Person({ name: 'Bob' }).worksForCorrect:
// Separate path construction from object creation
const path = $.Person.worksFor.Organization
const person = $.Person({
name: 'Bob',
worksFor: $.Organization({ name: 'Acme' }),
})3. Incorrect Event Pattern Definition
Wrong:
// Event patterns should use dot notation, not nesting
on($.Order({ status: 'created' }), handler)Correct:
// Use property access for event patterns
on($.Order.created, handler)4. Not Converting to String When Needed
Wrong:
// Some APIs expect strings
const path = $.Person.worksFor.Organization
fetch(`/api/${path}`) // May not work as expectedCorrect:
// Explicitly convert to string
const path = $.Person.worksFor.Organization
fetch(`/api/${String(path)}`)
// or
fetch(`/api/${path.toString()}`)Performance Considerations
1. Proxy Overhead
The $ proxy has minimal overhead for path construction, but avoid creating paths in tight loops:
// ❌ Bad: Creating path in loop
for (let i = 0; i < 10000; i++) {
const path = $.Order.created
// ... use path
}
// ✅ Good: Create path once
const orderCreatedPath = $.Order.created
for (let i = 0; i < 10000; i++) {
// ... use orderCreatedPath
}2. Object Creation
Creating semantic objects is fast, but batch operations when possible:
// ❌ Bad: Individual creates
for (const item of items) {
await db.create('products', $.Product(item))
}
// ✅ Good: Batch create
const products = items.map((item) => $.Product(item))
await Promise.all(products.map((p) => db.create('products', p)))3. Event Pattern Matching
Event patterns are matched as strings, so they're very efficient:
// All these are equally efficient
on($.Order.created, handler)
on($.Payment.succeeded, handler)
on($.User.email.verified, handler)Readonly vs Authenticated Mode
The $ proxy itself is available in both modes, but its usage with other primitives may be restricted:
Readonly Mode (Anonymous)
// ✅ Available: Path construction
const path = $.Order.created
const type = $.Person
// ✅ Available: Query with semantic types
const orders = await db.list('orders')
const person = await db.get('people', 'person-123')
// ❌ Blocked: Creating records requires auth
await db.create('orders', $.Order({ ... }))
// ❌ Blocked: Event publishing requires auth
await send($.Order.created, { ... })Authenticated Mode
All operations available:
// Create records with semantic types
await db.create('orders', $.Order({ orderNumber: 'ORD-123' }))
// Subscribe to events
on($.Order.created, handler)
// Publish events
await send($.Payment.succeeded, { ... })Related Primitives
db- Database operations with semantic typeson- Event subscriptions with semantic patternssend- Event publishing with semantic patternsai- AI generation with semantic schemas
Next Steps
- Database Operations - Learn to use
$with database queries - Event Patterns - Event handling with semantic patterns
- Schema.org Vocabulary - Explore all available types
- Examples - Real-world usage examples