> For the complete documentation index, see [llms.txt](https://gitbook.com/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gitbook.com/docs/documentation/zh/skill/build-integration.md).

# 构建集成

构建、开发并发布 GitBook 集成——可在 GitBook 内运行的应用，用于添加自定义区块、响应事件、通过 OAuth 连接外部服务，并扩展编辑器。只要在任何情况下需要使用此技能

用于在 GitBook 开发者平台上构建集成的技能：运行在 GitBook 内部的应用。集成可以在编辑器中渲染自定义区块、显示配置 UI、监听事件（内容更新、Git 同步完成、空间被查看）、通过 OAuth 对外部服务进行身份验证，并通过 HTTP 与任何服务通信。

此技能涵盖集成生命周期——脚手架、编码、开发、发布。用于创建或重构文档 *站点* 某个集成可能被安装到的，请参阅 `configure-site`；用于编写页面内容，请参阅 `write-docs`.

## 什么是集成（心智模型）

集成是由 GitBook 运行时执行的小型 TypeScript 应用——不是注入页面的脚本，也不是运行在用户服务器上的代码。以下三个结果决定了其他所有事项：

1. **渲染发生在 GitBook 的后端。** 你的组件的 `render` 函数会在每次交互时于服务端运行，并返回 ContentKit 标记（一种类似 JSX 的 UI 描述）。你无法控制客户端 React 树，也无法访问 DOM；UI 更新通过“操作 → 新状态 → 重新渲染”的循环进行。
2. **你不能向站点注入 JavaScript。** 该 `site:script:inject` 和 `site:script:cookies` 这些在 GitBook 自有集成中会看到的作用域仅供内部使用。如果用户的计划相当于“向他们的文档添加一个 script 标签”，请尽早说明无法实现——受支持的方式是自定义区块、网页框架和事件。
3. **本地开发是一个代理，而不是你要访问的服务器。** `gitbook dev` 将 *已安装的* 集成流量路由到你的机器。你绝不需要在浏览器中打开开发服务器的端口；应在 app.gitbook.com 中与集成交互。

## 项目

`gitbook new` 会生成如下结构：

```
my-integration/
├── gitbook-manifest.yaml   # 标识、作用域、区块、配置架构
├── .gitbook-dev.yaml       # 本地开发配置（由 `gitbook dev` 生成）
├── package.json
└── src/
    └── index.tsx           # 入口文件——默认导出 createIntegration()
```

入口文件（无论 `script:` 在清单中指向的文件）默认导出 `createIntegration({ fetch, components, events })`:

```tsx
import { createIntegration, createComponent } from '@gitbook/runtime';

const helloBlock = createComponent({
    componentId: 'hello-world',            // 必须与清单中的区块 ID 匹配
    initialState: { message: 'Say hello!' },
    action: async (element, action, context) => {
        switch (action.action) {
            case 'say':
                return { state: { message: 'Hello world' } };
            default:
                return {};
        }
    },
    render: async (element, context) => (
        <block>
            <button label={element.state.message} onPress={{ action: 'say' }} />
        </block>
    ),
});

export default createIntegration({
    components: [helloBlock],
    events: {
        space_content_updated: async (event, context) => {
            // 响应内容变更
        },
    },
});
```

只有在以下 **两个** 位置中声明时，自定义区块才会出现在编辑器的插入面板（⌘ + /）中： `createComponent` 代码中 *和* 一个 `blocks:` 清单中的条目，其 `id` 与 `componentId`匹配。遗漏任一部分，都是最常见的“我的区块没有显示”原因。

## 简述清单

`gitbook-manifest.yaml` 是集成的标识和权限授予。必填项： `名称` （在整个 GitBook 中全局唯一——选择带命名空间的名称，例如 `acme-changelog`，而不是 `test`), `标题`, `description`, `组织` （组织 ID 或子域名）、 `可见性`, `作用域`，以及 `脚本`。仅请求代码实际使用的作用域——安装者会看到它们。

清单还会声明 `区块`、面向安装者的 `配置` （渲染为设置表单的账户级和站点级属性架构），以及 `密钥` （例如 `CLIENT_ID: ${{ env.CLIENT_ID }}`，在发布时加载——使用 `dotenv-cli` 以便 `gitbook publish` 能读取你的 `.env`).

完整的逐字段架构、作用域列表和配置属性类型： `references/manifest.md`。每当你编辑超出基础内容的清单时，都应阅读它。

## 开发循环

这个循环的顺序并不直观—— **发布在本地开发之前**:

1. **先决条件。** Node 18+、来自 <https://app.gitbook.com/account/developer> 的个人访问令牌，以及 CLI： `npm install @gitbook/cli -g`，然后 `gitbook auth` （或 `gitbook auth --token=<token>`）。如果需要将令牌粘贴到对话中，请将其导出到环境变量，切勿回显或提交它。
2. **创建脚手架。** `gitbook new <dir>` ——提示输入名称、标题、组织和作用域。
3. **发布一次。** `gitbook publish` 在项目根目录中运行。此操作会注册集成（默认私有）并打印安装链接。
4. **安装它** 通过该链接安装到至少一个空间或站点中。在它被安装到某处之前，本地开发无法工作。
5. **开发。** `gitbook dev` 启动代理：已安装集成的所有流量将由本地代码提供服务，而非已发布版本。在 GitBook 编辑器中与其交互，而不是通过服务器 URL。UI 更改需要刷新浏览器；禁用浏览器缓存可让循环更顺畅。日志会显示在 *浏览器* 控制台或终端中，具体取决于代码运行的位置——在认定日志失效之前请两处都检查。
6. **重新发布** 使用 `gitbook publish` ，以便在需要时更新托管版本。 `gitbook unpublish <name>` 会将其移除。

