AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
fix: simplify Workers Builds token setup
yomacc14d692c2d1
diff --git a/.env.local.example b/.env.local.exampleindex d09ee0b8..4999ede8 100644--- a/.env.local.example+++ b/.env.local.example@@ -23,18 +23,6 @@ CLOUDFLARE_API_TOKEN=# It is used only by `bun run deploy:builds:setup` and is never sent to the Worker.EDGE_EVER_BUILDS_API_TOKEN=-# Optional Workers Builds build-token UUID. Set this only when the Cloudflare-# account has multiple build tokens and setup cannot choose one automatically.-# The selected build token must be able to apply D1 migrations and deploy Workers.-EDGE_EVER_BUILDS_BUILD_TOKEN_UUID=--# Optional: set this only for a Git-integrated Cloudflare Pages project.-# `bun run deploy:builds:setup` then limits its Git builds to apps/site/* plus-# shared root dependency files. The User API Token also needs Account ->-# Cloudflare Pages -> Edit. Direct Upload projects use their deploy workflow's-# path filters instead, so leave this empty for those projects.-EDGE_EVER_PAGES_PROJECT_NAME=-# Worker service name.# Defaults to the `edgeever` Cloudflare Worker.EDGE_EVER_WORKER_NAME=edgeeverdiff --git a/docs/agent-deploy-cloudflare.md b/docs/agent-deploy-cloudflare.mdindex 3d86ffb7..f64c4129 100644--- a/docs/agent-deploy-cloudflare.md+++ b/docs/agent-deploy-cloudflare.md@@ -1,100 +1,74 @@# AI Agent Cloudflare Deployment-This document is the deployment contract for AI agents. If a user asks an agent to deploy EdgeEver from a GitHub URL to Cloudflare, follow this runbook before asking the user for anything.+Use this runbook when a user asks an AI agent to deploy EdgeEver from a GitHub repository to Cloudflare.-## Agent Rules+## Rules-- Treat deployment as two required phases: use `bun run deploy:setup`, `bun run deploy:doctor`, and `bun run deploy` only for the initial installation; then run `bun run deploy:builds:setup` so all routine updates use Cloudflare Workers Builds.-- Do not hard-code a personal Worker name, D1 database ID, R2 bucket name, account ID, API token, or domain in source files.-- Use `.env.local` for local/private deployment values. It is git-ignored.-- If the Cloudflare MCP or Cloudflare plugin is available, it may be used to inspect or create resources. If not, use Wrangler through the scripts in this repo.-- Ask the user only for values that cannot be inferred or generated safely, such as Cloudflare authorization or custom domain ownership. The default first-login credentials are `admin` / `admin123`, so a custom password is optional.+- Use local deployment only for the first installation or emergency recovery. Connect Cloudflare Workers Builds after the first deployment.+- Keep account IDs, resource names, API tokens, domains, and passwords in the git-ignored `.env.local`; never hard-code or commit them.+- Prefer the repository's deployment scripts. Ask the user only for authorization, domain ownership, or other information that cannot be inferred safely.+- Do not configure a separate GitHub Actions deployment for the Worker.-## Standard Flow+## Runbook-1. Clone the repository and enter it.+1. Prepare the repository:```shgit clone <repo-url>cd edgeever- ```--2. Install dependencies.-- ```shbun install```-3. Ensure Cloudflare authentication.+2. Verify Cloudflare access:```shbunx wrangler whoami```- If this fails, ask the user to finish Cloudflare login or provide a suitable API token. Do not continue deployment until this works.+ If authentication fails and cannot be completed in the browser, ask the user to authorize Cloudflare before continuing.-4. Prepare deployment resources and `.env.local`.+3. Initialize the deployment. Use the default first login (`admin` / `admin123`):```shbun run deploy:setup```- This uses `admin` / `admin123`. If the user explicitly provided another plaintext password, use:+ If the user supplied another password, run this instead:```shEDGE_EVER_PASSWORD='<first-login-password>' bun run deploy:setup```-5. Check the deployment inputs.+ Then check and deploy:```shbun run deploy:doctor- ```-- Fix every `fail` result before deploying.--6. Deploy.-- ```shbun run deploy```- This builds the web app, applies remote D1 migrations, deploys the Worker, and uploads `EDGE_EVER_AUTH_PASSWORD` as a Worker Secret. Existing `EDGE_EVER_AUTH_PASSWORD_HASH` configurations remain supported and take precedence when both exist.+ Fix every `deploy:doctor` failure before deploying.-7. Verify the result.-- Use the Worker URL from Wrangler output, then check:+4. Verify the URL reported by Wrangler:```shcurl -I https://<worker-url>/curl https://<worker-url>/api/openapi.json```- Open the site and log in with the configured credentials (`admin` / `admin123` by default). Then create an MCP token from the in-app MCP settings.+ Open the site and confirm that login succeeds.-8. Connect Cloudflare Workers Builds.+5. Enable automatic updates:```shbun run deploy:builds:setup```- Follow [Cloudflare Workers Builds](cloudflare-workers-builds.md) for any GitHub authorization, User API Token, or build-token prompt. Complete browser authorization when possible. Do not add a GitHub Actions Worker deployment.--## Blocking Conditions--Stop and ask the user only when:+ Follow [Cloudflare Workers Builds](cloudflare-workers-builds.md) only when the command requests authorization or an API token.-- Cloudflare authentication is missing and the agent cannot open or complete login.-- The requested custom domain is not available in the Cloudflare account.-- Resource creation fails because of account limits, permissions, billing, or conflicting names that cannot be resolved by choosing a new name.+## Stop and Ask the User-## Final User Response+Stop only when Cloudflare authorization cannot be completed, a requested custom domain is unavailable, or account permissions, limits, billing, or an unresolvable resource-name conflict prevents deployment.-After deployment, report:+## Final Response-- deployed URL-- login username-- whether the default password or a user-provided override was used-- where to create the EdgeEver MCP token in the app-- confirmation that Workers Builds is connected and that future `main` pushes automatically migrate and deploy-- any custom domain or Cloudflare DNS step that remains+Report the deployed URL, initial login, Workers Builds status, and any remaining user action. Confirm that future pushes to `main` automatically deploy the instance.diff --git a/docs/cloudflare-workers-builds.md b/docs/cloudflare-workers-builds.mdindex 05c12202..7d20ef13 100644--- a/docs/cloudflare-workers-builds.md+++ b/docs/cloudflare-workers-builds.md@@ -1,112 +1,46 @@# Cloudflare Workers Builds-EdgeEver uses Cloudflare Workers Builds for routine deployments. Connect each EdgeEver Worker to the `main` branch of its repository once; every later push, including a GitHub **Sync fork**, then builds, migrates, and deploys that instance automatically.+Cloudflare Workers Builds deploys EdgeEver whenever `main` changes, including after GitHub **Sync fork**. Use local `bun run deploy` only for the first installation or emergency recovery.-The same deployment commands are used for the official instances and every fork. Local `bun run deploy` remains the first-installation and emergency-recovery path.+## Setup-## Connect an Instance--First create the instance resources and perform its first deployment as described in the [manual deployment guide](manual-deploy.md). Then use the setup command:+Complete the [first deployment](manual-deploy.md), then run:```shbun run deploy:builds:setup```-It reads the fork's `origin` remote plus `.env.local`, then idempotently creates or updates the repository connection, production trigger, build commands, build cache, watch paths, and Build Variables/Secrets. On its first successful run it also starts a build of `main`, verifying the complete automated path. Rerun it whenever an instance setting changes; later runs update configuration without starting another build.--### One-time Cloudflare authorization--Cloudflare requires two account-level authorizations that cannot be safely automated by a repository script:--1. Install and authorize the **Cloudflare Workers & Pages** GitHub App for the fork. An Agent can open the Cloudflare dashboard and complete this browser consent; a user only needs to approve the GitHub authorization.-2. Ensure the Worker has a Workers Builds **build token** with permission to deploy Workers and apply D1 migrations. If the setup command reports that it cannot choose a token, open **Worker** -> **Settings** -> **Builds** -> **API token**, create/select the token, then set its UUID as `EDGE_EVER_BUILDS_BUILD_TOKEN_UUID` in `.env.local` and rerun the command.--The setup API call requires a **User API Token**, not an **Account API Token**. Workers Builds Configuration API accepts user-scoped tokens only. Create it at [Cloudflare API Tokens](https://dash.cloudflare.com/profile/api-tokens) under **My Profile** -> **API Tokens** (not **Manage Account** -> **Account API Tokens**). Do not use a prebuilt template, including `Edit Cloudflare Workers`: none includes Workers Builds Configuration.----1. Select **Create Token**, scroll to the bottom, and select **Create Custom Token**.-2. Name it, for example `edgeever automated deployment`.-3. Add **Account** -> **Workers Builds Configuration** -> **Edit**, then select **Add more**.-4. Add **Account** -> **Workers Scripts** -> **Read**.-5. Under **Account Resources**, leave **Include / All accounts** or restrict it to the account for this instance; set a suitable expiry.-6. Select **Continue to summary** and verify that the summary contains exactly `Workers Builds Configuration: Edit, Workers Scripts: Read`, then select **Create Token**.-7. Cloudflare shows the token value once. Save it locally as `EDGE_EVER_BUILDS_API_TOKEN=<token>` in `.env.local`; never commit, screenshot, or share it.--This token is used only by `bun run deploy:builds:setup` and is never uploaded to the Worker or Cloudflare Builds. You may instead reuse `CLOUDFLARE_API_TOKEN` only if it is a User API Token with the same permissions.--## Monorepo Build Isolation--The Worker trigger already ignores changes limited to `apps/site/*`, `apps/mobile/*`, `apps/extension/*`, `docs/*`, README files, and `.github/*`. Thus a website-only change does not deploy the EdgeEver Worker.+The command reads the repository remote and `.env.local`, configures the build, and starts one verification build on first setup. It is safe to rerun after instance settings change.-For a Git-integrated Cloudflare Pages project, set `EDGE_EVER_PAGES_PROJECT_NAME` and rerun `bun run deploy:builds:setup`. The command configures Pages Build watch paths to `apps/site/*`, `bun.lock`, and `package.json`, so product-only changes do not rebuild the website. This optional step requires the User API Token to additionally have **Account** -> **Cloudflare Pages** -> **Edit**. Without automation, set the same paths in **Pages project** -> **Settings** -> **Build** -> **Build watch paths**.+Only complete the following steps when the command asks for them.-Cloudflare cannot set Build watch paths on a **Direct Upload** Pages project. In that case, keep the filter in the deploy workflow instead. This repository's `.github/workflows/deploy-site.yml` already runs only for website/docs/shared-build-input changes, so application-only changes do not deploy the official site.+### GitHub authorization-### Manual fallback+Approve installation of the **Cloudflare Workers & Pages** GitHub App for the fork. This is the app's name; an EdgeEver instance does not require a Pages project. The command handles the repository connection after authorization.-If the command cannot be used, configure the Worker in the Cloudflare dashboard:+### Configuration API token-1. Go to **Workers & Pages** and open the EdgeEver Worker.-2. Open **Settings** -> **Builds** -> **Connect**.-3. Authorize GitHub, select the instance repository, and choose the `main` production branch.-4. Configure the following commands:+If `EDGE_EVER_BUILDS_API_TOKEN` is missing, create a custom **User API Token** at [My Profile -> API Tokens](https://dash.cloudflare.com/profile/api-tokens) with:- ```text- Build command: bun install --frozen-lockfile && bun run build:cloudflare- Deploy command: bun run deploy:cloudflare-builds- ```+- **Account** -> **Workers Builds Configuration** -> **Edit**+- **Account** -> **Workers Scripts** -> **Read**-5. Add the instance values from `.env.local` under **Settings** -> **Builds** -> **Build variables and secrets**. Store `EDGE_EVER_AUTH_PASSWORD` as a Build Secret. Existing installations may keep using `EDGE_EVER_AUTH_PASSWORD_HASH` as a Build Secret.--The Worker selected in the dashboard must be the one named by `EDGE_EVER_WORKER_NAME`. The deployment command creates a temporary Wrangler configuration from these variables, so do not commit a D1 ID, R2 bucket name, route, password, or password hash.--## Required Build Variables--Copy the applicable `EDGE_EVER_*` values from the initial deployment's `.env.local` file:+Do not use an Account API Token or a prebuilt template. Limit the token to the relevant account, then save the value shown by Cloudflare once in `.env.local`:```text-EDGE_EVER_WORKER_NAME-EDGE_EVER_WORKERS_DEV-EDGE_EVER_D1_DATABASE_NAME-EDGE_EVER_D1_DATABASE_ID-EDGE_EVER_R2_BUCKET_NAME-EDGE_EVER_R2_PREVIEW_BUCKET_NAME-EDGE_EVER_AUTH_USERNAME-EDGE_EVER_AUTH_PASSWORD # Build Secret-EDGE_EVER_SESSION_TTL_DAYS-EDGE_EVER_DEMO_MODE # optional-EDGE_EVER_DEMO_RESET_CRON # optional-EDGE_EVER_CUSTOM_DOMAIN # optional-EDGE_EVER_ROUTE_PATTERN # optional+EDGE_EVER_BUILDS_API_TOKEN=<token>```-Existing installations that already use `EDGE_EVER_AUTH_PASSWORD_HASH` may keep it instead of `EDGE_EVER_AUTH_PASSWORD`. If both are present, the hash takes precedence for backward compatibility.--For a multi-instance configuration, set `EDGE_EVER_INSTANCE` and the matching scoped variables such as `EDGE_EVER_PROD_D1_DATABASE_ID` instead. The same resolution rules apply in local deployment and Workers Builds.--Workers Builds needs an API token that can deploy Workers, update R2 bindings, and apply D1 migrations. If the automatically created Builds token does not have D1 edit permission, select or create a token with that permission before enabling automated deployments.+Never commit or share this token. If `CLOUDFLARE_API_TOKEN` is already a User API Token with the same permissions, the command can reuse it.-## What Runs on Every Push--```text-bun install --frozen-lockfile--> bun run typecheck--> bun run build--> bun run db:migrate:remote--> wrangler deploy-```--`wrangler d1 migrations apply` records completed SQL migrations in D1. Thus, every instance receives only newly added migration files before the matching Worker version is published.+-## Updating a Fork+### Deployment API token-1. On GitHub, use **Sync fork** to merge upstream changes into the fork's `main` branch.-2. Cloudflare Workers Builds detects the push and runs the sequence above.-3. Inspect the build log in the Worker **Deployments** tab if the build fails.+If the command reports that no deployment API token is available, open **Worker** -> **Settings** -> **Builds** -> **API token** and create or select one that can deploy the Worker and update D1 and R2, then rerun the command. When several are available, select one by name in the terminal.-No GitHub Actions secrets or local redeployment are needed after the initial Workers Builds connection.+## Updates and Troubleshooting-## Limits+After setup, push to `main` or use GitHub **Sync fork**. Cloudflare installs dependencies, checks and builds the app, applies new D1 migrations, and deploys the Worker. No GitHub Actions secrets or local redeployment are required.-On the Workers Free plan, Workers Builds includes 3,000 build minutes per month and permits one concurrent build per account. See [Cloudflare Workers Builds limits and pricing](https://developers.cloudflare.com/workers/ci-cd/builds/limits-and-pricing/) for current limits.+If a build fails, inspect its log in the Worker **Deployments** tab. Rerun `bun run deploy:builds:setup` when instance settings change.diff --git a/docs/cloudflare-workers-builds.zh-CN.md b/docs/cloudflare-workers-builds.zh-CN.mdindex 3e2d0d20..abc12117 100644--- a/docs/cloudflare-workers-builds.zh-CN.md+++ b/docs/cloudflare-workers-builds.zh-CN.md@@ -1,113 +1,46 @@# Cloudflare Workers Builds 自动部署-EdgeEver 的日常发布统一使用 Cloudflare Workers Builds。每个 EdgeEver Worker 只需连接一次其仓库的 `main` 分支;之后任何推送(包括 GitHub 的 **Sync fork**)都会自动构建、迁移数据库并发布该实例。+Cloudflare Workers Builds 会在 `main` 发生变化时自动部署 EdgeEver,包括 GitHub **Sync fork** 带来的更新。本地 `bun run deploy` 只用于首次安装和紧急修复。-官方实例和所有 Fork 使用完全相同的发布命令。本地 `bun run deploy` 仅用于首次安装和紧急修复。+## 配置-## 为实例连接自动部署--先按[手动部署指南](manual-deploy.zh-CN.md)创建资源并完成首次部署,然后执行:+先完成[首次部署](manual-deploy.zh-CN.md),然后执行:```shbun run deploy:builds:setup```-该命令会读取 Fork 的 `origin` remote 与 `.env.local`,以幂等方式创建或更新仓库连接、生产触发器、构建命令、构建缓存、监听路径以及 Build Variables/Secrets。首次成功时还会自动构建一次 `main`,验证整条自动发布链路;后续重跑仅更新配置,不会再次触发构建。--### Cloudflare 的一次性授权--Cloudflare 有两项账号级授权,仓库脚本不能、也不应该绕过:--1. 为 Fork 安装并授权 **Cloudflare Workers & Pages** GitHub App。Agent 可以打开 Cloudflare 页面完成操作,用户只需确认 GitHub 授权。-2. 确保 Worker 已有可部署 Worker 且可执行 D1 migration 的 Workers Builds **build token**。若命令提示无法选择 token,请打开 **Worker** -> **Settings** -> **Builds** -> **API token**,创建/选择该 token,将其 UUID 填入 `.env.local` 的 `EDGE_EVER_BUILDS_BUILD_TOKEN_UUID`,然后重试命令。--配置 API 本身必须使用 **User API Token**,不能使用 **Account API Token**:Workers Builds Configuration API 仅接受 user-scoped token。请在 [Cloudflare API Tokens](https://dash.cloudflare.com/profile/api-tokens) 的 **My Profile** -> **API Tokens** 中创建,切勿进入 **Manage Account** -> **Account API Tokens**。它需要 **Workers Builds Configuration: Edit** 与 **Workers Scripts: Read** 权限。不要选择页面上的任何现成模板(包括 `Edit Cloudflare Workers`),它们不包含 Workers Builds Configuration 权限。按以下实际界面步骤创建:----1. 打开 [Cloudflare API Tokens](https://dash.cloudflare.com/profile/api-tokens)。-2. 点击 **Create Token**,滚到最下方并选择 **Create Custom Token**。-3. 给 token 命名,例如 `edgeever自动化部署`。-4. 第一行权限选择 **Account** -> **Workers Builds Configuration** -> **Edit**;点击 **Add more**。-5. 第二行选择 **Account** -> **Workers Scripts** -> **Read**。-6. 在 **Account Resources** 保持 **Include / All accounts**,或限缩到当前实例所属账号;TTL 按自己的安全策略设置。-7. 点击 **Continue to summary**,确认摘要恰好是 `Workers Builds Configuration: Edit, Workers Scripts: Read`,再点击 **Create Token**。-8. Cloudflare 只会显示一次 token 值:立即保存到本机 `.env.local`,写为 `EDGE_EVER_BUILDS_API_TOKEN=<token>`,不要提交、截图或发送给他人。--这个 token 仅供 `bun run deploy:builds:setup` 调用,不会上传到 Worker 或 Cloudflare Builds。只有在现有 `CLOUDFLARE_API_TOKEN` 同为 User API Token 且具备上述权限时,才可直接复用。--## Monorepo 构建隔离--Worker 触发器已经排除了仅发生在 `apps/site/*`、`apps/mobile/*`、`apps/extension/*`、`docs/*`、README 文件和 `.github/*` 中的变更。因此,仅改官网不会发布 EdgeEver Worker。+命令会读取仓库 remote 与 `.env.local`、配置自动构建,并在首次配置时启动一次验证构建。实例配置发生变化后可以安全重跑。-如果这个仓库还部署了 **Git 集成** 的 Cloudflare Pages 官网,请设置 `EDGE_EVER_PAGES_PROJECT_NAME`,再重跑 `bun run deploy:builds:setup`。命令会将 Pages 的 Build watch paths 设为 `apps/site/*`、`bun.lock`、`package.json`;这样仅改产品代码不会重新构建官网。该可选步骤要求 User API Token 额外拥有 **Account** -> **Cloudflare Pages** -> **Edit**。不使用自动化时,在 **Pages 项目** -> **Settings** -> **Build** -> **Build watch paths** 填入同样的路径即可。+只有命令明确提示时,才需要完成下面对应的操作。-Cloudflare 无法为 **Direct Upload(直接上传)** 类型的 Pages 项目设置 Build watch paths;此时应由部署工作流本身过滤路径。本仓库的 `.github/workflows/deploy-site.yml` 已只监听官网、文档及共享构建输入的改动,因此仅改笔记应用不会触发官网部署。+### GitHub 授权-### 手动兜底+为 Fork 安装并授权 **Cloudflare Workers & Pages** GitHub App。这只是应用名称,EdgeEver 实例不需要部署 Pages 项目。授权完成后,命令会继续配置仓库连接。-若不能运行命令,则在 Cloudflare Dashboard 中:+### 配置 API token-1. 打开 **Workers & Pages**,选择 EdgeEver Worker。-2. 打开 **Settings** -> **Builds** -> **Connect**。-3. 授权 GitHub,选择该实例对应的仓库,并选择 `main` 作为生产分支。-4. 设置以下命令:+如果缺少 `EDGE_EVER_BUILDS_API_TOKEN`,请在 [My Profile -> API Tokens](https://dash.cloudflare.com/profile/api-tokens) 创建自定义 **User API Token**,权限为:- ```text- Build command: bun install --frozen-lockfile && bun run build:cloudflare- Deploy command: bun run deploy:cloudflare-builds- ```+- **Account** -> **Workers Builds Configuration** -> **Edit**+- **Account** -> **Workers Scripts** -> **Read**-5. 在 **Settings** -> **Builds** -> **Build variables and secrets** 中,填入初次部署时 `.env.local` 的实例配置;推荐将 `EDGE_EVER_AUTH_PASSWORD` 保存为 Build Secret。已有实例可继续将 `EDGE_EVER_AUTH_PASSWORD_HASH` 保存为 Build Secret。--Dashboard 中选中的 Worker 必须与 `EDGE_EVER_WORKER_NAME` 对应。部署命令会根据这些变量生成临时 Wrangler 配置,因此严禁把 D1 ID、R2 bucket、路由、密码或密码 hash 提交进仓库。--## 必需的构建变量--从初次部署产生的 `.env.local` 复制适用的 `EDGE_EVER_*` 变量:+不要使用 Account API Token 或现成模板。将 token 限制到对应账号,然后把 Cloudflare 仅显示一次的值保存到 `.env.local`:```text-EDGE_EVER_WORKER_NAME-EDGE_EVER_WORKERS_DEV-EDGE_EVER_D1_DATABASE_NAME-EDGE_EVER_D1_DATABASE_ID-EDGE_EVER_R2_BUCKET_NAME-EDGE_EVER_R2_PREVIEW_BUCKET_NAME-EDGE_EVER_AUTH_USERNAME-EDGE_EVER_AUTH_PASSWORD # Build Secret-EDGE_EVER_SESSION_TTL_DAYS-EDGE_EVER_DEMO_MODE # 可选-EDGE_EVER_DEMO_RESET_CRON # 可选-EDGE_EVER_CUSTOM_DOMAIN # 可选-EDGE_EVER_ROUTE_PATTERN # 可选+EDGE_EVER_BUILDS_API_TOKEN=<token>```-已经使用 `EDGE_EVER_AUTH_PASSWORD_HASH` 的旧实例可以继续保留该变量,无需改成 `EDGE_EVER_AUTH_PASSWORD`。为兼容已有实例,两个变量同时存在时哈希优先。--多实例场景则设置 `EDGE_EVER_INSTANCE`,并使用 `EDGE_EVER_PROD_D1_DATABASE_ID` 之类的带实例前缀变量。本地部署和 Workers Builds 使用相同的变量解析规则。--Workers Builds 使用的 API Token 必须拥有 Worker 发布、R2 binding 更新和 D1 migration 所需权限。如果 Cloudflare 自动创建的 Builds token 没有 D1 编辑权限,请选择或新建一个具备该权限的 token。+不要提交或分享该 token。如果现有 `CLOUDFLARE_API_TOKEN` 已是具备相同权限的 User API Token,命令可以直接复用。-## 每次推送的执行顺序--```text-bun install --frozen-lockfile--> bun run typecheck--> bun run build--> bun run db:migrate:remote--> wrangler deploy-```--`wrangler d1 migrations apply` 会在 D1 中记录已完成的 SQL migration。因此每个实例只会在发布对应 Worker 版本之前执行新增加的 migration。+-## 更新 Fork+### 部署 API token-1. 在 GitHub 的 Fork 页面点击 **Sync fork**,将上游更新合入 fork 的 `main`。-2. Cloudflare Workers Builds 检测到 push 后自动执行上述流程。-3. 若失败,可在 Worker 的 **Deployments** 页面查看 build log。+如果命令提示没有可用的部署 API token,请打开 **Worker** -> **Settings** -> **Builds** -> **API token**,创建或选择一个能够部署 Worker 并更新 D1、R2 的 API token,然后重试。存在多个候选时,直接在终端中按名称选择。-首次连接完成后,不再需要 GitHub Actions Secrets,也不需要本地重新部署。+## 更新与排错-## 额度+配置完成后,只需推送到 `main` 或使用 GitHub **Sync fork**。Cloudflare 会安装依赖、检查并构建应用、执行新的 D1 migration,然后部署 Worker;不需要 GitHub Actions Secrets 或本地重新部署。-Workers Free 目前每月包含 3,000 分钟 Workers Builds,并且每个账号同时执行一个构建。最新限制请参考 [Cloudflare Workers Builds 限额与价格](https://developers.cloudflare.com/workers/ci-cd/builds/limits-and-pricing/)。+构建失败时,在 Worker 的 **Deployments** 页面查看日志。实例配置变化后,重新执行 `bun run deploy:builds:setup`。diff --git a/scripts/cloudflare-workers-builds.mjs b/scripts/cloudflare-workers-builds.mjsindex 3ab4e407..b0156025 100644--- a/scripts/cloudflare-workers-builds.mjs+++ b/scripts/cloudflare-workers-builds.mjs@@ -1,6 +1,7 @@import { execFileSync } from "node:child_process";import { existsSync, readFileSync } from "node:fs";import { resolve } from "node:path";+import { createInterface } from "node:readline/promises";const command = process.argv[2] ?? "setup";const dryRun = process.argv.includes("--dry-run");@@ -173,6 +174,60 @@ const configurePagesWatchPaths = async () => {}};+const selectBuildToken = async (buildTokens, existingTrigger) => {+ const tokens = Array.isArray(buildTokens)+ ? buildTokens.filter((token) => token?.build_token_uuid)+ : [];++ // Keep accepting the old environment variable so existing installations do+ // not break, but do not expose Cloudflare's internal UUID in the new setup UX.+ const legacyBuildTokenUuid = value("EDGE_EVER_BUILDS_BUILD_TOKEN_UUID");+ if (legacyBuildTokenUuid) {+ const legacyToken = tokens.find((token) => token.build_token_uuid === legacyBuildTokenUuid);+ if (legacyToken) return legacyToken;+ throw new Error(+ "The API token configured by the legacy EDGE_EVER_BUILDS_BUILD_TOKEN_UUID setting no longer exists. Remove that setting and rerun the command.",+ );+ }++ const existingToken = existingTrigger?.build_token_uuid+ ? tokens.find((token) => token.build_token_uuid === existingTrigger.build_token_uuid)+ : undefined;+ if (existingToken) return existingToken;++ if (tokens.length === 1) return tokens[0];+ if (tokens.length === 0) {+ throw new Error(+ "No Workers Builds API token was found. In Cloudflare Dashboard open this Worker -> Settings -> Builds -> API token, create or select an API token with D1 edit permission, then rerun the command.",+ );+ }++ if (!process.stdin.isTTY || !process.stdout.isTTY) {+ throw new Error(+ `Multiple Workers Builds API tokens are available (${tokens.map((token) => token.build_token_name || "Unnamed token").join(", ")}). Rerun this command in an interactive terminal and select one.`,+ );+ }++ console.log("Multiple Workers Builds API tokens are available:");+ tokens.forEach((token, index) => {+ console.log(` ${index + 1}. ${token.build_token_name || "Unnamed token"}`);+ });++ const prompt = createInterface({ input: process.stdin, output: process.stdout });+ try {+ while (true) {+ const answer = (await prompt.question(`Select an API token [1-${tokens.length}]: `)).trim();+ const selectedIndex = Number(answer) - 1;+ if (Number.isInteger(selectedIndex) && selectedIndex >= 0 && selectedIndex < tokens.length) {+ return tokens[selectedIndex];+ }+ console.log("Enter the number shown next to the API token you want to use.");+ }+ } finally {+ prompt.close();+ }+};+const setup = async () => {if (!accountId) throw new Error("Missing CLOUDFLARE_ACCOUNT_ID.");if (!workerName) throw new Error("Missing EDGE_EVER_WORKER_NAME.");@@ -207,16 +262,10 @@ const setup = async () => {throw new Error(`Worker ${workerName} was not found. Complete the first bun run deploy before enabling Workers Builds.`);}- const requestedBuildToken = value("EDGE_EVER_BUILDS_BUILD_TOKEN_UUID");const buildTokens = await request("GET", `/accounts/${accountId}/builds/tokens`);- const buildToken = requestedBuildToken- ? buildTokens?.find((token) => token.build_token_uuid === requestedBuildToken)- : buildTokens?.length === 1 ? buildTokens[0] : undefined;- if (!buildToken?.build_token_uuid) {- throw new Error(- "No unambiguous Workers Builds build token was found. In Cloudflare Dashboard open this Worker -> Settings -> Builds -> API token, create/select a token with D1 edit permission, then set EDGE_EVER_BUILDS_BUILD_TOKEN_UUID and rerun.",- );- }+ const triggers = await request("GET", `/accounts/${accountId}/builds/workers/${worker.tag}/triggers`);+ const existing = triggers?.find((trigger) => trigger.branch_includes?.includes("main"));+ const buildToken = await selectBuildToken(buildTokens, existing);const connection = await request("PUT", `/accounts/${accountId}/builds/repos/connections`, {provider_type: "github",@@ -228,8 +277,6 @@ const setup = async () => {const repoConnectionUuid = connection?.repo_connection_uuid;if (!repoConnectionUuid) throw new Error("Cloudflare did not return repo_connection_uuid.");- const triggers = await request("GET", `/accounts/${accountId}/builds/workers/${worker.tag}/triggers`);- const existing = triggers?.find((trigger) => trigger.branch_includes?.includes("main"));const payload = triggerPayload(worker.tag, repoConnectionUuid, buildToken.build_token_uuid);const trigger = existing? await request("PATCH", `/accounts/${accountId}/builds/triggers/${existing.trigger_uuid}`, payload)