npm package: @oichat/sdk
Description: OiChat TypeScript SDK — Real-time chat SDK for web and React Native
Latest version: 0.1.1

<p align="center">
  <img src="https://oichatapi.com/og-image.png" alt="OiChat" width="100%" />
</p>

<p align="center">
  <a href="https://www.npmjs.com/package/@oichat/sdk"><img src="https://img.shields.io/npm/v/@oichat/sdk?color=blue" alt="npm version" /></a>
  <a href="https://www.npmjs.com/package/@oichat/sdk"><img src="https://img.shields.io/npm/dm/@oichat/sdk" alt="npm downloads" /></a>
  <a href="https://github.com/oichatapi/oichat-samples/tree/main/react-client"><img src="https://img.shields.io/badge/sample-React-61dafb?logo=react" alt="Sample" /></a>
  <a href="https://oichatapi.com"><img src="https://img.shields.io/badge/docs-oichatapi.com-blue" alt="Docs" /></a>
  <a href="LICENSE"><img src="https://img.shields.io/npm/l/@oichat/sdk" alt="License" /></a>
</p>

# @oichat/sdk

Real-time chat SDK for web and React Native — REST API client + Centrifugo WebSocket integration.

> **[한국어](#한국어)** | [English](#installation)

## Installation

```bash
npm install @oichat/sdk
# or
yarn add @oichat/sdk
```

## Quick Start

### Server Mode

Your backend issues JWT tokens and passes them to the client.

```typescript
import { OiChat } from "@oichat/sdk";

const oichat = OiChat.init(
  {
    apiUrl: "https://api.oichatapi.com",
    wsUrl: "wss://ws.oichatapi.com/connection/websocket",
    projectId: "proj_xxxxxxxxxxxx",
    secretKey: "sk_xxxxxxxxxxxx",
  },
  { userId: "user-123" },
);

// Connect with JWT token from your backend
await oichat.realtime.connect({ token: jwtFromServer });
```

### Client Mode

SDK handles token issuance and auto-refresh internally.

```typescript
import { OiChat } from "@oichat/sdk";

const oichat = await OiChat.initClient(
  {
    apiUrl: "https://api.oichatapi.com",
    wsUrl: "wss://ws.oichatapi.com/connection/websocket",
    projectId: "proj_xxxxxxxxxxxx",
    publicKey: "pk_xxxxxxxxxxxx",
  },
  { userId: "user-123", userName: "John Doe" },
);
```

## Core APIs

### Rooms

```typescript
// List rooms
const { data, next_cursor } = await oichat.rooms.list({ limit: 20 });

// Create room
const room = await oichat.rooms.create({
  type: "group",
  name: "Support Chat",
  participant_ids: ["user-1", "user-2"],
});
```

### Messages

```typescript
// Subscribe to a room
const sub = await oichat.realtime.subscribeRoom("room-id");

// Listen for new messages
sub.onMessage((message) => {
  console.log(message.content);
});

// Send a message
await oichat.messages.send({
  room_id: "room-id",
  content: "Hello!",
  content_type: "text",
});
```

### Real-time Events

```typescript
// Typing indicator
sub.onTyping((event) => {
  console.log(`${event.user_id} is typing...`);
});

// Read receipts
sub.onRead((event) => {
  console.log(`${event.user_id} read messages`);
});

// Connection state
oichat.realtime.onConnectionStateChange.on((state) => {
  console.log("Connection:", state); // 'connecting' | 'connected' | 'disconnected'
});
```

### Push Notifications

```typescript
// Register FCM token
await oichat.push.registerToken({
  token: fcmToken,
  device_type: "web",
});
```

### File Upload

```typescript
// Upload with progress
const result = await oichat.messages.sendWithAttachment({
  room_id: "room-id",
  file,
  onProgress: (percent) => console.log(`${percent}%`),
});
```

## Cleanup

```typescript
// Disconnect and release resources
oichat.dispose();
```

## Links

- [Documentation](https://oichatapi.com) — Full guides and API reference
- [Sample: React + Next.js](https://github.com/oichatapi/oichat-samples/tree/main/react-client) — Complete working example
- [UI Components (@oichat/ui-react)](https://www.npmjs.com/package/@oichat/ui-react) — Pre-built chat widgets
- [Server SDK (@oichat/server-sdk)](https://www.npmjs.com/package/@oichat/server-sdk) — Backend token issuance & room management

---

## 한국어

모바일 앱과 웹에 채팅을 붙이는 가장 쉬운 방법 — REST API 클라이언트 + Centrifugo WebSocket 실시간 통신.

### 설치

```bash
npm install @oichat/sdk
# 또는
yarn add @oichat/sdk
```

### 빠른 시작

#### 서버 모드

백엔드에서 JWT 토큰을 발급하여 클라이언트에 전달하는 방식입니다.

```typescript
import { OiChat } from "@oichat/sdk";

const oichat = OiChat.init(
  {
    apiUrl: "https://api.oichatapi.com",
    wsUrl: "wss://ws.oichatapi.com/connection/websocket",
    projectId: "proj_xxxxxxxxxxxx",
    secretKey: "sk_xxxxxxxxxxxx",
  },
  { userId: "user-123" },
);

// 백엔드에서 받은 JWT 토큰으로 연결
await oichat.realtime.connect({ token: jwtFromServer });
```

#### 클라이언트 모드

SDK가 자동으로 토큰 발급/갱신 + 연결을 처리합니다.

```typescript
import { OiChat } from "@oichat/sdk";

const oichat = await OiChat.initClient(
  {
    apiUrl: "https://api.oichatapi.com",
    wsUrl: "wss://ws.oichatapi.com/connection/websocket",
    projectId: "proj_xxxxxxxxxxxx",
    publicKey: "pk_xxxxxxxxxxxx",
  },
  { userId: "user-123", userName: "홍길동" },
);
```

### 주요 기능

| 기능          | 설명                      |
| ------------- | ------------------------- |
| 채팅방 관리   | 생성, 목록, 참여, 나가기  |
| 실시간 메시징 | Centrifugo WebSocket 기반 |
| 프레전스      | 온라인/오프라인 상태 추적 |
| 파일 업로드   | 이미지, 파일 전송 지원    |
| 푸시 알림     | FCM 토큰 등록             |
| 멀티 테넌트   | 프로젝트 단위 데이터 격리 |

### 관련 링크

- [공식 문서](https://oichatapi.com) — 가이드 및 API 레퍼런스
- [샘플: React + Next.js](https://github.com/oichatapi/oichat-samples/tree/main/react-client) — 전체 동작 예제
- [UI 컴포넌트 (@oichat/ui-react)](https://www.npmjs.com/package/@oichat/ui-react) — 즉시 사용 가능한 채팅 위젯
- [서버 SDK (@oichat/server-sdk)](https://www.npmjs.com/package/@oichat/server-sdk) — 백엔드 토큰 발급 및 방 관리

## License

MIT