# Cloudflare 部署方案（Pages 单项目 · 三路径）

- 适用项目：`bdip-v1`（monorepo，含 `apps/home` 项目导航页、`apps/web` 前台门户、`apps/admin` 管理后台）
- 部署形态：**一个 Cloudflare Pages 项目**，同时提供三条路径

| 访问路径 | 内容 | 产物来源 |
|---|---|---|
| `/`、`/home/` | 项目导航页 | `apps/home/`（纯静态，无构建） |
| `/web/` | 前台门户（MPA + 客户端路由） | `apps/web/dist/` |
| `/admin/` | 管理后台（hash 路由） | `apps/admin/dist/` |
| `/docs/` | 项目文档（含本文） | 仓库 `docs/` |

- 状态：**已落地**。合并脚本 `scripts/build-cf.mjs` 与 `package.json` 里的 `build` / `build:cf` / `preview:cf` / `deploy:cf` 已就位，本地执行 `npm run build` 通过（566 个文件）。
- 后台的既有踩坑记录见 `apps/admin/.skills/cloudflare部署错误及解决方案.md`
- 架构说明见 `docs/前后台整合方案.md`

---

## 1. 为什么是 Pages，以及方案要点

前台与后台产物都是纯静态资源（Vite 构建的 MPA/SPA），没有服务端逻辑，**不需要 Workers**。整套方案只靠两件事成立：

1. **构建期合并**：`scripts/build-cf.mjs` 把三份产物 + 文档拍成一棵 `dist/` 树（第 2 节）。
2. **运行期用 `404.html` 做子站回落**：给 `dist/web/`、`dist/admin/` 各放一份子站 `index.html` 的副本当 `404.html`，利用 Pages「就近向上查找 404.html」的行为，让 `/web/tools/industry-navigation` 这类客户端路由刷新时落回**前台自己的壳**，而不是掉到导航页（第 3 节）。

两个关键前提：

- `apps/web` 的 `base: '/web/'`、`apps/admin` 的 `base: '/admin/'` **一行都不用改** —— 产物布局与本地 `scripts/serve.mjs` 的 `MOUNTS` 完全一致，本地和线上行为对齐。
- **完全不需要 `_redirects`**。这很重要，见 3.4。

---

## 2. 产物布局 `dist/`

`npm run build` 依次执行 `sync:data` → `build:admin` → `build:web` → `node scripts/build-cf.mjs`，最终得到：

```
dist/
├── index.html                  ← apps/home        裸域名 /
├── style.css                   ← apps/home        （home 用相对路径引 style.css）
├── 404.html                    ← 导航页副本        顶层 404，见 3.2
├── home/                       ← apps/home 副本   /home/
│   ├── index.html
│   └── style.css
├── web/                        ← apps/web/dist    /web/
│   ├── index.html
│   ├── 404.html                ← index.html 副本   子站回落壳
│   ├── standards.html / data-center.html / ...（9 个 MPA 入口）
│   ├── assets/
│   ├── data/
│   └── docs/
├── admin/                      ← apps/admin/dist  /admin/
│   ├── index.html
│   ├── 404.html                ← index.html 副本   子站回落壳
│   ├── assets/
│   └── docs/
└── docs/                       ← 仓库 docs/        /docs/
    ├── index.html              ← 由 build-cf.mjs 生成的目录索引页
    ├── Cloudflare部署方案.md
    └── ...
```

`dist/` 实测规模：**566 个文件 / 45.8 MB**，最大单文件 `dist/admin/docs/dict/参考资料/工程设计资质标准.pdf` 为 **6.03 MB**。

对照 Cloudflare Pages 的限额（见附录），两者都留有极大余量，**不需要任何限额豁免或特殊配置**：

| 限额 | 上限 | 本项目 |
|---|---|---|
| 文件数（Free） | 20,000 | 566 |
| 文件数（Pro / Business） | 100,000（需设 `PAGES_WRANGLER_MAJOR_VERSION=4`） | 不涉及 |
| 单文件体积 | 25 MiB | 6.03 MB |

### 2.1 关于三个 `docs/` 目录

合并时**不存在冲突**，因为三者落在不同层级：

