# @cf-platform/cim

> CIM 协议传输层 — WebSocket + Protobuf 编解码

Latest version **2.0.0** (published 2026-07-03) · ISC license · 0 weekly downloads

## Install

```sh
npm install @cf-platform/cim
pnpm add @cf-platform/cim
yarn add @cf-platform/cim
bun add @cf-platform/cim
```

## Health

**Score 55/100 (C)** — status: active.

Positive: has types; esm support; no vulnerabilities.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 2.0.0 |
| Published | 2026-07-03 |
| First published | 2024-04-07 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 1 |
| Unpacked size | 29.6 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | maomao |
| Maintainers | object_fu |
| Keywords | cim |

## Links

- npm: https://www.npmjs.com/package/@cf-platform/cim
- npm.io page: https://npm.io/package/@cf-platform/cim

## Dependencies (1)

- [@mm-custom/method](https://npm.io/package/@mm-custom/method.md) ^2.2.11

## Alternatives

- [random-seedable](https://npm.io/package/random-seedable.md) — 27.9K weekly downloads
- [n2words](https://npm.io/package/n2words.md) — 22.2K weekly downloads
- [@stdlib/math-base-special-factorialln](https://npm.io/package/@stdlib/math-base-special-factorialln.md) — 5.7K weekly downloads
- [@stdlib/math-base-special-abs2](https://npm.io/package/@stdlib/math-base-special-abs2.md) — 1.7K weekly downloads
- [commons-math-interpolation](https://npm.io/package/commons-math-interpolation.md) — 1.4K weekly downloads

## Recent versions

- 2.0.0 (latest) — 2026-07-03
- 1.0.2 — 2026-04-16
- 1.0.1 — 2024-04-07
- 1.0.0 — 2024-04-07

## README

# @cf-platform/cim

基于 WebSocket 的 CIM 协议传输层库，负责 Protobuf 编解码和 WebSocket 连接管理。**不包含**心跳检测、自动重连、认证流程等业务逻辑——这些由上层 `@cf-platform/mq` 的 CimAdapter 提供。

## 定位

```
┌─────────────────────────────────┐
│ @cf-platform/mq  (业务层)        │
│ • 心跳管理 / 重连策略 / 鉴权流程   │
├─────────────────────────────────┤
│ @cf-platform/cim (传输层) ← 本库  │
│ • WebSocket 连接                 │
│ • Protobuf 编解码 (Message/       │
│   ReplyBody/SentBody)            │
│ • PING→PONG 自动响应             │
└─────────────────────────────────┘
```

## 特性

- 🔌 **WebSocket 连接** — 纯粹的 WebSocket 生命周期管理
- 📦 **Protobuf 编解码** — 手写轻量 Protobuf 实现，零外部依赖（无 google-protobuf/Closure Library）
- 🔢 **int64 varint** — varint 编解码完整支持 int64（时间戳 / ID 等），不被截断到 32 位
- ⚡ **PING/PONG** — 自动响应服务端心跳
- 🎯 **类型安全** — 完整 TypeScript 类型定义
- 🪶 **极轻量** — ES 包仅 ~10.5 kB (gzip ~2.9 kB)

## 安装

```bash
npm install @cf-platform/cim
```

## 快速开始

```typescript
import { CIM } from '@cf-platform/cim'

const cim = new CIM({
  url: 'wss://127.0.0.1:8080'
})

// 绑定回调
cim.onOpen = (event) => console.log('WebSocket 已连接')
cim.onMessage = (msg) => console.log('收到消息:', msg)
cim.onReply = (reply) => console.log('收到回复:', reply)
cim.onClose = (event) => console.log('连接关闭:', event.code)
cim.onError = (event) => console.error('连接错误')
cim.onPing = () => console.log('收到服务端心跳')

// 建立连接
cim.connect()

// 发送消息
cim.sendMessage({
  key: 'send_message',
  content: 'Hello World',
  receiver: 'user456'
})

// 关闭连接
cim.close()
```

> **提示**：大多数场景下你不需要直接使用本库，推荐使用 `@cf-platform/mq` 的 `createCimMq()`，它在本库之上提供了心跳检测、自动重连、认证管理等完整功能。

## API 文档

### CIMOptions

| 参数 | 类型 | 默认值 | 必填 | 描述 |
|------|------|--------|------|------|
| url | `string` | - | ✓ | WebSocket 服务器地址（ws:// 或 wss://） |
| protocols | `string \| string[]` | - | | WebSocket 子协议 |

### CIM 类

#### 构造函数

```typescript
constructor(options: CIMOptions)
```

#### 连接管理

| 方法 | 返回值 | 描述 |
|------|--------|------|
| `connect()` | `void` | 建立 WebSocket 连接 |
| `reconnect()` | `void` | 重新连接（等价于 close + connect） |
| `close()` | `void` | 关闭连接，清理所有事件监听 |

#### 消息发送

| 方法 | 返回值 | 描述 |
|------|--------|------|
| `sendMessage(data)` | `boolean` | 编码为 Protobuf 并发送，返回是否成功 |
| `sendPong()` | `void` | 发送 PONG 心跳响应（通常由内部自动调用） |

#### 状态查询

| 方法 | 返回值 | 描述 |
|------|--------|------|
| `getConnectionState()` | `number` | WebSocket readyState (0-3) |
| `isConnected()` | `boolean` | readyState === OPEN |
| `isConnecting()` | `boolean` | readyState === CONNECTING |
| `isClosing()` | `boolean` | readyState === CLOSING |
| `isClosed()` | `boolean` | readyState === CLOSED |

#### 回调钩子

| 回调 | 类型 | 触发时机 |
|------|------|----------|
| `onOpen` | `(event: Event) => void` | WebSocket 连接建立 |
| `onClose` | `(event: CloseEvent) => void` | WebSocket 连接关闭 |
| `onError` | `(event: Event) => void` | WebSocket 连接错误 |
| `onMessage` | `(msg: ReceivedMessage) => void` | 收到 Protobuf 解码后的普通消息 |
| `onReply` | `(reply: ReplyMessage) => void` | 收到 Protobuf 解码后的回复消息 |
| `onPing` | `() => void` | 收到服务端 PING（上层可用于心跳超时重置） |

### 导出的枚举和常量

#### MessageType

```typescript
enum MessageType {
  PONG = 0,       // 客户端发送心跳
  PING = 1,       // 服务端发送心跳
  MESSAGE = 2,    // 服务端发送消息
  SENT_BODY = 3,  // 客户端发送消息
  REPLY_BODY = 4  // 服务端回复消息
}
```

#### AuthenticationConstants

```typescript
const AuthenticationConstants = {
  PONG_BODY:          new Uint8Array([80, 79, 78, 71]),
  CODE_UNAUTHORIZED:  '401',
  CODE_OK:            '200',
  CLIENT_BIND:        'client_bind',
  CLIENT_CLOSED:      'client_closed',
  CLIENT_HANDSHAKE:   'client_handshake',
  FORCE_OFFLINE:      '999'
}
```

### 类型定义

```typescript
// 发送消息结构（protobuf map<string,string>，value 仅支持 string）
interface CIMMessage {
  key: string
  [key: string]: string
}

// 解码后的普通消息
interface ReceivedMessage {
  action?: string
  content?: string
  sender?: string
  receiver?: string
  timestamp?: number
  [key: string]: any
}

// 解码后的回复消息
interface ReplyMessage {
  code: string
  key: string
  message: string
  timestamp: number
  data: Record<string, any>
}
```

## 与 @cf-platform/mq 的关系

本库是 CIM 协议的**传输层**实现。如需完整功能，请使用 `@cf-platform/mq`：

| 功能 | @cf-platform/cim | @cf-platform/mq (CimAdapter) |
|------|:---:|:---:|
| WebSocket 连接 | ✅ | ✅ |
| Protobuf 编解码 | ✅ | ✅ |
| PING→PONG 响应 | ✅ | ✅ |
| 心跳超时检测 | ❌ | ✅ |
| 自动重连 | ❌ | ✅ |
| CLIENT_BIND 认证 | ❌ | ✅ |
| HANDSHAKE 鉴权 | ❌ | ✅ |
| 强制下线处理 | ❌ | ✅ |
| EventManager 事件 | ❌ | ✅ |

## 更新日志

### v2.0.1 (修复)

- 🐛 **修复 varint 64 位截断** — `readVarint`/`writeVarint` 原先用 `>>> 0` 截断到 uint32，导致 `timestamp`/`id` 等 int64 字段在 `Date.now()` 量级（> 2^32）时丢失高位。现改用「低位按位 + 高位加权」/「取模分段」实现，正确支持到 `Number.MAX_SAFE_INTEGER`
- 🐛 **修复 map 反序列化字段顺序依赖** — `ReplyBody`/`SentBody` 的 `map<string,string>` 反序列化原先假定 entry 内 key(字段1) 在 value(字段2) 之前。现用临时变量收集后统一 set，兼容任意字段顺序
- 🧹 移除未使用的 `_manualClose` 内部状态

### v2.0.0 (重构)

- 🔥 **Breaking**: 移除心跳检测、自动重连、认证流程 — 迁移至 `@cf-platform/mq` 的 CimAdapter
- 🔥 **Breaking**: 移除 `CustomEvents`、`LoginConfiguration`、`LoginParams` 类型
- 🔥 **Breaking**: `CIMOptions` 精简为 `url` + `protocols`
- 🆕 Protobuf 手写 TS 实现，移除 google-protobuf 依赖（SDK 体积从 ~8000 行降至 ~270 行）
- 🆕 新增 `onPing`、`onReply` 回调钩子
- ✨ CIM 退化为纯传输层，职责单一

## 许可证

ISC

---
_Source: https://npm.io/package/@cf-platform/cim · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
