@daeryun/dr_components 0.6.45 → 0.6.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/dist/components/Daeryuntalk/ChatButton.d.ts +1 -0
  2. package/dist/components/Daeryuntalk/ChatButton.jsx +13 -3
  3. package/dist/components/Daeryuntalk/ChatButton.tsx +17 -3
  4. package/dist/components/Daeryuntalk/ChatConversation.tsx +1 -1
  5. package/dist/components/Daeryuntalk/DaeryuntalkContext.d.ts +9 -0
  6. package/dist/components/Daeryuntalk/DaeryuntalkContext.jsx +127 -3
  7. package/dist/components/Daeryuntalk/DaeryuntalkContext.tsx +130 -3
  8. package/dist/components/Daeryuntalk/DaeryuntalkProvider.d.ts +11 -0
  9. package/dist/components/Daeryuntalk/DaeryuntalkProvider.jsx +59 -0
  10. package/dist/components/Daeryuntalk/DaeryuntalkProvider.tsx +68 -0
  11. package/dist/components/ViewMoreSection/ViewMoreSection.jsx +3 -2
  12. package/dist/components/ViewMoreSection/ViewMoreSection.tsx +3 -2
  13. package/dist/lib/api/daeryuntalk/chatInquiry.d.ts +23 -0
  14. package/dist/lib/api/daeryuntalk/chatInquiry.js +78 -0
  15. package/dist/lib/api/daeryuntalk/chatInquiry.ts +80 -0
  16. package/dist/lib/api/daeryuntalk/index.d.ts +88 -0
  17. package/dist/lib/api/daeryuntalk/index.js +322 -0
  18. package/dist/lib/api/daeryuntalk/index.ts +424 -0
  19. package/dist/lib/api/daeryuntalk/useDaeryuntalkApi.d.ts +23 -0
  20. package/dist/lib/api/daeryuntalk/useDaeryuntalkApi.js +140 -0
  21. package/dist/lib/api/daeryuntalk/useDaeryuntalkApi.ts +187 -0
  22. package/dist/lib/api/index.d.ts +8 -0
  23. package/dist/lib/api/index.js +8 -0
  24. package/dist/lib/api/index.ts +9 -0
  25. package/dist/lib/index.js +1 -0
  26. package/dist/lib/index.ts +1 -0
  27. package/dist/tsconfig.tsbuildinfo +1 -1
  28. package/package.json +1 -1
