connectbase-client 3.3.1 → 3.5.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
@@ -314,6 +314,18 @@ declare class SessionManager {
314
314
  touch(): void;
315
315
  /** 세션 강제 리셋 */
316
316
  reset(): void;
317
+ /**
318
+ * visitor_uid 를 새로 발급하고 세션도 함께 초기화.
319
+ *
320
+ * 사용 시점:
321
+ * - 사용자 로그아웃 (이전 사용자 활동이 다음 사용자에 attribution 되는 것 방지)
322
+ * - 다른 사용자 로그인 감지 (link-member 가 `VISITOR_LINKED_TO_OTHER_MEMBER` 응답)
323
+ *
324
+ * localStorage 의 `__cb_visitor_uid` 가 새 UUID 로 교체되며 sessionStorage 의
325
+ * 세션 키도 같이 비워진다. 이후의 모든 batch 는 새 visitor 로 기록되어 멤버 간
326
+ * 데이터 오염이 차단된다.
327
+ */
328
+ regenerateVisitorUid(): string;
317
329
  private ensureSession;
318
330
  private loadOrCreateVisitorUid;
319
331
  }
@@ -368,6 +380,11 @@ declare class AnalyticsAPI {
368
380
  * 백엔드 `link-member` 엔드포인트를 한 번 호출합니다 (1.11.0+). 호출 실패는
369
381
  * silent — 다음 batch 가 닿을 때 백엔드 자동 매핑이 동일하게 처리하므로 자가 복구.
370
382
  *
383
+ * **사용자 전환 자동 처리 (1.13.0+)**: 동일 브라우저에서 다른 사용자가 로그인해
384
+ * 백엔드가 `VISITOR_LINKED_TO_OTHER_MEMBER` 응답을 보내면, 큐를 비우고
385
+ * `visitor_uid` 를 새로 발급한 뒤 link-member 를 한 번 더 호출해 새 visitor 가
386
+ * 즉시 회원으로 기록되도록 자가 복구한다.
387
+ *
371
388
  * 산업 표준(GA4 User-ID, Mixpanel/PostHog `identify`) 과 동작 정합.
372
389
  *
373
390
  * @example
@@ -378,11 +395,30 @@ declare class AnalyticsAPI {
378
395
  * ```
379
396
  */
380
397
  identify(memberId: string): void;
398
+ /**
399
+ * 로그아웃 / 사용자 전환 시 호출. 익명 상태로 복귀하면서 visitor_uid 를 새로
400
+ * 발급해 다음 사용자의 활동이 이전 사용자에게 attribution 되는 데이터 오염을 차단.
401
+ *
402
+ * 동작:
403
+ * 1. memberId 를 null 로 설정 (이후 batch 는 익명으로 기록)
404
+ * 2. 큐에 쌓인 미전송 이벤트 폐기 (이전 visitor 로 가는 것을 막기 위함)
405
+ * 3. localStorage `__cb_visitor_uid` 새 UUID 로 교체 + sessionStorage 세션 키 정리
406
+ * 4. heatmap 큐도 함께 비움
407
+ *
408
+ * @example
409
+ * ```ts
410
+ * // 로그아웃 핸들러
411
+ * await cb.auth.signOut()
412
+ * cb.analytics.reset()
413
+ * ```
414
+ */
415
+ reset(): void;
381
416
  /**
382
417
  * 방문자 트래커에 현재 회원 ID 설정 (로그인/게스트 가입 시 호출).
383
418
  *
384
419
  * `identify()` 와 달리 즉시 backfill 호출은 하지 않습니다 — 단순히 이후 batch 의
385
- * `app_member_id` 값만 갱신. null 을 넘기면 익명 상태로 복귀 (로그아웃).
420
+ * `app_member_id` 값만 갱신. null 을 넘기면 익명 상태로 복귀 (로그아웃 시에는
421
+ * 데이터 오염 방지를 위해 `reset()` 를 권장).
386
422
  */
387
423
  setMemberId(memberId: string | null): void;
388
424
  /**
@@ -390,6 +426,9 @@ declare class AnalyticsAPI {
390
426
  *
391
427
  * - 첫 페이지뷰가 아직 백엔드에 닿기 전이면 visitor 가 없어 404. 무시 — 다음 batch 가
392
428
  * 가면 백엔드 BatchRecordVisit 가 자동 LinkMember 를 호출.
429
+ * - 다른 멤버에 이미 연결된 visitor 인 경우 (`VISITOR_LINKED_TO_OTHER_MEMBER`)
430
+ * visitor_uid 를 자동 재발급하고 link-member 를 한 번 더 호출 — 한 단계의 자가
431
+ * 복구로 끝나며 무한 재귀를 막기 위해 두 번째 시도는 응답을 더 보지 않는다.
393
432
  * - storage_web_id 가 init 안 됐거나 모든 종류의 네트워크 오류 — silent fail.
394
433
  */
395
434
  private linkMemberSilent;
@@ -510,7 +549,13 @@ declare class AnalyticsAPI {
510
549
  private createBaseEvent;
511
550
  private enqueue;
512
551
  private flushQueue;
513
- /** sendBeacon으로 동기 flush (beforeunload용) */
552
+ /**
553
+ * sendBeacon 으로 동기 flush (beforeunload 용).
554
+ *
555
+ * sendBeacon 은 일반 fetch 와 달리 User-Agent 헤더가 신뢰할 수 있지만, 백엔드 봇
556
+ * 탐지가 body 의 `user_agent` 필드 첫 번째 값만 보므로 여기서도 동일하게 채워
557
+ * 첫 방문이 unload 타이밍에 도달했을 때 봇으로 오판되는 것을 방지한다.
558
+ */
514
559
  private flushSync;
515
560
  private trackSessionStart;
516
561
  private startBatchTimer;
@@ -6507,9 +6552,21 @@ interface ListDocumentsResponse {
6507
6552
  documents: DocumentResponse[];
6508
6553
  total_count: number;
6509
6554
  }
6555
+ /**
6556
+ * 사용자 격리용 magic 토큰. `where` 값에 이 문자열을 넣으면 서버가
6557
+ * 인증된 AppMember ID 로 자동 치환한다 (클라이언트 변조 불가).
6558
+ *
6559
+ * AppMember JWT 가 함께 오지 않은 호출에서 사용하면 401.
6560
+ */
6561
+ declare const AUTH_MEMBER_ID_TOKEN: "$auth.member_id";
6510
6562
  /**
6511
6563
  * 검색 요청
6512
6564
  * @example { query: "환불 방법", top_k: 5, agentic: true }
6565
+ *
6566
+ * 사용자별 격리 (AppMember JWT 가 Authorization 헤더로 함께 올 때):
6567
+ * - 서버가 자동으로 본인 metadata.user_id 문서로 결과를 제한.
6568
+ * - `where` 로 추가 필터를 걸 수 있음. magic 토큰 사용 예:
6569
+ * `where: { 'metadata.tag': 'work' }`
6513
6570
  */
6514
6571
  interface KnowledgeSearchRequest {
6515
6572
  /** 검색 쿼리 (필수) */
@@ -6518,6 +6575,12 @@ interface KnowledgeSearchRequest {
6518
6575
  top_k?: number;
6519
6576
  /** Agentic Search 활성화 — AI 가 쿼리를 자동 생성하여 다중 검색 수행 */
6520
6577
  agentic?: boolean;
6578
+ /**
6579
+ * metadata 기반 필터 (옵셔널). 키 형식 `metadata.<path>` 또는 raw key.
6580
+ * 값에 `AUTH_MEMBER_ID_TOKEN` 사용 시 서버가 인증된 AppMember ID 로 치환.
6581
+ * AppMember JWT 컨텍스트가 있으면 서버가 추가로 metadata.user_id 강제 필터를 AND.
6582
+ */
6583
+ where?: Record<string, unknown>;
6521
6584
  }
6522
6585
  interface KnowledgeSearchResult {
6523
6586
  chunk_id: string;
@@ -6541,6 +6604,13 @@ interface KnowledgeSearchResponse {
6541
6604
  * AI 데이터베이스를 위한 문서 저장 및 검색 API.
6542
6605
  * 문서를 업로드하면 자동으로 청킹되어 키워드 기반 검색이 가능합니다.
6543
6606
  *
6607
+ * ## 사용자별 격리 (다중 사용자 RAG 시나리오)
6608
+ *
6609
+ * `Authorization: Bearer <appmember-jwt>` 를 함께 보내면 서버가:
6610
+ * - 검색 결과를 본인 문서 (metadata.user_id == member_id) 로 제한
6611
+ * - addDocument 시 metadata.user_id 자동 태깅
6612
+ * - listDocuments / deleteDocument 도 본인 자료만 노출
6613
+ *
6544
6614
  * @example
6545
6615
  * ```typescript
6546
6616
  * const cb = new ConnectBase({ publicKey: 'your-public-key' })
@@ -6557,6 +6627,12 @@ interface KnowledgeSearchResponse {
6557
6627
  * query: '환불 정책',
6558
6628
  * top_k: 5
6559
6629
  * })
6630
+ *
6631
+ * // 사용자별 격리 + 추가 필터 (AppMember JWT 가 같이 와야 함)
6632
+ * const results = await cb.knowledge.search('kb-id', {
6633
+ * query: '내 메모',
6634
+ * where: { 'metadata.tag': 'work' },
6635
+ * })
6560
6636
  * ```
6561
6637
  */
6562
6638
  declare class KnowledgeAPI {
@@ -7445,4 +7521,4 @@ declare class ConnectBase {
7445
7521
  updateConfig(config: Partial<ConnectBaseConfig>): void;
7446
7522
  }
7447
7523
 
7448
- 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, EndpointAPI, type EndpointCallInit, 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 GameConfig, GameConfigAPI, type GameConfigPatch, 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 LeaderboardListResponse, type LeaderboardScoreEntry, 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 MatchqueueListResponse, type MatchqueueTicket, 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 PollUntilOptions, 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 ScriptDetailResponse, type ScriptListResponse, type ScriptMeta, type ScriptVersion, type ScriptVersionListResponse, 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 };
7524
+ export { AIAPI, type AIChatRequest, type AIChatResponse, type AIMessage, type AISource, type AIStreamChunk, type AITool, type AIToolCall, type AIToolEvent, AUTH_MEMBER_ID_TOKEN, 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, EndpointAPI, type EndpointCallInit, 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 GameConfig, GameConfigAPI, type GameConfigPatch, 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 LeaderboardListResponse, type LeaderboardScoreEntry, 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 MatchqueueListResponse, type MatchqueueTicket, 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 PollUntilOptions, 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 ScriptDetailResponse, type ScriptListResponse, type ScriptMeta, type ScriptVersion, type ScriptVersionListResponse, 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
@@ -314,6 +314,18 @@ declare class SessionManager {
314
314
  touch(): void;
315
315
  /** 세션 강제 리셋 */
316
316
  reset(): void;
317
+ /**
318
+ * visitor_uid 를 새로 발급하고 세션도 함께 초기화.
319
+ *
320
+ * 사용 시점:
321
+ * - 사용자 로그아웃 (이전 사용자 활동이 다음 사용자에 attribution 되는 것 방지)
322
+ * - 다른 사용자 로그인 감지 (link-member 가 `VISITOR_LINKED_TO_OTHER_MEMBER` 응답)
323
+ *
324
+ * localStorage 의 `__cb_visitor_uid` 가 새 UUID 로 교체되며 sessionStorage 의
325
+ * 세션 키도 같이 비워진다. 이후의 모든 batch 는 새 visitor 로 기록되어 멤버 간
326
+ * 데이터 오염이 차단된다.
327
+ */
328
+ regenerateVisitorUid(): string;
317
329
  private ensureSession;
318
330
  private loadOrCreateVisitorUid;
319
331
  }
@@ -368,6 +380,11 @@ declare class AnalyticsAPI {
368
380
  * 백엔드 `link-member` 엔드포인트를 한 번 호출합니다 (1.11.0+). 호출 실패는
369
381
  * silent — 다음 batch 가 닿을 때 백엔드 자동 매핑이 동일하게 처리하므로 자가 복구.
370
382
  *
383
+ * **사용자 전환 자동 처리 (1.13.0+)**: 동일 브라우저에서 다른 사용자가 로그인해
384
+ * 백엔드가 `VISITOR_LINKED_TO_OTHER_MEMBER` 응답을 보내면, 큐를 비우고
385
+ * `visitor_uid` 를 새로 발급한 뒤 link-member 를 한 번 더 호출해 새 visitor 가
386
+ * 즉시 회원으로 기록되도록 자가 복구한다.
387
+ *
371
388
  * 산업 표준(GA4 User-ID, Mixpanel/PostHog `identify`) 과 동작 정합.
372
389
  *
373
390
  * @example
@@ -378,11 +395,30 @@ declare class AnalyticsAPI {
378
395
  * ```
379
396
  */
380
397
  identify(memberId: string): void;
398
+ /**
399
+ * 로그아웃 / 사용자 전환 시 호출. 익명 상태로 복귀하면서 visitor_uid 를 새로
400
+ * 발급해 다음 사용자의 활동이 이전 사용자에게 attribution 되는 데이터 오염을 차단.
401
+ *
402
+ * 동작:
403
+ * 1. memberId 를 null 로 설정 (이후 batch 는 익명으로 기록)
404
+ * 2. 큐에 쌓인 미전송 이벤트 폐기 (이전 visitor 로 가는 것을 막기 위함)
405
+ * 3. localStorage `__cb_visitor_uid` 새 UUID 로 교체 + sessionStorage 세션 키 정리
406
+ * 4. heatmap 큐도 함께 비움
407
+ *
408
+ * @example
409
+ * ```ts
410
+ * // 로그아웃 핸들러
411
+ * await cb.auth.signOut()
412
+ * cb.analytics.reset()
413
+ * ```
414
+ */
415
+ reset(): void;
381
416
  /**
382
417
  * 방문자 트래커에 현재 회원 ID 설정 (로그인/게스트 가입 시 호출).
383
418
  *
384
419
  * `identify()` 와 달리 즉시 backfill 호출은 하지 않습니다 — 단순히 이후 batch 의
385
- * `app_member_id` 값만 갱신. null 을 넘기면 익명 상태로 복귀 (로그아웃).
420
+ * `app_member_id` 값만 갱신. null 을 넘기면 익명 상태로 복귀 (로그아웃 시에는
421
+ * 데이터 오염 방지를 위해 `reset()` 를 권장).
386
422
  */
387
423
  setMemberId(memberId: string | null): void;
388
424
  /**
@@ -390,6 +426,9 @@ declare class AnalyticsAPI {
390
426
  *
391
427
  * - 첫 페이지뷰가 아직 백엔드에 닿기 전이면 visitor 가 없어 404. 무시 — 다음 batch 가
392
428
  * 가면 백엔드 BatchRecordVisit 가 자동 LinkMember 를 호출.
429
+ * - 다른 멤버에 이미 연결된 visitor 인 경우 (`VISITOR_LINKED_TO_OTHER_MEMBER`)
430
+ * visitor_uid 를 자동 재발급하고 link-member 를 한 번 더 호출 — 한 단계의 자가
431
+ * 복구로 끝나며 무한 재귀를 막기 위해 두 번째 시도는 응답을 더 보지 않는다.
393
432
  * - storage_web_id 가 init 안 됐거나 모든 종류의 네트워크 오류 — silent fail.
394
433
  */
395
434
  private linkMemberSilent;
@@ -510,7 +549,13 @@ declare class AnalyticsAPI {
510
549
  private createBaseEvent;
511
550
  private enqueue;
512
551
  private flushQueue;
513
- /** sendBeacon으로 동기 flush (beforeunload용) */
552
+ /**
553
+ * sendBeacon 으로 동기 flush (beforeunload 용).
554
+ *
555
+ * sendBeacon 은 일반 fetch 와 달리 User-Agent 헤더가 신뢰할 수 있지만, 백엔드 봇
556
+ * 탐지가 body 의 `user_agent` 필드 첫 번째 값만 보므로 여기서도 동일하게 채워
557
+ * 첫 방문이 unload 타이밍에 도달했을 때 봇으로 오판되는 것을 방지한다.
558
+ */
514
559
  private flushSync;
515
560
  private trackSessionStart;
516
561
  private startBatchTimer;
@@ -6507,9 +6552,21 @@ interface ListDocumentsResponse {
6507
6552
  documents: DocumentResponse[];
6508
6553
  total_count: number;
6509
6554
  }
6555
+ /**
6556
+ * 사용자 격리용 magic 토큰. `where` 값에 이 문자열을 넣으면 서버가
6557
+ * 인증된 AppMember ID 로 자동 치환한다 (클라이언트 변조 불가).
6558
+ *
6559
+ * AppMember JWT 가 함께 오지 않은 호출에서 사용하면 401.
6560
+ */
6561
+ declare const AUTH_MEMBER_ID_TOKEN: "$auth.member_id";
6510
6562
  /**
6511
6563
  * 검색 요청
6512
6564
  * @example { query: "환불 방법", top_k: 5, agentic: true }
6565
+ *
6566
+ * 사용자별 격리 (AppMember JWT 가 Authorization 헤더로 함께 올 때):
6567
+ * - 서버가 자동으로 본인 metadata.user_id 문서로 결과를 제한.
6568
+ * - `where` 로 추가 필터를 걸 수 있음. magic 토큰 사용 예:
6569
+ * `where: { 'metadata.tag': 'work' }`
6513
6570
  */
6514
6571
  interface KnowledgeSearchRequest {
6515
6572
  /** 검색 쿼리 (필수) */
@@ -6518,6 +6575,12 @@ interface KnowledgeSearchRequest {
6518
6575
  top_k?: number;
6519
6576
  /** Agentic Search 활성화 — AI 가 쿼리를 자동 생성하여 다중 검색 수행 */
6520
6577
  agentic?: boolean;
6578
+ /**
6579
+ * metadata 기반 필터 (옵셔널). 키 형식 `metadata.<path>` 또는 raw key.
6580
+ * 값에 `AUTH_MEMBER_ID_TOKEN` 사용 시 서버가 인증된 AppMember ID 로 치환.
6581
+ * AppMember JWT 컨텍스트가 있으면 서버가 추가로 metadata.user_id 강제 필터를 AND.
6582
+ */
6583
+ where?: Record<string, unknown>;
6521
6584
  }
6522
6585
  interface KnowledgeSearchResult {
6523
6586
  chunk_id: string;
@@ -6541,6 +6604,13 @@ interface KnowledgeSearchResponse {
6541
6604
  * AI 데이터베이스를 위한 문서 저장 및 검색 API.
6542
6605
  * 문서를 업로드하면 자동으로 청킹되어 키워드 기반 검색이 가능합니다.
6543
6606
  *
6607
+ * ## 사용자별 격리 (다중 사용자 RAG 시나리오)
6608
+ *
6609
+ * `Authorization: Bearer <appmember-jwt>` 를 함께 보내면 서버가:
6610
+ * - 검색 결과를 본인 문서 (metadata.user_id == member_id) 로 제한
6611
+ * - addDocument 시 metadata.user_id 자동 태깅
6612
+ * - listDocuments / deleteDocument 도 본인 자료만 노출
6613
+ *
6544
6614
  * @example
6545
6615
  * ```typescript
6546
6616
  * const cb = new ConnectBase({ publicKey: 'your-public-key' })
@@ -6557,6 +6627,12 @@ interface KnowledgeSearchResponse {
6557
6627
  * query: '환불 정책',
6558
6628
  * top_k: 5
6559
6629
  * })
6630
+ *
6631
+ * // 사용자별 격리 + 추가 필터 (AppMember JWT 가 같이 와야 함)
6632
+ * const results = await cb.knowledge.search('kb-id', {
6633
+ * query: '내 메모',
6634
+ * where: { 'metadata.tag': 'work' },
6635
+ * })
6560
6636
  * ```
6561
6637
  */
6562
6638
  declare class KnowledgeAPI {
@@ -7445,4 +7521,4 @@ declare class ConnectBase {
7445
7521
  updateConfig(config: Partial<ConnectBaseConfig>): void;
7446
7522
  }
7447
7523
 
7448
- 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, EndpointAPI, type EndpointCallInit, 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 GameConfig, GameConfigAPI, type GameConfigPatch, 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 LeaderboardListResponse, type LeaderboardScoreEntry, 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 MatchqueueListResponse, type MatchqueueTicket, 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 PollUntilOptions, 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 ScriptDetailResponse, type ScriptListResponse, type ScriptMeta, type ScriptVersion, type ScriptVersionListResponse, 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 };
7524
+ export { AIAPI, type AIChatRequest, type AIChatResponse, type AIMessage, type AISource, type AIStreamChunk, type AITool, type AIToolCall, type AIToolEvent, AUTH_MEMBER_ID_TOKEN, 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, EndpointAPI, type EndpointCallInit, 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 GameConfig, GameConfigAPI, type GameConfigPatch, 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 LeaderboardListResponse, type LeaderboardScoreEntry, 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 MatchqueueListResponse, type MatchqueueTicket, 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 PollUntilOptions, 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 ScriptDetailResponse, type ScriptListResponse, type ScriptMeta, type ScriptVersion, type ScriptVersionListResponse, 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
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  AIAPI: () => AIAPI,
24
+ AUTH_MEMBER_ID_TOKEN: () => AUTH_MEMBER_ID_TOKEN,
24
25
  AdsAPI: () => AdsAPI,
25
26
  ApiError: () => ApiError,
26
27
  AuthError: () => AuthError,
@@ -8034,6 +8035,29 @@ var SessionManager = class {
8034
8035
  } catch {
8035
8036
  }
8036
8037
  }
8038
+ /**
8039
+ * visitor_uid 를 새로 발급하고 세션도 함께 초기화.
8040
+ *
8041
+ * 사용 시점:
8042
+ * - 사용자 로그아웃 (이전 사용자 활동이 다음 사용자에 attribution 되는 것 방지)
8043
+ * - 다른 사용자 로그인 감지 (link-member 가 `VISITOR_LINKED_TO_OTHER_MEMBER` 응답)
8044
+ *
8045
+ * localStorage 의 `__cb_visitor_uid` 가 새 UUID 로 교체되며 sessionStorage 의
8046
+ * 세션 키도 같이 비워진다. 이후의 모든 batch 는 새 visitor 로 기록되어 멤버 간
8047
+ * 데이터 오염이 차단된다.
8048
+ */
8049
+ regenerateVisitorUid() {
8050
+ const newUid = generateId();
8051
+ this._visitorUid = newUid;
8052
+ try {
8053
+ if (typeof localStorage !== "undefined") {
8054
+ localStorage.setItem(VISITOR_KEY, newUid);
8055
+ }
8056
+ } catch {
8057
+ }
8058
+ this.reset();
8059
+ return newUid;
8060
+ }
8037
8061
  ensureSession() {
8038
8062
  const now = Date.now();
8039
8063
  if (!this._sessionId) {
@@ -8239,6 +8263,11 @@ var AnalyticsAPI = class {
8239
8263
  * 백엔드 `link-member` 엔드포인트를 한 번 호출합니다 (1.11.0+). 호출 실패는
8240
8264
  * silent — 다음 batch 가 닿을 때 백엔드 자동 매핑이 동일하게 처리하므로 자가 복구.
8241
8265
  *
8266
+ * **사용자 전환 자동 처리 (1.13.0+)**: 동일 브라우저에서 다른 사용자가 로그인해
8267
+ * 백엔드가 `VISITOR_LINKED_TO_OTHER_MEMBER` 응답을 보내면, 큐를 비우고
8268
+ * `visitor_uid` 를 새로 발급한 뒤 link-member 를 한 번 더 호출해 새 visitor 가
8269
+ * 즉시 회원으로 기록되도록 자가 복구한다.
8270
+ *
8242
8271
  * 산업 표준(GA4 User-ID, Mixpanel/PostHog `identify`) 과 동작 정합.
8243
8272
  *
8244
8273
  * @example
@@ -8249,14 +8278,42 @@ var AnalyticsAPI = class {
8249
8278
  * ```
8250
8279
  */
8251
8280
  identify(memberId) {
8281
+ if (this.memberId && this.memberId !== memberId) {
8282
+ this.reset();
8283
+ }
8252
8284
  this.setMemberId(memberId);
8253
8285
  this.linkMemberSilent(memberId);
8254
8286
  }
8287
+ /**
8288
+ * 로그아웃 / 사용자 전환 시 호출. 익명 상태로 복귀하면서 visitor_uid 를 새로
8289
+ * 발급해 다음 사용자의 활동이 이전 사용자에게 attribution 되는 데이터 오염을 차단.
8290
+ *
8291
+ * 동작:
8292
+ * 1. memberId 를 null 로 설정 (이후 batch 는 익명으로 기록)
8293
+ * 2. 큐에 쌓인 미전송 이벤트 폐기 (이전 visitor 로 가는 것을 막기 위함)
8294
+ * 3. localStorage `__cb_visitor_uid` 새 UUID 로 교체 + sessionStorage 세션 키 정리
8295
+ * 4. heatmap 큐도 함께 비움
8296
+ *
8297
+ * @example
8298
+ * ```ts
8299
+ * // 로그아웃 핸들러
8300
+ * await cb.auth.signOut()
8301
+ * cb.analytics.reset()
8302
+ * ```
8303
+ */
8304
+ reset() {
8305
+ this.setMemberId(null);
8306
+ this.eventQueue = [];
8307
+ this.heatmapQueue = [];
8308
+ const newUid = this.session.regenerateVisitorUid();
8309
+ this.log("Analytics reset", { newVisitorUid: newUid });
8310
+ }
8255
8311
  /**
8256
8312
  * 방문자 트래커에 현재 회원 ID 설정 (로그인/게스트 가입 시 호출).
8257
8313
  *
8258
8314
  * `identify()` 와 달리 즉시 backfill 호출은 하지 않습니다 — 단순히 이후 batch 의
8259
- * `app_member_id` 값만 갱신. null 을 넘기면 익명 상태로 복귀 (로그아웃).
8315
+ * `app_member_id` 값만 갱신. null 을 넘기면 익명 상태로 복귀 (로그아웃 시에는
8316
+ * 데이터 오염 방지를 위해 `reset()` 를 권장).
8260
8317
  */
8261
8318
  setMemberId(memberId) {
8262
8319
  this.memberId = memberId || null;
@@ -8278,9 +8335,12 @@ var AnalyticsAPI = class {
8278
8335
  *
8279
8336
  * - 첫 페이지뷰가 아직 백엔드에 닿기 전이면 visitor 가 없어 404. 무시 — 다음 batch 가
8280
8337
  * 가면 백엔드 BatchRecordVisit 가 자동 LinkMember 를 호출.
8338
+ * - 다른 멤버에 이미 연결된 visitor 인 경우 (`VISITOR_LINKED_TO_OTHER_MEMBER`)
8339
+ * visitor_uid 를 자동 재발급하고 link-member 를 한 번 더 호출 — 한 단계의 자가
8340
+ * 복구로 끝나며 무한 재귀를 막기 위해 두 번째 시도는 응답을 더 보지 않는다.
8281
8341
  * - storage_web_id 가 init 안 됐거나 모든 종류의 네트워크 오류 — silent fail.
8282
8342
  */
8283
- linkMemberSilent(memberId) {
8343
+ linkMemberSilent(memberId, isRetry = false) {
8284
8344
  if (!this.storageWebId) return;
8285
8345
  const prefix = this.http.hasPublicKey() ? "/v1/public" : "/v1";
8286
8346
  this.http.post(
@@ -8289,7 +8349,18 @@ var AnalyticsAPI = class {
8289
8349
  visitor_uid: this.session.visitorUid,
8290
8350
  app_member_id: memberId
8291
8351
  }
8292
- ).catch(() => {
8352
+ ).then((resp) => {
8353
+ if (!resp) return;
8354
+ this.log("link-member response", resp);
8355
+ if (!isRetry && resp.success === false && resp.code === "VISITOR_LINKED_TO_OTHER_MEMBER") {
8356
+ this.log("user-switch detected \u2014 regenerating visitor_uid");
8357
+ this.eventQueue = [];
8358
+ this.heatmapQueue = [];
8359
+ this.session.regenerateVisitorUid();
8360
+ this.linkMemberSilent(memberId, true);
8361
+ }
8362
+ }).catch((err) => {
8363
+ this.log("link-member silent fail", err);
8293
8364
  });
8294
8365
  }
8295
8366
  /** 현재 설정된 회원 ID 조회 (미설정 시 null) */
@@ -8523,6 +8594,7 @@ var AnalyticsAPI = class {
8523
8594
  createBaseEvent(type) {
8524
8595
  return {
8525
8596
  type,
8597
+ event_id: generateId(),
8526
8598
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
8527
8599
  session_id: this.session.sessionId,
8528
8600
  visitor_uid: this.session.visitorUid
@@ -8545,6 +8617,7 @@ var AnalyticsAPI = class {
8545
8617
  visitor_uid: this.session.visitorUid,
8546
8618
  ...this.memberId ? { app_member_id: this.memberId } : {},
8547
8619
  events: events.map((e) => ({
8620
+ event_id: e.event_id,
8548
8621
  timestamp: e.timestamp,
8549
8622
  page_path: e.page_path || "",
8550
8623
  page_url: e.page_url || "",
@@ -8574,7 +8647,13 @@ var AnalyticsAPI = class {
8574
8647
  this.log("Flush failed", err);
8575
8648
  }
8576
8649
  }
8577
- /** sendBeacon으로 동기 flush (beforeunload용) */
8650
+ /**
8651
+ * sendBeacon 으로 동기 flush (beforeunload 용).
8652
+ *
8653
+ * sendBeacon 은 일반 fetch 와 달리 User-Agent 헤더가 신뢰할 수 있지만, 백엔드 봇
8654
+ * 탐지가 body 의 `user_agent` 필드 첫 번째 값만 보므로 여기서도 동일하게 채워
8655
+ * 첫 방문이 unload 타이밍에 도달했을 때 봇으로 오판되는 것을 방지한다.
8656
+ */
8578
8657
  flushSync() {
8579
8658
  if (this.eventQueue.length === 0 || !this.storageWebId) return;
8580
8659
  if (typeof navigator === "undefined" || !navigator.sendBeacon) return;
@@ -8582,20 +8661,30 @@ var AnalyticsAPI = class {
8582
8661
  const prefix = this.http.hasPublicKey() ? "/v1/public" : "/v1";
8583
8662
  const baseUrl = this.http.getBaseUrl();
8584
8663
  const url = `${baseUrl}${prefix}/storages/web/${this.storageWebId}/visitors/batch`;
8664
+ const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
8585
8665
  const body = JSON.stringify({
8586
8666
  visitor_uid: this.session.visitorUid,
8587
8667
  ...this.memberId ? { app_member_id: this.memberId } : {},
8588
8668
  events: events.map((e) => ({
8669
+ event_id: e.event_id,
8589
8670
  timestamp: e.timestamp,
8590
8671
  page_path: e.page_path || "",
8591
8672
  page_url: e.page_url || "",
8592
8673
  page_title: e.page_title || "",
8593
8674
  referrer: e.referrer || "",
8675
+ user_agent: ua,
8676
+ screen_width: e.screen_width || 0,
8677
+ screen_height: e.screen_height || 0,
8594
8678
  session_id: e.session_id,
8595
8679
  session_start: e.type === "session_start",
8596
8680
  is_page_view: e.type === "page_view",
8597
8681
  event_name: e.event_name,
8598
- event_properties: e.event_properties
8682
+ event_properties: e.event_properties,
8683
+ utm_source: e.utm_source,
8684
+ utm_medium: e.utm_medium,
8685
+ utm_campaign: e.utm_campaign,
8686
+ utm_content: e.utm_content,
8687
+ utm_term: e.utm_term
8599
8688
  }))
8600
8689
  });
8601
8690
  try {
@@ -8767,6 +8856,9 @@ var AnalyticsAPI = class {
8767
8856
  }
8768
8857
  };
8769
8858
 
8859
+ // src/types/knowledge.ts
8860
+ var AUTH_MEMBER_ID_TOKEN = "$auth.member_id";
8861
+
8770
8862
  // src/api/game-transport.ts
8771
8863
  var WebTransportTransport = class {
8772
8864
  constructor(config, onMessage, onClose, onError) {
@@ -9476,6 +9568,7 @@ var index_default = ConnectBase;
9476
9568
  // Annotate the CommonJS export names for ESM import in node:
9477
9569
  0 && (module.exports = {
9478
9570
  AIAPI,
9571
+ AUTH_MEMBER_ID_TOKEN,
9479
9572
  AdsAPI,
9480
9573
  ApiError,
9481
9574
  AuthError,