- `dist/docs/` ← 仓库根 `docs/`（本项目文档，本文档在这里）
- `dist/web/docs/` ← `apps/web/docs/`（`vite.config.ts` 的 `copyDocsPlugin()`）
- `dist/admin/docs/` ← `apps/admin/docs/`（`vite.config.ts` 的 `viteStaticCopy`）

仓库根 `docs/` 没有 `index.html`，`build-cf.mjs` 会补一个目录列表页（配色 `#1BAE70` / `#F7F9FA` / `#EAEAEA`），免得导航页的「总文档」链接 404。

### 2.2 关于 `sync:data`

根 `npm run sync:data` 把根 `data/` 同步到 `apps/web/public/data` 与 `apps/admin/public/data`。

**注意**：部署与本地构建统一用 `npm run build`，它**包含** `sync:data`；`build:cf` 是给「只想重跑构建、不重跑数据同步」的场景用的，**不含** `sync:data`。当前根 `data/` 目录不存在，脚本会打印 `[sync-data] 跳过`，所以现在没问题；但**将来若根 `data/` 放了数据**，务必走 `npm run build`（或在 `build:cf` 前手动补 `npm run sync:data`）：

```
npm run sync:data && npm run build:cf
```

---

## 3. 关键机制：`404.html` 就近向上查找

这是三路径能在一个 Pages 项目里跑通的核心。官方行为分三条（原文见附录）：

1. **路由匹配**：命中同名 HTML 文件即返回，并把 `.html` 重定向到无扩展名版本（`/contact.html` → `/contact`、`/about/index.html` → `/about/`）。
2. **Not Found 行为**：找不到文件时，Pages 就近找 `404.html`；**当前目录没有就逐级向上找**，最后落到 `/404.html`。
3. **SPA 渲染**：**如果项目没有顶层 `404.html`**，Pages 就假定这是个单页应用，把所有未命中路径**整站**回落到根 `/index.html`。

### 3.1 本项目的用法

| 请求 | 命中方式 | 结果 |
|---|---|---|
| `/` | 文件系统：`dist/index.html` | 导航页 |
| `/home/` | 文件系统：`dist/home/index.html` | 导航页（与 `/` 同内容） |
| `/web/` | 文件系统：`dist/web/index.html` | 前台首页 |
| `/web/standards` | 路由匹配：`dist/web/standards.html` | 9 个 MPA 入口之一，**不依赖回落** |
| `/web/tools/industry-navigation` | 无实体文件 → **就近找到 `dist/web/404.html`** | 前台首页 → 前端路由接管 → 渲染目标页 |
| `/admin/#/sys/users` | 服务端只被请求 `/admin/` | hash 路由，天然不受影响 |
| `/docs/前后台整合方案.md` | 文件系统 | 文档 |
| 任意不存在的路径 | 就近找到 `dist/web/404.html` 或顶层 `dist/404.html` | 子站壳 / 导航页 |

### 3.2 两个 `404.html` 的作用不同，都不能少

- **`dist/404.html`（顶层）**：只负责**关掉整站 SPA 模式**。若缺少它，Pages 会判定为 SPA，把 `/web/tools/...` 也塞给根 `index.html`（导航页），前端路由虽能渲染，但站内相对资源与 `basename` 全部对不上 → 白屏。
- **`dist/web/404.html`、`dist/admin/404.html`（子站）**：负责**按子站回落**。`dist/admin/404.html` 其实是保险（admin 走 hash 路由，服务端永远只被请求 `/admin/`），但加一份无害、语义完整。

> 内容说明：两个子站 `404.html` 就是各自 `index.html` 的**逐字节副本**（`build-cf.mjs` 里 `cp(index.html, 404.html)`），不是自定义错误页。

### 3.3 一个需要在线上确认的点

回落到 `404.html` 时，**HTTP 状态码预期仍是 404**（内容却是子站首页）。浏览器照常执行 JS 完成渲染，用户体验没问题；监控/SEO 上不理想，但**本项目不考虑 SEO**，可接受。

本地环境无法模拟 Pages 的这个行为（见 4.2），因此**上线后必须实测一次**（第 6 节清单第 4 条）。

### 3.4 为什么不用 `_redirects`

