diff --git a/.agents/skills/verify-web/SKILL.md b/.agents/skills/verify-web/SKILL.md new file mode 100644 index 0000000..faadfa5 --- /dev/null +++ b/.agents/skills/verify-web/SKILL.md @@ -0,0 +1,61 @@ +--- +name: verify-web +description: Verify Void Starter in a real browser when reproducing a UI bug, checking a changed user journey, or capturing E2E evidence. Covers articles, Chat and attachments, with an executable local smoke suite. +--- + +# Verify web + +Use this project-local entry point from any agent. Commands run at the repository root. Read [features/README.md](features/README.md) and select every entry point affected by the change before driving the app. + +## Launch + +Requires macOS or Linux, Node 24+ and the workspace's pnpm version. Install workspace dependencies with `pnpm install --frozen-lockfile` if missing. Install Playwright's headless Chromium once per machine. On Linux CI, use `pnpm exec playwright install --with-deps --only-shell chromium` to include system libraries. + +```sh +pnpm exec playwright install --only-shell chromium +pnpm e2e +``` + +The runner copies the current app and packages into a temporary workspace, excluding local env files, connection records and persisted data. It shares installed dependencies but gives Vite its own cache directory. It applies local migrations, forces local Cloudflare bindings and starts the dev server on an available loopback port with `--strictPort`. Empty D1 is the seed for smoke. Readiness requires both the article and an empty Chat loader to render successfully. + +Each invocation owns its workspace, port and evidence directory. Concurrent agents can run separately without sharing D1 or R2. Do not install dependencies while a run is active. The smoke suite never submits a turn or calls Workers AI. + +The script launches its own headless Chromium with an isolated browser context. It works from a terminal or CI without an agent-specific browser service. Manual journeys in the feature map can use any available browser tool with equivalent controls and evidence capture. + +## Doctor + +The runner prints `Ready` only after checking the owned server and usable routes. To diagnose that instance while it is running, use its printed URL. + +```sh +pnpm e2e --doctor http://127.0.0.1:5173 +``` + +Replace the port with the actual run's port. This read-only check requires HTTP 200 and recognizable rendered content at `/` and a fresh `/c/`. It checks local app and database readiness, not AI credentials or build identity. For identity, use the runner's `result.json`, `server.log` and owned PID. Never attach to an unexplained existing server just because the port answers. + +## Drive + +`scripts/e2e-browser.js` drives actual links and the composer through Playwright. It checks literal headings, URLs and Send state. `pnpm e2e` runs every automated journey in the feature map. A smoke pass covers only those journeys. + +For a changed feature beyond smoke, use its map's selectors and expected state. Connected journeys require a dedicated checkout and local database prepared with `pnpm dev`, plus the account and gateway setup in `docs/deployment.md`. Record the exact environment and AI usage. A missing precondition is blocked coverage, not a passing test. Preserve the mapped journey when reporting the blocker. + +## Evidence + +Every invocation prints `.verification/run-/`. It contains `server.log`, `browser.log`, `result.json`, `journey.json` and numbered DOM snapshots. The journey records action names, timestamps and outcomes. A failed action remains `started` and gets error evidence when the browser is still accessible. Exit 0 requires setup, every smoke assertion and workspace cleanup to succeed. A four-minute watchdog bounds the run. + +Use `pnpm e2e --screenshots` to require a PNG after every step. Screenshot failure then fails the run. Default DOM evidence proves interaction results, not visual correctness. + +Capture the action and the resulting state. For persisted Chat or attachment changes, reload and verify saved turns or download bytes as well as the screen. Use real user controls. Keep mocks at an existing external boundary and label mocked coverage explicitly. The shipped smoke uses no mocks. Include the evidence path, covered feature names, pass/fail/block status and remaining gaps in the handoff. Read the screenshot when claiming visual correctness. + +## Cleanup + +The runner terminates only process groups it started and removes its temporary workspace on success or failure. Evidence remains under `.verification/`, outside that workspace. SIGINT and SIGTERM trigger cleanup. An uncatchable kill can leave resources behind. Identify them from the run's recorded paths and PID before removing anything. Never kill by executable name or reset the developer's database. + +The driver closes its browser on success and failure. Inspect retained logs, snapshots and requested screenshots after a failure. Verify the evidence files still exist after cleanup. + +## Helpers and maintenance + +- `node scripts/e2e.js --help` lists supported commands. `e2e.js` owns launch, doctor and server cleanup. `e2e-browser.js` runs the browser journeys in a child Node process. +- `pnpm verify` remains the repository's full code gate. Browser E2E is an explicit additional check because Chromium must be installed first. +- Update the relevant feature map and executable journey when routes, labels or behavior change. Keep new automated checks in the existing driver until another independently runnable suite is needed. + +Adapted from Cursor's [create-verification-skill](https://github.com/cursor/plugins/blob/main/pstack/skills/create-verification-skill/SKILL.md). Its `/maintain-verification-skill` is an optional upstream workflow, not a command installed in this repository. diff --git a/.agents/skills/verify-web/features/README.md b/.agents/skills/verify-web/features/README.md new file mode 100644 index 0000000..213d870 --- /dev/null +++ b/.agents/skills/verify-web/features/README.md @@ -0,0 +1,10 @@ +# Feature map + +| Feature | Coverage | Read when | +| :------------------------------ | :--------------------------------------------------------------------------------- | :----------------------------------------------------------------- | +| [Articles](articles.md) | Automated navigation and language smoke. TOC, footer and mobile checks are manual. | Changing blog content, routes or navigation. | +| [Composer](composer.md) | Automated empty Chat and draft checks. Model selection is manual. | Changing Chat launch, composer or model picker. | +| [Answers and sessions](chat.md) | Requires connected AI. Not executed by smoke. | Changing streaming, persistence, retry, stop or visitor ownership. | +| [Attachments](attachments.md) | Requires connected AI and local R2. Not executed by smoke. | Changing file selection, upload, preview or download. | + +Select all affected entry points. Record unexecuted cases as gaps. Each feature file defines the expected user-visible result, including side effects where applicable. diff --git a/.agents/skills/verify-web/features/articles.md b/.agents/skills/verify-web/features/articles.md new file mode 100644 index 0000000..3c8dfbe --- /dev/null +++ b/.agents/skills/verify-web/features/articles.md @@ -0,0 +1,19 @@ +# Articles + +## Sub-features + +Overview and tooling articles, English and Chinese URLs, header navigation, language switching, footer links and a responsive table of contents. + +## How to get to it (user POV) + +Start at `/`. Header article links and the footer's Read next link switch articles. The language control keeps the current article. Direct links include `/zh/cloud`, `/en/harness` and `/zh/harness`. + +## Driving it with a browser + +Run `pnpm e2e` for the automated path. It clicks `a[aria-label="Switch to Chinese"]`, `nav[aria-label="Articles"] a[href="/zh/harness"]` and `a[aria-label="Switch to English"]`. Literal H1 assertions prove translated content. Reloading `/en/harness` proves a direct request renders the article. + +For navigation changes, also exercise the footer link and return to Overview from the header. For TOC changes, use a desktop viewport and click a visible heading entry. Observe the destination heading and active entry. On mobile, open On this page or 目录 and repeat. Capture before and after screenshots for scroll or layout claims. + +## Gotchas + +Desktop and mobile TOCs both exist in the DOM. Use the visible entry from a fresh snapshot. Smoke runs a dev server and does not prove prerendered production assets or responsive layout. Changes to prerendering also require `pnpm build` and inspection of `apps/web/dist/client`. diff --git a/.agents/skills/verify-web/features/attachments.md b/.agents/skills/verify-web/features/attachments.md new file mode 100644 index 0000000..a09c3a4 --- /dev/null +++ b/.agents/skills/verify-web/features/attachments.md @@ -0,0 +1,23 @@ +# Attachments + +## Sub-features + +Selecting and removing a file, submitting it with a turn, loading its saved attachment and downloading the stored bytes. + +## How to get to it (user POV) + +Open a new Chat and use Attach files in the composer. An attached chip can be removed before sending. Saved attachments appear beside their user turn. + +## Driving it with a browser + +Use the connected environment from [Answers and sessions](chat.md). Create a small UTF-8 text fixture with a unique marker in the evidence directory and record its SHA-256. + +1. Click `button[aria-label="Attach files"]` and select the fixture through the file chooser. With Playwright, arm `page.waitForEvent("filechooser")` before clicking, then call the chooser's `setFiles()` with the fixture's absolute path. Other browser tools may use their equivalent file-upload control. +2. Verify the filename chip. Remove it through the visible remove control and verify it disappears. Select it again. +3. Type a request to quote the marker and submit. Verify the filename on the saved user turn and a completed answer containing the marker. +4. Reload the Chat and verify the attachment remains. Read the rendered attachment link from a snapshot. Download that URL using the same Visitor session. With Playwright, `page.request.get(url)` shares the context's cookies. Require HTTP 200 and save the response body as bytes. Compare the downloaded bytes and SHA-256 with the fixture. +5. For image preview changes, repeat selection and reload with a small image fixture. Capture the visible preview as well as byte equality. + +## Gotchas + +The chip alone proves only local selection. Successful download after reload proves D1 metadata and R2 bytes are accessible to the Visitor. The route uses `/api/chats//files/`; obtain ids from the actual saved link. Missing AI setup blocks the submit path rather than reducing the check to a chip screenshot. File-size and type validation belong to `apps/web/src/lib/chat.ts`; inspect its current limits before testing rejection boundaries. diff --git a/.agents/skills/verify-web/features/chat.md b/.agents/skills/verify-web/features/chat.md new file mode 100644 index 0000000..8516d3d --- /dev/null +++ b/.agents/skills/verify-web/features/chat.md @@ -0,0 +1,25 @@ +# Answers and sessions + +## Sub-features + +Streaming answers and reasoning, stopping, regenerating, reloading saved turns, session switching and visitor ownership. + +## How to get to it (user POV) + +Open Playground or New chat. Type a turn and use Send message or Enter. Previous Chats appear in the sidebar, or under Chats on narrow screens. + +## Driving it with a browser + +Use a dedicated connected development checkout following `docs/deployment.md`. Run `pnpm dev` there and record its URL and PID. This journey calls Workers AI and persists local D1 data. The automated smoke's temporary instance forces local bindings and cannot prove it. + +1. Fill the composer with a unique marker and a short question. Click `button[aria-label="Send message"]`. Capture the user turn and in-progress Thinking or Stop state. +2. Wait for a nonempty answer and `button[aria-label="Copy answer"]`. An error toast is a failure, even if the user turn remains visible. +3. Reload the same `/c/`. Verify the exact submitted turn and completed answer remain. This proves persistence through the public page loader. +4. Open New chat and select the prior Chat from the visible Chats navigation. Verify the same turns return. +5. For retry changes, click `button[aria-label="Regenerate"]`. Verify a completed replacement answer and reload to check persistence. +6. For stop changes, send a long-output request and click `button[aria-label="Stop"]` while streaming. Verify the composer is usable again and record what survives reload. +7. For visitor ownership changes, open that URL in a separately isolated browser context. Verify the original turns and session list are inaccessible. Another tab in the same profile is the same Visitor. + +## Gotchas + +A connected Cloudflare account, an existing AI Gateway and model access are required. Missing setup, quota exhaustion or unavailable models block this journey and must be reported. Reasoning is model-dependent. Record the selected model when checking it. Treat failures without automatic resubmission to avoid duplicate paid requests. Preserve screenshots and logs before stopping the owned server. Local test records can remain in the dedicated checkout; deleting data requires separate authorization. diff --git a/.agents/skills/verify-web/features/composer.md b/.agents/skills/verify-web/features/composer.md new file mode 100644 index 0000000..0bd5459 --- /dev/null +++ b/.agents/skills/verify-web/features/composer.md @@ -0,0 +1,19 @@ +# Composer + +## Sub-features + +Starting a fresh Chat, editing a draft, enabling Send and choosing a model. + +## How to get to it (user POV) + +Use Playground in the site header, New chat in the Chat sidebar, or navigate to `/chat`. Each entry creates a new `/c/` URL. A Chat is persisted only on its first submitted turn. + +## Driving it with a browser + +Smoke clicks `header a[href="/chat"]` and waits for `textarea[placeholder="Ask anything, or drop in a file."]`. It verifies the UUID URL and disabled `button[aria-label="Send message"]`, types `Verification draft`, checks Send becomes enabled, then clears the textarea and checks Send becomes disabled. + +For launch changes, repeat through New chat and direct `/chat`, verifying different UUIDs and empty threads. For model picker changes, click `button[aria-label^="Model: "]`, choose a visible `menuitemradio` from the snapshot and verify the trigger displays that model. Submitting with that model belongs to the connected Chat journey. + +## Gotchas + +The composer becoming usable proves the Chat loader can read migrated D1. It does not prove a saved Chat or an AI answer. Desktop and mobile New chat links coexist. Choose the visible entry. diff --git a/.agents/skills/void b/.agents/skills/void new file mode 120000 index 0000000..12b531e --- /dev/null +++ b/.agents/skills/void @@ -0,0 +1 @@ +../../apps/web/node_modules/void/skills/void \ No newline at end of file diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..3ff9ad5 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +# Keep the workflow's actions on current majors. npm dependencies are updated by hand. +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: monthly + groups: + actions: + patterns: ["*"] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8cd9a85..5668637 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,54 +5,68 @@ on: branches: [main] push: branches: [main] + workflow_dispatch: concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true +permissions: + contents: read + jobs: + # The full gate (AGENTS.md › Verification). verify: runs-on: ubuntu-latest + timeout-minutes: 15 + + steps: + - uses: actions/checkout@v7 + + - uses: pnpm/action-setup@v6 + + - uses: actions/setup-node@v7 + with: + node-version: 24 + cache: pnpm - services: - postgres: - image: postgres:17-alpine - env: - POSTGRES_DB: sweet_kit - POSTGRES_PASSWORD: sweet - POSTGRES_USER: sweet - ports: - - 5432:5432 - options: >- - --health-cmd "pg_isready -U sweet -d sweet_kit" - --health-interval 2s - --health-timeout 5s - --health-retries 10 - - env: - DATABASE_URL: postgresql://sweet:sweet@localhost:5432/sweet_kit - BETTER_AUTH_SECRET: ci-test-secret-at-least-32-characters-long - BETTER_AUTH_URL: http://localhost:43111 - WEB_URL: http://localhost:43110 - SERVER_URL: http://localhost:43111 - NEXT_PUBLIC_SERVER_URL: http://localhost:43111 - LOG_LEVEL: silent - LOG_PRETTY: "false" - OTEL_METRICS_EXPORTER: none - OTEL_LOGS_EXPORTER: none + - run: pnpm install --frozen-lockfile + + - run: pnpm verify + + # Browser smoke journeys against a local copy of the app. No AI requests, no Cloudflare account. + e2e: + runs-on: ubuntu-latest + timeout-minutes: 15 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - - uses: pnpm/action-setup@v4 + - uses: pnpm/action-setup@v6 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@v7 with: node-version: 24 cache: pnpm - run: pnpm install --frozen-lockfile - - run: pnpm db:migrate + - id: playwright + run: echo "version=$(pnpm exec playwright --version | cut -d' ' -f2)" >> "$GITHUB_OUTPUT" - - run: pnpm verify + - uses: actions/cache@v6 + with: + path: ~/.cache/ms-playwright + key: playwright-${{ runner.os }}-${{ steps.playwright.outputs.version }} + + - run: pnpm exec playwright install --with-deps --only-shell chromium + + - run: pnpm e2e --screenshots + + # result.json, server.log, browser.log and one snapshot per step. + - if: failure() + uses: actions/upload-artifact@v7 + with: + name: e2e-evidence + path: .verification/ + retention-days: 7 diff --git a/.gitignore b/.gitignore index 8f5158f..38457c5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,42 +1,30 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - # Dependencies node_modules -.pnp -.pnp.js # Local env files .env -.env.local -.env.development.local -.env.test.local -.env.production.local +.env.* +!.env.example -# Testing +# Build and tool output +dist coverage - -# Turbo +.verification .turbo - -# Vercel -.vercel - -# Build Outputs -.next/ -out/ -build -dist -*.jsonl - +.tanstack +.void +.wrangler +.void-wrangler.jsonc +*.tsbuildinfo # Lefthook local overrides lefthook-local.yml -# Debug -npm-debug.log* - # Misc .DS_Store *.pem +npm-debug.log* -examples \ No newline at end of file +# Void records your Cloudflare account and resources here. The template must not ship one; +# in your own app, delete this line and commit the file. +apps/web/void.lock.json diff --git a/.markdownlint-cli2.jsonc b/.markdownlint-cli2.jsonc new file mode 100644 index 0000000..5fec307 --- /dev/null +++ b/.markdownlint-cli2.jsonc @@ -0,0 +1,20 @@ +{ + "$schema": "https://raw.githubusercontent.com/DavidAnson/markdownlint-cli2/main/schema/markdownlint-cli2-config-schema.json", + // Markdown gates: Oxfmt (`vp fmt`, see vite.config.ts › fmt) owns the shape of a + // document — list bullets, list indent, blank lines around blocks, table padding, + // thematic breaks, trailing whitespace. markdownlint only adds the structural rules + // Oxfmt has no opinion on, such as fence languages, heading structure and links. + // Keep it that way: a rule that overlaps Oxfmt's output causes churn between the two. + "gitignore": true, + "globs": ["**/*.md"], + // .agents/skills links to skills shipped inside dependencies; they are not ours to lint. + "ignores": [".agents/**"], + "config": { + // Prose stays unwrapped. These docs are CJK paragraphs and wide tables; Oxfmt + // preserves the author's line breaks, so a length limit would only force manual + // re-wrapping with no reader benefit. + "MD013": false, + // A repeated heading is worth flagging inside one section, not document-wide. + "MD024": { "siblings_only": true }, + }, +} diff --git a/.oxlintrc.json b/.oxlintrc.json deleted file mode 100644 index f6cacb3..0000000 --- a/.oxlintrc.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "$schema": "./node_modules/oxlint/configuration_schema.json", - "jsPlugins": ["@shadcn/lint"], - "settings": { - "shadcn": { - "note": "外观归属与变体落点见 AGENTS.md › 架构约定;设计规则按 DESIGN.md 路由。", - "componentImports": ["^@workspace/ui/components"] - } - }, - "rules": { - "shadcn/no-restyle": [ - "error", - { - "allow": ["layout"] - } - ], - "shadcn/no-raw-colors": "error", - "shadcn/no-unknown-classes": "error", - "shadcn/require-static-classes": "error", - "shadcn/no-inline-styles": "error", - "shadcn/no-arbitrary-values": [ - "error", - { - "allow": ["layout"] - } - ] - }, - "ignorePatterns": ["packages/ui/src/components/**"] -} diff --git a/AGENTS.md b/AGENTS.md index 9cbbc58..9c3e7e0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,62 +1,59 @@ -# Sweet Kit +# Void Starter -Sweet Kit 是 Turborepo + pnpm workspace 组织的全栈 TypeScript 开发套件。 +Void Starter is a full-stack TypeScript starter in a Turborepo + pnpm workspace. It deploys one Cloudflare Worker with [Void](https://github.com/voidzero-dev/void) and TanStack Start. -## 资料落点 +## Where things go -按内容路由:长期架构取舍 → `docs/adr/`;外部资料调研 → `docs/research/`;未定型的计划 → `docs/future/`;系统与使用知识 → `docs/`;强制工程约束 → `rules/`;Local Loop、构建、database seed 与 Agent 自定义工具 → `scripts/`。新增或修改 `rules/` 下的规则前先读 `rules/README.md`。 +Route content by kind: system and usage knowledge → `docs/`; plans not decided yet → `docs/future/`; engineering constraints → `rules/`; repo tooling → `scripts/`. Read `rules/README.md` before adding or changing a rule. -## 术语共识 +## Vocabulary -- 讨论需求、设计方案或进行代码命名前,先读 [CONTEXT.md](CONTEXT.md),沿用其中的规范术语。 -- 讨论中新增术语、明确歧义或修正含义后,及时更新 `CONTEXT.md`;此项维护属于持续授权,纯讨论也适用,用户明确要求不改文件时除外。 -- 仅记录用户已确认或现有文档与代码可核实的项目特定含义。发现用法与词表冲突且影响当前判断时,先指出差异并澄清,再更新定义;未确认的推测不写入词表。 -- 每个条目用一至两句说明含义与必要边界;有别名时标明,有易混用词时用 `_Avoid_` 列出。`CONTEXT.md` 只保存当前有效的术语定义,方案、实现细节与讨论记录按资料落点归档。 +- Read [CONTEXT.md](CONTEXT.md) before discussing requirements, designing or naming code, and use its terms. +- When a discussion adds a term, settles an ambiguity or corrects a meaning, update `CONTEXT.md` right away. This is standing permission, even in a pure discussion, unless the user says not to touch files. +- Record only meanings the user confirmed or that the docs and code show. When usage conflicts with the glossary and it matters for the decision at hand, point out the difference and settle it before updating. Never write a guess into the glossary. +- One or two sentences per entry, covering the meaning and its boundary. Note aliases, and list easily confused words under _Avoid_. `CONTEXT.md` holds current definitions only; designs, implementation notes and discussion go where the routing above says. -## 架构约定 +## Architecture -- `apps/*` 拥有应用入口、composition root 和应用专属业务模块;`packages/*` 只承载已被多个应用或进程共同使用的能力与契约,不以潜在复用性作为拆包依据。跨 package 只走公开 exports,不导入内部文件。 -- `packages/ui` 拥有组件**自身的外观**:高度、padding、圆角、颜色与字体由变体(`variant` / `size`)决定;调用方只用布局类(`margin`、宽度、flex/grid 位置)与 props 控制。 -- 新形态按复用面落点:多个应用共同需要的进组件变体(一次显式解冻),单一应用的方言进 recipe(`packages/ui/src/recipes`)或应用内组件。 -- `packages/ui` 与 `globals.css` 的更改必须 **HITL(Human-in-the-Loop,人工在环确认)**,避免不知不觉修改元组件或污染全局: - - `packages/ui/src/components/**` 是上游 shadcn/ui 实现的元组件,**字节冻结(F1)**:基线见 `packages/ui/frozen.manifest.json`,`pnpm ui:freeze` 已检入 `rules:check`。基线是「上次被显式接受的状态」,不等于上游最新——上游是否已变由升级时的 `shadcn diff` 回答。改动经 `pnpm ui:freeze:update` 显式接受并单独提交,说明是上游升级还是记录在案的解冻。 - - `src/styles/globals.css` 的主题与 token 是本地设计决策,不在冻结范围;但因涉及全站通用语义与基础样式,同样禁止 Agent 静默修改,必须 Proposal First 经人工显式确认。 -- 自行实现前先查现有依赖的文档、类型定义与扩展能力,优先维护活跃、经过生产验证的成熟库。 -- 测试不得自行启动或依赖开发机的 container runtime;需要外部资源的集成验证由显式 integration environment 提供。 -- 目录名承担分组与语义前缀;目录已表达领域或职责时,文件名只表达目录内的具体职责:`canvas-commands/generation-handlers.ts`,而非 `canvas-commands/canvas-command-generation-handlers.ts`。 +- `apps/*` own entry points, composition and app-specific business code. `packages/*` hold only capabilities that several apps or processes already share, never what might be reused someday. Cross package boundaries only through public `exports`. +- `packages/ui` owns each component's **own appearance**: height, padding, radius, color and type come from its variants (`variant` / `size`). Call sites control only layout (margin, width, flex or grid placement) and props. +- A new look goes where its reuse is: a variant in the component when several apps need it (an explicit unfreeze), otherwise a recipe (`packages/ui/src/recipes`) or an app component. +- Changes to `packages/ui` and `globals.css` need **HITL** (a human confirms first), so nobody quietly alters a base component or the global styles: + - `packages/ui/src/components/**` is upstream shadcn/ui code (Base UI, `base-nova`) with Retry's component deltas applied (`DESIGN.md` › Components). It is **byte-frozen (F1)**: the baseline is `packages/ui/frozen.manifest.json`, checked by `pnpm ui:freeze` inside `rules:check`. The baseline is the last accepted state, not upstream's latest; `shadcn diff` answers that at upgrade time. Accept a change with `pnpm ui:freeze:update` in its own commit that says whether it is an upstream upgrade or a recorded unfreeze. + - `packages/ui/src/styles/globals.css` and `retry.css` hold the theme and tokens. They implement Retry, specified in `DESIGN.md`. Agents never change them silently: propose first and wait for explicit approval. +- Before building something, check the docs, types and extension points of the dependencies already here. Prefer maintained, production-proven libraries. +- Tests never start or depend on a container runtime. Integration checks that need outside resources run in an explicit integration environment. +- Directory names carry the grouping. Inside a directory that already names the domain, a file name says only its own job: `server/notes.functions.ts`, not `server/server-notes-functions.ts`. +- `*.server.ts` modules are server-only. Server functions (`createServerFn`) live in `*.functions.ts` and may import them; components and `src/lib` never do. -当前 `apps/*` 与 `packages/*` 的职责与依赖方向见 [docs/architecture.md](docs/architecture.md)。 +[docs/architecture.md](docs/architecture.md) describes each app and package, the request path and the decisions behind the stack. -改动以下范围前先读对应 ADR: +## Rules by trigger -| 范围 | ADR | -| :--- | :--- | -| 应用 runtime 环境变量 | [0001 架构与 runtime 边界](docs/adr/0001-architecture-runtime-boundaries.md) | -| tracing、日志关联与 Agent trace 查询 | [0002 OpenTelemetry 可观测性](docs/adr/0002-opentelemetry-observability.md)、[0006 trace 契约与暴露出口](docs/adr/0006-trace-context-contract.md) | -| 运行时装配与应用业务模块的归属 | [0007 运行时装配与应用业务模块的归属](docs/adr/0007-runtime-assembly-and-app-ownership.md) | -| API 版本前缀、REST 严格度、不兼容的 API 变更 | [0005 HTTP API 形态](docs/adr/0005-http-api-shape.md) | +| Trigger | Read first | +| :-------------------------------------------------- | :--------------------------------------------------------------- | +| Void: bindings, CLI, config, deploy | `.agents/skills/void/SKILL.md` (ships with the installed `void`) | +| Using Zod or changing validation | `rules/zod-v4/README.md` | +| Frontend UI: screens, layout, motion, components | [DESIGN.md](DESIGN.md) | +| `/api/*` routes and error responses | [docs/api.md](docs/api.md) | +| Env vars, secrets, deploy, AI Gateway | [docs/deployment.md](docs/deployment.md) | +| What a request actually did: logs, traces, `cf-ray` | [docs/observability.md](docs/observability.md) | -## 专项规则 +## Tech choices -| 触发 | 先读 | -| :--- | :--- | -| 使用 Zod、改动数据校验 | `rules/zod-v4/README.md` | -| 前端 UI:界面、布局、动效、组件 | [DESIGN.md](DESIGN.md) | -| 品牌色、品牌字体、品牌页视觉方向 | [docs/branding.md](docs/branding.md) | -| HTTP 错误响应、`ErrorCode`、OpenAPI 描述 | `rules/api-contract.md`(RFC 9457,不变量由 `packages/request` 测试守护) | -| 排查运行期行为:某次请求实际做了什么、需要 trace 关联 | [docs/observability.md](docs/observability.md) | +One option per concern. Don't add alternatives. -## 技术选型 +- Framework: TanStack Start on Void (framework mode). Bindings come from `void/db`, `void/storage`, `void/ai`. +- Database: D1 through Drizzle. Auth, when the app adds accounts: Better Auth (today a cookie visitor owns each chat). +- Client state: zustand. Toasts: sonner. +- Motion: motion (`motion/react`) or Tailwind CSS transitions. +- Forms: react-hook-form + zod + @hookform/resolvers, rendered with shadcn/ui `Field` and `Controller` (Base UI has no `Form` component). +- Icons: lucide-react (installed in `packages/ui`). +- Dates: dayjs. -各项保持单一方案,不引入替代库: +## Verification -- 客户端状态 zustand;通知 sonner。 -- 动画 motion(`motion/react`)或 Tailwind CSS 过渡。 -- 表单 react-hook-form + zod + @hookform/resolvers,配 shadcn/ui Form 组件。 -- 图标 lucide-react(shadcn/ui 附带,安装在 `packages/ui`)。 -- 日期 dayjs。 - -## 验证门禁 - -- 完成代码修改后以 `pnpm verify` 为唯一全量验证入口(串联 Biome、rules:check、typecheck、test、build、knip);日常命令见根目录 `package.json`。 -- Git hooks 由根目录 `lefthook.yml` 管理,`pnpm install` 时自动安装:pre-commit 对 staged 文件跑 Biome(并重新入 stage)加 `rules:check`,pre-push 跑 typecheck 与 test。hook 只是 `pnpm verify` 的前置子集,不替代 CI;绕开用 `git commit --no-verify` 或 `LEFTHOOK=0`。 +- For browser E2E, reproducing user journeys, or capturing runtime evidence, read [.agents/skills/verify-web/SKILL.md](.agents/skills/verify-web/SKILL.md). `pnpm e2e` runs the local browser smoke suite. The feature map distinguishes automated checks from journeys that need connected AI. +- After a code change, `pnpm verify` is the one full gate. It runs `format:check`, `md:check`, `lint`, `rules:check`, `typecheck`, `test`, `build` and `knip`. Day-to-day commands are in the root `package.json`. +- Oxfmt shapes Markdown; markdownlint adds only structural rules (fence languages, heading levels, links), configured in `.markdownlint-cli2.jsonc`. Keep them from overlapping, or the two commands keep rewriting the same file. +- Git hooks come from the root `lefthook.yml` and install with `pnpm install`. Pre-commit runs Oxfmt and markdownlint on staged files (and re-stages them) plus `rules:check`. Pre-push runs typecheck and test. Hooks are a subset of `pnpm verify` and don't replace CI. Skip them with `git commit --no-verify` or `LEFTHOOK=0`. diff --git a/CONTEXT.md b/CONTEXT.md index 208c4dc..c5a2eee 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -1,3 +1,16 @@ -# Sweet Kit +# Void Starter -本词表记录项目术语,作为需求讨论、方案设计与代码命名的共同语言。 \ No newline at end of file +Project vocabulary. Use these terms in requirements, designs and code names. + +- **Chat.** One conversation, stored in D1 and addressed by a random UUID in its URL (`/c/`). It belongs to the visitor who sent its first turn. _Alias_: session, in the sidebar. +- **Visitor.** One browser, identified by a random UUID in the HttpOnly `visitor` cookie. It stands in for an account: no sign-in, no fingerprinting, and clearing cookies starts a new visitor. _Avoid_: user, account. +- **Turn.** One message in a chat, from the user or the assistant. _Avoid_: "message" in UI copy; the table is still `message`. +- **Answer.** The assistant turn streamed from Workers AI through AI Gateway and saved when the stream finishes. _Avoid_: "completion". +- **Reasoning.** The thinking a reasoning model streams before its answer (`reasoning_content`), saved beside the answer and shown in the thinking block. +- **Attachment.** A file on a user turn. The bytes live in R2 under `chats//`; the text the model reads is saved in D1. +- **Problem.** An RFC 9457 error body from an `/api/*` route. `code` is the field clients branch on. See `docs/api.md`. +- **Connect.** Linking a clone to a Cloudflare account with `pnpm connect`. Workers AI in dev and every deploy need it. +- **Motif.** The registry the chat UI was copied from (`motif.sweetretry.com`). The copies under `apps/web/src/components` are now local code: maintained, trimmed and linted here, with no sync back to Motif. +- **Retry.** The design language this starter ships: `DESIGN.md` is its spec, `packages/ui/src/styles/retry.css` its tokens. +- **Retry deltas.** The class changes that adapt upstream shadcn/ui components to Retry (`DESIGN.md` › Components). +- **F1 freeze.** The byte-level baseline for `packages/ui/src/components`, checked by `pnpm ui:freeze`. A change to it is either an **upstream upgrade** or a **recorded unfreeze**. diff --git a/DESIGN.md b/DESIGN.md index e943e9f..2de0d33 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1,15 +1,134 @@ -# 设计规则入口 +--- +version: alpha +name: Retry +description: Zimin's design language on Tailwind CSS v4 and shadcn/ui, for the site, notes, slides and tools. +omitted: + - section: colors + reason: In globals.css as oklch (:root light, .dark dark, the default). + - section: typography + reason: Tailwind v4's scale; Retry's tracking-tight on 3xl and up and the 5xl/6xl line heights are in globals.css @theme. + - section: rounded + reason: shadcn's default --radius (0.625rem) in globals.css; rounded-* derive from it. + - section: spacing + reason: Tailwind defaults, used as listed under Layout. + - section: motion + reason: Motion (motion/react) with MotionConfig defaults; rules under Interaction patterns. + - section: components + reason: shadcn/ui with the deltas listed under Components. +--- -编写、修改或评审 UI 时,按本次改动**实际触及的内容**查规则,不按需求名称判断。同一个需求常同时命中多行,命中即读。 +# Retry -| 改动中出现 | 规则 | -| :--- | :--- | -| 新增容器、分组结构、注意力与权重(6:3:1)、字段过多、折叠与浮层选型 | [信息层级与收纳](rules/web-design/hierarchy.md) | -| 留白、间距、内边距、内容最大宽度、12 栏栅格、轴线对齐 | [布局与间距](rules/web-design/layout.md) | -| 异步加载防跳动、Card 网格等高沉底、空结果、表单报错推挤、文本溢出穿孔 | [尺寸稳定](rules/web-design/stability.md) | -| 颜色、表面高度(E0–E3)、暗色主题、圆角同心、Z 轴层叠与 Portal 穿透 | [色彩、表面与层叠](rules/web-design/surface.md) | -| 字号、字体族、字重、排版字阶比重、数字金额与计数对齐(`tabular-nums`) | [排版与字体](rules/web-design/typography.md) | -| 过渡动效、按压反馈(scale-95)、Toast、字段级 inline 报错、提交等待态 | [交互反馈与动效](rules/web-design/interaction.md) | +Retry is Zimin's design language for the site, notes, slides and small tools: quiet surfaces, careful type, and one color that only shows up when it means something. It grows on Tailwind CSS v4 and shadcn/ui: their scales unchanged, Retry's values in `globals.css`, and a short list of shadcn deltas. -规则适用于应用与新增业务组件;组件外观归属和上游冻结边界遵循 [AGENTS.md](AGENTS.md)。`packages/ui` 与 `globals.css` 的改动必须 **HITL(人工在环确认)**,避免不知不觉修改元组件或污染全局。 -静态门禁与规则维护原则见 [rules/README.md](rules/README.md);UI 检查配置在 `.oxlintrc.json`。 +## Overview + +- **Restrained**: no gradients, glows, decorative glass or shadows to fake polish. +- **Precise**: exact alignment, numbers and wording. No filler, no fake stats. +- **Warm**: not corporate. First person, room to breathe. + +Made for peers and collaborators who judge the thinking, not the packaging. References: Linear's clarity, Apple's quiet finish, and quiet craft: small details with a job, unnoticed at first glance and rewarding on the second. Never: terminal or hacker styling, neo-brutalism, the SaaS template (blue-purple gradient, centered hero, three icon cards), Dribbble showpieces, an untouched shadcn default. + +When rules compete: facts and constraints › the host project's framework › task clarity › Retry's look › polish. + +### Setup + +Use `globals.css` as the global stylesheet (it replaces shadcn's). Put `class="dark"` on ``. Load Inter with the `opsz` axis. Animate with Motion (`motion/react`), with the app wrapped once in ``, so components set no `transition` unless they need a different duration. + +### Voice + +- English, sentence case, short sentences, conclusion first. +- First person on the site and in notes; product UI speaks as the product ("Your projects"). +- Buttons are verbs ("Save draft"), never "Submit" or "OK". Confirmations in past tense, no "successfully". +- Errors say what happened, then what to do. Empty states name the space and offer one verb. +- No emoji, no exclamation marks, never narrate the design on the page. + +## Colors + +shadcn names, so every color is a utility (`bg-card`, `text-muted-foreground`). Retry adds `surface-1…3`, `subtle-foreground`, `success`, `warning`, `*-hover` and `*-soft`. Values are `oklch()`; dark (`.dark`) is the default, light (`:root`) a full theme. + +- **Depth is lightness.** `bg-background` › `bg-surface-1` (= card, muted) › `bg-surface-2` (= secondary, accent) › `bg-surface-3`. New neutrals stay on hue 286 and step L only. +- **Text**: `text-foreground` to read, `text-muted-foreground` to support, `text-subtle-foreground` only for placeholders, timestamps and column headers on background, surface-1 or sidebar. Never set text hierarchy with opacity (a transient state such as stale data while reloading may fade). +- **Emerald (`primary`) is scarce**: one primary button per view, links, checked controls, focus, success. Under 5% of the screen; never decoration, never "good" numbers. +- **Status** (`success`, `warning`, `destructive`) always comes with a word; notices use the `*-soft` fills. +- `accent` is shadcn's neutral hover, not a brand color. Charts: `chart-1` for the series that matters, `chart-5` for the rest. + +## Typography + +Inter (`font-sans`) with optical sizing, which already tightens large text. Sizes are Tailwind's; the theme gives `text-3xl` and up `tracking-tight`, and `text-5xl`/`text-6xl` room between lines, so don't add `tracking-*` or `leading-*` to headings. `font-mono` only for code and data. + +| Class | Role | +| ----------------------------------- | ------------------------------------------ | +| `text-6xl` / `text-5xl` | Cover / site hero, once per page | +| `text-4xl` · `text-3xl` · `text-xl` | h1 · h2 · h3 (`font-semibold`) | +| `text-2xl` | Slide subheads, stat numbers | +| `text-lg` | Article body, `max-w-2xl` | +| `text-base` | Site copy | +| `text-sm` | Interface text; labels `font-medium` | +| `text-xs` | Metadata, timestamps, column headers, help | + +Weights 400, 500, 600 only. `tabular-nums` on numbers that line up; `text-balance` on headings. + +## Layout + +Tailwind spacing, in these steps: `gap-1` icon to label · `gap-2` buttons, label to field · `p-4` cards · `p-6` tool panels · `gap-8` blocks · `py-12` tool sections · `py-16` site sections. Group with space and tone, never a border around a group. Left-aligned by default. Articles `max-w-2xl`, sidebar `w-54`, controls `h-8` / `h-9` / `h-10`. + +## Elevation & Depth + +No shadows: `globals.css` empties every `shadow-*`, including those inside shadcn components. Lines appear only between table rows and around floating layers (`border`). Popover, menu and toast use `bg-popover`; Dialog and Sheet use `bg-background` over their overlay; Tooltip inverts (`bg-foreground text-background`). The sidebar sits beside the page, not on it, so in dark it is a step darker than `background` on purpose. At most two floating layers at once. + +## Shapes + +shadcn's default `--radius` (0.625rem) is the base. `rounded-md` (8px) for controls, popovers, menus and tooltips; `rounded-sm` (6px) for items inside them; `rounded-lg` (10px) for dialogs; `rounded-xl` (14px) for cards; `rounded-2xl` (18px) for emphasised containers and slides. Nested corners follow inner = outer − padding, rounded down to a step. `rounded-full` only for switches, avatars and dots. Change `--radius`, never single classes. + +## Components + +Theme utilities only: no arbitrary values (`bg-[#…]`, `text-[13px]`). A new value goes into the tokens first. Components are shadcn/ui with these deltas, applied once in the component files: + +- **Card**: no border; `bg-card` alone. +- **Input, Textarea, Select**: filled `bg-muted` with the `border-input` edge; focus `border-ring` plus a soft ring. +- **Button**: `default` once per view, then `secondary`, `ghost`, `destructive` (`bg-destructive-soft text-destructive`), `link`. No `outline`. +- **Badge**: not for metadata. Status is a 6px dot plus a word. +- **Tabs**: active is `bg-surface-2`; no underline, no emerald. +- **Popover, Dropdown, Toast**: `bg-popover`, `border`, `rounded-md`. **Dialog, Sheet**: `bg-background`, `border`, Dialog `rounded-lg`. **Tooltip**: `bg-foreground text-background`, `rounded-md`. +- **Table**: `border-t` rows, no outer border or zebra; numbers and their headers `text-right tabular-nums`. +- **Sidebar**: separated by tone, no line; active `bg-sidebar-accent`. +- **Switch, Checkbox, Radio**: off `bg-surface-2` / `bg-surface-3`, on `bg-primary`. **Skeleton**: `bg-surface-2`. + +## Interaction patterns + +- **States**: design rest, hover, focus and disabled. Focus is a 2px `ring` outline, 2px offset. Disabled is `bg-surface-1 text-subtle-foreground`, never `opacity-50`. +- **Undoable, rarely failing actions** (create, rename, move, toggle): update instantly, show a quiet dot until confirmed, revert with a toast on failure. +- **Money, other people, or irreversible**: spinner inside the button, no optimistic update. +- **First loads**: Skeleton in the shape of the content; nothing under 300ms; never a full-page spinner. +- **Hover-only actions** need a second route: shortcut, context menu or swipe. Primary actions are always visible. +- **Direction colors** (up green, down red) are off unless a surface's core information is direction; then always with + or −, declared in that surface's file. +- **Quiet craft**: a detail earns its place only if it has a job, stays invisible at first glance, lives where the person touches, and falls back to no motion under reduced motion. Adopted: numbers that change roll only the digits that changed (tabular, no layout shift); text links draw their underline in from the left on hover and out to the right. +- **Blur** only on chrome that content scrolls under: `bg-background/85 backdrop-blur`. +- **Motion**: CSS transitions for hover, press and color: name the property and nothing else (`transition-colors`, `transition-transform`); the theme already defaults every transition to 150ms on Retry's curve. Add `duration-200` only for movement. Motion for anything that appears, leaves or changes place: `AnimatePresence` for enter and exit, `layout` / `layoutId` for reflow and shared elements (a thumbnail opening to full view). Same curve everywhere (`ease-out` = `[0.2, 0, 0, 1]`); a spring only as `{ type: "spring", bounce: 0 }`. Animate only `transform` and `opacity`. Motion answers a state change: no decorative entrances, no bounce. + +## Surfaces + +| Surface | Job | Density | +| -------- | ---------------------------------------------------------------- | ------- | +| Site | Show the work; left-aligned `text-5xl` claim, one primary button | Low | +| Articles | Reading; `text-lg` in `max-w-2xl` | Low | +| Slides | One claim per slide; emerald on one phrase at most | Low | +| Tools | Get it done; sidebar, `text-sm`, `h-10` rows | Medium | + +A surface that needs other parameters gets `design/.md`: what it inherits, what it overrides, why. + +## Do's and Don'ts + +- Centered hero with three icon cards → a real claim or the work, left-aligned. +- Boxes around groups, cards in cards → space, tone, type size. +- Gradients, glows, glass cards, grid backdrops, shadows → flat tone steps. +- Untouched shadcn components → the deltas above. +- Badges on metadata → `text-xs text-muted-foreground`. +- Decorative icons on headings → icons only on actions. +- Mono headlines, heavy borders, all caps → mono stays in code. +- Squeezed tables, mixed alignment → full width, numbers right. +- Green for good numbers → `text-muted-foreground`. +- Arbitrary values → theme utilities. + +Restraint isn't emptiness: tension comes from type scale contrast, space, exact alignment, and the one emerald moment. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8d949cc --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 SweetRetry + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 969e31b..6315a21 100644 --- a/README.md +++ b/README.md @@ -1,64 +1,90 @@ -# Sweet Kit +# Void Starter -基于 TypeScript 的全栈开发套件,使用 Turborepo 按架构切面组织 Web 与 server。 +English | [简体中文](README.zh.md) -## 技术基线 +A full-stack TypeScript starter that deploys to your own Cloudflare account with [Void](https://github.com/voidzero-dev/void). One Worker serves a prerendered blog and a chat app. Chat messages live in D1, files in R2, and answers stream from Workers AI through AI Gateway. -- Web:Next.js App Router、React 19、Tailwind CSS v4、shadcn/ui -- Request:ky、TanStack Query -- Server:Hono、OpenAPI 3.1、Scalar -- AI:Vercel AI SDK(provider 与模型名由部署环境提供,见 `apps/server/src/ai.ts`) -- Auth:Better Auth、Bearer session -- Database:PostgreSQL、Drizzle ORM、node-postgres -- Logging:Pino、hono-pino、request ID、敏感字段 redaction -- Observability:OpenTelemetry、trace/log correlation、本地 JSONL 投影 -- Env:各应用独立拥有的 Zod 环境变量配置 -- Test:Vitest +> Void Starter is an independent project. It is not an official Void or Cloudflare template. -## 仓库知识与自动化 +## What you get -| 目录 | 关注点 | 内容 | -| --- | --- | --- | -| [`docs/`](./docs/) | What | 系统说明、开发指南、API、业务与运维知识 | -| [`docs/adr/`](./docs/adr/) | Why | 长期架构决策、背景、取舍与风险 | -| [`docs/research/`](./docs/research/) | Source | 外部资料调研存档:升级指南、上游设计与规范参考 | -| [`docs/future/`](./docs/future/) | Later | 尚未决定或时机未到的计划:候选方案与触发条件 | -| [`rules/`](./rules/) | How | 编码规范、架构边界和 Agent 必须遵守的约束 | -| [`scripts/`](./scripts/) | Tools | Local Loop、构建、database seed 与 Agent 自定义工具 | +- **App.** TanStack Start (React 19, SSR, server functions, file routes) running in Void's framework mode. +- **Data.** D1 through Drizzle, with migrations Void applies on deploy. +- **Files.** R2 through `void/storage`, read for the model with `ai.toMarkdown()`. +- **AI.** Workers AI models on Cloudflare's free daily allowance, so no provider key. Every call goes through AI Gateway, and reasoning models stream their thinking. +- **Blog.** `/` and every post are prerendered to static HTML at build time, in English and Chinese (`/en/*`, `/zh/*`). +- **UI.** Tailwind CSS v4, shadcn/ui on Base UI, the Retry design language ([DESIGN.md](DESIGN.md)), and the chat block from [Motif](https://motif.sweetretry.com). +- **Errors.** RFC 9457 problem+json on every `/api/*` route ([docs/api.md](docs/api.md)). +- **Gates.** Vite+ (format, lint, test), typecheck, knip and project rules behind one command, `pnpm verify`. `pnpm e2e` drives the app in headless Chromium. -根目录 `AGENTS.md` 是 Agent 规则入口;专项规则由它引用 `rules/` 中的文档。系统文档见 [architecture](docs/architecture.md) 与 [observability](docs/observability.md)。 +There are no accounts. A cookie gives each browser a random visitor id, and the sidebar lists that visitor's chats; other browsers get a 404. Add auth before you put anything private in it. -## 开始 +## Requirements -```bash +- Node.js 24 or newer and pnpm 12 (`corepack enable` picks the version pinned in `package.json`). +- A Cloudflare account, only to deploy or to get AI answers in dev. The free plan is enough to try it. + +## Quick start + +```sh +pnpm dlx giget gh:SweetRetry/void-starter my-app +cd my-app +git init pnpm install -pnpm infra:up -pnpm db:migrate pnpm dev ``` -默认地址: +`pnpm dev` applies migrations to local D1 and serves with local D1 and R2. -- Web: -- Hono: -- Scalar: -- OpenAPI: +Workers AI has no local simulator. To get answers in dev, connect the clone to Cloudflare once, create an AI Gateway named `void-starter` in the Cloudflare dashboard (AI › AI Gateway), and restart `pnpm dev`: -`POST /api/assistant/reply`(需登录)在部署提供 `OPENAI_API_KEY` 后返回模型输出,未配置时返回 `503 SERVICE_UNAVAILABLE`;provider 调用参与 trace 关联。 +```sh +pnpm connect +``` -`pnpm dev` 同时启动 Web 与 Hono server;PostgreSQL 由 `compose.yaml` 提供。 +## Deploy + +```sh +pnpm connect # once per clone: Cloudflare login +# once per account: create the AI Gateway "void-starter" in the dashboard +pnpm run deploy +``` -各应用的本地配置存放在对应目录的 `.env.local`,生产环境变量参考相邻的 `.env.example`;生产环境必须提供高熵 `BETTER_AUTH_SECRET`。 +`void deploy` builds the app, provisions D1, R2 and the AI binding, applies migrations and publishes the Worker. -日志与 tracing 的使用说明(trace 契约、本地 trace 查看、OTLP 导出、redaction)见 [docs/observability.md](docs/observability.md)。 +The public `workers.dev` URL starts closed (`workers_dev: false` in `apps/web/void.config.ts`), so it answers with Cloudflare error 1042. With no accounts, an open URL lets anyone spend your Workers AI allowance. Set a gateway rate limit, then set `workers_dev: true` and deploy again to open it. See [docs/deployment.md](docs/deployment.md) for AI Gateway, models, limits and rollback. -## 检查 +## Layout -```bash -pnpm test -pnpm verify +```text +apps/web/ TanStack Start app deployed by Void +packages/ui/ shadcn/ui components (byte-frozen) and Retry tokens +packages/typescript-config/ +docs/ architecture, API, deployment, observability +rules/ engineering rules with their gates +scripts/ UI freeze, guardrails and the e2e runner ``` -`pnpm install` 会通过 [lefthook](lefthook.yml) 安装 Git hooks:pre-commit 对 staged 文件跑 Biome 并跑机械门禁,pre-push 跑 typecheck 与 test。hook 是本地快速反馈,`pnpm verify` 与 CI 仍是全量门禁。 +## Commands + +| Command | What it does | +| :----------------- | :------------------------------------------------------------- | +| `pnpm dev` | Apply local migrations and start the dev server | +| `pnpm run deploy` | Build, provision and publish to Cloudflare | +| `pnpm db:generate` | Generate a D1 migration from `apps/web/db/schema.ts` | +| `pnpm verify` | Format, Markdown, lint, rules, typecheck, test, build and knip | +| `pnpm e2e` | Browser smoke suite in headless Chromium | + +`pnpm verify` is the full gate, and CI runs it alongside `pnpm e2e`. `pnpm e2e` runs the browser smoke suite against a disposable copy of the app; install Chromium once with `pnpm exec playwright install --only-shell chromium`. Git hooks from [lefthook.yml](lefthook.yml) run a fast subset on commit and push. + +## Docs + +- [docs/architecture.md](docs/architecture.md) explains the stack and why each choice was made. +- [docs/api.md](docs/api.md) defines the error contract and every problem type. +- [docs/deployment.md](docs/deployment.md) covers AI Gateway, models, usage limits and rollback. +- [docs/observability.md](docs/observability.md) covers logs and traces, locally and in production. +- [AGENTS.md](AGENTS.md) is the entry point for coding agents. + +## License -当前自动化测试覆盖 `packages/request` 的错误契约与 HTTP 客户端、`packages/tracing` 的 trace 契约不变量、`packages/logger` 的日志脱敏、`packages/observability` 的 span 投影、`apps/web` 的 analytics,以及 `apps/server` 的 HTTP 错误出口(需要 PostgreSQL,未提供 `DATABASE_URL` 时跳过)。其余成功响应分支与真实登录流程尚未建立。CI 会启动 PostgreSQL 并执行 `pnpm db:migrate`,随后运行 `pnpm verify`;其完整步骤见根目录 `package.json`。 +[MIT](LICENSE) diff --git a/README.zh.md b/README.zh.md new file mode 100644 index 0000000..522d3e4 --- /dev/null +++ b/README.zh.md @@ -0,0 +1,92 @@ +# Void Starter + +[English](README.md) | 简体中文 + +一个全栈 TypeScript 模板,用 [Void](https://github.com/voidzero-dev/void) 部署到你自己的 Cloudflare 账号。一个 Worker 同时提供预渲染的博客和一个聊天应用。聊天消息存在 D1,文件存在 R2,回答由 Workers AI 经 AI Gateway 流式返回。 + +> Void Starter 是独立项目,不是 Void 或 Cloudflare 的官方模板。 + +## 包含什么 + +- **应用。** TanStack Start(React 19、SSR、server functions、文件路由),运行在 Void 的框架模式下。 +- **数据。** 通过 Drizzle 使用 D1,迁移由 Void 在部署时执行。 +- **文件。** 通过 `void/storage` 使用 R2,用 `ai.toMarkdown()` 把文件转成模型可读的内容。 +- **AI。** 使用 Workers AI 模型,消耗 Cloudflare 每日免费额度,不需要任何供应商密钥。每次调用都经过 AI Gateway,推理模型会流式输出思考过程。 +- **博客。** `/` 和每篇文章都在构建时预渲染成静态 HTML,有中英两个版本(`/en/*`、`/zh/*`)。 +- **界面。** Tailwind CSS v4、基于 Base UI 的 shadcn/ui、Retry 设计语言([DESIGN.md](DESIGN.md)),以及来自 [Motif](https://motif.sweetretry.com) 的聊天组件。 +- **错误。** 每个 `/api/*` 路由都返回 RFC 9457 problem+json([docs/api.md](docs/api.md))。 +- **检查。** Vite+(格式化、lint、测试)、类型检查、knip 和项目规则,统一由 `pnpm verify` 执行。`pnpm e2e` 用无头 Chromium 操作应用。 + +没有账号系统。每个浏览器通过 cookie 拿到一个随机访客 id,侧边栏只列出这个访客的聊天,其他浏览器访问会得到 404。放任何私密内容之前,请先加上认证。 + +## 环境要求 + +- Node.js 24 或更高版本,以及 pnpm 12(执行 `corepack enable` 会使用 `package.json` 里锁定的版本)。 +- 一个 Cloudflare 账号。只有部署或在开发时获取 AI 回答才需要,免费套餐就够试用。 + +## 快速开始 + +```sh +pnpm dlx giget gh:SweetRetry/void-starter my-app +cd my-app +git init +pnpm install +pnpm dev +``` + +`pnpm dev` 会把迁移应用到本地 D1,并在 启动服务,使用本地的 D1 和 R2。 + +Workers AI 没有本地模拟器。要在开发时拿到回答,需要把这份代码连接到 Cloudflare 一次,在 Cloudflare 控制台(AI › AI Gateway)创建一个名为 `void-starter` 的 AI Gateway,然后重启 `pnpm dev`。 + +```sh +pnpm connect +``` + +## 部署 + +```sh +pnpm connect # 每份代码一次:登录 Cloudflare +# 每个账号一次:在控制台创建名为 "void-starter" 的 AI Gateway +pnpm run deploy +``` + +`void deploy` 会构建应用,创建 D1、R2 和 AI binding,执行迁移并发布 Worker。 + +公开的 `workers.dev` 地址默认是关闭的(`apps/web/void.config.ts` 里的 `workers_dev: false`),访问会返回 Cloudflare 错误 1042。因为没有账号系统,地址一旦公开,任何人都能消耗你的 Workers AI 额度。先给 gateway 设置限流,再把 `workers_dev` 改成 `true` 并重新部署,就能打开它。AI Gateway、模型、用量限制和回滚见 [docs/deployment.md](docs/deployment.md)。 + +## 目录结构 + +```text +apps/web/ 由 Void 部署的 TanStack Start 应用 +packages/ui/ shadcn/ui 组件(字节冻结)和 Retry 设计 token +packages/typescript-config/ +docs/ 架构、API、部署、可观测性 +rules/ 工程规则及其检查 +scripts/ UI 冻结检查、护栏和 e2e 运行器 +``` + +## 常用命令 + +| 命令 | 作用 | +| :----------------- | :------------------------------------------------------ | +| `pnpm dev` | 应用本地迁移并启动开发服务器 | +| `pnpm run deploy` | 构建、创建资源并发布到 Cloudflare | +| `pnpm db:generate` | 根据 `apps/web/db/schema.ts` 生成 D1 迁移 | +| `pnpm verify` | 格式、Markdown、lint、规则、类型检查、测试、构建和 knip | +| `pnpm e2e` | 用无头 Chromium 跑浏览器冒烟测试 | + +`pnpm verify` 是完整的检查,CI 会同时运行它和 `pnpm e2e`。`pnpm e2e` 在一份临时的应用副本上跑浏览器冒烟测试。第一次使用前,先用 `pnpm exec playwright install --only-shell chromium` 安装 Chromium。[lefthook.yml](lefthook.yml) 里的 Git hooks 会在 commit 和 push 时跑其中一部分快速检查。 + +## 文档 + +- [docs/architecture.md](docs/architecture.md) 介绍技术栈和每个选择的理由。 +- [docs/api.md](docs/api.md) 定义错误约定和所有 problem 类型。 +- [docs/deployment.md](docs/deployment.md) 介绍 AI Gateway、模型、用量限制和回滚。 +- [docs/observability.md](docs/observability.md) 介绍本地和生产环境的日志与 trace。 +- [AGENTS.md](AGENTS.md) 是编码 agent 的入口。 + +文档目前只有英文版。 + +## 许可证 + +[MIT](LICENSE) diff --git a/apps/server/.env.example b/apps/server/.env.example deleted file mode 100644 index e666aea..0000000 --- a/apps/server/.env.example +++ /dev/null @@ -1,35 +0,0 @@ -# ─── Runtime ───────────────────────────────────────────── -NODE_ENV=development - -# ─── URLs ──────────────────────────────────────────────── -SERVER_URL=http://localhost:43111 -WEB_URL=http://localhost:43110 - -# ─── Auth ──────────────────────────────────────────────── -BETTER_AUTH_SECRET=replace-with-at-least-32-random-characters -# GOOGLE_CLIENT_ID= -# GOOGLE_CLIENT_SECRET= - -# ─── Database ──────────────────────────────────────────── -DATABASE_URL=postgresql://sweet:sweet@localhost:5432/sweet_kit - -# ─── Server ────────────────────────────────────────────── -PORT=43111 - -# 仅在服务确实部署在可信代理之后时设为 true:启用后才读取 x-forwarded-for -TRUST_PROXY=false - -# ─── AI provider ──────────────────────────────────────── -# 未设置时 /api/assistant/reply 返回 503 SERVICE_UNAVAILABLE -# OPENAI_API_KEY=sk-... -# OPENAI_MODEL=gpt-4o - -# ─── Logger ────────────────────────────────────────────── -LOG_LEVEL=info -LOG_PRETTY=false - -# ─── OpenTelemetry ─────────────────────────────────────── -OTEL_METRICS_EXPORTER=none -OTEL_LOGS_EXPORTER=none -# OTEL_TRACES_EXPORTER=otlp -# OTEL_EXPORTER_OTLP_ENDPOINT=https://collector.example.com diff --git a/apps/server/drizzle.config.ts b/apps/server/drizzle.config.ts deleted file mode 100644 index 16c12f1..0000000 --- a/apps/server/drizzle.config.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { config } from "dotenv" -import { defineConfig } from "drizzle-kit" -import { z } from "zod" - -// drizzle-kit 默认只加载 `.env`,而本仓库的本地配置在 `.env.local`(与 server / worker 运行期一致)。 -// dotenv 不覆盖已存在的变量,因此 CI 或显式传入的 DATABASE_URL 仍然生效。 -config({ path: process.env.DOTENV_CONFIG_PATH ?? ".env.local", quiet: true }) - -const databaseUrl = z.url().parse(process.env.DATABASE_URL) - -export default defineConfig({ - dialect: "postgresql", - schema: "./src/database/schema.ts", - out: "./drizzle", - dbCredentials: { - url: databaseUrl, - }, -}) diff --git a/apps/server/drizzle/0000_great_silver_centurion.sql b/apps/server/drizzle/0000_great_silver_centurion.sql deleted file mode 100644 index dbf2696..0000000 --- a/apps/server/drizzle/0000_great_silver_centurion.sql +++ /dev/null @@ -1,70 +0,0 @@ -CREATE TABLE "account" ( - "id" text PRIMARY KEY NOT NULL, - "issuer" text NOT NULL, - "account_id" text NOT NULL, - "provider_id" text NOT NULL, - "user_id" text NOT NULL, - "access_token" text, - "refresh_token" text, - "id_token" text, - "access_token_expires_at" timestamp, - "refresh_token_expires_at" timestamp, - "scope" text, - "password" text, - "created_at" timestamp DEFAULT now() NOT NULL, - "updated_at" timestamp NOT NULL -); ---> statement-breakpoint -CREATE TABLE "device_code" ( - "id" text PRIMARY KEY NOT NULL, - "device_code" text NOT NULL, - "user_code" text NOT NULL, - "user_id" text, - "expires_at" timestamp NOT NULL, - "status" text NOT NULL, - "last_polled_at" timestamp, - "polling_interval" integer, - "client_id" text, - "scope" text -); ---> statement-breakpoint -CREATE TABLE "session" ( - "id" text PRIMARY KEY NOT NULL, - "expires_at" timestamp NOT NULL, - "token" text NOT NULL, - "created_at" timestamp DEFAULT now() NOT NULL, - "updated_at" timestamp NOT NULL, - "ip_address" text, - "user_agent" text, - "user_id" text NOT NULL, - CONSTRAINT "session_token_unique" UNIQUE("token") -); ---> statement-breakpoint -CREATE TABLE "user" ( - "id" text PRIMARY KEY NOT NULL, - "name" text NOT NULL, - "email" text NOT NULL, - "email_verified" boolean DEFAULT false NOT NULL, - "image" text, - "created_at" timestamp DEFAULT now() NOT NULL, - "updated_at" timestamp DEFAULT now() NOT NULL, - CONSTRAINT "user_email_unique" UNIQUE("email") -); ---> statement-breakpoint -CREATE TABLE "verification" ( - "id" text PRIMARY KEY NOT NULL, - "identifier" text NOT NULL, - "value" text NOT NULL, - "expires_at" timestamp NOT NULL, - "created_at" timestamp DEFAULT now() NOT NULL, - "updated_at" timestamp DEFAULT now() NOT NULL -); ---> statement-breakpoint -ALTER TABLE "account" ADD CONSTRAINT "account_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "session" ADD CONSTRAINT "session_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -CREATE UNIQUE INDEX "account_issuer_accountId_uidx" ON "account" USING btree ("issuer","account_id");--> statement-breakpoint -CREATE INDEX "account_userId_idx" ON "account" USING btree ("user_id");--> statement-breakpoint -CREATE UNIQUE INDEX "deviceCode_deviceCode_uidx" ON "device_code" USING btree ("device_code");--> statement-breakpoint -CREATE UNIQUE INDEX "deviceCode_userCode_uidx" ON "device_code" USING btree ("user_code");--> statement-breakpoint -CREATE INDEX "session_userId_idx" ON "session" USING btree ("user_id");--> statement-breakpoint -CREATE INDEX "verification_identifier_idx" ON "verification" USING btree ("identifier"); diff --git a/apps/server/drizzle/0001_natural_puff_adder.sql b/apps/server/drizzle/0001_natural_puff_adder.sql deleted file mode 100644 index 22652da..0000000 --- a/apps/server/drizzle/0001_natural_puff_adder.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE "device_code" CASCADE; \ No newline at end of file diff --git a/apps/server/drizzle/meta/0000_snapshot.json b/apps/server/drizzle/meta/0000_snapshot.json deleted file mode 100644 index 3710b60..0000000 --- a/apps/server/drizzle/meta/0000_snapshot.json +++ /dev/null @@ -1,493 +0,0 @@ -{ - "id": "aaefce62-3064-4c0f-860a-04e1d3bffbae", - "prevId": "00000000-0000-0000-0000-000000000000", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.account": { - "name": "account", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "issuer": { - "name": "issuer", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "account_id": { - "name": "account_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider_id": { - "name": "provider_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "access_token": { - "name": "access_token", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "refresh_token": { - "name": "refresh_token", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "id_token": { - "name": "id_token", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "access_token_expires_at": { - "name": "access_token_expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": false - }, - "refresh_token_expires_at": { - "name": "refresh_token_expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": false - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "password": { - "name": "password", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - } - }, - "indexes": { - "account_issuer_accountId_uidx": { - "name": "account_issuer_accountId_uidx", - "columns": [ - { - "expression": "issuer", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "account_id", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - }, - "account_userId_idx": { - "name": "account_userId_idx", - "columns": [ - { - "expression": "user_id", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": false, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "foreignKeys": { - "account_user_id_user_id_fk": { - "name": "account_user_id_user_id_fk", - "tableFrom": "account", - "tableTo": "user", - "columnsFrom": ["user_id"], - "columnsTo": ["id"], - "onDelete": "cascade", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.device_code": { - "name": "device_code", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "device_code": { - "name": "device_code", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_code": { - "name": "user_code", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "last_polled_at": { - "name": "last_polled_at", - "type": "timestamp", - "primaryKey": false, - "notNull": false - }, - "polling_interval": { - "name": "polling_interval", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - } - }, - "indexes": { - "deviceCode_deviceCode_uidx": { - "name": "deviceCode_deviceCode_uidx", - "columns": [ - { - "expression": "device_code", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - }, - "deviceCode_userCode_uidx": { - "name": "deviceCode_userCode_uidx", - "columns": [ - { - "expression": "user_code", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.session": { - "name": "session", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "token": { - "name": "token", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "ip_address": { - "name": "ip_address", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "user_agent": { - "name": "user_agent", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "user_id": { - "name": "user_id", - "type": "text", - "primaryKey": false, - "notNull": true - } - }, - "indexes": { - "session_userId_idx": { - "name": "session_userId_idx", - "columns": [ - { - "expression": "user_id", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": false, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "foreignKeys": { - "session_user_id_user_id_fk": { - "name": "session_user_id_user_id_fk", - "tableFrom": "session", - "tableTo": "user", - "columnsFrom": ["user_id"], - "columnsTo": ["id"], - "onDelete": "cascade", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "session_token_unique": { - "name": "session_token_unique", - "nullsNotDistinct": false, - "columns": ["token"] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.user": { - "name": "user", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "email": { - "name": "email", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "email_verified": { - "name": "email_verified", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "image": { - "name": "image", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "user_email_unique": { - "name": "user_email_unique", - "nullsNotDistinct": false, - "columns": ["email"] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.verification": { - "name": "verification", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "identifier": { - "name": "identifier", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "value": { - "name": "value", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "verification_identifier_idx": { - "name": "verification_identifier_idx", - "columns": [ - { - "expression": "identifier", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": false, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": {}, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} diff --git a/apps/server/drizzle/meta/0001_snapshot.json b/apps/server/drizzle/meta/0001_snapshot.json deleted file mode 100644 index 1729178..0000000 --- a/apps/server/drizzle/meta/0001_snapshot.json +++ /dev/null @@ -1,389 +0,0 @@ -{ - "id": "340e166b-9398-4125-9db9-2b2977b07be1", - "prevId": "aaefce62-3064-4c0f-860a-04e1d3bffbae", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.account": { - "name": "account", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "issuer": { - "name": "issuer", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "account_id": { - "name": "account_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider_id": { - "name": "provider_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "access_token": { - "name": "access_token", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "refresh_token": { - "name": "refresh_token", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "id_token": { - "name": "id_token", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "access_token_expires_at": { - "name": "access_token_expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": false - }, - "refresh_token_expires_at": { - "name": "refresh_token_expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": false - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "password": { - "name": "password", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - } - }, - "indexes": { - "account_issuer_accountId_uidx": { - "name": "account_issuer_accountId_uidx", - "columns": [ - { - "expression": "issuer", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "account_id", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - }, - "account_userId_idx": { - "name": "account_userId_idx", - "columns": [ - { - "expression": "user_id", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": false, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "foreignKeys": { - "account_user_id_user_id_fk": { - "name": "account_user_id_user_id_fk", - "tableFrom": "account", - "tableTo": "user", - "columnsFrom": ["user_id"], - "columnsTo": ["id"], - "onDelete": "cascade", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.session": { - "name": "session", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "token": { - "name": "token", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "ip_address": { - "name": "ip_address", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "user_agent": { - "name": "user_agent", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "user_id": { - "name": "user_id", - "type": "text", - "primaryKey": false, - "notNull": true - } - }, - "indexes": { - "session_userId_idx": { - "name": "session_userId_idx", - "columns": [ - { - "expression": "user_id", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": false, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "foreignKeys": { - "session_user_id_user_id_fk": { - "name": "session_user_id_user_id_fk", - "tableFrom": "session", - "tableTo": "user", - "columnsFrom": ["user_id"], - "columnsTo": ["id"], - "onDelete": "cascade", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "session_token_unique": { - "name": "session_token_unique", - "nullsNotDistinct": false, - "columns": ["token"] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.user": { - "name": "user", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "email": { - "name": "email", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "email_verified": { - "name": "email_verified", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "image": { - "name": "image", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "user_email_unique": { - "name": "user_email_unique", - "nullsNotDistinct": false, - "columns": ["email"] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.verification": { - "name": "verification", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "identifier": { - "name": "identifier", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "value": { - "name": "value", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "verification_identifier_idx": { - "name": "verification_identifier_idx", - "columns": [ - { - "expression": "identifier", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": false, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": {}, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} diff --git a/apps/server/drizzle/meta/_journal.json b/apps/server/drizzle/meta/_journal.json deleted file mode 100644 index e6d0636..0000000 --- a/apps/server/drizzle/meta/_journal.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "version": "7", - "dialect": "postgresql", - "entries": [ - { - "idx": 0, - "version": "7", - "when": 1787326507047, - "tag": "0000_great_silver_centurion", - "breakpoints": true - }, - { - "idx": 1, - "version": "7", - "when": 1789876446629, - "tag": "0001_natural_puff_adder", - "breakpoints": true - } - ] -} diff --git a/apps/server/package.json b/apps/server/package.json deleted file mode 100644 index 826427c..0000000 --- a/apps/server/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "server", - "version": "0.0.0", - "type": "module", - "private": true, - "scripts": { - "build": "tsc -p tsconfig.json", - "dev": "NODE_OPTIONS=--conditions=development DOTENV_CONFIG_PATH=.env.local tsx watch src/index.ts", - "start": "DOTENV_CONFIG_PATH=.env.local node dist/index.js", - "auth:generate": "NODE_OPTIONS=--conditions=development DOTENV_CONFIG_PATH=.env.local auth generate --config src/auth-config.ts --output src/database/schema.ts --yes && pnpm exec biome check --write src/database/schema.ts", - "db:generate": "drizzle-kit generate --config drizzle.config.ts && pnpm exec biome format --write drizzle/meta/*.json", - "db:migrate": "drizzle-kit migrate --config drizzle.config.ts", - "lint": "biome check .", - "lint:fix": "biome check --write .", - "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json" - }, - "dependencies": { - "@ai-sdk/openai": "^4.0.51", - "@better-auth/drizzle-adapter": "^1.7.2", - "@hono/node-server": "^2.1.1", - "@hono/otel": "^1.1.2", - "@hono/zod-openapi": "^1.6.1", - "@opentelemetry/sdk-node": "^0.221.0", - "@opentelemetry/sdk-trace-base": "^2.10.0", - "@scalar/hono-api-reference": "^0.12.0", - "@workspace/logger": "workspace:*", - "@workspace/observability": "workspace:*", - "@workspace/request": "workspace:*", - "@workspace/tracing": "workspace:*", - "ai": "^7.0.84", - "better-auth": "^1.7.2", - "dotenv": "^17.4.2", - "drizzle-orm": "^0.45.2", - "hono": "^4.13.5", - "hono-pino": "^0.10.3", - "hono-rate-limiter": "^0.5.3", - "pg": "^8.23.0", - "zod": "^4.5.2" - }, - "devDependencies": { - "@types/node": "^26.4.0", - "@types/pg": "^8.23.1", - "@workspace/typescript-config": "workspace:*", - "auth": "^1.7.2", - "drizzle-kit": "^0.31.10", - "tsx": "^4.23.12", - "typescript": "^7.0.2", - "vitest": "^4.1.11" - } -} diff --git a/apps/server/src/ai.ts b/apps/server/src/ai.ts deleted file mode 100644 index f385e91..0000000 --- a/apps/server/src/ai.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { createOpenAI } from "@ai-sdk/openai" -import { generateText, type LanguageModel } from "ai" - -export interface AiProviderOptions { - apiKey: string - modelId: string -} - -/** - * AI provider 的装配入口。 - * - * 凭据与模型名由应用环境变量提供(见 `src/env.ts`),这里只把 provider 客户端 - * 收敛成 `generateText` 可用的 model;装配位置在 composition root(`src/index.ts`), - * 见 [ADR 0007](../../../docs/adr/0007-runtime-assembly-and-app-ownership.md)。 - */ -export function createAiModel(options: AiProviderOptions): LanguageModel { - return createOpenAI({ apiKey: options.apiKey })(options.modelId) -} - -/** - * 生成一次回复。 - * - * `telemetry` 打开后 provider 调用会产出 span,本地开发时进入 trace projection, - * 由 `data/traces.jsonl` 查看,见 [docs/observability.md](../../../docs/observability.md)。 - */ -export async function generateAssistantReply( - model: LanguageModel, - prompt: string -): Promise { - const { text } = await generateText({ - model, - prompt, - telemetry: { - functionId: "assistant.reply", - isEnabled: true, - }, - }) - - return text -} diff --git a/apps/server/src/auth-config.ts b/apps/server/src/auth-config.ts deleted file mode 100644 index c12c506..0000000 --- a/apps/server/src/auth-config.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createAuth } from "./auth.ts" -import { createDatabase } from "./database/client.ts" -import { serverEnv } from "./env.ts" - -/** - * Better Auth CLI 的配置入口(`pnpm --filter server auth:generate --config src/auth-config.ts`), - * 只为 schema 生成而存在,进程运行时由 `src/index.ts` 装配。 - */ -export const db = createDatabase(serverEnv.databaseUrl) - -export const auth = createAuth({ - baseURL: serverEnv.serverUrl, - database: db, - google: serverEnv.google, - secret: serverEnv.authSecret, - trustedOrigins: [serverEnv.webUrl], -}) diff --git a/apps/server/src/auth.ts b/apps/server/src/auth.ts deleted file mode 100644 index 667eb6b..0000000 --- a/apps/server/src/auth.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { drizzleAdapter } from "@better-auth/drizzle-adapter" -import { betterAuth } from "better-auth/minimal" -import { bearer } from "better-auth/plugins" - -import type { Database } from "./database/client.ts" -import * as schema from "./database/schema.ts" - -interface SocialProviderOptions { - clientId: string - clientSecret: string -} - -export interface AuthOptions { - baseURL: string - database: Database - google?: SocialProviderOptions - secret: string - trustedOrigins: string[] -} - -export function createAuth(options: AuthOptions) { - return betterAuth({ - appName: "Sweet Kit", - baseURL: options.baseURL, - database: drizzleAdapter(options.database, { - provider: "pg", - schema, - }), - emailAndPassword: { - enabled: true, - }, - secret: options.secret, - socialProviders: { - ...(options.google && { - google: { - clientId: options.google.clientId, - clientSecret: options.google.clientSecret, - }, - }), - }, - trustedOrigins: options.trustedOrigins, - plugins: [bearer()], - }) -} - -export type Auth = ReturnType diff --git a/apps/server/src/create-app.ts b/apps/server/src/create-app.ts deleted file mode 100644 index 89048cd..0000000 --- a/apps/server/src/create-app.ts +++ /dev/null @@ -1,361 +0,0 @@ -import { getConnInfo } from "@hono/node-server/conninfo" -import { httpInstrumentationMiddleware } from "@hono/otel" -import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi" -import { Scalar } from "@scalar/hono-api-reference" -import type { Logger } from "@workspace/logger" -import { - createProblemDetails, - ErrorCode, - getErrorStatus, - PROBLEM_MEDIA_TYPE, -} from "@workspace/request/contract" -import { - getActiveSpanContext, - TRACE_ID_PATTERN, - TRACE_PARENT_HEADER, - traceResponseHeaders, -} from "@workspace/tracing" -import type { Context } from "hono" -import { cors } from "hono/cors" -import { requestId } from "hono/request-id" -import { type Env as HonoPinoEnv, pinoLogger } from "hono-pino" -import { rateLimiter } from "hono-rate-limiter" - -import { type AiProviderOptions, createAiModel, generateAssistantReply } from "./ai.ts" -import type { Auth } from "./auth.ts" - -const RATE_LIMIT_WINDOW_MS = 60_000 -const RATE_LIMIT_MAX = 100 - -const HealthSchema = z - .object({ - status: z.literal("ok"), - service: z.literal("sweet-kit-server"), - }) - .openapi("Health") - -const UserSchema = z - .object({ - id: z.string(), - email: z.email(), - name: z.string(), - }) - .openapi("User") - -const AssistantRequestSchema = z - .object({ - prompt: z.string().min(1).max(2_000), - }) - .openapi("AssistantRequest") - -const AssistantReplySchema = z - .object({ - text: z.string(), - }) - .openapi("AssistantReply") - -const ProblemDetailsSchema = z - .object({ - type: z.string(), - title: z.string(), - status: z.number().int(), - detail: z.string(), - code: z.enum(ErrorCode), - traceId: z.string().regex(new RegExp(TRACE_ID_PATTERN)).optional(), - }) - .openapi("ProblemDetails") - -const problemContent = { [PROBLEM_MEDIA_TYPE]: { schema: ProblemDetailsSchema } } - -const validationErrorResponse = { - content: problemContent, - description: "Request validation failed", -} - -const unauthorizedResponse = { - content: problemContent, - description: "Authentication required", -} - -const tooManyRequestsResponse = { - content: problemContent, - description: "Rate limit exceeded, see Retry-After", -} - -const serviceUnavailableResponse = { - content: problemContent, - description: "Feature is not configured in this deployment", -} - -const internalErrorResponse = { - content: problemContent, - description: "Internal server error with trace correlation", -} - -function problemResponse(c: Context, code: C, detail: string) { - const status = getErrorStatus(code) - const body = createProblemDetails(code, detail, { traceId: getActiveSpanContext()?.traceId }) - - return c.json(body, status, { "Content-Type": PROBLEM_MEDIA_TYPE }) -} - -/** - * 校验失败的统一出口。 - * - * `@hono/zod-openapi` 在未提供 hook 时会把 ZodError 整体序列化进响应体, - * 这里改成 problem details:detail 只带出错位置与原因,不带内部结构。 - */ -function describeValidationFailure(result: { error: z.ZodError; target: string }): string { - const [issue] = result.error.issues - - if (!issue) { - return `${result.target} 未通过校验` - } - - const location = issue.path.length > 0 ? `${issue.path.join(".")} ` : "" - - return `${result.target} 校验失败:${location}${issue.message}` -} - -/** - * 限流使用的客户端标识。 - * - * `x-forwarded-for` 可被客户端伪造,因此只有部署在可信代理之后(`TRUST_PROXY=true`) - * 才读取它,且取最右侧一项——它由可信代理追加,客户端伪造的前缀覆盖不到。 - */ -function clientAddress(c: Context, trustProxy: boolean): string { - if (trustProxy) { - const forwarded = c.req - .header("x-forwarded-for") - ?.split(",") - .map((value) => value.trim()) - .filter(Boolean) - .at(-1) - - if (forwarded) { - return forwarded - } - } - - try { - return getConnInfo(c).remote.address ?? "unknown" - } catch { - return "unknown" - } -} - -const healthRoute = createRoute({ - method: "get", - path: "/api/health", - tags: ["System"], - summary: "Server health", - responses: { - 200: { - content: { "application/json": { schema: HealthSchema } }, - description: "Server health", - }, - 429: tooManyRequestsResponse, - 500: internalErrorResponse, - }, -}) - -const meRoute = createRoute({ - method: "get", - path: "/api/me", - tags: ["Account"], - summary: "Current authenticated user", - security: [{ bearerAuth: [] }], - responses: { - 200: { - content: { "application/json": { schema: UserSchema } }, - description: "Current authenticated user", - }, - 401: unauthorizedResponse, - 429: tooManyRequestsResponse, - 500: internalErrorResponse, - }, -}) - -const assistantRoute = createRoute({ - method: "post", - path: "/api/assistant/reply", - tags: ["Assistant"], - summary: "Generate a reply through the configured AI provider", - description: - "需要登录;上游凭据由部署环境提供(OPENAI_API_KEY)。未配置时返回 503,provider 调用会参与 trace 关联。", - security: [{ bearerAuth: [] }], - request: { - body: { - content: { "application/json": { schema: AssistantRequestSchema } }, - required: true, - }, - }, - responses: { - 200: { - content: { "application/json": { schema: AssistantReplySchema } }, - description: "Generated reply", - }, - 400: validationErrorResponse, - 401: unauthorizedResponse, - 429: tooManyRequestsResponse, - 500: internalErrorResponse, - 503: serviceUnavailableResponse, - }, -}) - -interface CreateServerAppOptions { - ai?: AiProviderOptions - auth: Auth - logger: Logger - trustProxy: boolean - webUrl: string -} - -export function createServerApp(options: CreateServerAppOptions) { - const app = new OpenAPIHono({ - defaultHook: (result, c) => { - if (result.success) return - - return problemResponse( - c, - ErrorCode.VALIDATION_ERROR, - describeValidationFailure({ error: result.error, target: result.target }) - ) - }, - }) - - const aiModel = options.ai ? createAiModel(options.ai) : undefined - - app.openAPIRegistry.registerComponent("securitySchemes", "bearerAuth", { - type: "http", - scheme: "bearer", - }) - - app.use( - "*", - httpInstrumentationMiddleware({ - serviceName: "sweet-kit-server", - serviceVersion: "0.0.1", - }) - ) - app.use("*", requestId()) - app.use( - "*", - pinoLogger({ - pino: options.logger, - http: { - onResBindings: (c) => ({ - res: { - status: c.res.status, - }, - ...(c.error ? { err: c.error } : {}), - }), - onResLevel: (c) => { - if (c.res.status >= 500) return "error" - if (c.res.status >= 400) return "warn" - return "info" - }, - }, - }) - ) - app.use("*", async (c, next) => { - await next() - for (const [name, value] of Object.entries(traceResponseHeaders())) c.header(name, value) - }) - - app.use( - "/api/*", - cors({ - origin: options.webUrl, - credentials: true, - exposeHeaders: ["x-request-id", TRACE_PARENT_HEADER], - }) - ) - - app.use( - "/api/*", - /** - * 默认 store 是进程内 MemoryStore:多实例部署时限流按实例计算, - * 需要跨实例一致时换成共享 store(如 Redis)。 - */ - rateLimiter({ - windowMs: RATE_LIMIT_WINDOW_MS, - limit: RATE_LIMIT_MAX, - keyGenerator: (c) => clientAddress(c, options.trustProxy), - handler: (c) => { - c.header("Retry-After", String(RATE_LIMIT_WINDOW_MS / 1_000)) - - return problemResponse(c, ErrorCode.TOO_MANY_REQUESTS, "请求过于频繁,请稍后重试") - }, - }) - ) - - app.all("/api/auth/*", (c) => options.auth.handler(c.req.raw)) - - app.openapi(healthRoute, (c) => c.json({ status: "ok", service: "sweet-kit-server" }, 200)) - - app.openapi(meRoute, async (c) => { - const session = await options.auth.api.getSession({ headers: c.req.raw.headers }) - - if (!session) { - return problemResponse(c, ErrorCode.UNAUTHORIZED, "Authentication required") - } - - return c.json( - { - id: session.user.id, - email: session.user.email, - name: session.user.name, - }, - 200 - ) - }) - - app.openapi(assistantRoute, async (c) => { - const session = await options.auth.api.getSession({ headers: c.req.raw.headers }) - - if (!session) { - return problemResponse(c, ErrorCode.UNAUTHORIZED, "Authentication required") - } - - if (!aiModel) { - return problemResponse( - c, - ErrorCode.SERVICE_UNAVAILABLE, - "此部署未配置 AI provider:需要 OPENAI_API_KEY" - ) - } - - const { prompt } = c.req.valid("json") - const text = await generateAssistantReply(aiModel, prompt) - - return c.json({ text }, 200) - }) - - app.doc31("/openapi.json", { - openapi: "3.1.0", - info: { - title: "Sweet Kit API", - version: "0.1.0", - }, - }) - - app.get( - "/docs", - Scalar({ - pageTitle: "Sweet Kit API", - url: "/openapi.json", - }) - ) - - app.notFound((c) => - problemResponse(c, ErrorCode.NOT_FOUND, `未找到 ${c.req.method} ${c.req.path}`) - ) - - app.onError((error, c) => { - c.get("logger").error({ err: error }, "request.failed") - return problemResponse(c, ErrorCode.INTERNAL_SERVER_ERROR, "Internal Server Error") - }) - - return app -} diff --git a/apps/server/src/database/client.ts b/apps/server/src/database/client.ts deleted file mode 100644 index 6699393..0000000 --- a/apps/server/src/database/client.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { drizzle } from "drizzle-orm/node-postgres" -import { Pool } from "pg" - -import * as schema from "./schema.ts" - -export function createDatabase(connectionString: string) { - const pool = new Pool({ connectionString }) - return drizzle(pool, { schema }) -} - -export type Database = ReturnType - -export async function closeDatabase(database: Database): Promise { - await database.$client.end() -} diff --git a/apps/server/src/database/schema.ts b/apps/server/src/database/schema.ts deleted file mode 100644 index fa26ecb..0000000 --- a/apps/server/src/database/schema.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { relations } from "drizzle-orm" -import { boolean, index, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core" - -export const user = pgTable("user", { - id: text("id").primaryKey(), - name: text("name").notNull(), - email: text("email").notNull().unique(), - emailVerified: boolean("email_verified").default(false).notNull(), - image: text("image"), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at") - .defaultNow() - .$onUpdate(() => /* @__PURE__ */ new Date()) - .notNull(), -}) - -export const session = pgTable( - "session", - { - id: text("id").primaryKey(), - expiresAt: timestamp("expires_at").notNull(), - token: text("token").notNull().unique(), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at") - .$onUpdate(() => /* @__PURE__ */ new Date()) - .notNull(), - ipAddress: text("ip_address"), - userAgent: text("user_agent"), - userId: text("user_id") - .notNull() - .references(() => user.id, { onDelete: "cascade" }), - }, - (table) => [index("session_userId_idx").on(table.userId)] -) - -export const account = pgTable( - "account", - { - id: text("id").primaryKey(), - issuer: text("issuer").notNull(), - accountId: text("account_id").notNull(), - providerId: text("provider_id").notNull(), - userId: text("user_id") - .notNull() - .references(() => user.id, { onDelete: "cascade" }), - accessToken: text("access_token"), - refreshToken: text("refresh_token"), - idToken: text("id_token"), - accessTokenExpiresAt: timestamp("access_token_expires_at"), - refreshTokenExpiresAt: timestamp("refresh_token_expires_at"), - scope: text("scope"), - password: text("password"), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at") - .$onUpdate(() => /* @__PURE__ */ new Date()) - .notNull(), - }, - (table) => [ - uniqueIndex("account_issuer_accountId_uidx").on(table.issuer, table.accountId), - index("account_userId_idx").on(table.userId), - ] -) - -export const verification = pgTable( - "verification", - { - id: text("id").primaryKey(), - identifier: text("identifier").notNull(), - value: text("value").notNull(), - expiresAt: timestamp("expires_at").notNull(), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at") - .defaultNow() - .$onUpdate(() => /* @__PURE__ */ new Date()) - .notNull(), - }, - (table) => [index("verification_identifier_idx").on(table.identifier)] -) - -export const userRelations = relations(user, ({ many }) => ({ - sessions: many(session), - accounts: many(account), -})) - -export const sessionRelations = relations(session, ({ one }) => ({ - user: one(user, { - fields: [session.userId], - references: [user.id], - }), -})) - -export const accountRelations = relations(account, ({ one }) => ({ - user: one(user, { - fields: [account.userId], - references: [user.id], - }), -})) diff --git a/apps/server/src/env.ts b/apps/server/src/env.ts deleted file mode 100644 index 47c5614..0000000 --- a/apps/server/src/env.ts +++ /dev/null @@ -1,58 +0,0 @@ -import path from "node:path" -import { z } from "zod" - -/** AI provider 未显式指定模型时的默认值;取值由 `OPENAI_MODEL` 覆盖 */ -const DEFAULT_AI_MODEL_ID = "gpt-4o" - -const values = z - .object({ - BETTER_AUTH_SECRET: z.string().min(32), - DATABASE_URL: z.url(), - GOOGLE_CLIENT_ID: z.string().min(1).optional(), - GOOGLE_CLIENT_SECRET: z.string().min(1).optional(), - LOG_LEVEL: z.string().min(1), - LOG_PRETTY: z.enum(["true", "false"]), - NODE_ENV: z.enum(["development", "test", "production"]), - OPENAI_API_KEY: z.string().min(1).optional(), - OPENAI_MODEL: z.string().min(1).optional(), - OTEL_TRACES_EXPORTER: z.string().optional(), - PORT: z.coerce.number().int().min(1).max(65_535), - SERVER_URL: z.url(), - SWEET_KIT_TRACE_FILE: z.string().min(1).optional(), - TRUST_PROXY: z.enum(["true", "false"]).default("false"), - WEB_URL: z.url(), - }) - .parse(process.env) - -export const serverEnv = { - agentTraceFile: - values.SWEET_KIT_TRACE_FILE ?? - (values.NODE_ENV !== "production" && values.OTEL_TRACES_EXPORTER === undefined - ? path.resolve("data/traces.jsonl") - : undefined), - ai: values.OPENAI_API_KEY - ? { - apiKey: values.OPENAI_API_KEY, - modelId: values.OPENAI_MODEL ?? DEFAULT_AI_MODEL_ID, - } - : undefined, - authSecret: values.BETTER_AUTH_SECRET, - databaseUrl: values.DATABASE_URL, - google: - values.GOOGLE_CLIENT_ID && values.GOOGLE_CLIENT_SECRET - ? { clientId: values.GOOGLE_CLIENT_ID, clientSecret: values.GOOGLE_CLIENT_SECRET } - : undefined, - logger: { - environment: values.NODE_ENV, - level: values.LOG_LEVEL, - pretty: values.LOG_PRETTY === "true", - }, - port: values.PORT, - serverUrl: values.SERVER_URL, - /** - * 是否信任 `x-forwarded-for`。默认关闭:只在确实部署在可信代理之后时启用, - * 否则客户端可自行伪造该 header 绕过基于 IP 的限流。 - */ - trustProxy: values.TRUST_PROXY === "true", - webUrl: values.WEB_URL, -} diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts deleted file mode 100644 index 4ea3b31..0000000 --- a/apps/server/src/index.ts +++ /dev/null @@ -1,78 +0,0 @@ -import "dotenv/config" -import { serverEnv } from "./env.ts" -import { startObservability } from "./observability.ts" - -/** - * Server composition root:先起 telemetry(instrumentation 需要在被观测模块加载前就位), - * 再装配 database、auth、logger 与 app,最后注册关停流程。 - * 装配归属见 [ADR 0007](../../../docs/adr/0007-runtime-assembly-and-app-ownership.md)。 - */ -const observability = startObservability() - -const [ - { serve }, - { createServerApp }, - { createLogger }, - { createAuth }, - { closeDatabase, createDatabase }, -] = await Promise.all([ - import("@hono/node-server"), - import("./create-app.ts"), - import("@workspace/logger"), - import("./auth.ts"), - import("./database/client.ts"), -]) - -const logger = createLogger({ ...serverEnv.logger, service: "sweet-kit-server" }) -const db = createDatabase(serverEnv.databaseUrl) -const auth = createAuth({ - baseURL: serverEnv.serverUrl, - database: db, - google: serverEnv.google, - secret: serverEnv.authSecret, - trustedOrigins: [serverEnv.webUrl], -}) -const app = createServerApp({ - ai: serverEnv.ai, - auth, - logger, - trustProxy: serverEnv.trustProxy, - webUrl: serverEnv.webUrl, -}) - -const server = serve({ - fetch: app.fetch, - port: serverEnv.port, -}) - -logger.info( - { - port: serverEnv.port, - url: serverEnv.serverUrl, - ...(observability.localTraceFile ? { agentTraceFile: observability.localTraceFile } : {}), - }, - "server.started" -) - -let shuttingDown = false - -async function shutdown(signal: NodeJS.Signals) { - if (shuttingDown) return - shuttingDown = true - logger.info({ signal }, "server.stopping") - - await new Promise((resolve, reject) => { - server.close((error) => (error ? reject(error) : resolve())) - }) - await closeDatabase(db) - await observability.shutdown() -} - -for (const signal of ["SIGINT", "SIGTERM"] as const) { - process.once(signal, () => { - shutdown(signal).catch((error: unknown) => { - logger.error({ err: error }, "server.shutdown.failed") - process.exitCode = 1 - }) - }) -} diff --git a/apps/server/src/observability.ts b/apps/server/src/observability.ts deleted file mode 100644 index c4b1249..0000000 --- a/apps/server/src/observability.ts +++ /dev/null @@ -1,45 +0,0 @@ -import path from "node:path" -import { NodeSDK } from "@opentelemetry/sdk-node" -import { SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base" -import { AgentTraceFileExporter } from "@workspace/observability/agent-traces" -import { createTracePropagator } from "@workspace/tracing" - -import { serverEnv } from "./env.ts" - -export interface Observability { - localTraceFile?: string - shutdown(): Promise -} - -/** - * Server 进程的 telemetry 装配(composition root)。 - * 本地开发把 span 投影到 JSONL 供按行检索,生产由 OTel 环境变量选择 OTLP; - * 这里只固定 service name 与项目采用的 W3C propagator。 - * - * 本地用 SimpleSpanProcessor 而非默认的 BatchSpanProcessor:批处理是为了摊薄 OTLP 的网络开销, - * 对本地文件追加只剩延迟(默认 5s),会让刚发完的请求查不到自己的 trace。 - */ -export function startObservability(): Observability { - const localTraceFile = serverEnv.agentTraceFile - ? path.resolve(serverEnv.agentTraceFile) - : undefined - - const sdk = new NodeSDK({ - serviceName: process.env.OTEL_SERVICE_NAME ?? "sweet-kit-server", - textMapPropagator: createTracePropagator(), - ...(localTraceFile - ? { - spanProcessors: [new SimpleSpanProcessor(new AgentTraceFileExporter(localTraceFile))], - metricReaders: [], - logRecordProcessors: [], - } - : {}), - }) - - sdk.start() - - return { - ...(localTraceFile ? { localTraceFile } : {}), - shutdown: () => sdk.shutdown(), - } -} diff --git a/apps/server/test/http-contract.test.ts b/apps/server/test/http-contract.test.ts deleted file mode 100644 index 0df7aa5..0000000 --- a/apps/server/test/http-contract.test.ts +++ /dev/null @@ -1,183 +0,0 @@ -import { randomUUID } from "node:crypto" -import { Writable } from "node:stream" -import { createLogger } from "@workspace/logger" -import { PROBLEM_MEDIA_TYPE } from "@workspace/request/contract" -import { afterAll, beforeAll, describe, expect, it } from "vitest" - -import { type Auth, createAuth } from "../src/auth.ts" -import { createServerApp } from "../src/create-app.ts" -import { closeDatabase, createDatabase, type Database } from "../src/database/client.ts" - -/** - * 应用响应测试:验证路由与中间件的错误出口符合 `rules/api-contract.md`。 - * - * 需要 PostgreSQL(`DATABASE_URL`)与已执行的 migration;未提供时跳过, - * 由 CI 的 integration environment 提供,不在测试内启动 container runtime。 - */ -const databaseUrl = process.env.DATABASE_URL -const baseUrl = "http://localhost:43111" -const webUrl = "http://localhost:43110" - -let db: Database -let auth: Auth -let app: ReturnType - -function createApp(database: Database, options?: { ai?: boolean }) { - return createServerApp({ - ai: options?.ai ? { apiKey: "test-key", modelId: "gpt-4o" } : undefined, - auth: createAuth({ - baseURL: baseUrl, - database, - secret: "integration-test-secret-at-least-32-characters", - trustedOrigins: [webUrl], - }), - logger: createLogger({ - destination: new Writable({ write: (_chunk, _encoding, callback) => callback() }), - environment: "test", - level: "info", - pretty: false, - service: "sweet-kit-server-test", - }), - trustProxy: false, - webUrl, - }) -} - -async function problem(response: Response) { - // Hono 默认追加 charset;problem 响应显式声明媒体类型,因此只断言前缀 - expect(response.headers.get("content-type")).toContain(PROBLEM_MEDIA_TYPE) - - return (await response.json()) as { code: string; detail: string; status: number; type: string } -} - -describe.skipIf(!databaseUrl)("HTTP 错误出口", () => { - beforeAll(() => { - db = createDatabase(databaseUrl ?? "") - auth = createAuth({ - baseURL: baseUrl, - database: db, - secret: "integration-test-secret-at-least-32-characters", - trustedOrigins: [webUrl], - }) - app = createApp(db) - }) - - afterAll(async () => { - await closeDatabase(db) - }) - - it("未匹配路由返回 404 problem details", async () => { - const response = await app.request(`${baseUrl}/api/does-not-exist`) - const body = await problem(response) - - expect(response.status).toBe(404) - expect(body).toMatchObject({ code: "NOT_FOUND", status: 404 }) - expect(body.type.endsWith("/not-found")).toBe(true) - expect(body.detail).toContain("/api/does-not-exist") - }) - - it("请求体校验失败返回 400 problem details,不带 Zod 内部结构", async () => { - const response = await app.request(`${baseUrl}/api/assistant/reply`, { - body: JSON.stringify({ prompt: "" }), - headers: { "content-type": "application/json" }, - method: "POST", - }) - const body = await problem(response) - - expect(response.status).toBe(400) - expect(body).toMatchObject({ code: "VALIDATION_ERROR", status: 400 }) - expect(body.detail).toContain("prompt") - expect(body).not.toHaveProperty("error") - }) - - it("缺少凭据返回 401,不泄漏部署配置", async () => { - const response = await problem(await app.request(`${baseUrl}/api/me`)) - - expect(response).toMatchObject({ code: "UNAUTHORIZED", status: 401 }) - }) - - it("未配置 AI provider 时登录用户得到 503", async () => { - const cookie = await signUp() - - const anonymous = await app.request(`${baseUrl}/api/assistant/reply`, { - body: JSON.stringify({ prompt: "hello" }), - headers: { "content-type": "application/json" }, - method: "POST", - }) - expect(anonymous.status).toBe(401) - - const response = await app.request(`${baseUrl}/api/assistant/reply`, { - body: JSON.stringify({ prompt: "hello" }), - headers: { "content-type": "application/json", cookie }, - method: "POST", - }) - const body = await problem(response) - - expect(response.status).toBe(503) - expect(body).toMatchObject({ code: "SERVICE_UNAVAILABLE", status: 503 }) - }) - - it("已认证时 /api/me 返回当前用户", async () => { - const email = `contract-${randomUUID()}@example.com` - const cookie = await signUp(email) - const response = await app.request(`${baseUrl}/api/me`, { headers: { cookie } }) - - expect(response.status).toBe(200) - expect(await response.json()).toMatchObject({ email }) - }) - - it("超过窗口阈值返回 429 problem details,并带 Retry-After", async () => { - const localDb = createDatabase(databaseUrl ?? "") - const localApp = createApp(localDb) - - try { - for (let index = 0; index < 100; index += 1) { - const response = await localApp.request(`${baseUrl}/api/health`) - expect(response.status).toBe(200) - } - - const limited = await localApp.request(`${baseUrl}/api/health`) - const body = await problem(limited) - - expect(limited.status).toBe(429) - expect(body).toMatchObject({ code: "TOO_MANY_REQUESTS", status: 429 }) - expect(limited.headers.get("retry-after")).toBe("60") - } finally { - await closeDatabase(localDb) - } - }) - - it("OpenAPI 为每个错误状态声明 problem 媒体类型", async () => { - const document = (await (await app.request(`${baseUrl}/openapi.json`)).json()) as { - paths: Record }>> - } - - for (const [path, operations] of Object.entries(document.paths)) { - for (const [method, operation] of Object.entries(operations)) { - for (const [status, response] of Object.entries(operation.responses)) { - if (Number(status) < 400) continue - - const content = (response as { content?: Record }).content ?? {} - - expect(Object.keys(content), `${method.toUpperCase()} ${path} ${status}`).toContain( - PROBLEM_MEDIA_TYPE - ) - } - } - } - }) -}) - -async function signUp(email = `contract-${randomUUID()}@example.com`): Promise { - const result = await auth.api.signUpEmail({ - body: { email, name: "Contract", password: "contract-password" }, - returnHeaders: true, - }) - const cookie = result.headers.get("set-cookie") - - if (!cookie) { - throw new Error("sign-up 未返回 session cookie") - } - - return cookie -} diff --git a/apps/server/tsconfig.json b/apps/server/tsconfig.json deleted file mode 100644 index 68eb3eb..0000000 --- a/apps/server/tsconfig.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "extends": "@workspace/typescript-config/base.json", - "compilerOptions": { - "declaration": false, - "declarationMap": false, - "outDir": "dist", - "rootDir": "src" - }, - "include": ["src"], - "exclude": ["node_modules", "dist"] -} diff --git a/apps/server/tsconfig.test.json b/apps/server/tsconfig.test.json deleted file mode 100644 index 68cb4d6..0000000 --- a/apps/server/tsconfig.test.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "@workspace/typescript-config/base.json", - "compilerOptions": { - "declaration": false, - "declarationMap": false, - "noEmit": true - }, - "include": ["src", "test", "vitest.config.ts"], - "exclude": ["node_modules", "dist"] -} diff --git a/apps/server/vitest.config.ts b/apps/server/vitest.config.ts deleted file mode 100644 index decd39e..0000000 --- a/apps/server/vitest.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { defineProject } from "vitest/config" - -export default defineProject({ - test: { - environment: "node", - include: ["test/**/*.test.ts"], - name: "server", - }, -}) diff --git a/apps/web/.env.example b/apps/web/.env.example deleted file mode 100644 index 745ffd5..0000000 --- a/apps/web/.env.example +++ /dev/null @@ -1,7 +0,0 @@ -# ─── URLs ──────────────────────────────────────────────── -NEXT_PUBLIC_SERVER_URL=http://localhost:43111 - -# ─── Analytics ───────────────────────────────────────── -# NEXT_PUBLIC_GOOGLE_ANALYTICS_ID=G-XXXXXXXXXX -# NEXT_PUBLIC_MICROSOFT_UET_TAG_ID=000000000 -# NEXT_PUBLIC_META_PIXEL_ID=000000000000000 diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md deleted file mode 100644 index 643577d..0000000 --- a/apps/web/AGENTS.md +++ /dev/null @@ -1,9 +0,0 @@ - - -# 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. - - diff --git a/apps/web/CLAUDE.md b/apps/web/CLAUDE.md deleted file mode 100644 index 43c994c..0000000 --- a/apps/web/CLAUDE.md +++ /dev/null @@ -1 +0,0 @@ -@AGENTS.md diff --git a/apps/web/app/favicon.ico b/apps/web/app/favicon.ico deleted file mode 100644 index 718d6fe..0000000 Binary files a/apps/web/app/favicon.ico and /dev/null differ diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx deleted file mode 100644 index faec268..0000000 --- a/apps/web/app/layout.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import type { Metadata } from "next" -import { Geist, Geist_Mono } from "next/font/google" -import "@workspace/ui/globals.css" -import { Analytics } from "@/components/analytics" -import { Providers } from "@/components/providers" -import { webEnv } from "@/lib/env" - -const fontSans = Geist({ - subsets: ["latin"], - variable: "--font-sans", -}) - -const fontMono = Geist_Mono({ - subsets: ["latin"], - variable: "--font-mono", -}) - -export const metadata: Metadata = { - title: "Sweet Kit", - description: "A full-stack TypeScript development kit", -} - -export default function RootLayout({ - children, -}: Readonly<{ - children: React.ReactNode -}>) { - return ( - - - - {children} - - - ) -} diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsx deleted file mode 100644 index 1626ca8..0000000 --- a/apps/web/app/page.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { Button } from "@workspace/ui/components/button" -import Link from "next/link" - -import { ServerStatus } from "@/components/server-status" - -export default function Page() { - return ( -
-
-