@@ -0,0 +1,78 @@
1
+ /**
2
+ * 채팅 문의 흐름 처리기
3
+ *
4
+ * 이 모듈은 사용자 상태에 따라 채팅 문의 흐름을 처리
5
+ * - 처음 방문자: 새 문의 생성 후 상세 정보 조회
6
+ * - 재방문자: 기존 문의의 상세 정보 조회
7
+ */
8
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10
+ return new (P || (P = Promise))(function (resolve, reject) {
11
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
12
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
13
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
14
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
15
+ });
16
+ };
17
+ import { createChatInquiry, getChatInquiryDetail, getChatInquiryMain } from './index';
18
+ /**
19
+ * 채팅 문의 흐름 처리
20
+ * 메인 문의 데이터를 기반으로 새 문의를 생성하거나 기존 문의의 상세 정보를 조회
21
+ *
22
+ * @param version API 버전 (기본값: 1.0.0)
23
+ * @returns 채팅 문의 상세 정보
24
+ */
25
+ export function handleChatInquiryFlow(version) {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ console.log('[채팅 문의 흐름] 시작', version ? `버전: ${version}` : '기본 버전 사용');
28
+ try {
29
+ // 1단계: 진행중인 문의가 있는지 확인하기 위해 메인 문의 데이터 조회
30
+ console.log('[채팅 문의 흐름] 1단계: 메인 문의 데이터 조회 시작');
31
+ const mainData = yield getChatInquiryMain(version);
32
+ console.log('[채팅 문의 흐름] 메인 문의 데이터 조회 결과:', mainData);
33
+ // 기존 문의가 있는지 확인
34
+ // todo: trophy198 실제 응답 구조에 따라 이 로직 조정 필요
35
+ const hasOngoingInquiry = mainData && mainData.ongoingInquiry;
36
+ console.log('[채팅 문의 흐름] 진행중인 문의 여부:', hasOngoingInquiry, '문의 번호:', mainData === null || mainData === void 0 ? void 0 : mainData.inquiryNumber);
37
+ if (hasOngoingInquiry && mainData.inquiryNumber) {
38
+ // 진행중인 문의가 있는 재방문자
39
+ console.log('[채팅 문의 흐름] 재방문자 - 기존 문의 상세 조회 시작. 문의 번호:', mainData.inquiryNumber);
40
+ const detailData = yield getChatInquiryDetail(mainData.inquiryNumber, version);
41
+ console.log('[채팅 문의 흐름] 재방문자 - 기존 문의 상세 조회 완료');
42
+ return detailData;
43
+ }
44
+ else {
45
+ // 처음 방문자 또는 진행중인 문의가 없는 경우
46
+ // 2단계: 새 채팅 문의 생성
47
+ console.log('[채팅 문의 흐름] 첫 방문자 - 새 채팅 문의 생성 시작');
48
+ const createResponse = yield createChatInquiry(version);
49
+ console.log('[채팅 문의 흐름] 첫 방문자 - 새 채팅 문의 생성 완료:', createResponse);
50
+ // 3단계: 새로 생성된 문의의 상세 정보 조회
51
+ if (createResponse && createResponse.chat_inquiry_number) {
52
+ console.log('[채팅 문의 흐름] 첫 방문자 - 새 문의 상세 조회 시작. 문의 번호:', createResponse.chat_inquiry_number);
53
+ const detailData = yield getChatInquiryDetail(createResponse.chat_inquiry_number, version);
54
+ console.log('[채팅 문의 흐름] 첫 방문자 - 새 문의 상세 조회 완료');
55
+ return detailData;
56
+ }
57
+ else {
58
+ console.error('[채팅 문의 흐름] 오류: 문의 번호가 없음', createResponse);
59
+ throw new Error('채팅 문의 생성 실패: 문의 번호가 수신되지 않음');
60
+ }
61
+ }
62
+ }
63
+ catch (error) {
64
+ console.error('[채팅 문의 흐름 오류]', error);
65
+ throw error;
66
+ }
67
+ });
68
+ }
69
+ /**
70
+ * 문의 데이터를 기반으로 사용자가 처음 방문자인지 확인
71
+ *
72
+ * @param mainData 메인 문의 데이터
73
+ * @returns 사용자가 처음 방문자인 경우 true
74
+ */
75
+ export function isFirstTimeVisitor(mainData) {
76
+ // todo: trophy198 실제 응답 구조에 따라 이 로직 조정 필요
77
+ return !mainData || !mainData.ongoingInquiry;
78
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * 채팅 문의 흐름 처리기
3
+ *
4
+ * 이 모듈은 사용자 상태에 따라 채팅 문의 흐름을 처리
5
+ * - 처음 방문자: 새 문의 생성 후 상세 정보 조회
6
+ * - 재방문자: 기존 문의의 상세 정보 조회
7
+ */
8
+
9
+ import {
10
+ createChatInquiry,
11
+ getChatInquiryDetail,
12
+ getChatInquiryMain,
13
+ ChatInquiryMainResponse,
14
+ ChatInquiryCreateResponse,
15
+ ChatInquiryDetailResponse
16
+ } from './index';
17
+
18
+ /**
19
+ * 채팅 문의 흐름 처리
20
+ * 메인 문의 데이터를 기반으로 새 문의를 생성하거나 기존 문의의 상세 정보를 조회
21
+ *
22
+ * @param version API 버전 (기본값: 1.0.0)
23
+ * @returns 채팅 문의 상세 정보
24
+ */
25
+ export async function handleChatInquiryFlow(version?: string): Promise<ChatInquiryDetailResponse> {
26
+ console.log('[채팅 문의 흐름] 시작', version ? `버전: ${version}` : '기본 버전 사용');
27
+ try {
28
+ // 1단계: 진행중인 문의가 있는지 확인하기 위해 메인 문의 데이터 조회
29
+ console.log('[채팅 문의 흐름] 1단계: 메인 문의 데이터 조회 시작');
30
+ const mainData = await getChatInquiryMain(version);
31
+ console.log('[채팅 문의 흐름] 메인 문의 데이터 조회 결과:', mainData);
32
+
33
+ // 기존 문의가 있는지 확인
34
+ // todo: trophy198 실제 응답 구조에 따라 이 로직 조정 필요
35
+ const hasOngoingInquiry = mainData && mainData.ongoingInquiry;
36
+ console.log('[채팅 문의 흐름] 진행중인 문의 여부:', hasOngoingInquiry, '문의 번호:', mainData?.inquiryNumber);
37
+
38
+ if (hasOngoingInquiry && mainData.inquiryNumber) {
39
+ // 진행중인 문의가 있는 재방문자
40
+ console.log('[채팅 문의 흐름] 재방문자 - 기존 문의 상세 조회 시작. 문의 번호:', mainData.inquiryNumber);
41
+ const detailData = await getChatInquiryDetail(mainData.inquiryNumber, version);
42
+ console.log('[채팅 문의 흐름] 재방문자 - 기존 문의 상세 조회 완료');
43
+ return detailData;
44
+ } else {
45
+ // 처음 방문자 또는 진행중인 문의가 없는 경우
46
+ // 2단계: 새 채팅 문의 생성
47
+ console.log('[채팅 문의 흐름] 첫 방문자 - 새 채팅 문의 생성 시작');
48
+ const createResponse = await createChatInquiry(version);
49
+ console.log('[채팅 문의 흐름] 첫 방문자 - 새 채팅 문의 생성 완료:', createResponse);
50
+
51
+ // 3단계: 새로 생성된 문의의 상세 정보 조회
52
+ if (createResponse && createResponse.chat_inquiry_number) {
53
+ console.log(
54
+ '[채팅 문의 흐름] 첫 방문자 - 새 문의 상세 조회 시작. 문의 번호:',
55
+ createResponse.chat_inquiry_number
56
+ );
57
+ const detailData = await getChatInquiryDetail(createResponse.chat_inquiry_number, version);
58
+ console.log('[채팅 문의 흐름] 첫 방문자 - 새 문의 상세 조회 완료');
59
+ return detailData;
60
+ } else {
61
+ console.error('[채팅 문의 흐름] 오류: 문의 번호가 없음', createResponse);
62
+ throw new Error('채팅 문의 생성 실패: 문의 번호가 수신되지 않음');
63
+ }
64
+ }
65
+ } catch (error) {
66
+ console.error('[채팅 문의 흐름 오류]', error);
67
+ throw error;
68
+ }
69
+ }
70
+
71
+ /**
72
+ * 문의 데이터를 기반으로 사용자가 처음 방문자인지 확인
73
+ *
74
+ * @param mainData 메인 문의 데이터
75
+ * @returns 사용자가 처음 방문자인 경우 true
76
+ */
77
+ export function isFirstTimeVisitor(mainData: ChatInquiryMainResponse): boolean {
78
+ // todo: trophy198 실제 응답 구조에 따라 이 로직 조정 필요
79
+ return !mainData || !mainData.ongoingInquiry;
80
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Daeryuntalk API 클라이언트 모듈 2025-04-23
3
+ *
4
+ * 이 모듈은 Daeryuntalk 채팅 API와 상호작용하기 위한 함수를 제공
5
+ * 1. 고객 인증
6
+ * 2. 웹소켓 연결 초기화
7
+ * 3. 웹소켓 연결
8
+ * 4. 채팅 문의 관리
9
+ */
10
+ export interface WebSocketInitResponse {
11
+ data: {
12
+ cnnc_url: string;
13
+ cnnc_token: string;
14
+ };
15
+ }
16
+ export interface ChatInquiryMainResponse {
17
+ ongoingInquiry?: boolean;
18
+ inquiryNumber?: string;
19
+ }
20
+ export interface ChatInquiryCreateResponse {
21
+ chat_inquiry_number?: string;
22
+ }
23
+ export interface ChatInquiryDetailData {
24
+ inquiry_number?: string;
25
+ status?: string;
26
+ created_at?: string;
27
+ updated_at?: string;
28
+ }
29
+ export interface ChatInquiryDetailResponse {
30
+ data?: ChatInquiryDetailData;
31
+ success?: boolean;
32
+ error_code?: string;
33
+ error_message?: string;
34
+ }
35
+ /**
36
+ * 사용자 인증
37
+ * @param version API 버전 (기본값: 1.0.0)
38
+ * @returns 인증 응답
39
+ */
40
+ export declare function authenticateUser(version?: string): Promise<any>;
41
+ /**
42
+ * 웹소켓 연결 초기화
43
+ * @param version API 버전 (기본값: 1.0.0)
44
+ * @returns 연결 URL과 토큰이 포함된 웹소켓 초기화 데이터
45
+ */
46
+ export declare function initializeWebSocket(version?: string): Promise<WebSocketInitResponse>;
47
+ /**
48
+ * 웹소켓 연결
49
+ * @param wsUrl 웹소켓 URL
50
+ * @param token 연결 토큰
51
+ * @param onMessage 메시지 핸들러
52
+ * @param onOpen 연결 열림 핸들러
53
+ * @param onClose 연결 닫힘 핸들러
54
+ * @param onError 오류 핸들러
55
+ * @returns 웹소켓 인스턴스
56
+ */
57
+ export declare function connectWebSocket(wsUrl: string, token: string, onMessage?: (event: MessageEvent) => void, onOpen?: (event: Event) => void, onClose?: (event: CloseEvent) => void, onError?: (event: Event) => void): WebSocket;
58
+ /**
59
+ * 채팅 문의 메인 조회
60
+ * @param version API 버전 (기본값: 1.0.0)
61
+ * @returns 채팅 문의 메인 데이터
62
+ */
63
+ export declare function getChatInquiryMain(version?: string): Promise<ChatInquiryMainResponse>;
64
+ /**
65
+ * 새 채팅 문의 생성 (처음 방문자용)
66
+ * @param version API 버전 (기본값: 1.0.0)
67
+ * @returns 문의 번호가 포함된 생성된 채팅 문의 데이터
68
+ */
69
+ export declare function createChatInquiry(version?: string): Promise<ChatInquiryCreateResponse>;
70
+ /**
71
+ * 채팅 문의 상세 조회
72
+ * @param inquiryNumber 채팅 문의 번호
73
+ * @param version API 버전 (기본값: 1.0.0)
74
+ * @returns 채팅 문의 상세 정보
75
+ */
76
+ export declare function getChatInquiryDetail(inquiryNumber: string, version?: string): Promise<ChatInquiryDetailResponse>;
77
+ /**
78
+ * Daeryuntalk 초기화 완료 흐름
79
+ * 이 함수는 인증부터 웹소켓 연결까지 완전한 흐름을 처리
80
+ * @param onWebSocketConnected 웹소켓 연결 시 콜백
81
+ * @param onWebSocketMessage 메시지 핸들러
82
+ * @param version API 버전 (기본값: 1.0.0)
83
+ * @returns 웹소켓 인스턴스 및 문의 데이터
84
+ */
85
+ export declare function initializeDaeryuntalk(onWebSocketConnected?: (socket: WebSocket) => void, onWebSocketMessage?: (event: MessageEvent) => void, version?: string): Promise<{
86
+ socket: WebSocket;
87
+ inquiryData?: any;
88
+ }>;
@@ -0,0 +1,322 @@
1
+ /**
2
+ * Daeryuntalk API 클라이언트 모듈 2025-04-23
3
+ *
4
+ * 이 모듈은 Daeryuntalk 채팅 API와 상호작용하기 위한 함수를 제공
5
+ * 1. 고객 인증
6
+ * 2. 웹소켓 연결 초기화
7
+ * 3. 웹소켓 연결
8
+ * 4. 채팅 문의 관리
9
+ */
10
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
11
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
12
+ return new (P || (P = Promise))(function (resolve, reject) {
13
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
14
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
15
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
16
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
17
+ });
18
+ };
19
+ // API 기본 URL
20
+ const API_BASE_URL = 'https://chat-client-api.lawmance.com';
21
+ // API 기본 버전
22
+ const DEFAULT_API_VERSION = '1.0.0';
23
+ // API 엔드포인트
24
+ const ENDPOINTS = {
25
+ AUTHENTICATE: '/chatctm/ctf/crtfica',
26
+ WEBSOCKET_INIT: '/chatctm/cmp/ws-init',
27
+ CHAT_INQUIRY_MAIN: '/chatctm/hom/chatinquirymainsearch',
28
+ CHAT_INQUIRY_CREATE: '/chatctm/hom/chatinquirycreate',
29
+ CHAT_INQUIRY_DETAIL: '/chatctm/hom/chatinquirydetailsearch'
30
+ };
31
+ /**
32
+ * 쿠키 지원이 포함된 기본 fetch 함수
33
+ */
34
+ function fetchWithCookies(url_1) {
35
+ return __awaiter(this, arguments, void 0, function* (url, options = {}, version = DEFAULT_API_VERSION // 버전 매개변수 추가
36
+ ) {
37
+ const headers = new Headers(options.headers || {});
38
+ // Content-Type 헤더가 없으면 추가
39
+ if (!headers.has('Content-Type')) {
40
+ headers.set('Content-Type', 'application/json');
41
+ }
42
+ // 버전 헤더 추가
43
+ headers.set('v', version);
44
+ const defaultOptions = {
45
+ credentials: 'include', // 요청에 쿠키 포함
46
+ headers
47
+ };
48
+ const mergedOptions = Object.assign(Object.assign(Object.assign({}, defaultOptions), options), { headers });
49
+ console.log(`[API 요청] ${options.method || 'GET'} ${url}`, {
50
+ 옵션: mergedOptions,
51
+ 본문: mergedOptions.body,
52
+ 버전: version
53
+ });
54
+ try {
55
+ const response = yield fetch(url, mergedOptions);
56
+ console.log(`[API 응답] ${options.method || 'GET'} ${url}`, {
57
+ 상태: response.status,
58
+ 상태텍스트: response.statusText,
59
+ 헤더: Object.fromEntries([...response.headers.entries()])
60
+ });
61
+ if (!response.ok) {
62
+ // 400 에러 상세 정보 추출 시도
63
+ try {
64
+ const errorData = yield response.json();
65
+ console.error(`[API 오류] ${response.status} ${response.statusText}`, errorData);
66
+ throw new Error(`API 오류: ${response.status} - ${response.statusText} - ${JSON.stringify(errorData)}`);
67
+ }
68
+ catch (parseError) {
69
+ console.error(`[API 오류] ${response.status} ${response.statusText} - 응답 파싱 실패`, parseError);
70
+ throw new Error(`API 오류: ${response.status} - ${response.statusText}`);
71
+ }
72
+ }
73
+ // 응답 본문이 비어 있는지 확인
74
+ const contentLength = response.headers.get('content-length');
75
+ const isEmpty = contentLength === '0';
76
+ let data;
77
+ if (isEmpty) {
78
+ console.log(`[API 응답 데이터] ${options.method || 'GET'} ${url} - 빈 응답 본문 (헤더 기반 확인)`);
79
+ // 빈 응답이면 빈 객체 반환
80
+ data = {};
81
+ }
82
+ else {
83
+ try {
84
+ // 응답 텍스트를 먼저 확인하여 비어있는지 검사
85
+ const clonedResponse = response.clone();
86
+ const responseText = yield clonedResponse.text();
87
+ if (!responseText || responseText.trim() === '') {
88
+ console.log(`[API 응답 데이터] ${options.method || 'GET'} ${url} - 빈 응답 본문 (내용 기반 확인)`);
89
+ data = {};
90
+ }
91
+ else {
92
+ // 유효한 JSON인 경우만 파싱
93
+ data = JSON.parse(responseText);
94
+ console.log(`[API 응답 데이터] ${options.method || 'GET'} ${url}`, data);
95
+ }
96
+ }
97
+ catch (error) {
98
+ console.error(`[API 응답 JSON 파싱 오류] ${options.method || 'GET'} ${url}`, error);
99
+ // JSON 파싱 오류가 발생해도 요청은 성공했으므로 빈 객체 반환
100
+ data = {};
101
+ }
102
+ }
103
+ return data;
104
+ }
105
+ catch (error) {
106
+ console.error(`[API 호출 실패] ${options.method || 'GET'} ${url}`, error);
107
+ throw error;
108
+ }
109
+ });
110
+ }
111
+ /**
112
+ * 사용자 인증
113
+ * @param version API 버전 (기본값: 1.0.0)
114
+ * @returns 인증 응답
115
+ */
116
+ export function authenticateUser(version) {
117
+ return __awaiter(this, void 0, void 0, function* () {
118
+ console.log('[인증 시작] 사용자 인증 요청', version ? `버전: ${version}` : `기본 버전: ${DEFAULT_API_VERSION}`);
119
+ try {
120
+ // 인증 API 호출
121
+ const response = yield fetchWithCookies(`${API_BASE_URL}${ENDPOINTS.AUTHENTICATE}`, { method: 'GET' }, version);
122
+ // 빈 응답인 경우에도 성공으로 처리
123
+ if (Object.keys(response).length === 0) {
124
+ console.log('[인증 성공] 사용자 인증 완료 - 빈 응답 (쿠키만 설정됨)');
125
+ return { success: true, status: 'authenticated' };
126
+ }
127
+ console.log('[인증 성공] 사용자 인증 완료', response);
128
+ return response;
129
+ }
130
+ catch (error) {
131
+ console.error('[인증 실패] 사용자 인증 오류:', error);
132
+ throw error;
133
+ }
134
+ });
135
+ }
136
+ /**
137
+ * 웹소켓 연결 초기화
138
+ * @param version API 버전 (기본값: 1.0.0)
139
+ * @returns 연결 URL과 토큰이 포함된 웹소켓 초기화 데이터
140
+ */
141
+ export function initializeWebSocket(version) {
142
+ return __awaiter(this, void 0, void 0, function* () {
143
+ console.log('[웹소켓 초기화 시작] 웹소켓 연결 초기화 요청', version ? `버전: ${version}` : `기본 버전: ${DEFAULT_API_VERSION}`);
144
+ try {
145
+ const response = yield fetchWithCookies(`${API_BASE_URL}${ENDPOINTS.WEBSOCKET_INIT}`, { method: 'POST' }, version);
146
+ console.log('[웹소켓 초기화 성공] 웹소켓 연결 URL 및 토큰 수신', response);
147
+ return response;
148
+ }
149
+ catch (error) {
150
+ console.error('[웹소켓 초기화 실패] 웹소켓 연결 초기화 오류:', error);
151
+ throw error;
152
+ }
153
+ });
154
+ }
155
+ /**
156
+ * 웹소켓 연결
157
+ * @param wsUrl 웹소켓 URL
158
+ * @param token 연결 토큰
159
+ * @param onMessage 메시지 핸들러
160
+ * @param onOpen 연결 열림 핸들러
161
+ * @param onClose 연결 닫힘 핸들러
162
+ * @param onError 오류 핸들러
163
+ * @returns 웹소켓 인스턴스
164
+ */
165
+ export function connectWebSocket(wsUrl, token, onMessage, onOpen, onClose, onError) {
166
+ // URL에 토큰을 파라미터로 추가
167
+ const connectionUrl = `${wsUrl}?token=${token}`;
168
+ console.log('[웹소켓 연결 시작] 연결 URL:', connectionUrl);
169
+ try {
170
+ const socket = new WebSocket(connectionUrl);
171
+ socket.onopen = event => {
172
+ console.log('[웹소켓 연결 성공] 웹소켓 연결됨');
173
+ if (onOpen)
174
+ onOpen(event);
175
+ };
176
+ if (onMessage) {
177
+ socket.onmessage = event => {
178
+ console.log('[웹소켓 메시지 수신]', event.data);
179
+ onMessage(event);
180
+ };
181
+ }
182
+ if (onClose) {
183
+ socket.onclose = event => {
184
+ console.log('[웹소켓 연결 종료] 코드:', event.code, '사유:', event.reason);
185
+ onClose(event);
186
+ };
187
+ }
188
+ if (onError) {
189
+ socket.onerror = event => {
190
+ console.error('[웹소켓 오류]', event);
191
+ onError(event);
192
+ };
193
+ }
194
+ return socket;
195
+ }
196
+ catch (error) {
197
+ console.error('[웹소켓 연결 실패]', error);
198
+ throw error;
199
+ }
200
+ }
201
+ /**
202
+ * 채팅 문의 메인 조회
203
+ * @param version API 버전 (기본값: 1.0.0)
204
+ * @returns 채팅 문의 메인 데이터
205
+ */
206
+ export function getChatInquiryMain(version) {
207
+ return __awaiter(this, void 0, void 0, function* () {
208
+ const body = {
209
+ d: {
210
+ channel_number: 'CH123456789012345678' // 명시된 고정값
211
+ }
212
+ };
213
+ console.log('[채팅 문의 메인 조회 시작] 채널 번호:', body.d.channel_number, version ? `버전: ${version}` : `기본 버전: ${DEFAULT_API_VERSION}`);
214
+ try {
215
+ const response = yield fetchWithCookies(`${API_BASE_URL}${ENDPOINTS.CHAT_INQUIRY_MAIN}`, {
216
+ method: 'POST',
217
+ body: JSON.stringify(body)
218
+ }, version);
219
+ console.log('[채팅 문의 메인 조회 성공]', response);
220
+ return response;
221
+ }
222
+ catch (error) {
223
+ console.error('[채팅 문의 메인 조회 실패]', error);
224
+ throw error;
225
+ }
226
+ });
227
+ }
228
+ /**
229
+ * 새 채팅 문의 생성 (처음 방문자용)
230
+ * @param version API 버전 (기본값: 1.0.0)
231
+ * @returns 문의 번호가 포함된 생성된 채팅 문의 데이터
232
+ */
233
+ export function createChatInquiry(version) {
234
+ return __awaiter(this, void 0, void 0, function* () {
235
+ console.log('[새 채팅 문의 생성 시작]', version ? `버전: ${version}` : `기본 버전: ${DEFAULT_API_VERSION}`);
236
+ try {
237
+ const response = yield fetchWithCookies(`${API_BASE_URL}${ENDPOINTS.CHAT_INQUIRY_CREATE}`, { method: 'POST' }, version);
238
+ console.log('[새 채팅 문의 생성 성공] 문의 번호:', response.chat_inquiry_number);
239
+ return response;
240
+ }
241
+ catch (error) {
242
+ console.error('[새 채팅 문의 생성 실패]', error);
243
+ throw error;
244
+ }
245
+ });
246
+ }
247
+ /**
248
+ * 채팅 문의 상세 조회
249
+ * @param inquiryNumber 채팅 문의 번호
250
+ * @param version API 버전 (기본값: 1.0.0)
251
+ * @returns 채팅 문의 상세 정보
252
+ */
253
+ export function getChatInquiryDetail(inquiryNumber, version) {
254
+ return __awaiter(this, void 0, void 0, function* () {
255
+ const body = {
256
+ d: {
257
+ inquiry_number: inquiryNumber
258
+ }
259
+ };
260
+ console.log('[채팅 문의 상세 조회 시작] 문의 번호:', inquiryNumber, version ? `버전: ${version}` : `기본 버전: ${DEFAULT_API_VERSION}`);
261
+ try {
262
+ const response = yield fetchWithCookies(`${API_BASE_URL}${ENDPOINTS.CHAT_INQUIRY_DETAIL}`, {
263
+ method: 'POST',
264
+ body: JSON.stringify(body)
265
+ }, version);
266
+ console.log('[채팅 문의 상세 조회 성공]', response);
267
+ return response;
268
+ }
269
+ catch (error) {
270
+ console.error('[채팅 문의 상세 조회 실패]', error);
271
+ throw error;
272
+ }
273
+ });
274
+ }
275
+ /**
276
+ * Daeryuntalk 초기화 완료 흐름
277
+ * 이 함수는 인증부터 웹소켓 연결까지 완전한 흐름을 처리
278
+ * @param onWebSocketConnected 웹소켓 연결 시 콜백
279
+ * @param onWebSocketMessage 메시지 핸들러
280
+ * @param version API 버전 (기본값: 1.0.0)
281
+ * @returns 웹소켓 인스턴스 및 문의 데이터
282
+ */
283
+ export function initializeDaeryuntalk(onWebSocketConnected, onWebSocketMessage, version) {
284
+ return __awaiter(this, void 0, void 0, function* () {
285
+ console.log('[Daeryuntalk 초기화 시작] 전체 흐름 실행', version ? `버전: ${version}` : `기본 버전: ${DEFAULT_API_VERSION}`);
286
+ try {
287
+ // 1단계: 사용자 인증
288
+ console.log('[Daeryuntalk 초기화] 1단계: 사용자 인증 시작');
289
+ yield authenticateUser(version);
290
+ console.log('[Daeryuntalk 초기화] 1단계: 사용자 인증 완료');
291
+ // 2단계: 웹소켓 초기화
292
+ console.log('[Daeryuntalk 초기화] 2단계: 웹소켓 초기화 시작');
293
+ const wsInitData = yield initializeWebSocket(version);
294
+ console.log('[Daeryuntalk 초기화] 2단계: 웹소켓 초기화 완료', {
295
+ cnnc_url: wsInitData.data.cnnc_url,
296
+ token_일부: wsInitData.data.cnnc_token ? `${wsInitData.data.cnnc_token.substring(0, 10)}...` : '없음'
297
+ });
298
+ // 3단계: 웹소켓 연결
299
+ console.log('[Daeryuntalk 초기화] 3단계: 웹소켓 연결 시작');
300
+ const socket = connectWebSocket(wsInitData.data.cnnc_url, wsInitData.data.cnnc_token, onWebSocketMessage, onWebSocketConnected
301
+ ? () => {
302
+ console.log('[Daeryuntalk 초기화] 3단계: 웹소켓 연결 콜백 실행');
303
+ onWebSocketConnected(socket);
304
+ }
305
+ : undefined);
306
+ console.log('[Daeryuntalk 초기화] 3단계: 웹소켓 연결 객체 생성됨');
307
+ // 4단계: 채팅 문의 메인 조회
308
+ console.log('[Daeryuntalk 초기화] 4단계: 채팅 문의 메인 조회 시작');
309
+ const chatInquiryData = yield getChatInquiryMain(version);
310
+ console.log('[Daeryuntalk 초기화] 4단계: 채팅 문의 메인 조회 완료', chatInquiryData);
311
+ console.log('[Daeryuntalk 초기화 완료] 모든 단계 성공');
312
+ return {
313
+ socket,
314
+ inquiryData: chatInquiryData
315
+ };
316
+ }
317
+ catch (error) {
318
+ console.error('[Daeryuntalk 초기화 실패] 오류 발생:', error);
319
+ throw error;
320
+ }
321
+ });
322
+ }