`_redirects` 是这类需求的常见做法，但官方明确：

> Redirects are always followed, regardless of whether or not an asset matches the incoming request.

所以写 `/web/* /web/index.html 200` 会**连 `/web/assets/*.js` 一起命中**，把 JS 请求也改写成 HTML → 前台全站脚本报错。要收窄就得逐条补静态规则（`/web/assets/*`、`/web/data/*`、`/web/docs/*` …），规则数有上限（2000 静态 + 100 动态）且容易漏。

而 `404.html` 方案**只在“确实没命中任何文件”时生效**，静态资源永远不会被误伤，也不需要逐条列举。

> 同理，Transform Rules 也不行：它会改写浏览器地址栏，破坏 history 路由。

### 3.5 与本地服务的差异

| 行为 | 本地 `scripts/serve.mjs` | Cloudflare Pages |
|---|---|---|
| 无扩展名解析已有 HTML（`/web/standards` → `standards.html`） | 支持 | 支持（Pages 会把 `.html` 重定向到无扩展名版） |
| 未命中路径的回落粒度 | 按挂载点（`/web/*` → web 壳、`/admin/*` → admin 壳） | 靠 `404.html` 就近查找，**同样按子站** |

加了子站 `404.html` 之后，两者回落粒度**重新对齐**。

---

## 4. 本地构建与预览

### 4.1 构建

```bash
npm ci                       # 必须在仓库根安装（见 5.3）
npm run build                # = sync:data && build:admin && build:web && node scripts/build-cf.mjs
npm run build:cf             # 只重跑构建（不含 sync:data），部署用哪条都行
```

成功时最后一行会打印：

```
[build-cf] 共 566 个文件，可以交给 Cloudflare Pages 了
```

`build-cf.mjs` 会先校验 `apps/web/dist/index.html` 与 `apps/admin/dist/index.html` 是否存在，缺失则直接报错退出，避免合并出一份残缺的 `dist/`。

### 4.2 本地无法用 wrangler 模拟 Pages（实测记录）

`package.json` 里的 `preview:cf` 是 `npx wrangler pages dev dist`，但**在本机沙箱环境实测跑不起来**：

- `EPERM: operation not permitted, mkdir '...\AppData\Roaming\xdg.config'`（wrangler 写默认日志目录被拦）
- 设置 `XDG_CONFIG_HOME` / `XDG_CACHE_HOME` 绕开后，改为 `workerd` 本地运行时启动失败：`MiniflareCoreError [ERR_RUNTIME_FAILURE]`

这是**本地环境限制，不是配置错误**，与线上 Pages 无关。因此本方案的行为结论均依据官方文档（附录），并**必须在线上部署后实测确认**（第 6 节）。

替代的本地验证手段：`npm run serve`（`scripts/serve.mjs`，端口 8090），它按 `MOUNTS` 提供 `/admin`、`/web`、`/docs` 与根路径，布局与 `dist/` 一致，可用来核对页面本身的正确性（不含 Pages 的 404 回落语义）。

---

## 5. 部署到 Cloudflare Pages（二选一）

### 5.1 通路 A：Git 集成（推荐，推送即部署）

Cloudflare Dashboard → Workers & Pages → Create → Pages → Connect to Git → 选仓库，然后按下表填：

| 配置项 | 值 | 说明 |
|---|---|---|
| Production branch | 你的主分支 | |
| Framework preset | `None` | 非框架项目 |
| **Root directory** | **留空（仓库根）** | 见 5.3，**不能**填 `apps/web` |
| **Build command** | `npm run build` | 与 `build:cf` 等价，都产出根 `dist/`；见 5.4 |
| **Build output directory** | `dist` | `build-cf.mjs` 的产物目录 |
| 环境变量 `NODE_VERSION` | `20` | |
| 环境变量 `GEMINI_API_KEY` | 按需 | 见 7.2，不配则为 `undefined` |

**前置条件**：`bdip-v1` 目前**不是 git 仓库**（无 `.git`，`git rev-parse` 报 `not a git repository`），需先初始化并推送：

```bash
cd bdip-v1
git init
git add .
git commit -m "chore: 初始化仓库"
git remote add origin <仓库地址>
git push -u origin main
```

