diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..c3ca9df --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,65 @@ + + + +## 变更类型 + +- [ ] 新材料(第三方项目首次收录) +- [ ] 官方项目上架 / 更新(`source: official`) +- [ ] 更新既有条目(改名 / 仓库迁移 / 部署方式 / 免费层变化) +- [ ] 下架(`status: delisted`) +- [ ] 其他(请在下方说明) + +## 条目信息 + +| 项 | 值 | +| ------------------------------- | ---------------------------------- | +| 数据文件 | `src/data/projects/` 下的哪个文件 | +| `slug` | | +| `repo`(上游原仓库,不是 fork) | | +| `source` | `third-party` / `official` | +| `category` | | +| `deploy.method` | | +| `tier` | `listed` / `verified` / `official` | + +## 收录门槛逐项勾选(五条全过才可收录,每条都要附证据链接) + +- [ ] **1. 开源且许可证明确**:仓库根目录有 LICENSE,且 GitHub 能识别出许可证类型(无许可证一律不收) + - 证据(LICENSE 文件链接): +- [ ] **2. 真实可部署在 Cloudflare Workers 或 Pages**:有 wrangler 配置 / Pages 配置,或明确成型的部署文档;仅「理论上能跑」不算 + - 证据(配置文件路径或部署文档链接): +- [ ] **3. 近 12 个月内有代码更新**:构建时由自动字段 `pushed_at` 判定(老牌稳定项目请在此写豁免理由) + - 证据(豁免理由;无需手写 `pushed_at`): +- [ ] **4. 部署步骤可复现**:README 或文档含完整部署章节,本人按文档跑通过 + - 证据(章节链接 + 实际步骤摘要): +- [ ] **5. 免费层可跑,或付费要求写在明处**:`free_tier` 与 `pricing_note` 与仓库文档一致 + - 证据(价格 / 免费层限制说明链接): + +## 数据合规自查 + +- [ ] `slug` 与文件名一致(`src/data/projects/.yaml`),且不与现有项目重复(CI 按 slug 与 repo 双维度查重) +- [ ] 没有手写 GitHub 自动字段(star / fork / 语言 / 许可证 / `pushed_at` / archived / 最新 release / Open Graph 图) +- [ ] 本 PR **只**新增或修改了 `src/data/projects/.yaml`(可选 `public/screenshots/.webp`),没改代码、依赖、工作流、模板,也没动别人的条目 +- [ ] 中文文案为本人撰写(不是机翻),与该项目的实际功能一致,部署方式与难度**宁可低标不高标** +- [ ] 如填了 `screenshot`:webp 格式、宽度 ≥1200px、体积 ≤300KB,文件名为 `.webp` +- [ ] 如填了 `tier: verified`:已附 `verified_at` 与 `verified_note_url`(第三方投稿请保持 `listed`,由维护者实测后升级) + +## 验证等级声明 + +- [ ] `listed`(已收录,未实测——第三方投稿默认) +- [ ] `verified`(已验证,附验证记录链接) +- [ ] `official`(仅 WorkerHub 官方项目可用) + +## 上架后需要更正 / 作者异议 + +条目信息有误、或你是被收录项目的作者希望更正/移除,请在本仓库开 issue 说明 `slug` 与诉求(见 CONTRIBUTING 第 9 节,移除不设门槛)。 + +## 声明 + +- [ ] 我确认以上信息准确;如为第三方项目,我理解其版权与责任归项目作者,本站收录不构成对质量或安全性的担保 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7716cc3..d3bb497 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,6 +38,12 @@ jobs: - name: 数据文件 schema 校验(§4.1 / §7:非法数据直接失败并点名字段) run: pnpm validate:data + - name: 投稿数据校验(§7:repo 存在且 public / 外链可达性 / 截图规格) + run: pnpm validate:submission + env: + # 只读公开数据足够;不要求、也不允许任何 PAT 入仓(§9.2) + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Lint 与类型检查 run: pnpm lint @@ -104,3 +110,69 @@ jobs: exit 1 fi echo "守卫演练通过:非法数据构建失败" + + - name: 演练 3|不存在的 repo 必须让 CI 失败并点名(§7) + run: | + if HUB_PROJECTS_DIR=tests/fixtures/submission/repos pnpm check:repos; then + echo "::error::不存在的 repo 竟然通过了核验,§7 门槛失效" + exit 1 + fi + echo "repo 核验演练通过:不存在的仓库被拦下" + + - name: 演练 4|第三方外链失败只警告,官方/演示站失败硬拦(§7) + run: | + HUB_PROJECTS_DIR=tests/fixtures/submission/links/third-party pnpm check:links + echo "第三方外链失败仅警告:CI 未失败,符合 §7" + if HUB_PROJECTS_DIR=tests/fixtures/submission/links/official pnpm check:links; then + echo "::error::官方/演示站外链失败竟然放行了,§7 硬拦失效" + exit 1 + fi + echo "官方/演示站外链失败硬拦:符合 §7" + + - name: 演练 5|不合规截图必须让 CI 失败并逐条点名(§7) + run: | + if HUB_PROJECTS_DIR=tests/fixtures/submission/screenshots \ + HUB_SCREENSHOTS_DIR=tests/fixtures/screenshots \ + pnpm check:screenshots; then + echo "::error::不合规截图竟然通过了,截图规格校验失效" + exit 1 + fi + echo "截图规格演练通过:宽不足 / 超体积 / 假 webp 均被拦下" + + - name: 演练 6|投稿 PR 越界改代码必须失败(§7) + run: | + if HUB_PR_BODY='' \ + HUB_PR_CHANGED_FILES=$'src/data/projects/demo.yaml\nsrc/lib/project-schema.ts' \ + pnpm check:pr-scope; then + echo "::error::投稿 PR 越界改代码竟然放行了,变更范围校验失效" + exit 1 + fi + HUB_PR_BODY='' \ + HUB_PR_CHANGED_FILES='src/data/projects/demo.yaml' pnpm check:pr-scope + echo "变更范围演练通过:越界被拦、合规放行" + + submission-scope: + name: 投稿 PR 变更范围 + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + # 需要与目标分支的 merge-base 做三点 diff + fetch-depth: 0 + persist-credentials: false + + - uses: pnpm/action-setup@v6 + + - uses: actions/setup-node@v7 + with: + node-version-file: .nvmrc + cache: pnpm + + - run: pnpm install --frozen-lockfile + + - name: 投稿 PR 只允许改数据文件与截图(§7) + run: pnpm check:pr-scope + env: + HUB_PR_BODY: ${{ github.event.pull_request.body }} + HUB_PR_BASE_REF: ${{ github.base_ref }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..45bfd10 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,298 @@ +# 向 WorkerHub 投稿收录 + +WorkerHub(hub)是 Cloudflare Workers 生态的中文精选应用目录:官方自研项目 + 经收录把关的第三方开源项目,每个项目都标清部署方式、所需资源与验证等级。 + +这份文件是投稿规则的**唯一真源**:站点的 `/submit/` 页面在构建时直接引入本文件渲染,页面与本文不得分叉——要改规则,改这里,不要改页面。数据校验 CI 的每一条规则也都与本文一一对应(见第 8 节)。 + +- 站点主域名:`https://hub.oneboy.app` +- 仓库:`https://github.com/WorkerHub/workerhub.github.io` +- 投稿方式:**向本仓库提 Pull Request**(没有站内表单、没有后台、没有账号系统) +- 维护者联系方式:GitHub 组织页 + +--- + +## 1. 我们收录什么 + +**收录**:开源、可自部署在 Cloudflare Workers 或 Pages 上的应用/服务。你自己写的、你维护的、或你特别喜欢并愿意长期跟进的项目,都可以提。 + +**不收录**: + +- 没有明确开源许可证的项目(无 LICENSE 一律不收,不开例外); +- 只能在你自己服务器上跑、或需要 Cloudflare 之外的重型基础设施的项目; +- 「理论上能跑」但没有 wrangler/Pages 配置、没有成型部署文档的项目; +- 商业闭源产品、纯 API 转发壳、纯演示页(无实际可部署代码); +- 已归档或被证实无法部署且作者不维护的项目。 + +本站不是托管平台,不代跑任何人的项目,也不持有访客的 Cloudflare 凭证:部署入口一律指向 Cloudflare 官方 Deploy Button、目标仓库的 GitHub Actions 或其部署文档。 + +--- + +## 2. 收录门槛(五条,全部通过才可收录) + +投稿 PR 里按模板逐项勾选,并**为每一条附上证据链接**。CI 会机械校验其中可校验的部分,人工评审核验其余部分。 + +| # | 门槛 | 判定方式 | 你需要在 PR 里给出的证据 | +| --- | -------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | +| 1 | **开源且许可证明确** | 仓库根目录有 LICENSE 文件,且 GitHub 能识别出许可证类型 | 许可证文件链接(如 `.../blob/main/LICENSE`) | +| 2 | **真实可部署在 Cloudflare Workers 或 Pages** | 有 `wrangler.toml`/`wrangler.json(c)`、Pages 配置,或明确的部署文档;仅「理论上能跑」不算 | 配置文件路径 / 部署文档章节链接 | +| 3 | **近 12 个月内有代码更新** | 构建时自动字段 `pushed_at` 判定,无需你手写 | 无需提供(构建自动判定)。官方特批的老牌稳定项目在 PR 说明里写理由后可豁免 | +| 4 | **部署步骤可复现** | README 或文档含完整部署章节(资源创建 → 绑定 → 变量 → 部署 → 首次初始化) | 部署章节链接 + 你自己跑通的步骤摘要 | +| 5 | **免费层可跑,或付费要求写在明处** | 数据字段 `free_tier` / `pricing_note` 与仓库文档一致;免费层受限的具体限制要在 `pricing_note` 写明 | 文档中价格/免费层限制说明的链接 | + +补充说明: + +- 门槛 5 里「免费层可跑」指 Workers **Free** 计划下能完整跑通核心功能。只能部分跑通就填 `free_tier: partial` 并在 `pricing_note` 写清限制;必须付费才能跑就填 `no`,同样必须写 `pricing_note`。 +- 部署方式宁可**低标不高标**(见 4.3):仓库还没适配 Deploy Button 就别填 `deploy-button`。 + +--- + +## 3. 验证等级(三级) + +| 等级 | 徽章 | 含义 | 取得方式 | +| ---------- | ---- | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | +| **官方** | 金色 | WorkerHub 自研项目 | `source: official` 时自动取得(第三方条目不能用这一级) | +| **已验证** | 绿色 | 本站维护者按项目文档**实际完成过一次部署**,并留有记录 | 在数据 PR 中附 `verified_at`(验证日期)与 `verified_note_url`(记录链接:issue/PR/文档),经评审合入后生效 | +| **已收录** | 灰色 | 仅通过第 2 节五条门槛审核,**未做部署实测**(第三方条目的默认等级) | 无需额外字段:`tier: listed` | + +规则: + +- 第三方投稿**默认等级就是「已收录」**。请不要自己填 `tier: verified`——那是维护者实测后才能给的等级。 +- `tier: verified` 时 `verified_at` 与 `verified_note_url` **必填**,缺一项 CI 直接失败。 +- 「已收录」条目的详情页会固定显示一句声明,这是站点行为,不需要你在数据文件里写:**「本站尚未实测部署,部署体验以项目文档为准」**。 +- 「已验证」只代表**验证日期当天**的部署实测结论,不构成对项目后续版本、质量或安全性的担保。 + +--- + +## 4. 数据文件:位置与字段 + +### 4.1 位置与基本约定 + +一个项目一个文件:`src/data/projects/.yaml`。 + +- `slug` 只允许小写字母、数字与连字符(`^[a-z0-9-]+$`),**必须与文件名一致**(`cloud-mail.yaml` → `slug: cloud-mail`)。 +- `slug` 与 `repo` 都是全站唯一的:CI 同时按这两个维度查重,重复直接失败。 +- 数据文件是**唯一真源**,页面全部由它生成;不允许在别处写死项目信息。 + +### 4.2 字段说明 + +`?` 表示可选。写错字段名(拼写错误)会直接报错,不会静默丢弃。 + +| 字段 | 类型 | 必填 | 说明 | +| ------------------- | ----------- | -------- | --------------------------------------------------------------------------------------------- | +| `slug` | string | ✓ | 全站唯一,`^[a-z0-9-]+$`,与文件名一致 | +| `name` | string | ✓ | 展示名:用项目官方名,不自行翻译改名 | +| `repo` | string | ✓ | GitHub `owner/repo`;官方项目 owner 恒为 `WorkerHub`;**指向上游原仓库**,不要指向组织内 fork | +| `source` | enum | ✓ | `official` / `third-party` | +| `tagline_zh` | string | ✓ | 中文一句话介绍,≤40 字,人工撰写,不要机翻仓库描述 | +| `description_zh` | string | ✓ | 中文长介绍(详情页用),2–4 句(以 `。!?` 计句) | +| `description_en` | string | ? | 预留字段,v1 不渲染 | +| `features` | string[] | ✓ | 特性 3–5 条(详情页列表);卡片只显示 tagline | +| `category` | enum | ✓ | 主分类,取值见 4.4 | +| `tags` | string[] | ✓ | 自由标签 ≤5 个,不得重复 | +| `homepage` | string(url) | ? | 项目官网 / 在线演示站(官方项目填各自 `oneboy.app` 域名);**演示站不可达会被 CI 硬拦** | +| `docs_url` | string(url) | ? | 部署/使用文档链接;缺省时页面取仓库 README | +| `deploy` | object | ✓ | 部署信息,见 4.3 | +| `resources` | enum[] | ✓ | 部署所需 Cloudflare 资源,≥1 个且不重复,见 4.5 | +| `difficulty` | int | ✓ | 部署难度 1–3,见 4.6 | +| `free_tier` | enum | ✓ | `yes` / `partial` / `no` | +| `pricing_note` | string | 条件必填 | `free_tier != yes` 时**必填**,写清限制或价格 | +| `tier` | enum | ✓ | 验证等级 `official` / `verified` / `listed`,见第 3 节 | +| `verified_at` | date | 条件必填 | `tier: verified` 时必填,格式 `YYYY-MM-DD` | +| `verified_note_url` | string(url) | 条件必填 | `tier: verified` 时必填,验证记录链接 | +| `screenshot` | string | ? | `public/screenshots/.webp`;不填则走前端回退链,见第 6 节 | +| `featured` | bool | ? | 是否进首页精选推荐位(**仅第三方**,默认 `false`) | +| `added_at` | date | ✓ | 收录日期 `YYYY-MM-DD`,「最新收录」排序依据 | +| `status` | enum | ? | `active`(默认)/ `coming-soon`(仅官方预告位)/ `delisted`(下架保留记录) | + +**不要手写这些字段**(GitHub API 自动抓取,写进数据文件会直接报错):`stars` / `stargazers_count`、`forks` / `forks_count`、`language`、`license`、`pushed_at`、`archived`、`latest_release` / `release`、`open_graph_image`。 + +### 4.3 `deploy` 对象(部署方式) + +| `deploy.method` | 含义 | 详情页按钮 | +| ----------------- | -------------------------------------------- | ---------------------------------------------------------------------- | +| `deploy-button` | 仓库已适配 Cloudflare 官方 Deploy Button | 官方样式「Deploy to Cloudflare」,直达 `deploy.workers.cloudflare.com` | +| `git-integration` | 通过 Pages / Workers 的 Git 集成导入仓库部署 | 「导入到 Cloudflare」,链到文档对应章节 | +| `github-actions` | Fork 后启用仓库自带 Actions 部署 | 「Fork 后部署」,链到仓库与指南 | +| `wrangler` | 本地 `wrangler deploy` 手动部署 | 「部署指南」 | +| `docs-only` | 仅有文档说明,无成型部署路径 | 「查看仓库」,详情页明示「暂无成型一键部署路径」 | + +- `deploy.url`:Deploy Button 或部署入口,可空。`method: deploy-button` 时必填,且必须形如 `https://deploy.workers.cloudflare.com/?url=https://github.com//`;若仓库 README 的官方按钮带分支/路径参数,以 README 为准原样收录。 +- `deploy.guide_url`:部署指南链接,可空。 +- **宁可低标,不许高标**:判定以目标仓库**当前实际状态**为准,PR 里给出依据(按钮位置或工作流文件路径)。 +- `status: coming-soon`(预告位)的条目不得填 `deploy.url`。 + +### 4.4 分类(`category`,v1 定版) + +| 值 | 中文名 | 值 | 中文名 | +| -------------- | ------------ | -------------- | ---------- | +| `productivity` | 效率工具 | `notification` | 通知与消息 | +| `content` | 内容与博客 | `email` | 邮箱 | +| `files-media` | 文件与媒体 | `devops` | 开发与运维 | +| `data` | 数据与数据库 | `ai` | AI 应用 | +| `life` | 生活服务 | `other` | 其他 | + +新增分类不在投稿范围内(会失败):确实需要新分类的,先在本仓库开 issue 讨论,由维护者改规格。 + +### 4.5 资源(`resources`) + +| 值 | 含义 | 值 | 含义 | +| -------------- | ----------------------------------------------- | ----------------- | ------------------------- | +| `workers-only` | 仅 Worker,无额外绑定 | `pages` | 需要 Pages | +| `d1` | D1 数据库 | `kv` | KV 命名空间 | +| `r2` | R2 对象存储 | `durable-objects` | Durable Objects | +| `queues` | Queues 队列 | `cron` | Cron 定时触发 | +| `workers-ai` | Workers AI | `vectorize` | Vectorize 向量索引 | +| `hyperdrive` | Hyperdrive 数据库加速 | `email-workers` | Email Workers(收信绑定) | +| `external` | 依赖 Cloudflare 之外的外部服务(如 SMTP、支付) | | | + +用了 `external` 的,在 `description_zh` 或 `docs_url` 指向的文档里写清具体是什么外部服务。 + +### 4.6 难度(`difficulty`) + +| 值 | 说明 | +| --- | ---------------------------------------- | +| `1` | 快速:≤10 分钟、近零配置 | +| `2` | 标准:需自建 D1/KV 等绑定 + 少量环境变量 | +| `3` | 进阶:多绑定 / 多密钥 / 依赖外部服务 | + +--- + +## 5. 数据文件模板 + +复制下面这段到 `src/data/projects/.yaml`,把值改成你的项目(**删除用不到的可选字段,别留空值**)。模板本身通过 schema 校验,测试会守住这一点,因此它永远是可用的最新字段集。 + +```yaml +# WorkerHub 收录数据文件模板:文件名必须与 slug 一致(如 cloud-mail.yaml) +slug: your-project +name: Your Project +repo: your-org/your-project +source: third-party +tagline_zh: 中文一句话介绍,不超过四十字 +description_zh: 第一句说明它是做什么的。第二句说明部署形态与适用场景。 +features: + - 特性一:具体、可核验 + - 特性二 + - 特性三 +tags: + - 标签一 + - 标签二 +category: productivity +homepage: https://example.com +docs_url: https://github.com/your-org/your-project/blob/main/docs/deploy.md +deploy: + method: git-integration + guide_url: https://github.com/your-org/your-project/blob/main/docs/deploy.md +resources: + - d1 + - kv +difficulty: 2 +free_tier: yes +tier: listed +# screenshot: public/screenshots/your-project.webp # 可选,规格见第 6 节 +featured: false +added_at: 2026-10-26 +status: active +``` + +如果 `free_tier` 不是 `yes`,加上 `pricing_note`: + +```yaml +free_tier: partial +pricing_note: 免费层每日 10 万次请求,超过需 Workers Paid($5/月起)。 +``` + +如果你是替官方项目补录(维护者),`source: official`、`repo` 的 owner 必须是 `WorkerHub`、`tier: official`。 + +本地自检(可选,需要 Node 24 + pnpm): + +```bash +pnpm install +pnpm validate:data # schema、枚举、slug 与文件名一致、slug/repo 查重 +pnpm check:repos # repo 存在且为 public(调 GitHub API) +pnpm check:links # 外链可达性(官方与演示站链接失败会硬拦) +pnpm check:screenshots # 截图规格 +``` + +--- + +## 6. 截图(可选) + +- 路径固定 `public/screenshots/.webp`,**文件名必须与 slug 一致**。 +- 格式必须是 **webp**(把 png/jpg 改后缀不算,CI 会检测真实格式)。 +- **宽度 ≥1200px**(详情页按 1200px 宽出图,窄图会被拦)。 +- **体积 ≤300KB**(307200 字节)。 +- 压缩方式参考:`cwebp -q 82 -resize 1200 0 screenshot.png -o public/screenshots/.webp`。 +- 不提供截图完全可以:删掉 `screenshot` 字段即可,前端按「项目截图 → 仓库 Open Graph 图 → 分类着色首字图」回退,不会破图。 +- 请只提交**你自己项目的界面截图**,不要放商标、他人作品或不相关内容。 + +--- + +## 7. 投稿步骤 + +1. **Fork** 本仓库,从 `main` 拉一个分支(建议 `contrib/`)。 +2. **只新增/修改 `src/data/projects/.yaml`**(可选:`public/screenshots/.webp`)。投稿 PR 不许改代码、依赖、工作流、模板、他人条目——CI 会按投稿标记检查变更范围。 +3. **按 PR 模板逐项勾选**第 2 节五条门槛,并在每条的「证据」后填链接。 +4. 等 **CI** 跑完(校验项见第 8 节)。 +5. 等**人工评审**。评审只审三件事:项目值不值得收(质量与定位)、中文文案是否属实、部署方式与验证等级是否高标。 +6. 合并即上架(维护者合并后会构建发布)。 + +其他约定: + +- 一个 PR 一个项目,方便评审与回滚。 +- 更新既有条目(改名、迁移、部署方式变化、免费层变化)走同样的 PR 流程,改对应 YAML 即可。 +- 官方新项目上架也走同一流程的数据 PR,不开后门。 +- 不要手写 GitHub 自动字段(第 4.2 节末尾清单)。 +- 收录第三方项目时 `repo` 一律指向上游原仓库,不要指向任何 fork 副本(包括 WorkerHub 组织内用于跟踪的 fork)。 + +--- + +## 8. CI 会检查什么(硬拦 vs 仅警告) + +投稿 PR 与官方数据 PR 适用完全相同的校验管线。 + +| 检查项 | 规则 | 失败后果 | +| ---------------------------------------------------------- | ------------------ | ---------------------------------------------- | +| schema / 枚举 / 未知字段 / 手写自动字段 | 字段定义见第 4 节 | **失败**并点名文件与字段 | +| `slug` 与文件名一致 | 见 4.1 | **失败** | +| `slug` / `repo` 双维度查重 | 见 4.1 | **失败** | +| `repo` 真实存在且为 public | 调 GitHub API 核验 | **失败**(仓库不存在、私有、或无法核验需重跑) | +| `tier: verified` 的 `verified_at` + `verified_note_url` | 见第 3 节 | **失败** | +| `free_tier != yes` 时 `pricing_note` | 见 4.2 | **失败** | +| 外链可达性(`docs_url`、`deploy.url`、`deploy.guide_url`) | HTTP 探测 | **警告**(不硬拦,评审人人工确认) | +| 官方项目的全部外链、任何项目的 `homepage`(演示站) | HTTP 探测 | **失败** | +| 截图规格(webp、宽 ≥1200px、≤300KB) | 见第 6 节 | **失败** | +| 投稿 PR 变更范围 | 见第 7 节第 2 步 | **失败** | + +对应的本地命令:`pnpm validate:data`、`pnpm check:repos`、`pnpm check:links`、`pnpm check:screenshots`、`pnpm check:pr-scope`。 + +--- + +## 9. 状态维护、下架与作者异议 + +**自动检查(只标记,不自动下架)**:构建时若仓库已被 archive,或 `pushed_at` 距今超过 12 个月,卡片会自动加「长期未更新」标记,并在构建摘要中列出异常项目,供维护者判断。 + +**下架**(`status: delisted`)走人工数据 PR,情形包括: + +- 仓库被删除或转为私有; +- 许可证变更为闭源或不可核实; +- 被证实无法部署且作者不修复; +- 作者本人要求移除。 + +下架后条目保留记录但页面不再渲染入口(详情页返回真实 404),列表与「最新收录」也不再出现。 + +**作者异议通道**:如果你是被收录项目的作者,且不希望被收录、或认为条目信息有误(名称、简介、部署方式、许可证等),**在本仓库开 issue** 说明条目 slug 与诉求,维护者会处理: + +- 要求移除 → 按上架流程同样提数据 PR 下架,不设门槛、不需要理由; +- 信息有误 → 欢迎直接提修正 PR(同样只改 YAML)。 + +站点 `/about/` 与 `/submit/` 两个页面都会写明这条通道。 + +--- + +## 10. 责任与许可 + +- 第三方项目的**版权与责任归其作者**。本站的收录不构成对项目质量、安全性或商业适用性的担保。 +- 「已验证」仅代表验证日期当天的部署实测结论,项目后续版本的行为以项目自身文档为准。 +- 本站不代跑、不托管任何人的项目,也不持有访客的 Cloudflare 凭证。 +- 投稿即表示你确认所提交内容的准确性,并同意本站按上述规则展示该项目信息。 +- 本仓库代码与站点内容的许可见仓库 `LICENSE`;收录的第三方项目沿用其自身许可证。 diff --git a/README.md b/README.md index c68abfa..a0cc510 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Cloudflare Workers 生态的中文精选应用目录:官方自研项目 + 经 **本站是纯静态站点**:无后端、无数据库、无鉴权、无站点级 secret(SPEC v1.4 §0 明示例外项)。构建产物是纯静态 HTML,同时发布到主站 `hub.oneboy.app`(Cloudflare Pages)与镜像 `workerhub.github.io`(GitHub Pages),canonical 恒写主域名。 -> 本仓库当前处于 S1-A 阶段:脚手架 + 数据管线(schema 校验 + GitHub 自动字段抓取 + 缓存降级)。正式页面与组件、内容数据、投稿基建、双线部署分属后续子单,见文末「范围」。 +> 本仓库当前处于 S1-A + S2-B 阶段:脚手架、数据管线(schema 校验 + GitHub 自动字段抓取 + 缓存降级)、投稿基建(CONTRIBUTING / PR 模板 / 投稿数据校验)。正式页面与组件、内容数据、双线部署分属后续子单,见文末「范围」。 ## 技术栈(SPEC §8.1) @@ -20,6 +20,11 @@ pnpm dev # 本地开发(http://localhost:4321) pnpm build # 构建:读数据 → schema 校验 → 抓取/合并自动字段 → 输出 dist/ pnpm preview # 预览 dist/ pnpm validate:data # 只跑数据文件 schema 校验 +pnpm validate:submission # 投稿校验三项:repo 存在且 public / 外链可达性 / 截图规格(§7) +pnpm check:repos # 只跑 repo 核验 +pnpm check:links # 只跑外链可达性 +pnpm check:screenshots # 只跑截图规格 +pnpm check:pr-scope # 投稿 PR 变更范围(只允许数据文件与截图) pnpm fetch:meta # 只跑 GitHub 自动字段抓取 pnpm lint # astro check(类型检查)+ prettier --check pnpm format # prettier 自动格式化 @@ -89,6 +94,32 @@ HUB_PROJECTS_DIR=<放了一个坏文件的目录> pnpm build `tests/fixtures/projects-run/` 是演练夹具(指向两个真实 public 仓库),`tests/fixtures/projects/` 是 schema 夹具。两者都不是正式内容。 +## 投稿基建(SPEC §7) + +投稿 = 向本仓库提 PR,只新增/修改 `src/data/projects/.yaml`(及可选截图)。相关文件: + +| 文件 | 作用 | +| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| `CONTRIBUTING.md`(仓库根) | 收录门槛(五条)、字段说明、数据文件模板、验证等级、下架与异议通道。**与 `/submit/` 页同源**:页面构建时引入本文件,二者不得分叉 | +| `.github/PULL_REQUEST_TEMPLATE.md` | 逐项勾选五条门槛 + 证据链接 + 数据合规自查 + 变更范围声明 | +| `src/lib/submission-checks.ts` | repo 核验 / 外链可达性 / 截图规格的校验逻辑 | +| `src/lib/pr-scope.ts` | 投稿 PR 变更范围(只允许数据文件与截图) | + +投稿数据校验(`pnpm validate:submission`,CI 对投稿 PR 与官方数据 PR 同等适用): + +| 检查 | 失败后果 | +| -------------------------------------------------------------- | -------------------------------------------- | +| schema / 枚举 / 未知字段 / 手写自动字段 | 失败 | +| `slug` 与文件名一致、slug 与 repo 双维度查重 | 失败 | +| `repo` 真实存在且为 public(GitHub API) | 失败(不存在 / 私有 / 无法核验) | +| `tier=verified` 凭证书、`free_tier != yes` 时的 `pricing_note` | 失败 | +| 第三方外链(`docs_url` / `deploy.*`)不可达 | **警告**,评审人人工确认 | +| 官方项目全部外链、任何项目的 `homepage`(演示站)不可达 | 失败 | +| 截图(webp / 宽 ≥1200px / ≤300KB) | 失败 | +| 投稿 PR 改了数据文件与截图之外的文件 | 失败(PR 描述带 `hub-submission-pr` 标记时) | + +演练:`tests/fixtures/submission/` 是投稿校验夹具(不存在的 repo、不可达外链、不合规截图),CI 的 `drills` job 逐项验证「该拦的拦、该放的放」。 + ## 目录结构 ``` @@ -98,12 +129,15 @@ src/data/projects/ 项目数据文件(内容子单维护) src/data/cache/ GitHub 自动字段缓存 src/lib/project-schema.ts 数据字段/枚举定义(冻结契约) src/lib/validate-projects.ts 集合级校验(slug 与文件名一致、slug/repo 查重) +src/lib/submission-checks.ts 投稿校验(repo public / 外链可达性 / 截图规格) +src/lib/pr-scope.ts 投稿 PR 变更范围判定 src/lib/github-meta.ts 抓取、缓存、降级、异常清单 src/lib/projects.ts 页面侧取数入口(人工字段 + 自动字段合并、默认排序) src/lib/build-info.ts 版本号 / 构建时间 src/pages/index.astro 占位页(正式页面由 S2-A 替换) -scripts/ validate-data.ts / fetch-github-meta.ts +scripts/ validate-data.ts / validate-submission.ts / check-pr-scope.ts / fetch-github-meta.ts tests/ 单测 + 进程级集成测试 + 夹具 +.github/PULL_REQUEST_TEMPLATE.md 投稿 PR 模板(五条门槛逐项勾选 + 证据栏) .github/workflows/ci.yml 校验与演练(不含发布) ``` @@ -126,5 +160,6 @@ tests/ 单测 + 进程级集成测试 + 夹具 ## 范围(防止顺带扩大,SPEC §11) - 本单(S1-A):脚手架、数据管线(schema + 抓取 + 缓存降级)、能让 `pnpm build` 跑通的占位页、CI 校验与演练。 +- 本单(S2-B):`CONTRIBUTING.md`、PR 模板、投稿数据校验(repo / 外链 / 截图 / PR 变更范围)与对应演练;`/submit/` 页面的引入由 S2-A 负责。 - 不在本单:正式页面/组件与主题(S2-A)、官方与第三方内容数据(内容子单)、CONTRIBUTING 与 PR 模板、每日重建与双线发布(部署子单)、PR 合并与域名绑定(用户关口)。 - 本站不加后端、不加 D1/KV/DO/R2、不加登录鉴权、不引入任何 secret(SPEC §0)。 diff --git a/package.json b/package.json index 0e19146..9ed7cc9 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,11 @@ "build": "tsx scripts/fetch-github-meta.ts && astro build", "preview": "astro preview", "validate:data": "tsx scripts/validate-data.ts", + "validate:submission": "tsx scripts/validate-submission.ts", + "check:repos": "tsx scripts/validate-submission.ts --checks=repos", + "check:links": "tsx scripts/validate-submission.ts --checks=links", + "check:screenshots": "tsx scripts/validate-submission.ts --checks=screenshots", + "check:pr-scope": "tsx scripts/check-pr-scope.ts", "fetch:meta": "tsx scripts/fetch-github-meta.ts", "lint": "pnpm lint:types && pnpm lint:format", "format": "prettier --write .", @@ -29,6 +34,7 @@ "@astrojs/check": "^0.9.12", "@tailwindcss/vite": "^4.3.3", "@types/node": "^26.6.5", + "image-size": "^2.0.4", "prettier": "^3.6.2", "prettier-plugin-astro": "^1.1.2", "tailwindcss": "^4.3.3", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6cd9265..d32abcc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -27,6 +27,9 @@ importers: '@types/node': specifier: ^26.6.5 version: 26.6.5 + image-size: + specifier: ^2.0.4 + version: 2.0.4 prettier: specifier: ^3.6.2 version: 3.9.10 @@ -1195,6 +1198,11 @@ packages: http-cache-semantics@4.3.0: resolution: {integrity: sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA==} + image-size@2.0.4: + resolution: {integrity: sha512-QRUkFFsRV/6fuESxb9Vkq+a0LkSrgKXuc2NEqfikiXxxN/G3tjWt5EVUlMaImRBZRZK/jRBEbYvpPYZL8t08Zw==} + engines: {node: '>=18'} + hasBin: true + iron-webcrypto@1.2.1: resolution: {integrity: sha512-feOM6FaSr6rEABp/eDfVseKyTMDt+KGpeB35SkVn9Tyn0CqvVsY3EwI0v5i8nMHyJnzCIQf7nsy3p41TPkJZhg==} @@ -3042,6 +3050,8 @@ snapshots: http-cache-semantics@4.3.0: {} + image-size@2.0.4: {} + iron-webcrypto@1.2.1: {} is-docker@4.0.0: {} diff --git a/scripts/check-pr-scope.ts b/scripts/check-pr-scope.ts new file mode 100644 index 0000000..784e1b3 --- /dev/null +++ b/scripts/check-pr-scope.ts @@ -0,0 +1,73 @@ +#!/usr/bin/env tsx +/** + * 投稿 PR 变更范围校验 CLI(SPEC §7:投稿 PR 只改数据文件与截图,不许改代码)。 + * + * 在 GitHub Actions 里由 `.github/workflows/ci.yml` 的 `submission-scope` job 调用: + * 环境变量 HUB_PR_BODY PR 描述(github.event.pull_request.body) + * 环境变量 HUB_PR_BASE_REF PR 目标分支(github.base_ref) + * 本地复现: + * HUB_PR_BODY="$(cat pr.md)" HUB_PR_BASE_REF=main pnpm check:pr-scope + * 或直接给变更清单:HUB_PR_CHANGED_FILES=$'src/data/projects/x.yaml\nREADME.md' pnpm check:pr-scope + * + * 退出码: + * 0 非投稿 PR(无标记,跳过),或投稿 PR 只改了允许的文件 + * 1 投稿 PR 改了允许范围外的文件 + */ +import { execFileSync } from 'node:child_process'; +import { + SUBMISSION_PR_MARKER, + classifySubmissionPaths, + isSubmissionPr, +} from '../src/lib/pr-scope.js'; + +const body = process.env.HUB_PR_BODY ?? ''; +const changedFilesEnv = process.env.HUB_PR_CHANGED_FILES; +const baseRef = process.env.HUB_PR_BASE_REF; + +if (!isSubmissionPr(body)) { + console.log( + `非投稿 PR(描述里没有 ${SUBMISSION_PR_MARKER} 标记):跳过投稿范围校验。` + + '该标记由 .github/PULL_REQUEST_TEMPLATE.md 自带,只有外部投稿 PR 会命中。', + ); + process.exit(0); +} + +let changedFiles: string[]; +if (typeof changedFilesEnv === 'string' && changedFilesEnv.length > 0) { + changedFiles = changedFilesEnv.split('\n'); +} else if (baseRef) { + // 三点 diff:与目标分支的 merge-base 比较,避免把目标分支的新提交算进本 PR + const output = execFileSync( + 'git', + ['diff', '--name-only', '--no-renames', `origin/${baseRef}...HEAD`], + { encoding: 'utf8' }, + ); + changedFiles = output.split('\n'); +} else { + console.error('缺少 HUB_PR_BASE_REF 或 HUB_PR_CHANGED_FILES,无法确定本 PR 的变更文件'); + process.exit(2); +} + +const { outOfScope, inScope } = classifySubmissionPaths(changedFiles); + +console.log(`投稿 PR 变更文件:${inScope.length + outOfScope.length} 个`); +for (const path of inScope) console.log(` ✓ ${path}`); +for (const path of outOfScope) console.log(` ✗ ${path}`); + +if (inScope.length === 0) { + console.error( + '\n投稿 PR 没有新增或修改任何 src/data/projects/.yaml:请确认分支是否正确(数据文件与截图是唯一允许的变更)。', + ); + process.exit(1); +} + +if (outOfScope.length > 0) { + console.error( + '\n投稿 PR 只允许新增/修改 src/data/projects/.yaml 与 public/screenshots/.webp(SPEC §7)。', + ); + console.error('以下文件超出投稿范围,请从本 PR 撤出(代码/依赖/工作流/模板的改动请另开 PR):'); + for (const path of outOfScope) console.error(` ✗ ${path}`); + process.exit(1); +} + +console.log('\n投稿范围校验通过:只改了数据文件与截图。'); diff --git a/scripts/validate-submission.ts b/scripts/validate-submission.ts new file mode 100644 index 0000000..9ab47b0 --- /dev/null +++ b/scripts/validate-submission.ts @@ -0,0 +1,110 @@ +#!/usr/bin/env tsx +/** + * 投稿数据校验 CLI(SPEC §7「CI 自动校验」的联网部分)。 + * + * 用法: + * pnpm validate:submission # 三项全跑:repo 核验 + 外链可达性 + 截图规格 + * pnpm check:repos # 只做 repo「存在且 public」核验 + * pnpm check:links # 只做外链可达性 + * pnpm check:screenshots # 只做截图规格 + * pnpm validate:submission --fail-on-warnings # 把外链警告也升级为失败(维护者本地复核用) + * + * 环境变量(均可缺省,生产 CI 无需额外配置): + * HUB_PROJECTS_DIR 数据文件目录(默认 src/data/projects) + * HUB_SCREENSHOTS_DIR 截图目录(默认 public/screenshots) + * GITHUB_API_BASE GitHub API 基址(演练时指向不可达地址) + * GITHUB_TOKEN CI 工作流自带只读 token(可选;不要求任何 PAT 入仓) + * HUB_LINK_TIMEOUT_MS 单条外链探测超时(默认 8000) + * + * 退出码: + * 0 没有硬拦问题(允许存在 warning) + * 1 有硬拦问题(§7:repo 不存在/私有、官方与演示站外链失败、截图不合规…) + * 传入 --fail-on-warnings 时,warning 也会导致退出码 1 + */ +import { resolve } from 'node:path'; +import { PROJECTS_DIR, GITHUB_API_BASE, GITHUB_TOKEN } from '../src/lib/build-config.js'; +import { loadProjects } from '../src/lib/load-projects.js'; +import { + DEFAULT_LINK_TIMEOUT_MS, + checkLinks, + checkRepos, + checkScreenshots, + formatFindings, + summarize, + type CheckName, + type Finding, +} from '../src/lib/submission-checks.js'; + +const ALL_CHECKS: CheckName[] = ['repos', 'links', 'screenshots']; + +const parseArgs = (argv: string[]): { checks: CheckName[]; failOnWarnings: boolean } => { + let checks = ALL_CHECKS; + let failOnWarnings = false; + for (const arg of argv) { + if (arg === '--fail-on-warnings') { + failOnWarnings = true; + continue; + } + if (arg.startsWith('--checks=')) { + const requested = arg + .slice('--checks='.length) + .split(',') + .map((name) => name.trim()) + .filter(Boolean); + const unknown = requested.filter((name) => !ALL_CHECKS.includes(name as CheckName)); + if (unknown.length > 0) { + console.error(`未知检查项:${unknown.join(', ')}(可选:${ALL_CHECKS.join(' / ')})`); + process.exit(2); + } + checks = requested as CheckName[]; + } + } + return { checks, failOnWarnings }; +}; + +const screenshotsDir = resolve(process.env.HUB_SCREENSHOTS_DIR ?? 'public/screenshots'); +const timeoutMs = Number(process.env.HUB_LINK_TIMEOUT_MS ?? DEFAULT_LINK_TIMEOUT_MS); +const { checks, failOnWarnings } = parseArgs(process.argv.slice(2)); + +const loaded = loadProjects(PROJECTS_DIR); +if (!loaded.ok) { + console.error(loaded.message); + process.exit(1); +} +console.log(loaded.message); +console.log(`检查项:${checks.join(' / ')}`); + +const findings: Finding[] = []; +for (const check of checks) { + if (check === 'repos') { + findings.push( + ...(await checkRepos(loaded.projects, { + apiBase: GITHUB_API_BASE, + token: GITHUB_TOKEN, + timeoutMs, + })), + ); + } else if (check === 'links') { + findings.push(...(await checkLinks(loaded.projects, { timeoutMs }))); + } else { + findings.push(...checkScreenshots(loaded.projects, { screenshotsDir })); + } +} + +const summary = summarize(findings); +const failed = summary.errors.length > 0 || (failOnWarnings && summary.warnings.length > 0); + +if (findings.length > 0) { + console.log( + `\n投稿校验结果(硬拦 ${summary.errors.length} 项 / 警告 ${summary.warnings.length} 项):`, + ); + console.log(formatFindings(summary)); +} else { + console.log('投稿校验通过:repo 均存在且 public、外链可达、截图合规'); +} + +if (summary.warnings.length > 0) { + console.log('\n警告不阻断 CI(§7:外链失败给 warning,由评审人人工确认)'); +} + +process.exit(failed ? 1 : 0); diff --git a/src/lib/pr-scope.ts b/src/lib/pr-scope.ts new file mode 100644 index 0000000..9d24ecc --- /dev/null +++ b/src/lib/pr-scope.ts @@ -0,0 +1,45 @@ +/** + * 投稿 PR 变更范围校验(SPEC §7:投稿 PR 只新增/修改 `src/data/projects/.yaml` + * 及可选截图,「不许在投稿 PR 中改代码」)。 + * + * 生效条件:PR 描述里带投稿标记 `` + * (`.github/PULL_REQUEST_TEMPLATE.md` 自带该标记,投稿者无需自己写)。 + * 维护者自己的数据 PR / 代码 PR 不写标记即不受此限制——这条规则是为外部投稿者划边界, + * 不是给仓库常规开发加锁。 + * + * 纯函数在这里(便于单测),git 调用在 scripts/check-pr-scope.ts。 + */ + +/** 投稿标记:PR 描述中**单独占一行**时生效(模板把标记放在首行) */ +export const SUBMISSION_PR_MARKER = ''; + +/** 允许的变更路径:数据文件与截图(§7 + §4.1 固定路径) */ +export const ALLOWED_SUBMISSION_PATHS = [ + /^src\/data\/projects\/[a-z0-9-]+\.ya?ml$/, + /^public\/screenshots\/[a-z0-9-]+\.webp$/, +] as const; + +export const isSubmissionPr = (body: string | undefined | null): boolean => + typeof body === 'string' && + body.split(/\r?\n/).some((line) => line.trim().toLowerCase() === SUBMISSION_PR_MARKER); + +export const isAllowedSubmissionPath = (path: string): boolean => + ALLOWED_SUBMISSION_PATHS.some((pattern) => pattern.test(path)); + +export interface ScopeResult { + /** 不在允许范围内的文件 */ + outOfScope: string[]; + /** 允许范围内的文件 */ + inScope: string[]; +} + +/** 拆分变更文件列表,区分允许 / 越界 */ +export function classifySubmissionPaths(paths: string[]): ScopeResult { + const outOfScope: string[] = []; + const inScope: string[] = []; + for (const path of paths.map((value) => value.trim()).filter(Boolean)) { + if (isAllowedSubmissionPath(path)) inScope.push(path); + else outOfScope.push(path); + } + return { outOfScope, inScope }; +} diff --git a/src/lib/submission-checks.ts b/src/lib/submission-checks.ts new file mode 100644 index 0000000..fc91d81 --- /dev/null +++ b/src/lib/submission-checks.ts @@ -0,0 +1,445 @@ +/** + * 投稿数据的三类必检项(SPEC §7「CI 自动校验」,投稿 PR 与官方数据 PR 同等适用): + * + * 1. `repo` 真实存在且为 public(GitHub REST API 核验) + * 2. 外链可达性(homepage / docs_url / deploy.url / deploy.guide_url) + * 3. 截图规格(webp、宽 ≥1200px、体积 ≤300KB) + * + * 严重级别严格照抄 §7 原文: + * - `repo` 不存在 / 私有 / 无法核验 → **硬拦**(error) + * - 外链失败 → **默认只警告**,由评审人人工确认; + * 但「官方项目的全部外链」与「任何项目的演示站(homepage)」失败 → **硬拦**(error) + * - 截图不合规 → **硬拦**(error) + * + * 校验函数全部是「注入 fetch / 注入目录」的纯逻辑,磁盘与网络都在边界上,便于单测与演练。 + */ +import { existsSync, readFileSync, statSync } from 'node:fs'; +import { basename, join } from 'node:path'; +import { imageSize } from 'image-size'; +import type { ProjectInput } from './project-schema.js'; + +/** §7 截图规格:webp、宽 ≥1200px、体积 ≤300KB */ +export const SCREENSHOT_MIN_WIDTH = 1200; +export const SCREENSHOT_MAX_BYTES = 300 * 1024; +export const SCREENSHOT_REQUIRED_EXT = '.webp'; + +export const DEFAULT_LINK_TIMEOUT_MS = 8_000; +export const DEFAULT_LINK_CONCURRENCY = 6; +export const DEFAULT_API_BASE = 'https://api.github.com'; +const USER_AGENT = 'workerhub-hub-ci (+https://hub.oneboy.app)'; + +export type CheckName = 'repos' | 'links' | 'screenshots'; +export type Severity = 'error' | 'warning'; + +/** 一条检查结论:硬拦(error)会让 CI 失败,警告(warning)只打印 */ +export interface Finding { + check: CheckName; + severity: Severity; + /** 项目 slug(用于日志定位) */ + slug: string; + /** 数据文件名 */ + file: string; + /** 出问题的目标:仓库 / 链接 / 截图路径 */ + target: string; + message: string; +} + +/** 校验输入:至少要有 slug 与人工字段 */ +export interface CheckTarget { + slug: string; + file: string; + data: ProjectInput; +} + +export interface HttpOptions { + /** 便于测试注入 */ + fetchImpl?: typeof fetch; + timeoutMs?: number; + /** 额外重试次数(默认 1:瞬时抖动不该误伤投稿者) */ + retries?: number; + /** GitHub 只读 token(CI 用工作流自带 GITHUB_TOKEN) */ + token?: string; + apiBase?: string; +} + +const errorFinding = ( + check: CheckName, + target: CheckTarget, + targetName: string, + message: string, +): Finding => ({ + check, + severity: 'error', + slug: target.slug, + file: target.file, + target: targetName, + message, +}); + +const warningFinding = ( + check: CheckName, + target: CheckTarget, + targetName: string, + message: string, +): Finding => ({ + check, + severity: 'warning', + slug: target.slug, + file: target.file, + target: targetName, + message, +}); + +const sleep = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); + +/** 带超时与重试的请求;返回响应或抛出最后一次错误 */ +async function requestWithRetry( + url: string, + init: RequestInit, + options: HttpOptions, +): Promise { + const fetchImpl = options.fetchImpl ?? fetch; + const timeoutMs = options.timeoutMs ?? DEFAULT_LINK_TIMEOUT_MS; + const retries = options.retries ?? 1; + let lastError: unknown; + + for (let attempt = 0; attempt <= retries; attempt += 1) { + if (attempt > 0) await sleep(300 * attempt); + try { + const response = await fetchImpl(url, { + ...init, + signal: AbortSignal.timeout(timeoutMs), + }); + // 5xx 视作可重试的瞬时故障;4xx 是确定性结论 + if (response.status >= 500 && attempt < retries) { + lastError = new Error(`HTTP ${response.status}`); + continue; + } + return response; + } catch (error) { + lastError = error; + } + } + throw lastError instanceof Error ? lastError : new Error(String(lastError)); +} + +// --------------------------------------------------------------------------- +// 1. repo 真实存在且为 public(§7) +// --------------------------------------------------------------------------- + +export type RepoAccessKind = 'ok' | 'not-found' | 'private' | 'infra'; + +export interface RepoAccessResult { + repo: string; + kind: RepoAccessKind; + detail: string; +} + +/** + * 核验单个仓库「存在且 public」。 + * + * - 200 且 `private: false` → ok + * - 200 且 `private: true`(有 token 时私有库会返回 200)→ private + * - 404 → not-found(无权限或不存在;两者对投稿者都是同一个结论:必须换成公开仓库) + * - 其它(网络/超时/限流/5xx/403)→ infra:**同样硬拦**,但提示「无法核验,请重跑 CI」, + * 因为这项是必检门槛,静默放行等于取消门槛。 + */ +export async function checkRepoAccess( + repo: string, + options: HttpOptions = {}, +): Promise { + const apiBase = options.apiBase ?? DEFAULT_API_BASE; + const headers: Record = { + accept: 'application/vnd.github+json', + 'x-github-api-version': '2022-11-28', + 'user-agent': USER_AGENT, + }; + if (options.token) headers.authorization = `Bearer ${options.token}`; + + let response: Response; + try { + response = await requestWithRetry(`${apiBase}/repos/${repo}`, { headers }, options); + } catch (error) { + return { + repo, + kind: 'infra', + detail: `GitHub API 不可达(${(error as Error).message}),无法核验仓库是否存在且公开,请重跑 CI`, + }; + } + + if (response.status === 404) { + return { repo, kind: 'not-found', detail: 'GitHub 返回 404:仓库不存在或不是 public' }; + } + if (response.status === 403 || response.status === 429) { + return { + repo, + kind: 'infra', + detail: `GitHub API 拒绝访问(HTTP ${response.status},可能限流),请重跑 CI`, + }; + } + if (!response.ok) { + return { repo, kind: 'infra', detail: `GitHub API 返回 HTTP ${response.status},请重跑 CI` }; + } + + let body: { private?: unknown; full_name?: unknown }; + try { + body = (await response.json()) as typeof body; + } catch { + return { repo, kind: 'infra', detail: 'GitHub API 响应无法解析,请重跑 CI' }; + } + + if (body.private === true) { + return { repo, kind: 'private', detail: '仓库是 private:收录只接受 public 仓库' }; + } + const resolved = typeof body.full_name === 'string' ? body.full_name : repo; + return { repo, kind: 'ok', detail: `存在且为 public(${resolved})` }; +} + +/** 逐仓库核验(同一 repo 只查一次),返回 findings */ +export async function checkRepos( + targets: CheckTarget[], + options: HttpOptions = {}, +): Promise { + const byRepo = new Map(); + for (const target of targets) { + const list = byRepo.get(target.data.repo) ?? []; + list.push(target); + byRepo.set(target.data.repo, list); + } + + const findings: Finding[] = []; + for (const [repo, owners] of byRepo) { + const result = await checkRepoAccess(repo, options); + if (result.kind === 'ok') continue; + for (const owner of owners) { + findings.push(errorFinding('repos', owner, repo, `repo 核验失败:${result.detail}`)); + } + } + return findings; +} + +// --------------------------------------------------------------------------- +// 2. 外链可达性(§7) +// --------------------------------------------------------------------------- + +export type LinkField = 'homepage' | 'docs_url' | 'deploy.url' | 'deploy.guide_url'; + +export interface ProjectLink { + field: LinkField; + url: string; +} + +/** 该项目的全部外链(§7 列举:homepage / docs / deploy url) */ +export function collectLinks(data: ProjectInput): ProjectLink[] { + const links: ProjectLink[] = []; + if (data.homepage) links.push({ field: 'homepage', url: data.homepage }); + if (data.docs_url) links.push({ field: 'docs_url', url: data.docs_url }); + if (data.deploy.url) links.push({ field: 'deploy.url', url: data.deploy.url }); + if (data.deploy.guide_url) links.push({ field: 'deploy.guide_url', url: data.deploy.guide_url }); + return links; +} + +/** + * 外链失败时的严重级别(§7 原文): + * 「失败给 warning 不硬拦(评审人人工确认);官方项目与演示站链接失败则硬拦」。 + * 即:`source=official` 的任何外链、以及任何项目的 `homepage`(官网/演示站)→ error。 + */ +export const linkFailureSeverity = (data: ProjectInput, field: LinkField): Severity => + data.source === 'official' || field === 'homepage' ? 'error' : 'warning'; + +export interface LinkProbeResult { + url: string; + ok: boolean; + detail: string; +} + +/** 探测单条外链是否可达(2xx/3xx 视为可达;跟随重定向) */ +export async function probeUrl(url: string, options: HttpOptions = {}): Promise { + const headers: Record = { + accept: 'text/html,application/xhtml+xml,application/json;q=0.8,*/*;q=0.5', + 'user-agent': USER_AGENT, + }; + let response: Response; + try { + response = await requestWithRetry(url, { headers, redirect: 'follow', method: 'GET' }, options); + } catch (error) { + return { url, ok: false, detail: `请求失败:${(error as Error).message}` }; + } + + if (response.status >= 200 && response.status < 400) { + return { url, ok: true, detail: `HTTP ${response.status}` }; + } + return { url, ok: false, detail: `HTTP ${response.status}` }; +} + +/** 逐项目逐链接探测(并发受限),按 §7 分级产出 findings */ +export async function checkLinks( + targets: CheckTarget[], + options: HttpOptions & { concurrency?: number } = {}, +): Promise { + const concurrency = Math.max(1, options.concurrency ?? DEFAULT_LINK_CONCURRENCY); + const jobs: { target: CheckTarget; link: ProjectLink }[] = []; + for (const target of targets) { + for (const link of collectLinks(target.data)) jobs.push({ target, link }); + } + + const findings: Finding[] = []; + for (let index = 0; index < jobs.length; index += concurrency) { + const batch = jobs.slice(index, index + concurrency); + const results = await Promise.all( + batch.map(async ({ target, link }) => { + const probe = await probeUrl(link.url, options); + return { target, link, probe }; + }), + ); + for (const { target, link, probe } of results) { + if (probe.ok) continue; + const severity = linkFailureSeverity(target.data, link.field); + const message = `外链不可达(${link.field},${probe.detail})${ + severity === 'warning' ? ':投稿者可稍后修正,评审人需人工确认链接是否长期失效' : '' + }`; + findings.push( + severity === 'error' + ? errorFinding('links', target, link.url, message) + : warningFinding('links', target, link.url, message), + ); + } + } + return findings; +} + +// --------------------------------------------------------------------------- +// 3. 截图规格(§7) +// --------------------------------------------------------------------------- + +/** 截图的磁盘路径:数据文件里写路径,这里只取文件名拼到截图目录(§4.1 固定 public/screenshots/) */ +export const screenshotFileName = (data: ProjectInput): string => basename(data.screenshot ?? ''); + +/** + * 校验已填写 `screenshot` 的项目: + * - 文件名必须与 slug 一致(`public/screenshots/.webp`) + * - 文件必须存在 + * - 必须是 webp(不是改后缀的 png/jpg) + * - 宽 ≥1200px + * - 体积 ≤300KB + * 未填写 `screenshot` 的项目自动走前端回退链(§8.3),这里不报错。 + */ +export function checkScreenshots( + targets: CheckTarget[], + options: { screenshotsDir: string }, +): Finding[] { + const findings: Finding[] = []; + + for (const target of targets) { + const { data } = target; + if (!data.screenshot) continue; + + const fileName = screenshotFileName(data); + const expected = `${target.slug}${SCREENSHOT_REQUIRED_EXT}`; + + if (fileName !== expected) { + findings.push( + errorFinding( + 'screenshots', + target, + data.screenshot, + `截图文件名必须与 slug 一致:应为 public/screenshots/${expected},实际为 ${fileName}`, + ), + ); + } + + const filePath = join(options.screenshotsDir, fileName); + if (!existsSync(filePath)) { + findings.push( + errorFinding( + 'screenshots', + target, + data.screenshot, + `截图文件不存在:${filePath}(若暂不提供截图,请删除数据文件里的 screenshot 字段,前端会自动走回退链)`, + ), + ); + continue; + } + + const bytes = readFileSync(filePath); + const size = statSync(filePath).size; + + let detected: { width?: number; height?: number; type?: string }; + try { + detected = imageSize(bytes); + } catch { + findings.push( + errorFinding('screenshots', target, data.screenshot, '截图无法解析:不是有效的图片文件'), + ); + continue; + } + + if (detected.type !== 'webp') { + findings.push( + errorFinding( + 'screenshots', + target, + data.screenshot, + `截图必须是 webp(检测到 ${detected.type ?? '未知格式'});改后缀不算转换`, + ), + ); + } + + const width = detected.width ?? 0; + if (width < SCREENSHOT_MIN_WIDTH) { + findings.push( + errorFinding( + 'screenshots', + target, + data.screenshot, + `截图宽度不足:${width}px < ${SCREENSHOT_MIN_WIDTH}px(详情页按 1200px 宽出图)`, + ), + ); + } + + if (size > SCREENSHOT_MAX_BYTES) { + findings.push( + errorFinding( + 'screenshots', + target, + data.screenshot, + `截图体积超标:${(size / 1024).toFixed(1)}KB > ${SCREENSHOT_MAX_BYTES / 1024}KB(用 cwebp -q 82 -resize 1200 0 压缩)`, + ), + ); + } + } + + return findings; +} + +// --------------------------------------------------------------------------- +// 汇总与输出 +// --------------------------------------------------------------------------- + +export interface CheckSummary { + errors: Finding[]; + warnings: Finding[]; +} + +export function summarize(findings: Finding[]): CheckSummary { + return { + errors: findings.filter((finding) => finding.severity === 'error'), + warnings: findings.filter((finding) => finding.severity === 'warning'), + }; +} + +/** 渲染成可直接贴进 CI 日志的文本 */ +export function formatFindings(summary: CheckSummary): string { + const lines: string[] = []; + for (const finding of summary.errors) { + lines.push( + ` ✗ [${finding.check}] ${finding.file}(${finding.slug})→ ${finding.target}:${finding.message}`, + ); + } + for (const finding of summary.warnings) { + lines.push( + ` ⚠ [${finding.check}] ${finding.file}(${finding.slug})→ ${finding.target}:${finding.message}`, + ); + } + return lines.join('\n'); +} diff --git a/tests/contributing-docs.test.ts b/tests/contributing-docs.test.ts new file mode 100644 index 0000000..6f1cc80 --- /dev/null +++ b/tests/contributing-docs.test.ts @@ -0,0 +1,152 @@ +/** + * 投稿文档守卫(SPEC §7 验收 1、2): + * - `CONTRIBUTING.md` 必须在仓库根,且覆盖 §4.1 字段、§4.2/§5/§6 枚举、§6.1 五条门槛、§6.3 下架与异议通道 + * - 文档里的数据文件模板必须真的能过 schema(防止文档与 schema 分叉) + * - `/submit/` 页同源契约必须写进文件(S2-A 构建时引入本文件) + * - PR 模板必须逐项对应五条门槛并含证据栏 + */ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { parse as parseYaml } from 'yaml'; +import { + CATEGORIES, + DEPLOY_METHODS, + FREE_TIERS, + RESOURCES, + TIERS, + projectSchema, +} from '../src/lib/project-schema.js'; +import { SUBMISSION_PR_MARKER } from '../src/lib/pr-scope.js'; + +const ROOT = process.cwd(); +const contributing = readFileSync(join(ROOT, 'CONTRIBUTING.md'), 'utf8'); +const prTemplate = readFileSync(join(ROOT, '.github', 'PULL_REQUEST_TEMPLATE.md'), 'utf8'); + +/** §4.1 全部人工字段 */ +const MANUAL_FIELDS = [ + 'slug', + 'name', + 'repo', + 'source', + 'tagline_zh', + 'description_zh', + 'description_en', + 'features', + 'category', + 'tags', + 'homepage', + 'docs_url', + 'deploy', + 'resources', + 'difficulty', + 'free_tier', + 'pricing_note', + 'tier', + 'verified_at', + 'verified_note_url', + 'screenshot', + 'featured', + 'added_at', + 'status', +]; + +/** §6.1 五条门槛的关键措辞 */ +const GATES = [ + '开源且许可证明确', + '真实可部署在 Cloudflare Workers 或 Pages', + '近 12 个月内有代码更新', + '部署步骤可复现', + '免费层可跑', +]; + +test('§7 CONTRIBUTING.md 位于仓库根', () => { + assert.ok(contributing.length > 2000, 'CONTRIBUTING.md 内容过短,可能被误删或截断'); +}); + +test('§7 CONTRIBUTING.md 覆盖 §4.1 全部人工字段', () => { + for (const field of MANUAL_FIELDS) { + assert.ok(contributing.includes(`\`${field}\``), `CONTRIBUTING 缺字段说明:${field}`); + } +}); + +test('§7 CONTRIBUTING.md 覆盖 §4.2 / §4.5 / §5 / §6 全部枚举值', () => { + for (const value of [...CATEGORIES, ...RESOURCES, ...DEPLOY_METHODS, ...FREE_TIERS, ...TIERS]) { + assert.ok(contributing.includes(value), `CONTRIBUTING 缺枚举值:${value}`); + } +}); + +test('§7 CONTRIBUTING.md 覆盖 §6.1 五条门槛与证据要求', () => { + for (const gate of GATES) { + assert.ok(contributing.includes(gate), `CONTRIBUTING 缺门槛:${gate}`); + } + assert.match(contributing, /证据/); +}); + +test('§7 CONTRIBUTING.md 写明禁止手写自动字段与投稿 PR 只改数据文件', () => { + for (const field of ['stargazers_count', 'forks_count', 'pushed_at', 'archived']) { + assert.ok(contributing.includes(field), `CONTRIBUTING 缺自动字段禁写清单:${field}`); + } + assert.match(contributing, /只新增\/修改 `src\/data\/projects\/\.yaml`/); +}); + +test('§7 CONTRIBUTING.md 写明截图三条硬规格', () => { + assert.match(contributing, /webp/); + assert.match(contributing, /1200px/); + assert.match(contributing, /300KB/); +}); + +test('§7 CONTRIBUTING.md 写明验证等级与「已收录」固定声明', () => { + assert.match(contributing, /已验证/); + assert.match(contributing, /本站尚未实测部署,部署体验以项目文档为准/); + assert.match(contributing, /verified_note_url/); +}); + +test('§6.3 CONTRIBUTING.md 写下架通道与作者异议通道', () => { + assert.match(contributing, /delisted/); + assert.match(contributing, /下架/); + assert.match(contributing, /在本仓库开 issue/); +}); + +test('§7 CONTRIBUTING.md 声明与 /submit/ 页同源、不得分叉(S2-A 对接契约)', () => { + assert.match(contributing, /`\/submit\/`/); + assert.match(contributing, /不得分叉/); +}); + +test('§7 CONTRIBUTING.md 的 YAML 模板能通过 schema(文档与 schema 不分叉)', () => { + const blocks = [...contributing.matchAll(/```yaml\n([\s\S]*?)```/g)].map((match) => match[1]!); + const templates = blocks.filter((block) => /^slug:/m.test(block)); + assert.ok(templates.length >= 1, 'CONTRIBUTING 里找不到可复制的数据文件模板'); + for (const template of templates) { + const parsed = projectSchema.safeParse(parseYaml(template)); + assert.ok( + parsed.success, + `模板不符合 schema:${parsed.success ? '' : JSON.stringify(parsed.error.issues, null, 2)}\n${template}`, + ); + } +}); + +test('§7 PR 模板存在、带投稿标记,并逐项对应五条门槛与证据栏', () => { + assert.ok(prTemplate.includes(SUBMISSION_PR_MARKER), 'PR 模板缺少投稿标记'); + for (const gate of GATES) { + assert.ok(prTemplate.includes(gate), `PR 模板缺门槛勾选项:${gate}`); + } + const gateBoxes = prTemplate.match(/- \[ \] \*{0,2}\d\./g); + assert.equal(gateBoxes?.length ?? 0, 5, 'PR 模板应恰好有 5 条门槛勾选框'); + const evidenceLines = prTemplate.match(/证据/g) ?? []; + assert.ok(evidenceLines.length >= 5, 'PR 模板每条门槛都应留证据栏'); +}); + +test('§7 PR 模板含数据合规自查(自动字段 / 变更范围 / 截图 / 验证等级)', () => { + assert.match(prTemplate, /自动字段/); + assert.match(prTemplate, /src\/data\/projects\/\.yaml/); + assert.match(prTemplate, /webp/); + assert.match(prTemplate, /listed/); + assert.match(prTemplate, /verified_note_url/); +}); + +test('§7 PR 模板提示异议通道与免责声明', () => { + assert.match(prTemplate, /issue/); + assert.match(prTemplate, /版权与责任归项目作者/); +}); diff --git a/tests/fixtures/screenshots/fixture-fake.webp b/tests/fixtures/screenshots/fixture-fake.webp new file mode 100644 index 0000000..147ef8d Binary files /dev/null and b/tests/fixtures/screenshots/fixture-fake.webp differ diff --git a/tests/fixtures/screenshots/fixture-narrow-800.webp b/tests/fixtures/screenshots/fixture-narrow-800.webp new file mode 100644 index 0000000..2cfd658 Binary files /dev/null and b/tests/fixtures/screenshots/fixture-narrow-800.webp differ diff --git a/tests/fixtures/screenshots/fixture-ok-1200.webp b/tests/fixtures/screenshots/fixture-ok-1200.webp new file mode 100644 index 0000000..06e5bcc Binary files /dev/null and b/tests/fixtures/screenshots/fixture-ok-1200.webp differ diff --git a/tests/fixtures/screenshots/fixture-oversize.webp b/tests/fixtures/screenshots/fixture-oversize.webp new file mode 100644 index 0000000..1183e18 Binary files /dev/null and b/tests/fixtures/screenshots/fixture-oversize.webp differ diff --git a/tests/fixtures/submission/links/official/drill-official-broken-home.yaml b/tests/fixtures/submission/links/official/drill-official-broken-home.yaml new file mode 100644 index 0000000..2c08eef --- /dev/null +++ b/tests/fixtures/submission/links/official/drill-official-broken-home.yaml @@ -0,0 +1,23 @@ +# 演练夹具:官方项目的 homepage(演示站)不可达 → §7 要求 CI 硬拦 +slug: drill-official-broken-home +name: Drill Official Broken Home +repo: WorkerHub/hub-drill-official +source: official +tagline_zh: 演练用官方条目,演示站地址不可达。 +description_zh: 第一条说明句。第二条说明句。 +features: + - 特性一 + - 特性二 + - 特性三 +tags: + - drill +category: notification +homepage: http://127.0.0.1:9/demo +deploy: + method: docs-only +resources: + - d1 +difficulty: 2 +free_tier: yes +tier: official +added_at: 2026-10-26 diff --git a/tests/fixtures/submission/links/third-party/drill-broken-docs.yaml b/tests/fixtures/submission/links/third-party/drill-broken-docs.yaml new file mode 100644 index 0000000..d742699 --- /dev/null +++ b/tests/fixtures/submission/links/third-party/drill-broken-docs.yaml @@ -0,0 +1,25 @@ +# 演练夹具:第三方条目的 docs_url 不可达 → 只警告,CI 仍通过(§7) +# 127.0.0.1:9 是必然拒绝连接的地址,用于稳定复现「外链探测失败」。 +slug: drill-broken-docs +name: Drill Broken Docs +repo: WorkerHub/workerhub.github.io +source: third-party +tagline_zh: 演练用条目,文档链接指向不可达地址。 +description_zh: 第一条说明句。第二条说明句。 +features: + - 特性一 + - 特性二 + - 特性三 +tags: + - drill +category: devops +docs_url: http://127.0.0.1:9/drill/guide +deploy: + method: wrangler + guide_url: http://127.0.0.1:9/drill/deploy +resources: + - workers-only +difficulty: 1 +free_tier: yes +tier: listed +added_at: 2026-10-26 diff --git a/tests/fixtures/submission/repos/drill-missing-repo.yaml b/tests/fixtures/submission/repos/drill-missing-repo.yaml new file mode 100644 index 0000000..f9aad6f --- /dev/null +++ b/tests/fixtures/submission/repos/drill-missing-repo.yaml @@ -0,0 +1,22 @@ +# 演练夹具:repo 指向一个不存在的仓库 → §7 要求 CI 硬拦 +slug: drill-missing-repo +name: Drill Missing Repo +repo: WorkerHub/hub-drill-repo-does-not-exist +source: third-party +tagline_zh: 演练用条目,仓库在 GitHub 上并不存在。 +description_zh: 第一条说明句。第二条说明句。 +features: + - 特性一 + - 特性二 + - 特性三 +tags: + - drill +category: devops +deploy: + method: wrangler +resources: + - workers-only +difficulty: 1 +free_tier: yes +tier: listed +added_at: 2026-10-26 diff --git a/tests/fixtures/submission/screenshots/fixture-fake.yaml b/tests/fixtures/submission/screenshots/fixture-fake.yaml new file mode 100644 index 0000000..1ef0c32 --- /dev/null +++ b/tests/fixtures/submission/screenshots/fixture-fake.yaml @@ -0,0 +1,23 @@ +# 演练夹具:扩展名是 .webp,内容其实是 PNG → 硬拦(改后缀不算转换) +slug: fixture-fake +name: Fixture Fake Webp +repo: WorkerHub/hub-drill-shots-fake +source: third-party +tagline_zh: 演练用条目,截图后缀与真实格式不符。 +description_zh: 第一条说明句。第二条说明句。 +features: + - 特性一 + - 特性二 + - 特性三 +tags: + - drill +category: productivity +deploy: + method: wrangler +resources: + - workers-only +difficulty: 1 +free_tier: yes +tier: listed +screenshot: public/screenshots/fixture-fake.webp +added_at: 2026-10-26 diff --git a/tests/fixtures/submission/screenshots/fixture-narrow-800.yaml b/tests/fixtures/submission/screenshots/fixture-narrow-800.yaml new file mode 100644 index 0000000..4e86384 --- /dev/null +++ b/tests/fixtures/submission/screenshots/fixture-narrow-800.yaml @@ -0,0 +1,23 @@ +# 演练夹具:截图宽度不足 1200px → 硬拦 +slug: fixture-narrow-800 +name: Fixture Narrow Screenshot +repo: WorkerHub/hub-drill-shots-narrow +source: third-party +tagline_zh: 演练用条目,截图只有八百像素宽。 +description_zh: 第一条说明句。第二条说明句。 +features: + - 特性一 + - 特性二 + - 特性三 +tags: + - drill +category: productivity +deploy: + method: wrangler +resources: + - workers-only +difficulty: 1 +free_tier: yes +tier: listed +screenshot: public/screenshots/fixture-narrow-800.webp +added_at: 2026-10-26 diff --git a/tests/fixtures/submission/screenshots/fixture-ok-1200.yaml b/tests/fixtures/submission/screenshots/fixture-ok-1200.yaml new file mode 100644 index 0000000..d92fab7 --- /dev/null +++ b/tests/fixtures/submission/screenshots/fixture-ok-1200.yaml @@ -0,0 +1,23 @@ +# 演练夹具:截图合规(1200px 宽 webp,体积远低于 300KB) +slug: fixture-ok-1200 +name: Fixture Ok Screenshot +repo: WorkerHub/hub-drill-shots-ok +source: third-party +tagline_zh: 演练用条目,截图规格完全合规。 +description_zh: 第一条说明句。第二条说明句。 +features: + - 特性一 + - 特性二 + - 特性三 +tags: + - drill +category: productivity +deploy: + method: wrangler +resources: + - workers-only +difficulty: 1 +free_tier: yes +tier: listed +screenshot: public/screenshots/fixture-ok-1200.webp +added_at: 2026-10-26 diff --git a/tests/fixtures/submission/screenshots/fixture-oversize.yaml b/tests/fixtures/submission/screenshots/fixture-oversize.yaml new file mode 100644 index 0000000..d7a861b --- /dev/null +++ b/tests/fixtures/submission/screenshots/fixture-oversize.yaml @@ -0,0 +1,23 @@ +# 演练夹具:截图体积超过 300KB → 硬拦 +slug: fixture-oversize +name: Fixture Oversize Screenshot +repo: WorkerHub/hub-drill-shots-oversize +source: third-party +tagline_zh: 演练用条目,截图体积超过三百千字节。 +description_zh: 第一条说明句。第二条说明句。 +features: + - 特性一 + - 特性二 + - 特性三 +tags: + - drill +category: productivity +deploy: + method: wrangler +resources: + - workers-only +difficulty: 1 +free_tier: yes +tier: listed +screenshot: public/screenshots/fixture-oversize.webp +added_at: 2026-10-26 diff --git a/tests/pr-scope.test.ts b/tests/pr-scope.test.ts new file mode 100644 index 0000000..08fad31 --- /dev/null +++ b/tests/pr-scope.test.ts @@ -0,0 +1,69 @@ +/** + * 投稿 PR 变更范围逻辑单测(SPEC §7:投稿 PR 只改数据文件与截图,不许改代码)。 + */ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { + SUBMISSION_PR_MARKER, + classifySubmissionPaths, + isAllowedSubmissionPath, + isSubmissionPr, +} from '../src/lib/pr-scope.js'; + +test('§7 带投稿标记的 PR 视为投稿 PR', () => { + assert.equal(isSubmissionPr(`## 说明\n\n${SUBMISSION_PR_MARKER}\n\n- [x] 开源`), true); + assert.equal(isSubmissionPr(`${SUBMISSION_PR_MARKER}`), true); + assert.equal(isSubmissionPr(` ${SUBMISSION_PR_MARKER} `), true); + assert.equal(isSubmissionPr(`无标记的代码 PR`), false); + assert.equal(isSubmissionPr(undefined), false); + assert.equal(isSubmissionPr(null), false); +}); + +test('§7 仅提及投稿标记(行内引用、说明又一个标记)不触发投稿范围检查', () => { + // 维护者在 PR 里解释模板时会把标记写进行内代码/句子,不应因此被当成投稿 PR + assert.equal(isSubmissionPr(`首行 \`${SUBMISSION_PR_MARKER}\` 是投稿标记`), false); + assert.equal(isSubmissionPr(`标记写法:${SUBMISSION_PR_MARKER} 放在首行`), false); + assert.equal(isSubmissionPr(` 行内追加说明`), false); +}); + +test('§7 投稿允许的路径:数据文件与截图', () => { + assert.equal(isAllowedSubmissionPath('src/data/projects/cloud-mail.yaml'), true); + assert.equal(isAllowedSubmissionPath('src/data/projects/edge-ever.yml'), true); + assert.equal(isAllowedSubmissionPath('public/screenshots/cloud-mail.webp'), true); +}); + +test('§7 投稿越界路径:代码 / 依赖 / 工作流 / 模板 / 他人目录', () => { + for (const path of [ + 'README.md', + 'CONTRIBUTING.md', + 'package.json', + 'pnpm-lock.yaml', + '.github/workflows/ci.yml', + '.github/PULL_REQUEST_TEMPLATE.md', + 'src/lib/project-schema.ts', + 'src/pages/index.astro', + 'scripts/validate-data.ts', + 'src/data/cache/github-meta.json', + 'src/data/projects/nested/deep.yaml', + 'src/data/projects/Cloud-Mail.yaml', + 'public/screenshots/cloud-mail.png', + 'public/screenshots/nested/cloud-mail.webp', + '../src/data/projects/evil.yaml', + ]) { + assert.equal(isAllowedSubmissionPath(path), false, `${path} 不应被允许`); + } +}); + +test('§7 拆分变更清单时保留允许项并点名越界项', () => { + const result = classifySubmissionPaths([ + 'src/data/projects/cloud-mail.yaml', + 'public/screenshots/cloud-mail.webp', + 'scripts/validate-data.ts', + '', + ]); + assert.deepEqual(result.inScope, [ + 'src/data/projects/cloud-mail.yaml', + 'public/screenshots/cloud-mail.webp', + ]); + assert.deepEqual(result.outOfScope, ['scripts/validate-data.ts']); +}); diff --git a/tests/submission-checks.test.ts b/tests/submission-checks.test.ts new file mode 100644 index 0000000..bc43db5 --- /dev/null +++ b/tests/submission-checks.test.ts @@ -0,0 +1,346 @@ +/** + * 投稿校验逻辑单测(SPEC §7):repo 核验 / 外链可达性与分级 / 截图规格。 + * 网络一律用注入的 fetchImpl,不打真实网络;截图用仓库内夹具文件。 + */ +import assert from 'node:assert/strict'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { projectSchema, type ProjectInput } from '../src/lib/project-schema.js'; +import { + SCREENSHOT_MAX_BYTES, + checkLinks, + checkRepoAccess, + checkRepos, + checkScreenshots, + collectLinks, + formatFindings, + linkFailureSeverity, + probeUrl, + screenshotFileName, + summarize, + type CheckTarget, +} from '../src/lib/submission-checks.js'; + +const SCREENSHOTS_DIR = join(process.cwd(), 'tests', 'fixtures', 'screenshots'); + +const jsonResponse = (body: unknown, status = 200): Response => + new Response(JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json' }, + }); + +const baseProject = (overrides: Record = {}): ProjectInput => + projectSchema.parse({ + slug: 'demo-project', + name: 'Demo Project', + repo: 'maillab/cloud-mail', + source: 'third-party', + tagline_zh: '中文一句话介绍用于校验流程是否合法', + description_zh: '第一条说明句。第二条说明句。', + features: ['特性一', '特性二', '特性三'], + tags: ['demo'], + category: 'email', + deploy: { method: 'wrangler' }, + resources: ['d1'], + difficulty: 2, + free_tier: 'yes', + tier: 'listed', + added_at: '2026-10-26', + ...overrides, + }); + +const target = (overrides: Record = {}): CheckTarget => ({ + slug: String(overrides.slug ?? 'demo-project'), + file: `${String(overrides.slug ?? 'demo-project')}.yaml`, + data: baseProject(overrides), +}); + +// --------------------------------------------------------------------------- +// repo 核验 +// --------------------------------------------------------------------------- + +test('§7 public 仓库 → ok', async () => { + const result = await checkRepoAccess('maillab/cloud-mail', { + fetchImpl: async () => jsonResponse({ full_name: 'maillab/cloud-mail', private: false }), + }); + assert.equal(result.kind, 'ok'); + assert.match(result.detail, /public/); +}); + +test('§7 私有仓库(有 token 时返回 200 + private:true)→ private', async () => { + const result = await checkRepoAccess('someone/private-repo', { + fetchImpl: async () => jsonResponse({ full_name: 'someone/private-repo', private: true }), + }); + assert.equal(result.kind, 'private'); + assert.match(result.detail, /private/); +}); + +test('§7 仓库不存在(404)→ not-found', async () => { + const result = await checkRepoAccess('WorkerHub/no-such-repo', { + fetchImpl: async () => jsonResponse({ message: 'Not Found' }, 404), + }); + assert.equal(result.kind, 'not-found'); + assert.match(result.detail, /404/); +}); + +test('§7 GitHub API 不可达 → infra(无法核验也要硬拦,提示重跑)', async () => { + const result = await checkRepoAccess('maillab/cloud-mail', { + retries: 0, + fetchImpl: async () => { + throw new TypeError('fetch failed'); + }, + }); + assert.equal(result.kind, 'infra'); + assert.match(result.detail, /重跑 CI/); +}); + +test('§7 限流(403)→ infra,不误判成仓库不存在', async () => { + const result = await checkRepoAccess('maillab/cloud-mail', { + fetchImpl: async () => jsonResponse({ message: 'rate limited' }, 403), + }); + assert.equal(result.kind, 'infra'); + assert.match(result.detail, /403/); +}); + +test('瞬时 5xx 会重试一次后成功', async () => { + let calls = 0; + const result = await checkRepoAccess('maillab/cloud-mail', { + fetchImpl: async () => { + calls += 1; + return calls === 1 + ? jsonResponse({ message: 'boom' }, 502) + : jsonResponse({ full_name: 'maillab/cloud-mail', private: false }); + }, + }); + assert.equal(result.kind, 'ok'); + assert.equal(calls, 2); +}); + +test('§7 同一 repo 只查一次,错误按条目分别报告', async () => { + let calls = 0; + const findings = await checkRepos( + [ + target({ slug: 'one', repo: 'WorkerHub/missing' }), + target({ slug: 'two', repo: 'WorkerHub/missing' }), + ], + { + fetchImpl: async () => { + calls += 1; + return jsonResponse({ message: 'Not Found' }, 404); + }, + }, + ); + assert.equal(calls, 1); + assert.equal(findings.length, 2); + assert.ok(findings.every((finding) => finding.severity === 'error')); + assert.ok(findings.every((finding) => finding.check === 'repos')); +}); + +test('repo 全部通过时不产出 findings', async () => { + const findings = await checkRepos([target()], { + fetchImpl: async () => jsonResponse({ full_name: 'maillab/cloud-mail', private: false }), + }); + assert.deepEqual(findings, []); +}); + +// --------------------------------------------------------------------------- +// 外链可达性与严重级别 +// --------------------------------------------------------------------------- + +test('§7 外链分级:官方项目全部硬拦、任何项目的演示站(homepage)硬拦、其余仅警告', () => { + const thirdParty = baseProject(); + assert.equal(linkFailureSeverity(thirdParty, 'docs_url'), 'warning'); + assert.equal(linkFailureSeverity(thirdParty, 'deploy.url'), 'warning'); + assert.equal(linkFailureSeverity(thirdParty, 'deploy.guide_url'), 'warning'); + assert.equal(linkFailureSeverity(thirdParty, 'homepage'), 'error'); + + const official = baseProject({ + source: 'official', + repo: 'WorkerHub/eNotify', + tier: 'official', + }); + assert.equal(linkFailureSeverity(official, 'docs_url'), 'error'); + assert.equal(linkFailureSeverity(official, 'homepage'), 'error'); +}); + +test('§7 只收集实际填写的字段(含 deploy.url / guide_url)', () => { + const links = collectLinks( + baseProject({ + homepage: 'https://example.com', + docs_url: 'https://example.com/docs', + deploy: { + method: 'deploy-button', + url: 'https://deploy.workers.cloudflare.com/?url=https://github.com/a/b', + guide_url: 'https://example.com/guide', + }, + }), + ); + assert.deepEqual( + links.map((link) => link.field), + ['homepage', 'docs_url', 'deploy.url', 'deploy.guide_url'], + ); + assert.deepEqual(collectLinks(baseProject()), []); +}); + +test('probeUrl:2xx 视为可达,404 视为不可达', async () => { + const ok = await probeUrl('https://example.com', { + fetchImpl: async () => new Response('ok', { status: 200 }), + }); + assert.equal(ok.ok, true); + + const missing = await probeUrl('https://example.com/gone', { + fetchImpl: async () => new Response('nope', { status: 404 }), + }); + assert.equal(missing.ok, false); + assert.match(missing.detail, /404/); +}); + +test('§7 第三方外链失败 → warning(不阻断 CI)', async () => { + const findings = await checkLinks( + [ + target({ + docs_url: 'https://broken.example.com/docs', + deploy: { method: 'wrangler', guide_url: 'https://broken.example.com/guide' }, + }), + ], + { + fetchImpl: async () => new Response('down', { status: 503 }), + retries: 0, + }, + ); + // docs_url 与 deploy.guide_url 各一条,均为警告 + assert.equal(findings.length, 2); + assert.ok(findings.every((finding) => finding.severity === 'warning')); + assert.equal(summarize(findings).errors.length, 0); +}); + +test('§7 官方项目 / 演示站链接失败 → error(硬拦)', async () => { + const findings = await checkLinks( + [ + target({ slug: 'demo-official', homepage: 'https://demo.example.com' }), + target({ + slug: 'demo-official-2', + repo: 'WorkerHub/eNotify', + source: 'official', + tier: 'official', + docs_url: 'https://docs.example.com', + homepage: undefined, + }), + ], + { + fetchImpl: async () => new Response('down', { status: 500 }), + retries: 0, + }, + ); + assert.equal(findings.length, 2); + assert.ok(findings.every((finding) => finding.severity === 'error')); +}); + +// --------------------------------------------------------------------------- +// 截图规格 +// --------------------------------------------------------------------------- + +test('§7 截图合规(1200px webp / ≤300KB)→ 无 findings', () => { + const findings = checkScreenshots( + [target({ screenshot: 'public/screenshots/fixture-ok-1200.webp', slug: 'fixture-ok-1200' })], + { + screenshotsDir: SCREENSHOTS_DIR, + }, + ); + assert.deepEqual(findings, []); +}); + +test('§7 未填 screenshot 的条目走前端回退链,不报错', () => { + assert.deepEqual(checkScreenshots([target()], { screenshotsDir: SCREENSHOTS_DIR }), []); +}); + +test('§7 截图宽度不足 1200px → error 并给出实际宽度', () => { + const findings = checkScreenshots( + [ + target({ + slug: 'fixture-narrow-800', + screenshot: 'public/screenshots/fixture-narrow-800.webp', + }), + ], + { screenshotsDir: SCREENSHOTS_DIR }, + ); + assert.equal(findings.length, 1); + assert.equal(findings[0]!.severity, 'error'); + assert.match(findings[0]!.message, /800px/); +}); + +test('§7 截图体积超过 300KB → error', () => { + const findings = checkScreenshots( + [target({ slug: 'fixture-oversize', screenshot: 'public/screenshots/fixture-oversize.webp' })], + { screenshotsDir: SCREENSHOTS_DIR }, + ); + assert.equal(findings.length, 1); + assert.match(findings[0]!.message, new RegExp(`${SCREENSHOT_MAX_BYTES / 1024}KB`)); +}); + +test('§7 改后缀的 PNG 不算 webp → error', () => { + const findings = checkScreenshots( + [target({ slug: 'fixture-fake', screenshot: 'public/screenshots/fixture-fake.webp' })], + { screenshotsDir: SCREENSHOTS_DIR }, + ); + assert.equal(findings.length, 1); + assert.match(findings[0]!.message, /webp/); + assert.match(findings[0]!.message, /png/); +}); + +test('§7 截图文件缺失 → error 并提示可删除字段走回退链', () => { + const findings = checkScreenshots( + [target({ slug: 'ghost', screenshot: 'public/screenshots/ghost.webp' })], + { screenshotsDir: SCREENSHOTS_DIR }, + ); + assert.equal(findings.length, 1); + assert.match(findings[0]!.message, /不存在/); + assert.match(findings[0]!.message, /回退链/); +}); + +test('§7 截图文件名与 slug 不一致 → error', () => { + const findings = checkScreenshots( + [target({ slug: 'wrong-name', screenshot: 'public/screenshots/fixture-ok-1200.webp' })], + { screenshotsDir: SCREENSHOTS_DIR }, + ); + assert.equal(findings.length, 1); + assert.match(findings[0]!.message, /wrong-name\.webp/); +}); + +test('screenshotFileName 只取文件名(忽略数据文件里的目录写法)', () => { + assert.equal(screenshotFileName(baseProject({ screenshot: '/screenshots/a.webp' })), 'a.webp'); + assert.equal( + screenshotFileName(baseProject({ screenshot: 'public/screenshots/b.webp' })), + 'b.webp', + ); +}); + +// --------------------------------------------------------------------------- +// 汇总输出 +// --------------------------------------------------------------------------- + +test('汇总区分硬拦与警告,并可渲染成 CI 日志', () => { + const summary = summarize([ + { + check: 'repos', + severity: 'error', + slug: 'a', + file: 'a.yaml', + target: 'WorkerHub/a', + message: '仓库不存在', + }, + { + check: 'links', + severity: 'warning', + slug: 'b', + file: 'b.yaml', + target: 'https://x.example.com', + message: '外链不可达', + }, + ]); + assert.equal(summary.errors.length, 1); + assert.equal(summary.warnings.length, 1); + const text = formatFindings(summary); + assert.match(text, /✗ \[repos\] a\.yaml(a)/); + assert.match(text, /⚠ \[links\] b\.yaml(b)/); +}); diff --git a/tests/submission-cli.test.ts b/tests/submission-cli.test.ts new file mode 100644 index 0000000..71911f3 --- /dev/null +++ b/tests/submission-cli.test.ts @@ -0,0 +1,87 @@ +/** + * 投稿校验 CLI 的进程级测试(SPEC §7 验收 3:故意提交违规数据 → CI 明确失败并指出原因)。 + * 全部走真实 `tsx scripts/validate-submission.ts` 进程,只把网络与目录换成夹具/不可达地址。 + */ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { join } from 'node:path'; +import { test } from 'node:test'; + +const ROOT = process.cwd(); +const UNREACHABLE = 'http://127.0.0.1:9'; +const FIXTURES = join(ROOT, 'tests', 'fixtures'); + +interface RunResult { + status: number | null; + output: string; +} + +const run = (args: string[], env: Record = {}): RunResult => { + const result = spawnSync( + process.execPath, + ['--import', 'tsx', 'scripts/validate-submission.ts', ...args], + { + cwd: ROOT, + encoding: 'utf8', + env: { ...process.env, GITHUB_TOKEN: '', ...env }, + }, + ); + return { status: result.status, output: `${result.stdout ?? ''}${result.stderr ?? ''}` }; +}; + +test('§7 截图不合规 → CLI 失败并逐条点名原因(宽不足 / 超体积 / 假 webp)', () => { + const result = run(['--checks=screenshots'], { + HUB_PROJECTS_DIR: join(FIXTURES, 'submission', 'screenshots'), + HUB_SCREENSHOTS_DIR: join(FIXTURES, 'screenshots'), + }); + assert.equal(result.status, 1); + assert.match(result.output, /宽度不足:800px/); + assert.match(result.output, /体积超标/); + assert.match(result.output, /检测到 png/); + // 合规的那条不应被点名 + assert.doesNotMatch(result.output, /fixture-ok-1200\.yaml(fixture-ok-1200)/); +}); + +test('§7 第三方外链失败 → 警告不阻断(退出码 0)', () => { + const result = run(['--checks=links'], { + HUB_PROJECTS_DIR: join(FIXTURES, 'submission', 'links', 'third-party'), + }); + assert.equal(result.status, 0, result.output); + assert.match(result.output, /警告 2 项/); + assert.match(result.output, /docs_url/); +}); + +test('§7 官方 / 演示站外链失败 → CLI 失败(硬拦)', () => { + const result = run(['--checks=links'], { + HUB_PROJECTS_DIR: join(FIXTURES, 'submission', 'links', 'official'), + }); + assert.equal(result.status, 1, result.output); + assert.match(result.output, /homepage/); +}); + +test('§7 GitHub API 不可达 → repo 核验失败(无法核验也硬拦并提示重跑)', () => { + const result = run(['--checks=repos'], { + HUB_PROJECTS_DIR: join(FIXTURES, 'submission', 'repos'), + GITHUB_API_BASE: UNREACHABLE, + HUB_LINK_TIMEOUT_MS: '1000', + }); + assert.equal(result.status, 1); + assert.match(result.output, /repo 核验失败/); + assert.match(result.output, /重跑 CI/); +}); + +test('§7 --fail-on-warnings 把外链警告升级为失败(维护者本地复核用)', () => { + const result = run(['--checks=links', '--fail-on-warnings'], { + HUB_PROJECTS_DIR: join(FIXTURES, 'submission', 'links', 'third-party'), + }); + assert.equal(result.status, 1); + assert.match(result.output, /警告 2 项/); +}); + +test('未知检查项 → 退出码 2(参数错误,不误报成数据错误)', () => { + const result = run(['--checks=nope'], { + HUB_PROJECTS_DIR: join(FIXTURES, 'submission', 'repos'), + }); + assert.equal(result.status, 2); + assert.match(result.output, /未知检查项/); +});