Code Generation (~~)
Generate valid NAIDE code from natural language instructions. No AI, no network, no dependencies — pure pattern matching + template composition with self-healing parser validation. Runs in microseconds.
CLI Usage
Use ~~ or gen followed by a quoted instruction:
naide ~~ "REST API for users with auth"
naide gen "todo app with database"
naide ~~ "Discord bot with hello command"
naide ~~ "blog app with auth and websocket"
naide ~~ "users and products and orders with auth"
naide gen "chat app"
Japanese instructions are fully supported:
naide ~~ "ユーザー管理APIを認証付きで"
naide ~~ "掲示板アプリ"
naide ~~ "ECサイト"
naide ~~ "チャットアプリ"
Write the output to a file with -o:
naide ~~ "REST API for users" -o app.naide
Multi-Target Output
Generate and compile to any of the 15 supported targets with --target:
naide ~~ "REST API for users" --target python # Python/Flask
naide ~~ "todo app" --target go # Go/net-http
naide ~~ "REST API for users" --target rust # Rust/actix-web
naide ~~ "REST API for users" --target all # All 15 targets
naide ~~ "REST API for users" --target all -o app # app.py, app.go, app.rs, ...
Targets: node, python, bun, typescript, go, java, rust, cpp, c, csharp, kotlin, swift, dart, php, ruby.
Multi-Entity Support
Specify multiple entities separated by spaces, and, &, or ,. The engine detects parent-child and many-to-many relationships automatically:
naide ~~ "users products orders with auth"
naide ~~ "users and products and orders with auth"
This generates 3 schemas (User, Product, Order), detects that User → Order and Product → Order, and adds user_id and product_id FK fields automatically. Each entity gets full CRUD, paginated list, soft delete, batch operations, nested routes, and tests.
Composite keywords also expand to multiple entities:
naide ~~ "shop" # User + Product + Order
naide ~~ "ECサイト" # User + Product + Order
naide ~~ "crm" # User + Contact + Deal + Activity
naide ~~ "sns" # User + Post + Comment + Message + Notification
Project Mode
Generate a complete project directory with all supporting files:
naide ~~ "e-commerce app with auth" --project
This creates a directory with 17 files:
app.naide— Main NAIDE source codepackage.json— With dev/test/seed/migrate scripts.env— Environment variables (JWT_SECRET, PORT).env.development/.env.production— Environment-specific configs.gitignore— node_modules, .env, data/Dockerfile+.dockerignore— Docker container supportdocker-compose.yml— Docker Compose with app + PostgreSQLREADME.md— Full API documentation with endpointsopenapi.json— OpenAPI 3.0.3 specificationadmin.html— Admin dashboard with CRUD forms, search, statsindex.html— Frontend SPA with auth UI, CRUD per entity, search/sort/paginationclient.mjs— JavaScript API client with typed functionstest.mjs— HTTP integration tests (Node.js test runner)migrate.naide— Database migration with CREATE TABLE + rollback.github/workflows/ci.yml— GitHub Actions CI pipeline
Project Update
Run --project again on an existing project directory to add entities and features incrementally:
# Step 1: Create project
naide ~~ "chat app" --project -o my-app
# Step 2: Add users with auth
naide ~~ "users with auth" --project -o my-app
# Step 3: Add products
naide ~~ "products" --project -o my-app
# Step 4: Remove an entity
naide ~~ "remove products" --project -o my-app
The engine detects the existing app.naide, combines all entities, regenerates the full code with relationships, and updates all 15 supporting files.
Entity removal is supported via remove, delete, or drop keywords. The engine filters out the target entities and regenerates the project without them.
File Write Mode
Write generated code directly to a .naide file:
naide ~~ "REST API for users with auth" --write app.naide
naide ~~ "todo app" --write todo.naide
naide ~~ "users API" --write app.naide --replace
Without --replace, the engine merges intelligently — avoids duplicate schemas and servers. With --replace, the file is overwritten completely.
Generated Features
Every server-type generation automatically includes:
Per-Entity Routes
| Route | Description |
|---|---|
GET /api/users?page=1&limit=20&search=&sort=id&order=desc | Paginated list with search, sort, filter |
POST /api/users | Create (with validation) |
GET /api/users/:id | Get by ID |
PUT /api/users/:id | Update (with validation) |
DELETE /api/users/:id | Hard delete |
DELETE /api/users/:id/soft | Soft delete (sets deleted = true) |
PUT /api/users/:id/restore | Restore soft-deleted |
POST /api/users/batch | Batch create |
DELETE /api/users/batch | Batch delete |
Nested Routes (from relationships)
When parent-child relationships are detected, nested routes are generated:
GET /api/users/:userId/orders # Orders by User
GET /api/users/:userId/posts # Posts by User
GET /api/products/:productId/orders # Orders by Product
Global Routes
| Route | Description |
|---|---|
GET /api/health | Health check with entity counts |
POST /api/upload | File upload endpoint |
POST /api/webhooks | Register a webhook |
GET /api/webhooks/health | Webhook health check |
Auth Routes (when auth intent detected)
| Route | Description |
|---|---|
POST /api/auth/register | User registration |
POST /api/auth/login | JWT login |
GET /api/auth/me | Current user profile |
POST /api/auth/forgot-password | Request password reset token |
POST /api/auth/reset-password | Reset password with token |
POST /api/auth/change-password | Change password (authenticated) |
GET /api/admin/stats | Admin-only aggregate stats |
Many-to-Many Routes
When two entities have a known M:N relationship (e.g., User ↔ Product), a junction table and link/unlink routes are auto-generated:
| Route | Description |
|---|---|
GET /api/users/:id/products | Products for a User (via Favorite junction) |
GET /api/products/:id/users | Users for a Product |
POST /api/favorite | Link User ↔ Product |
DELETE /api/favorite | Unlink User ↔ Product |
Known M:N pairs: User↔Product (Favorite), User↔Team (TeamMember), Post↔Category (PostTag), Product↔Category (ProductCategory), User↔Group (GroupMember).
Utility Functions
Standard response helpers and input sanitization:
fn ok(any data, any meta) → {ok: true, data, meta}
fn err(str message, int code) → {ok: false, error: message, code}
fn sanitize(str input) → stripped HTML tags
Input Validation
A validateEntity(body) function is generated per entity, checking required fields, types, enum values, and min/max constraints. POST and PUT routes call validation before saving.
Rate Limiting & Logging
A rateLimit(windowMs, maxReqs) function and a requestLogger(req, res, next) middleware are generated for production hardening.
Caching
A GET /api/cache-demo route demonstrates Cache-Control headers for static content caching.
Swagger UI
A GET /docs route serves an interactive Swagger UI page powered by the generated OpenAPI spec at /api/openapi.json. Both routes are public (no auth required).
RBAC (Role-Based Access Control)
When auth is enabled, a requireRole(allowed) middleware function is generated. Delete routes require admin or moderator role. Roles: user, admin, moderator.
WebSocket Rooms + Auth
When websocket intent is detected, room-based WebSocket is generated with join, leave, and broadcast actions. Messages are scoped to rooms. When auth is also enabled, WS connections require a JWT token via ?token= query parameter — unauthenticated clients are rejected.
Frontend SPA
Project mode generates an index.html with a complete single-page application:
- Navigation between entities with per-entity CRUD UI
- Search, sort (asc/desc), and pagination controls
- Modal forms for create/edit
- When auth is enabled: login/register forms, auth-aware fetch calls, logout, token persistence (localStorage)
- Error handling: try/catch on all API calls, loading spinners, error banners, 401 auto-redirect to login
- Toast notifications (success/error/warning) and responsive layout
Integration Tests
Project mode generates a test.mjs file with HTTP integration tests using Node.js built-in test runner. Tests cover:
- Health check endpoint
- Auth flow (register, login, me, invalid credentials) when auth is enabled
- Full CRUD cycle per entity (create, list, get, update, delete)
Run with npm test (requires server running).
Database Migration
Project mode generates a migrate.naide file with SQL DDL for all entities. Includes migrate() (CREATE TABLE with types, constraints, foreign keys) and rollback() (DROP TABLE). Run with npm run migrate.
Enum Validation
Fields named status, priority, role, or visibility automatically get enum validation with preset allowed values.
Audit Log
When auth is enabled, an AuditLog schema and auditLog() function are generated for tracking actions.
Seed Function
A fn seed() function is generated with sample data for each entity, callable via npm run seed in project mode.
Auto-Generated Tests
CRUD test suites are generated for each entity — create, find, list, remove with assertions.
Inline Directives
Use ~~ inside .naide files. The directive is expanded at compile time, before parsing:
# app.naide
~~ "REST API for users with auth"
# You can mix with hand-written code
fn customRoute(req, res):
ret {custom: true}
Debug the expansion with --expand:
naide --expand app.naide
API Usage
Use programmatically in JavaScript/TypeScript:
import { generate, generateProject } from 'naider';
const result = generate("users and products with auth");
console.log(result.code); // generated NAIDE source code
console.log(result.valid); // true (parser-validated)
console.log(result.intents); // ['server', 'schema', 'crud', 'auth', 'database']
console.log(result.entities); // ['User', 'Product']
console.log(result.relationships); // [{parent:'User', child:'Product', fk:'user_id'}]
console.log(result.port); // 3000
console.log(result.fixed); // false (true if auto-repaired)
console.log(result.repairs); // [] (list of auto-fix descriptions)
console.log(result.analysis); // {entities, relationships, plan, ...}
// Full project generation (17 files)
const project = generateProject("e-commerce with auth");
project.files.forEach(f => console.log(f.path));
// app.naide, package.json, .env, .env.development, .env.production,
// Dockerfile, .dockerignore, docker-compose.yml, README.md,
// openapi.json, admin.html, index.html, client.mjs, test.mjs,
// migrate.naide, .github/workflows/ci.yml
// Multi-target: generate for a specific target
import { generateForTarget, generateAllTargets } from 'naider';
const py = await generateForTarget("users API", "python");
console.log(py.compiled); // Python/Flask code
console.log(py.target); // "python"
// Generate for ALL 15 targets at once
const all = await generateAllTargets("todo app");
for (const [target, result] of Object.entries(all.targets)) {
console.log(target, result.ext, result.error || 'OK');
}
MCP Server
The naide_generate tool is available via the MCP server for AI agent integration:
naide-mcp
The tool accepts instruction, port, and schemaName parameters, and returns generated code with metadata.
Self-Healing Validation
Generated code is validated against the actual NAIDE parser. If a parse error occurs, the engine auto-repairs it (up to 5 retries):
- Missing
:at the end of block headers - Unexpected indentation (adds colon to previous line)
- Reserved keyword used as identifier (renames with suffix)
- Structural issues (removes problematic lines)
Repairs are logged in result.repairs:
["L5: added missing ':' at end of block header",
"L8: renamed reserved word 'post' → 'postApp'"]
Field Normalization
Field names are automatically normalized via a synonym dictionary:
| Input | Normalized | Inferred Type |
|---|---|---|
e-mail, mail_address | email | str + email |
pwd, passwd | password | str + min(8) |
tel, phone_number | phone | str |
desc, detail | description | str |
img, pic, avatar | image | str |
qty | quantity | int |
is_done, is_active | done, active | bool |
created_at | created | auto |
Keyword Cheat Sheet
Intent Keywords
| Keyword | What it generates |
|---|---|
server api rest web backend | Server block with Express |
schema model entity | Schema definition with fields |
crud create list | Auto-generated REST endpoints |
auth jwt login | JWT authentication middleware |
database db storage | Persistent storage (db "data/") |
bot | Bot with event handlers |
cli command terminal | CLI app with flags |
page html frontend | HTML page generation |
test spec | Test block with assertions |
websocket ws realtime | WebSocket endpoint |
ai llm gpt | AI prompt endpoint |
mail smtp | Email configuration |
graphql gql | GraphQL endpoint |
Composite Keywords
These trigger multiple intents and multi-entity generation:
| Keyword | Entities | Intents |
|---|---|---|
todo | Todo | server + crud + database |
blog | Post | server + crud + database |
chat | Message | server + websocket + database |
shop ecommerce ECサイト | User + Product + Order | server + crud + auth + database |
fullstack | (from instruction) | server + crud + auth + database |
board 掲示板 | Post | server + crud + database |
crm | User + Contact + Deal + Activity | server + crud + auth + database |
inventory | Product + Category + Inventory | server + crud + auth + database |
booking 予約 | User + Event + Reservation | server + crud + auth + database |
sns | User + Post + Comment + Message + Notification | server + crud + auth + websocket + database |
Natural Language Detection
Complex phrases are parsed into intents:
| Phrase | Detected |
|---|---|
| "users can comment", "users post reviews" | auth + crud |
| "admin delete", "admin manage" | auth + admin routes |
| "upload", "file upload" | upload route |
| "search", "filter", "sort" | paginated list |
| "notification", "push", "alert" | websocket |
| "deploy", "docker", "container" | Docker support |
| "seed", "初期データ", "サンプルデータ" | seed function |
Platform & DB Keywords
| Keyword | Effect |
|---|---|
discord slack telegram line | Bot platform selection |
sqlite | db.sql "sqlite" |
postgres | db.sql "postgres" |
Japanese Keywords
| Category | Keywords |
|---|---|
| Intent | サーバー 認証 ログイン 会員 CRUD 管理 データベース ボット テスト ページ メール リアルタイム |
| Entity | ユーザー 商品 記事 タスク 注文 コメント イベント 問い合わせ 通知 カテゴリ 掲示板 決済 予約 社員 |
| Composite | 管理システム やることリスト ブログ チャットアプリ ECサイト 掲示板 |
Field Specification
Add with followed by field names to customize the schema:
naide ~~ "REST API for users with name email age role"
Field types are auto-inferred from names: id→auto, email→str+email, age→int, done→bool, created→auto. Without with, preset fields are used based on the entity name.
Agent-Style Analysis
The CLI shows an analysis header before code output, including detected entities, relationships, plan, and feature counts:
--- NAIDE Agent Analysis ---
Entities: User (5 fields), Product (6 fields), Order (5 fields)
Relations: User → Order (user_id), Product → Order (product_id)
Intents: server, schema, crud, auth, database
Routes: 9 per entity + 3 nested + 6 global
Plan: Define User/Product/Order schemas, configure database, create server with CRUD...
Examples
Multi-Entity E-commerce
naide ~~ "users and products and orders with auth"
Generates: 3 schemas with auto FK relations, paginated CRUD, soft delete, batch ops, nested routes, seed, tests, auth with admin stats
Full Project (15 files)
naide ~~ "e-commerce app with auth" --project
Generates: complete project with source, package.json, Docker + Compose, OpenAPI, admin dashboard, frontend SPA, API client, CI pipeline, env configs, README
CRM System
naide ~~ "crm"
Generates: User + Contact + Deal + Activity with auth, relationships, full CRUD stack
Write to File
naide ~~ "REST API for users with auth" --write app.naide
Generates and writes directly to app.naide, merging with existing code
Japanese: EC Site
naide ~~ "ECサイト"
Generates: User + Product + Order with auth, same as English "shop" composite