> **重要**：Cloudflare Pages 已经从 `https://github.com/fangspx/bdip` 拉代码构建（构建日志首行为 `Cloning repository... From https://github.com/fangspx/bdip`）。本机这份 `bdip-v1` 没有 `.git`，**改动只落在本地磁盘，不会自动同步到线上仓库** —— 修完必须把改动推送到该 GitHub 仓库并重新触发构建，否则下次部署仍会复现同样的失败。

根 `.gitignore` 已忽略 `node_modules/`、`dist/`、`*.log`、`.env*`（保留 `.env.example`）等，可直接使用。

系统会默认注入 `CI=true`、`CF_PAGES=1`、`CF_PAGES_BRANCH`、`CF_PAGES_COMMIT_SHA`、`CF_PAGES_URL`，本方案不依赖它们。

### 5.2 通路 B：本地构建 + 直接上传

不初始化 git 也能部署，`package.json` 里已封装好：

```bash
npm run deploy:cf
# = npm run build:cf && npx wrangler pages deploy dist --project-name=bdip
```

首次需 `npx wrangler login` 完成授权。`wrangler` 未装进 `devDependencies`，脚本用 `npx` 按需拉取。

> 通路 B 每次都要在本地上传全部 566 个文件；通路 A 由 Cloudflare 构建，更省事，也能天然拿到每次提交的独立 Preview 部署。

### 5.3 monorepo 坑位一：Root directory 必须是仓库根

`apps/web/package.json`、`apps/admin/package.json` 都依赖 `"@bms/shared": "*"`（workspace 包，**未发布到 npm**）。

若把 Root directory 设为 `apps/web` 或 `apps/admin`，Cloudflare 会在该目录单独执行安装，npm 去 registry 解析这个不存在的包 → 安装失败。

`apps/web/src` 当前**并没有实际 import `@bms/shared`**，但依赖声明仍在，`npm install` 阶段就会尝试解析。**必须从仓库根安装**（根有 `package-lock.json`，workspaces 才生效）。

### 5.4 monorepo 坑位二：`build` 与 `build:cf` 必须都产出根 `dist/`

根 `package.json` 里：

```json
"build": "npm run sync:data && npm run build:admin && npm run build:web && node scripts/build-cf.mjs",
"build:cf": "npm run build:web && npm run build:admin && node scripts/build-cf.mjs"
```

两条命令**产物一致**（都能得到根 `dist/`，即 Build output directory 要的那个目录），差别只在顺序和 `sync:data`：

- `npm run build`：先 `sync:data` 同步根 `data/`，再 admin（带 `tsc -b` 门禁）→ web，最后合并；
- `npm run build:cf`：不含 `sync:data`，且 web 先、admin 后。

**历史坑**：`build` 曾经只跑两个子应用的构建，不合并，于是根目录没有 `dist/`。Cloudflare 的 Build command 若填的是 `npm run build`，日志会走到最后一步才报：

```
Validating asset output directory
Error: Output directory "dist" not found.
Failed: build output directory not found
```

现在 `build` 末尾也接了 `node scripts/build-cf.mjs`，两种填法都不会再踩这个坑。

另外要清楚 **admin 的 TS 门禁在两条路径上**：`apps/admin` 的 build 是 `tsc -b && vite build`（带类型检查），admin 一旦有 TS 报错，整条构建就会中断，前台也发不出去。这是**预期行为**——admin 本来就该能编译通过。

对比之下 `apps/web` 的 build 只是 `vite build`（**无 tsc 门禁**），类型错误不阻断构建；本地仍建议自查：

```bash
npm --workspace @bms/web run lint     # tsc --noEmit
```

---

## 6. 部署前 / 部署后检查清单

**构建阶段**

1. `npm ci` 在**仓库根**执行成功（不是 `apps/web`）
2. `npm run build` 通过，末行输出 `共 566 个文件`
3. `dist/` 顶层含 `index.html`、`style.css`、`404.html`、`home/`、`web/`、`admin/`、`docs/`
4. `dist/web/404.html`、`dist/admin/404.html`、`dist/404.html` **三者都存在**（缺顶层那份就退化成整站 SPA 回落）
5. admin 的 `tsc -b` 无报错（有则先在本地修掉）
6. 根 `data/` 有数据时也不用改命令：`npm run build` 自带 `sync:data`（见 2.2）

