# @omnifyjp/omnify

**Schema-driven migration & type generation for Laravel and TypeScript.**

Define your database schemas in YAML, generate Laravel PHP migrations, raw SQL, and TypeScript types — all with a single command.

**YAMLでデータベーススキーマを定義し、Laravelマイグレーション・SQL・TypeScript型を一括生成するCLIツールです。**

---

## Features / 機能

- **YAML Schema Definition** — Human-readable schema format with localized display names
- **Laravel Migration Generation** — Complete PHP migration files with foreign keys, indexes, and comments
- **Raw SQL Generation** — MySQL, PostgreSQL, and SQLite
- **TypeScript Generation** — Interfaces, Zod schemas, and i18n types from `schemas.json`
- **PHP Codegen** — Eloquent models, form requests, API resources, and factories from `schemas.json`
- **Incremental Generation** — Lock file tracks changes; only regenerates what's needed
- **Compound Types** — Single property expands to multiple columns (e.g., `JapaneseName` → 4 columns)
- **Associations** — ManyToOne, OneToMany, ManyToMany (pivot tables), MorphMany/MorphTo
- **MCP Server** — AI tool integration for Cursor, Claude Code, and other MCP-compatible editors
- **Zero Runtime Dependencies** — Single Go binary + bundled TypeScript generator

---

## Installation / インストール

```bash
npm install -D @omnifyjp/omnify
```

This installs:
- `omnify` — Go CLI binary (platform-specific)
- `omnify-ts` — TypeScript type generator

Both are available in `node_modules/.bin/` after installation.

---

## Quick Start / クイックスタート

### 1. Initialize / 初期化

```bash
npx omnify init
```

Creates `omnify.yaml` and `schemas/` directory.

### 2. Define a Schema / スキーマ定義

Create `schemas/system/User.yaml`:

```yaml
displayName:
  ja: ユーザー
  en: User
group: system

options:
  timestamps: true
  softDelete: true

properties:
  name:
    type: String
    length: 100
    displayName:
      ja: 名前
      en: Name

  email:
    type: Email
    unique: true
    displayName:
      ja: メールアドレス
      en: Email

  password:
    type: Password
    displayName:
      ja: パスワード
      en: Password
```

### 3. Generate / 生成

```bash
npx omnify generate
```

This generates:
- **Laravel migrations** → `database/migrations/omnify/`
- **SQL files** → configured output path
- **TypeScript types** → if `codegen.typescript` configured (interfaces, Zod schemas, i18n)
- **PHP codegen** → if `codegen.laravel` configured (Eloquent models, requests, resources, factories)
- **schemas.json** → serialized schema data
- **Lock file** → `.omnify/lock.json` (tracks schema state)

---

## Configuration / 設定

Create `omnify.yaml` in your project root:

```yaml
schemasDir: ./schemas
lockFilePath: .omnify/lock.json

connections:
  default:
    driver: mysql
    migrations:
      - type: laravel
        path: database/migrations/omnify
        schemasPath: database/omnify/schemas.json
      - type: sql
        path: migrations/sql
        dialect: mysql

default: default

locale:
  locales: [ja, en, vi]
  defaultLocale: ja
  fallbackLocale: en

compoundTypes:
  - japan    # Enables JapaneseName, JapaneseAddress, JapaneseBankAccount

codegen:
  typescript:
    enable: true
    modelsPath: resources/js/types/models    # TS interfaces, Zod schemas, i18n
  laravel:
    enable: true
    model:                                   # Eloquent models
      path: app/Models/Omnify
      namespace: App\Models\Omnify
```

### Codegen / コード自動生成

When `codegen` is configured, `omnify generate` automatically generates code after writing `schemas.json`. No separate step needed.

`codegen`を設定すると、`omnify generate`実行時にコードが自動生成されます。

#### TypeScript (`codegen.typescript`)
- `base/` — Auto-generated interfaces and Zod schemas (overwritten on each generation)
- `enum/` — Enum type definitions
- Model files — User-editable model files (created once, never overwritten)

#### Laravel PHP (`codegen.laravel`)
- Eloquent base models (`Base/`) — always overwritten
- User models — created once, never overwritten
- Form requests (Store + Update) — base + user files
- API resources — base + user files
- Factories — created once
- Service provider, traits, locales

### Multiple Connections / 複数接続

```yaml
connections:
  default:
    driver: mysql
    migrations:
      - type: laravel
        path: database/migrations/omnify

  product-db:
    driver: pgsql
    migrations:
      - type: laravel
        path: database/migrations/product
      - type: sql
        path: output/sql/product
        dialect: postgresql
```

---

## CLI Commands / コマンド一覧

