npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

babitalk-chat-box-frontend

v1.0.1-beta.2

Published

Babitalk Chat Box Frontend

Readme

Babitalk Chat SDK

AWS Chime SDK를 활용한 범용 실시간 채팅 SDK와 데모 애플리케이션입니다. 웹 및 관리자 시스템에서 공통으로 사용할 수 있는 채팅 모듈을 제공합니다.

목차

빠른 시작

5분 만에 시작하기

# 1. SDK 설치
npm install git+https://github.com/babitalk/babitalk_chat_box_frontend.git#v1.0.0

# 2. 기본 설정
import { createServiceFactory, useAuth, ChatRoomList } from '@babitalk/chatbox-sdk';

// 3. SDK 초기화
createServiceFactory({ apiBaseUrl: '/api' });

# 4. 컴포넌트 사용
<ChatRoomList onRoomSelect={handleRoomSelect} onLogout={handleLogout} />

개발자 빠른 배포

# 개발 완료 후 즉시 배포
pnpm ship  # 빌드 + 버전업 + Git 푸시

프로젝트 구조

├── apps/
│   └── chatbox-demo/          # Next.js 기반 데모 애플리케이션
├── packages/
│   └── chatbox-sdk/           # @babitalk/chatbox-sdk - 범용 채팅 SDK
└── scripts/                   # 빌드 및 배포 스크립트

주요 기능

범용 채팅 SDK (@babitalk/chatbox-sdk)

  • 인증 시스템: JWT 토큰 기반 사용자 인증 및 자동 토큰 관리
  • 채팅방 관리: 채팅방 생성, 목록 조회, 참여/나가기
  • 실시간 메시지: AWS Chime SDK 기반 WebSocket 실시간 채팅
  • React 훅: 채팅 기능을 쉽게 사용할 수 있는 커스텀 훅 제공
  • TypeScript 완전 지원: 모든 API와 컴포넌트에 타입 정의 제공
  • Tailwind CSS: 모던하고 반응형 UI 컴포넌트
  • 서비스 팩토리 패턴: 의존성 주입 및 서비스 관리
  • 범용 모듈: 웹/관리자 시스템에서 공통 사용 가능

데모 애플리케이션 (chatbox-demo)

  • Next.js 14: 최신 App Router와 Server Components 활용
  • 완전한 채팅 UI: 로그인, 채팅방 목록, 실시간 채팅 인터페이스
  • 반응형 디자인: 데스크톱과 모바일 환경 완벽 지원
  • SDK 통합 예시: 라이브러리 사용법 실전 데모
  • API 프록시: 개발/프로덕션 환경 자동 API 라우팅

설치 및 실행

사전 요구사항

  • Node.js 18 이상
  • pnpm 8 이상

설치

# 저장소 클론
git clone <repository-url>
cd babitalk_chat_box_frontend

# 의존성 설치
pnpm install

개발 모드 실행

# 데모 애플리케이션 실행 (http://localhost:3000)
pnpm dev

# SDK 라이브러리 개발 모드 (watch 모드)
pnpm dev:sdk

빌드

# 전체 빌드 (SDK + 데모)
pnpm build

# SDK만 빌드
pnpm build:sdk

# 개별 패키지 정리
pnpm clean

SDK 사용법

기본 설정

import { createServiceFactory } from '@babitalk/chatbox-sdk';

// SDK 초기화
createServiceFactory({
  apiBaseUrl: '/api', // API 서버 URL
});

인증 시스템

import { useAuth } from '@babitalk/chatbox-sdk';

function LoginComponent() {
  const { login, logout, isAuthenticated, loading, error } = useAuth();

  const handleLogin = async (email: string, password: string) => {
    try {
      await login({ email, password });
    } catch (error) {
      console.error('로그인 실패:', error);
    }
  };

  if (loading) return <div>로딩 중...</div>;

  return (
    <div>
      {isAuthenticated ? (
        <button onClick={logout}>로그아웃</button>
      ) : (
        <button onClick={() => handleLogin('[email protected]', 'password')}>
          로그인
        </button>
      )}
      {error && <div className='error'>{error}</div>}
    </div>
  );
}

채팅방 목록