**Pages 项目配置**

7. Root directory 留空、Build command `npm run build`、Build output directory `dist`、`NODE_VERSION=20`

**上线后实测**（本地无法验证 Pages 行为，这几条必做）

8. `/` 与 `/home/` → 导航页；`/web/` → 前台首页；`/admin/` → 后台登录；`/docs/` → 文档索引
9. **`/web/tools/industry-navigation` 直接打开并原地刷新** → 必须是前台页面的正常渲染，**不能**变成导航页、不能白屏
10. 前台 9 个 MPA 入口抽查：`/web/standards`、`/web/data-center`（无扩展名直达 + 刷新）
11. 静态资源抽查：`/web/assets/*.js`、`/web/assets/*.css`、`/admin/assets/*.js` 返回 200，`Content-Type` 不是 `text/html`
12. `/admin/#/` 下切换几个后台菜单并刷新，确认 hash 路由正常
13. 打开浏览器控制台确认无 404（尤其 favicon，见 7.1）

---

## 7. 其他注意事项

### 7.1 favicon：5 个 PNG 图标缺失（**已修复**）

`apps/web/*.html`（9 个入口）曾各自声明 6 个图标：

```html
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="48x48" href="/favicon-48x48.png" />
<link rel="icon" type="image/png" sizes="64x64" href="/favicon-64x64.png" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
```

Vite 构建时**只重写那些在 `apps/web/public/` 中真实存在的引用**。产物 `apps/web/dist/index.html` 中只有 `/favicon.svg` 被改写成 `/web/favicon.svg`；而 `favicon-16x16.png` 等 5 个文件在 `apps/web/public/` 下**并不存在**，其余 5 行仍是根绝对路径 → 部署后必然 404。

**修复方式**：删掉这 5 行声明，只留 `<link rel="icon" type="image/svg+xml" href="/favicon.svg" />`。

顺带修掉同类断链两处：
- `apps/admin/docs/*.html` 用绝对路径 `/favicon.svg`，而根产物原本没有该文件 → 新增 `apps/home/favicon.svg`（由 `build-cf.mjs` 铺到 `dist/favicon.svg`，全站可达）。
- `apps/web/docs/axure/v1|v2/*.html` 用相对路径 `../../favicon.svg`（解析到 `/web/docs/favicon.svg`）→ 新增 `apps/web/docs/favicon.svg`，避免改 30+ 个原型页。

（`<meta property="og:image">` / `twitter:image` 不参与重写，若要保留需自己写成 `/web/favicon.svg`。）

### 7.2 `GEMINI_API_KEY`

`apps/web/vite.config.ts` 通过 `define` 把 `process.env.GEMINI_API_KEY` 注入到代码里，构建时从构建环境变量读取；未配置则注入 `undefined`。

- 通路 A（Git 集成）：在 Pages 项目的 Settings → Environment variables 里配置，**改完要重新部署**才会写入产物。
- 通路 B（本地构建）：构建前在本地 shell 里设置该变量。

### 7.3 遗留的 GitHub Pages 配置（无害）

| 文件 | 说明 |
|---|---|
| `apps/web/_config.yml` | 内容 `include: [".html", ".md"]`，GitHub Pages 遗留，Cloudflare 不读取 |
| `apps/web/public/.nojekyll` | 同为 GitHub Pages 遗留，会被拷进 `dist/web/.nojekyll`，Cloudflare 不读取 |
| `apps/web/public/` 下无 `_redirects` | 本方案不需要它（见 3.4）；若将来误加，会与 404 机制叠加出意外行为 |

### 7.4 构建验证纪律

Cloudflare 执行的就是 `package.json` 里的命令。**本地必须跑与线上完全一致的那一条**（`npm run build`），不要用 `npx vite build` 之类的捷径绕过，否则本地通过、线上失败。

改完必须 commit + push（通路 A）或在本地重新 `npm run build` 后重新上传（通路 B）。

