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(deploy): auto-resolve Cloudflare D1 database id
tianma-if8ec7307d0690
diff --git a/docs/agent-deploy-cloudflare.md b/docs/agent-deploy-cloudflare.mdindex a77b7f7b..84cd9a91 100644--- a/docs/agent-deploy-cloudflare.md+++ b/docs/agent-deploy-cloudflare.md@@ -19,7 +19,7 @@ This document defines the standard operating specifications and conventions for- Configure the project to use the repository root, the production `main` branch, and read the root `wrangler.toml`.4. **Resource Bindings & Secrets**- - **D1 Database Binding**: Binding name `DB`, associated with database `edgeever`.+ - **D1 Database Binding**: Binding name `DB`, associated with a database named exactly `edgeever`.- **R2 Bucket Binding**: Binding name `RESOURCES`, associated with a globally unique R2 Bucket.- **Admin username**: Configure `EDGE_EVER_AUTH_USERNAME`; it defaults to `admin` and can be replaced with a custom username.- **Worker Secret**: Add secret `EDGE_EVER_AUTH_PASSWORD` for initial admin password.@@ -32,6 +32,9 @@ This document defines the standard operating specifications and conventions forDeploy command: bun run deploy:cloudflare-builds```+ - The deploy command automatically resolves the D1 UUID from the `edgeever` database name and writes it only to a temporary generated Wrangler configuration. Users do not need to edit `wrangler.toml` or copy a D1 ID into a build variable.+ - Ensure the Workers Builds API token can read and edit D1. An advanced deployment that uses a differently named database must set the build variable `EDGE_EVER_D1_DATABASE_ID` explicitly.+6. **Start Initial Build & Verify Service**- Trigger the initial build. Once deployed, run the following automated verifications:- Check `https://<your-worker-domain>/api/health` returns HTTP `200` with JSON `{"ok": true}`.diff --git a/docs/agent-deploy-cloudflare.zh-CN.md b/docs/agent-deploy-cloudflare.zh-CN.mdindex 6cd44e94..eb0f6754 100644--- a/docs/agent-deploy-cloudflare.zh-CN.md+++ b/docs/agent-deploy-cloudflare.zh-CN.md@@ -19,7 +19,7 @@- 配置项目使用仓库根目录、生产环境 `main` 分支,并读取仓库根目录下的 `wrangler.toml`。4. **绑定资源与凭据 (Bindings & Secrets)**- - **D1 数据库绑定**:Binding 名称填 `DB`,关联数据库名称为 `edgeever`。+ - **D1 数据库绑定**:Binding 名称填 `DB`,关联名称严格为 `edgeever` 的数据库。- **R2 存储桶绑定**:Binding 名称填 `RESOURCES`,关联全局唯一的 R2 Bucket。- **管理员用户名**:配置 `EDGE_EVER_AUTH_USERNAME`,默认值为 `admin`;如需自定义,可替换为其他用户名。- **Worker Secret**:添加密钥 `EDGE_EVER_AUTH_PASSWORD`,值为初始管理员登录密码。@@ -32,6 +32,9 @@Deploy command: bun run deploy:cloudflare-builds```+ - 部署命令会根据 `edgeever` 数据库名称自动查询 D1 UUID,并且只写入临时生成的 Wrangler 配置。用户无需修改 `wrangler.toml`,也无需手工把 D1 ID 复制到构建变量。+ - 请确保 Workers Builds API Token 具有 D1 读取和编辑权限。使用其他数据库名称的高级部署需要显式设置构建变量 `EDGE_EVER_D1_DATABASE_ID`。+6. **启动首次构建与服务验证**- 触发启动首次构建,待构建部署完成后,进行如下自动化验证:- 检查 `https://<你的 Worker 域名>/api/health` 返回 `200` 状态码且 JSON 内容为 `{"ok": true}`。diff --git a/docs/deploy-cloudflare-button.md b/docs/deploy-cloudflare-button.mdindex acda1903..17b5d9e4 100644--- a/docs/deploy-cloudflare-button.md+++ b/docs/deploy-cloudflare-button.md@@ -29,7 +29,7 @@ Log into your [Cloudflare Dashboard](https://dash.cloudflare.com/):1. **Create a D1 Database**:- Navigate to **Workers & Pages** -> **D1**, then click **Create database**.- - Database name: `edgeever`, then click **Create**.+ - Database name: exactly `edgeever`, then click **Create**.2. **Create an R2 Bucket** (for note attachments & images):- Navigate to **Workers & Pages** -> **R2**, then click **Create bucket**.- Enter a globally unique bucket name (e.g., `my-edgeever-resources`), then click **Create bucket**.@@ -67,6 +67,8 @@ Deploy command: bun run deploy:cloudflare-buildsClick **Save and Deploy** to trigger the initial build.+The deploy command automatically looks up the D1 UUID by the `edgeever` database name. Do not edit `wrangler.toml` or manually copy the D1 ID. The Workers Builds API token must have D1 read/edit permission.+---### Step 5: Verify Deployment & Login@@ -93,6 +95,6 @@ EDGE_EVER_UPDATE_CHANNEL=edge## Troubleshooting-- **Initial build failed**: Check the Worker **Deployments** log in Cloudflare to verify that D1 (`DB`) and R2 (`RESOURCES`) binding names match the exact case required.+- **Initial build failed**: Check the Worker **Deployments** log. Verify that the D1 binding is `DB`, its database is named exactly `edgeever`, the R2 binding is `RESOURCES`, and the Workers Builds API token has D1 read/edit permission. For an intentionally different D1 database, add the build variable `EDGE_EVER_D1_DATABASE_ID` with its UUID.- **Updates not syncing**: Navigate to your Fork's **Actions** tab, verify **Update deployed EdgeEver** is enabled, and try clicking **Run workflow** manually.- **Reset or Manual Recovery**: See the [Cloudflare Manual Deployment Guide](manual-deploy.md).diff --git a/docs/deploy-cloudflare-button.zh-CN.md b/docs/deploy-cloudflare-button.zh-CN.mdindex 4431045b..2a2b58f3 100644--- a/docs/deploy-cloudflare-button.zh-CN.md+++ b/docs/deploy-cloudflare-button.zh-CN.md@@ -29,7 +29,7 @@1. **创建 D1 数据库**:- 导航至 **Workers & Pages** -> **D1**,点击 **Create database**。- - 数据库名称填入:`edgeever`,点击 **Create**。+ - 数据库名称严格填入:`edgeever`,点击 **Create**。2. **创建 R2 存储桶**(用于存储笔记附件与图片):- 导航至 **Workers & Pages** -> **R2**,点击 **Create bucket**。- 填入自定义存储桶名称(全局唯一,如 `my-edgeever-resources`),点击 **Create bucket**。@@ -67,6 +67,8 @@ Deploy command: bun run deploy:cloudflare-builds点击 **Save and Deploy** 启动首次构建部署。+部署命令会根据 `edgeever` 数据库名称自动查询 D1 UUID。无需修改 `wrangler.toml`,也无需手工复制 D1 ID。Workers Builds API Token 必须具有 D1 读取和编辑权限。+---### 步骤 5:验证部署与登录@@ -93,6 +95,6 @@ EDGE_EVER_UPDATE_CHANNEL=edge## 常见问题与排错-- **首次构建失败**:请检查 Cloudflare 控制台中 Worker 的 **Deployments** 构建日志,确认 D1 (`DB`) 和 R2 (`RESOURCES`) Binding 名称大小写是否正确。+- **首次构建失败**:请检查 Cloudflare 控制台中 Worker 的 **Deployments** 构建日志,确认 D1 Binding 为 `DB`、数据库名称严格为 `edgeever`、R2 Binding 为 `RESOURCES`,并确认 Workers Builds API Token 具有 D1 读取和编辑权限。如有意使用其他 D1 数据库,请添加构建变量 `EDGE_EVER_D1_DATABASE_ID` 并填入其 UUID。- **无法同步上游更新**:打开您 Fork 仓库的 **Actions** 标签页,确认 **Update deployed EdgeEver** 工作流是否处于已启用状态,并尝试手动点击 **Run workflow**。- **需要重置或手动恢复部署**:请参阅 [手动部署指南](manual-deploy.zh-CN.md)。diff --git a/scripts/run-wrangler.mjs b/scripts/run-wrangler.mjsindex 8a141191..d5d1be77 100644--- a/scripts/run-wrangler.mjs+++ b/scripts/run-wrangler.mjs@@ -7,7 +7,11 @@ import {writeFileSync,} from "node:fs";import { dirname, resolve } from "node:path";-import { normalizeD1MigrationSql, runWranglerSync } from "./wrangler-runner.mjs";+import {+ findD1DatabaseIdByName,+ normalizeD1MigrationSql,+ runWranglerSync,+} from "./wrangler-runner.mjs";const PLACEHOLDER_D1_ID = "00000000-0000-0000-0000-000000000000";const UUID_PATTERN =@@ -177,6 +181,36 @@ if (d1DatabaseId) {}config = replaceTomlValue(config, "database_name", envValue("D1_DATABASE_NAME"));++if (isRemoteCommand && config.includes(`database_id = "${PLACEHOLDER_D1_ID}"`)) {+ const databaseName = config.match(/^database_name\s*=\s*"([^"]+)"/m)?.[1];+ if (databaseName) {+ console.log(`[info] resolving Cloudflare D1 database id for ${databaseName}`);+ const listResult = runWranglerSync(+ ["--config", baseConfigPath, "d1", "list", "--json"],+ {+ cwd: resolve("."),+ encoding: "utf8",+ env: process.env,+ },+ );++ if (listResult.status === 0) {+ try {+ const discoveredId = findD1DatabaseIdByName(listResult.stdout, databaseName);+ if (discoveredId && UUID_PATTERN.test(discoveredId)) {+ config = replaceTomlValue(config, "database_id", discoveredId);+ console.log(`[ok] resolved D1 database ${databaseName}`);+ }+ } catch (error) {+ console.error(error instanceof Error ? error.message : String(error));+ }+ } else if (listResult.stderr) {+ console.error(listResult.stderr.trim());+ }+ }+}+config = replaceTomlValue(config, "bucket_name", envValue("R2_BUCKET_NAME"));config = replaceTomlValue(config,@@ -254,9 +288,11 @@ if (isRemoteDevCommand && !instance) {}if (isRemoteCommand && config.includes(`database_id = "${PLACEHOLDER_D1_ID}"`)) {+ const databaseName = config.match(/^database_name\s*=\s*"([^"]+)"/m)?.[1] ?? "edgeever";console.error([- "Missing Cloudflare D1 database id.",+ `Could not resolve Cloudflare D1 database "${databaseName}".`,+ "Create it with that exact name and ensure the Workers Builds API token has D1 read/edit permission.",instanceKey? `Set EDGE_EVER_${instanceKey}_D1_DATABASE_ID or EDGE_EVER_D1_DATABASE_ID,`: "Set EDGE_EVER_D1_DATABASE_ID,",diff --git a/scripts/wrangler-runner.mjs b/scripts/wrangler-runner.mjsindex 6777905a..a681c6a1 100644--- a/scripts/wrangler-runner.mjs+++ b/scripts/wrangler-runner.mjs@@ -25,6 +25,27 @@ export const buildWranglerEnvironment = (args, env = process.env) => ({export const normalizeD1MigrationSql = (sql) => sql.replace(/\r\n?/g, "\n");+export const findD1DatabaseIdByName = (json, databaseName) => {+ let databases;+ try {+ databases = JSON.parse(json);+ } catch {+ throw new Error("Wrangler returned invalid JSON while listing D1 databases.");+ }++ if (!Array.isArray(databases)) {+ throw new Error("Wrangler returned an unexpected response while listing D1 databases.");+ }++ const matches = databases.filter((database) => database?.name === databaseName);+ if (matches.length !== 1) {+ return undefined;+ }++ const databaseId = matches[0]?.uuid;+ return typeof databaseId === "string" ? databaseId : undefined;+};+export const buildWranglerSpawnOptions = (args, options = {}) => {if (!isD1MigrationApplyCommand(args) || options.input !== undefined) {return options;diff --git a/tests/deployment-entrypoints.test.ts b/tests/deployment-entrypoints.test.tsindex a05ac25e..82149f8e 100644--- a/tests/deployment-entrypoints.test.ts+++ b/tests/deployment-entrypoints.test.ts@@ -30,6 +30,17 @@ describe("Cloudflare deployment entrypoints", () => {expect(packageJson.cloudflare.bindings.EDGE_EVER_AUTH_PASSWORD.description).toBeTruthy();});+ test("online deployment resolves the D1 id without editing the repository config", () => {+ const runner = readRepositoryFile("scripts/run-wrangler.mjs");+ const englishAgentDoc = readRepositoryFile("docs/agent-deploy-cloudflare.md");+ const chineseAgentDoc = readRepositoryFile("docs/agent-deploy-cloudflare.zh-CN.md");++ expect(runner).toContain('"d1", "list", "--json"');+ expect(runner).toContain("findD1DatabaseIdByName");+ expect(englishAgentDoc).toContain("automatically resolves the D1 UUID");+ expect(chineseAgentDoc).toContain("自动查询 D1 UUID");+ });+test("deployed repositories receive guarded daily upstream updates", () => {const workflow = readRepositoryFile(".github/workflows/sync-edgeever-upstream.yml");diff --git a/tests/wrangler-runner.test.ts b/tests/wrangler-runner.test.tsindex 72fe116e..546cb325 100644--- a/tests/wrangler-runner.test.ts+++ b/tests/wrangler-runner.test.ts@@ -5,6 +5,7 @@ import {buildWranglerInvocation,buildWranglerEnvironment,buildWranglerSpawnOptions,+ findD1DatabaseIdByName,isD1MigrationApplyCommand,normalizeD1MigrationSql,resolveWranglerCliPath,@@ -57,6 +58,28 @@ describe("cross-platform Wrangler runner", () => {);});+ test("resolves an exact D1 database name from Wrangler JSON", () => {+ const databases = JSON.stringify([+ { uuid: "11111111-1111-1111-1111-111111111111", name: "another-database" },+ { uuid: "22222222-2222-2222-2222-222222222222", name: "edgeever" },+ ]);++ expect(findD1DatabaseIdByName(databases, "edgeever")).toBe(+ "22222222-2222-2222-2222-222222222222",+ );+ expect(findD1DatabaseIdByName(databases, "EdgeEver")).toBeUndefined();+ expect(findD1DatabaseIdByName("[]", "edgeever")).toBeUndefined();+ });++ test("rejects malformed D1 database list output", () => {+ expect(() => findD1DatabaseIdByName("not-json", "edgeever")).toThrow(+ "Wrangler returned invalid JSON",+ );+ expect(() => findD1DatabaseIdByName("{}", "edgeever")).toThrow(+ "Wrangler returned an unexpected response",+ );+ });+test("keeps every D1 trigger on one physical line for remote compatibility", () => {const migrationSql = ["0001_initial.sql", "0013_mobile_sync_changes.sql"].map((file) => readFileSync(resolve("migrations", file), "utf8"))