---
url: https://docs.snapotter.com/zh-TW/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

只有在你要處理 AI/ML 附屬程序（去背、放大、OCR）時，才需要 Python 3.11+。

## 設定

```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
```

這會啟動兩個開發伺服器：

| 服務  | 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 使用的[慣例式提交](https://www.conventionalcommits.org/)
* 所有 API 輸入驗證皆使用 Zod
* 不修改 Biome、TypeScript 或編輯器設定檔。修正程式碼，而非 linter。

## 資料庫

透過 Drizzle ORM（pg-core）使用 PostgreSQL 17。本機開發需要 Postgres 與 Redis 執行中 - 以下列指令啟動它們：

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

這會在 5432 埠提供 Postgres，並在 6379 埠提供 Redis。接著產生並套用遷移：

```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. 測試

為你的動作按鈕新增一個 `data-testid` 屬性（如上所示），這樣 e2e 測試就能可靠地鎖定它。

### 5. 視覺基準圖

截圖測試不允許任何像素改變，而新工具會改變它們渲染的內容：首頁和目錄中的工具數量、網格中的新卡片，以及工具本身的頁面。在該頁面有基準圖之前，`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
```

每個作業系統工作都會上傳 `visual-baselines-linux-<run-id>-<attempt>` 或 `visual-baselines-darwin-<run-id>-<attempt>` 產物，並針對 `main` 開啟一個包含重新產生之 PNG 的草稿 PR（`chore/visual-baselines-linux-...` 與 `chore/visual-baselines-darwin-...`）。每個草稿 PR 的描述中都有一行 `gh run download` 指令；在你的 checkout 根目錄執行這兩行指令，把 PNG 放進你的分支，提交後關閉這些草稿 PR。如果 `changed` 漏掉了你預期會改變的截圖，請改用 `update_snapshots=all`。觸發工作流程需要儲存庫的寫入權限，所以如果你的分支在 fork 上，請在 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 有意有三個版本域。發佈期間請勿將一個網域複製到另一個網域：

* 應用程式發布版本涵蓋根清單、所有私人工作區包和 `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` 中；應用程式版本同步絕對不能隱含重寫該原則檔。

## 環境變數

完整清單請見[設定指南](/zh-TW/guide/configuration)。開發時的關鍵變數：

| 變數                    | 預設   | 描述                                    |
|-----------------------------|-----------|------------------------------------------------|
| `AUTH_ENABLED`              | `true`    | 啟用／停用驗證                  |
| `DEFAULT_USERNAME`          | `admin`   | 預設管理員使用者名稱                         |
| `DEFAULT_PASSWORD`          | `admin`   | 預設管理員密碼                         |
| `SKIP_MUST_CHANGE_PASSWORD` | `false`   | 略過強制變更密碼（僅供 CI／開發）      |
| `RATE_LIMIT_PER_MIN`       | `1000`    | 每分鐘的 API 速率限制（0 = 停用）       |
| `MAX_UPLOAD_SIZE_MB`       | `100`     | 最大上傳大小（MB）（0 = 無限制）      |