### 7.5 构建资源限制（Pages 侧）

| 项 | 限制 |
|---|---|
| 每月构建次数（Free） | 500 次 |
| 单次构建超时 | 20 分钟 |
| 每账号项目数 | 100 个 |
| `_headers` 规则 | 最多 100 条、单条 2000 字符（本方案未使用） |

`npm run build` 要跑两个 Vite 构建，请留意单次构建 20 分钟的上限；当前产物量（566 文件）离上限很远。

---

## 8. 已知遗留 / 待办

| 项 | 状态 |
|---|---|
| `apps/web/index.html` 声明的 5 个 PNG 图标不存在 | **已处理**：9 个入口 HTML 只留 `favicon.svg` 声明，并补 `apps/home/favicon.svg`、`apps/web/docs/favicon.svg` |
| Pages 回落到 `404.html` 时的实际状态码与渲染行为 | **待线上实测**，见 3.3 / 第 6 节 |
| 根 `data/` 一旦有数据 | 提醒，见 2.2；`npm run build` 已自带 `sync:data`，无需改命令 |
| 仓库尚未 `git init` | 走通路 A 前需处理，见 5.1 |
| **本机无 git 仓库，修复必须推到 `github.com/fangspx/bdip` 才会生效** | 提醒，见 7.4 |
| `/jobs`、`/services`、`/insights/*`、`/tools/utilities` 等页面未建 | 长期挂起，与部署无关 |

---

## 附录：参考

### 项目内文件

| 文件 | 作用 |
|---|---|
| `scripts/build-cf.mjs` | 三份产物 + 文档合并成 `dist/`，并生成子站与顶层 `404.html` |
| `package.json` | `build`（部署用，含全流程）/ `preview:cf` / `deploy:cf` |
| `scripts/serve.mjs` | 本地单端口静态服务，`MOUNTS` 布局即 `dist/` 布局 |
| `scripts/sync-data.mjs` | 根 `data/` → 各端 `public/data` |
| `apps/admin/.skills/cloudflare部署错误及解决方案.md` | 后台部署踩坑记录（核心教训：Cloudflare 执行的就是 `package.json` 的 build 命令，本地必须跑同一条） |
| `docs/前后台整合方案.md` | 前后台架构说明 |

### Cloudflare 官方文档（本文结论的依据）

- 路由匹配 / Not Found / SPA 渲染：<https://developers.cloudflare.com/pages/configuration/serving-pages/>
  - 「If an HTML file is found with a matching path to the current route requested, Pages will serve it. Pages will also redirect HTML pages to their extension-less counterparts」
  - 「You can define a custom page to be displayed when Pages cannot find a requested file by creating a `404.html` file. Pages will then attempt to find the **closest 404 page**. If one is not found in the same directory as the route you are currently requesting, it will continue to **look up the directory tree** for a matching `404.html` file, ending in `/404.html`」
  - 「If your project does not include a **top-level `404.html`** file, Pages assumes that you are deploying a single-page application… matches all incoming paths to the **root (`/`)**」
- `_redirects` 语法与限制：<https://developers.cloudflare.com/pages/configuration/redirects/>
  - 「Redirects are always followed, regardless of whether or not an asset matches the incoming request」
  - 「The order of your redirects matter. If there are multiple redirects for the same `source` path, the top-most redirect is applied」
- 限额：<https://developers.cloudflare.com/pages/platform/limits/>
  - Free 计划每站点最多 **20,000 个文件**，付费 100,000（需设 `PAGES_WRANGLER_MAJOR_VERSION=4`）
  - 单个文件最大 **25 MiB**；每账号最多 100 个项目
  - 每月 500 次构建、单次构建 20 分钟超时
  - `_headers` 最多 100 条规则、单条 2000 字符
- 构建配置：<https://developers.cloudflare.com/pages/configuration/build-configuration/>
  - Root directory 留空即仓库根；系统默认注入 `CI=true`、`CF_PAGES=1`、`CF_PAGES_COMMIT_SHA`、`CF_PAGES_BRANCH`、`CF_PAGES_URL`
- 自定义 404（补充）：<https://developers.cloudflare.com/pages/configuration/serving-pages/#not-found-behavior>
