# @ganache/flavor 中文文档

规范地址：https://npmcn.com/package/%40ganache/flavor/

版本：0\.10\.2
npm 元数据更新时间：2023-12-21T00:20:02.542Z
中文译文更新时间：2026-11-15T22:28:33.255Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40ganache/flavor
原文对照：https://npmcn.com/package/%40ganache/flavor/?lang=original
项目主页：https://github.com/trufflesuite/ganache/tree/develop/packages/flavor#readme
源码仓库：https://github.com/trufflesuite/ganache

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

- 包体积（解压后）：66.8 kB，52 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：5 个
- 首次发布：2023-08-22T21:59:12.351Z
- 最新版本发布：2023-12-21T00:20:02.218Z
- 近 30 天下载量：2212（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：2（近 12 个月 0 个）

## 中文简介

Ganache 的口味计数和类型

## 安装

```sh
npm install @ganache/flavor
```

也可以使用：`pnpm add @ganache/flavor`、`yarn add @ganache/flavor`、`bun add @ganache/flavor`

## README

# `@ganache/flavor`

Ganache的口味 TypeScript 类型,帮助器,和效用功能.

Ganache Flavors 是可用于启动链条测试网络的插件 除了Ganache的内置Ethereum网络。 在运行时通过 加纳切的 `--flavor` 旗帜.

### 警告和发现

Ganache的口味是实验性的,不完整的,可以不改变 备注.

Ganache的口味是Ethereum JSON-RPC(2.0)的灵感,我们仍在工作 了解其他链条的需求以及如何延长甘纳切口味 在HTTP/WS上支持JSON-RPC 2.0以外的传输的模型.

非JSON-RPC链的一个缺陷实例:

-   ganache 只接受 POST 在一个可配置路径上的请求( 默认) 改为 `/`) (中文(简体) ). 如果你需要别的东西,如JSON over REST,GRPC,SOAP, 等,请打开一个问题描述您的使用案例 .
-   基于 websocket 订阅的邮件非常有限,只支持 就像Ethereum JSON -RPC那样.

### 如何创建实验性甘露口味

要创造出新的口味, 您必须创建一个新包, 导出一个 `Flavor`A级 口味是一个 JavaScript 对象,用于执行 `Flavor` TypeScript 接口.

以下是TypeScript中"Hello World"风格口味的例子:

```typescript
import { Flavor, Connector, CliSettings } from "@ganache/flavor";

export type Provider = { sayHi: (name: string) => string };
export type RequestPayload = { name: string };
export type ResponsePayload = { result: string };

const provider: Provider = {
  sayHi(name: string) {
    return `Hello, ${name}`;
  }
};

const helloConnector: Connector<Provider, RequestPayload, ResponsePayload> = {
  // the `provider` is yours to implement however you'd like. In programmatic
  // usage it will be returned to the user when they call
  // `Ganache.provider()` or `Ganache.server().provider`
  provider,

  async connect(): Promise<void> {
    // ganache will `await` the return of your `connect` method before
    // forwarding any requests to your connector.
    // if your connector doesn't need to do any async work to initialize you
    // can leave this empty.
  },

  parse(message: Buffer) {
    // the `message` doesn't have to be JSON, you can use any data interchange
    // format you'd like.
    // NOTE: If your connector's `parse` method throws, Ganache does
    // _not_ call your `formatError` and instead returns a `400 Bad Request`
    // response.
    return JSON.parse(message);
  },

  async handle(
    this: typeof helloConnector,
    payload: RequestPayload
  ): Promise<{ value: unknown }> {
    if (!payload || typeof payload.name !== "string") {
      // you can throw an Exception here and ganache will catch the error and
      // pass it to your `formatError` function.
      throw new Error("payload must have a `name` property of type `string`");
    }

    // in this "Hello World" example we only have one method, but you can
    // implement as many as you need in any way you want. Here we just call the
    // our provider's `sayHi` with the user provided `payload`'s `name`
    //  property.
    const value = this.provider.sayHi(payload.name);

    // Your `handle` function MUST always return any object with a `value`
    // property. The value of `value` MAY itself be a `Promise`. The _resolved_
    // `value` will be passed to your connector's `format` function.
    //
    // NOTE: if a client is connected via WebSockets, and the the `value` is a
    // `PromiEvent` (a `Promise` that also has an `on` function) that emits a
    // `"message"` event Ganache will subscribe to the `"message"` event. If
    // the `PromiEvent` then emits a "message" its event data will be sent to
    // the client.
    // ATTENTION: A flavor cannot `format` this message though; it will always
    // be sent as am Ethereum JSON-RPC 2.0 subscription style message. This
    // behavior will change in the future *without notice*. It is not recommened
    // that you use the PromiEvent feature at this time.
    return { value };
  },

  format(result: ResponsePayload, payload: RequestPayload) {
    console.log(
      `formatting result (${result.result}) for payload (${payload.name})`
    );
    // You don't have to return a string here, you can also return a Buffer
    // and the serialization doesn't have to be JSON. However...
    // ATTENTION: ganache flavors don't yet support changing the `content-type`
    // header so it always returns `content-type: application/json`. This will
    // change in the future and flavors will be able to specify their own
    // content-type and other HTTP headers.
    //
    // You can also return a Generator (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator)
    // which will cause ganache to send the response in chunks (one chunk for
    // yield). This is useful if your response data is too large for Node.js to
    // handle (string and Buffer sizes are limited to about 1-2GB, and memory is
    // capped to 4GB on most systems).
    return JSON.stringify({ result });
  },

  formatError(error: Error, payload: RequestPayload) {
    // Ganache calls your `formatError` if any errors occured while processing
    // a request.

    console.log(`formatting error (${error.message}) for payload (${payload})`);
    // you don't have to return a string here, you can also return a Buffer
    // and the serialization doesn't have to be JSON
    return JSON.stringify({ error: error.message });
  },

  async close() {
    // ganache calls your connector's `close` function when shutting down.
    // This is where you'd perform clean up, like closing database connections
    // or cleaning temporary files.
  }
};

type HelloFlavor = Flavor<"hello-chain", typeof helloConnector>;

const HelloFlavor: HelloFlavor = {
  flavor: "hello-chain",
  options: {
    // see the `example/` directory for how Options work
  },
  connect(providerOptions: never) {
    return helloConnector;
  },
  // the `ready` function is required for your flavor to work with ganache on
  // the CLI
  ready: ({
    provider,
    options
  }: {
    provider: Provider;
    options: { server: CliSettings };
  }) => {
    // this function is only called after ganache has fully initialized, and is
    // only called when used via ganache cli (it is not used when your flavor is
    // used programatically)
    console.log(
      `Hello Chain server is running at http://${options.server.host}:${options.server.port}`
    );
  }
};

/**
 * Your flavor needs to be exported as `default` so Ganache can find it.
 */
export default HelloFlavor;
```

看看这个 [实例执行](https://npmcn.com/package/%40ganache/flavor/example) 更深层次的例子.

## 常见问题

### @ganache/flavor 是什么？

Ganache 的口味计数和类型

### 如何安装 @ganache/flavor？

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

### @ganache/flavor 支持 TypeScript 吗？

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

### @ganache/flavor 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @ganache/flavor 可以商用吗？

@ganache/flavor 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @ganache/flavor 的下载量有多少？

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

### @ganache/flavor 还在维护吗？

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