```bash
omnify init                        # Initialize project / プロジェクト初期化
omnify validate                    # Validate all schemas / スキーマ検証
omnify diff                        # Show pending changes / 変更差分表示
omnify generate                    # Generate migrations + types / マイグレーション＋型生成
omnify generate --force            # Regenerate all / 全再生成
omnify generate --migrations-only  # Migrations only (skip SQL, TypeScript) / マイグレーションのみ
omnify generate --connection=name  # Generate for specific connection / 特定接続のみ
omnify list                        # List schemas and types / スキーマ一覧
omnify add                         # Add a new schema / スキーマ追加
omnify mcp                         # Start MCP server / MCPサーバー起動
omnify version                     # Show version / バージョン表示
```

### Global Flags

| Flag | Short | Description |
|------|-------|-------------|
| `--config` | `-c` | Config file path (default: `omnify.yaml`) |
| `--verbose` | `-v` | Enable verbose output |

---

## Schema Format / スキーマフォーマット

### Associations / アソシエーション

```yaml
properties:
  # ManyToOne — creates foreign key column
  author:
    type: Association
    relation: ManyToOne
    target: User
    onDelete: CASCADE

  # ManyToMany — generates pivot table
  tags:
    type: Association
    relation: ManyToMany
    target: Tag
    joinTable: post_tags

  # Polymorphic
  comments:
    type: Association
    relation: MorphMany
    target: Comment
    morphName: commentable
```

### Enum Schema / Enumスキーマ

```yaml
# schemas/blog/PostStatus.yaml
kind: enum
displayName:
  ja: 投稿ステータス
  en: Post Status
group: blog

values:
  - draft
  - published
  - archived
```

### Schema Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `id` | bool | `true` | Auto-incrementing primary key / 自動採番主キー |
| `idType` | string | `BigInt` | Primary key type / 主キー型 |
| `timestamps` | bool | `true` | `created_at` / `updated_at` columns |
| `softDelete` | bool | `false` | `deleted_at` column / 論理削除 |
| `indexes` | array | `[]` | Composite indexes / 複合インデックス |

### Property Options

| Option | Type | Description |
|--------|------|-------------|
| `type` | string | Property type (see Type System below) |
| `nullable` | bool | Allow NULL values |
| `unique` | bool | Unique constraint |
| `default` | any | Default value |
| `length` | int | String/VARCHAR length |
| `unsigned` | bool | Unsigned integer |
| `precision` | int | Decimal precision |
| `scale` | int | Decimal scale |
| `displayName` | object | Localized display names / 多言語表示名 |

---

## Type System / 型システム

### Built-in Types / 組み込み型

| Type | Laravel | MySQL | PostgreSQL | SQLite |
|------|---------|-------|------------|--------|
| `String` | `string` | VARCHAR(255) | VARCHAR(255) | TEXT |
| `TinyInt` | `tinyInteger` | TINYINT | SMALLINT | INTEGER |
| `Int` | `integer` | INT | INTEGER | INTEGER |
| `BigInt` | `bigInteger` | BIGINT UNSIGNED | BIGINT | INTEGER |
| `Float` | `double` | DOUBLE | DOUBLE PRECISION | REAL |
| `Decimal` | `decimal` | DECIMAL(p,s) | DECIMAL(p,s) | REAL |
| `Boolean` | `boolean` | TINYINT(1) | BOOLEAN | INTEGER |
| `Text` | `text` | TEXT | TEXT | TEXT |
| `MediumText` | `mediumText` | MEDIUMTEXT | TEXT | TEXT |
| `LongText` | `longText` | LONGTEXT | TEXT | TEXT |
| `Date` | `date` | DATE | DATE | TEXT |
| `Time` | `time` | TIME | TIME | TEXT |
| `Timestamp` | `timestamp` | TIMESTAMP | TIMESTAMP | TEXT |
| `DateTime` | `dateTime` | DATETIME | TIMESTAMP | TEXT |
| `Json` | `json` | JSON | JSONB | TEXT |
| `Email` | `string` | VARCHAR(255) | VARCHAR(255) | TEXT |
| `Password` | `string` | VARCHAR(255) | VARCHAR(255) | TEXT |
| `Uuid` | `uuid` | CHAR(36) | UUID | TEXT |
| `Enum` | `enum` | ENUM(...) | VARCHAR(50) | TEXT |
| `EnumRef` | `string(50)` | VARCHAR(50) | VARCHAR(50) | TEXT |
| `Point` | `point` | POINT | POINT | - |
| `Coordinates` | `decimal` x2 | DECIMAL | DECIMAL | REAL |

### Compound Types (Japan Plugin) / 複合型（日本プラグイン）

Enable with `compoundTypes: [japan]` in `omnify.yaml`.

