@sonicjs-cms/core
Core framework for SonicJS - A modern, TypeScript-first headless CMS built for Cloudflare's edge platform.
๐ New to SonicJS?
Visit sonicjs.com for full documentation and guides.
To create a new SonicJS project, use:
npx create-sonicjs my-app
This is the recommended way to get started with SonicJS. It sets up everything you need with a single command.
โจ Features
- ๐ Edge-First: Runs on Cloudflare Workers for sub-50ms global response times
- ๐ฆ Zero Cold Starts: V8 isolates provide instant startup
- ๐ Type-Safe: Full TypeScript support with comprehensive type definitions
- ๐ Plugin System: Extensible architecture with hooks and middleware
- โก Three-Tier Caching: Memory, KV, and database layers for optimal performance
- ๐จ Admin Interface: Beautiful glass morphism design system
- ๐ Authentication: JWT-based auth with role-based permissions
- ๐ Content Management: Dynamic collections with versioning and workflows
- ๐ผ๏ธ Media Management: R2 storage with automatic optimization
- ๐ REST API: Auto-generated endpoints for all collections
๐ฆ Installation
npm install @sonicjs-cms/core
Required Peer Dependencies
npm install @cloudflare/workers-types hono drizzle-orm zod
Optional Dependencies
npm install wrangler drizzle-kit # For development
๐ Quick Start
1. Create Your Application
// src/index.ts
import { createSonicJSApp } from '@sonicjs-cms/core'
import type { SonicJSConfig } from '@sonicjs-cms/core'
const config: SonicJSConfig = {
collections: {
directory: './src/collections',
autoSync: true
},
plugins: {
directory: './src/plugins',
autoLoad: false
}
}
export default createSonicJSApp(config)
2. Define Collections
// src/collections/blog-posts.collection.ts
import type { CollectionConfig } from '@sonicjs-cms/core'
export default {
name: 'blog-posts',
displayName: 'Blog Posts',
description: 'Manage your blog posts',
schema: {
type: 'object',
properties: {
title: {
type: 'string',
title: 'Title',
required: true,
maxLength: 200
},
content: {
type: 'markdown',
title: 'Content',
required: true
},
publishedAt: {
type: 'datetime',
title: 'Published Date'
},
status: {
type: 'select',
title: 'Status',
enum: ['draft', 'published', 'archived'],
default: 'draft'
}
},
required: ['title', 'content']
}
} satisfies CollectionConfig
3. Configure Cloudflare Workers
# wrangler.toml
name = "my-sonicjs-app"
main = "src/index.ts"
compatibility_date = "2024-01-01"
[[d1_databases]]
binding = "DB"
database_name = "my-sonicjs-db"
database_id = "your-database-id"
migrations_dir = "./node_modules/@sonicjs-cms/core/migrations"
[[r2_buckets]]
binding = "BUCKET"
bucket_name = "my-sonicjs-media"
4. Start Development
# Run migrations
wrangler d1 migrations apply DB --local
# Start dev server
wrangler dev
Visit http://localhost:8787/admin to access the admin interface.
๐ Core Exports
Main Application
import { createSonicJSApp } from '@sonicjs-cms/core'
import type { SonicJSConfig, SonicJSApp, Bindings, Variables } from '@sonicjs-cms/core'
Services
import {
loadCollectionConfigs,
syncCollections,
MigrationService,
Logger,
PluginService
} from '@sonicjs-cms/core'
Middleware
import {
requireAuth,
requireRole,
requirePermission,
loggingMiddleware,
cacheHeaders,
securityHeaders
} from '@sonicjs-cms/core'
Types
import type {
CollectionConfig,
FieldConfig,
Plugin,
PluginContext,
User,
Content,
Media
} from '@sonicjs-cms/core'
Templates
import {
renderForm,
renderTable,
renderPagination,
renderAlert
} from '@sonicjs-cms/core'
Utilities
import {
sanitizeInput,
TemplateRenderer,
QueryFilterBuilder,
metricsTracker
} from '@sonicjs-cms/core'
Database
import {
createDb,
users,
collections,
content,
media
} from '@sonicjs-cms/core'
๐ Subpath Exports
The package provides organized subpath exports:
// Services only
import { MigrationService } from '@sonicjs-cms/core/services'
// Middleware only
import { requireAuth } from '@sonicjs-cms/core/middleware'
// Types only
import type { CollectionConfig } from '@sonicjs-cms/core/types'
// Templates only
import { renderForm } from '@sonicjs-cms/core/templates'
// Utilities only
import { sanitizeInput } from '@sonicjs-cms/core/utils'
// Plugins only
import { HookSystemImpl } from '@sonicjs-cms/core/plugins'
๐ฏ Usage Examples
Custom Routes
import { Hono } from 'hono'
import { requireAuth } from '@sonicjs-cms/core/middleware'
import type { Bindings } from '@sonicjs-cms/core'
const customRoutes = new Hono<{ Bindings: Bindings }>()
customRoutes.get('/api/custom', requireAuth(), async (c) => {
const db = c.env.DB
// Your custom logic
return c.json({ message: 'Custom endpoint' })
})
// In your app config
export default createSonicJSApp({
routes: [{ path: '/custom', handler: customRoutes }]
})
Custom Plugin
import type { Plugin } from '@sonicjs-cms/core'
export default {
name: 'my-plugin',
version: '1.0.0',
description: 'My custom plugin',
async onActivate() {
console.log('Plugin activated!')
},
hooks: {
'content.beforeSave': async (content) => {
// Transform content before saving
content.metadata = { modified: new Date() }
return content
}
}
} satisfies Plugin
Accessing Services
import { Logger, MigrationService } from '@sonicjs-cms/core'
const logger = new Logger({ category: 'custom', level: 'info' })
logger.info('Application started')
const migrationService = new MigrationService(db)
await migrationService.runAllMigrations()
๐๏ธ Architecture
@sonicjs-cms/core
โโโ src/
โ โโโ app.ts # Application factory
โ โโโ db/ # Database schemas & utilities
โ โ โโโ migrations-bundle.ts # Auto-generated migration bundle
โ โโโ services/ # Business logic
โ โโโ middleware/ # Request processing
โ โโโ routes/ # HTTP handlers
โ โโโ templates/ # Admin UI components
โ โโโ plugins/ # Plugin system & core plugins
โ โโโ types/ # TypeScript definitions
โ โโโ utils/ # Utility functions
โโโ migrations/ # Core database migrations (.sql files)
โโโ scripts/
โ โโโ generate-migrations.ts # Migration bundler script
โโโ dist/ # Compiled output
๐ Development Workflow
Migration System
SonicJS uses a build-time migration bundler because Cloudflare Workers cannot access the filesystem at runtime. All migration SQL is bundled into TypeScript during the build process.
Creating New Migrations
-
Create the SQL file in
migrations/:# Use sequential three-digit numbering touch migrations/027_add_your_feature.sql -
Write idempotent SQL:
-- migrations/027_add_your_feature.sql CREATE TABLE IF NOT EXISTS your_table ( id TEXT PRIMARY KEY, name TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_your_table_name ON your_table(name); -
Regenerate the bundle:
npm run generate:migrations # Or this runs automatically during: npm run build -
Build the package:
npm run build -
Apply to your test database:
cd ../my-sonicjs-app wrangler d1 migrations apply DB --local
Available Scripts
# Generate migrations bundle only
npm run generate:migrations
# Build (automatically runs generate:migrations first)
npm run build
# Type check
npm run type-check
# Run tests
npm run test
How It Works
migrations/*.sql โ scripts/generate-migrations.ts โ src/db/migrations-bundle.ts โ dist/
The generate-migrations.ts script:
- Reads all
.sqlfiles frommigrations/ - Generates
src/db/migrations-bundle.tswith embedded SQL - Provides
getMigrationSQLById()for runtime access
Important: Always rebuild after modifying migration files. The .sql files are not used at runtime.
๐ Versioning
SonicJS follows semantic versioning:
- v2.x.x - Current npm package (core extracted)
- v1.x.x - Legacy monolith (deprecated)
Current Version: 2.0.0-alpha.1
Upgrade Path
# Install the new package
npm install @sonicjs-cms/core@2.0.0-alpha.1
# Run any new migrations
wrangler d1 migrations apply DB
# Test your application
npm run dev
๐ Documentation
๐ค Contributing
We welcome contributions! Please see CONTRIBUTING.md.
๐ License
MIT ยฉ SonicJS Team - See LICENSE for details.
๐ฌ Support & Community
- Issues: GitHub Issues
- Discord: Join our community
- Docs: sonicjs.com
- Twitter: @sonicjscms
๐ Resources
- Create SonicJS App - Scaffold a new project
- Cloudflare Workers Docs
- D1 Database
- R2 Storage
โก Performance
- Global edge deployment
- Sub-50ms response times
- Zero cold starts
- Automatic scaling
- Built-in caching
๐ก๏ธ Security
- JWT authentication
- Role-based access control (RBAC)
- Permission system
- Secure headers
- Input sanitization
Built with โค๏ธ for the edge | v2.0.0-alpha.1