import { ChatRoomList } from '@babitalk/chatbox-sdk';

function ChatRoomListPage() {
  const handleRoomSelect = room => {
    // 선택한 채팅방으로 이동
    router.push(`/chat/${room.id}`);
  };

  const handleLogout = () => {
    // 로그아웃 후 홈으로 이동
    router.push('/');
  };

  return (
    <ChatRoomList onRoomSelect={handleRoomSelect} onLogout={handleLogout} />
  );
}

채팅방 인터페이스

import { ChatRoomComponent } from '@babitalk/chatbox-sdk';

function ChatPage({ params }: { params: { roomId: string } }) {
  const room = { id: parseInt(params.roomId), name: 'Chat Room' };

  return <ChatRoomComponent room={room} onBack={() => router.back()} />;
}

커스텀 훅 활용

import { useChatRoom, useAuth, useChatRoomList } from '@babitalk/chatbox-sdk';

function CustomChatComponent() {
  const { isAuthenticated } = useAuth();
  const {
    rooms,
    loading: roomsLoading,
    createRoom,
    refreshRooms,
  } = useChatRoomList();

  const room = rooms[0];
  const { messages, loading, error, sendMessage, isConnected } = useChatRoom({
    room,
    onError: error => console.error('채팅 에러:', error),
    onConnectionChange: connected => console.log('연결 상태:', connected),
  });

  const handleSendMessage = async (content: string) => {
    try {
      await sendMessage(content);
    } catch (error) {
      console.error('메시지 전송 실패:', error);
    }
  };

  return (
    <div className='chat-container'>
      <div className='connection-status'>
        {isConnected ? '🟢 연결됨' : '🔴 연결 끊김'}
      </div>

      <div className='messages'>
        {messages.map(message => (
          <div key={message.id} className='message'>
            <strong>{message.sender.name}</strong>: {message.content}
            <small>{new Date(message.created_at).toLocaleTimeString()}</small>
          </div>
        ))}
      </div>

      <MessageInput onSend={handleSendMessage} disabled={!isConnected} />
    </div>
  );
}

API 문서

주요 타입

// 채팅방
interface ChatRoom {
  id: number;
  name: string;
  member_count?: number;
  is_active?: boolean;
  created_at?: string;
  channel_arn?: string; // AWS Chime 채널 ARN
}

// 채팅 메시지
interface ChatMessage {
  id: string;
  content: string;
  created_at: string;
  sender: {
    id: number;
    name: string;
  };
  type: 'text' | 'system';
}

// 사용자
interface User {
  id: number;
  name: string;
  email?: string;
}

// 인증 정보
interface AuthCredentials {
  email: string;
  password: string;
}

주요 훅

useAuth()

interface UseAuthReturn {
  isAuthenticated: boolean;
  loading: boolean;
  error: string | null;
  login: (credentials: AuthCredentials) => Promise<void>;
  logout: () => Promise<void>;
  refreshToken: () => Promise<string>;
}

useChatRoom(options)

interface UseChatRoomOptions {
  room: ChatRoom;
  onError?: (error: Error) => void;
  onConnectionChange?: (isConnected: boolean) => void;
  onMessageReceived?: (message: ChatMessage) => void;
}

interface UseChatRoomReturn {
  messages: ChatMessage[];
  loading: boolean;
  error: string | null;
  isConnected: boolean;
  sendMessage: (content: string) => Promise<void>;
  leaveRoom: () => Promise<void>;
}

useChatRoomList(options)

interface UseChatRoomListOptions {
  autoLoad?: boolean;
  limit?: number;
  onError?: (error: Error) => void;
}

interface UseChatRoomListReturn {
  rooms: ChatRoom[];
  loading: boolean;
  error: string | null;
  hasMore: boolean;
  createRoom: () => Promise<void>;
  refreshRooms: () => Promise<void>;
  loadMoreRooms: () => Promise<void>;
}

주요 컴포넌트

<ChatBox />

기본 메시지 입력 컴포넌트

interface ChatBoxProps {
  onSubmit?: (message: string) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
}

<ChatRoomComponent />

완전한 채팅방 UI