| Type | Columns | Description |
|------|---------|-------------|
| `JapaneseName` | 4 | `lastname`, `firstname`, `kana_lastname`, `kana_firstname` |
| `JapaneseAddress` | 5 | `postal_code`, `prefecture` (ENUM 47都道府県), `address1`, `address2`, `address3` |
| `JapaneseBankAccount` | 7 | `bank_code`, `bank_name`, `branch_code`, `branch_name`, `account_type`, `account_number`, `account_holder` |
| `JapanesePhone` | 1 | Maps to String (VARCHAR 15) |
| `JapanesePostalCode` | 1 | Maps to String (VARCHAR 8) |

#### Example / 使用例

```yaml
properties:
  name:
    type: JapaneseName
    displayName:
      ja: 氏名
      en: Full Name
```

Generates:

```php
$table->string('name_lastname', 100)->comment('Full Name (Lastname)');
$table->string('name_firstname', 100)->comment('Full Name (Firstname)');
$table->string('name_kana_lastname', 200)->nullable()->comment('Full Name (KanaLastname)');
$table->string('name_kana_firstname', 200)->nullable()->comment('Full Name (KanaFirstname)');
```

---

## MCP Server (AI Integration) / MCPサーバー（AI連携）

Omnify includes a built-in [Model Context Protocol](https://modelcontextprotocol.io/) server for AI-powered editors.

AI対応エディタ（Cursor、Claude Code等）でスキーマ情報をリアルタイムに参照できるMCPサーバーを内蔵しています。

### Cursor

Add to `.cursor/mcp.json`:

```json
{
  "mcpServers": {
    "omnify": {
      "command": "npx",
      "args": ["omnify", "mcp"]
    }
  }
}
```

### Claude Code

Add to `.mcp.json`:

```json
{
  "mcpServers": {
    "omnify": {
      "command": "npx",
      "args": ["omnify", "mcp"],
      "type": "stdio"
    }
  }
}
```

### Available MCP Tools / 利用可能なツール

| Tool | Description |
|------|-------------|
| `omnify_guide` | Interactive documentation (YAML format, types, associations, best practices) |
| `omnify_list_schemas` | List all schemas with metadata, filterable by kind/group |
| `omnify_get_schema` | Get raw YAML + computed metadata for a specific schema |
| `omnify_list_types` | List all property types (built-in, compound, simple, enum) |
| `omnify_validate` | Validate YAML against the schema system with target verification |

### MCP Prompts (Slash Commands) / スラッシュコマンド

MCP prompts appear as autocomplete options when you type `/` in your editor.

MCPプロンプトはエディタで`/`を入力すると自動補完されます。

| Prompt | Usage | Description |
|--------|-------|-------------|
| `create_schema` | `/create_schema "Product with name, price, category"` | Create a new schema with full project context (existing schemas, types, locales) |
| `add_property` | `/add_property schema=Product "email field"` | Add a property to an existing schema with type guidance |
| `review_schema` | `/review_schema schema=User` | Review schema for best practices, missing fields, improvements |

In Claude Code, prompts are accessed via `/mcp__omnify__create_schema`.
In Cursor, prompts appear in the `/` autocomplete menu.

---

## TypeScript Editor DX / TypeScriptエディタ支援

This package includes `.d.ts` type definitions for `omnify.yaml` and YAML schema files, providing autocompletion in your editor.

このパッケージには`omnify.yaml`とYAMLスキーマファイル用の`.d.ts`型定義が含まれており、エディタで自動補完が利用できます。

```typescript
import type { OmnifyConfig } from '@omnifyjp/omnify/types/config';
import type { SchemaDefinition } from '@omnifyjp/omnify/types/schema';
```

---

## Supported Platforms / 対応プラットフォーム

| Platform | Architecture | Package |
|----------|-------------|---------|
| macOS | Apple Silicon (arm64) | `@omnifyjp/omnify-darwin-arm64` |
| macOS | Intel (x64) | `@omnifyjp/omnify-darwin-x64` |
| Linux | x86_64 | `@omnifyjp/omnify-linux-x64` |
| Linux | ARM64 | `@omnifyjp/omnify-linux-arm64` |
| Windows | x86_64 | `@omnifyjp/omnify-win32-x64` |

The correct platform binary is installed automatically via `optionalDependencies`.

プラットフォームに応じたバイナリが`optionalDependencies`経由で自動インストールされます。

---

## Links

- [GitHub](https://github.com/omnifyjp/omnify-go) — Source code, issues, and contributions
- [docs/explanation/development.md](https://github.com/omnifyjp/omnify-go/blob/main/docs/explanation/development.md) — Architecture docs, data flow, type system reference

## License

MIT