CLI 命令参考（包括 `gitbook whoami` 和 `gitbook openapi publish`): `references/manifest.md`.

## 运行时：fetch、事件、环境、OAuth

详细信息和完整表格位于 `references/runtime.md` ——编写事件处理程序、OAuth 流程或任何涉及 `context.environment`的内容时请阅读它。要点如下：

* **`fetch`** 使用标准 Fetch API 处理发送至集成公共端点的传入 HTTP 请求 `Request`/`Response` 对象。传出 HTTP 同样只是普通的 `fetch` 。
* **`events`** 将事件名称（`installation_setup`, `space_installation_setup`, `space_view`, `ui_render`, `space_content_updated`, `space_visibility_updated`, `space_gitsync_started`, `space_gitsync_completed`）映射到处理程序。某些事件需要匹配的作用域。
* **`context.environment`** 公开提供 `apiEndpoint`, `apiTokens`、安装信息（空间、状态、每次安装的 `配置` 值，由安装者输入）、 `密钥`以及公共 URL（`environment.integration.urls.publicEndpoint`).
* **OAuth** 针对外部提供商的 OAuth 是一种固定模式：一个 `按钮`类型的配置属性，其 `callback_url` 路由到 `createOAuthHandler({...})` ，位于你的 fetch 处理程序中，客户端 ID/密钥来自 `密钥`。不要自行实现重定向/令牌交换。
* **从集成内部调用 GitBook API**：使用 `context.api` （一个已认证的 `@gitbook/api` 客户端），而不是基于原始令牌构建自己的客户端。

## ContentKit：构建 UI

ContentKit 是组件可返回的组件词汇： `render` 可返回：布局（`block`, `vstack`, `hstack`, `divider`）、展示（`box`, `card`, `text`, `image`, `markdown`），以及交互元素（`按钮`, `textinput`, `select`, `switch`, `checkbox`, `radio`, `codeblock`, `webframe`, `modal`）。交互模型一言以蔽之：输入将其值绑定到一个 `state` 键；按钮分发操作；你的 `action` 归约器返回新状态；GitBook 重新渲染。

阅读 `references/contentkit.md` ，再编写任何不止是简单按钮的组件——其中包含完整的属性表，以及难以猜出的模式：用于实时预览的动态状态绑定、网页框架 `postMessage` 通信、带有 `returnValue`的模态框、使用 `@editor.node.updateProps`持久化属性、通过 `@link.unfurl` + `urlUnfurl` 实现的链接展开清单模式，以及区块的 Markdown 代码块序列化。

## 发布和共享

清单中的可见性控制覆盖范围：

* `private` （默认）——仅所属组织的成员可以安装。适用于内部工具；开发期间请保持此设置。
* `unlisted` ——任何组织均可安装，但只能通过共享安装链接安装。适用于与特定客户或 Beta 测试者共享。
* `public` ——任何人均可安装；提交到集成市场前必须设为此项（市场审核是独立流程——请参阅 GitBook 的“提交应用以供审核”文档）。

重新运行 `gitbook publish` 在更改可见性后。在建议 `public`之前，请确认清单内容适合展示： `图标`, `摘要` （Markdown，≤2048 个字符）、 `预览图片` （1600×800）、 `类别`, `外部链接`.

## 工作方式

* **新建项目时使用 CLI 创建脚手架，而非手动创建** —— `gitbook new` 会正确配置清单、TypeScript 配置和 `@gitbook/runtime` 版本。
* **追踪区块的 ID 链** （清单 `blocks[].id` ↔ `componentId`）——只要组件行为异常就应检查它。
* **将密钥排除在清单文件本身之外** ——始终使用 `${{ env.X }}` 这种间接引用，绝不要使用字面值。
* **当用户的目标是从&#x20;*****外部*****&#x20;GitBook** 实现内容或站点自动化（调用 REST API 的脚本、CI 流水线）时，集成可能不是合适的工具——使用带个人令牌的普通 API 更简单。当代码必须运行在 *内部* GitBook 中时，集成才物有所值：区块、配置 UI、事件响应、代表安装者进行 OAuth。

## 参考资料

* `references/manifest.md` ——每个 `gitbook-manifest.yaml` 字段、所有作用域、配置属性类型、密钥、CLI 命令参考、安装/配置流程。
* `references/runtime.md` — `createIntegration` / `createComponent` / `createOAuthHandler` 签名、事件目录、 `context.environment` 结构、传入和传出的 HTTP。
* `references/contentkit.md` ——完整的组件参考，包括属性、内置操作和交互配方（动态绑定、网页框架、模态框、链接展开、Markdown 序列化）。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://gitbook.com/docs/documentation/zh/skill/build-integration.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
