@basenative/flags

中文文档
3.0.0发布于 2026/10/31Apache-2.0TypeScriptES Module构建来源已验证

Feature flags with percentage rollouts and @feature template directive

原始使用文档
文档目录11 节
  1. Install
  2. Quick Start
  3. Server Middleware
  4. Template Directive: @feature
  5. createFlagContext(flagManager, context?)
  6. API
  7. createFlagManager(provider, options?)
  8. Flag Config Shape
  9. Providers
  10. flagMiddleware(flagManager, options?)
  11. License

@basenative/flags

Feature flags with percentage rollouts, rule-based targeting, and pluggable providers

Part of the BaseNative ecosystem — a signal-based web runtime over native HTML.

Install

npm install @basenative/flags

Quick Start

import { createFlagManager, createMemoryProvider } from '@basenative/flags';

const provider = createMemoryProvider({
  newDashboard: { enabled: true },
  betaSearch: { percentage: 20 },
  premiumFeature: {
    enabled: false,
    rules: [{ attribute: 'plan', value: 'pro', value: true }],
  },
});

const flags = createFlagManager(provider);

// Simple boolean check
const showNew = await flags.isEnabled('newDashboard'); // true

// Percentage rollout (consistent per userId)
const inBeta = await flags.isEnabled('betaSearch', { userId: 'user-42' });

// Get all flags for client hydration
const allFlags = await flags.getAll({ userId: 'user-42' });

Server Middleware

import { flagMiddleware } from '@basenative/flags';
import { createPipeline } from '@basenative/middleware';

const pipeline = createPipeline()
  .use(flagMiddleware(flags));
// ctx.state.flags is now an object of resolved flag values

Template Directive: @feature

@basenative/flags registers a @feature template directive with @basenative/runtime's directive registry as a side effect of importing this package — it works anywhere render() (SSR) or hydrate() (client) runs, with no extra wiring:

<template @feature="newDashboard">
  <p>Try the new dashboard.</p>
</template>
<template @else>
  <p>Classic dashboard.</p>
</template>

@feature reads ctx.$flags from the render/hydrate context — a synchronous { isEnabled(name) } object. flagManager.isEnabled() is async (it awaits the provider), while template rendering is synchronous end to end, so resolve every flag once, ahead of render, with createFlagContext():

import { createFlagManager, createMemoryProvider, createFlagContext } from '@basenative/flags';
import { render } from '@basenative/server';

const flags = createFlagManager(createMemoryProvider({ newDashboard: { enabled: true } }));
const $flags = await createFlagContext(flags, { userId: user.id });

const html = render(template, { ...data, $flags });

On the client, hydrate with the same shape — typically embedded from the server response (e.g. $flags.flags) and reconstructed as { isEnabled: (name) => Boolean(flags[name]) }, or a live object if you want flags to react to change:

import { hydrate } from '@basenative/runtime';

hydrate(root, { ...data, $flags: { isEnabled: (name) => window.__FLAGS__[name] } });

With no $flags on context, @feature treats the flag as disabled — it renders @else if present, otherwise nothing — and emits a BN_FEATURE_NO_PROVIDER diagnostic (via options.onDiagnostic) rather than guessing "enabled" for a flag it cannot evaluate. flagName is a literal flag name, not an expression — no quotes, unlike @if/@switch.

On a non-<template> element, @feature="x" is not control flow — like any other @name there, it becomes an event listener named feature, and @basenative/validate flags this as BN_E_CONTROL_FLOW_ON_ELEMENT.

createFlagContext(flagManager, context?)

Resolves every flag once for context (same shape as isEnabled's context) and returns a plain synchronous snapshot: { flags: Record<string, boolean>, isEnabled: (name) => boolean }. Use its isEnabled on ctx.$flags for @feature.

API

createFlagManager(provider, options?)

Creates a flag evaluation manager. Options: defaultValue — value returned when a flag is not found (default: false).

Returns:

  • isEnabled(flagName, context?) — Returns Promise<boolean>. Context fields like userId and sessionId are used for percentage rollout hashing.
  • getAll(context?) — Returns Promise<Record<string, boolean>> with all flags resolved for the given context.
  • setFlag(flagName, config) — Updates a flag's config if the provider supports writes.

Flag Config Shape

{
  enabled: true,                   // simple boolean
  percentage: 25,                  // % rollout, 0-100
  rules: [                         // rule-based targeting
    { attribute: 'plan', value: 'pro', result: true }
  ]
}

Providers

  • createMemoryProvider(options) — In-memory provider. Options: flags — initial flag config map.
    • .getFlag(name) — Returns a flag config.
    • .getAllFlags() — Returns all flag configs.
    • .setFlag(name, config) — Updates a flag config.
  • createRemoteProvider(options) — Fetches flags from an HTTP endpoint. Options: url, token, ttl (cache TTL in ms).

flagMiddleware(flagManager, options?)

Resolves all flags for the current request context and sets ctx.state.flags. Options: getContext(ctx) — function to extract the evaluation context from the request context.

License

Apache-2.0

版本与发布记录

@basenative/flags 共发布 11 个版本,首次发布于 2026/03/20;过去 12 个月发布了 11 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.0.0latest2026/10/312 天前
2.4.02026/10/268 天前
2.3.22026/10/2212 天前
2.3.12026/10/2212 天前
2.3.02026/10/2212 天前
2.2.02026/10/2113 天前

关于 @basenative/flags 的常见问题

@basenative/flags 是什么?

带有percentage rollouts和@feature template指令的特性标志

如何安装 @basenative/flags?

在项目目录运行 npm install @basenative/flags,或使用 pnpm add / yarn add / bun add。

@basenative/flags 支持 TypeScript 吗?

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

@basenative/flags 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@basenative/flags 可以商用吗?

@basenative/flags 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@basenative/flags 还在维护吗?

最新版本 3.0.0 发布于 2026/10/31(2 天前);至今共发布 11 个版本,其中过去 12 个月发布了 11 个;首次发布于 2026/03/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。