interface ChatRoomComponentProps {
  room: ChatRoom;
  onBack?: () => void;
  onLeave?: () => void;
}

<ChatRoomList />

채팅방 목록 UI

interface ChatRoomListProps {
  onRoomSelect?: (room: ChatRoom) => void;
  onLogout?: () => void;
}

환경 설정

개발 환경

데모 애플리케이션의 환경 변수 설정:

# apps/chatbox-demo/.env.local
NEXT_PUBLIC_API_BASE_URL=http://localhost:8080

프로덕션 환경

Next.js rewrites를 통해 API 프록시가 자동 설정됩니다:

// next.config.js
async rewrites() {
  return [
    {
      source: '/api/authenticate',
      destination: 'https://api.babitalk.com/authenticate',
    },
    {
      source: '/api/chat_box/:path*',
      destination: 'https://api.babitalk.com/chat_box/:path*',
    },
  ];
}

아키텍처

서비스 팩토리 패턴

// 서비스 초기화
const factory = createServiceFactory({
  apiBaseUrl: '/api',
});

// 개별 서비스 접근
const authService = getAuthService();
const chatRoomService = getChatRoomService();
const userService = getUserService();

AWS Chime SDK 통합

  • MessagingSession: 실시간 WebSocket 연결
  • ChimeMessagingService: 메시지 송수신 및 채널 관리
  • 자동 재연결: 네트워크 불안정 시 자동 복구

배포

SDK 라이브러리 배포

# 빌드 및 패키징
pnpm build:sdk

# npm 배포 (선택사항)
cd packages/chatbox-sdk
npm publish

데모 애플리케이션 배포

# Next.js 빌드
pnpm build

# 정적 파일 생성 (선택사항)
cd apps/chatbox-demo
pnpm export

기여하기

  1. 이 저장소를 포크하세요
  2. 기능 브랜치를 생성하세요 (git checkout -b feature/amazing-feature)
  3. 변경사항을 커밋하세요 (git commit -m 'Add amazing feature')
  4. 브랜치에 푸시하세요 (git push origin feature/amazing-feature)
  5. Pull Request를 생성하세요

커밋 메시지 규칙

feat: 새로운 기능 추가
fix: 버그 수정
docs: 문서 수정
style: 코드 스타일 변경
refactor: 코드 리팩토링
test: 테스트 추가/수정
chore: 빌드/설정 변경

라이선스

이 프로젝트는 MIT 라이선스를 따릅니다. 자세한 내용은 LICENSE 파일을 참조하세요.

기술 스택

Frontend

  • React 18: 최신 React 기능 (Concurrent Features, Suspense)
  • TypeScript: 엄격한 타입 안전성 보장
  • Next.js 14: App Router, Server Components, API Routes
  • Tailwind CSS: 유틸리티 퍼스트 CSS 프레임워크
  • pnpm workspace: 효율적인 모노레포 관리

Backend Integration

  • AWS Chime SDK: 실시간 메시징 및 WebSocket 통신
  • JWT Authentication: 토큰 기반 인증 시스템
  • REST API: RESTful API 통신

Development Tools

  • Rollup: 라이브러리 번들링 및 최적화
  • ESLint + Prettier: 코드 품질 및 포매팅
  • TypeScript Strict Mode: 엄격한 타입 체크
  • Responsive Design: 모바일 퍼스트 반응형 디자인

문제 해결

일반적인 문제

1. 테일윈드 스타일이 적용되지 않는 경우

# 캐시 삭제 후 재시작
rm -rf apps/chatbox-demo/.next
pnpm dev

2. SDK 빌드 오류

# 의존성 재설치
rm -rf node_modules
pnpm install
pnpm build:sdk

3. WebSocket 연결 실패

  • 네트워크 방화벽 설정 확인
  • AWS Chime SDK 자격 증명 확인
  • API 서버 연결 상태 확인

개발자 도구

# 전체 프로젝트 정리
pnpm clean

# 타입 체크
pnpm type-check

# 린팅
pnpm lint

# 테스트 (구현 예정)
pnpm test

📋 버전 호환성

