setup-project-foundation: Next.js 16 + SQLite scaffold (WIP)

- Next.js 16 App Router (TS strict, src/), minimal placeholder page
- ESLint (domain/ may not import server/ or next) + Prettier
- SQLite via better-sqlite3 + Drizzle: WAL/foreign_keys/busy_timeout,
  migrations, idempotent seed, withTransaction (BEGIN IMMEDIATE)
- Zod-validated env; startup exits on bad config and creates attachments dir
- Vitest unit/integration tests with temp-DB helper (12 passing)
- Playwright config + home e2e test (not yet verified passing)

Tasks 1.1-5.1 done; 5.2, 6.x, 7.x pending.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-06 18:06:31 +08:00
co-authored by Claude Opus 5.5
parent 350e83b58e
commit bbd81f6137
43 changed files with 9568 additions and 11 deletions
+13
View File
@@ -0,0 +1,13 @@
# 複製為 .env 後填入。.env 不進版控。
# SQLite 資料庫檔路徑
DATABASE_PATH=./data/app.db
# 附件儲存目錄(伺服器啟動時自動建立;不可放在 public/ 底下)
ATTACHMENTS_DIR=./data/attachments
# Session 簽章金鑰,至少 32 字元。產生方式:node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
SESSION_SECRET=
# 業務時區(申請截止、月份判斷)
TZ_APP=Asia/Taipei
# 備份輸出目錄與保留份數
BACKUP_DIR=./backups
BACKUP_KEEP=14
+4
View File
@@ -43,3 +43,7 @@ desktop.ini
# Claude Code local settings
.claude/settings.local.json
# misc
*.pem
.vercel
+12
View File
@@ -0,0 +1,12 @@
.next/
node_modules/
package-lock.json
src/server/db/migrations/
openspec/
docs/
.claude/
playwright-report/
test-results/
coverage/
data/
backups/
+3
View File
@@ -0,0 +1,3 @@
{
"printWidth": 100
}
+9
View File
@@ -0,0 +1,9 @@
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
<!-- END:nextjs-agent-rules -->
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from "drizzle-kit";
// 只用於 `npm run db:generate` 產生 migration;套用 migration 由 `npm run db:migrate` 負責。
export default defineConfig({
dialect: "sqlite",
schema: "./src/server/db/schema/index.ts",
out: "./src/server/db/migrations",
});
+42
View File
@@ -0,0 +1,42 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
import prettier from "eslint-config-prettier/flat";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
prettier,
// domain/ 是純函式業務邏輯,不得依賴伺服器端程式或 Next.js,才能單獨單元測試。
{
files: ["src/domain/**/*.{ts,tsx}"],
rules: {
"no-restricted-imports": [
"error",
{
patterns: [
{
group: ["@/server", "@/server/*", "**/server/*", "next", "next/*"],
message: "src/domain 必須是純函式,不得 import src/server 或 Next.js。",
},
],
},
],
},
},
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
// Generated / local output:
"src/server/db/migrations/**",
"playwright-report/**",
"test-results/**",
"coverage/**",
]),
]);
export default eslintConfig;
+5
View File
@@ -0,0 +1,5 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {/* config options here */};
export default nextConfig;
@@ -2,29 +2,29 @@
## 1. 專案初始化
- [ ] 1.1 `git init`,建立 `.gitignore`(node_modules、.next、data/、backups/、.env、playwright 報告),並確認 `git status` 不出現上述目錄
- [ ] 1.2 以 Next.js(App Router、TypeScript、`src/` 目錄)建立專案,開啟 TypeScript strict,確認 `npm run dev` 可開啟預設首頁且 `npm run build` 成功
- [ ] 1.3 建立 design 所列目錄結構(`src/domain`、`src/server/db/{schema,migrations}`、`src/lib`、`src/components`、`tests/e2e`),各放一個說明用途的 README 或 index,確認結構存在
- [x] 1.1 `git init`,建立 `.gitignore`(node_modules、.next、data/、backups/、.env、playwright 報告),並確認 `git status` 不出現上述目錄
- [x] 1.2 以 Next.js(App Router、TypeScript、`src/` 目錄)建立專案,開啟 TypeScript strict,確認 `npm run dev` 可開啟預設首頁且 `npm run build` 成功
- [x] 1.3 建立 design 所列目錄結構(`src/domain`、`src/server/db/{schema,migrations}`、`src/lib`、`src/components`、`tests/e2e`),各放一個說明用途的 README 或 index,確認結構存在
## 2. 程式碼品質工具
- [ ] 2.1 設定 ESLint(含 `no-restricted-imports` 禁止 `src/domain` 引用 `src/server`、`next/*`)與 Prettier,新增 `lint`、`format`、`typecheck` 腳本,並以一個故意違規的暫時檔確認 lint 會報錯後刪除
- [x] 2.1 設定 ESLint(含 `no-restricted-imports` 禁止 `src/domain` 引用 `src/server`、`next/*`)與 Prettier,新增 `lint`、`format`、`typecheck` 腳本,並以一個故意違規的暫時檔確認 lint 會報錯後刪除
## 3. 資料庫
- [ ] 3.1 安裝 better-sqlite3、drizzle-orm、drizzle-kit,建立連線模組(WAL、foreign_keys、busy_timeout、dev 模式 globalThis singleton),確認啟動後 `PRAGMA journal_mode` 回傳 `wal`
- [ ] 3.2 設定 drizzle-kit 與 `db:generate`、`db:migrate` 腳本,建立一張暫時的 `_meta` 表產生第一個 migration,確認 `npm run db:migrate` 可在空資料庫上成功執行
- [ ] 3.3 建立 `db:seed` 腳本骨架(可重複執行、不重複插入),確認連續執行兩次不報錯
- [ ] 3.4 建立交易工具函式(以 `BEGIN IMMEDIATE` 包住 callback,例外時 rollback),並以 Vitest 測試 commit 與 rollback 兩種情況通過
- [x] 3.1 安裝 better-sqlite3、drizzle-orm、drizzle-kit,建立連線模組(WAL、foreign_keys、busy_timeout、dev 模式 globalThis singleton),確認啟動後 `PRAGMA journal_mode` 回傳 `wal`
- [x] 3.2 設定 drizzle-kit 與 `db:generate`、`db:migrate` 腳本,建立一張暫時的 `_meta` 表產生第一個 migration,確認 `npm run db:migrate` 可在空資料庫上成功執行
- [x] 3.3 建立 `db:seed` 腳本骨架(可重複執行、不重複插入),確認連續執行兩次不報錯
- [x] 3.4 建立交易工具函式(以 `BEGIN IMMEDIATE` 包住 callback,例外時 rollback),並以 Vitest 測試 commit 與 rollback 兩種情況通過
## 4. 環境設定與附件目錄
- [ ] 4.1 建立 `.env.example` 與以 Zod 驗證環境變數的模組,確認缺少 `SESSION_SECRET` 時啟動失敗並顯示明確訊息
- [ ] 4.2 建立附件儲存目錄設定(啟動時自動建立 `ATTACHMENTS_DIR`),確認首次啟動後目錄存在
- [x] 4.1 建立 `.env.example` 與以 Zod 驗證環境變數的模組,確認缺少 `SESSION_SECRET` 時啟動失敗並顯示明確訊息
- [x] 4.2 建立附件儲存目錄設定(啟動時自動建立 `ATTACHMENTS_DIR`),確認首次啟動後目錄存在
## 5. 測試框架
- [ ] 5.1 設定 Vitest(node 環境、整合測試用暫存資料庫 helper:建立暫存 SQLite 並跑 migration),新增 `test` 腳本,確認範例單元與整合測試通過
- [x] 5.1 設定 Vitest(node 環境、整合測試用暫存資料庫 helper:建立暫存 SQLite 並跑 migration),新增 `test` 腳本,確認範例單元與整合測試通過
- [ ] 5.2 設定 Playwright(使用獨立測試資料庫、build+start 啟動),新增 `test:e2e` 腳本,確認一個開啟首頁的範例測試通過
## 6. 備份
+8861
View File
File diff suppressed because it is too large Load Diff
+43
View File
@@ -0,0 +1,43 @@
{
"name": "ai-subsidy-system",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint",
"format": "prettier --write .",
"format:check": "prettier --check .",
"typecheck": "next typegen && tsc --noEmit",
"db:generate": "drizzle-kit generate",
"db:migrate": "tsx scripts/db-migrate.ts",
"db:seed": "tsx scripts/db-seed.ts",
"test": "vitest run",
"test:watch": "vitest",
"test:e2e": "playwright test"
},
"dependencies": {
"better-sqlite3": "^13.0.3",
"drizzle-orm": "^0.45.3",
"next": "16.3.8",
"react": "19.2.8",
"react-dom": "19.2.8",
"zod": "^4.6.5"
},
"devDependencies": {
"@playwright/test": "^1.63.0",
"@types/better-sqlite3": "^9.6.0",
"@types/node": "^24.19.1",
"@types/react": "^19",
"@types/react-dom": "^19",
"drizzle-kit": "^0.31.11",
"eslint": "^9",
"eslint-config-next": "16.3.8",
"eslint-config-prettier": "^10.1.8",
"prettier": "^3.9.9",
"tsx": "^4.23.15",
"typescript": "^5",
"vitest": "^5.0.3"
}
}
+32
View File
@@ -0,0 +1,32 @@
import { defineConfig, devices } from "@playwright/test";
const PORT = 3100;
// e2e 使用獨立的資料庫與附件目錄,不碰開發用的 data/app.db。
const e2eEnv = {
DATABASE_PATH: "./data/e2e/app.db",
ATTACHMENTS_DIR: "./data/e2e/attachments",
SESSION_SECRET: "e2e-session-secret-0123456789abcdef",
TZ_APP: "Asia/Taipei",
};
export default defineConfig({
testDir: "./tests/e2e",
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
reporter: process.env.CI ? "github" : "list",
use: {
baseURL: `http://localhost:${PORT}`,
trace: "on-first-retry",
},
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
webServer: {
// 對正式建置測試:build → migrate → seed → start。
command: `npm run build && npm run db:migrate && npm run db:seed && npx next start -p ${PORT}`,
url: `http://localhost:${PORT}`,
env: e2eEnv,
reuseExistingServer: !process.env.CI,
timeout: 300_000,
},
});
+9
View File
@@ -0,0 +1,9 @@
import "./load-env";
import { getDatabase } from "@/server/db/client";
import { runMigrations } from "@/server/db/migrate";
import { getEnv } from "@/server/env";
const { db, sqlite } = getDatabase();
runMigrations(db);
console.log(`migration 完成:${getEnv().DATABASE_PATH}`);
sqlite.close();
+8
View File
@@ -0,0 +1,8 @@
import "./load-env";
import { getDatabase } from "@/server/db/client";
import { seed } from "@/server/db/seed";
const { db, sqlite } = getDatabase();
seed(db);
console.log("seed 完成");
sqlite.close();
+4
View File
@@ -0,0 +1,4 @@
import { loadEnvConfig } from "@next/env";
// 讓 CLI 腳本與 Next.js 用同一套規則載入 .env、.env.local 等檔案。
loadEnvConfig(process.cwd());
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+11
View File
@@ -0,0 +1,11 @@
/* 全站樣式與設計 tokens 由 add-app-shell 建立。 */
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
margin: 0;
font-family: system-ui, "Noto Sans TC", "Microsoft JhengHei", sans-serif;
}
+15
View File
@@ -0,0 +1,15 @@
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "AI 補助申請系統",
description: "AI Subsidy Application System",
};
export default function RootLayout({ children }: LayoutProps<"/">) {
return (
<html lang="zh-Hant-TW">
<body>{children}</body>
</html>
);
}
+9
View File
@@ -0,0 +1,9 @@
// 暫時首頁:全站框架與 Dashboard 由 add-app-shell、add-role-dashboards 建立。
export default function Home() {
return (
<main>
<h1>AI 補助申請系統</h1>
<p>AI Subsidy Application System</p>
</main>
);
}
+3
View File
@@ -0,0 +1,3 @@
# src/components
共用 UI 元件(StatusBadge、MoneyDisplay、ConfirmDialog 等,由 add-app-shell 建立)。
+7
View File
@@ -0,0 +1,7 @@
# src/domain
純函式業務邏輯:月結計算、狀態機、日期與月份規則等。
- 不得有 I/O(資料庫、檔案、網路、`Date.now()` 之類的隱含時間);「現在」由呼叫端傳入。
- 不得 import `@/server/*`、`next` 或 `next/*`(ESLint `no-restricted-imports` 強制)。
- 單元測試與被測檔放在一起:`*.test.ts`。
+12
View File
@@ -0,0 +1,12 @@
export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
const { runStartupChecks } = await import("@/server/startup");
try {
runStartupChecks();
} catch (error) {
// 設定錯誤時直接結束程序,讓服務管理器看得到失敗,而不是留下一個無法服務的程序。
console.error(error instanceof Error ? error.message : error);
process.exit(1);
}
}
}
+3
View File
@@ -0,0 +1,3 @@
# src/lib
前後端共用的程式:Zod 驗證 schema、金額/日期格式化等。不得 import `@/server/*`。
+8
View File
@@ -0,0 +1,8 @@
# src/server
只在伺服器端執行的程式:資料庫連線、repository、service(交易邊界在這一層)、auth、環境變數。
- `db/client.ts`:SQLite 單一連線(WAL、foreign_keys、busy_timeout)。
- `db/transaction.ts`:`withTransaction`,以 `BEGIN IMMEDIATE` 包住多筆寫入。
- `db/schema/`:Drizzle schema,依 capability 分檔,由 `db/schema/index.ts` 匯出。
- `db/migrations/`:`npm run db:generate` 產生的 SQL migration,納入版控,不要手改。
+37
View File
@@ -0,0 +1,37 @@
import fs from "node:fs";
import path from "node:path";
import Database from "better-sqlite3";
import { drizzle, type BetterSQLite3Database } from "drizzle-orm/better-sqlite3";
import { getEnv } from "@/server/env";
import * as schema from "./schema";
export type Db = BetterSQLite3Database<typeof schema>;
export interface DatabaseHandle {
sqlite: Database.Database;
db: Db;
}
/** 開啟 SQLite 並套用連線設定(WAL、外鍵檢查、鎖定等待)。 */
export function openDatabase(file: string): DatabaseHandle {
if (file !== ":memory:") {
fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true });
}
const sqlite = new Database(file);
sqlite.pragma("journal_mode = WAL");
sqlite.pragma("foreign_keys = ON");
sqlite.pragma("busy_timeout = 5000");
return { sqlite, db: drizzle(sqlite, { schema }) };
}
// 整個 Node 程序共用一條連線。掛在 globalThis 上,dev 模式 HMR 重新載入模組時不會重複開啟。
const globalForDb = globalThis as unknown as { __appDatabase?: DatabaseHandle };
export function getDatabase(): DatabaseHandle {
globalForDb.__appDatabase ??= openDatabase(getEnv().DATABASE_PATH);
return globalForDb.__appDatabase;
}
export function getDb(): Db {
return getDatabase().db;
}
+10
View File
@@ -0,0 +1,10 @@
import path from "node:path";
import { migrate } from "drizzle-orm/better-sqlite3/migrator";
import type { Db } from "./client";
export const MIGRATIONS_DIR = path.join(process.cwd(), "src", "server", "db", "migrations");
/** 套用所有尚未執行的 migration;已套用的會略過,可重複執行。 */
export function runMigrations(db: Db): void {
migrate(db, { migrationsFolder: MIGRATIONS_DIR });
}
@@ -0,0 +1,5 @@
CREATE TABLE `_meta` (
`key` text PRIMARY KEY NOT NULL,
`value` text NOT NULL,
`updated_at` text NOT NULL
);
@@ -0,0 +1,49 @@
{
"version": "6",
"dialect": "sqlite",
"id": "572e1ecd-dece-498b-9902-d668dee6ef0b",
"prevId": "00000000-0000-0000-0000-000000000000",
"tables": {
"_meta": {
"name": "_meta",
"columns": {
"key": {
"name": "key",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
@@ -0,0 +1,13 @@
{
"version": "7",
"dialect": "sqlite",
"entries": [
{
"idx": 0,
"version": "6",
"when": 1791199731109,
"tag": "0000_long_cannonball",
"breakpoints": true
}
]
}
+2
View File
@@ -0,0 +1,2 @@
// 所有 Drizzle schema 由此匯出;drizzle-kit 與資料庫連線都從這裡讀取。
export * from "./meta";
+8
View File
@@ -0,0 +1,8 @@
import { sqliteTable, text } from "drizzle-orm/sqlite-core";
// 系統層級的 key/value 紀錄(例如 seed 執行時間)。業務資料表由各功能 change 依 capability 分檔建立。
export const meta = sqliteTable("_meta", {
key: text("key").primaryKey(),
value: text("value").notNull(),
updatedAt: text("updated_at").notNull(),
});
+19
View File
@@ -0,0 +1,19 @@
import { meta } from "./schema";
import { withTransaction } from "./transaction";
import type { Db } from "./client";
/**
* 種子資料。必須可重複執行:每筆都用 upsert 或 `onConflictDoNothing`,不得重複插入。
* 各功能 change 在這裡加入自己的初始資料(例如制度參數預設值、範例帳號)。
*/
export function seed(db: Db, now: Date = new Date()): void {
withTransaction(db, (tx) => {
tx.insert(meta)
.values({ key: "seeded_at", value: now.toISOString(), updatedAt: now.toISOString() })
.onConflictDoUpdate({
target: meta.key,
set: { value: now.toISOString(), updatedAt: now.toISOString() },
})
.run();
});
}
+65
View File
@@ -0,0 +1,65 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import Database from "better-sqlite3";
import { eq } from "drizzle-orm";
import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db";
import { meta } from "./schema";
import { withTransaction } from "./transaction";
const row = (key: string) => ({ key, value: "v", updatedAt: "2026-10-05T00:00:00.000Z" });
describe("withTransaction", () => {
let t: TestDatabase;
beforeEach(() => {
t = createTestDatabase();
});
afterEach(() => t.cleanup());
it("callback 正常結束時 commit 所有寫入", () => {
withTransaction(t.db, (tx) => {
tx.insert(meta).values(row("a")).run();
tx.insert(meta).values(row("b")).run();
});
expect(t.db.select().from(meta).all().map((r) => r.key)).toEqual(["a", "b"]);
});
it("callback 丟出例外時 rollback,且例外向外拋出", () => {
expect(() =>
withTransaction(t.db, (tx) => {
tx.insert(meta).values(row("a")).run();
throw new Error("boom");
}),
).toThrow("boom");
expect(t.db.select().from(meta).where(eq(meta.key, "a")).all()).toEqual([]);
});
it("違反約束時整筆交易 rollback", () => {
expect(() =>
withTransaction(t.db, (tx) => {
tx.insert(meta).values(row("a")).run();
tx.insert(meta).values(row("a")).run();
}),
).toThrow();
expect(t.db.select().from(meta).all()).toEqual([]);
});
it("拒絕非同步 callback", () => {
expect(() => withTransaction(t.db, async () => undefined)).toThrow(/同步/);
});
it("以 BEGIN IMMEDIATE 開始:尚未寫入前就已持有寫入鎖", () => {
const other = new Database(t.file);
other.pragma("busy_timeout = 0");
try {
withTransaction(t.db, () => {
// 交易內還沒有任何寫入;DEFERRED 交易此時不持有鎖,IMMEDIATE 則已鎖住。
expect(() => other.prepare("INSERT INTO _meta VALUES ('x', 'v', 'now')").run()).toThrow(
/locked|busy/i,
);
});
// 交易結束後鎖釋放,另一條連線可以寫入。
other.prepare("INSERT INTO _meta VALUES ('x', 'v', 'now')").run();
} finally {
other.close();
}
});
});
+23
View File
@@ -0,0 +1,23 @@
import type { Db } from "./client";
export type Tx = Parameters<Parameters<Db["transaction"]>[0]>[0];
/**
* 以 `BEGIN IMMEDIATE` 執行一段寫入交易:callback 正常結束即 commit,丟出例外即 rollback。
*
* better-sqlite3 的交易是同步的,callback 必須是同步函式;需要的資料請在交易前先準備好。
* IMMEDIATE 會在交易開始時就取得寫入鎖,避免「先讀後寫」的交易在提交時才發現衝突
* (月結提交、比例分配、最終核定都依賴這點)。
*/
export function withTransaction<T>(db: Db, fn: (tx: Tx) => T): T {
return db.transaction(
(tx) => {
const result = fn(tx);
if (result instanceof Promise) {
throw new TypeError("withTransaction 的 callback 必須是同步函式");
}
return result;
},
{ behavior: "immediate" },
);
}
+35
View File
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vitest";
import { EnvError, parseEnv } from "./env";
const secret = "x".repeat(32);
describe("parseEnv", () => {
it("只給 SESSION_SECRET 時其餘套用預設值", () => {
expect(parseEnv({ SESSION_SECRET: secret })).toEqual({
DATABASE_PATH: "./data/app.db",
ATTACHMENTS_DIR: "./data/attachments",
SESSION_SECRET: secret,
TZ_APP: "Asia/Taipei",
BACKUP_DIR: "./backups",
BACKUP_KEEP: 14,
});
});
it("缺少 SESSION_SECRET 時以明確訊息失敗", () => {
expect(() => parseEnv({})).toThrow(EnvError);
expect(() => parseEnv({})).toThrow(/SESSION_SECRET 未設定/);
});
it("SESSION_SECRET 為空字串視同未設定", () => {
expect(() => parseEnv({ SESSION_SECRET: "" })).toThrow(/SESSION_SECRET 未設定/);
});
it("SESSION_SECRET 太短時失敗", () => {
expect(() => parseEnv({ SESSION_SECRET: "short" })).toThrow(/至少需要 32 個字元/);
});
it("BACKUP_KEEP 必須是正整數", () => {
expect(parseEnv({ SESSION_SECRET: secret, BACKUP_KEEP: "7" }).BACKUP_KEEP).toBe(7);
expect(() => parseEnv({ SESSION_SECRET: secret, BACKUP_KEEP: "0" })).toThrow(EnvError);
});
});
+39
View File
@@ -0,0 +1,39 @@
import { z } from "zod";
// 伺服器端環境變數。Next.js 會自動載入 .env;CLI 腳本由 scripts/load-env.ts 以相同規則載入。
const envSchema = z.object({
DATABASE_PATH: z.string().min(1).default("./data/app.db"),
ATTACHMENTS_DIR: z.string().min(1).default("./data/attachments"),
SESSION_SECRET: z
.string({ error: "SESSION_SECRET 未設定(請複製 .env.example 為 .env 並填入)" })
.min(32, "SESSION_SECRET 至少需要 32 個字元"),
TZ_APP: z.string().min(1).default("Asia/Taipei"),
BACKUP_DIR: z.string().min(1).default("./backups"),
BACKUP_KEEP: z.coerce.number().int().positive().default(14),
});
export type Env = z.infer<typeof envSchema>;
export class EnvError extends Error {
constructor(message: string) {
super(message);
this.name = "EnvError";
}
}
export function parseEnv(source: Record<string, string | undefined>): Env {
// 空字串視為未設定,避免 `SESSION_SECRET=` 這類空值通過驗證。
const cleaned = Object.fromEntries(Object.entries(source).filter(([, value]) => value !== ""));
const result = envSchema.safeParse(cleaned);
if (!result.success) {
throw new EnvError(`環境變數設定錯誤:\n${z.prettifyError(result.error)}`);
}
return result.data;
}
let cached: Env | undefined;
export function getEnv(): Env {
cached ??= parseEnv(process.env);
return cached;
}
+30
View File
@@ -0,0 +1,30 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
describe("runStartupChecks", () => {
let dir: string;
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), "ai-sss-startup-"));
vi.resetModules();
});
afterEach(() => {
vi.unstubAllEnvs();
fs.rmSync(dir, { recursive: true, force: true });
});
it("建立不存在的附件目錄", async () => {
const attachments = path.join(dir, "nested", "attachments");
vi.stubEnv("ATTACHMENTS_DIR", attachments);
const { runStartupChecks } = await import("./startup");
runStartupChecks();
expect(fs.statSync(attachments).isDirectory()).toBe(true);
});
it("環境變數不合法時丟出錯誤", async () => {
vi.stubEnv("SESSION_SECRET", "");
const { runStartupChecks } = await import("./startup");
expect(() => runStartupChecks()).toThrow(/SESSION_SECRET 未設定/);
});
});
+12
View File
@@ -0,0 +1,12 @@
import fs from "node:fs";
import path from "node:path";
import { getEnv } from "@/server/env";
/**
* 伺服器啟動檢查:驗證環境變數、建立附件目錄。任何一項失敗都讓伺服器無法啟動,
* 而不是等到第一個請求才出錯。由 src/instrumentation.ts 在 Node.js runtime 呼叫。
*/
export function runStartupChecks(): void {
const env = getEnv();
fs.mkdirSync(path.resolve(env.ATTACHMENTS_DIR), { recursive: true });
}
+31
View File
@@ -0,0 +1,31 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { openDatabase, type DatabaseHandle } from "@/server/db/client";
import { runMigrations } from "@/server/db/migrate";
export interface TestDatabase extends DatabaseHandle {
/** 暫存資料庫檔的路徑(需要第二條連線時使用)。 */
file: string;
/** 關閉連線並刪除暫存檔。 */
cleanup: () => void;
}
/**
* 建立一個已跑完所有 migration 的暫存 SQLite 資料庫,供整合測試使用。
* 用實體暫存檔而非 :memory:,才能涵蓋 WAL 等與正式環境相同的檔案行為。
*/
export function createTestDatabase(): TestDatabase {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ai-sss-test-"));
const file = path.join(dir, "test.db");
const handle = openDatabase(file);
runMigrations(handle.db);
return {
...handle,
file,
cleanup: () => {
handle.sqlite.close();
fs.rmSync(dir, { recursive: true, force: true });
},
};
}
+3
View File
@@ -0,0 +1,3 @@
# tests/e2e
Playwright 端到端測試。執行:`npm run test:e2e`;單一檔案:`npx playwright test tests/e2e/<file>.spec.ts`。
+7
View File
@@ -0,0 +1,7 @@
import { expect, test } from "@playwright/test";
test("首頁可以開啟並顯示系統名稱", async ({ page }) => {
await page.goto("/");
await expect(page).toHaveTitle("AI 補助申請系統");
await expect(page.getByRole("heading", { level: 1 })).toHaveText("AI 補助申請系統");
});
+34
View File
@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from "vitest/config";
export default defineConfig({
resolve: { tsconfigPaths: true },
test: {
environment: "node",
include: ["src/**/*.test.{ts,tsx}", "scripts/**/*.test.ts"],
// 測試不讀 .env;需要的環境變數在這裡給固定值。
env: {
SESSION_SECRET: "test-session-secret-0123456789abcdef",
TZ_APP: "Asia/Taipei",
},
},
});