- Full-stack TypeScript development kit -

-

Sweet Kit

-

- Next.js frontend, Hono server, OpenAPI contract, and aspect-oriented packages. -

- -
- -
-
-
- ) -} diff --git a/apps/web/app/sign-in/page.tsx b/apps/web/app/sign-in/page.tsx deleted file mode 100644 index 8f7d966..0000000 --- a/apps/web/app/sign-in/page.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import Link from "next/link" - -import { AuthLayout } from "@/components/auth-layout" -import { SignInForm } from "@/components/sign-in-form" -import { SocialLogin } from "@/components/social-login" - -function safeRedirect(value: string | undefined) { - return value?.startsWith("/") && !value.startsWith("//") ? value : "/" -} - -export default async function SignInPage({ - searchParams, -}: { - searchParams: Promise<{ redirect?: string }> -}) { - const { redirect } = await searchParams - - return ( - -
-
-

登录 Sweet Kit

-

选择登录方式继续

-
- - - -
-
- -
-
- OR -
-
- - - -
- 没有账号?{" "} - - 创建账号 - -
-
-
- ) -} diff --git a/apps/web/app/sign-up/page.tsx b/apps/web/app/sign-up/page.tsx deleted file mode 100644 index 788a8bc..0000000 --- a/apps/web/app/sign-up/page.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import Link from "next/link" - -import { AuthLayout } from "@/components/auth-layout" -import { SignUpForm } from "@/components/sign-up-form" -import { SocialLogin } from "@/components/social-login" - -function safeRedirect(value: string | undefined) { - return value?.startsWith("/") && !value.startsWith("//") ? value : "/" -} - -export default async function SignUpPage({ - searchParams, -}: { - searchParams: Promise<{ redirect?: string }> -}) { - const { redirect } = await searchParams - - return ( - -
-
-

创建账号

-

注册以开始使用 Sweet Kit

-
- - - -
-
- -
-
- OR -
-
- - - -
- 已有账号?{" "} - - 登录 - -
-
-
- ) -} diff --git a/apps/web/components.json b/apps/web/components.json deleted file mode 100644 index 1fd99d3..0000000 --- a/apps/web/components.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "$schema": "https://ui.shadcn.com/schema.json", - "style": "new-york", - "rsc": true, - "tsx": true, - "tailwind": { - "config": "", - "css": "../../packages/ui/src/styles/globals.css", - "baseColor": "neutral", - "cssVariables": true - }, - "iconLibrary": "lucide", - "aliases": { - "components": "@/components", - "hooks": "@/hooks", - "lib": "@/lib", - "utils": "@workspace/ui/lib/utils", - "ui": "@workspace/ui/components" - } -} diff --git a/apps/web/components/analytics.tsx b/apps/web/components/analytics.tsx deleted file mode 100644 index 3aabd1b..0000000 --- a/apps/web/components/analytics.tsx +++ /dev/null @@ -1,91 +0,0 @@ -"use client" - -import { usePathname } from "next/navigation" -import Script from "next/script" -import { useEffect } from "react" - -import { - initializeGoogleAnalytics, - initializeMetaPixel, - initializeMicrosoftUet, - trackMetaPageView, -} from "@/lib/analytics" -import { useConsentStore } from "@/lib/consent" - -interface AnalyticsProps { - googleAnalyticsId?: string - metaPixelId?: string - microsoftUetTagId?: string -} - -/** - * 第三方统计装配。 - * - * 未取得同意(`consent.status !== "granted"`)时不加载任何脚本,也不上报 pageview: - * 登录、注册与授权页同样适用。决定入口见 `components/consent-banner.tsx`。 - */ -export function Analytics({ googleAnalyticsId, metaPixelId, microsoftUetTagId }: AnalyticsProps) { - const pathname = usePathname() - const granted = useConsentStore((state) => state.status) === "granted" - - useEffect(() => { - if (granted && googleAnalyticsId) { - initializeGoogleAnalytics(googleAnalyticsId) - } - }, [granted, googleAnalyticsId]) - - useEffect(() => { - if (granted && metaPixelId) { - initializeMetaPixel(metaPixelId) - } - }, [granted, metaPixelId]) - - useEffect(() => { - if (granted && metaPixelId) { - trackMetaPageView(metaPixelId, pathname) - } - }, [granted, metaPixelId, pathname]) - - if (!granted) { - return null - } - - return ( - <> - {googleAnalyticsId ? ( -