| SDK 버전 | React | Next.js | Node.js | 상태 | | -------- | ----- | ------- | ------- | --------- | | 1.x.x | ≥18.0 | ≥14.0 | ≥18.0 | ✅ 현재 | | 0.x.x | ≥16.8 | ≥13.0 | ≥16.0 | ⚠️ 레거시 |

버전 관리 및 배포

개발자를 위한 버전 관리

간단한 버전업

# 버그 수정 (1.0.0 → 1.0.1)
pnpm patch

# 새 기능 추가 (1.0.0 → 1.1.0)
pnpm minor

# Breaking Changes (1.0.0 → 2.0.0)
pnpm major

빌드 + 배포 자동화

# 가장 간단한 배포 (빌드 + 패치 + 푸시)
pnpm ship

# 세부 제어가 필요한 경우
pnpm release        # 패치 버전 배포
pnpm release:minor  # 마이너 버전 배포
pnpm release:major  # 메이저 버전 배포

일반적인 개발 워크플로우

# 1. 개발 완료
git add .
git commit -m "feat: 새로운 채팅 필터링 기능 추가"

# 2. 기능 추가이므로 minor 버전업
pnpm minor  # package.json 버전 업데이트 + Git 태그 생성

# 3. 원격 저장소에 푸시
git push --follow-tags

# 또는 2-3단계를 한번에
pnpm release:minor

초고속 배포 (권장)

# 개발 완료 후 즉시 배포
pnpm ship

버전 태그 시스템

| 버전 타입 | 명령어 | 사용 시기 | 예시 | | --------- | ------------ | -------------------- | ----------------- | | Patch | pnpm patch | 버그 수정, 보안 패치 | 1.0.01.0.1 | | Minor | pnpm minor | 새 기능, API 추가 | 1.0.11.1.0 | | Major | pnpm major | Breaking Changes | 1.1.02.0.0 |

Git 태그 기반 설치

특정 버전 설치

# 최신 안정 버전
npm install git+https://github.com/babitalk/babitalk_chat_box_frontend.git

# 특정 태그 버전
npm install git+https://github.com/babitalk/babitalk_chat_box_frontend.git#v1.0.0
npm install git+https://github.com/babitalk/babitalk_chat_box_frontend.git#v1.1.0

# pnpm 사용시
pnpm add git+https://github.com/babitalk/babitalk_chat_box_frontend.git#v1.0.0

package.json에서 관리

{
  "dependencies": {
    "@babitalk/chatbox-sdk": "git+https://github.com/babitalk/babitalk_chat_box_frontend.git#v1.0.0"
  }
}

업그레이드 가이드

v1.0.0 → v1.x.x (Minor Updates)

# 안전한 업그레이드 (하위 호환 보장)
npm install git+https://github.com/babitalk/babitalk_chat_box_frontend.git#v1.1.0

# package.json 업데이트 후
npm install

v0.x.x → v1.0.0 (Major Update)

# Breaking Changes 포함 - 코드 수정 필요할 수 있음
npm install git+https://github.com/babitalk/babitalk_chat_box_frontend.git#v1.0.0

최신 버전 확인

# GitHub에서 최신 태그 확인
git ls-remote --tags https://github.com/babitalk/babitalk_chat_box_frontend.git

# 또는 GitHub Releases 페이지에서 확인
# https://github.com/babitalk/babitalk_chat_box_frontend/releases

안전한 업그레이드 전략

단계별 업그레이드

# 1. 현재 버전 백업
git tag backup-before-upgrade

# 2. 테스트 환경에서 먼저 테스트
npm install git+https://github.com/babitalk/babitalk_chat_box_frontend.git#v1.1.0

# 3. 테스트 통과 후 프로덕션 적용
npm run build
npm run test  # 테스트 실행

# 4. 문제 발생시 롤백
npm install git+https://github.com/babitalk/babitalk_chat_box_frontend.git#v1.0.0

버전 히스토리 추적

# 설치된 버전 확인
npm list @babitalk/chatbox-sdk

# Git 태그 히스토리 확인
git tag -l "v*" --sort=-version:refname

# 특정 버전의 변경사항 확인
git show v1.1.0

Migration Guide: 각 버전별 상세 변경사항은 GitHub Releases 참조


Made by Babitalk Team