# @cloudflare/flagship 中文文档

规范地址：https://npmcn.com/package/%40cloudflare/flagship/

版本：0\.7\.0
npm 元数据更新时间：2026-11-04T10:11:54.335Z
中文译文更新时间：2026-11-10T03:04:10.760Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40cloudflare/flagship
原文对照：https://npmcn.com/package/%40cloudflare/flagship/?lang=original
项目主页：https://github.com/cloudflare/flagship
源码仓库：https://github.com/cloudflare/flagship

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：140 kB，21 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：@openfeature/web-sdk ^1\.7\.3，@openfeature/server-sdk ^1\.20\.2
- 首次发布：2026-03-30T08:19:26.158Z
- 最新版本发布：2026-11-04T10:11:53.956Z
- 近 30 天下载量：357720（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：14（近 12 个月 14 个）

## 中文简介

旗舰特性旗的 OpenFeature 提供者

## 安装

```sh
npm install @cloudflare/flagship
```

也可以使用：`pnpm add @cloudflare/flagship`、`yarn add @cloudflare/flagship`、`bun add @cloudflare/flagship`

## README

# @cloudflare/旗舰

[![npm version](https://img.shields.io/npm/v/@cloudflare/flagship.svg)](https://www.npmjs.com/package/@cloudflare/flagship) [![npm downloads](https://img.shields.io/npm/dm/@cloudflare/flagship.svg)](https://www.npmjs.com/package/@cloudflare/flagship) [![license](https://img.shields.io/npm/l/@cloudflare/flagship.svg)](https://github.com/cloudflare/flagship/blob/main/LICENSE)

[打开形状](https://openfeature.dev/)\- 符合要求的供应商SDK [旗舰](https://github.com/cloudflare/flagship), Cloudflare 全球分布,低纬度地物地标旗平台.

服务器侧(Node.js, Cloudflare Workers)和客户端侧(浏览器)通过孤立的子路径导出支持. 可树摇动-导入 `@cloudflare/flagship/server` 从不装载 `@openfeature/web-sdk` 而反之亦然.

## 安装

**服务器侧** (节点.js, Cloudflare工人):

```bash
npm install @cloudflare/flagship @openfeature/server-sdk
```

**客户端** (浏览器):

```bash
npm install @cloudflare/flagship @openfeature/web-sdk
```

## 快速启动 — 服务器

```typescript
import { OpenFeature } from '@openfeature/server-sdk';
import { FlagshipServerProvider } from '@cloudflare/flagship/server';

await OpenFeature.setProviderAndWait(
  new FlagshipServerProvider({ appId: 'your-app-id', accountId: 'your-account-id', authToken: 'your-token' }),
);

const client = OpenFeature.getClient();
const enabled = await client.getBooleanValue('dark-mode', false, { userId: 'user-123' });
```

## 快速启动——云浮工人

建议对Cloudflare工人采取的办法。 使用扳手绑定——不需要HTTP上架,不需要认证符.

配置在 `wrangler.json`数字 :

```jsonc
{
  "flagship": [{ "binding": "FLAGS", "app_id": "<your-app-id>" }]
}
```

```typescript
import { OpenFeature } from '@openfeature/server-sdk';
import { FlagshipServerProvider } from '@cloudflare/flagship/server';
import type { FlagshipBinding } from '@cloudflare/flagship/server';

export default {
  async fetch(request: Request, env: { FLAGS: FlagshipBinding }): Promise<Response> {
    await OpenFeature.setProviderAndWait(new FlagshipServerProvider({ binding: env.FLAGS }));

    const client = OpenFeature.getClient();
    const darkMode = await client.getBooleanValue('dark-mode', false, {
      targetingKey: new URL(request.url).searchParams.get('userId') ?? 'anonymous',
    });

    return Response.json({ darkMode });
  },
};
```

## 快速启动 — HTTP

对于没有旗舰绑定或非工人服务器环境的工人:

```typescript
import { OpenFeature } from '@openfeature/server-sdk';
import { FlagshipServerProvider } from '@cloudflare/flagship/server';

let initialized = false;

export default {
  async fetch(request: Request): Promise<Response> {
    if (!initialized) {
      await OpenFeature.setProviderAndWait(
        new FlagshipServerProvider({ appId: 'your-app-id', accountId: 'your-account-id', authToken: 'your-token' }),
      );
      initialized = true;
    }

    const client = OpenFeature.getClient();
    const darkMode = await client.getBooleanValue('dark-mode', false, {
      userId: new URL(request.url).searchParams.get('userId') ?? 'anonymous',
    });

    return Response.json({ darkMode });
  },
};
```

## 结构化评价背景

绑定和 HTTP 模式支持嵌入对象、阵列和 `null` 在评价方面。 日期被递归转换为ISO-8601字符串.

```typescript
const checkout = await client.getStringValue('checkout-flow', 'control', {
  targetingKey: 'user-123',
  profile: { account: { plan: 'enterprise' } },
  tags: ['beta', 'internal'],
});
```

原始的仅HTTP上下文继续使用GET查询参数. 结构化背景,包括 `null`,使用 JSON POST 端点;在浏览器中此选项添加了 CORS 飞行前请求。 只有弦,数字,布尔斯, `null`、日期、数组和平面对象均得到支持。 其他任何东西,包括循环值,都与 `INVALID_CONTEXT` 无需装订或HTTP呼叫.

## 缓存

服务器提供商可以缓存评价来避免网络回行(HTTP模式)或对重复的旗/上线对的绑定调用(绑定模式). 缓存是 **默认关闭** 通过设置 `cacheTtl`数字 :

```typescript
new FlagshipServerProvider({
  appId: 'your-app-id',
  accountId: 'your-account-id',
  cacheTtl: 30_000, // ms — enables caching; values may be up to this stale
  cacheMaxSize: 1000, // max cached entries, LRU-evicted (default: 1000)
});
```

每个条目按旗下键键、类型和 **全面评价背景**,所以不同的情况 从来没有共享一个价值。 缓存点击解析 `reason: 'CACHED'`。禁用旗帜和错误永远不会被缓存。 由于新鲜度以TTL为主,在条目到期后,Flagship的一面国旗更名生效.

## 地方评价

服务器提供者可以一次下载旗下定义,并在过程中评价旗下,每次评价没有网络呼叫. 定义在背景中轻而易举地更新(在评价时更新).

```typescript
await OpenFeature.setProviderAndWait(
  new FlagshipServerProvider({
    appId: 'your-app-id',
    accountId: 'your-account-id', // required — used as the rollout hash seed
    authToken: 'your-read-token', // needs app **read** permission, not evaluate
    localEvaluation: true,
    refreshInterval: 30_000, // ms between background refreshes (default 30s)
  }),
);
```

注释:

-   与 `binding` 模式和模式 `cacheTtl` (没有什么可缓存的).
-   `accountId` 总是需要本地模式,包括何时 `endpoint` 已使用.
-   与 `endpoint`, URL 路径必须结束于 `/evaluate` 这样 `/definitions` 可导出.
-   地方评价 **没有** 出现在服务器侧分析中.
-   见 [`examples/server-local.ts`](https://npmcn.com/package/%40cloudflare/flagship/examples/server-local.ts)。 。 。 .

## 快速启动 — 浏览器

```typescript
import { OpenFeature } from '@openfeature/web-sdk';
import { FlagshipClientProvider } from '@cloudflare/flagship/web';

await OpenFeature.setProviderAndWait(
  new FlagshipClientProvider({
    appId: 'your-app-id',
    accountId: 'your-account-id',
    authToken: 'your-token',
  }),
);

await OpenFeature.setContext({ userId: 'user-123', plan: 'premium' });

const client = OpenFeature.getClient();
const darkMode = client.getBooleanValue('dark-mode', false);
```

## 特征

| 特性 | 说明 |
| --- | --- |
| OpenFeet 兼容性 | 执行 CNCF OpenFeature 规格 |
| 约束工人 | 本地 wrangler 绑定支持 – 0 HTTP 上方, 无认证符 |
| 服务器+客户端 | Async 按请求( 服务器) 和同步缓存( 浏览器) 提供者 |
| 服务器提供者 | `FlagshipServerProvider` 通过 HTTP 、 本地评价或wrangler 绑定工作 |
| 地方评价 | 从下载的定义中进行过程内评价(`localEvaluation: true`(中文(简体) ) |
| 所有旗帜类型 | 布尔、 字符串、 数字和对象( JSON) |
| 认证 | `authToken` 选项添加 `Authorization: Bearer` 切换到每个请求(仅 HTTP) |
| 日志 | `logging` 选项表面获取出错和缓存缺失(默认关闭) |
| 响应缓存 | 以 TTL + LRU 缓存键通过 `cacheTtl` (默认关闭) |
| 重复+超时 | 可配置重试逻辑 `AbortController`\- 基于超时(仅限HTTP) |
| 自定义运输 | 弹出 `fetch` 每个客户或每个呼叫——无全球变异(仅HTTP) |
| 取消 | 打电话者 `AbortSignal` 中止飞行中的请求, 永远不要重试( 只有HTTP) |
| 钩子 | 内建 `LoggingHook` 财务报告和审定财务报表 `TelemetryHook` |
| 树能震动 | 服务器和客户端捆绑完全隔离 |
| 类型脚本 | 整个严格类型 |

## 软件包

| 导出 | 说明 | 同伴依赖关系 |
| --- | --- | --- |
| `@cloudflare/flagship` | 核心客户端、类型、错误 | 无 |
| `@cloudflare/flagship/server` | `FlagshipServerProvider` + 钩 | `@openfeature/server-sdk` |
| `@cloudflare/flagship/web` | `FlagshipClientProvider` | `@openfeature/web-sdk` |

## 文档

-   [API 参考](https://npmcn.com/package/%40cloudflare/flagship/API.md)
-   [OpenFeature 规格](https://openfeature.dev/specification/)
-   [实例](https://npmcn.com/package/%40cloudflare/flagship/examples/)

## 发展

```bash
pnpm install         # install dependencies
pnpm run dev         # watch mode
pnpm run test        # run tests
pnpm run build       # build for distribution
```

## 捐款

欢迎捐款。 请先开出一个问题来讨论你想要改变什么. 见 [仓库](https://github.com/cloudflare/flagship) 更多细节.

## 许可证

[阿帕奇 - 2.0](https://npmcn.com/package/LICENSE)

## 常见问题

### @cloudflare/flagship 是什么？

旗舰特性旗的 OpenFeature 提供者

### 如何安装 @cloudflare/flagship？

在项目目录运行 npm install @cloudflare/flagship，或使用 pnpm add / yarn add / bun add。

### @cloudflare/flagship 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @cloudflare/flagship 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @cloudflare/flagship 可以商用吗？

@cloudflare/flagship 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @cloudflare/flagship 的下载量有多少？

根据 npm 官方下载统计，@cloudflare/flagship 在 2026/10/10 – 2026/11/08 这 30 天内被下载 357,720 次，日均约 11,924 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @cloudflare/flagship 还在维护吗？

最新版本 0\.7\.0 发布于 2026/11/04（5 天前）；至今共发布 14 个版本，其中过去 12 个月发布了 14 个；首次发布于 2026/03/30。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

