connectbase-client 1.10.0 → 2.0.0

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.
package/dist/index.d.mts CHANGED
@@ -241,7 +241,66 @@ interface AnalyticsRangeOptions {
241
241
  interface VisitorListOptions {
242
242
  limit?: number;
243
243
  offset?: number;
244
- sort_by?: 'last_visit' | 'total_visits' | 'total_page_views';
244
+ /**
245
+ * 백엔드가 인식하는 정렬 키 — 외 값은 silent 로 default(`last_visit`) 처리됩니다.
246
+ *
247
+ * 1.12.0 에서 백엔드 실제 동작에 맞춰 enum 정정 (1.10/1.11 의 `total_visits`/
248
+ * `total_page_views` 는 백엔드에서 인식되지 않아 항상 default 분기였음).
249
+ */
250
+ sort_by?: 'last_visit' | 'visits' | 'page_views' | 'first_visit';
251
+ }
252
+ /**
253
+ * 멤버별 합산 방문자 그룹 항목.
254
+ *
255
+ * 한 명의 회원이 여러 디바이스/브라우저로 접속했을 때 visitor row 들을 합쳐 단일 row.
256
+ * 익명 visitor 는 `app_member_id == undefined` 로 단일 row 그대로 노출되며 `visitor_count == 1`.
257
+ *
258
+ * `visitor_count` 는 "디바이스 수" 가 아닌 **"추적 브라우저 인스턴스 수"** 를 의미합니다.
259
+ * 같은 디바이스에서 시크릿모드 + 일반모드는 visitor 2 = visitor_count 2 로 카운트됩니다.
260
+ */
261
+ interface VisitorGroupItem {
262
+ app_member_id?: string;
263
+ /** 익명 visitor row 의 경우 단일 visitor_uid. 회원 그룹은 visitor_uids 참조. */
264
+ visitor_uid?: string;
265
+ /** 회원 그룹에 속한 visitor_uid 목록. 익명 row 는 undefined. */
266
+ visitor_uids?: string[];
267
+ visitor_count: number;
268
+ total_visits: number;
269
+ total_page_views: number;
270
+ first_visit_at: string;
271
+ last_visit_at: string;
272
+ country?: string;
273
+ is_bot: boolean;
274
+ }
275
+ interface VisitorGroupListResponse {
276
+ groups: VisitorGroupItem[];
277
+ total: number;
278
+ limit: number;
279
+ offset: number;
280
+ has_more: boolean;
281
+ }
282
+ interface VisitorByMemberResponse {
283
+ app_member_id: string;
284
+ visitor_uids: string[];
285
+ visitor_count: number;
286
+ total_visits: number;
287
+ total_page_views: number;
288
+ first_visit_at: string;
289
+ last_visit_at: string;
290
+ country?: string;
291
+ is_bot: boolean;
292
+ }
293
+ interface MergeVisitorsRequest {
294
+ source_visitor_uid: string;
295
+ /** target_visitor_uid 또는 target_member_id 중 하나는 필수. */
296
+ target_visitor_uid?: string;
297
+ target_member_id?: string;
298
+ }
299
+ interface MergeVisitorsResponse {
300
+ success: boolean;
301
+ target_visitor_id: string;
302
+ moved_records: number;
303
+ message?: string;
245
304
  }
246
305
  declare class SessionManager {
247
306
  private _sessionId;
@@ -302,15 +361,38 @@ declare class AnalyticsAPI {
302
361
  */
303
362
  trackEvent(name: string, properties?: Record<string, unknown>): void;
304
363
  /**
305
- * 사용자 식별 (로그인 )
306
- * 이후 모든 방문 배치에 `app_member_id`가 첨부되어 게스트 방문자가 회원으로 연결됩니다.
364
+ * 사용자 식별 (로그인 직후 호출).
365
+ *
366
+ * 이후 모든 방문 배치에 `app_member_id` 가 첨부되어 새 활동은 회원으로 기록됩니다.
367
+ * 추가로 **현재 visitor_uid 의 기존 익명 활동을 즉시 회원에게 backfill** 하기 위해
368
+ * 백엔드 `link-member` 엔드포인트를 한 번 호출합니다 (1.11.0+). 호출 실패는
369
+ * silent — 다음 batch 가 닿을 때 백엔드 자동 매핑이 동일하게 처리하므로 자가 복구.
370
+ *
371
+ * 산업 표준(GA4 User-ID, Mixpanel/PostHog `identify`) 과 동작 정합.
372
+ *
373
+ * @example
374
+ * ```ts
375
+ * // 로그인 성공 직후
376
+ * await cb.auth.signIn({ email, password })
377
+ * cb.analytics.identify(member.id)
378
+ * ```
307
379
  */
308
380
  identify(memberId: string): void;
309
381
  /**
310
- * 방문자 트래커에 현재 회원 ID 설정 (로그인/게스트 가입 시 호출)
311
- * null 을 넘기면 익명 상태로 복귀 (로그아웃).
382
+ * 방문자 트래커에 현재 회원 ID 설정 (로그인/게스트 가입 시 호출).
383
+ *
384
+ * `identify()` 와 달리 즉시 backfill 호출은 하지 않습니다 — 단순히 이후 batch 의
385
+ * `app_member_id` 값만 갱신. null 을 넘기면 익명 상태로 복귀 (로그아웃).
312
386
  */
313
387
  setMemberId(memberId: string | null): void;
388
+ /**
389
+ * 백엔드 link-member 엔드포인트 한 번 호출 — 즉시 backfill 트리거.
390
+ *
391
+ * - 첫 페이지뷰가 아직 백엔드에 닿기 전이면 visitor 가 없어 404. 무시 — 다음 batch 가
392
+ * 가면 백엔드 BatchRecordVisit 가 자동 LinkMember 를 호출.
393
+ * - storage_web_id 가 init 안 됐거나 모든 종류의 네트워크 오류 — silent fail.
394
+ */
395
+ private linkMemberSilent;
314
396
  /** 현재 설정된 회원 ID 조회 (미설정 시 null) */
315
397
  getMemberId(): string | null;
316
398
  /**
@@ -363,6 +445,52 @@ declare class AnalyticsAPI {
363
445
  * 방문자 목록 조회 — JWT/cb_sk_ 인증 필요.
364
446
  */
365
447
  getVisitors(storageWebId?: string, options?: VisitorListOptions): Promise<VisitorListResponse>;
448
+ /**
449
+ * 멤버별 합산 방문자 그룹 조회 — JWT/cb_sk_ 인증 필요. (1.11+)
450
+ *
451
+ * `getVisitors` 와 달리 visitor row 들을 `app_member_id` 로 합쳐 단일 row 로 반환.
452
+ * 같은 사람이 PC + 모바일 + 태블릿으로 접속한 경우 visitor 3개 → 그룹 1개.
453
+ * 익명 visitor 는 단일 row 로 그대로 포함되어 페이지네이션이 일관됨.
454
+ *
455
+ * @example
456
+ * ```ts
457
+ * const { groups } = await cb.analytics.getVisitorGroups('019d8...', { limit: 50 })
458
+ * for (const g of groups) {
459
+ * if (g.app_member_id) console.log(`${g.app_member_id}: ${g.visitor_count} 디바이스`)
460
+ * }
461
+ * ```
462
+ */
463
+ getVisitorGroups(storageWebId?: string, options?: VisitorListOptions): Promise<VisitorGroupListResponse>;
464
+ /**
465
+ * 단건 멤버 합산 방문자 조회 — JWT/cb_sk_ 인증 필요. (1.11+)
466
+ *
467
+ * 어드민 회원 상세 페이지처럼 **한 명만 필요**할 때. 페이지네이션 풀 다운 없이
468
+ * 한 번의 호출로 합산 결과 반환.
469
+ *
470
+ * @example
471
+ * ```ts
472
+ * const v = await cb.analytics.getVisitorByMember('019d8...', memberId)
473
+ * console.log(`${v.visitor_count} 디바이스, 총 ${v.total_page_views} pv`)
474
+ * ```
475
+ */
476
+ getVisitorByMember(storageWebId: string | undefined, memberId: string): Promise<VisitorByMemberResponse>;
477
+ /**
478
+ * 두 visitor 를 한 사람으로 통합하는 admin 작업 — JWT/cb_sk_ 인증 필요. (1.11+)
479
+ *
480
+ * 외부 인증 시스템에서 두 visitor 가 동일인임을 알았을 때 사용. source 의 자식 레코드
481
+ * (page_views, daily, custom_events, experiment_assignments, heatmap_events,
482
+ * session_recordings) 를 target 으로 옮기고 source visitor 는 삭제됨.
483
+ *
484
+ * @param request 둘 중 하나 필수: `target_visitor_uid` 또는 `target_member_id`.
485
+ * @example
486
+ * ```ts
487
+ * await cb.analytics.mergeVisitors('019d8...', {
488
+ * source_visitor_uid: 'old-uid',
489
+ * target_member_id: '01a...',
490
+ * })
491
+ * ```
492
+ */
493
+ mergeVisitors(storageWebId: string | undefined, request: MergeVisitorsRequest): Promise<MergeVisitorsResponse>;
366
494
  /**
367
495
  * 조회 메서드 공통 가드 — Public Key 인증 SDK 인스턴스에서는 명확한 에러를 던진다.
368
496
  * 백엔드 라우트는 cb_pk_ 를 거부하므로 호출 자체를 막는 것이 디버깅에 유리.
@@ -1232,14 +1360,6 @@ interface DatabaseRealtimeConnectOptions {
1232
1360
  /** 디버그 로깅 (기본: false) */
1233
1361
  debug?: boolean;
1234
1362
  }
1235
- /** 데이터베이스 실시간 프레즌스 상태 */
1236
- interface DatabasePresenceState {
1237
- user_id: string;
1238
- status: 'online' | 'away' | 'offline';
1239
- last_seen: string;
1240
- device?: string;
1241
- metadata?: Record<string, unknown>;
1242
- }
1243
1363
  interface CreateBackupRequest {
1244
1364
  /** 백업 이름 */
1245
1365
  name: string;
@@ -1770,14 +1890,6 @@ declare class DatabaseAPI {
1770
1890
  * @returns 구독 해제 가능한 객체
1771
1891
  */
1772
1892
  subscribe(tableId: string, handlers: DatabaseRealtimeHandlers, options?: DatabaseSubscribeOptions): DatabaseRealtimeSubscription;
1773
- /**
1774
- * 프레즌스 상태 설정
1775
- */
1776
- setPresence(status: string, device?: string, metadata?: Record<string, unknown>): void;
1777
- /**
1778
- * 프레즌스 구독 (다른 사용자의 온라인 상태 감시)
1779
- */
1780
- subscribePresence(userIds: string[], onPresence: (states: Record<string, DatabasePresenceState>) => void): void;
1781
1893
  /**
1782
1894
  * 실시간 연결 상태 확인
1783
1895
  */
@@ -7037,4 +7149,4 @@ declare class ConnectBase {
7037
7149
  updateConfig(config: Partial<ConnectBaseConfig>): void;
7038
7150
  }
7039
7151
 
7040
- export { AIAPI, type AIChatRequest, type AIChatResponse, type AIMessage, type AISource, type AIStreamChunk, type AITool, type AIToolCall, type AIToolEvent, type AckMessagesRequest, type AdMobDailyReport, type AdMobReportResponse, type AdMobReportSummary, type AdReportResponse, type AdReportSummary, type AdmobConnectionInfo, AdsAPI, type AdsenseConnectionInfo, type AggregateResult, type AggregateStage, type AnalyticsConfig, type AnalyticsEvent, ApiError, type ApiErrorDetail, type AppStatsResponse, type ArchivePolicy, type AtomicOperator, type AtomicOperatorType, AuthError, type AuthSettingsResponse, type BackupInfo, type BatchOperation, type BatchSetPageMetaRequest, type BillingCycle, type BillingKeyResponse, type BiometricInfo, type BiometricResult, type BulkCreateResponse, type BulkError, type CPUInfo, type CancelPaymentRequest, type CancelPaymentResponse, type CancelSubscriptionRequest, type CategoryInfo, type Channel, type ChannelMembership, type ChargeWithBillingKeyRequest, type ChargeWithBillingKeyResponse, type ChatMessage, type ClientMessage, type ColumnSchema, type CommentListResponse, type CompleteUploadRequest, type CompleteUploadResponse, type ConfirmBillingKeyRequest, type ConfirmPaymentRequest, type ConfirmPaymentResponse, ConnectBase, type ConnectBaseConfig, type ConnectedData, type ConnectionState, type ConsentOptions, type ConsumeMessagesResponse, type ConsumeOptions, type CopyTableRequest, type CopyTableResponse, type CreateBackupRequest, type CreateChannelRequest, type CreateCheckoutSessionRequest, type CreateCheckoutSessionResponse, type CreateColumnRequest, type CreateDataRequest, type CreateDocumentRequest, type CreateFolderRequest, type CreateFolderResponse, type CreateGeoIndexRequest, type CreateIndexRequest, type CreateLobbyRequest, type CreatePlaylistRequest, type CreatePublicKeyRequest, type CreatePublicKeyResponse, type CreateRelationRequest, type CreateSearchIndexRequest, type CreateSecurityRuleRequest, type CreateSubscriptionRequest, type CreateTableRequest, type CreateTriggerRequest, type CreateVideoStorageRequest, type DailyReport, type DataItem, type DataType, type DatabaseChange, type DatabaseChangeMessage, type DatabaseChangeType, type DatabasePresenceState, type DatabaseRealtimeConnectOptions, type DatabaseRealtimeFilter, type DatabaseRealtimeHandlers, type DatabaseRealtimeSubscription, type DatabaseSnapshot, type DatabaseSnapshotMessage, type DatabaseSubscribeOptions, type DeleteWhereResponse, type DeviceInfo, type DocumentResponse, type EnabledProviderInfo, type EnabledProvidersResponse, type ErrorHandler, type ErrorMessage, type ErrorReport, type ErrorTrackerConfig, type ErrorType, type ExportDataRequest, type ExportDataResponse, type FetchDataResponse, type FetchFilesResponse, type FetchPublicKeysResponse, type FileItem, type FileStats, GameAPI, type GameAction, type GameClientConfig, type GameConnectionState, type GameConnectionStatus, type GameDelta, type GameEventHandlers, type GamePlayer, GameRoom, type GameRoomConfig, type GameRoomInfo, GameRoomTransport, type GameServerMessage, type GameServerMessageType, type GameState, type GameTransportConfig, type GenerateUploadURLByPathRequest, type GenerateUploadURLRequest, type GenerateUploadURLResponse, type GeoIndex, type GeoNear, type GeoPoint, type GeoPolygon, type GeoQuery, type GeoResponse, type GeoResult, type GeoWithin, type GetAuthorizationURLResponse, type GetFileByPathResponse, type GoogleConnectionStatus, type GuestMemberSignInResponse, type HistoryResponse, type ICEServer, type ICEServersResponse, type ImageResult, type ImportDataRequest, type ImportDataResponse, type IndexAnalysis, type IndexRecommendation, type InitUploadResponse, type InvokeFunctionRequest, type InvokeFunctionResponse, type IssueBillingKeyRequest, type IssueBillingKeyResponse, type JoinQueueRequest, type JoinRoomRequest, type JoinRoomResponse, type KnowledgeSearchRequest, type KnowledgeSearchResponse, type KnowledgeSearchResult, type LeaderboardEntry, type LifecyclePolicy, type ListBillingKeysResponse, type ListDocumentsResponse, type ListPageMetasOptions, type ListPageMetasResponse, type ListSubscriptionPaymentsRequest, type ListSubscriptionPaymentsResponse, type ListSubscriptionsRequest, type ListSubscriptionsResponse, type LobbyInfo, type LobbyInvite, type LobbyMember, type LobbyVisibility, type MatchResult, type MatchmakingTicket, type MemberInfoResponse, type MemberSignInRequest, type MemberSignInResponse, type MemberSignUpRequest, type MemberSignUpResponse, type MembershipTier, type MemoryInfo, type MessageHandler, type MigrateDataRequest, type MigrateDataResponse, type MoveFileRequest, type NackMessageRequest, NativeAPI, type OAuthCallbackResponse, type OAuthProvider, type OpenDialogOptions, type OpenDialogResult, type PageMetaResponse, type PartyInfo, type PartyInvite, type PartyMember, type PauseSubscriptionRequest, type PaymentDetail, type PaymentProvider, type PaymentStatus, type PeerInfo, type Platform, type PlayerEvent, type PlayerStats, type Playlist, type PlaylistItem, type PongMessage, type PopulateOption, type Position, type PreparePaymentRequest, type PreparePaymentResponse, type PresenceChangeHandler, type PresenceInfo, type PresenceSetOptions, type PresenceStatus, type PresenceStatusResult, type PublicKeyItem, type PublishBatchRequest, type PublishBatchResponse, type PublishMessageRequest, type PublishMessageResponse, type PushPlatform, type QualityProgress, type QueryOptions, type QueueInfoResponse, type QueueMessage, type ReadReceiptHandler, type ReadReceiptInfo, type RealtimeConnectOptions, type RealtimeMessage, type RegisterDeviceRequest, type RelationType, type RenameFileRequest, type RenameFileResponse, type ReplayHighlight, type ReplayInfo, type ReplayPlayerInfo, type RestoreBackupRequest, type RestoreBackupResponse, type RetentionPolicy, type RoomInfo, type RoomStats, type RoomsResponse, type SaveDialogOptions, type SaveDialogResult, type SearchIndex, type SearchOptions, type SearchResponse, type SearchResult, type SecurityRule, type SendOptions, type ServerMessage, SessionManager, type SetPageMetaRequest, type Shorts, type ShortsListResponse, type SignalingMessage, type SignalingMessageType, type SlowQueryInfo, type SpectatorInfo, type SpectatorPlayerState, type SpectatorState, type StateChange, type StateChangeHandler, type StorageUploadOptions, type StreamDoneCallback, type StreamDoneData, type StreamErrorCallback, type StreamHandlers, type StreamMessage, type StreamOptions, type StreamSession, type StreamTokenCallback, type StreamToolCallCallback, type StreamToolResultCallback, type StreamURLResponse, type SubscribeOptions, type SubscribeTopicRequest, type SubscribedData, type Subscription, type SubscriptionPaymentResponse, type SubscriptionPaymentStatus, type SubscriptionResponse, type SubscriptionStatus, type SuperChat, type SystemInfo, type TTLConfig, type TableAccessLevel, type TableColumnDef, type TableIndex, type TableRelation, type TableSchema, type TableSchemaDefinition, type TokenPersistence, type TransactionRead, type TransactionWrite, type TranscodeStatus, type TransportType, type Trigger, type TriggerEvent, type TriggerHandlerType, type TypingChangeHandler, type TypingInfo, type UpdateBillingKeyRequest, type UpdateChannelRequest, type UpdateColumnRequest, type UpdateCustomDataRequest, type UpdateCustomDataResponse, type UpdateDataRequest, type UpdateLobbyRequest, type UpdatePublicKeyRequest, type UpdatePublicKeyResponse, type UpdateSecurityRuleRequest, type UpdateSubscriptionRequest, type UpdateTriggerRequest, type UpdateVideoRequest, type UpdateVideoStorageRequest, type UploadByPathOptions, type UploadFileResponse, type UploadOptions, type UploadProgress, type VAPIDPublicKeyResponse, type ValidateResponse, type ValidationSchema, type ValidationSchemaField, type ValidationStateTransitions, type Video, type VideoComment, type VideoListOptions, type VideoListResponse, VideoProcessingError, type VideoQuality, type VideoStatus, type VideoStorage, type VideoStorageListResponse, type VideoVisibility, type VoiceChannel, type VoiceMember, type WaitOptions, type WatchHistoryItem, type WebPushSubscription, type WebRTCConnectOptions, type WebRTCConnectionState, type WebRTCMode, type WhereCondition, type WhereOperator, ConnectBase as default, isWebTransportSupported };
7152
+ export { AIAPI, type AIChatRequest, type AIChatResponse, type AIMessage, type AISource, type AIStreamChunk, type AITool, type AIToolCall, type AIToolEvent, type AckMessagesRequest, type AdMobDailyReport, type AdMobReportResponse, type AdMobReportSummary, type AdReportResponse, type AdReportSummary, type AdmobConnectionInfo, AdsAPI, type AdsenseConnectionInfo, type AggregateResult, type AggregateStage, type AnalyticsConfig, type AnalyticsEvent, ApiError, type ApiErrorDetail, type AppStatsResponse, type ArchivePolicy, type AtomicOperator, type AtomicOperatorType, AuthError, type AuthSettingsResponse, type BackupInfo, type BatchOperation, type BatchSetPageMetaRequest, type BillingCycle, type BillingKeyResponse, type BiometricInfo, type BiometricResult, type BulkCreateResponse, type BulkError, type CPUInfo, type CancelPaymentRequest, type CancelPaymentResponse, type CancelSubscriptionRequest, type CategoryInfo, type Channel, type ChannelMembership, type ChargeWithBillingKeyRequest, type ChargeWithBillingKeyResponse, type ChatMessage, type ClientMessage, type ColumnSchema, type CommentListResponse, type CompleteUploadRequest, type CompleteUploadResponse, type ConfirmBillingKeyRequest, type ConfirmPaymentRequest, type ConfirmPaymentResponse, ConnectBase, type ConnectBaseConfig, type ConnectedData, type ConnectionState, type ConsentOptions, type ConsumeMessagesResponse, type ConsumeOptions, type CopyTableRequest, type CopyTableResponse, type CreateBackupRequest, type CreateChannelRequest, type CreateCheckoutSessionRequest, type CreateCheckoutSessionResponse, type CreateColumnRequest, type CreateDataRequest, type CreateDocumentRequest, type CreateFolderRequest, type CreateFolderResponse, type CreateGeoIndexRequest, type CreateIndexRequest, type CreateLobbyRequest, type CreatePlaylistRequest, type CreatePublicKeyRequest, type CreatePublicKeyResponse, type CreateRelationRequest, type CreateSearchIndexRequest, type CreateSecurityRuleRequest, type CreateSubscriptionRequest, type CreateTableRequest, type CreateTriggerRequest, type CreateVideoStorageRequest, type DailyReport, type DataItem, type DataType, type DatabaseChange, type DatabaseChangeMessage, type DatabaseChangeType, type DatabaseRealtimeConnectOptions, type DatabaseRealtimeFilter, type DatabaseRealtimeHandlers, type DatabaseRealtimeSubscription, type DatabaseSnapshot, type DatabaseSnapshotMessage, type DatabaseSubscribeOptions, type DeleteWhereResponse, type DeviceInfo, type DocumentResponse, type EnabledProviderInfo, type EnabledProvidersResponse, type ErrorHandler, type ErrorMessage, type ErrorReport, type ErrorTrackerConfig, type ErrorType, type ExportDataRequest, type ExportDataResponse, type FetchDataResponse, type FetchFilesResponse, type FetchPublicKeysResponse, type FileItem, type FileStats, GameAPI, type GameAction, type GameClientConfig, type GameConnectionState, type GameConnectionStatus, type GameDelta, type GameEventHandlers, type GamePlayer, GameRoom, type GameRoomConfig, type GameRoomInfo, GameRoomTransport, type GameServerMessage, type GameServerMessageType, type GameState, type GameTransportConfig, type GenerateUploadURLByPathRequest, type GenerateUploadURLRequest, type GenerateUploadURLResponse, type GeoIndex, type GeoNear, type GeoPoint, type GeoPolygon, type GeoQuery, type GeoResponse, type GeoResult, type GeoWithin, type GetAuthorizationURLResponse, type GetFileByPathResponse, type GoogleConnectionStatus, type GuestMemberSignInResponse, type HistoryResponse, type ICEServer, type ICEServersResponse, type ImageResult, type ImportDataRequest, type ImportDataResponse, type IndexAnalysis, type IndexRecommendation, type InitUploadResponse, type InvokeFunctionRequest, type InvokeFunctionResponse, type IssueBillingKeyRequest, type IssueBillingKeyResponse, type JoinQueueRequest, type JoinRoomRequest, type JoinRoomResponse, type KnowledgeSearchRequest, type KnowledgeSearchResponse, type KnowledgeSearchResult, type LeaderboardEntry, type LifecyclePolicy, type ListBillingKeysResponse, type ListDocumentsResponse, type ListPageMetasOptions, type ListPageMetasResponse, type ListSubscriptionPaymentsRequest, type ListSubscriptionPaymentsResponse, type ListSubscriptionsRequest, type ListSubscriptionsResponse, type LobbyInfo, type LobbyInvite, type LobbyMember, type LobbyVisibility, type MatchResult, type MatchmakingTicket, type MemberInfoResponse, type MemberSignInRequest, type MemberSignInResponse, type MemberSignUpRequest, type MemberSignUpResponse, type MembershipTier, type MemoryInfo, type MessageHandler, type MigrateDataRequest, type MigrateDataResponse, type MoveFileRequest, type NackMessageRequest, NativeAPI, type OAuthCallbackResponse, type OAuthProvider, type OpenDialogOptions, type OpenDialogResult, type PageMetaResponse, type PartyInfo, type PartyInvite, type PartyMember, type PauseSubscriptionRequest, type PaymentDetail, type PaymentProvider, type PaymentStatus, type PeerInfo, type Platform, type PlayerEvent, type PlayerStats, type Playlist, type PlaylistItem, type PongMessage, type PopulateOption, type Position, type PreparePaymentRequest, type PreparePaymentResponse, type PresenceChangeHandler, type PresenceInfo, type PresenceSetOptions, type PresenceStatus, type PresenceStatusResult, type PublicKeyItem, type PublishBatchRequest, type PublishBatchResponse, type PublishMessageRequest, type PublishMessageResponse, type PushPlatform, type QualityProgress, type QueryOptions, type QueueInfoResponse, type QueueMessage, type ReadReceiptHandler, type ReadReceiptInfo, type RealtimeConnectOptions, type RealtimeMessage, type RegisterDeviceRequest, type RelationType, type RenameFileRequest, type RenameFileResponse, type ReplayHighlight, type ReplayInfo, type ReplayPlayerInfo, type RestoreBackupRequest, type RestoreBackupResponse, type RetentionPolicy, type RoomInfo, type RoomStats, type RoomsResponse, type SaveDialogOptions, type SaveDialogResult, type SearchIndex, type SearchOptions, type SearchResponse, type SearchResult, type SecurityRule, type SendOptions, type ServerMessage, SessionManager, type SetPageMetaRequest, type Shorts, type ShortsListResponse, type SignalingMessage, type SignalingMessageType, type SlowQueryInfo, type SpectatorInfo, type SpectatorPlayerState, type SpectatorState, type StateChange, type StateChangeHandler, type StorageUploadOptions, type StreamDoneCallback, type StreamDoneData, type StreamErrorCallback, type StreamHandlers, type StreamMessage, type StreamOptions, type StreamSession, type StreamTokenCallback, type StreamToolCallCallback, type StreamToolResultCallback, type StreamURLResponse, type SubscribeOptions, type SubscribeTopicRequest, type SubscribedData, type Subscription, type SubscriptionPaymentResponse, type SubscriptionPaymentStatus, type SubscriptionResponse, type SubscriptionStatus, type SuperChat, type SystemInfo, type TTLConfig, type TableAccessLevel, type TableColumnDef, type TableIndex, type TableRelation, type TableSchema, type TableSchemaDefinition, type TokenPersistence, type TransactionRead, type TransactionWrite, type TranscodeStatus, type TransportType, type Trigger, type TriggerEvent, type TriggerHandlerType, type TypingChangeHandler, type TypingInfo, type UpdateBillingKeyRequest, type UpdateChannelRequest, type UpdateColumnRequest, type UpdateCustomDataRequest, type UpdateCustomDataResponse, type UpdateDataRequest, type UpdateLobbyRequest, type UpdatePublicKeyRequest, type UpdatePublicKeyResponse, type UpdateSecurityRuleRequest, type UpdateSubscriptionRequest, type UpdateTriggerRequest, type UpdateVideoRequest, type UpdateVideoStorageRequest, type UploadByPathOptions, type UploadFileResponse, type UploadOptions, type UploadProgress, type VAPIDPublicKeyResponse, type ValidateResponse, type ValidationSchema, type ValidationSchemaField, type ValidationStateTransitions, type Video, type VideoComment, type VideoListOptions, type VideoListResponse, VideoProcessingError, type VideoQuality, type VideoStatus, type VideoStorage, type VideoStorageListResponse, type VideoVisibility, type VoiceChannel, type VoiceMember, type WaitOptions, type WatchHistoryItem, type WebPushSubscription, type WebRTCConnectOptions, type WebRTCConnectionState, type WebRTCMode, type WhereCondition, type WhereOperator, ConnectBase as default, isWebTransportSupported };
package/dist/index.d.ts CHANGED
@@ -241,7 +241,66 @@ interface AnalyticsRangeOptions {
241
241
  interface VisitorListOptions {
242
242
  limit?: number;
243
243
  offset?: number;
244
- sort_by?: 'last_visit' | 'total_visits' | 'total_page_views';
244
+ /**
245
+ * 백엔드가 인식하는 정렬 키 — 외 값은 silent 로 default(`last_visit`) 처리됩니다.
246
+ *
247
+ * 1.12.0 에서 백엔드 실제 동작에 맞춰 enum 정정 (1.10/1.11 의 `total_visits`/
248
+ * `total_page_views` 는 백엔드에서 인식되지 않아 항상 default 분기였음).
249
+ */
250
+ sort_by?: 'last_visit' | 'visits' | 'page_views' | 'first_visit';
251
+ }
252
+ /**
253
+ * 멤버별 합산 방문자 그룹 항목.
254
+ *
255
+ * 한 명의 회원이 여러 디바이스/브라우저로 접속했을 때 visitor row 들을 합쳐 단일 row.
256
+ * 익명 visitor 는 `app_member_id == undefined` 로 단일 row 그대로 노출되며 `visitor_count == 1`.
257
+ *
258
+ * `visitor_count` 는 "디바이스 수" 가 아닌 **"추적 브라우저 인스턴스 수"** 를 의미합니다.
259
+ * 같은 디바이스에서 시크릿모드 + 일반모드는 visitor 2 = visitor_count 2 로 카운트됩니다.
260
+ */
261
+ interface VisitorGroupItem {
262
+ app_member_id?: string;
263
+ /** 익명 visitor row 의 경우 단일 visitor_uid. 회원 그룹은 visitor_uids 참조. */
264
+ visitor_uid?: string;
265
+ /** 회원 그룹에 속한 visitor_uid 목록. 익명 row 는 undefined. */
266
+ visitor_uids?: string[];
267
+ visitor_count: number;
268
+ total_visits: number;
269
+ total_page_views: number;
270
+ first_visit_at: string;
271
+ last_visit_at: string;
272
+ country?: string;
273
+ is_bot: boolean;
274
+ }
275
+ interface VisitorGroupListResponse {
276
+ groups: VisitorGroupItem[];
277
+ total: number;
278
+ limit: number;
279
+ offset: number;
280
+ has_more: boolean;
281
+ }
282
+ interface VisitorByMemberResponse {
283
+ app_member_id: string;
284
+ visitor_uids: string[];
285
+ visitor_count: number;
286
+ total_visits: number;
287
+ total_page_views: number;
288
+ first_visit_at: string;
289
+ last_visit_at: string;
290
+ country?: string;
291
+ is_bot: boolean;
292
+ }
293
+ interface MergeVisitorsRequest {
294
+ source_visitor_uid: string;
295
+ /** target_visitor_uid 또는 target_member_id 중 하나는 필수. */
296
+ target_visitor_uid?: string;
297
+ target_member_id?: string;
298
+ }
299
+ interface MergeVisitorsResponse {
300
+ success: boolean;
301
+ target_visitor_id: string;
302
+ moved_records: number;
303
+ message?: string;
245
304
  }
246
305
  declare class SessionManager {
247
306
  private _sessionId;
@@ -302,15 +361,38 @@ declare class AnalyticsAPI {
302
361
  */
303
362
  trackEvent(name: string, properties?: Record<string, unknown>): void;
304
363
  /**
305
- * 사용자 식별 (로그인 )
306
- * 이후 모든 방문 배치에 `app_member_id`가 첨부되어 게스트 방문자가 회원으로 연결됩니다.
364
+ * 사용자 식별 (로그인 직후 호출).
365
+ *
366
+ * 이후 모든 방문 배치에 `app_member_id` 가 첨부되어 새 활동은 회원으로 기록됩니다.
367
+ * 추가로 **현재 visitor_uid 의 기존 익명 활동을 즉시 회원에게 backfill** 하기 위해
368
+ * 백엔드 `link-member` 엔드포인트를 한 번 호출합니다 (1.11.0+). 호출 실패는
369
+ * silent — 다음 batch 가 닿을 때 백엔드 자동 매핑이 동일하게 처리하므로 자가 복구.
370
+ *
371
+ * 산업 표준(GA4 User-ID, Mixpanel/PostHog `identify`) 과 동작 정합.
372
+ *
373
+ * @example
374
+ * ```ts
375
+ * // 로그인 성공 직후
376
+ * await cb.auth.signIn({ email, password })
377
+ * cb.analytics.identify(member.id)
378
+ * ```
307
379
  */
308
380
  identify(memberId: string): void;
309
381
  /**
310
- * 방문자 트래커에 현재 회원 ID 설정 (로그인/게스트 가입 시 호출)
311
- * null 을 넘기면 익명 상태로 복귀 (로그아웃).
382
+ * 방문자 트래커에 현재 회원 ID 설정 (로그인/게스트 가입 시 호출).
383
+ *
384
+ * `identify()` 와 달리 즉시 backfill 호출은 하지 않습니다 — 단순히 이후 batch 의
385
+ * `app_member_id` 값만 갱신. null 을 넘기면 익명 상태로 복귀 (로그아웃).
312
386
  */
313
387
  setMemberId(memberId: string | null): void;
388
+ /**
389
+ * 백엔드 link-member 엔드포인트 한 번 호출 — 즉시 backfill 트리거.
390
+ *
391
+ * - 첫 페이지뷰가 아직 백엔드에 닿기 전이면 visitor 가 없어 404. 무시 — 다음 batch 가
392
+ * 가면 백엔드 BatchRecordVisit 가 자동 LinkMember 를 호출.
393
+ * - storage_web_id 가 init 안 됐거나 모든 종류의 네트워크 오류 — silent fail.
394
+ */
395
+ private linkMemberSilent;
314
396
  /** 현재 설정된 회원 ID 조회 (미설정 시 null) */
315
397
  getMemberId(): string | null;
316
398
  /**
@@ -363,6 +445,52 @@ declare class AnalyticsAPI {
363
445
  * 방문자 목록 조회 — JWT/cb_sk_ 인증 필요.
364
446
  */
365
447
  getVisitors(storageWebId?: string, options?: VisitorListOptions): Promise<VisitorListResponse>;
448
+ /**
449
+ * 멤버별 합산 방문자 그룹 조회 — JWT/cb_sk_ 인증 필요. (1.11+)
450
+ *
451
+ * `getVisitors` 와 달리 visitor row 들을 `app_member_id` 로 합쳐 단일 row 로 반환.
452
+ * 같은 사람이 PC + 모바일 + 태블릿으로 접속한 경우 visitor 3개 → 그룹 1개.
453
+ * 익명 visitor 는 단일 row 로 그대로 포함되어 페이지네이션이 일관됨.
454
+ *
455
+ * @example
456
+ * ```ts
457
+ * const { groups } = await cb.analytics.getVisitorGroups('019d8...', { limit: 50 })
458
+ * for (const g of groups) {
459
+ * if (g.app_member_id) console.log(`${g.app_member_id}: ${g.visitor_count} 디바이스`)
460
+ * }
461
+ * ```
462
+ */
463
+ getVisitorGroups(storageWebId?: string, options?: VisitorListOptions): Promise<VisitorGroupListResponse>;
464
+ /**
465
+ * 단건 멤버 합산 방문자 조회 — JWT/cb_sk_ 인증 필요. (1.11+)
466
+ *
467
+ * 어드민 회원 상세 페이지처럼 **한 명만 필요**할 때. 페이지네이션 풀 다운 없이
468
+ * 한 번의 호출로 합산 결과 반환.
469
+ *
470
+ * @example
471
+ * ```ts
472
+ * const v = await cb.analytics.getVisitorByMember('019d8...', memberId)
473
+ * console.log(`${v.visitor_count} 디바이스, 총 ${v.total_page_views} pv`)
474
+ * ```
475
+ */
476
+ getVisitorByMember(storageWebId: string | undefined, memberId: string): Promise<VisitorByMemberResponse>;
477
+ /**
478
+ * 두 visitor 를 한 사람으로 통합하는 admin 작업 — JWT/cb_sk_ 인증 필요. (1.11+)
479
+ *
480
+ * 외부 인증 시스템에서 두 visitor 가 동일인임을 알았을 때 사용. source 의 자식 레코드
481
+ * (page_views, daily, custom_events, experiment_assignments, heatmap_events,
482
+ * session_recordings) 를 target 으로 옮기고 source visitor 는 삭제됨.
483
+ *
484
+ * @param request 둘 중 하나 필수: `target_visitor_uid` 또는 `target_member_id`.
485
+ * @example
486
+ * ```ts
487
+ * await cb.analytics.mergeVisitors('019d8...', {
488
+ * source_visitor_uid: 'old-uid',
489
+ * target_member_id: '01a...',
490
+ * })
491
+ * ```
492
+ */
493
+ mergeVisitors(storageWebId: string | undefined, request: MergeVisitorsRequest): Promise<MergeVisitorsResponse>;
366
494
  /**
367
495
  * 조회 메서드 공통 가드 — Public Key 인증 SDK 인스턴스에서는 명확한 에러를 던진다.
368
496
  * 백엔드 라우트는 cb_pk_ 를 거부하므로 호출 자체를 막는 것이 디버깅에 유리.
@@ -1232,14 +1360,6 @@ interface DatabaseRealtimeConnectOptions {
1232
1360
  /** 디버그 로깅 (기본: false) */
1233
1361
  debug?: boolean;
1234
1362
  }
1235
- /** 데이터베이스 실시간 프레즌스 상태 */
1236
- interface DatabasePresenceState {
1237
- user_id: string;
1238
- status: 'online' | 'away' | 'offline';
1239
- last_seen: string;
1240
- device?: string;
1241
- metadata?: Record<string, unknown>;
1242
- }
1243
1363
  interface CreateBackupRequest {
1244
1364
  /** 백업 이름 */
1245
1365
  name: string;
@@ -1770,14 +1890,6 @@ declare class DatabaseAPI {
1770
1890
  * @returns 구독 해제 가능한 객체
1771
1891
  */
1772
1892
  subscribe(tableId: string, handlers: DatabaseRealtimeHandlers, options?: DatabaseSubscribeOptions): DatabaseRealtimeSubscription;
1773
- /**
1774
- * 프레즌스 상태 설정
1775
- */
1776
- setPresence(status: string, device?: string, metadata?: Record<string, unknown>): void;
1777
- /**
1778
- * 프레즌스 구독 (다른 사용자의 온라인 상태 감시)
1779
- */
1780
- subscribePresence(userIds: string[], onPresence: (states: Record<string, DatabasePresenceState>) => void): void;
1781
1893
  /**
1782
1894
  * 실시간 연결 상태 확인
1783
1895
  */
@@ -7037,4 +7149,4 @@ declare class ConnectBase {
7037
7149
  updateConfig(config: Partial<ConnectBaseConfig>): void;
7038
7150
  }
7039
7151
 
7040
- export { AIAPI, type AIChatRequest, type AIChatResponse, type AIMessage, type AISource, type AIStreamChunk, type AITool, type AIToolCall, type AIToolEvent, type AckMessagesRequest, type AdMobDailyReport, type AdMobReportResponse, type AdMobReportSummary, type AdReportResponse, type AdReportSummary, type AdmobConnectionInfo, AdsAPI, type AdsenseConnectionInfo, type AggregateResult, type AggregateStage, type AnalyticsConfig, type AnalyticsEvent, ApiError, type ApiErrorDetail, type AppStatsResponse, type ArchivePolicy, type AtomicOperator, type AtomicOperatorType, AuthError, type AuthSettingsResponse, type BackupInfo, type BatchOperation, type BatchSetPageMetaRequest, type BillingCycle, type BillingKeyResponse, type BiometricInfo, type BiometricResult, type BulkCreateResponse, type BulkError, type CPUInfo, type CancelPaymentRequest, type CancelPaymentResponse, type CancelSubscriptionRequest, type CategoryInfo, type Channel, type ChannelMembership, type ChargeWithBillingKeyRequest, type ChargeWithBillingKeyResponse, type ChatMessage, type ClientMessage, type ColumnSchema, type CommentListResponse, type CompleteUploadRequest, type CompleteUploadResponse, type ConfirmBillingKeyRequest, type ConfirmPaymentRequest, type ConfirmPaymentResponse, ConnectBase, type ConnectBaseConfig, type ConnectedData, type ConnectionState, type ConsentOptions, type ConsumeMessagesResponse, type ConsumeOptions, type CopyTableRequest, type CopyTableResponse, type CreateBackupRequest, type CreateChannelRequest, type CreateCheckoutSessionRequest, type CreateCheckoutSessionResponse, type CreateColumnRequest, type CreateDataRequest, type CreateDocumentRequest, type CreateFolderRequest, type CreateFolderResponse, type CreateGeoIndexRequest, type CreateIndexRequest, type CreateLobbyRequest, type CreatePlaylistRequest, type CreatePublicKeyRequest, type CreatePublicKeyResponse, type CreateRelationRequest, type CreateSearchIndexRequest, type CreateSecurityRuleRequest, type CreateSubscriptionRequest, type CreateTableRequest, type CreateTriggerRequest, type CreateVideoStorageRequest, type DailyReport, type DataItem, type DataType, type DatabaseChange, type DatabaseChangeMessage, type DatabaseChangeType, type DatabasePresenceState, type DatabaseRealtimeConnectOptions, type DatabaseRealtimeFilter, type DatabaseRealtimeHandlers, type DatabaseRealtimeSubscription, type DatabaseSnapshot, type DatabaseSnapshotMessage, type DatabaseSubscribeOptions, type DeleteWhereResponse, type DeviceInfo, type DocumentResponse, type EnabledProviderInfo, type EnabledProvidersResponse, type ErrorHandler, type ErrorMessage, type ErrorReport, type ErrorTrackerConfig, type ErrorType, type ExportDataRequest, type ExportDataResponse, type FetchDataResponse, type FetchFilesResponse, type FetchPublicKeysResponse, type FileItem, type FileStats, GameAPI, type GameAction, type GameClientConfig, type GameConnectionState, type GameConnectionStatus, type GameDelta, type GameEventHandlers, type GamePlayer, GameRoom, type GameRoomConfig, type GameRoomInfo, GameRoomTransport, type GameServerMessage, type GameServerMessageType, type GameState, type GameTransportConfig, type GenerateUploadURLByPathRequest, type GenerateUploadURLRequest, type GenerateUploadURLResponse, type GeoIndex, type GeoNear, type GeoPoint, type GeoPolygon, type GeoQuery, type GeoResponse, type GeoResult, type GeoWithin, type GetAuthorizationURLResponse, type GetFileByPathResponse, type GoogleConnectionStatus, type GuestMemberSignInResponse, type HistoryResponse, type ICEServer, type ICEServersResponse, type ImageResult, type ImportDataRequest, type ImportDataResponse, type IndexAnalysis, type IndexRecommendation, type InitUploadResponse, type InvokeFunctionRequest, type InvokeFunctionResponse, type IssueBillingKeyRequest, type IssueBillingKeyResponse, type JoinQueueRequest, type JoinRoomRequest, type JoinRoomResponse, type KnowledgeSearchRequest, type KnowledgeSearchResponse, type KnowledgeSearchResult, type LeaderboardEntry, type LifecyclePolicy, type ListBillingKeysResponse, type ListDocumentsResponse, type ListPageMetasOptions, type ListPageMetasResponse, type ListSubscriptionPaymentsRequest, type ListSubscriptionPaymentsResponse, type ListSubscriptionsRequest, type ListSubscriptionsResponse, type LobbyInfo, type LobbyInvite, type LobbyMember, type LobbyVisibility, type MatchResult, type MatchmakingTicket, type MemberInfoResponse, type MemberSignInRequest, type MemberSignInResponse, type MemberSignUpRequest, type MemberSignUpResponse, type MembershipTier, type MemoryInfo, type MessageHandler, type MigrateDataRequest, type MigrateDataResponse, type MoveFileRequest, type NackMessageRequest, NativeAPI, type OAuthCallbackResponse, type OAuthProvider, type OpenDialogOptions, type OpenDialogResult, type PageMetaResponse, type PartyInfo, type PartyInvite, type PartyMember, type PauseSubscriptionRequest, type PaymentDetail, type PaymentProvider, type PaymentStatus, type PeerInfo, type Platform, type PlayerEvent, type PlayerStats, type Playlist, type PlaylistItem, type PongMessage, type PopulateOption, type Position, type PreparePaymentRequest, type PreparePaymentResponse, type PresenceChangeHandler, type PresenceInfo, type PresenceSetOptions, type PresenceStatus, type PresenceStatusResult, type PublicKeyItem, type PublishBatchRequest, type PublishBatchResponse, type PublishMessageRequest, type PublishMessageResponse, type PushPlatform, type QualityProgress, type QueryOptions, type QueueInfoResponse, type QueueMessage, type ReadReceiptHandler, type ReadReceiptInfo, type RealtimeConnectOptions, type RealtimeMessage, type RegisterDeviceRequest, type RelationType, type RenameFileRequest, type RenameFileResponse, type ReplayHighlight, type ReplayInfo, type ReplayPlayerInfo, type RestoreBackupRequest, type RestoreBackupResponse, type RetentionPolicy, type RoomInfo, type RoomStats, type RoomsResponse, type SaveDialogOptions, type SaveDialogResult, type SearchIndex, type SearchOptions, type SearchResponse, type SearchResult, type SecurityRule, type SendOptions, type ServerMessage, SessionManager, type SetPageMetaRequest, type Shorts, type ShortsListResponse, type SignalingMessage, type SignalingMessageType, type SlowQueryInfo, type SpectatorInfo, type SpectatorPlayerState, type SpectatorState, type StateChange, type StateChangeHandler, type StorageUploadOptions, type StreamDoneCallback, type StreamDoneData, type StreamErrorCallback, type StreamHandlers, type StreamMessage, type StreamOptions, type StreamSession, type StreamTokenCallback, type StreamToolCallCallback, type StreamToolResultCallback, type StreamURLResponse, type SubscribeOptions, type SubscribeTopicRequest, type SubscribedData, type Subscription, type SubscriptionPaymentResponse, type SubscriptionPaymentStatus, type SubscriptionResponse, type SubscriptionStatus, type SuperChat, type SystemInfo, type TTLConfig, type TableAccessLevel, type TableColumnDef, type TableIndex, type TableRelation, type TableSchema, type TableSchemaDefinition, type TokenPersistence, type TransactionRead, type TransactionWrite, type TranscodeStatus, type TransportType, type Trigger, type TriggerEvent, type TriggerHandlerType, type TypingChangeHandler, type TypingInfo, type UpdateBillingKeyRequest, type UpdateChannelRequest, type UpdateColumnRequest, type UpdateCustomDataRequest, type UpdateCustomDataResponse, type UpdateDataRequest, type UpdateLobbyRequest, type UpdatePublicKeyRequest, type UpdatePublicKeyResponse, type UpdateSecurityRuleRequest, type UpdateSubscriptionRequest, type UpdateTriggerRequest, type UpdateVideoRequest, type UpdateVideoStorageRequest, type UploadByPathOptions, type UploadFileResponse, type UploadOptions, type UploadProgress, type VAPIDPublicKeyResponse, type ValidateResponse, type ValidationSchema, type ValidationSchemaField, type ValidationStateTransitions, type Video, type VideoComment, type VideoListOptions, type VideoListResponse, VideoProcessingError, type VideoQuality, type VideoStatus, type VideoStorage, type VideoStorageListResponse, type VideoVisibility, type VoiceChannel, type VoiceMember, type WaitOptions, type WatchHistoryItem, type WebPushSubscription, type WebRTCConnectOptions, type WebRTCConnectionState, type WebRTCMode, type WhereCondition, type WhereOperator, ConnectBase as default, isWebTransportSupported };
7152
+ export { AIAPI, type AIChatRequest, type AIChatResponse, type AIMessage, type AISource, type AIStreamChunk, type AITool, type AIToolCall, type AIToolEvent, type AckMessagesRequest, type AdMobDailyReport, type AdMobReportResponse, type AdMobReportSummary, type AdReportResponse, type AdReportSummary, type AdmobConnectionInfo, AdsAPI, type AdsenseConnectionInfo, type AggregateResult, type AggregateStage, type AnalyticsConfig, type AnalyticsEvent, ApiError, type ApiErrorDetail, type AppStatsResponse, type ArchivePolicy, type AtomicOperator, type AtomicOperatorType, AuthError, type AuthSettingsResponse, type BackupInfo, type BatchOperation, type BatchSetPageMetaRequest, type BillingCycle, type BillingKeyResponse, type BiometricInfo, type BiometricResult, type BulkCreateResponse, type BulkError, type CPUInfo, type CancelPaymentRequest, type CancelPaymentResponse, type CancelSubscriptionRequest, type CategoryInfo, type Channel, type ChannelMembership, type ChargeWithBillingKeyRequest, type ChargeWithBillingKeyResponse, type ChatMessage, type ClientMessage, type ColumnSchema, type CommentListResponse, type CompleteUploadRequest, type CompleteUploadResponse, type ConfirmBillingKeyRequest, type ConfirmPaymentRequest, type ConfirmPaymentResponse, ConnectBase, type ConnectBaseConfig, type ConnectedData, type ConnectionState, type ConsentOptions, type ConsumeMessagesResponse, type ConsumeOptions, type CopyTableRequest, type CopyTableResponse, type CreateBackupRequest, type CreateChannelRequest, type CreateCheckoutSessionRequest, type CreateCheckoutSessionResponse, type CreateColumnRequest, type CreateDataRequest, type CreateDocumentRequest, type CreateFolderRequest, type CreateFolderResponse, type CreateGeoIndexRequest, type CreateIndexRequest, type CreateLobbyRequest, type CreatePlaylistRequest, type CreatePublicKeyRequest, type CreatePublicKeyResponse, type CreateRelationRequest, type CreateSearchIndexRequest, type CreateSecurityRuleRequest, type CreateSubscriptionRequest, type CreateTableRequest, type CreateTriggerRequest, type CreateVideoStorageRequest, type DailyReport, type DataItem, type DataType, type DatabaseChange, type DatabaseChangeMessage, type DatabaseChangeType, type DatabaseRealtimeConnectOptions, type DatabaseRealtimeFilter, type DatabaseRealtimeHandlers, type DatabaseRealtimeSubscription, type DatabaseSnapshot, type DatabaseSnapshotMessage, type DatabaseSubscribeOptions, type DeleteWhereResponse, type DeviceInfo, type DocumentResponse, type EnabledProviderInfo, type EnabledProvidersResponse, type ErrorHandler, type ErrorMessage, type ErrorReport, type ErrorTrackerConfig, type ErrorType, type ExportDataRequest, type ExportDataResponse, type FetchDataResponse, type FetchFilesResponse, type FetchPublicKeysResponse, type FileItem, type FileStats, GameAPI, type GameAction, type GameClientConfig, type GameConnectionState, type GameConnectionStatus, type GameDelta, type GameEventHandlers, type GamePlayer, GameRoom, type GameRoomConfig, type GameRoomInfo, GameRoomTransport, type GameServerMessage, type GameServerMessageType, type GameState, type GameTransportConfig, type GenerateUploadURLByPathRequest, type GenerateUploadURLRequest, type GenerateUploadURLResponse, type GeoIndex, type GeoNear, type GeoPoint, type GeoPolygon, type GeoQuery, type GeoResponse, type GeoResult, type GeoWithin, type GetAuthorizationURLResponse, type GetFileByPathResponse, type GoogleConnectionStatus, type GuestMemberSignInResponse, type HistoryResponse, type ICEServer, type ICEServersResponse, type ImageResult, type ImportDataRequest, type ImportDataResponse, type IndexAnalysis, type IndexRecommendation, type InitUploadResponse, type InvokeFunctionRequest, type InvokeFunctionResponse, type IssueBillingKeyRequest, type IssueBillingKeyResponse, type JoinQueueRequest, type JoinRoomRequest, type JoinRoomResponse, type KnowledgeSearchRequest, type KnowledgeSearchResponse, type KnowledgeSearchResult, type LeaderboardEntry, type LifecyclePolicy, type ListBillingKeysResponse, type ListDocumentsResponse, type ListPageMetasOptions, type ListPageMetasResponse, type ListSubscriptionPaymentsRequest, type ListSubscriptionPaymentsResponse, type ListSubscriptionsRequest, type ListSubscriptionsResponse, type LobbyInfo, type LobbyInvite, type LobbyMember, type LobbyVisibility, type MatchResult, type MatchmakingTicket, type MemberInfoResponse, type MemberSignInRequest, type MemberSignInResponse, type MemberSignUpRequest, type MemberSignUpResponse, type MembershipTier, type MemoryInfo, type MessageHandler, type MigrateDataRequest, type MigrateDataResponse, type MoveFileRequest, type NackMessageRequest, NativeAPI, type OAuthCallbackResponse, type OAuthProvider, type OpenDialogOptions, type OpenDialogResult, type PageMetaResponse, type PartyInfo, type PartyInvite, type PartyMember, type PauseSubscriptionRequest, type PaymentDetail, type PaymentProvider, type PaymentStatus, type PeerInfo, type Platform, type PlayerEvent, type PlayerStats, type Playlist, type PlaylistItem, type PongMessage, type PopulateOption, type Position, type PreparePaymentRequest, type PreparePaymentResponse, type PresenceChangeHandler, type PresenceInfo, type PresenceSetOptions, type PresenceStatus, type PresenceStatusResult, type PublicKeyItem, type PublishBatchRequest, type PublishBatchResponse, type PublishMessageRequest, type PublishMessageResponse, type PushPlatform, type QualityProgress, type QueryOptions, type QueueInfoResponse, type QueueMessage, type ReadReceiptHandler, type ReadReceiptInfo, type RealtimeConnectOptions, type RealtimeMessage, type RegisterDeviceRequest, type RelationType, type RenameFileRequest, type RenameFileResponse, type ReplayHighlight, type ReplayInfo, type ReplayPlayerInfo, type RestoreBackupRequest, type RestoreBackupResponse, type RetentionPolicy, type RoomInfo, type RoomStats, type RoomsResponse, type SaveDialogOptions, type SaveDialogResult, type SearchIndex, type SearchOptions, type SearchResponse, type SearchResult, type SecurityRule, type SendOptions, type ServerMessage, SessionManager, type SetPageMetaRequest, type Shorts, type ShortsListResponse, type SignalingMessage, type SignalingMessageType, type SlowQueryInfo, type SpectatorInfo, type SpectatorPlayerState, type SpectatorState, type StateChange, type StateChangeHandler, type StorageUploadOptions, type StreamDoneCallback, type StreamDoneData, type StreamErrorCallback, type StreamHandlers, type StreamMessage, type StreamOptions, type StreamSession, type StreamTokenCallback, type StreamToolCallCallback, type StreamToolResultCallback, type StreamURLResponse, type SubscribeOptions, type SubscribeTopicRequest, type SubscribedData, type Subscription, type SubscriptionPaymentResponse, type SubscriptionPaymentStatus, type SubscriptionResponse, type SubscriptionStatus, type SuperChat, type SystemInfo, type TTLConfig, type TableAccessLevel, type TableColumnDef, type TableIndex, type TableRelation, type TableSchema, type TableSchemaDefinition, type TokenPersistence, type TransactionRead, type TransactionWrite, type TranscodeStatus, type TransportType, type Trigger, type TriggerEvent, type TriggerHandlerType, type TypingChangeHandler, type TypingInfo, type UpdateBillingKeyRequest, type UpdateChannelRequest, type UpdateColumnRequest, type UpdateCustomDataRequest, type UpdateCustomDataResponse, type UpdateDataRequest, type UpdateLobbyRequest, type UpdatePublicKeyRequest, type UpdatePublicKeyResponse, type UpdateSecurityRuleRequest, type UpdateSubscriptionRequest, type UpdateTriggerRequest, type UpdateVideoRequest, type UpdateVideoStorageRequest, type UploadByPathOptions, type UploadFileResponse, type UploadOptions, type UploadProgress, type VAPIDPublicKeyResponse, type ValidateResponse, type ValidationSchema, type ValidationSchemaField, type ValidationStateTransitions, type Video, type VideoComment, type VideoListOptions, type VideoListResponse, VideoProcessingError, type VideoQuality, type VideoStatus, type VideoStorage, type VideoStorageListResponse, type VideoVisibility, type VoiceChannel, type VoiceMember, type WaitOptions, type WatchHistoryItem, type WebPushSubscription, type WebRTCConnectOptions, type WebRTCConnectionState, type WebRTCMode, type WhereCondition, type WhereOperator, ConnectBase as default, isWebTransportSupported };
package/dist/index.js CHANGED
@@ -1651,41 +1651,6 @@ var DatabaseAPI = class {
1651
1651
  }
1652
1652
  };
1653
1653
  }
1654
- /**
1655
- * 프레즌스 상태 설정
1656
- */
1657
- setPresence(status, device, metadata) {
1658
- if (this.realtimeState !== "connected") return;
1659
- this.sendRealtimeMessage({
1660
- type: "presence_set",
1661
- request_id: this.generateRequestId(),
1662
- status,
1663
- device,
1664
- metadata
1665
- });
1666
- }
1667
- /**
1668
- * 프레즌스 구독 (다른 사용자의 온라인 상태 감시)
1669
- */
1670
- subscribePresence(userIds, onPresence) {
1671
- if (this.realtimeState !== "connected") return;
1672
- this.realtimeHandlers.set("__presence__", {
1673
- onSnapshot: (docs) => {
1674
- const states = {};
1675
- for (const doc of docs) {
1676
- if (doc.data) {
1677
- states[doc.id] = doc.data;
1678
- }
1679
- }
1680
- onPresence(states);
1681
- }
1682
- });
1683
- this.sendRealtimeMessage({
1684
- type: "presence_subscribe",
1685
- request_id: this.generateRequestId(),
1686
- user_ids: userIds
1687
- });
1688
- }
1689
1654
  /**
1690
1655
  * 실시간 연결 상태 확인
1691
1656
  */
@@ -1727,7 +1692,7 @@ var DatabaseAPI = class {
1727
1692
  this.setRealtimeState("connecting");
1728
1693
  const baseUrl = this.realtimeOptions.dataServerUrl || this.http.getBaseUrl();
1729
1694
  const wsUrl = baseUrl.replace(/^http/, "ws");
1730
- const url = `${wsUrl}/v1/realtime/ws?access_token=${encodeURIComponent(this.realtimeOptions.accessToken)}`;
1695
+ const url = `${wsUrl}/v1/database/realtime/ws?access_token=${encodeURIComponent(this.realtimeOptions.accessToken)}`;
1731
1696
  return new Promise((resolve, reject) => {
1732
1697
  try {
1733
1698
  this.realtimeWs = new WebSocket(url);
@@ -8384,15 +8349,31 @@ var AnalyticsAPI = class {
8384
8349
  this.enqueue(event);
8385
8350
  }
8386
8351
  /**
8387
- * 사용자 식별 (로그인 )
8388
- * 이후 모든 방문 배치에 `app_member_id`가 첨부되어 게스트 방문자가 회원으로 연결됩니다.
8352
+ * 사용자 식별 (로그인 직후 호출).
8353
+ *
8354
+ * 이후 모든 방문 배치에 `app_member_id` 가 첨부되어 새 활동은 회원으로 기록됩니다.
8355
+ * 추가로 **현재 visitor_uid 의 기존 익명 활동을 즉시 회원에게 backfill** 하기 위해
8356
+ * 백엔드 `link-member` 엔드포인트를 한 번 호출합니다 (1.11.0+). 호출 실패는
8357
+ * silent — 다음 batch 가 닿을 때 백엔드 자동 매핑이 동일하게 처리하므로 자가 복구.
8358
+ *
8359
+ * 산업 표준(GA4 User-ID, Mixpanel/PostHog `identify`) 과 동작 정합.
8360
+ *
8361
+ * @example
8362
+ * ```ts
8363
+ * // 로그인 성공 직후
8364
+ * await cb.auth.signIn({ email, password })
8365
+ * cb.analytics.identify(member.id)
8366
+ * ```
8389
8367
  */
8390
8368
  identify(memberId) {
8391
8369
  this.setMemberId(memberId);
8370
+ this.linkMemberSilent(memberId);
8392
8371
  }
8393
8372
  /**
8394
- * 방문자 트래커에 현재 회원 ID 설정 (로그인/게스트 가입 시 호출)
8395
- * null 을 넘기면 익명 상태로 복귀 (로그아웃).
8373
+ * 방문자 트래커에 현재 회원 ID 설정 (로그인/게스트 가입 시 호출).
8374
+ *
8375
+ * `identify()` 와 달리 즉시 backfill 호출은 하지 않습니다 — 단순히 이후 batch 의
8376
+ * `app_member_id` 값만 갱신. null 을 넘기면 익명 상태로 복귀 (로그아웃).
8396
8377
  */
8397
8378
  setMemberId(memberId) {
8398
8379
  this.memberId = memberId || null;
@@ -8409,6 +8390,25 @@ var AnalyticsAPI = class {
8409
8390
  }
8410
8391
  this.log("Member id set", { memberId });
8411
8392
  }
8393
+ /**
8394
+ * 백엔드 link-member 엔드포인트 한 번 호출 — 즉시 backfill 트리거.
8395
+ *
8396
+ * - 첫 페이지뷰가 아직 백엔드에 닿기 전이면 visitor 가 없어 404. 무시 — 다음 batch 가
8397
+ * 가면 백엔드 BatchRecordVisit 가 자동 LinkMember 를 호출.
8398
+ * - storage_web_id 가 init 안 됐거나 모든 종류의 네트워크 오류 — silent fail.
8399
+ */
8400
+ linkMemberSilent(memberId) {
8401
+ if (!this.storageWebId) return;
8402
+ const prefix = this.http.hasPublicKey() ? "/v1/public" : "/v1";
8403
+ this.http.post(
8404
+ `${prefix}/storages/web/${this.storageWebId}/visitors/link-member`,
8405
+ {
8406
+ visitor_uid: this.session.visitorUid,
8407
+ app_member_id: memberId
8408
+ }
8409
+ ).catch(() => {
8410
+ });
8411
+ }
8412
8412
  /** 현재 설정된 회원 ID 조회 (미설정 시 null) */
8413
8413
  getMemberId() {
8414
8414
  return this.memberId;
@@ -8540,6 +8540,66 @@ var AnalyticsAPI = class {
8540
8540
  const qs = params.toString() ? `?${params.toString()}` : "";
8541
8541
  return this.http.get(`/v1/storages/web/${id}/visitors${qs}`);
8542
8542
  }
8543
+ /**
8544
+ * 멤버별 합산 방문자 그룹 조회 — JWT/cb_sk_ 인증 필요. (1.11+)
8545
+ *
8546
+ * `getVisitors` 와 달리 visitor row 들을 `app_member_id` 로 합쳐 단일 row 로 반환.
8547
+ * 같은 사람이 PC + 모바일 + 태블릿으로 접속한 경우 visitor 3개 → 그룹 1개.
8548
+ * 익명 visitor 는 단일 row 로 그대로 포함되어 페이지네이션이 일관됨.
8549
+ *
8550
+ * @example
8551
+ * ```ts
8552
+ * const { groups } = await cb.analytics.getVisitorGroups('019d8...', { limit: 50 })
8553
+ * for (const g of groups) {
8554
+ * if (g.app_member_id) console.log(`${g.app_member_id}: ${g.visitor_count} 디바이스`)
8555
+ * }
8556
+ * ```
8557
+ */
8558
+ async getVisitorGroups(storageWebId, options) {
8559
+ const id = this.requireServerSideStorageId(storageWebId, "getVisitorGroups");
8560
+ const params = new URLSearchParams();
8561
+ if (options?.limit !== void 0) params.set("limit", String(options.limit));
8562
+ if (options?.offset !== void 0) params.set("offset", String(options.offset));
8563
+ if (options?.sort_by) params.set("sort_by", options.sort_by);
8564
+ const qs = params.toString() ? `?${params.toString()}` : "";
8565
+ return this.http.get(`/v1/storages/web/${id}/visitor-groups${qs}`);
8566
+ }
8567
+ /**
8568
+ * 단건 멤버 합산 방문자 조회 — JWT/cb_sk_ 인증 필요. (1.11+)
8569
+ *
8570
+ * 어드민 회원 상세 페이지처럼 **한 명만 필요**할 때. 페이지네이션 풀 다운 없이
8571
+ * 한 번의 호출로 합산 결과 반환.
8572
+ *
8573
+ * @example
8574
+ * ```ts
8575
+ * const v = await cb.analytics.getVisitorByMember('019d8...', memberId)
8576
+ * console.log(`${v.visitor_count} 디바이스, 총 ${v.total_page_views} pv`)
8577
+ * ```
8578
+ */
8579
+ async getVisitorByMember(storageWebId, memberId) {
8580
+ const id = this.requireServerSideStorageId(storageWebId, "getVisitorByMember");
8581
+ return this.http.get(`/v1/storages/web/${id}/members/${memberId}/visitor`);
8582
+ }
8583
+ /**
8584
+ * 두 visitor 를 한 사람으로 통합하는 admin 작업 — JWT/cb_sk_ 인증 필요. (1.11+)
8585
+ *
8586
+ * 외부 인증 시스템에서 두 visitor 가 동일인임을 알았을 때 사용. source 의 자식 레코드
8587
+ * (page_views, daily, custom_events, experiment_assignments, heatmap_events,
8588
+ * session_recordings) 를 target 으로 옮기고 source visitor 는 삭제됨.
8589
+ *
8590
+ * @param request 둘 중 하나 필수: `target_visitor_uid` 또는 `target_member_id`.
8591
+ * @example
8592
+ * ```ts
8593
+ * await cb.analytics.mergeVisitors('019d8...', {
8594
+ * source_visitor_uid: 'old-uid',
8595
+ * target_member_id: '01a...',
8596
+ * })
8597
+ * ```
8598
+ */
8599
+ async mergeVisitors(storageWebId, request) {
8600
+ const id = this.requireServerSideStorageId(storageWebId, "mergeVisitors");
8601
+ return this.http.post(`/v1/storages/web/${id}/visitors/merge`, request);
8602
+ }
8543
8603
  /**
8544
8604
  * 조회 메서드 공통 가드 — Public Key 인증 SDK 인스턴스에서는 명확한 에러를 던진다.
8545
8605
  * 백엔드 라우트는 cb_pk_ 를 거부하므로 호출 자체를 막는 것이 디버깅에 유리.