Files
SnapOtter/apps/docs/zh-TW/guide/developer.md
T
SnapOtterandGitHub d10d0f544f fix: release QA hardening across processing, media, security, and CI gates (#649)
A release-readiness QA pass over the whole product. The commits split into
defects a user would hit and gates that were reporting green while measuring
nothing.

## Fixes that change behaviour

Rate limiting was bypassable on every install: TRUST_PROXY defaulted to true, so
request.ip came from a client-set header and a forged X-Forwarded-For got past
the login limiter. The default is now a private-network trust list.

A transient Postgres outage stranded in-flight jobs, leaving finished output on
disk with no row pointing at it. A reconciler now resolves those rows and adopts
the bytes rather than dropping the work.

A Redis connection that moved to a new address wedged every read-blocked
consumer, so completions stopped signalling while health still answered 200.
Socket timeouts plus subscriber pings recover it.

Installing more than one AI bundle left the shared venv multi-versioned and
silently broke three tools. The installer now reconciles distributions to one
version each.

Converting an image to JXL at quality 1 through 4 returned a 500, because
libjxl 0.7 rejects the distance those values compute. The quality is floored at
what the encoder honours. A missing ffmpeg was also reported to the user as a
corrupt upload; it now says the engine is unavailable.

RAW uploads reached an unpatched LibRaw on arm64, so it is built from source at
0.22.2, and the release scan was split so it can fail on an unfixed critical
instead of hiding it behind ignore-unfixed.

## Gates that could not fail

Two mutation lanes ran zero mutants because Stryker crawled the gitignored docs
build; coverage discarded its whole report on any failing test; the lint gate
skipped root tests, scripts, and two workspaces; and several generated matrices
counted a host missing ffmpeg as a passing tool. Each now measures what it
claims.

Full evidence and the outstanding release items are tracked locally and are not
part of this branch.
2026-07-27 15:37:30 +08:00

8.5 KiB
Raw Blame History

description, i18n_source_hash, i18n_provenance, i18n_output_hash, i18n_hash_version
description i18n_source_hash i18n_provenance i18n_output_hash i18n_hash_version
SnapOtter 的本機開發環境設定、指令、程式碼慣例,以及如何新增工具。 56acc1bf9a9b machine d94d76633902 2

開發者指南

如何設定本機開發環境,並為 SnapOtter 貢獻程式碼。

先決條件

  • Node.js 22.22+
  • pnpm 9+corepack enable && corepack prepare pnpm@latest --activate
  • Docker(本機 Postgres + Redis、容器建置與 AI 功能所必需)
  • Git

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

設定

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

指令

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 使用的慣例式提交
  • 所有 API 輸入驗證皆使用 Zod
  • 不修改 Biome、TypeScript 或編輯器設定檔。修正程式碼,而非 linter。

資料庫

透過 Drizzle ORMpg-core)使用 PostgreSQL 17。本機開發需要 Postgres 與 Redis 執行中 - 以下列指令啟動它們:

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

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

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

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

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 的前端工具登錄表中註冊它:

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

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

4. 測試

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

Docker 建置

在本機建置完整的生產映像檔:

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

使用 BuildKit 快取掛載以加快重新建置:

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 中;應用程式版本同步絕對不能隱含重寫該原則檔。

環境變數

完整清單請見設定指南。開發時的關鍵變數:

變數 預設 描述
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 = 無限制)