---
url: https://docs.snapotter.com/ja/guide/developer.md
description: ローカル開発環境のセットアップ、コマンド、コード規約、そして SnapOtter に新しいツールを追加する方法。
---

# 開発者ガイド

ローカル開発環境をセットアップし、SnapOtter にコードを貢献する方法。

## 前提条件

* [Node.js](https://nodejs.org/) 22.22 以上
* [pnpm](https://pnpm.io/) 9 以上（`corepack enable && corepack prepare pnpm@latest --activate`）
* [Docker](https://www.docker.com/)（ローカルの Postgres + Redis、コンテナビルド、AI 機能に必要）
* Git

Python 3.10 以上は、AI/ML サイドカー（背景除去、アップスケール、OCR）に取り組む場合にのみ必要です。

## セットアップ

```bash
git clone https://github.com/snapotter-hq/snapotter.git
cd snapotter
docker compose -f docker-compose.dev.yml up -d   # start Postgres + Redis
pnpm install
pnpm dev
```

これにより 2 つの開発サーバーが起動します。

| サービス | URL | 備考 |
|----------|--------------------------|------------------------------------|
| フロントエンド | http://localhost:1351 | Vite 開発サーバー、/api をプロキシ |
| バックエンド | http://localhost:13490 | Fastify API（プロキシ経由でアクセス） |

ブラウザで http://localhost:1351 を開きます。`admin` / `admin` でログインします。初回ログイン時にパスワードの変更を求められます。

## プロジェクト構成

```
apps/
  api/              Fastify backend
  web/              Vite + React frontend
  docs/             VitePress documentation (this site)
packages/
  shared/           Constants, types, i18n strings
  image-engine/     Sharp-based image operations
  media-engine/     FFmpeg spawn + progress parsing
  doc-engine/       qpdf, LibreOffice, ghostscript wrappers
  ai/               Python sidecar bridge for ML models
tests/
  unit/             Vitest unit tests
  integration/      Vitest integration tests (full API)
  e2e/              Playwright end-to-end specs
  fixtures/         Small test images
```

## コマンド

```bash
pnpm dev                # start frontend + backend
pnpm build              # build all workspaces
pnpm typecheck          # TypeScript check across monorepo
pnpm lint               # Biome lint + format check
pnpm lint:fix           # auto-fix lint + format
pnpm test               # unit + integration tests
pnpm test:unit          # unit tests only
pnpm test:integration   # integration tests only
pnpm test:e2e           # Playwright e2e tests
pnpm test:coverage      # tests with coverage report
```

## コード規約

* ダブルクォート、セミコロン、2 スペースインデント（Biome で強制）
* すべてのワークスペースで ES モジュール
* semantic-release 用の [Conventional Commits](https://www.conventionalcommits.org/)
* すべての API 入力検証に Zod
* Biome、TypeScript、エディタの設定ファイルは変更しないこと。リンターではなくコードを修正してください。

## データベース

Drizzle ORM（pg-core）経由の PostgreSQL 17。ローカル開発では Postgres と Redis の起動が必要です。次で起動します。

```bash
docker compose -f docker-compose.dev.yml up -d
```

これにより、Postgres がポート 5432 で、Redis がポート 6379 で利用できます。続いてマイグレーションを生成して適用します。

```bash
cd apps/api
npx drizzle-kit generate   # generate a migration from schema changes
npx drizzle-kit migrate    # apply pending migrations
```

スキーマは `apps/api/src/db/schema.ts` で定義されています。テーブル: users、sessions、settings、jobs、apiKeys、pipelines、teams、userFiles、roles、auditLog。

## 新しいツールの追加

すべてのツールは同じパターンに従います。以下は最小限の例です。

### 1. バックエンドルート

`apps/api/src/routes/tools/my-tool.ts` を作成します。

```ts
import { z } from "zod";
import type { FastifyInstance } from "fastify";
import { createToolRoute } from "../tool-factory.js";

const settingsSchema = z.object({
  intensity: z.number().min(0).max(100).default(50),
});

export function registerMyTool(app: FastifyInstance) {
  createToolRoute(app, {
    toolId: "my-tool",
    settingsSchema,
    async process(inputBuffer, settings, filename) {
      // Use sharp or other libraries to process the image
      const sharp = (await import("sharp")).default;
      const result = await sharp(inputBuffer)
        // ... your processing logic
        .toBuffer();

      return {
        buffer: result,
        filename: filename.replace(/\.[^.]+$/, ".png"),
        contentType: "image/png",
      };
    },
  });
}
```

その後、`apps/api/src/routes/tools/index.ts` で登録します。

### 2. フロントエンド設定コンポーネント

`apps/web/src/components/tools/my-tool-settings.tsx` を作成します。

```tsx
import { useState } from "react";
import { useToolProcessor } from "@/hooks/use-tool-processor";
import { useFileStore } from "@/stores/file-store";

export function MyToolSettings() {
  const { files } = useFileStore();
  const { processFiles, processing, error, downloadUrl } =
    useToolProcessor("my-tool");

  const [intensity, setIntensity] = useState(50);

  const handleProcess = () => {
    processFiles(files, { intensity });
  };

  return (
    <div className="space-y-4">
      {/* your controls here */}
      <button
        type="button"
        onClick={handleProcess}
        disabled={files.length === 0 || processing}
        data-testid="my-tool-submit"
        className="w-full py-2.5 rounded-lg bg-primary text-primary-foreground font-medium disabled:opacity-50"
      >
        Process
      </button>
    </div>
  );
}
```

その後、`apps/web/src/lib/tool-registry.tsx` のフロントエンドツールレジストリで登録します。

```tsx
// Add the lazy import
const MyToolSettings = lazy(() =>
  import("@/components/tools/my-tool-settings").then((m) => ({
    default: m.MyToolSettings,
  })),
);

// Add to the toolRegistry Map
["my-tool", { displayMode: "before-after", Settings: MyToolSettings }],
```

表示モード: `"side-by-side"`、`"before-after"`、`"live-preview"`、`"no-comparison"`、`"interactive-crop"`、`"interactive-eraser"`、`"no-dropzone"`。

### 3. i18n エントリ

`packages/shared/src/i18n/en.ts` に追加します。

```ts
"my-tool": {
  name: "My Tool",
  description: "Short description of what this tool does",
},
```

### 4. テスト

e2e テストが確実に対象にできるよう、アクションボタンに `data-testid` 属性を追加します（上記のとおり）。

### 5. ビジュアルベースライン

スクリーンショットテストは変化したピクセルを 1 つも許容しません。新しいツールを追加すると描画内容が変わります。ホームページとカタログのツール数、グリッドの新しいカード、そしてベースラインができるまで `tests/e2e/gui-visual-tools.spec.ts` が "snapshot doesn't exist" で失敗するツール自身のページです。夜間のビジュアル比較をグリーンに保つため、ベースラインはツールと同じ PR で更新してください。

CI は `linux`（`ubuntu-latest`）と `darwin`（`macos-latest`）の両方のベースラインを生成します。ブランチをプッシュし、そのブランチで更新を実行します：

```bash
gh workflow run update-visual-baselines.yml --ref <your-branch> -f update_snapshots=changed
```

各 OS ジョブは `visual-baselines-linux-<run-id>-<attempt>` または `visual-baselines-darwin-<run-id>-<attempt>` アーティファクトをアップロードし、再生成した PNG を含むドラフト PR（`chore/visual-baselines-linux-...` と `chore/visual-baselines-darwin-...`）を `main` 向けに作成します。各ドラフト PR の本文に `gh run download` コマンドがあるので、チェックアウトのルートで両方とも実行して PNG をブランチに取り込み、コミットしてからドラフト PR をクローズしてください。変わるはずのスクリーンショットを `changed` が拾わない場合は、代わりに `update_snapshots=all` を使います。実行にはリポジトリへの書き込み権限が必要です。ブランチがフォークにある場合は、ベースラインの更新が必要だと PR に書いてください。メンテナーが実行します。

Mac では、手元で素早く確認したい場合に `darwin` のベースラインをローカルで更新することもできます：

```bash
pnpm playwright test tests/e2e/gui-visual-desktop.spec.ts tests/e2e/gui-visual-tools.spec.ts tests/e2e/device-visual.spec.ts --project=chromium-visual --project=mobile-chromium --project=tablet-chromium --update-snapshots=changed
```

いずれの場合も、コミットする前に新規または変更された PNG をすべて開いて確認してください。ベースラインは、壊れていてもいなくても、描画された内容をそのまま記録します。

リリースではこの作業は不要です。アプリのバージョンは表示されるすべてのスクリーンショットでマスクされるため、バージョンを上げてもベースラインは変わりません。

## Docker ビルド

完全な本番イメージをローカルでビルドします。

```bash
docker build -f docker/Dockerfile -t snapotter:latest .
```

より高速な再ビルドのために BuildKit のキャッシュマウントを使います。

```bash
DOCKER_BUILDKIT=1 docker build -f docker/Dockerfile -t snapotter:latest .
```

## リリースバージョンのドメイン

SnapOtter には意図的に 3 つのバージョン ドメインがあります。リリース中に、あるドメインを別のドメインにコピーしないでください。

* アプリケーションのリリース バージョンには、ルート マニフェスト、すべてのプライベート ワークスペース パッケージ、および `APP_VERSION` が含まれます。 Semantic-release はこの値を提供し、`pnpm version:sync <version>` はアプリケーションのリリース前にすべてのワークスペースを更新します。
* OpenAPI `info.version` は、安定したパブリック API メジャー コントラクトです。すべてのローカライズされた仕様は、互換性のあるアプリケーション リリースでは `<major>.0.0` に残り、API 契約が新しいメジャー バージョンに移行する場合にのみ変更されます。
* `docker/feature-manifest.json` は、`imageVersion: 2.0.0` を不変のレガシー機能バンドル ストレージ エポックとして保持します。これらの v2 アーカイブ パスは、アプリケーション パッケージのバージョンではありません。正確な OCR はランタイム形式 v3 を使用し、アプリケーションのリリースの出所を個別に記録します。

`tests/unit/infra/release-version-policy.test.ts` はこれらの境界を強制します。新しいバージョンのドメインまたは移行では、その契約と関連するアーティファクトの移行設計を一緒に更新する必要があります。
独立した API およびレガシーバンドルの値は `config/release-version-policy.json` に存在します。アプリケーションのバージョン同期では、そのポリシー ファイルを暗黙的に書き換えてはなりません。

## 環境変数

完全な一覧については [設定ガイド](/ja/guide/configuration) を参照してください。開発で重要なものは次のとおりです。

| 変数 | デフォルト | 説明 |
|-----------------------------|-----------|------------------------------------------------|
| `AUTH_ENABLED` | `true` | 認証の有効化/無効化 |
| `DEFAULT_USERNAME` | `admin` | デフォルトの管理者ユーザー名 |
| `DEFAULT_PASSWORD` | `admin` | デフォルトの管理者パスワード |
| `SKIP_MUST_CHANGE_PASSWORD` | `false` | パスワードの強制変更をスキップ（CI/開発のみ） |
| `RATE_LIMIT_PER_MIN` | `1000` | 1 分あたりの API レート制限（0 = 無効） |
| `MAX_UPLOAD_SIZE_MB` | `100` | 最大アップロードサイズ（MB）（0 = 無制限） |
