connectbase-client 6.16.0 → 6.17.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/CHANGELOG.md CHANGED
@@ -3,6 +3,14 @@
3
3
  본 SDK 의 모든 주요 변경사항을 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/) 형식으로 기록합니다.
4
4
  버전은 [Semantic Versioning](https://semver.org/lang/ko/) 을 따릅니다.
5
5
 
6
+ ## [6.17.0] - 2026-11-14
7
+
8
+ ### Removed — `TriggerHandlerType` 의 `"workflow"`
9
+
10
+ - 플랫폼에서 워크플로우 기능이 제거됐다. DB 트리거의 핸들러 타입은 `"function"`, `"webhook"`, `"inline"` 세 가지다.
11
+ 서버는 `"workflow"` 핸들러를 받지 않으므로(생성 요청 400) 타입에서도 뺐다. 운영에 이 값을 쓰는 트리거는 없었다.
12
+ - `handler_type: "workflow"` 를 넘기던 코드는 타입 오류가 난다. 같은 일을 하는 함수를 만들어 `"function"` 으로 연결한다.
13
+
6
14
  ## [6.16.0] - 2026-11-12
7
15
 
8
16
  ### Added — `cb.webrtc.getSFUToken()` (SFU 방 입장 토큰)
package/dist/cli.js CHANGED
@@ -170,7 +170,7 @@ function handleTunnelError(msg, appId, localPort) {
170
170
  }
171
171
 
172
172
  // src/cli.ts
173
- var VERSION = "6.16.0" ? "6.16.0" : getPackageVersion();
173
+ var VERSION = "6.17.0" ? "6.17.0" : getPackageVersion();
174
174
  var DEFAULT_BASE_URL = "https://api.connectbase.world";
175
175
  var colors = {
176
176
  reset: "\x1B[0m",
@@ -1,6 +1,6 @@
1
1
  "use strict";var ConnectBaseModule=(()=>{var qe=Object.defineProperty;var Dt=Object.getOwnPropertyDescriptor;var Lt=Object.getOwnPropertyNames;var qt=Object.prototype.hasOwnProperty;var Nt=(n,e)=>{for(var t in e)qe(n,t,{get:e[t],enumerable:!0})},Bt=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Lt(e))!qt.call(n,r)&&r!==t&&qe(n,r,{get:()=>e[r],enumerable:!(s=Dt(e,r))||s.enumerable});return n};var Ht=n=>Bt(qe({},"__esModule",{value:!0}),n);var Ks={};Nt(Ks,{AIAPI:()=>N,AIError:()=>T,AUTH_MEMBER_ID_TOKEN:()=>Ls,AdsAPI:()=>L,ApiError:()=>b,AppMembersAPI:()=>B,AuthError:()=>I,ConnectBase:()=>Le,EndpointAPI:()=>G,GameAPI:()=>W,GameConfigAPI:()=>K,GameError:()=>w,GameRoom:()=>Z,GameRoomTransport:()=>De,NativeAPI:()=>V,OrganizationsAPI:()=>z,RealtimeConnectionError:()=>R,RealtimeRequestError:()=>q,RolesAPI:()=>j,SessionManager:()=>X,VideoProcessingError:()=>J,WsTicketError:()=>C,default:()=>Gs,detectInAppBrowser:()=>re,escapeToExternalBrowser:()=>Re,isWebTransportSupported:()=>Qe,toAIError:()=>M,toCreateRoomWire:()=>ee});var L=class{constructor(e){this.http=e}getPublicPrefix(){return this.http.hasPublicKey()?"/v1/public":"/v1"}async getConnectionStatus(){let e=this.getPublicPrefix();return this.http.get(`${e}/ads/connection`)}async getReport(e,t){let s=this.getPublicPrefix(),r=new URLSearchParams;e&&r.set("start",e),t&&r.set("end",t);let i=r.toString();return this.http.get(`${s}/ads/reports${i?`?${i}`:""}`)}async getReportSummary(){let e=this.getPublicPrefix();return this.http.get(`${e}/ads/reports/summary`)}async getAdMobReport(e,t){let s=this.getPublicPrefix(),r=new URLSearchParams;e&&r.set("start",e),t&&r.set("end",t);let i=r.toString();return this.http.get(`${s}/ads/admob/reports${i?`?${i}`:""}`)}async getAdMobReportSummary(){let e=this.getPublicPrefix();return this.http.get(`${e}/ads/admob/reports/summary`)}};var b=class extends Error{constructor(t,s,r,i){super(s);this.statusCode=t;this.name="ApiError",this.code=r,this.details=i}toJSON(){return{name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,details:this.details}}},T=class extends Error{constructor(e){super(e.message||e.code||"AI request failed"),this.name="AIError",this.code=e.code||"stream_failed",this.retryable=e.retryable??Ft(this.code),this.status=e.status,this.provider=e.provider,this.model=e.model,this.retryAfter=e.retryAfter,this.detailCode=e.detailCode,this.sessionId=e.sessionId}toJSON(){return{name:this.name,code:this.code,message:this.message,retryable:this.retryable,status:this.status,provider:this.provider,model:this.model,retryAfter:this.retryAfter,detailCode:this.detailCode,sessionId:this.sessionId}}};function Ft(n){return n==="provider_timeout"||n==="service_unavailable"||n==="rate_limit_exceeded"||n==="stream_failed"}function M(n,e){if(n instanceof T)return n;let t=typeof n=="object"&&n!==null?n:{},s=u=>typeof u=="string"&&u!==""?u:void 0,r=u=>typeof u=="number"&&Number.isFinite(u)?u:void 0,i=s(t.error)??s(t.code)??e?.code,o=s(t.detail_code)??s(t.detailCode)??s(t.code),a=i??"stream_failed",c=o&&o!==a?o:void 0,l=s(t.message)??(n instanceof Error?n.message:void 0)??e?.message??a;return new T({code:a,message:l,retryable:typeof t.retryable=="boolean"?t.retryable:void 0,status:r(t.status)??r(t.statusCode)??e?.status,provider:s(t.provider),model:s(t.model),retryAfter:r(t.retry_after_seconds)??r(t.retryAfter),detailCode:c,sessionId:s(t.session_id)??s(t.sessionId)??e?.sessionId})}var I=class extends Error{constructor(e){super(e),this.name="AuthError"}},w=class extends Error{constructor(e){super(e.message||e.code||"GameError"),this.name="GameError",this.code=e.code||"UNKNOWN",this.phase=e.phase,this.feature=e.feature,this.roomId=e.roomId,this.scriptId=e.scriptId,this.originClientId=e.originClientId,this.requested=e.requested,this.available=e.available}toJSON(){return{name:this.name,code:this.code,message:this.message,phase:this.phase,feature:this.feature,roomId:this.roomId,scriptId:this.scriptId,originClientId:this.originClientId,requested:this.requested,available:this.available}}},R=class extends Error{constructor(e){super(e.message||e.code||"Realtime connection rejected"),this.name="RealtimeConnectionError",this.code=e.code||"unknown",this.closeCode=e.closeCode,this.retryable=e.retryable??Gt(this.code,e.closeCode),this.details=e.details,this.retryAfterMs=e.retryAfterMs}toJSON(){return{name:this.name,code:this.code,message:this.message,closeCode:this.closeCode,retryable:this.retryable,details:this.details,retryAfterMs:this.retryAfterMs}}};function Gt(n,e){return e===4429||e===4500||e===4503||n==="connection_limit_exceeded"||n==="rate_limit_exceeded"||n==="server_at_capacity"||n==="rate_limited"||n==="auth_unavailable"||n==="internal_error"||n==="invalid_ws_ticket"||n==="ws_ticket_unavailable"}var q=class extends Error{constructor(e){super(e.message||e.code||"Realtime request failed"),this.name="RealtimeRequestError",this.code=e.code||"unknown",this.category=e.category}toJSON(){return{name:this.name,code:this.code,message:this.message,category:this.category}}};function Kt(n){let e={provider_timeout:504,gateway_timeout:504,bad_gateway:502,service_unavailable:503,rate_limit_exceeded:429,quota_exceeded:429,invalid_request:400,config_error:400,unauthorized:401},t={};return n.provider&&(t.provider=n.provider),n.model&&(t.model=n.model),n.retryAfter!==void 0&&(t.retry_after_seconds=n.retryAfter),new b(n.status??e[n.code]??500,n.message,n.detailCode||n.code,Object.keys(t).length>0?t:void 0)}var Wt=9e4,Vt=3e5,zt=1e4,N=class{constructor(e){this.http=e}async chat(e,t){let s=Math.min(t?.timeout??this.http.requestTimeoutMs??Wt,Vt),r=new AbortController,i=!1,o=setTimeout(()=>{i=!0,r.abort()},s+zt),a=t?.signal,c=()=>r.abort();a&&(a.aborted?r.abort():a.addEventListener("abort",c,{once:!0}));let l={content:"",provider:"",model:""},u,d=!1,h="";try{await this.runStream({...e,timeoutSeconds:Math.ceil(s/1e3)},{onToken:p=>{l.content+=p},onReasoning:p=>{h+=p},onSources:p=>{l.sources=p},onError:p=>{u=p},onAbort:()=>{d=!0}},{signal:r.signal},{onHttpError:async p=>{throw await this.http.buildApiError(p)},onResultMeta:p=>{p.finishReason&&(l.finishReason=p.finishReason),p.toolCalls?.length&&(l.toolCalls=p.toolCalls),p.usage&&(l.usage=p.usage),p.provider&&(l.provider=p.provider),p.model&&(l.model=p.model)}})}finally{clearTimeout(o),a?.removeEventListener("abort",c)}if(u)throw Kt(u);if(d)throw i?new b(504,`AI \uC751\uB2F5\uC774 ${Math.round(s/1e3)}\uCD08 \uC608\uC0B0 \uC548\uC5D0 \uB05D\uB098\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4`,"provider_timeout"):new DOMException("The operation was aborted.","AbortError");if(u)throw u;return h&&(l.reasoning=h),l}async chatStream(e,t,s){return this.runStream(e,t,s)}async runStream(e,t,s,r){let i=s?.signal,o=c=>i?.aborted===!0||c instanceof DOMException&&c.name==="AbortError"||typeof c=="object"&&c!==null&&c.name==="AbortError",a;try{let c=await this.http.fetchRaw("/v1/public/ai/chat/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:i});if(!c.ok){r?.onHttpError&&await r.onHttpError(c);let d=await c.json().catch(()=>({error:"stream_failed"}));t.onError?.(M(d,{message:"Stream request failed",status:c.status}));return}if(a=c.body?.getReader(),!a){t.onError?.(new T({code:"stream_failed",message:"ReadableStream not supported",retryable:!1}));return}let l=new TextDecoder,u="";for(;;){let{done:d,value:h}=await a.read();if(d)break;u+=l.decode(h,{stream:!0});let p=u.split(`
2
2
  `);u=p.pop()||"";for(let f of p){if(!f.startsWith("data: "))continue;let m=f.slice(6).trim();if(m==="[DONE]"){t.onDone?.();return}try{let g=JSON.parse(m);if(g.error){t.onError?.(M(g));return}if(g.type==="sources"&&g.sources){t.onSources?.(g.sources);continue}if(g.type==="tool_start"||g.type==="tool_end"){t.onToolEvent?.({type:g.type,name:g.name,toolCallId:g.toolCallId,arguments:g.arguments,result:g.result,success:g.success,durationMs:g.durationMs});continue}if(g.type==="searching"){g.searching&&t.onSearching?.(g.searching);continue}if(g.type==="heartbeat")continue;if((g.finishReason||g.toolCalls?.length||g.usage||g.provider||g.model)&&r?.onResultMeta?.(g),g.reasoning&&t.onReasoning?.(g.reasoning),g.content&&t.onToken?.(g.content),g.done){t.onDone?.();return}}catch{}}}}catch(c){if(o(c)){t.onAbort?.();return}throw c}finally{if(a)try{await a.cancel()}catch{}}}};var jt=new Set(["access_token","refresh_token","id_token","token","auth_token","session_token","jwt","client_secret","secret_key","api_key","apikey","code_verifier","password"]),Jt=new Set(["member_id","is_new_member","email","state"]),Qt=/\b(access_token|refresh_token|id_token|token|auth_token|session_token|jwt|client_secret|secret_key|api_key|apikey|code_verifier)=[^&#\s"'<>)\]]+/gi;function Xe(n){let e=n.split("=",1)[0].replace(/\+/g," ");try{return decodeURIComponent(e).toLowerCase()}catch{return e.toLowerCase()}}function Ye(n,e){if(!n)return n;let t=n.split("&"),s=t.filter(r=>!e(Xe(r)));return s.length===t.length?n:s.join("&")}function Ne(n){if(!n)return n;let e=new Set(n.split("&").map(Xe)),t=e.has("access_token")||e.has("refresh_token"),s=e.has("code")&&e.has("state");return Ye(n,r=>jt.has(r)||t&&Jt.has(r)||s&&(r==="code"||r==="state"))}function Xt(n){let e=n.indexOf("?");if(e>=0){let t=n.slice(0,e),s=Ne(n.slice(e+1));return s?`${t}?${s}`:t}return n.includes("=")?Ne(n):n}function Ze(n,e,t){let s=n.indexOf("#"),r=s>=0?n.slice(0,s):n,i=r.indexOf("?"),o=i>=0?r.slice(0,i):r,a=i>=0?r.slice(i+1):"",c=s>=0?n.slice(s+1):"",l=e(a),u=t(c);return l===a&&u===c?n:`${o}${l?`?${l}`:""}${u?`#${u}`:""}`}function O(n){return n&&Ze(n,Ne,Xt)}function et(n){return n.replace(Qt,"$1=[redacted]")}function tt(n,e){let t=new Set(e);return Ze(n,s=>Ye(s,r=>t.has(r)),s=>s)}var Yt=1800*1e3,Be="__cb_session",He="__cb_visitor_uid",oe="__cb_last_activity";function Q(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}var X=class{constructor(){this._sessionId=null;this._visitorUid=null;this._lastActivity=0;this._isNewSession=!1}get sessionId(){return this.ensureSession(),this._sessionId}get visitorUid(){return this._visitorUid||(this._visitorUid=this.loadOrCreateVisitorUid()),this._visitorUid}get isNewSession(){return this._isNewSession}touch(){this._lastActivity=Date.now(),this._isNewSession=!1;try{typeof sessionStorage<"u"&&sessionStorage.setItem(oe,String(this._lastActivity))}catch{}}reset(){this._sessionId=null,this._isNewSession=!1;try{typeof sessionStorage<"u"&&(sessionStorage.removeItem(Be),sessionStorage.removeItem(oe))}catch{}}regenerateVisitorUid(){let e=Q();this._visitorUid=e;try{typeof localStorage<"u"&&localStorage.setItem(He,e)}catch{}return this.reset(),e}ensureSession(){let e=Date.now();if(!this._sessionId)try{if(typeof sessionStorage<"u"){this._sessionId=sessionStorage.getItem(Be);let t=sessionStorage.getItem(oe);this._lastActivity=t?parseInt(t,10):0}}catch{}if(!this._sessionId||this._lastActivity>0&&e-this._lastActivity>Yt){this._sessionId=Q(),this._isNewSession=!0,this._lastActivity=e;try{typeof sessionStorage<"u"&&(sessionStorage.setItem(Be,this._sessionId),sessionStorage.setItem(oe,String(e)))}catch{}}}loadOrCreateVisitorUid(){try{if(typeof localStorage<"u"){let e=localStorage.getItem(He);if(e)return e;let t=Q();return localStorage.setItem(He,t),t}}catch{}return Q()}};function st(n){if(!n)return"";let e=new URLSearchParams;n.start_date!==void 0&&e.set("start_date",String(n.start_date)),n.end_date!==void 0&&e.set("end_date",String(n.end_date)),n.limit!==void 0&&e.set("limit",String(n.limit));let t=e.toString();return t?`?${t}`:""}function Zt(){if(typeof window>"u")return{};try{let n=new URLSearchParams(window.location.search),e={};for(let t of["utm_source","utm_medium","utm_campaign","utm_content","utm_term"]){let s=n.get(t);s&&(e[t]=s)}return e}catch{return{}}}var ae=class{constructor(e){this.storageWebId=null;this.memberId=null;this.eventQueue=[];this.batchTimer=null;this.isInitialized=!1;this.heartbeatTimer=null;this.visibilityHandler=null;this.unloadHeartbeatHandler=null;this.popstateHandler=null;this.beforeUnloadHandler=null;this.origPushState=null;this.origReplaceState=null;this.heatmapClickHandler=null;this.heatmapScrollHandler=null;this.utm={};this.handleHeatmapClick=e=>{let t=e.clientX/window.innerWidth*100,s=e.clientY/window.innerHeight*100;this.recordHeatmapEvent("click",t,s)};this.heatmapQueue=[];this.http=e,this.config={trackPageViews:!0,trackEvents:!0,trackSessions:!0,heatmap:!1,recording:!1,batchSize:10,flushInterval:5e3,respectDoNotTrack:!0,debug:!1},this.consent={analytics:!0,heatmap:!1,recording:!1},this.session=new X}init(e,t){if(this.isInitialized){this.log("Analytics already initialized");return}if(typeof window>"u"){this.log("Analytics only works in browser environment");return}if(t?.respectDoNotTrack!==!1&&this.isDNT()){this.log("Do Not Track enabled, analytics disabled");return}this.storageWebId=e,Object.assign(this.config,t),this.isInitialized=!0,this.utm=Zt(),this.config.trackSessions&&(this.trackSessionStart(),this.startHeartbeat()),this.config.trackPageViews&&(this.trackPageView(),this.setupAutoPageView()),this.startBatchTimer(),this.beforeUnloadHandler=()=>this.flushSync(),window.addEventListener("beforeunload",this.beforeUnloadHandler),this.log("Analytics initialized",{storageWebId:e})}destroy(){this.isInitialized&&(this.stopBatchTimer(),this.stopHeartbeat(),this.removeAutoPageView(),this.removeHeatmapListeners(),this.beforeUnloadHandler&&(window.removeEventListener("beforeunload",this.beforeUnloadHandler),this.beforeUnloadHandler=null),this.flush(),this.isInitialized=!1,this.log("Analytics destroyed"))}setConsent(e){Object.assign(this.consent,e),this.log("Consent updated",e),e.analytics===!1&&this.isInitialized&&this.destroy()}getConsent(){return{...this.consent}}trackPageView(e){if(!this.canTrack())return;this.session.touch();let t=this.createBaseEvent("page_view");t.page_path=e||window.location.pathname,t.page_url=O(window.location.href),t.page_title=document.title,t.referrer=O(document.referrer)||void 0,t.screen_width=window.screen.width,t.screen_height=window.screen.height,Object.assign(t,this.utm),this.enqueue(t)}trackEvent(e,t){if(!this.canTrack()||!this.config.trackEvents)return;this.session.touch();let s=this.createBaseEvent("event");s.event_name=e,s.event_properties=t,s.page_path=window.location.pathname,s.page_url=O(window.location.href),this.enqueue(s)}identify(e){this.memberId&&this.memberId!==e&&this.reset(),this.setMemberId(e),this.linkMemberSilent(e)}reset(){this.setMemberId(null),this.eventQueue=[],this.heatmapQueue=[];let e=this.session.regenerateVisitorUid();this.log("Analytics reset",{newVisitorUid:e})}setMemberId(e){if(this.memberId=e||null,typeof window<"u"){let t=window;e?typeof t.__cbSetMember=="function"&&t.__cbSetMember(e):typeof t.__cbClearMember=="function"&&t.__cbClearMember()}this.log("Member id set",{memberId:e})}linkMemberSilent(e,t=!1){if(!this.storageWebId)return;let s=this.http.hasPublicKey()?"/v1/public":"/v1";this.http.post(`${s}/storages/web/${this.storageWebId}/visitors/link-member`,{visitor_uid:this.session.visitorUid,app_member_id:e}).then(r=>{r&&(this.log("link-member response",r),!t&&r.success===!1&&r.code==="VISITOR_LINKED_TO_OTHER_MEMBER"&&(this.log("user-switch detected \u2014 regenerating visitor_uid"),this.eventQueue=[],this.heatmapQueue=[],this.session.regenerateVisitorUid(),this.linkMemberSilent(e,!0)))}).catch(r=>{this.log("link-member silent fail",r)})}getMemberId(){return this.memberId}enableHeatmap(e){if(!this.canTrack()||!this.consent.heatmap)return;let t=e?.click??!0,s=e?.scroll??!0;if(t&&(this.heatmapClickHandler=this.handleHeatmapClick,document.addEventListener("click",this.heatmapClickHandler)),s){let r=null,i=0;this.heatmapScrollHandler=()=>{let o=Math.round((window.scrollY+window.innerHeight)/document.documentElement.scrollHeight*100);i=Math.max(i,o),r&&clearTimeout(r),r=setTimeout(()=>{this.recordHeatmapEvent("scroll",50,i*(window.innerHeight/100),i)},500)},window.addEventListener("scroll",this.heatmapScrollHandler,{passive:!0})}this.log("Heatmap enabled",e)}enableHeartbeat(){if(!this.canTrack()||this.heartbeatTimer)return;let e=()=>{if(!this.canTrack())return;let t=this.http.hasPublicKey()?"/v1/public":"/v1";this.http.post(`${t}/storages/web/${this.storageWebId}/sessions/heartbeat`,{visitor_uid:this.session.visitorUid,session_id:this.session.sessionId}).catch(()=>{})};this.heartbeatTimer=setInterval(e,3e4),document.addEventListener("visibilitychange",()=>{document.hidden?this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null):this.heartbeatTimer||(this.heartbeatTimer=setInterval(e,3e4),e())}),window.addEventListener("beforeunload",()=>{if(navigator?.sendBeacon&&this.storageWebId){let t=this.http.hasPublicKey()?"/v1/public":"/v1",s=`${this.http.getBaseUrl()}${t}/storages/web/${this.storageWebId}/sessions/heartbeat`;navigator.sendBeacon(s,JSON.stringify({visitor_uid:this.session.visitorUid,session_id:this.session.sessionId}))}}),e(),this.log("Heartbeat enabled (30s interval)")}async flush(){await this.flushQueue()}async getPopularPages(e,t){let s=this.requireServerSideStorageId(e,"getPopularPages"),r=st(t);return this.http.get(`/v1/storages/web/${s}/popular-pages${r}`)}async getNavigationFlow(e,t){let s=this.requireServerSideStorageId(e,"getNavigationFlow"),r=st(t);return this.http.get(`/v1/storages/web/${s}/navigation/flow${r}`)}async getVisitors(e,t){let s=this.requireServerSideStorageId(e,"getVisitors"),r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",String(t.limit)),t?.offset!==void 0&&r.set("offset",String(t.offset)),t?.sort_by&&r.set("sort_by",t.sort_by);let i=r.toString()?`?${r.toString()}`:"";return this.http.get(`/v1/storages/web/${s}/visitors${i}`)}async getVisitorGroups(e,t){let s=this.requireServerSideStorageId(e,"getVisitorGroups"),r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",String(t.limit)),t?.offset!==void 0&&r.set("offset",String(t.offset)),t?.sort_by&&r.set("sort_by",t.sort_by);let i=r.toString()?`?${r.toString()}`:"";return this.http.get(`/v1/storages/web/${s}/visitor-groups${i}`)}async getVisitorByMember(e,t){let s=this.requireServerSideStorageId(e,"getVisitorByMember");return this.http.get(`/v1/storages/web/${s}/members/${t}/visitor`)}async mergeVisitors(e,t){let s=this.requireServerSideStorageId(e,"mergeVisitors");return this.http.post(`/v1/storages/web/${s}/visitors/merge`,t)}requireServerSideStorageId(e,t){if(this.http.hasPublicKey())throw new Error(`cb.analytics.${t}() \uB294 \uCF58\uC194 JWT \uB610\uB294 User Secret Key(cb_sk_) \uC778\uC99D\uC774 \uD544\uC694\uD569\uB2C8\uB2E4. \uBE0C\uB77C\uC6B0\uC800 SDK \uC758 Public Key(cb_pk_) \uB85C\uB294 \uD638\uCD9C\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 Functions \uD658\uACBD\uC5D0\uC11C \uC0AC\uC6A9\uD558\uC138\uC694.`);let s=e??this.storageWebId;if(!s)throw new Error(`cb.analytics.${t}() \uD638\uCD9C \uC2DC storageWebId \uAC00 \uD544\uC694\uD569\uB2C8\uB2E4 (init \uB610\uB294 \uC778\uC790\uB85C \uC804\uB2EC).`);return s}getSession(){return this.session}canTrack(){return!(!this.isInitialized||!this.storageWebId||!this.consent.analytics)}isDNT(){if(typeof navigator>"u")return!1;let e=navigator.globalPrivacyControl;return navigator.doNotTrack==="1"||e===!0}createBaseEvent(e){return{type:e,event_id:Q(),timestamp:new Date().toISOString(),session_id:this.session.sessionId,visitor_uid:this.session.visitorUid}}enqueue(e){this.eventQueue.push(e),this.eventQueue.length>=this.config.batchSize&&this.flushQueue()}async flushQueue(){if(this.eventQueue.length===0||!this.storageWebId)return;let e=this.eventQueue.splice(0),t=this.http.hasPublicKey()?"/v1/public":"/v1";try{await this.http.post(`${t}/storages/web/${this.storageWebId}/visitors/batch`,{visitor_uid:this.session.visitorUid,...this.memberId?{app_member_id:this.memberId}:{},events:e.map(s=>({event_id:s.event_id,timestamp:s.timestamp,page_path:s.page_path||"",page_url:s.page_url||"",page_title:s.page_title||"",referrer:s.referrer||"",user_agent:typeof navigator<"u"?navigator.userAgent:"",screen_width:s.screen_width||0,screen_height:s.screen_height||0,session_id:s.session_id,session_start:s.type==="session_start",is_page_view:s.type==="page_view",event_name:s.event_name,event_properties:s.event_properties,utm_source:s.utm_source,utm_medium:s.utm_medium,utm_campaign:s.utm_campaign,utm_content:s.utm_content,utm_term:s.utm_term}))}),this.log(`Flushed ${e.length} events`)}catch(s){this.eventQueue.length<this.config.batchSize*3&&this.eventQueue.unshift(...e),this.log("Flush failed",s)}}flushSync(){if(this.eventQueue.length===0||!this.storageWebId||typeof navigator>"u"||!navigator.sendBeacon)return;let e=this.eventQueue.splice(0),t=this.http.hasPublicKey()?"/v1/public":"/v1",r=`${this.http.getBaseUrl()}${t}/storages/web/${this.storageWebId}/visitors/batch`,i=typeof navigator<"u"?navigator.userAgent:"",o=JSON.stringify({visitor_uid:this.session.visitorUid,...this.memberId?{app_member_id:this.memberId}:{},events:e.map(a=>({event_id:a.event_id,timestamp:a.timestamp,page_path:a.page_path||"",page_url:a.page_url||"",page_title:a.page_title||"",referrer:a.referrer||"",user_agent:i,screen_width:a.screen_width||0,screen_height:a.screen_height||0,session_id:a.session_id,session_start:a.type==="session_start",is_page_view:a.type==="page_view",event_name:a.event_name,event_properties:a.event_properties,utm_source:a.utm_source,utm_medium:a.utm_medium,utm_campaign:a.utm_campaign,utm_content:a.utm_content,utm_term:a.utm_term}))});try{navigator.sendBeacon(r,new Blob([o],{type:"application/json"}))}catch{}}trackSessionStart(){let e=this.createBaseEvent("session_start");e.page_path=window.location.pathname,e.page_url=O(window.location.href),e.referrer=O(document.referrer)||void 0,e.screen_width=window.screen.width,e.screen_height=window.screen.height,Object.assign(e,this.utm),this.enqueue(e)}startBatchTimer(){this.batchTimer=setInterval(()=>this.flushQueue(),this.config.flushInterval)}stopBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=null)}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.canTrack()&&this.sendHeartbeat()},30*1e3),typeof document<"u"&&(this.visibilityHandler=()=>{document.visibilityState==="hidden"?(this.sendHeartbeatBeacon(),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)):document.visibilityState==="visible"&&(this.heartbeatTimer||(this.sendHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.canTrack()&&this.sendHeartbeat()},30*1e3)))},document.addEventListener("visibilitychange",this.visibilityHandler)),typeof window<"u"&&(this.unloadHeartbeatHandler=()=>this.sendHeartbeatBeacon(),window.addEventListener("beforeunload",this.unloadHeartbeatHandler))}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),typeof document<"u"&&this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),typeof window<"u"&&this.unloadHeartbeatHandler&&(window.removeEventListener("beforeunload",this.unloadHeartbeatHandler),this.unloadHeartbeatHandler=null)}sendHeartbeat(){let e=this.createBaseEvent("heartbeat");if(e.page_path=window.location.pathname,this.enqueue(e),this.storageWebId){let t=this.http.hasPublicKey()?"/v1/public":"/v1";this.http.post(`${t}/storages/web/${this.storageWebId}/sessions/heartbeat`,{visitor_uid:this.session.visitorUid,session_id:this.session.sessionId}).catch(()=>{})}}sendHeartbeatBeacon(){if(!this.storageWebId||typeof navigator>"u"||!navigator.sendBeacon)return;let e=this.http.hasPublicKey()?"/v1/public":"/v1",s=`${this.http.getBaseUrl()}${e}/storages/web/${this.storageWebId}/sessions/heartbeat`,r=JSON.stringify({visitor_uid:this.session.visitorUid,session_id:this.session.sessionId});try{navigator.sendBeacon(s,new Blob([r],{type:"application/json"}))}catch{}}setupAutoPageView(){this.popstateHandler=()=>this.trackPageView(),window.addEventListener("popstate",this.popstateHandler),this.origPushState=history.pushState.bind(history),this.origReplaceState=history.replaceState.bind(history),history.pushState=(...e)=>{this.origPushState(...e),this.trackPageView()},history.replaceState=(...e)=>{this.origReplaceState(...e),this.trackPageView()}}removeAutoPageView(){this.popstateHandler&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),this.origPushState&&(history.pushState=this.origPushState,this.origPushState=null),this.origReplaceState&&(history.replaceState=this.origReplaceState,this.origReplaceState=null)}removeHeatmapListeners(){this.heatmapClickHandler&&(document.removeEventListener("click",this.heatmapClickHandler),this.heatmapClickHandler=null),this.heatmapScrollHandler&&(window.removeEventListener("scroll",this.heatmapScrollHandler),this.heatmapScrollHandler=null)}recordHeatmapEvent(e,t,s,r){if(!this.canTrack()||!this.storageWebId)return;let i=this.http.hasPublicKey()?"/v1/public":"/v1";if(this.heatmapQueue.push({page_path:window.location.pathname,event_type:e,x_percent:Math.round(t*100)/100,y_percent:Math.round(s*100)/100,viewport_width:window.innerWidth,viewport_height:window.innerHeight,scroll_depth_percent:r,session_id:this.session.sessionId}),this.heatmapQueue.length>=50){let o=this.heatmapQueue.splice(0);this.http.post(`${i}/storages/web/${this.storageWebId}/heatmap/batch`,{visitor_uid:this.session.visitorUid,events:o}).catch(()=>{})}}log(...e){this.config.debug&&console.log("[Analytics]",...e)}};var es={list:"app_member:read",get:"app_member:read",remove:"app_member:write",suspend:"app_member:suspend",unsuspend:"app_member:suspend"},B=class{constructor(e){this.http=e}ensureServerAuth(e){if(this.http.hasPublicKey()&&!this.http.hasJWT()){let t=es[e]??"app_member:read";throw new Error(`cb.appMembers.${e}() \uB294 \uCF58\uC194 JWT \uB610\uB294 service_role(ctx.cbAdmin, management_scopes: ["${t}"]) \uC778\uC99D\uC774 \uD544\uC694\uD569\uB2C8\uB2E4. Public Key(cb_pk_) \uB2E8\uB3C5 SDK \uC778\uC2A4\uD134\uC2A4\uB85C\uB294 \uD638\uCD9C\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 \uC790\uAE30 \uC815\uBCF4\uB294 cb.auth.getMe() \uB97C \uC4F0\uACE0, \uBCF8\uC778 \uD0C8\uD1F4\uB294 cb.auth.deleteMyAccount() \uB97C \uC4F0\uC138\uC694.`)}}async list(e,t={}){this.ensureServerAuth("list");let s=new URLSearchParams;t.page!==void 0&&s.set("page",String(t.page)),t.pageSize!==void 0&&s.set("page_size",String(t.pageSize));let r=t.search?.trim();r&&s.set("search",r);let i=s.toString();return this.http.get(`/v1/apps/${e}/app-members${i?`?${i}`:""}`)}async get(e,t){return this.ensureServerAuth("get"),this.http.get(`/v1/apps/${e}/app-members/${t}`)}async remove(e,t){return this.ensureServerAuth("remove"),this.http.delete(`/v1/apps/${e}/app-members/${t}`)}async suspend(e,t,s){this.ensureServerAuth("suspend");let r=s?.reason?.trim();if(!r)throw new Error("cb.appMembers.suspend(): reason \uC774 \uD544\uC694\uD569\uB2C8\uB2E4 \u2014 \uC815\uC9C0\uB41C \uD68C\uC6D0\uC5D0\uAC8C \uBCF4\uC774\uB294 \uC0AC\uC720\uC785\uB2C8\uB2E4");let i={reason:r};if(s.until!==void 0&&s.until!==null){let o=s.until instanceof Date?s.until:new Date(s.until);if(Number.isNaN(o.getTime()))throw new Error(`cb.appMembers.suspend(): until \uC774 \uC62C\uBC14\uB978 \uC2DC\uAC01\uC774 \uC544\uB2D9\uB2C8\uB2E4 (${String(s.until)})`);i.until=o.toISOString()}else i.duration="permanent";return this.http.post(`/v1/apps/${e}/app-members/${t}/suspend`,i)}async unsuspend(e,t){return this.ensureServerAuth("unsuspend"),this.http.post(`/v1/apps/${e}/app-members/${t}/unsuspend`,{})}};function ts(n,e){switch(e){case"string":return typeof n=="string";case"number":return typeof n=="number"&&Number.isFinite(n);case"boolean":return typeof n=="boolean";case"array":return Array.isArray(n);case"object":return typeof n=="object"&&n!==null&&!Array.isArray(n);case"string-or-number":return typeof n=="string"||typeof n=="number"&&Number.isFinite(n)}}function S(n,e,t){if(typeof n!="object"||n===null||Array.isArray(n))throw new b(502,`[${t}] expected object, got ${typeof n}`,"SCHEMA_MISMATCH");let s=n;for(let[r,i]of Object.entries(e)){if(!(r in s)){if(i.optional)continue;throw new b(502,`[${t}] missing required field "${r}"`,"SCHEMA_MISMATCH")}let a=s[r];if(!(i.optional&&a==null)&&!ts(a,i.type))throw new b(502,`[${t}] field "${r}" expected ${i.type}, got ${typeof a}`,"SCHEMA_MISMATCH")}return n}var ce=class{constructor(e){this.http=e;this.analytics=null}_attachAnalytics(e){this.analytics=e}notifyVisitorTracker(e){if(this.analytics){this.analytics.setMemberId(e);return}if(typeof window>"u")return;let t=window;e?typeof t.__cbSetMember=="function"&&t.__cbSetMember(e):typeof t.__cbClearMember=="function"&&t.__cbClearMember()}async getAuthSettings(){return this.http.get("/v1/public/auth-settings",{skipAuth:!0})}async signUpMember(e){if(!e.login_id&&!e.email)throw new Error("signUpMember requires at least one of login_id or email.");let t=await this.http.post("/v1/public/app-members/signup",e,{skipAuth:!0});return S(t,{access_token:{type:"string"},refresh_token:{type:"string"},member_id:{type:"string-or-number"}},"auth.signUpMember"),this.http.setTokens(t.access_token,t.refresh_token),this.notifyVisitorTracker(t.member_id),t}async signInMember(e){if(!e.login_id&&!e.email)throw new Error("signInMember requires at least one of login_id or email.");let t=await this.http.post("/v1/public/app-members/signin",e,{skipAuth:!0});return S(t,{access_token:{type:"string"},refresh_token:{type:"string"},member_id:{type:"string-or-number"}},"auth.signInMember"),this.http.setTokens(t.access_token,t.refresh_token),this.notifyVisitorTracker(t.member_id),t}async requestPasswordReset(e){return this.http.post("/v1/public/app-members/password-reset/request",e,{skipAuth:!0})}async confirmPasswordReset(e){let t=await this.http.post("/v1/public/app-members/password-reset/confirm",e,{skipAuth:!0});return this.http.clearTokens(),this.notifyVisitorTracker(null),t}async changePassword(e){let t=await this.http.post("/v1/public/app-members/me/password",e);return this.http.clearTokens(),this.notifyVisitorTracker(null),t}async sendEmailVerification(e){return this.http.post("/v1/public/app-members/me/email-verification/request",e??{})}async confirmEmailVerification(e){let t=await this.http.post("/v1/public/app-members/email-verification/confirm",e,{skipAuth:!0});return S(t,{member_id:{type:"string-or-number"}},"auth.confirmEmailVerification"),t}async getMe(){if(this.http.knowsNoSession())throw await this.http.rejectNoSession();let e=await this.http.get("/v1/public/app-members/me");return S(e,{member_id:{type:"string-or-number"}},"auth.getMe"),e}async updateCustomData(e){return this.http.patch("/v1/public/app-members/me/custom-data",e)}async adminUpdateMember(e,t){if(!this.http.getSecretKey())throw new Error("adminUpdateMember requires a secretKey. Initialize ConnectBase with both publicKey and secretKey.");return this.http.patch(`/v1/public/app-members/${encodeURIComponent(e)}`,t)}async adminDeleteMember(e){if(!this.http.getSecretKey())throw new Error("adminDeleteMember requires a secretKey. Initialize ConnectBase with both publicKey and secretKey.");return this.http.delete(`/v1/public/app-members/${encodeURIComponent(e)}`)}async deleteMyAccount(){try{return await this.http.delete("/v1/public/app-members/me")}finally{this.http.clearTokens(),this.notifyVisitorTracker(null)}}async signOut(){try{await this.http.post("/v1/auth/logout")}finally{this.http.clearTokens(),this.notifyVisitorTracker(null)}}async listSessions(){let e=await this.http.get("/v1/public/app-members/me/sessions");return S(e,{sessions:{type:"array"}},"auth.listSessions"),e}async revokeSession(e){let t=await this.isCurrentSession(e),s=await this.http.delete(`/v1/public/app-members/me/sessions/${encodeURIComponent(e)}`);return t&&(this.http.clearTokens(),this.notifyVisitorTracker(null)),s}async revokeOtherSessions(){return this.http.delete("/v1/public/app-members/me/sessions")}async isCurrentSession(e){try{let{sessions:t}=await this.listSessions();return t.some(s=>s.session_id===e&&s.current===!0)}catch{return!1}}};function A(n={}){let e=new AbortController,t=n.timeout??3e4,s=n.signal,r=null,i=null;return s&&(s.aborted?e.abort(s.reason):(i=()=>e.abort(s.reason),s.addEventListener("abort",i,{once:!0}))),t>0&&Number.isFinite(t)&&(r=setTimeout(()=>{e.abort(new DOMException(`Request timed out after ${t}ms`,"TimeoutError"))},t)),{signal:e.signal,cleanup:()=>{r!==null&&clearTimeout(r),s&&i&&s.removeEventListener("abort",i)}}}function U(n,e){if(!e)return n;let t=()=>e.reason??new DOMException("The operation was aborted.","AbortError");return e.aborted?(n.catch(()=>{}),Promise.reject(t())):new Promise((s,r)=>{let i=()=>r(t());e.addEventListener("abort",i,{once:!0}),n.then(o=>{e.removeEventListener("abort",i),s(o)},o=>{e.removeEventListener("abort",i),r(o)})})}var le=class{constructor(e=20){this.buf=[];this.capacity=Math.min(Math.max(1,e),50)}push(e){this.buf.length>=this.capacity&&this.buf.shift(),this.buf.push(e)}snapshot(){return this.buf.slice()}clear(){this.buf=[]}};function rt(n){try{return(n.startsWith("http")?new URL(n):new URL(n,"http://x")).pathname||n}catch{let e=n.indexOf("?");return e>=0?n.slice(0,e):n}}var ss=new Set(["/v1/public/app-members/signup","/v1/public/app-members/signin","/v1/public/app-members/signout"]);function Fe(n){return typeof n=="object"&&n!==null&&"name"in n&&n.name==="AbortError"}function ue(n){let e=n.split("?")[0];return ss.has(e)?"include":e.startsWith("/v1/public/")||e.startsWith("/v1/proxy/")?"omit":"include"}var it="cb_auth_tokens",rs=6e4;function is(n){switch(n){case 502:return"bad_gateway";case 503:return"service_unavailable";case 504:return"gateway_timeout";default:return}}function ns(n){switch(n){case 502:return"\uAC8C\uC774\uD2B8\uC6E8\uC774\uAC00 \uC11C\uBC84\uB85C\uBD80\uD130 \uC62C\uBC14\uB978 \uC751\uB2F5\uC744 \uBC1B\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4 (502)";case 503:return"\uC11C\uBC84\uAC00 \uC77C\uC2DC\uC801\uC73C\uB85C \uC694\uCCAD\uC744 \uCC98\uB9AC\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 (503)";case 504:return"\uAC8C\uC774\uD2B8\uC6E8\uC774\uAC00 \uC751\uB2F5\uC744 \uAE30\uB2E4\uB9AC\uB2E4 \uC5F0\uACB0\uC744 \uB04A\uC5C8\uC2B5\uB2C8\uB2E4 (504). \uC624\uB798 \uAC78\uB9AC\uB294 \uC791\uC5C5\uC774\uBA74 \uC694\uCCAD \uD0C0\uC784\uC544\uC6C3\uC744 \uB298\uB9AC\uAC70\uB098 \uC2A4\uD2B8\uB9AC\uBC0D\uC744 \uC0AC\uC6A9\uD558\uC138\uC694";default:return}}function Y(n){try{let e=n.split(".")[1];if(!e)return null;let t=e.replace(/-/g,"+").replace(/_/g,"/"),s=t+"=".repeat((4-t.length%4)%4),r=JSON.parse(atob(s));return r&&typeof r=="object"?r:null}catch{return null}}function F(n,e){let t=Y(n);return!t||typeof t.exp!="number"?!0:t.exp<Date.now()/1e3+e}function nt(n,e){let t=Y(n),s=Y(e);if(!t||!s||t.role!=="AppMember"||s.role!=="AppMember")return!1;let r=t.app_member_id;return typeof r=="string"&&r!==""&&r===s.app_member_id&&t.app_id===s.app_id}function ot(n){let e=Y(n)?.role;return e==="User"||e==="AdminInvite"}var os=10*6e4,de=new Map;function as(n,e){let t=de.get(n);if(t&&Date.now()<t.expiresAt)return t.promise;let s={promise:cs(n,e),expiresAt:Number.POSITIVE_INFINITY};return de.set(n,s),s.promise.then(()=>{s.expiresAt=Date.now()+os},()=>{de.get(n)===s&&de.delete(n)}),s.promise}async function cs(n,e){let{signal:t,cleanup:s}=A({timeout:e});try{let r=await U(fetch(`${n}/v1/public/edge-hints`,{method:"GET",credentials:"omit",signal:t}),t);if(!r.ok)throw new Error(`edge-hints HTTP ${r.status}`);let i={direct:r.headers?.get("X-CB-Direct-Base")||null,realtime:r.headers?.get("X-CB-Realtime-Direct-Base")||null},o;try{o=await U(r.json(),t)}catch(a){if(i.direct||i.realtime)return[i];throw a}return[i,{direct:o?.direct_base,realtime:o?.realtime_direct_base}]}finally{s()}}var pe=class{constructor(e){this.isRefreshing=!1;this.refreshPromise=null;this.refreshFailureCount=0;this.refreshLockedUntil=0;this.recentCalls=new le;this.bootRestorePromise=null;this.bootRestoreAlwaysAwait=!1;this.directBaseUrl=null;this.directDisabled=!1;this.directRealtimeBaseUrl=null;this.directRealtimeDisabled=!1;this.config={...e},this.storageKey=this.buildStorageKey(),this.warnIfUnsafePersistence(),this.warnIfSecretKeyInBrowser(),this.restoreTokens()}get requestTimeoutMs(){return this.config.requestTimeoutMs}setBootRestorePromise(e,t){this.bootRestorePromise=e.catch(()=>!1),this.bootRestoreAlwaysAwait=t?.alwaysAwait===!0}getRecentCalls(){return this.recentCalls.snapshot()}clearRecentCalls(){this.recentCalls.clear()}warnIfSecretKeyInBrowser(){if(typeof window>"u"||typeof document>"u")return;let e=this.config.publicKey?.startsWith("cb_sk_")===!0;!this.config.secretKey&&!e||console.warn("[connect-base-client] \uBE0C\uB77C\uC6B0\uC800\uC5D0\uC11C Secret Key(cb_sk_)\uB97C \uC4F0\uACE0 \uC788\uC2B5\uB2C8\uB2E4. \uD398\uC774\uC9C0\uB97C \uC5EC\uB294 \uB204\uAD6C\uB098 \uC774 \uD0A4\uB97C \uC77D\uC5B4 \uACC4\uC815 \uAD8C\uD55C\uC73C\uB85C API \uB97C \uD638\uCD9C\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4. \uBE0C\uB77C\uC6B0\uC800\uC5D0\uB294 publicKey(cb_pk_)\uB9CC \uB123\uACE0 Secret Key \uB294 \uC11C\uBC84\uB098 CLI \uC5D0\uC11C\uB9CC \uC4F0\uC138\uC694. \uC774\uBBF8 \uBC30\uD3EC\uB410\uB2E4\uBA74 \uCF58\uC194\uC5D0\uC11C \uD0A4\uB97C \uD3D0\uAE30\uD558\uACE0 \uC0C8\uB85C \uBC1C\uAE09\uD558\uC138\uC694.")}warnIfUnsafePersistence(){typeof window>"u"||(this.config.persistence==="localStorage"?console.warn(`[connect-base-client] persistence="localStorage" \uB294 XSS \uC2DC refresh token \uC601\uAD6C \uD0C8\uCDE8 \uC704\uD5D8\uC774 \uC788\uC2B5\uB2C8\uB2E4. \uAE30\uBCF8\uAC12('none') \uC744 \uC0AC\uC6A9\uD558\uBA74 \uC11C\uBC84\uAC00 \uBC1C\uAE09\uD55C HttpOnly cookie \uB85C\uB9CC refresh token \uC774 \uBCF4\uAD00\uB418\uC5B4 JS \uAC00 \uC811\uADFC\uD560 \uC218 \uC5C6\uACE0, \uC0C8\uB85C\uACE0\uCE68 \uD6C4\uC5D0\uB3C4 autoRestoreSession \uC73C\uB85C \uC790\uB3D9 \uBCF5\uAD6C\uB429\uB2C8\uB2E4.`):this.config.persistence==="sessionStorage"&&console.warn(`[connect-base-client] persistence="sessionStorage" \uB294 XSS \uC2DC \uD0ED \uC138\uC158 \uD0C8\uCDE8 \uC704\uD5D8\uC774 \uC788\uC2B5\uB2C8\uB2E4. \uAE30\uBCF8\uAC12('none') + HttpOnly cookie \uD750\uB984\uC744 \uAD8C\uC7A5\uD569\uB2C8\uB2E4.`))}updateConfig(e){this.config={...this.config,...e}}setTokens(e,t){this.config.accessToken=e,this.config.refreshToken=t,this.persistTokens(),this.markSessionHint(),this.clearNoCookieSessionMark()}clearTokens(){this.config.accessToken=void 0,this.config.refreshToken=void 0,this.removePersistedTokens(),this.clearSessionHint()}setAccessToken(e){this.config.accessToken=e,this.persistTokens()}buildSessionHintKey(){return`${this.buildStorageKey()}:has_session`}markSessionHint(){if(!(typeof window>"u"))try{localStorage.setItem(this.buildSessionHintKey(),"1")}catch{}}clearSessionHint(){if(!(typeof window>"u"))try{localStorage.removeItem(this.buildSessionHintKey())}catch{}}hasSessionHint(){if(typeof window>"u")return!1;try{return localStorage.getItem(this.buildSessionHintKey())==="1"}catch{return!0}}buildNoCookieSessionKey(){return`${this.storageKey}:no_cookie_session`}markNoCookieSession(){if(!(typeof window>"u"))try{localStorage.setItem(this.buildNoCookieSessionKey(),String(Date.now()))}catch{}}clearNoCookieSessionMark(){if(!(typeof window>"u"))try{localStorage.removeItem(this.buildNoCookieSessionKey())}catch{}}knowsNoSession(){return typeof window<"u"&&!this.config.accessToken&&!this.config.refreshToken&&this.isNoCookieSessionMarkFresh()}async rejectNoSession(){let e=await this.buildApiError(new Response(JSON.stringify({error:"\uC778\uC99D \uD1A0\uD070\uC774 \uD544\uC694\uD569\uB2C8\uB2E4"}),{status:401,headers:{"Content-Type":"application/json"}}));return this.emitError(e),e}isNoCookieSessionMarkFresh(){if(typeof window>"u")return!1;try{let e=localStorage.getItem(this.buildNoCookieSessionKey());if(!e)return!1;let t=Number.parseInt(e,10);return Number.isFinite(t)?Date.now()-t>=rs?(this.clearNoCookieSessionMark(),!1):!0:!1}catch{return!1}}async bootstrapRefreshCookie(){if(!(typeof window>"u")&&this.persistence==="none"&&this.config.refreshToken)try{await this.refreshAccessToken({silent:!0})}catch{}}get persistence(){return this.config.persistence??"none"}getStorage(){return typeof window>"u"?null:this.persistence==="localStorage"&&typeof localStorage<"u"?localStorage:this.persistence==="sessionStorage"&&typeof sessionStorage<"u"?sessionStorage:null}getPersistenceStorage(){return this.getStorage()}buildStorageKey(){let e=this.config.publicKey??this.config.secretKey;if(!e)return it;let t=0;for(let s=0;s<e.length;s++)t=(t<<5)-t+e.charCodeAt(s),t=t&t;return`${it}_${Math.abs(t).toString(36)}`}persistTokens(){if(this.persistence==="none")return;let e=this.getStorage();!e||!this.config.accessToken||!this.config.refreshToken||e.setItem(this.storageKey,JSON.stringify({accessToken:this.config.accessToken,refreshToken:this.config.refreshToken}))}restoreTokens(){if(this.persistence==="none"||this.config.accessToken&&this.config.refreshToken)return;let e=this.getStorage();if(!e)return;let t=e.getItem(this.storageKey);if(t)try{let{accessToken:s,refreshToken:r}=JSON.parse(t);s&&r&&(this.config.accessToken=s,this.config.refreshToken=r)}catch{e.removeItem(this.storageKey)}}removePersistedTokens(){if(this.persistence==="none")return;let e=this.getStorage();e&&e.removeItem(this.storageKey)}hasPublicKey(){return!!this.config.publicKey}getPublicKey(){return this.config.publicKey}hasSecretKey(){return!!this.config.secretKey}getSecretKey(){return this.config.secretKey}getCredential(){return this.config.publicKey??this.config.secretKey}getAccessToken(){return this.config.accessToken}hasJWT(){return!!this.config.accessToken}getBaseUrl(){return this.config.baseUrl}getDirectRealtimeBaseUrl(){return this.directRealtimeDisabled?null:this.directRealtimeBaseUrl}disableDirectRealtime(){this.directRealtimeDisabled=!0}getAppId(){return this.config.appId}async refreshAccessToken(e){let t=e?.silent??!1;if(this.isRefreshing)return this.refreshPromise;if(Date.now()<this.refreshLockedUntil){let r=new I("Token refresh locked due to repeated failures. Please login again.");throw this.emitError(r),this.config.onAuthError?.(r),r}if(!this.config.refreshToken&&this.isNoCookieSessionMarkFresh())throw new I("No cookie session (recently rejected). Skipping token refresh.");if(this.isRefreshing=!0,!this.config.refreshToken&&typeof window>"u"){this.isRefreshing=!1,this.config.onTokenExpired?.();let r=new I("Refresh token is missing. Please login again.");throw this.emitError(r),this.config.onAuthError?.(r),r}return this.refreshPromise=(async()=>{let{signal:r,cleanup:i}=A({timeout:this.config.requestTimeoutMs??3e4}),o="transient";try{let a={"Content-Type":"application/json"};this.config.refreshToken&&(a.Authorization=`Bearer ${this.config.refreshToken}`);let c=this.getCredential();c&&(a["X-Public-Key"]=c);let l=!this.config.refreshToken,u=await U(fetch(`${this.config.baseUrl}/v1/auth/re-issue${l?"?quiet=1":""}`,{method:"POST",headers:a,credentials:"include",signal:r}),r);if(l&&u.status===204)throw o="permanent",new Error("Token refresh failed (no session)");if(!u.ok){let p=u.status,f;try{let m=await u.clone().json();m&&typeof m.error=="string"?f=m.error:m&&typeof m.code=="string"&&(f=m.code)}catch{}throw p>=500?new Error(`Token refresh failed (${p})`):(p===401||p===403||p===400&&(f==="invalid_grant"||f==="invalid_token")?o="permanent":o="client_bug",new Error(`Token refresh failed (${p}${f?` ${f}`:""})`))}let d=await u.json();if(!d||typeof d.access_token!="string")throw new Error("Token refresh response missing access_token");if(ot(d.access_token))return this.refreshFailureCount=0,this.refreshLockedUntil=0,null;if(this.config.appId){let p=Y(d.access_token)?.app_id;if(typeof p=="string"&&p!==this.config.appId)return this.clearTokens(),this.refreshFailureCount=0,this.refreshLockedUntil=0,null}let h=typeof d.refresh_token=="string"&&d.refresh_token.length>0?d.refresh_token:this.config.refreshToken??"";return h?this.setTokens(d.access_token,h):(this.config.accessToken=d.access_token,this.persistTokens()),this.config.onTokenRefresh?.({accessToken:d.access_token,refreshToken:h}),this.refreshFailureCount=0,this.refreshLockedUntil=0,this.clearNoCookieSessionMark(),d.access_token}catch(a){let c=a instanceof Error?a.message:"Token refresh failed";this.refreshFailureCount++;let l=Math.min(500*2**Math.max(0,this.refreshFailureCount-1),3e4);if(this.refreshLockedUntil=Date.now()+l,o==="permanent"&&!this.config.refreshToken&&this.markNoCookieSession(),o==="permanent"){t||(this.clearTokens(),this.config.onTokenExpired?.());let d=new I(`${c}. Please login again.`);throw t||(this.emitError(d),this.config.onAuthError?.(d)),d}if(o==="client_bug"){let d=new I(`${c}. Client request invalid; tokens preserved.`);throw t||(this.emitError(d),this.config.onAuthError?.(d)),d}let u=new I(`${c}. Transient failure; tokens preserved, will retry after backoff.`);throw t||(this.emitError(u),this.config.onTransientRefreshFailure?.(u),this.config.onAuthError?.(u)),u}finally{i(),this.isRefreshing=!1,this.refreshPromise=null}})(),this.refreshPromise}async tryRestoreSessionFromCookie(){if(typeof window>"u")return!1;if(this.config.accessToken&&!this.isTokenExpired(this.config.accessToken))return!0;try{return!!await this.refreshAccessToken()}catch{return!1}}emitError(e){try{this.config.onError?.(e)}catch{}}isTokenExpired(e){return F(e,300)}canRefreshMemberToken(e){let t=this.config.accessToken;return!e||!t||!nt(e,t)?!1:!!this.config.refreshToken||typeof window<"u"}async freshTokenForMember(e,t,s){if(!this.canRefreshMemberToken(e))return;let r=this.config.accessToken,i=s?.replace===!0&&r===e;if(r&&!i&&!F(r,t))return r;try{let o=await this.refreshAccessToken();return o&&nt(o,e)?o:void 0}catch{return}}async prepareHeaders(e){let t=new Headers;t.set("Content-Type","application/json");let s=this.getCredential();if(s&&t.set("X-Public-Key",s),!e?.skipAuth&&!this.config.accessToken&&this.config.publicKey&&typeof window<"u"&&this.bootRestorePromise&&(this.bootRestoreAlwaysAwait||this.hasSessionHint()))try{await this.bootRestorePromise}catch{}if(!e?.skipAuth&&this.config.accessToken){let r=this.config.accessToken;if(this.isTokenExpired(r)&&this.config.refreshToken){let i=await this.refreshAccessToken();i&&(r=i)}ot(r)||t.set("Authorization",`Bearer ${r}`)}else!e?.skipAuth&&this.config.publicKey&&this.config.secretKey&&!t.has("Authorization")&&t.set("Authorization",`Bearer ${this.config.secretKey}`);return!e?.skipAuth&&this.config.secretKey&&t.set("X-User-Secret-Key",this.config.secretKey),e?.headers&&Object.entries(e.headers).forEach(([r,i])=>{t.set(r,i)}),t}async buildApiError(e){let t={},s=!0;try{t=await e.json()}catch{s=!1}let r=e.status===429?e.headers.get("Retry-After"):null,i;if(r){let f=Number.parseInt(r,10);if(Number.isFinite(f)&&f>=0)i=f;else{let m=Date.parse(r);Number.isFinite(m)&&(i=Math.max(0,Math.round((m-Date.now())/1e3)))}}let o=t.error;if(o&&typeof o=="object"&&"message"in o){let f=o,m={...f.details&&typeof f.details=="object"?f.details:{}};return i!==void 0&&(m.retry_after_seconds=i),new b(e.status,typeof f.message=="string"&&f.message!==""?f.message:"Unknown error",typeof f.code=="string"?f.code:void 0,Object.keys(m).length>0?m:void 0)}let a=typeof t.message=="string"&&t.message!==""?t.message:void 0,c=typeof t.code=="string"&&t.code!==""?t.code:void 0,l=typeof o=="string"&&/^[a-z][a-z0-9_]*$/.test(o),u=a??(typeof o=="string"&&o!==""?o:void 0)??(s?void 0:ns(e.status))??(e.statusText!==""?e.statusText:"Unknown error"),d=c??(l?o:void 0)??is(e.status),h={};return i!==void 0&&(h.retry_after_seconds=i),typeof t.provider=="string"&&(h.provider=t.provider),typeof t.model=="string"&&(h.model=t.model),new b(e.status,u,d,Object.keys(h).length>0?h:void 0)}async handleResponse(e){if(!e.ok){let t=await this.buildApiError(e);throw this.emitError(t),t}return e.status===204||e.headers.get("content-length")==="0"?{}:e.json()}async doFetch(e,t,s){let r=Date.now(),i=0;try{let o=await this.tryFetchOnce(e,t,s);if(i=o.status,!o.ok&&o.status===401&&!s?.skipAuth&&this.config.publicKey&&typeof window<"u"&&await this.tryRestoreSessionFromCookie()){let c=await this.prepareHeaders(s);t.body instanceof FormData&&c.delete("Content-Type");let l=await this.tryFetchOnce(e,{...t,headers:c},s);return i=l.status,await this.handleResponse(l.response)}return await this.handleResponse(o.response)}finally{this.recentCalls.push({method:(t.method||"GET").toUpperCase(),path:rt(e),status:i,duration_ms:Date.now()-r,timestamp:new Date().toISOString()})}}resolveOrigin(e,t){return t||(this.directBaseUrl&&!this.directDisabled&&ue(e)==="omit"?this.directBaseUrl:this.config.baseUrl)}learnDirectOrigin(e){e.headers&&this.adoptDirectBases(e.headers.get("X-CB-Direct-Base"),e.headers.get("X-CB-Realtime-Direct-Base"))}adoptDirectBases(e,t){let s=i=>i.split(".").slice(-2).join("."),r=null;try{r=new URL(this.config.baseUrl)}catch{}if(r&&!this.directDisabled&&!this.directBaseUrl&&typeof e=="string"&&e)try{let i=new URL(e);i.protocol==="https:"&&s(i.hostname)===s(r.hostname)&&(this.directBaseUrl=i.origin)}catch{}if(!this.directRealtimeDisabled&&!this.directRealtimeBaseUrl&&typeof t=="string"&&t){let i=r?s(r.hostname):"connectbase.world";try{let o=new URL(t);o.protocol==="wss:"&&s(o.hostname)===i&&(this.directRealtimeBaseUrl=o.origin)}catch{}}}async primeEdgeHints(e){if(this.directRealtimeBaseUrl||this.directRealtimeDisabled)return;let t=await as(this.config.baseUrl,e);for(let s of t)this.adoptDirectBases(s.direct,s.realtime)}async fetchPassthrough(e,t){let s=this.resolveOrigin(e);try{let r=await fetch(`${s}${e}`,t);return this.learnDirectOrigin(r),r}catch(r){if(s!==this.config.baseUrl&&!Fe(r))return this.directDisabled=!0,fetch(`${this.config.baseUrl}${e}`,t);throw r}}async tryFetchOnce(e,t,s){let{signal:r,cleanup:i}=A({timeout:s?.timeout??this.config.requestTimeoutMs??3e4,signal:s?.signal}),o=this.resolveOrigin(e,s?.baseUrl);try{let a=await U(fetch(`${o}${e}`,{...t,credentials:ue(e),signal:r}),r);return s?.baseUrl||this.learnDirectOrigin(a),{response:a,ok:a.ok,status:a.status}}catch(a){if(!s?.baseUrl&&o!==this.config.baseUrl&&!Fe(a)){this.directDisabled=!0;let c=await U(fetch(`${this.config.baseUrl}${e}`,{...t,credentials:ue(e),signal:r}),r);return{response:c,ok:c.ok,status:c.status}}throw a}finally{i()}}async get(e,t){let s=await this.prepareHeaders(t);return this.doFetch(e,{method:"GET",headers:s},t)}async post(e,t,s){let r=await this.prepareHeaders(s);return t instanceof FormData&&r.delete("Content-Type"),this.doFetch(e,{method:"POST",headers:r,body:t instanceof FormData?t:JSON.stringify(t)},s)}async put(e,t,s){let r=await this.prepareHeaders(s);return t instanceof FormData&&r.delete("Content-Type"),this.doFetch(e,{method:"PUT",headers:r,body:t instanceof FormData?t:JSON.stringify(t)},s)}async patch(e,t,s){let r=await this.prepareHeaders(s);return this.doFetch(e,{method:"PATCH",headers:r,body:JSON.stringify(t)},s)}async delete(e,t){let s=await this.prepareHeaders(t);return this.doFetch(e,{method:"DELETE",headers:s},t)}async fetchRaw(e,t){let s=await this.prepareHeaders(),r=new Headers(s);t?.headers&&new Headers(t.headers).forEach((a,c)=>r.set(c,a));let i=this.resolveOrigin(e);try{let o=await fetch(`${i}${e}`,{...t,credentials:ue(e),headers:r});return this.learnDirectOrigin(o),o}catch(o){throw i!==this.config.baseUrl&&!Fe(o)&&(this.directDisabled=!0),o}}};var C=class extends Error{constructor(e){super(e.message||e.code||`WebSocket ticket request failed (${e.status})`),this.name="WsTicketError",this.status=e.status,this.code=e.code||"ws_ticket_rejected",this.retryAfterMs=e.retryAfterMs}},at=5e3,ct=new Set;function ls(n,e){try{return`${new URL(n).origin}|${e}`}catch{return`${n}|${e}`}}async function x(n,e,t,s={}){let r=ls(n,e);if(ct.has(r))return null;let i={};t.kind==="access_token"?i.Authorization=`Bearer ${t.value}`:i["X-Public-Key"]=t.value;let{signal:o,cleanup:a}=A({timeout:Math.max(1,Math.min(s.timeoutMs??at,at)),signal:s.signal}),c;try{c=await U(fetch(n,{method:"POST",headers:i,credentials:"omit",signal:o}),o)}catch(l){if(a(),s.signal?.aborted)throw l;return null}try{if(c.ok){let m=await c.json().catch(()=>null);return typeof m?.ticket=="string"&&m.ticket!==""?m.ticket:null}if(c.status===404||c.status===405||c.status===501)return ct.add(r),null;if(c.status>=500)return null;let l=await c.json().catch(()=>null),u=typeof l?.error=="string"?l.error:void 0,h=u!==void 0&&/^[a-z0-9_]+$/.test(u)?u:us(c.status),p=typeof l?.message=="string"?l.message:u,f=typeof l?.retry_after_ms=="number"&&l.retry_after_ms>0?l.retry_after_ms:void 0;throw new C({status:c.status,code:h,message:p,retryAfterMs:f})}finally{a()}}function us(n){switch(n){case 401:return"unauthorized";case 402:return"quota_exceeded";case 403:return"forbidden";case 429:return"rate_limited";default:return"ws_ticket_rejected"}}function $(n,e){return`${n.replace(/^ws(s?):\/\//,"http$1://").replace(/\/+$/,"")}${e}`}var ds=600,lt=60,ut=15e3,ps=3e4,hs=new Set(["TOKEN_EXPIRED","MEMBER_REVOKED"]),ms=4401,dt=4403;function gs(n){if(n.type!=="error"||n.request_id||typeof n.close_code!="number")return null;let e=n.details;return new R({code:typeof n.code=="string"?n.code:void 0,message:typeof n.message=="string"?n.message:void 0,closeCode:n.close_code,retryable:typeof n.retryable=="boolean"?n.retryable:void 0,details:e&&typeof e=="object"&&!Array.isArray(e)?e:void 0,retryAfterMs:typeof n.retry_after_ms=="number"&&n.retry_after_ms>0?n.retry_after_ms:void 0})}var he=class{constructor(e){this.realtimeWs=null;this.realtimeState="disconnected";this.realtimeHandlers=new Map;this.realtimeRetryCount=0;this.realtimeOptions=null;this.pendingRequests=new Map;this.pingInterval=null;this.realtimeOnStateChange=null;this.realtimeOnError=null;this.realtimeTokenRefresh=!1;this.realtimeAuthRefreshInFlight=null;this.realtimeAuthRetryTimer=null;this.realtimeCloseNotice=null;this.activeSubscriptions=new Map;this.http=e}getPublicPrefix(){return"/v1/public"}async getTables(){let e=this.getPublicPrefix();return(await this.http.get(`${e}/tables`)).tables}async getTable(e){let t=this.getPublicPrefix();return this.http.get(`${t}/tables/${e}`)}async createTable(e){let t=this.getPublicPrefix(),s={title:e.name,access_level:e.accessLevel??"Creator"};e.schema&&Object.keys(e.schema).length>0&&(s.schema=e.schema),await this.http.post(`${t}/tables`,s)}async updateTable(e,t){let s=this.getPublicPrefix(),r={};t.name!==void 0&&(r.title=t.name),t.schema!==void 0&&(r.schema=t.schema),t.accessLevel!==void 0&&(r.access_level=t.accessLevel),t.description!==void 0&&(r.description=t.description),await this.http.patch(`${s}/tables/${e}`,r)}async deleteTable(e){let t=this.getPublicPrefix();await this.http.delete(`${t}/tables/${e}`)}async getValidationSchema(e){let t=this.getPublicPrefix();return(await this.http.get(`${t}/tables/${e}/validation-schema`)).validation_schema}async setValidationSchema(e,t){await this.http.put(`/v1/apps/${this.requireAppId()}/databases/tables/${e}/validation-schema`,{validation_schema:t})}async deleteValidationSchema(e){await this.http.delete(`/v1/apps/${this.requireAppId()}/databases/tables/${e}/validation-schema`)}requireAppId(){let e=this.http.getAppId();if(!e)throw new Error("setValidationSchema/deleteValidationSchema \uB294 \uCF58\uC194 (JWT) \uC778\uC99D\uC774 \uD544\uC694\uD558\uBA70 ConnectBase config \uC5D0 appId \uAC00 \uC124\uC815\uB418\uC5B4\uC57C \uD569\uB2C8\uB2E4.");return e}async getColumns(e){let t=await this.getTable(e),s=t.schema??{},r=new Set(Array.isArray(s.$required)?s.$required:[]),i=[],o=0;for(let[a,c]of Object.entries(s)){if(a.startsWith("$")||c===void 0||Array.isArray(c))continue;let l="string",u=r.has(a),d,h,p;typeof c=="string"?l=c:(l=c.type,c.required===!0&&(u=!0),c.default!==void 0&&(d=c.default),c.description!==void 0&&(h=c.description),c.encrypted!==void 0&&(p=c.encrypted)),i.push({id:a,name:a,data_type:l,is_required:u,default_value:d,description:h,encrypted:p,order:o++,created_at:t.created_at})}return i}async createColumn(e,t){let s=this.getPublicPrefix();await this.http.post(`${s}/tables/${e}/columns`,t)}async updateColumn(e,t,s){let r=this.getPublicPrefix();await this.http.patch(`${r}/tables/${e}/columns/${t}`,s)}async deleteColumn(e,t){let s=this.getPublicPrefix();await this.http.delete(`${s}/tables/${e}/columns/${t}`)}async getData(e,t){let s=this.getPublicPrefix();if(t?.where||t?.select||t?.exclude)return this.queryData(e,t);let r=new URLSearchParams;t?.limit&&r.append("limit",t.limit.toString()),t?.offset&&r.append("offset",t.offset.toString()),t?.count===!1&&r.append("count","false"),t?.cursor&&r.append("cursor",t.cursor);let i=r.toString(),o=i?`${s}/tables/${e}/data?${i}`:`${s}/tables/${e}/data`;return this.http.get(o)}async queryData(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/tables/${e}/data/query`,{where:t.where,order_by:t.orderBy,order_direction:t.orderDirection,limit:t.limit,offset:t.offset,select:t.select,exclude:t.exclude,count:t.count,cursor:t.cursor})}async getDataById(e,t){let s=this.getPublicPrefix();return this.http.get(`${s}/tables/${e}/data/${t}`)}async createData(e,t,s){let r=this.getPublicPrefix();if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))return this.http.post(`${r}/tables/${e}/data`,t);let o=s?.autoCreate?"?auto_create=true":"";return this.http.post(`${r}/tables/name/${encodeURIComponent(e)}/data${o}`,t)}async updateData(e,t,s){let r=this.getPublicPrefix();return this.http.patch(`${r}/tables/${e}/data/${t}`,s)}async deleteData(e,t){let s=this.getPublicPrefix();await this.http.delete(`${s}/tables/${e}/data/${t}`)}async createMany(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/tables/${e}/data/bulk`,{data:t.map(r=>r.data)})}async deleteWhere(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/tables/${e}/data/delete-where`,{where:t})}async aggregate(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/aggregate`,{table_id:e,pipeline:t})}async search(e,t,s,r){let i=this.getPublicPrefix();return this.http.post(`${i}/search`,{table_id:e,query:t,fields:s,options:r})}async autocomplete(e,t,s,r){let i=this.getPublicPrefix();return this.http.post(`${i}/autocomplete`,{table_id:e,query:t,field:s,...r})}async geoQuery(e,t,s,r){let i=this.getPublicPrefix();return this.http.post(`${i}/geo`,{table_id:e,field:t,query:s,...r})}async batch(e){let t=this.getPublicPrefix(),s=await this.http.post(`${t}/batch`,{operations:e});if(s&&s.success===!1){let r=s.results?.find(i=>i&&i.success===!1);throw new Error(r?.error||"batch operation failed")}return s}async transaction(e,t){let s=this.getPublicPrefix(),r=await this.http.post(`${s}/transactions`,{reads:e,writes:t});if(r&&r.success===!1)throw new Error(r.error||"transaction failed");return r}async getDataWithPopulate(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/tables/${e}/data/query`,{where:t.where,order_by:t.orderBy,order_direction:t.orderDirection,limit:t.limit,offset:t.offset,select:t.select,exclude:t.exclude,populate:t.populate,count:t.count})}async listSecurityRules(e){return(await this.http.get(`/v1/apps/${e}/databases/security/rules`)).rules}async createSecurityRule(e,t){return this.http.post(`/v1/apps/${e}/databases/security/rules`,t)}async updateSecurityRule(e,t,s){return this.http.put(`/v1/apps/${e}/databases/security/rules/${t}`,s)}async deleteSecurityRule(e,t){await this.http.delete(`/v1/apps/${e}/databases/security/rules/${t}`)}async listIndexes(e,t){return(await this.http.get(`/v1/apps/${e}/databases/tables/${t}/indexes`)).indexes}async createIndex(e,t,s){return this.http.post(`/v1/apps/${e}/databases/tables/${t}/indexes`,s)}async deleteIndex(e,t,s){await this.http.delete(`/v1/apps/${e}/databases/tables/${t}/indexes/${s}`)}async analyzeIndexes(e,t){return this.http.get(`/v1/apps/${e}/databases/tables/${t}/indexes/analyze`)}async listSearchIndexes(e,t){return(await this.http.get(`/v1/apps/${e}/databases/tables/${t}/search-indexes`)).indexes}async createSearchIndex(e,t,s){return this.http.post(`/v1/apps/${e}/databases/tables/${t}/search-indexes`,s)}async deleteSearchIndex(e,t,s){await this.http.delete(`/v1/apps/${e}/databases/tables/${t}/search-indexes/${s}`)}async listGeoIndexes(e,t){return(await this.http.get(`/v1/apps/${e}/databases/tables/${t}/geo-indexes`)).indexes}async createGeoIndex(e,t,s){return this.http.post(`/v1/apps/${e}/databases/tables/${t}/geo-indexes`,s)}async deleteGeoIndex(e,t,s){await this.http.delete(`/v1/apps/${e}/databases/tables/${t}/geo-indexes/${s}`)}async listRelations(e,t){let s=t?`?source_table=${encodeURIComponent(t)}`:"";return(await this.http.get(`/v1/apps/${e}/databases/relations${s}`)).relations}async createRelation(e,t){return this.http.post(`/v1/apps/${e}/databases/relations`,t)}async deleteRelation(e,t){await this.http.delete(`/v1/apps/${e}/databases/relations/${t}`)}async listTriggers(e){return(await this.http.get(`/v1/apps/${e}/databases/triggers`)).triggers}async createTrigger(e,t){return this.http.post(`/v1/apps/${e}/databases/triggers`,t)}async updateTrigger(e,t,s){return this.http.put(`/v1/apps/${e}/databases/triggers/${t}`,s)}async deleteTrigger(e,t){await this.http.delete(`/v1/apps/${e}/databases/triggers/${t}`)}async setTTL(e,t){return this.http.post(`/v1/apps/${e}/lifecycle/ttl`,t)}async getTTL(e,t){return this.http.get(`/v1/apps/${e}/lifecycle/ttl/${t}`)}async setRetentionPolicy(e,t){return this.http.post(`/v1/apps/${e}/lifecycle/retention`,t)}async getRetentionPolicy(e,t){return this.http.get(`/v1/apps/${e}/lifecycle/retention/${t}`)}async setArchivePolicy(e,t){return this.http.post(`/v1/apps/${e}/lifecycle/archive`,t)}async getArchivePolicy(e,t){return this.http.get(`/v1/apps/${e}/lifecycle/archive/${t}`)}async executeTTL(e,t){return this.http.post(`/v1/apps/${e}/lifecycle/ttl/${t}/execute`,{})}async executeArchive(e,t){return this.http.post(`/v1/apps/${e}/lifecycle/archive/${t}/execute`,{})}async executeRetention(e,t){return this.http.post(`/v1/apps/${e}/lifecycle/retention/${t}/execute`,{})}async listPolicies(e){return(await this.http.get(`/v1/apps/${e}/lifecycle`)).policies}async deletePolicy(e,t){await this.http.delete(`/v1/apps/${e}/lifecycle/${t}`)}async generateTypes(e){return this.http.get(`/v1/apps/${e}/types`)}async listBackups(e){return this.http.get(`/v1/apps/${e}/backups`)}async createBackup(e,t){return this.http.post(`/v1/apps/${e}/backups`,t)}async getBackup(e,t){return this.http.get(`/v1/apps/${e}/backups/${t}`)}async deleteBackup(e,t){await this.http.delete(`/v1/apps/${e}/backups/${t}`)}async restoreBackup(e,t,s){return this.http.post(`/v1/apps/${e}/backups/${t}/restore`,s||{backup_id:t})}async exportData(e,t){return this.http.post(`/v1/apps/${e}/data/export`,t||{format:"json"})}async importData(e,t){return this.http.post(`/v1/apps/${e}/data/import`,t)}async copyTable(e,t){return this.http.post(`/v1/apps/${e}/tables/copy`,t)}async migrateData(e,t){return this.http.post(`/v1/apps/${e}/tables/migrate`,t)}connectRealtime(e){return this.realtimeState==="connected"?Promise.resolve():this.realtimeState==="connecting"?Promise.reject(new Error("Already connecting")):(this.realtimeOptions={...e},this.realtimeRetryCount=0,this.connectRealtimeSocket())}disconnectRealtime(){this.realtimeOptions=null,this.setRealtimeState("disconnected"),this.realtimeRetryCount=0,this.stopRealtimePing(),this.clearRealtimeAuthRetry(),this.realtimeTokenRefresh=!1,this.realtimeCloseNotice=null,this.realtimeWs&&(this.realtimeWs.close(),this.realtimeWs=null),this.pendingRequests.forEach(e=>{clearTimeout(e.timeout),e.reject(new Error("Connection closed"))}),this.pendingRequests.clear(),this.realtimeHandlers.clear(),this.activeSubscriptions.clear()}subscribe(e,t,s){if(this.realtimeState!=="connected")throw new Error("Not connected. Call connectRealtime() first.");let r=`csub_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;this.activeSubscriptions.set(r,{tableId:e,options:s,handlers:t});let i=this.sendSubscribeRequest(e,t,s);return i.catch(o=>{this.activeSubscriptions.delete(r),t.onError?.(o instanceof Error?o:new Error(String(o)))}),{subscriptionId:r,unsubscribe:()=>{this.activeSubscriptions.delete(r),i.then(o=>{this.realtimeHandlers.delete(o),this.realtimeState==="connected"&&this.sendRealtimeMessage({type:"unsubscribe",request_id:this.generateRequestId(),subscription_id:o})}).catch(()=>{})},loadMore:(o,a)=>{this.realtimeState==="connected"&&i.then(c=>{let l={type:"snapshot_more",request_id:this.generateRequestId(),subscription_id:c,offset:o};a!==void 0&&(l.limit=a),this.sendRealtimeMessage(l)}).catch(()=>{})}}}isRealtimeConnected(){return this.realtimeState==="connected"}getRealtimeState(){return this.realtimeState}onRealtimeStateChange(e){return this.realtimeOnStateChange=e,()=>{this.realtimeOnStateChange=null}}onRealtimeError(e){return this.realtimeOnError=e,()=>{this.realtimeOnError=null}}setRealtimeState(e){this.realtimeState!==e&&(this.realtimeState=e,this.realtimeOnStateChange?.(e))}async connectRealtimeSocket(){this.setRealtimeState("connecting");let e=this.realtimeOptions;if(e&&this.http.canRefreshMemberToken(e.accessToken)&&F(e.accessToken,lt)){let s=await this.http.freshTokenForMember(e.accessToken,lt);s&&(e.accessToken=s)}let t;try{t=await this.realtimeTicket()}catch(s){if(s instanceof C){let r=new R({code:s.code,message:s.message,closeCode:4e3+s.status,retryAfterMs:s.retryAfterMs});throw this.handleRealtimeRejection(r),r}throw s}return this.doRealtimeConnect(t)}async realtimeTicket(){let e=this.realtimeOptions;if(!e?.accessToken)return null;let t=e.dataServerUrl||this.http.getBaseUrl();return x($(t,"/v1/database/realtime/ws-ticket"),"data.realtime",{kind:"access_token",value:e.accessToken},{timeoutMs:ut})}doRealtimeConnect(e=null){if(!this.realtimeOptions)return Promise.reject(new Error("No realtime options"));this.setRealtimeState("connecting");let s=(this.realtimeOptions.dataServerUrl||this.http.getBaseUrl()).replace(/^http/,"ws"),r=e?`${s}/v1/database/realtime/ws?ticket=${encodeURIComponent(e)}`:`${s}/v1/database/realtime/ws?access_token=${encodeURIComponent(this.realtimeOptions.accessToken)}`;return this.realtimeTokenRefresh=this.http.canRefreshMemberToken(this.realtimeOptions.accessToken),this.realtimeTokenRefresh&&(r+="&token_refresh=1"),r+="&reject_mode=close",new Promise((i,o)=>{try{let a=new WebSocket(r);this.realtimeWs=a;let c=!1,l=!1,u=null,d=setTimeout(()=>{c||(c=!0,this.realtimeWs&&(this.realtimeWs.close(),this.realtimeWs=null),this.setRealtimeState("disconnected"),o(new Error("Connection timeout")))},ut),h=()=>{l=!0,c||(c=!0,clearTimeout(d)),this.setRealtimeState("connected"),this.realtimeRetryCount=0,this.realtimeCloseNotice=null,this.startRealtimePing(),this.debugLog("Database realtime connected"),this.resubscribeAll(),i()};a.onopen=()=>{a.send(JSON.stringify({type:"ping",timestamp:Date.now()}))},a.onmessage=p=>{let f;try{f=JSON.parse(p.data)}catch{this.debugLog("Failed to parse realtime message");return}if(!l){let m=gs(f);if(m){u=m;return}h()}this.handleRealtimeMessage(f)},a.onclose=p=>{this.debugLog(`Database realtime disconnected (code=${p?.code}, reason=${p?.reason})`),this.realtimeWs=null,this.stopRealtimePing(),this.clearRealtimeAuthRetry();let f=this.realtimeCloseNotice;this.realtimeCloseNotice=null;let m=p?.code;if(!l&&m>=4e3&&m<=4999){let g=u??new R({code:p.reason||void 0,closeCode:m});c||(c=!0,clearTimeout(d),o(g)),this.handleRealtimeRejection(g);return}if(c||(c=!0,clearTimeout(d),o(new Error("Connection closed during handshake"))),this.realtimeOptions&&this.realtimeState!=="disconnected"&&(m===dt||m===ms&&!this.http.canRefreshMemberToken(this.realtimeOptions.accessToken))){this.setRealtimeState("disconnected"),this.realtimeOnError?.(new R({code:p.reason||(m===dt?"member_revoked":"token_expired"),closeCode:m,message:f??void 0}));return}this.realtimeOptions&&this.realtimeState!=="disconnected"&&this.attemptRealtimeReconnect()},a.onerror=()=>{this.debugLog("Database realtime error"),this.realtimeOnError?.(new Error("WebSocket connection error"))}}catch(a){this.setRealtimeState("disconnected"),o(a)}})}handleRealtimeRejection(e){if(!(!this.realtimeOptions||this.realtimeState==="disconnected")){if(e.retryable){this.attemptRealtimeReconnect(e);return}this.setRealtimeState("disconnected"),this.realtimeOnError?.(e)}}sendSubscribeRequest(e,t,s){let r=this.generateRequestId();this.realtimeHandlers.set(r,t);let i=s?.where?{filters:s.where.map(o=>({field:o.field,operator:o.operator,value:o.value}))}:void 0;return this.sendRealtimeMessage({type:"subscribe",request_id:r,table_id:e,doc_id:s?.docId,query:i,options:{include_self:s?.includeSelf??!1,include_metadata_changes:s?.includeMetadataChanges??!1}}),new Promise((o,a)=>{let c=setTimeout(()=>{this.pendingRequests.delete(r),this.realtimeHandlers.delete(r),a(new Error("Subscribe request timeout"))},3e4);this.pendingRequests.set(r,{resolve:l=>{let u=l,d=this.realtimeHandlers.get(r);d&&(this.realtimeHandlers.delete(r),this.realtimeHandlers.set(u,d)),o(u)},reject:a,timeout:c})})}resubscribeAll(){if(this.activeSubscriptions.size!==0){this.realtimeHandlers.clear(),this.pendingRequests.forEach(e=>clearTimeout(e.timeout)),this.pendingRequests.clear(),this.debugLog(`Resubscribing ${this.activeSubscriptions.size} subscriptions`);for(let[,e]of this.activeSubscriptions)this.sendSubscribeRequest(e.tableId,e.handlers,e.options).catch(t=>{e.handlers.onError?.(t instanceof Error?t:new Error(String(t)))})}}handleRealtimeMessage(e){let t=e.type;switch(t){case"subscribed":{let s=e.request_id,r=e.subscription_id,i=this.pendingRequests.get(s);i&&(clearTimeout(i.timeout),i.resolve(r),this.pendingRequests.delete(s));break}case"snapshot":{let s=e.subscription_id,r=this.realtimeHandlers.get(s);if(r?.onSnapshot){let i=e.docs||[],o=e.has_more||!1,a=o?e.next_offset:void 0;r.onSnapshot(i,{totalCount:e.total_count||0,hasMore:o,nextOffset:a})}break}case"change":{let s=e.subscription_id,r=this.realtimeHandlers.get(s);if(r?.onChange){let i=e.changes||[];r.onChange(i)}break}case"presence":{let s=this.realtimeHandlers.get("__presence__");if(s?.onSnapshot){let r=e.states,i=Object.entries(r||{}).map(([o,a])=>({id:o,data:a,exists:!0}));s.onSnapshot(i,{totalCount:i.length,hasMore:!1})}break}case"token_expiring":case"token_expired":{this.debugLog(`Server sent ${t}; refreshing the access token`),this.refreshRealtimeAuth();break}case"token_refreshed":{let s=e.request_id,r=s?this.pendingRequests.get(s):void 0;r&&(clearTimeout(r.timeout),r.resolve(e),this.pendingRequests.delete(s));break}case"error":{let s=e.request_id,r=e.message||"Unknown error";if(!s&&hs.has(e.code)){this.realtimeCloseNotice=r;break}if(s){let i=this.pendingRequests.get(s);i&&(clearTimeout(i.timeout),i.reject(new Error(r)),this.pendingRequests.delete(s));let o=this.realtimeHandlers.get(s);o?.onError&&o.onError(new Error(r))}else this.realtimeOnError?.(new Error(r));break}case"pong":break;case"unsubscribed":case"presence_set_ack":case"presence_subscribed":case"typing_subscribed":break}}attemptRealtimeReconnect(e){let t=this.realtimeOptions?.maxRetries??5,s=this.realtimeOptions?.retryInterval??1e3;if(this.realtimeRetryCount>=t){this.setRealtimeState("disconnected"),this.realtimeOnError?.(e??new Error("Realtime connection lost. Max retries exceeded."));return}this.setRealtimeState("connecting"),this.realtimeRetryCount++;let r=Math.max(Math.min(s*2**(this.realtimeRetryCount-1),3e4),e?.retryAfterMs??0);this.debugLog(`Reconnecting in ${r}ms (attempt ${this.realtimeRetryCount}/${t})`),setTimeout(()=>{this.realtimeOptions&&this.connectRealtimeSocket().catch(i=>{this.debugLog(`Reconnect failed: ${i}`)})},r)}startRealtimePing(){this.stopRealtimePing(),this.pingInterval=setInterval(()=>{this.realtimeState==="connected"&&this.realtimeWs?.readyState===WebSocket.OPEN&&this.sendRealtimeMessage({type:"ping",timestamp:Date.now()})},3e4)}stopRealtimePing(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null)}sendRealtimeMessage(e){this.realtimeWs?.readyState===WebSocket.OPEN&&this.realtimeWs.send(JSON.stringify(e))}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}refreshRealtimeAuth(){let e=this.realtimeOptions;if(!this.realtimeTokenRefresh||!e||this.realtimeState!=="connected")return Promise.resolve(!1);if(this.realtimeAuthRefreshInFlight)return this.realtimeAuthRefreshInFlight;this.clearRealtimeAuthRetry();let t=(async()=>{let s=e.accessToken;try{let r=await this.http.freshTokenForMember(s,ds,{replace:!0});if(!r||r===s)throw new Error("No fresh access token from the SDK session");return await this.sendRealtimeRequest({type:"auth_refresh",access_token:r}),e.accessToken=r,this.realtimeCloseNotice=null,this.debugLog("Access token refreshed over the connection"),!0}catch(r){return this.debugLog(`auth_refresh failed: ${r instanceof Error?r.message:String(r)}`),this.realtimeOptions===e&&this.http.canRefreshMemberToken(e.accessToken)&&this.scheduleRealtimeAuthRetry(),!1}finally{this.realtimeAuthRefreshInFlight=null}})();return this.realtimeAuthRefreshInFlight=t,t}sendRealtimeRequest(e){let t=this.generateRequestId();return new Promise((s,r)=>{if(this.realtimeWs?.readyState!==WebSocket.OPEN){r(new Error("Not connected"));return}let i=setTimeout(()=>{this.pendingRequests.delete(t),r(new Error("Request timeout"))},3e4);this.pendingRequests.set(t,{resolve:s,reject:r,timeout:i}),this.sendRealtimeMessage({...e,request_id:t})})}scheduleRealtimeAuthRetry(){this.realtimeAuthRetryTimer||!this.realtimeTokenRefresh||(this.realtimeAuthRetryTimer=setTimeout(()=>{this.realtimeAuthRetryTimer=null,this.refreshRealtimeAuth()},ps))}clearRealtimeAuthRetry(){this.realtimeAuthRetryTimer&&(clearTimeout(this.realtimeAuthRetryTimer),this.realtimeAuthRetryTimer=null)}debugLog(e){this.realtimeOptions?.debug&&console.log(`[DatabaseRealtime] ${e}`)}};var G=class{constructor(e){this.http=e}async call(e,t){if(!e)throw new Error("EndpointAPI.call: label required");if(!t.path||!t.path.startsWith("/"))throw new Error(`EndpointAPI.call: path must start with '/', got ${JSON.stringify(t.path)}`);let s=this.proxyPath(e,t.path),r=new Headers(t.headers??{});if(!r.has("X-Public-Key")){let i=this.http.getPublicKey();if(!i)throw new Error("EndpointAPI.call: publicKey not configured. Pass `publicKey` to ConnectBase constructor.");r.set("X-Public-Key",i)}return this.http.fetchPassthrough(s,{method:t.method??"GET",headers:r,body:t.body,signal:t.signal,redirect:"follow"})}proxyPath(e,t){if(!e)throw new Error("EndpointAPI.call: label required");if(!t||!t.startsWith("/"))throw new Error(`EndpointAPI.call: path must start with '/', got ${JSON.stringify(t)}`);return`/v1/proxy/${encodeURIComponent(e)}${t}`}url(e,t){if(!e)throw new Error("EndpointAPI.url: label required");if(!t||!t.startsWith("/"))throw new Error(`EndpointAPI.url: path must start with '/', got ${JSON.stringify(t)}`);return`${this.http.getBaseUrl().replace(/\/+$/,"")}/v1/proxy/${encodeURIComponent(e)}${t}`}async connectWebSocket(e,t={}){if(!e)throw new Error("EndpointAPI.connectWebSocket: label required");let s=t.path??"/";if(!s.startsWith("/"))throw new Error(`EndpointAPI.connectWebSocket: path must start with '/', got ${JSON.stringify(s)}`);let r=this.http.getBaseUrl().replace(/\/+$/,""),i=`${r}/v1/proxy/${encodeURIComponent(e)}/ws-ticket`,o=new Headers,a=this.http.getPublicKey();if(!a)throw new Error("EndpointAPI.connectWebSocket: publicKey not configured. Pass `publicKey` to ConnectBase constructor.");o.set("X-Public-Key",a);let c=await fetch(i,{method:"POST",headers:o,signal:t.signal});if(!c.ok){let h=await c.text().catch(()=>"");throw new Error(`EndpointAPI.connectWebSocket: ticket issuance failed (${c.status}) ${h.slice(0,200)}`)}let{ticket:l}=await c.json();if(!l)throw new Error("EndpointAPI.connectWebSocket: server returned empty ticket");let u=new URL(`${r}/v1/proxy/${encodeURIComponent(e)}${s}`);if(u.protocol=u.protocol==="https:"?"wss:":"ws:",t.query)for(let[h,p]of Object.entries(t.query))u.searchParams.set(h,p);u.searchParams.set("ticket",l);let d=t.protocols?new WebSocket(u.toString(),t.protocols):new WebSocket(u.toString());if(t.signal){let h=()=>{try{d.close(1e3,"client aborted")}catch{}};t.signal.aborted?h():t.signal.addEventListener("abort",h,{once:!0})}return d}async pollUntil(e,t,s,r={}){let i=r.intervalMs??1500,o=r.timeoutMs??5*6e4,a=r.parse??"json",c=Date.now();for(;;){if(r.signal?.aborted)throw new DOMException("aborted","AbortError");if(Date.now()-c>o)throw new Error(`EndpointAPI.pollUntil: timeout after ${o}ms (label=${e}, path=${t.path})`);let l;try{l=await this.call(e,{...t,signal:r.signal})}catch(h){if(h.name==="AbortError")throw h;await Ge(i,r.signal);continue}if(l.status>=500){await fs(l),await Ge(i,r.signal);continue}if(l.status>=400){let h=await l.text().catch(()=>"");throw new Error(`EndpointAPI.pollUntil: ${l.status} ${l.statusText} (label=${e}, path=${t.path})${h?` \u2014 ${h.slice(0,200)}`:""}`)}let u;a==="text"?u=await l.text():a==="none"?u=void 0:u=await l.json().catch(()=>{});let d=await s(u,l);if(d!==void 0)return d;await Ge(i,r.signal)}}};async function Ge(n,e){if(e?.aborted)throw new DOMException("aborted","AbortError");return new Promise((t,s)=>{let r=setTimeout(()=>{e?.removeEventListener("abort",i),t()},n),i=()=>{clearTimeout(r),s(new DOMException("aborted","AbortError"))};e?.addEventListener("abort",i,{once:!0})})}async function fs(n){try{await n.text()}catch{}}function bs(n){let e=s=>typeof s=="string"?et(s):s,t=s=>typeof s=="string"?O(s):s;return{...n,message:e(n.message),stack:e(n.stack),url:t(n.url),referrer:t(n.referrer),source:t(n.source)}}var me=class{constructor(e,t={}){this.storageWebId=null;this.errorQueue=[];this.batchTimer=null;this.isInitialized=!1;this.originalOnError=null;this.originalOnUnhandledRejection=null;this.http=e,this.config={autoCapture:t.autoCapture??!0,captureTypes:t.captureTypes??["error","unhandledrejection"],batchInterval:t.batchInterval??5e3,maxBatchSize:t.maxBatchSize??10,beforeSend:t.beforeSend??(s=>s),debug:t.debug??!1}}init(e){if(this.isInitialized){this.log("ErrorTracker already initialized");return}if(typeof window>"u"){this.log("ErrorTracker only works in browser environment");return}this.storageWebId=e,this.isInitialized=!0,this.config.autoCapture&&this.setupAutoCapture(),this.startBatchTimer(),this.log("ErrorTracker initialized",{storageWebId:e})}destroy(){this.stopBatchTimer(),this.removeAutoCapture(),this.flushQueue(),this.isInitialized=!1,this.log("ErrorTracker destroyed")}async captureError(e,t){let s=this.createErrorReport(e,t);s&&this.queueError(s)}async captureMessage(e,t){let s={message:e,error_type:"custom",url:typeof window<"u"?window.location.href:void 0,referrer:typeof document<"u"?document.referrer:void 0,...t};this.queueError(s)}async flush(){await this.flushQueue()}log(...e){this.config.debug&&console.log("[ErrorTracker]",...e)}setupAutoCapture(){typeof window>"u"||(this.config.captureTypes.includes("error")&&(this.originalOnError=window.onerror,window.onerror=(e,t,s,r,i)=>(this.handleGlobalError(e,t,s,r,i),this.originalOnError?this.originalOnError(e,t,s,r,i):!1)),this.config.captureTypes.includes("unhandledrejection")&&(this.originalOnUnhandledRejection=window.onunhandledrejection,window.onunhandledrejection=e=>{this.handleUnhandledRejection(e),this.originalOnUnhandledRejection&&this.originalOnUnhandledRejection(e)}),this.log("Auto capture enabled",{types:this.config.captureTypes}))}removeAutoCapture(){typeof window>"u"||(this.originalOnError!==null&&(window.onerror=this.originalOnError),this.originalOnUnhandledRejection!==null&&(window.onunhandledrejection=this.originalOnUnhandledRejection))}handleGlobalError(e,t,s,r,i){let o={message:typeof e=="string"?e:e.type||"Unknown error",source:t||void 0,lineno:s||void 0,colno:r||void 0,stack:i?.stack,error_type:"error",url:typeof window<"u"?window.location.href:void 0,referrer:typeof document<"u"?document.referrer:void 0};this.queueError(o)}handleUnhandledRejection(e){let t=e.reason,s="Unhandled Promise Rejection",r;t instanceof Error?(s=t.message,r=t.stack):typeof t=="string"?s=t:t&&typeof t=="object"&&(s=JSON.stringify(t));let i={message:s,stack:r,error_type:"unhandledrejection",url:typeof window<"u"?window.location.href:void 0,referrer:typeof document<"u"?document.referrer:void 0};this.queueError(i)}createErrorReport(e,t){let s;e instanceof Error?s={message:e.message,stack:e.stack,error_type:"error",url:typeof window<"u"?window.location.href:void 0,referrer:typeof document<"u"?document.referrer:void 0,...t}:s={message:e,error_type:"custom",url:typeof window<"u"?window.location.href:void 0,referrer:typeof document<"u"?document.referrer:void 0,...t};let r=this.config.beforeSend(s);return r===!1||r===null?(this.log("Error filtered out by beforeSend"),null):r}queueError(e){this.errorQueue.push(bs(e)),this.log("Error queued",{message:e.message,queueSize:this.errorQueue.length}),this.errorQueue.length>=this.config.maxBatchSize&&this.flushQueue()}startBatchTimer(){this.batchTimer||(this.batchTimer=setInterval(()=>{this.flushQueue()},this.config.batchInterval))}stopBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=null)}async flushQueue(){if(!this.storageWebId||this.errorQueue.length===0)return;let e=[...this.errorQueue];this.errorQueue=[];try{e.length===1?await this.http.post(`/v1/public/storages/web/${this.storageWebId}/errors/report`,e[0]):await this.http.post(`/v1/public/storages/web/${this.storageWebId}/errors/batch`,{errors:e,user_agent:typeof navigator<"u"?navigator.userAgent:void 0}),this.log("Errors sent",{count:e.length})}catch(t){let s=this.config.maxBatchSize-this.errorQueue.length;s>0&&this.errorQueue.unshift(...e.slice(0,s)),this.log("Failed to send errors, re-queued",{error:t})}}};var ge=class{constructor(e){this.http=e}getPublicPrefix(){return this.http.hasPublicKey()?"/v1/public":"/v1"}async invoke(e,t,s){let r=this.getPublicPrefix(),i={};return t!==void 0&&(i.payload=t),s!==void 0&&(i.timeout=s),this.http.post(`${r}/functions/${e}/invoke`,i)}async invokeCrossApp(e,t,s,r,i){let o={};return r!==void 0&&(o.payload=r),i!==void 0&&(o.timeout=i),this.http.post(`/v1/integrations/providers/${e}/functions/${t}/invoke`,o,{skipAuth:!0,headers:{Authorization:`Bearer ${s}`}})}async call(e,t){let s=await this.invoke(e,t);if(!s.success)throw s.retryable?new b(503,s.error||"Function gateway is temporarily unavailable","FUNCTION_UNAVAILABLE"):new b(500,s.error||"Function execution failed","FUNCTION_EXECUTION_FAILED");return s.result}getWebhookURL(e){return`${this.http.getBaseUrl().replace(/\/+$/,"")}/v1/public/functions/${encodeURIComponent(e)}/webhook`}};var K=class{constructor(e,t){this.http=e,this.appId=t}async get(e){let t=this.resolveAppId(e);return this.http.get(`/v1/apps/${t}/game/config`)}async set(e,t){let s,r;return typeof e=="string"?(s=e,r=t??{}):(s=this.resolveAppId(),r=e),this.http.patch(`/v1/apps/${s}/game/config`,r)}async enable(e,t){return this.set(e,{[t]:!0})}async disable(e,t){return this.set(e,{[t]:!1})}resolveAppId(e){let t=e??this.appId;if(!t)throw new Error("appId not provided (pass it explicitly or set in client constructor)");return t}};function k(n){let e=n.data??n,t=s=>e[s];return new w({code:t("code")||n.code,message:t("message")||"Unknown error",phase:t("phase")||n.phase,feature:t("feature")||n.feature,roomId:t("room_id")||n.room_id,scriptId:t("script_id")||n.script_id,originClientId:t("origin_client_id")||n.origin_client_id,requested:t("requested")||n.requested,available:t("available")||n.available})}var ys=1e3,ht=()=>{if(typeof window<"u"){let n=window.location.hostname;if(n==="localhost"||n==="127.0.0.1")return"ws://localhost:8087"}return"wss://game.connectbase.world"};function ee(n){let e={};return n.roomId&&(e.room_id=n.roomId),n.categoryId&&(e.category_id=n.categoryId),typeof n.tickRate=="number"&&(e.tick_rate=n.tickRate),typeof n.maxPlayers=="number"&&(e.max_players=n.maxPlayers),n.scriptName&&(e.script_name=n.scriptName),n.metadata&&(e.metadata=n.metadata),e}var ws=new Set(["__proto__","constructor","prototype"]),pt=(n,e)=>Object.prototype.hasOwnProperty.call(n,e);function Ke(n,e){let t=typeof e.path=="string"?e.path.split("."):null;if(!t||t.some(o=>ws.has(o)))return console.warn("[connect-base game] \uC704\uD5D8\uD55C \uACBD\uB85C\uC758 \uC0C1\uD0DC \uBCC0\uACBD\uC744 \uBB34\uC2DC\uD588\uC2B5\uB2C8\uB2E4:",String(e.path).slice(0,100)),!1;let s=e.operation==="delete",r=n;for(let o of t.slice(0,-1)){let a=pt(r,o)?r[o]:void 0;if(a!==null&&typeof a=="object")r=a;else{if(s)return!0;{let c={};r[o]=c,r=c}}}let i=t[t.length-1];return s?pt(r,i)&&delete r[i]:r[i]=e.value,!0}var Z=class{constructor(e){this.ws=null;this.handlers={};this.reconnectAttempts=0;this.reconnectTimer=null;this.pingInterval=null;this.actionSequence=0;this._roomId=null;this._state=null;this._scriptName=null;this._scriptVersion=null;this._isConnected=!1;this.msgIdCounter=0;this.resyncInFlight=!1;this.lastResyncAt=0;this.config={gameServerUrl:ht(),autoReconnect:!0,maxReconnectAttempts:5,reconnectInterval:1e3,...e}}get roomId(){return this._roomId}get state(){return this._state}get isConnected(){return this._isConnected}on(e,t){return this.handlers[e]=t,this}connect(e){return this.ws?.readyState===WebSocket.OPEN?Promise.resolve():this.config.appId?this.config.clientId?this.connectionTicket().then(t=>this.openSocket(e,t)):Promise.reject(new Error("cb.game: clientId is required to build a game connection URL. Pass it via `cb.game.createClient({ appId, clientId })`.")):Promise.reject(new Error("cb.game: appId is required to connect. Pass it to `new ConnectBase({ appId })` or per-client via `cb.game.createClient({ appId, clientId })`."))}async connectionTicket(){let{accessToken:e,publicKey:t,appId:s,gameServerUrl:r}=this.config;if(!e&&!t||!s||!r)return null;try{return await x($(r,`/v1/game/${encodeURIComponent(s)}/ws-ticket`),"game.ws",e?{kind:"access_token",value:e}:{kind:"public_key",value:t})}catch(i){throw i instanceof C?new w({code:i.code,message:i.message}):i}}openSocket(e,t){return new Promise((s,r)=>{let i=this.buildConnectionUrl(e,t);this.ws=new WebSocket(i);let o=()=>{this._isConnected=!0,this.reconnectAttempts=0,this.startPingInterval(),this.handlers.onConnect?.(),s()},a=u=>{this._isConnected=!1,this.stopPingInterval(),this.handlers.onDisconnect?.(u),this.config.autoReconnect&&u.code!==1e3&&this.scheduleReconnect(e)},c=u=>{this.handlers.onError?.(u),r(new Error("WebSocket connection failed"))},l=u=>{this.handleMessage(u.data)};this.ws.addEventListener("open",o,{once:!0}),this.ws.addEventListener("close",a),this.ws.addEventListener("error",c,{once:!0}),this.ws.addEventListener("message",l)})}disconnect(){this.stopPingInterval(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.close(1e3,"Client disconnected"),this.ws=null),this._isConnected=!1,this._roomId=null,this._scriptName=null,this._scriptVersion=null}createRoom(e={}){return this.createRoomDetailed(e).then(t=>t.state)}createRoomDetailed(e={}){return new Promise((t,s)=>{let r=i=>{if(i.type==="room_created"){let o=i.data;return this._roomId=o.room_id,this._state=o.initial_state,this._scriptName=o.script_name??null,this._scriptVersion=o.script_version??null,t({roomId:o.room_id,state:o.initial_state,scriptName:o.script_name,scriptVersion:o.script_version}),!0}else if(i.type==="error")return s(k(i)),!0;return!1};this.sendWithHandler("create_room",ee(e),r,15e3,s)})}get scriptName(){return this._scriptName}get scriptVersion(){return this._scriptVersion}joinRoom(e,t){return new Promise((s,r)=>{let i=o=>{if(o.type==="room_joined"){let a=o.data;return this._roomId=a.room_id,this._state=a.initial_state,this._scriptName=null,this._scriptVersion=null,s(a.initial_state),!0}else if(o.type==="error")return r(k(o)),!0;return!1};this.sendWithHandler("join_room",{room_id:e,metadata:t},i,15e3,r)})}leaveRoom(){return new Promise((e,t)=>{if(!this._roomId){t(new w({code:"NOT_IN_ROOM",message:"Not in a room"}));return}let s=r=>r.type==="room_left"?(this._roomId=null,this._state=null,this._scriptName=null,this._scriptVersion=null,e(),!0):r.type==="error"?(t(k(r)),!0):!1;this.sendWithHandler("leave_room",{},s,15e3,t)})}sendAction(e){if(!this._roomId)throw new w({code:"NOT_IN_ROOM",message:"Not in a room"});this.send("action",{type:e.type,data:e.data,client_timestamp:e.clientTimestamp??Date.now(),sequence:this.actionSequence++})}sendChat(e){if(!this._roomId)throw new w({code:"NOT_IN_ROOM",message:"Not in a room"});this.send("chat",{message:e})}requestState(){return new Promise((e,t)=>{if(!this._roomId){t(new w({code:"NOT_IN_ROOM",message:"Not in a room"}));return}let s=r=>{if(r.type==="state"){let i=r.data;return this._state=i,e(i),!0}else if(r.type==="error")return t(k(r)),!0;return!1};this.sendWithHandler("get_state",{},s,15e3,t)})}listRooms(){return new Promise((e,t)=>{let s=r=>{if(r.type==="room_list"){let i=r.data;return e(i.rooms),!0}else if(r.type==="error")return t(k(r)),!0;return!1};this.sendWithHandler("list_rooms",{},s,15e3,t)})}ping(){return new Promise((e,t)=>{let s=Date.now(),r=i=>{if(i.type==="pong"){let o=i.data,a=Date.now()-o.clientTimestamp;return this.handlers.onPong?.(o),e(a),!0}else if(i.type==="error")return t(k(i)),!0;return!1};this.sendWithHandler("ping",{timestamp:s},r,15e3,t)})}buildConnectionUrl(e,t){let r=this.config.gameServerUrl.replace(/^http/,"ws"),i=new URLSearchParams;if(!this.config.clientId)throw new Error("cb.game: clientId is required to build a game connection URL. Pass it via `cb.game.createClient({ appId, clientId })`.");if(i.set("client_id",this.config.clientId),e&&i.set("room_id",e),t?i.set("ticket",t):(this.config.publicKey&&i.set("public_key",this.config.publicKey),this.config.accessToken&&i.set("token",this.config.accessToken)),!this.config.appId)throw new Error("cb.game: appId is required to build a game connection URL");return`${r}/v1/game/${this.config.appId}/ws?${i.toString()}`}send(e,t,s){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected");this.ws.send(JSON.stringify({type:e,data:t,msg_id:s}))}sendWithHandler(e,t,s,r=15e3,i){let o=`${e}-${++this.msgIdCounter}`,a=null,c=()=>{this.ws?.removeEventListener("message",l),a&&(clearTimeout(a),a=null)},l=u=>{try{let d=JSON.parse(u.data);if(d.msg_id&&d.msg_id!==o)return;s(d)&&c()}catch{}};this.ws?.addEventListener("message",l),a=setTimeout(()=>{c();let u=new w({code:"TIMEOUT",message:`Request '${e}' timed out after ${r}ms`});i?.(u),this.handlers.onError?.(u)},r);try{this.send(e,t,o)}catch(u){c();let d=u instanceof Error?u:new Error(String(u));i?.(d)}}handleMessage(e){try{let t=JSON.parse(e);switch(t.type){case"delta":this.handleDelta(t);break;case"state":this._state=t.data,this.handlers.onStateUpdate?.(this._state);break;case"player_event":this.handlePlayerEvent(t);break;case"chat":this.handlers.onChat?.({roomId:t.room_id||"",clientId:t.client_id||"",userId:t.user_id,message:t.message||"",serverTime:t.server_time||0});break;case"error":this.handlers.onError?.(k(t));break;case"sync_lost":this.handleSyncLost(t);break;case"room_stale":this.handlers.onRoomStale?this.handlers.onRoomStale({reason:t.reason||"unknown",roomId:t.room_id||"",scriptId:t.script_id,scriptVersion:t.script_version,serverTime:t.server_time||0}):console.warn("[connect-base game] room_stale received but onRoomStale handler not set:",t.reason);break;default:this.handlers.onMessage?.(t);break}}catch{console.error("Failed to parse game message:",e)}}handleSyncLost(e){if(this.handlers.onSyncLost?.({roomId:e.room_id||"",tick:e.tick||0,hint:e.hint||"",serverTime:e.server_time||0}),this.resyncInFlight)return;let t=Date.now();t-this.lastResyncAt<ys||(this.resyncInFlight=!0,this.lastResyncAt=t,this.requestState().catch(s=>{console.warn("[connect-base game] sync_lost resync failed:",s)}).finally(()=>{this.resyncInFlight=!1}))}handleDelta(e){let t=e.delta;if(!t)return;let s={fromVersion:t.from_version,toVersion:t.to_version,changes:t.changes.map(r=>({path:r.path,operation:r.operation,value:r.value,oldValue:r.old_value})),tick:t.tick};if(this._state){for(let r of s.changes)this.applyChange(r);this._state.version=s.toVersion}if(this.handlers.onAction){for(let r of s.changes)if(r.path.startsWith("actions.")&&r.operation==="set"&&r.value){let i=r.value;this.handlers.onAction({type:i.type||"",clientId:i.client_id||"",data:i.data,timestamp:i.timestamp||0})}}this.handlers.onDelta?.(s)}applyChange(e){this._state&&Ke(this._state.state,e)}handlePlayerEvent(e){let t={clientId:e.player?.client_id||"",userId:e.player?.user_id,joinedAt:e.player?.joined_at||0,metadata:e.player?.metadata};e.event==="joined"?this.handlers.onPlayerJoined?.(t):e.event==="left"&&this.handlers.onPlayerLeft?.(t)}scheduleReconnect(e){if(this.reconnectAttempts>=(this.config.maxReconnectAttempts??5)){console.error("Max reconnect attempts reached"),this.handlers.onError?.(new w({code:"MAX_RECONNECT_ATTEMPTS",message:"Maximum reconnection attempts reached"}));return}let t=Math.min((this.config.reconnectInterval??1e3)*2**this.reconnectAttempts,3e4);this.reconnectAttempts++;let s=e||this._roomId;this.reconnectTimer=setTimeout(async()=>{console.log(`Reconnecting... (attempt ${this.reconnectAttempts})`);try{if(await this.connect(),s){console.log(`Rejoining room ${s}...`);try{await this.joinRoom(s),console.log(`Successfully rejoined room ${s}`)}catch(r){console.error(`Failed to rejoin room ${s}:`,r),this.handlers.onError?.(new w({code:"REJOIN_FAILED",message:`Failed to rejoin room: ${r}`,roomId:s}))}}}catch{}},t)}startPingInterval(){this.pingInterval=setInterval(()=>{this.ping().catch(()=>{})},3e4)}stopPingInterval(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null)}},W=class{constructor(e,t,s){this.http=e,this.gameServerUrl=t||ht().replace(/^ws/,"http"),this.appId=s,this.config=new K(e,s)}createClient(e){return new Z({...e,gameServerUrl:this.gameServerUrl.replace(/^http/,"ws"),appId:e.appId??this.appId,publicKey:this.http.getPublicKey(),accessToken:this.http.getAccessToken()})}async listRooms(e){let t=e||this.appId||"",s=await fetch(`${this.gameServerUrl}/v1/game/${t}/rooms`,{headers:this.getHeaders()});if(!s.ok)throw new b(s.status,`Failed to list rooms: ${s.statusText}`,"GAME_LIST_ROOMS_FAILED");return(await s.json()).rooms}async getRoom(e){let t=this.appId||"",s=await fetch(`${this.gameServerUrl}/v1/game/${t}/rooms/${e}`,{headers:this.getHeaders()});if(!s.ok)throw new b(s.status,`Failed to get room: ${s.statusText}`,"GAME_GET_ROOM_FAILED");return(await s.json()).room}async createRoom(e,t={}){throw new Error("cb.game.createRoom is not yet publicly available \u2014 use the admin console or request a backend public route.")}async deleteRoom(e){throw new Error("cb.game.deleteRoom is not yet publicly available \u2014 use the admin console or request a backend public route.")}async joinSpectator(e,t){let s=this.appId||"",r=await fetch(`${this.gameServerUrl}/v1/game/${s}/rooms/${e}/spectators`,{method:"POST",headers:{...this.getHeaders(),"Content-Type":"application/json"},body:JSON.stringify({user_id:t})});if(!r.ok)throw new Error(`Failed to join spectator: ${r.statusText}`);return r.json()}async leaveSpectator(e,t){let s=this.appId||"",r=await fetch(`${this.gameServerUrl}/v1/game/${s}/rooms/${e}/spectators/${t}`,{method:"DELETE",headers:this.getHeaders()});if(!r.ok)throw new Error(`Failed to leave spectator: ${r.statusText}`)}async getSpectators(e){let t=this.appId||"",s=await fetch(`${this.gameServerUrl}/v1/game/${t}/rooms/${e}/spectators`,{headers:this.getHeaders()});if(!s.ok)throw new Error(`Failed to get spectators: ${s.statusText}`);return(await s.json()).spectators||[]}async joinVoiceChannel(e,t){let s=this.appId||"",r=await fetch(`${this.gameServerUrl}/v1/game/${s}/voice/rooms/${e}/join`,{method:"POST",headers:{...this.getHeaders(),"Content-Type":"application/json"},body:JSON.stringify({player_id:t})});if(!r.ok)throw new Error(`Failed to join voice channel: ${r.statusText}`);return r.json()}async leaveVoiceChannel(e,t){let s=this.appId||"",r=await fetch(`${this.gameServerUrl}/v1/game/${s}/voice/rooms/${e}/leave`,{method:"POST",headers:{...this.getHeaders(),"Content-Type":"application/json"},body:JSON.stringify({player_id:t})});if(!r.ok)throw new Error(`Failed to leave voice channel: ${r.statusText}`)}async setMute(e,t){let s=this.appId||"",r=await fetch(`${this.gameServerUrl}/v1/game/${s}/voice/mute`,{method:"POST",headers:{...this.getHeaders(),"Content-Type":"application/json"},body:JSON.stringify({player_id:e,muted:t})});if(!r.ok)throw new Error(`Failed to set mute: ${r.statusText}`)}async listReplays(e){let t=this.appId||"",s=`${this.gameServerUrl}/v1/game/${t}/replays`;e&&(s+=`?room_id=${e}`);let r=await fetch(s,{headers:this.getHeaders()});if(r.status===404)throw new Error("cb.game.listReplays: replay storage is not configured on this server (REPLAY_STORAGE_PATH unset).");if(!r.ok)throw new Error(`Failed to list replays: ${r.statusText}`);return(await r.json()).replays||[]}async getReplay(e){let t=this.appId||"",s=await fetch(`${this.gameServerUrl}/v1/game/${t}/replays/${e}`,{headers:this.getHeaders()});if(s.status===404)throw new Error("cb.game.getReplay: replay not found or replay storage unconfigured.");if(!s.ok)throw new Error(`Failed to get replay: ${s.statusText}`);return s.json()}async downloadReplay(e){let t=this.appId||"",s=await fetch(`${this.gameServerUrl}/v1/game/${t}/replays/${e}/download`,{headers:this.getHeaders()});if(s.status===404)throw new Error("cb.game.downloadReplay: replay not found or replay storage unconfigured.");if(!s.ok)throw new Error(`Failed to download replay: ${s.statusText}`);return s.arrayBuffer()}async getReplayHighlights(e){let t=this.appId||"",s=await fetch(`${this.gameServerUrl}/v1/game/${t}/replays/${e}/highlights`,{headers:this.getHeaders()});if(s.status===404)throw new Error("cb.game.getReplayHighlights: replay not found or replay storage unconfigured.");if(!s.ok)throw new Error(`Failed to get highlights: ${s.statusText}`);return(await s.json()).highlights||[]}getHeaders(){let e={},t=this.http.getPublicKey();t&&(e["X-Public-Key"]=t);let s=this.http.getAccessToken();return s&&(e.Authorization=`Bearer ${s}`),e}async gameFetch(e,t,s,r="GAME_REQUEST_FAILED"){let i={method:e,headers:{...this.getHeaders()}};s!==void 0&&(i.headers["Content-Type"]="application/json",i.body=JSON.stringify(s));let o=await fetch(`${this.gameServerUrl}${t}`,i);if(!o.ok){let c=r,l=`${e} ${t} failed: ${o.statusText}`;try{let u=await o.json();u&&typeof u.error=="string"&&(l=u.error,c=u.error)}catch{}throw new b(o.status,l,c)}if(!(o.status===204||!(o.headers.get("content-type")||"").includes("application/json")))return o.json()}async enqueueMatch(e,t,s,r,i){return this.gameFetch("POST",`/v1/game/${e}/matchqueue/${t}/tickets`,{ticket_id:s,attributes:r,ttl_sec:i??0},"GAME_ENQUEUE_MATCH_FAILED")}async listMatchqueue(e,t){return this.gameFetch("GET",`/v1/game/${e}/matchqueue/${t}`,void 0,"GAME_LIST_MATCHQUEUE_FAILED")}async cancelMatch(e,t,s){await this.gameFetch("DELETE",`/v1/game/${e}/matchqueue/${t}/tickets/${s}`,void 0,"GAME_CANCEL_MATCH_FAILED")}async submitScore(e,t,s,r,i="set"){return this.gameFetch("POST",`/v1/game/${e}/leaderboards/${t}/scores`,{member:s,score:r,mode:i},"GAME_SUBMIT_SCORE_FAILED")}async getTopScores(e,t,s=10){return this.gameFetch("GET",`/v1/game/${e}/leaderboards/${t}/top?n=${s}`,void 0,"GAME_GET_TOP_SCORES_FAILED")}async getMemberRank(e,t,s){return this.gameFetch("GET",`/v1/game/${e}/leaderboards/${t}/members/${s}`,void 0,"GAME_GET_MEMBER_RANK_FAILED")}async getRankAround(e,t,s,r=5,i=5){return this.gameFetch("GET",`/v1/game/${e}/leaderboards/${t}/around/${s}?above=${r}&below=${i}`,void 0,"GAME_GET_RANK_AROUND_FAILED")}async resetLeaderboard(e,t){await this.gameFetch("DELETE",`/v1/game/${e}/leaderboards/${t}`,void 0,"GAME_RESET_LEADERBOARD_FAILED")}async removeFromLeaderboard(e,t,s){await this.gameFetch("DELETE",`/v1/game/${e}/leaderboards/${t}/members/${s}`,void 0,"GAME_REMOVE_FROM_LEADERBOARD_FAILED")}async uploadScript(e,t,s){return this.gameFetch("POST",`/v1/game/${e}/scripts`,{name:t,code:s},"GAME_UPLOAD_SCRIPT_FAILED")}async listScripts(e){return this.gameFetch("GET",`/v1/game/${e}/scripts`,void 0,"GAME_LIST_SCRIPTS_FAILED")}async getScript(e,t){return this.gameFetch("GET",`/v1/game/${e}/scripts/${t}`,void 0,"GAME_GET_SCRIPT_FAILED")}async listScriptVersions(e,t){return this.gameFetch("GET",`/v1/game/${e}/scripts/${t}/versions`,void 0,"GAME_LIST_SCRIPT_VERSIONS_FAILED")}async activateScript(e,t,s){return this.gameFetch("POST",`/v1/game/${e}/scripts/${t}/activate`,{version:s??0},"GAME_ACTIVATE_SCRIPT_FAILED")}async rollbackScript(e,t){return this.gameFetch("POST",`/v1/game/${e}/scripts/${t}/rollback`,{},"GAME_ROLLBACK_SCRIPT_FAILED")}async deactivateScript(e,t){await this.gameFetch("POST",`/v1/game/${e}/scripts/${t}/deactivate`,{},"GAME_DEACTIVATE_SCRIPT_FAILED")}async deleteScript(e,t){await this.gameFetch("DELETE",`/v1/game/${e}/scripts/${t}`,void 0,"GAME_DELETE_SCRIPT_FAILED")}async getScriptLogs(e,t,s={}){let r=new URLSearchParams;typeof s.since=="number"&&r.set("since",String(s.since)),typeof s.limit=="number"&&r.set("limit",String(s.limit));let i=r.toString();return this.gameFetch("GET",`/v1/game/${e}/scripts/${t}/logs${i?`?${i}`:""}`,void 0,"GAME_GET_SCRIPT_LOGS_FAILED")}async getScriptMetrics(e,t){return this.gameFetch("GET",`/v1/game/${e}/scripts/${t}/metrics`,void 0,"GAME_GET_SCRIPT_METRICS_FAILED")}};async function mt(n){if(typeof Blob<"u"&&n instanceof Blob){let s=await n.arrayBuffer(),r="name"in n?n.name:void 0;return{data:gt(new Uint8Array(s)),mimeType:n.type||"",defaultName:r}}let e=n;if(!e||e.data===void 0)throw new Error("addDocumentFromFile: file must be a Blob/File or { data, mimeType?, name? }");let t=e.data instanceof Uint8Array?e.data:new Uint8Array(e.data);return{data:gt(t),mimeType:e.mimeType??"",defaultName:e.name}}function gt(n){let e=globalThis;if(e.Buffer)return e.Buffer.from(n).toString("base64");let t=8192,s="";for(let r=0;r<n.length;r+=t){let i=n.subarray(r,Math.min(r+t,n.length));s+=String.fromCharCode.apply(null,Array.from(i))}return btoa(s)}var fe=class{constructor(e){this.http=e}async addDocument(e,t){return this.http.post(`/v1/public/knowledge-bases/${e}/documents`,t)}async updateDocument(e,t,s){return this.http.put(`/v1/public/knowledge-bases/${e}/documents/${t}`,s)}async updateDocumentFromFile(e,t,s,r){let{data:i,mimeType:o}=await mt(s);return this.updateDocument(e,t,{name:r?.name,file_content:i,mime_type:o,metadata:r?.metadata})}async addDocumentFromFile(e,t,s){let{data:r,mimeType:i,defaultName:o}=await mt(t),a=s?.name??o??"document";return this.addDocument(e,{name:a,source_type:"file",file_content:r,mime_type:i,metadata:s?.metadata})}async listDocuments(e){return this.http.get(`/v1/public/knowledge-bases/${e}/documents`)}async deleteDocument(e,t){await this.http.delete(`/v1/public/knowledge-bases/${e}/documents/${t}`)}async search(e,t){return this.http.post(`/v1/public/knowledge-bases/${e}/search`,t)}async searchGet(e,t,s){let r=new URLSearchParams({query:t});return s&&r.append("top_k",String(s)),this.http.get(`/v1/public/knowledge-bases/${e}/search?${r.toString()}`)}};var V=class{constructor(){this._webSpeechRecognition=null;this.clipboard={writeText:async e=>{this.getPlatform()==="desktop"&&window.NativeBridge?.clipboard?await window.NativeBridge.clipboard.writeText(e):await navigator.clipboard.writeText(e)},readText:async()=>this.getPlatform()==="desktop"&&window.NativeBridge?.clipboard?window.NativeBridge.clipboard.readText():navigator.clipboard.readText(),writeHTML:async e=>{window.NativeBridge?.clipboard?.writeHTML?await window.NativeBridge.clipboard.writeHTML(e):await navigator.clipboard.writeText(e)},writeImage:async e=>{if(window.NativeBridge?.clipboard?.writeImage)await window.NativeBridge.clipboard.writeImage(e);else throw new Error("Image clipboard not supported on this platform")},readImage:async()=>window.NativeBridge?.clipboard?.readImage?window.NativeBridge.clipboard.readImage():null,has:async e=>window.NativeBridge?.clipboard?.has?window.NativeBridge.clipboard.has(e):!1};this.filesystem={pickFile:async e=>{if(this.getPlatform()==="desktop"&&window.NativeBridge?.filesystem?.showOpenDialog){let s=await window.NativeBridge.filesystem.showOpenDialog({properties:e?.multiple?["openFile","multiSelections"]:["openFile"],filters:e?.filters});return s.canceled||!s.filePaths.length?null:s.filePaths.map(r=>new File([],r.split("/").pop()||"file"))}return new Promise(s=>{let r=document.createElement("input");r.type="file",e?.accept&&(r.accept=e.accept),e?.multiple&&(r.multiple=!0),r.onchange=()=>{s(r.files?Array.from(r.files):null)},r.click()})},saveFile:async(e,t,s)=>{let r=this.getPlatform();if(r==="desktop"&&window.NativeBridge?.filesystem)try{let c=await window.NativeBridge.filesystem.showSaveDialog?.({defaultPath:t,filters:s?.filters});if(c?.canceled||!c?.filePath)return!1;let l=e instanceof Blob?await e.text():e;return(await window.NativeBridge.filesystem.writeFile(c.filePath,l)).success}catch{return!1}if(r==="mobile"&&window.NativeBridge?.filesystem)try{let c=e instanceof Blob?await e.text():e;return(await window.NativeBridge.filesystem.writeFile(t,c)).success}catch{return!1}let i=e instanceof Blob?e:new Blob([e],{type:"text/plain"}),o=URL.createObjectURL(i),a=document.createElement("a");return a.href=o,a.download=t,a.click(),URL.revokeObjectURL(o),!0},readFile:async e=>{if(window.NativeBridge?.filesystem?.readFile)try{let t=await window.NativeBridge.filesystem.readFile(e);return t.success?t.content??null:null}catch{return null}return null},exists:async e=>window.NativeBridge?.filesystem?.exists?window.NativeBridge.filesystem.exists(e):!1};this.camera={takePicture:async e=>{if(this.getPlatform()==="mobile"&&window.NativeBridge?.camera)try{return await window.NativeBridge.camera.takePicture(e)}catch{return null}return new Promise(s=>{let r=document.createElement("input");r.type="file",r.accept="image/*",r.capture="environment",r.onchange=async()=>{let i=r.files?.[0];if(!i){s(null);return}let o=new FileReader;o.onload=()=>{let a=new Image;a.onload=()=>{s({uri:URL.createObjectURL(i),base64:e?.base64?o.result.split(",")[1]:void 0,width:a.width,height:a.height})},a.src=o.result},o.readAsDataURL(i)},r.click()})},pickImage:async e=>{if(this.getPlatform()==="mobile"&&window.NativeBridge?.camera)try{return await window.NativeBridge.camera.pickImage(e)}catch{return null}return new Promise(s=>{let r=document.createElement("input");r.type="file",r.accept="image/*",e?.multiple&&(r.multiple=!0),r.onchange=async()=>{let i=r.files;if(!i?.length){s(null);return}let o=[];for(let a of Array.from(i)){let c=await new Promise(l=>{let u=new FileReader;u.onload=()=>{let d=new Image;d.onload=()=>{l({uri:URL.createObjectURL(a),base64:e?.base64?u.result.split(",")[1]:void 0,width:d.width,height:d.height})},d.src=u.result},u.readAsDataURL(a)});o.push(c)}s(o)},r.click()})}};this.location={getCurrentPosition:async e=>this.getPlatform()==="mobile"&&window.NativeBridge?.location?window.NativeBridge.location.getCurrentPosition(e):new Promise((s,r)=>{navigator.geolocation.getCurrentPosition(i=>{s({latitude:i.coords.latitude,longitude:i.coords.longitude,altitude:i.coords.altitude,accuracy:i.coords.accuracy,timestamp:i.timestamp})},r,{enableHighAccuracy:e?.accuracy==="high",timeout:1e4,maximumAge:0})}),watchPosition:async(e,t)=>{let s=this.getPlatform(),r=window.NativeBridge;if(s==="mobile"&&r?.location?.watchPosition){let{watchId:o}=await r.location.watchPosition(t),a=c=>{let l=c.detail;!l||l.watchId&&l.watchId!==o||e({latitude:l.latitude,longitude:l.longitude,altitude:l.altitude,accuracy:l.accuracy,timestamp:l.timestamp})};return window.addEventListener("nativeLocationUpdate",a),{watchId:o,clear:async()=>{window.removeEventListener("nativeLocationUpdate",a),await r.location?.stopWatch(o)}}}let i=navigator.geolocation.watchPosition(o=>e({latitude:o.coords.latitude,longitude:o.coords.longitude,altitude:o.coords.altitude,accuracy:o.coords.accuracy,timestamp:o.timestamp}),void 0,{enableHighAccuracy:t?.accuracy==="high",timeout:1e4,maximumAge:0});return{watchId:String(i),clear:async()=>navigator.geolocation.clearWatch(i)}}};this.push={getToken:async()=>{if(this.getPlatform()==="mobile"&&window.NativeBridge?.push)try{return await window.NativeBridge.push.getToken()}catch{return null}return null},requestPermission:async()=>this.notification.requestPermission(),scheduleLocal:async e=>{if(this.getPlatform()==="mobile"&&window.NativeBridge?.push)try{return(await window.NativeBridge.push.scheduleLocal(e)).notificationId}catch{return null}return null},setBadgeCount:async e=>{let t=window.NativeBridge?.push?.setBadgeCount;if(!t)return!1;try{return(await t(e)).success}catch{return!1}}};this.notification={show:async e=>{let t=this.getPlatform();return t==="desktop"&&window.NativeBridge?.notification?(await window.NativeBridge.notification.show(e)).success:t==="mobile"&&window.NativeBridge?.push?.scheduleLocal?await this.notification.requestPermission()?await this.push.scheduleLocal({title:e.title,body:e.body,trigger:null})!==null:!1:!("Notification"in window)||Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"?!1:(new Notification(e.title,{body:e.body,icon:e.icon,silent:e.silent}),!0)},requestPermission:async()=>{if(this.getPlatform()==="mobile"&&window.NativeBridge?.push)try{return(await window.NativeBridge.push.requestPermission()).granted}catch{return!1}return"Notification"in window?await Notification.requestPermission()==="granted":!1}};this.shell={openExternal:async e=>{let t=this.getPlatform();if(t==="desktop"&&window.NativeBridge?.shell)return(await window.NativeBridge.shell.openExternal(e)).success;if(t==="mobile"&&window.NativeBridge?.browser)try{return(await window.NativeBridge.browser.openExternal(e)).success}catch{return!1}return window.open(e,"_blank"),!0}};this.oauth={signIn:async(e,t)=>{let s=window.NativeBridge;if(this.getPlatform()!=="mobile"||!s?.oauth)return null;let r=t??s.oauth.getCallbackScheme();try{return await s.oauth.signIn(e,r)}catch{return null}},getCallbackScheme:()=>this.getPlatform()!=="mobile"||!window.NativeBridge?.oauth?null:window.NativeBridge.oauth.getCallbackScheme()};this.connectbase={uploadFile:async(e,t,s)=>{if(this.getPlatform()!=="mobile"||!window.NativeBridge?.connectbase)return null;try{return await window.NativeBridge.connectbase.uploadFile(e,t,s)}catch{return null}}};this.window={minimize:async()=>{await window.NativeBridge?.window?.minimize()},maximize:async()=>{await window.NativeBridge?.window?.maximize()},unmaximize:async()=>{await window.NativeBridge?.window?.unmaximize()},close:async()=>{await window.NativeBridge?.window?.close()},isMaximized:async()=>await window.NativeBridge?.window?.isMaximized()??!1,setTitle:async e=>{window.NativeBridge?.window?await window.NativeBridge.window.setTitle(e):document.title=e},setFullScreen:async e=>{window.NativeBridge?.window?await window.NativeBridge.window.setFullScreen(e):document.documentElement.requestFullscreen&&(e?await document.documentElement.requestFullscreen():document.exitFullscreen&&await document.exitFullscreen())},isFullScreen:async()=>window.NativeBridge?.window?await window.NativeBridge.window.isFullScreen()??!1:!!document.fullscreenElement,setSize:async(e,t)=>{await window.NativeBridge?.window?.setSize(e,t)},getSize:async()=>await window.NativeBridge?.window?.getSize()??null,setPosition:async(e,t)=>{await window.NativeBridge?.window?.setPosition(e,t)},getPosition:async()=>await window.NativeBridge?.window?.getPosition()??null,center:async()=>{await window.NativeBridge?.window?.center()},setAlwaysOnTop:async e=>{await window.NativeBridge?.window?.setAlwaysOnTop(e)}};this.system={getInfo:async()=>window.NativeBridge?.system?window.NativeBridge.system.getInfo():null,getMemory:async()=>window.NativeBridge?.system?window.NativeBridge.system.getMemory():null,getCPU:async()=>window.NativeBridge?.system?window.NativeBridge.system.getCPU():null};this.biometric={isAvailable:async()=>{if(window.NativeBridge?.biometric)try{return await window.NativeBridge.biometric.isAvailable()}catch{return null}return null},authenticate:async e=>{if(window.NativeBridge?.biometric)try{return await window.NativeBridge.biometric.authenticate(e)}catch{return null}return null}};this.secureStore={setItem:async(e,t)=>{if(window.NativeBridge?.secureStore)try{return(await window.NativeBridge.secureStore.setItem(e,t)).success}catch{return!1}return localStorage.setItem(e,t),!0},getItem:async e=>{if(window.NativeBridge?.secureStore)try{return(await window.NativeBridge.secureStore.getItem(e)).value}catch{return null}return localStorage.getItem(e)},deleteItem:async e=>{if(window.NativeBridge?.secureStore)try{return(await window.NativeBridge.secureStore.deleteItem(e)).success}catch{return!1}return localStorage.removeItem(e),!0}};this.admob={showInterstitial:async()=>{if(window.NativeBridge?.admob)try{return(await window.NativeBridge.admob.showInterstitial()).shown}catch{return!1}return!1},showRewarded:async()=>{if(window.NativeBridge?.admob)try{return(await window.NativeBridge.admob.showRewarded()).rewarded}catch{return!1}return!1}};this.speech={isAvailable:async()=>this.getPlatform()==="mobile"&&window.NativeBridge?.speech?(await window.NativeBridge.speech.isAvailable()).available:typeof window>"u"?!1:"SpeechRecognition"in window||"webkitSpeechRecognition"in window,recognize:async e=>{if(this.getPlatform()==="mobile"&&window.NativeBridge?.speech){let r;e?.onPartial&&(r=i=>{let o=i.detail;o?.transcript&&e.onPartial?.(o.transcript)},window.addEventListener("nativeSpeechPartial",r));try{return await window.NativeBridge.speech.recognize(e)}finally{r&&window.removeEventListener("nativeSpeechPartial",r)}}let t=window,s=t.SpeechRecognition||t.webkitSpeechRecognition;if(!s)throw new Error("\uC774 \uD50C\uB7AB\uD3FC\uC5D0\uC11C\uB294 \uC74C\uC131 \uC778\uC2DD\uC744 \uC9C0\uC6D0\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. \uD328\uD0A4\uC9D5 \uC571\uC5D0\uC11C\uB294 speech \uB124\uC774\uD2F0\uBE0C \uAE30\uB2A5\uC744 \uD65C\uC131\uD654\uD558\uC138\uC694.");return new Promise((r,i)=>{let o=new s;this._webSpeechRecognition=o,o.lang=e?.lang??"en-US",o.interimResults=e?.interim??!0,o.continuous=e?.continuous??!1;let a="";o.onresult=c=>{let l="";for(let u=c.resultIndex;u<c.results.length;u++){let d=c.results[u];d.isFinal?a+=d[0].transcript:l+=d[0].transcript}l&&e?.onPartial&&e.onPartial(l)},o.onerror=c=>{this._webSpeechRecognition=null,i(new Error(c?.error||"\uC74C\uC131 \uC778\uC2DD \uC624\uB958"))},o.onend=()=>{this._webSpeechRecognition=null,r({transcript:a.trim(),isFinal:!0})},o.start()})},stop:async()=>{if(this.getPlatform()==="mobile"&&window.NativeBridge?.speech){await window.NativeBridge.speech.stop();return}if(this._webSpeechRecognition)try{this._webSpeechRecognition.stop()}catch{}}}}getPlatform(){if(typeof window>"u")return"web";let e=window.NativeBridge;return e?.platform==="electron"?"desktop":e?.platform==="react-native"||e?.platform==="ios"||e?.platform==="android"||e?.camera||window.ReactNativeWebView?"mobile":"web"}isNativeApp(){return this.getPlatform()!=="web"}async getAppInfo(){let e=this.bridge?.app?.getInfo;return e?e():null}hasFeature(e){return typeof window>"u"?!1:!!window.NativeBridge?.[e]}get bridge(){if(!(typeof window>"u"))return window.NativeBridge}};var We="cb_oauth_pending_states";var te="oauth_state_mismatch";function ft(){try{return typeof window<"u"?window.localStorage:null}catch{return null}}function bt(n,e){try{let t=JSON.parse(n.getItem(We)||"[]");return Array.isArray(t)?t.filter(s=>typeof s?.nonce=="string"&&typeof s?.expiresAt=="number"&&s.expiresAt>e):[]}catch{return[]}}function yt(n,e){e.length===0?n.removeItem(We):n.setItem(We,JSON.stringify(e))}function vs(){let n=new Uint8Array(16);return globalThis.crypto.getRandomValues(n),Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function be(n){let e=ft(),t=vs();try{if(!e)throw new Error("storage unavailable");let s=Date.now(),r=bt(e,s);r.push({nonce:t,expiresAt:s+36e5,...n?{appState:n}:{}}),yt(e,r.slice(-8))}catch{throw new Error("\uBE0C\uB77C\uC6B0\uC800 \uC800\uC7A5\uC18C\uB97C \uC0AC\uC6A9\uD560 \uC218 \uC5C6\uC5B4 \uC18C\uC15C \uB85C\uADF8\uC778\uC744 \uC2DC\uC791\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uCFE0\uD0A4\uC640 \uC0AC\uC774\uD2B8 \uB370\uC774\uD130 \uCC28\uB2E8\uC744 \uD574\uC81C\uD55C \uB4A4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694.")}return t}function se(n){if(!n)return{valid:!1};let e=ft();if(!e)return{valid:!1};try{let t=bt(e,Date.now()),s=t.findIndex(i=>i.nonce===n);if(s<0)return{valid:!1};let[r]=t.splice(s,1);return yt(e,t),{valid:!0,appState:r.appState}}catch{return{valid:!1}}}function wt(){if(typeof window>"u")return null;let n=window.NativeBridge?.oauth;return!n||typeof n.signIn!="function"||typeof n.getCallbackScheme!="function"?null:n}var vt="popup_opener_not_allowed",Rs=["access_token","refresh_token","member_id","is_new_member","email","state"],_s=["code","state"],ye="code",Rt=new WeakMap;function ze(){try{return!!window.opener&&window.opener.location.origin===window.location.origin}catch{return!1}}function Pt(n){try{let{pathname:e,search:t,hash:s}=window.location;window.history.replaceState(window.history.state,"",tt(`${e}${t}${s}`,n))}catch{}}function Ve(){if(typeof window>"u"||!window.location)return null;let n=Rt.get(window),e=new URLSearchParams(window.location.search),t=e.get("access_token"),s=e.get("refresh_token");if(!(!!t&&!!s))return n&&n.href===window.location.href?n:null;if(n?.accessToken===t)return n;Pt(Rs);let i=e.get("member_id");if(!i)return null;let o=e.get("state"),a=se(o),c={kind:a.valid?"redirect":ze()?"popup":"rejected",accessToken:t,refreshToken:s,memberId:i,isNewMember:e.get("is_new_member")==="true",email:e.get("email"),appState:a.valid?a.appState:o||void 0,href:window.location.href};return Rt.set(window,c),c.kind==="rejected"&&ve(),c}var _t=new WeakMap;function we(n){if(typeof window>"u"||!window.location)return null;let e=_t.get(window),t=new URLSearchParams(window.location.search),s=t.get("code");if(!s)return e&&e.href===window.location.href?e:null;if(e?.code===s)return e;if(t.get("error"))return null;let r=t.get("state"),i=se(r),o;if(i.valid)o="redirect";else if(n&&!r&&ze())o="popup";else return"rejected";Pt(_s);let a={kind:o,code:s,appState:i.valid?i.appState:r||void 0,href:window.location.href};return _t.set(window,a),a}function ve(){console.warn("[connect-base-client] OAuth \uCF5C\uBC31\uC744 \uBC1B\uC544\uB4E4\uC774\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4. \uC774 \uBE0C\uB77C\uC6B0\uC800\uC5D0\uC11C \uC2DC\uC791\uD55C \uB85C\uADF8\uC778\uC758 \uACB0\uACFC\uC784\uC744 \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4(state \uBD88\uC77C\uCE58). \uB0A8\uC774 \uBCF4\uB0B8 \uB9C1\uD06C\uB77C\uBA74 \uC815\uC0C1 \uB3D9\uC791\uC785\uB2C8\uB2E4. \uC815\uC0C1 \uB85C\uADF8\uC778\uC774 \uAC70\uBD80\uB41C\uB2E4\uBA74 cb.oauth.signIn() \uC744 \uBD80\uB978 \uD398\uC774\uC9C0\uC640 \uCF5C\uBC31 \uC8FC\uC18C\uC758 \uCD9C\uCC98\uAC00 \uAC19\uC740\uC9C0, \uC778\uAC00 \uC8FC\uC18C\uB97C \uC9C1\uC811 \uB9CC\uB4E0\uB2E4\uBA74 cb.oauth.createCallbackState() \uAC12\uC744 state \uB85C \uB118\uACBC\uB294\uC9C0 \uD655\uC778\uD558\uC138\uC694.")}function re(){if(typeof navigator>"u")return null;let n=navigator.userAgent||"";return/KAKAOTALK/i.test(n)?{type:"kakaotalk",ua:n}:/Line\//i.test(n)?{type:"line",ua:n}:/Instagram/i.test(n)?{type:"instagram",ua:n}:/FBAN|FBAV|FB_IAB/i.test(n)?{type:"facebook",ua:n}:/NAVER\(inapp/i.test(n)?{type:"naverapp",ua:n}:/MicroMessenger/i.test(n)?{type:"wechat",ua:n}:null}function Re(n){if(typeof window>"u")return!1;let e=re();if(!e)return!1;let t=n??window.location.href,s=encodeURIComponent(t);switch(e.type){case"kakaotalk":return window.location.href=`kakaotalk://web/openExternal?url=${s}`,!0;case"line":return window.location.href=`line://nv/openURL?url=${s}`,!0;default:return!1}}var _e=class{constructor(e){this.http=e;this.bootConsumePromise=null;this.loadedCallback=null;this.loadedCodeCallback=null}async getEnabledProviders(){return this.http.get("/v1/public/oauth/providers")}async signIn(e,t,s,r){return this.startCentralOAuth(e,t,s,r?.createIfNotExists?"signup":"signin")}async signUp(e,t,s){return this.startCentralOAuth(e,t,s,"signup")}async startCentralOAuth(e,t,s,r){let i=wt();if(i){let l=i.getCallbackScheme(),u=new URLSearchParams({app_callback:l,intent:r,state:this.createCallbackStateFor(t,s),response_type:ye}),d=await this.http.get(`/v1/public/oauth/${e}/authorize/central?${u.toString()}`),{url:h}=await i.signIn(d.authorization_url,l),p=new URL(h),f=new URL(t,window.location.href);p.searchParams.forEach((m,g)=>{f.searchParams.set(g,m)}),window.location.href=f.toString();return}let o=re();if(o&&(e==="google"||e==="apple")){if(Re())return;throw new Error(`\uD604\uC7AC ${o.type==="kakaotalk"?"\uCE74\uCE74\uC624\uD1A1":o.type==="line"?"\uB77C\uC778":"\uC778\uC571"} \uBE0C\uB77C\uC6B0\uC800\uC5D0\uC11C\uB294 Google/Apple \uB85C\uADF8\uC778\uC774 \uC81C\uD55C\uB429\uB2C8\uB2E4. \uC6B0\uCE21 \uC0C1\uB2E8 \uBA54\uB274\uC5D0\uC11C "\uB2E4\uB978 \uBE0C\uB77C\uC6B0\uC800\uB85C \uC5F4\uAE30"\uB97C \uC120\uD0DD\uD574\uC8FC\uC138\uC694.`)}let a=new URLSearchParams({app_callback:t,intent:r,state:this.createCallbackStateFor(t,s),response_type:ye}),c=await this.http.get(`/v1/public/oauth/${e}/authorize/central?${a.toString()}`);window.location.href=c.authorization_url}createCallbackState(e){return be(e)}createCallbackStateFor(e,t){let s=be(t);try{let r=new URL(e,window.location.href);r.origin!==window.location.origin&&console.warn(`[connect-base-client] \uCF5C\uBC31 \uC8FC\uC18C(${r.origin})\uAC00 \uC9C0\uAE08 \uD398\uC774\uC9C0\uC640 \uCD9C\uCC98\uAC00 \uB2EC\uB77C SDK \uAC00 \uD1A0\uD070\uC744 \uBC1B\uC544\uB4E4\uC774\uC9C0 \uBABB\uD569\uB2C8\uB2E4. \uB85C\uADF8\uC778\uC744 \uC2DC\uC791\uD55C \uD398\uC774\uC9C0\uC640 \uAC19\uC740 \uCD9C\uCC98\uB97C \uCF5C\uBC31\uC73C\uB85C \uC9C0\uC815\uD558\uC138\uC694.`)}catch{}return s}async signInWithPopup(e,t,s={}){let r=s.intent??"signin",i=wt();if(i){let m=i.getCallbackScheme(),g=new URLSearchParams({app_callback:m,intent:r,state:be(),response_type:ye}),v=await this.http.get(`/v1/public/oauth/${e}/authorize/central?${g.toString()}`),{url:_}=await i.signIn(v.authorization_url,m),P=new URL(_),y=se(P.searchParams.get("state")),D=P.searchParams.get("error");if(D)throw new Error(D);if(!y.valid)throw ve(),new Error(te);let E=await this.readBridgeResult(P.searchParams);return this.http.setTokens(E.access_token,E.refresh_token),E}let o=re();if(o&&(e==="google"||e==="apple"))throw Re()?new Error("\uC678\uBD80 \uBE0C\uB77C\uC6B0\uC800\uB85C \uC774\uB3D9\uD588\uC2B5\uB2C8\uB2E4. \uB2E4\uC2DC \uC2DC\uB3C4\uD574\uC8FC\uC138\uC694."):new Error(`\uD604\uC7AC ${o.type==="kakaotalk"?"\uCE74\uCE74\uC624\uD1A1":o.type==="line"?"\uB77C\uC778":"\uC778\uC571"} \uBE0C\uB77C\uC6B0\uC800\uC5D0\uC11C\uB294 Google/Apple \uB85C\uADF8\uC778\uC774 \uC81C\uD55C\uB429\uB2C8\uB2E4. \uC678\uBD80 \uBE0C\uB77C\uC6B0\uC800\uC5D0\uC11C \uC5F4\uC5B4\uC8FC\uC138\uC694.`);let a=new URLSearchParams;a.set("intent",r),a.set("response_type",ye),t?a.set("app_callback",t):a.set("opener_origin",window.location.origin);let c;try{c=await this.http.get(`/v1/public/oauth/${e}/authorize/central?${a.toString()}`)}catch(m){throw m instanceof b&&m.code===vt?new b(m.statusCode,`\uC774 \uD398\uC774\uC9C0(${window.location.origin})\uC5D0\uC11C\uB294 \uD31D\uC5C5 \uB85C\uADF8\uC778\uC744 \uC2DC\uC791\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uC774 \uC571\uC758 \uC6F9 \uC2A4\uD1A0\uB9AC\uC9C0 \uC8FC\uC18C\uB098 \uC5F0\uACB0\uB41C \uCEE4\uC2A4\uD140 \uB3C4\uBA54\uC778\uC5D0\uC11C \uC5EC\uC138\uC694. \uB2E4\uB978 \uC8FC\uC18C\uB77C\uBA74 \uCF58\uC194\uC758 \uC6F9 \uC2A4\uD1A0\uB9AC\uC9C0 \uBCF4\uC548 \uC124\uC815\uC5D0 \uC774 \uCD9C\uCC98\uB97C \uD5C8\uC6A9 origin \uC73C\uB85C \uCD94\uAC00\uD558\uAC70\uB098 \uB9AC\uB2E4\uC774\uB809\uD2B8 \uBC29\uC2DD(cb.oauth.signIn)\uC744 \uC4F0\uC138\uC694.`,vt):m}let l=500,u=600,d=window.screenX+(window.outerWidth-l)/2,h=window.screenY+(window.outerHeight-u)/2,p=window.open(c.authorization_url,"oauth-popup",`width=${l},height=${u},left=${d},top=${h}`);if(!p)throw new Error("\uD31D\uC5C5\uC774 \uCC28\uB2E8\uB418\uC5C8\uC2B5\uB2C8\uB2E4. \uD31D\uC5C5 \uCC28\uB2E8\uC744 \uD574\uC81C\uD574\uC8FC\uC138\uC694.");let f=this.popupMessageOrigins(c.authorization_url,t);return new Promise((m,g)=>{let v=!1,_=()=>{v=!0,window.removeEventListener("message",P),clearInterval(y),clearTimeout(D)},P=async E=>{if(E.source!==p||!f.has(E.origin)||E.data?.type!=="oauth-callback"||v)return;if(_(),E.data.error){g(new Error(E.data.error));return}let ne;try{ne=await this.readPopupResult(E.data)}catch(Ut){g(Ut);return}this.http.setTokens(ne.access_token,ne.refresh_token);try{await this.http.bootstrapRefreshCookie()}catch{}m(ne)};window.addEventListener("message",P);let y=setInterval(()=>{try{p.closed&&(v||(_(),g(new Error("\uB85C\uADF8\uC778\uC774 \uCDE8\uC18C\uB418\uC5C8\uC2B5\uB2C8\uB2E4."))))}catch{clearInterval(y)}},500),D=setTimeout(()=>{if(!v){_();try{p.close()}catch{}g(new Error("\uB85C\uADF8\uC778 \uC2DC\uAC04\uC774 \uCD08\uACFC\uB418\uC5C8\uC2B5\uB2C8\uB2E4. \uB2E4\uC2DC \uC2DC\uB3C4\uD574\uC8FC\uC138\uC694."))}},18e4)})}async readBridgeResult(e){let t=e.get("code");if(t)return this.http.post("/v1/auth/oauth/exchange",{code:t});let s=e.get("access_token")||"",r=e.get("refresh_token")||"",i=e.get("member_id")||"";if(!s||!r||!i)throw new Error("OAuth \uC751\uB2F5\uC5D0 \uD1A0\uD070\uC774 \uC5C6\uC2B5\uB2C8\uB2E4.");let o=e.get("email");return{access_token:s,refresh_token:r,member_id:i,is_new_member:e.get("is_new_member")==="true",...o?{email:o}:{}}}popupMessageOrigins(e,t){let s=new Set,r=i=>{if(i)try{s.add(new URL(i,window.location.href).origin)}catch{}};r(this.http.getBaseUrl());try{r(new URL(e).searchParams.get("redirect_uri"))}catch{}return r(t),s}async readPopupResult(e){if(typeof e.code=="string"&&e.code)return this.http.post("/v1/auth/oauth/exchange",{code:e.code});let{access_token:t,refresh_token:s,member_id:r,email:i}=e;if(typeof t!="string"||typeof s!="string"||typeof r!="string"||!t||!s||!r)throw new Error("OAuth \uC751\uB2F5\uC5D0 \uD1A0\uD070\uC774 \uC5C6\uC2B5\uB2C8\uB2E4.");return{member_id:r,access_token:t,refresh_token:s,is_new_member:e.is_new_member==="true"||e.is_new_member===!0,...typeof i=="string"&&i.length>0?{email:i}:{}}}async getCallbackResult(){let e=Ve(),t=new URLSearchParams(window.location.search),s=t.get("error");if(s){se(t.get("state"));let i={error:s};return ze()&&(window.opener.postMessage({type:"oauth-callback",...i},window.location.origin),window.close()),i}if(!e){let i=we(!0);return i==="rejected"?(ve(),{error:te}):i?this.completeCodeCallback(i):null}if(e.kind==="rejected")return{error:te};let r={access_token:e.accessToken,refresh_token:e.refreshToken,member_id:e.memberId,is_new_member:e.isNewMember,...e.email?{email:e.email}:{},state:e.appState};return e.kind==="popup"?(window.opener.postMessage({type:"oauth-callback",...r},window.location.origin),window.close(),r):(this.bootConsumePromise&&await this.bootConsumePromise||await this.loadCallbackOnce(e),r)}loadCallbackOnce(e){return this.loadedCallback?.callback!==e&&(this.http.setTokens(e.accessToken,e.refreshToken),this.loadedCallback={callback:e,done:this.http.bootstrapRefreshCookie()}),this.loadedCallback.done}captureCallbackOnBoot(){let e=Ve();if(e)return e.kind==="rejected"?"none":e.kind;let t=we(!1);return typeof t=="object"&&t?.kind==="redirect"?"redirect":"none"}consumeRedirectCallbackOnBoot(){return this.bootConsumePromise||(this.bootConsumePromise=this.doConsumeRedirectOnBoot()),this.bootConsumePromise}async doConsumeRedirectOnBoot(){try{let e=Ve();if(e)return e.kind!=="redirect"?!1:(this.http.setTokens(e.accessToken,e.refreshToken),await this.http.bootstrapRefreshCookie(),!0);let t=we(!1);return typeof t!="object"||t?.kind!=="redirect"?!1:(await this.completeCodeCallback(t),!0)}catch{return!1}}async exchangeCodeFromCallback(){let e=we(!0);if(e==="rejected")throw ve(),new Error(te);return e?this.completeCodeCallback(e):null}async completeCodeCallback(e){e.exchange||(e.exchange=this.http.post("/v1/auth/oauth/exchange",{code:e.code}));let t=await e.exchange,s={access_token:t.access_token,refresh_token:t.refresh_token,member_id:t.member_id,is_new_member:t.is_new_member,...t.email?{email:t.email}:{},state:e.appState};return e.kind==="popup"?(e.delivered||(e.delivered=!0,window.opener.postMessage({type:"oauth-callback",...s},window.location.origin),window.close()),s):(this.loadedCodeCallback?.callback!==e&&(this.http.setTokens(s.access_token,s.refresh_token),this.loadedCodeCallback={callback:e,done:this.http.bootstrapRefreshCookie()}),await this.loadedCodeCallback.done,s)}};var z=class{constructor(e){this.http=e;this.prefix="/v1/public/organizations"}async create(e){return this.http.post(this.prefix,e)}async listMine(){return(await this.http.get(this.prefix)).organizations??[]}async get(e){return this.http.get(`${this.prefix}/${e}`)}async update(e,t){return this.http.patch(`${this.prefix}/${e}`,t)}async delete(e){return this.http.delete(`${this.prefix}/${e}`)}async listMembers(e,t){let s=new URLSearchParams;t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.offset!==void 0&&s.set("offset",String(t.offset));let r=s.toString();return this.http.get(`${this.prefix}/${e}/members${r?`?${r}`:""}`)}async updateMemberRole(e,t,s){return this.http.patch(`${this.prefix}/${e}/members/${t}`,{role:s})}async removeMember(e,t){return this.http.delete(`${this.prefix}/${e}/members/${t}`)}async createInvitation(e,t){return this.http.post(`${this.prefix}/${e}/invitations`,t)}async listInvitations(e){return(await this.http.get(`${this.prefix}/${e}/invitations`)).invitations??[]}async revokeInvitation(e,t){return this.http.delete(`${this.prefix}/${e}/invitations/${t}`)}async acceptInvitation(e){return this.http.post(`${this.prefix}/invitations/accept`,{token:e})}async switchTo(e){let t=await this.http.post(`${this.prefix}/${e}/context`,{});return t?.access_token&&this.http.setAccessToken(t.access_token),t}};var Pe=class{constructor(e){this.http=e}getPublicPrefix(){return this.http.hasPublicKey()?"/v1/public":"/v1"}async prepare(e){let t=this.getPublicPrefix();return this.http.post(`${t}/payments/prepare`,e)}async createCheckoutSession(e){let t=this.getPublicPrefix(),s=await this.http.post(`${t}/payments/checkout-session`,e);return S(s,{session_id:{type:"string"},session_url:{type:"string"}},"payment.createCheckoutSession"),s}async confirm(e){let t=this.getPublicPrefix();return this.http.post(`${t}/payments/confirm`,e)}async cancel(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/payments/cancel`,{payment_id:e,...t})}async getByOrderId(e){let t=this.getPublicPrefix();return this.http.get(`${t}/payments/orders/${e}`)}async list(e,t){if(this.http.hasPublicKey()&&!this.http.hasJWT())throw new Error('cb.payment.list() \uB294 \uCF58\uC194 JWT \uB610\uB294 service_role(ctx.cbAdmin, management_scopes: ["payment:read"]) \uC778\uC99D\uC774 \uD544\uC694\uD569\uB2C8\uB2E4. Public Key(cb_pk_) \uB2E8\uB3C5 SDK \uC778\uC2A4\uD134\uC2A4\uB85C\uB294 \uD638\uCD9C\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 Functions \uD658\uACBD\uC5D0\uC11C \uC0AC\uC6A9\uD558\uC138\uC694.');let s=new URLSearchParams;t?.status&&s.set("status",t.status),t?.mode&&s.set("mode",t.mode),t?.startDate&&s.set("start_date",t.startDate),t?.endDate&&s.set("end_date",t.endDate),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.offset!==void 0&&s.set("offset",String(t.offset));let r=s.toString();return this.http.get(`/v1/apps/${e}/payments${r?`?${r}`:""}`)}};var Se=class{constructor(e){this.http=e}ensureServerAuth(e){if(this.http.hasPublicKey()&&!this.http.hasJWT())throw new Error(`cb.publicKey.${e}() \uB294 \uCF58\uC194 JWT \uB610\uB294 service_role(ctx.cbAdmin, management_scopes: ["publickey:read" | "publickey:manage"]) \uC778\uC99D\uC774 \uD544\uC694\uD569\uB2C8\uB2E4. Public Key(cb_pk_) \uB2E8\uB3C5 SDK \uC778\uC2A4\uD134\uC2A4\uB85C\uB294 \uD638\uCD9C\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 Functions \uD658\uACBD\uC5D0\uC11C \uC0AC\uC6A9\uD558\uC138\uC694.`)}async getPublicKeys(e){return this.ensureServerAuth("getPublicKeys"),this.http.get(`/v1/apps/${e}/public-keys`)}async createPublicKey(e,t){return this.ensureServerAuth("createPublicKey"),this.http.post(`/v1/apps/${e}/public-keys`,t)}async updatePublicKey(e,t,s){return this.ensureServerAuth("updatePublicKey"),this.http.patch(`/v1/apps/${e}/public-keys/${t}`,s)}async deletePublicKey(e,t){this.ensureServerAuth("deletePublicKey"),await this.http.delete(`/v1/apps/${e}/public-keys/${t}`)}async rotatePublicKey(e,t,s){return this.ensureServerAuth("rotatePublicKey"),this.http.post(`/v1/apps/${e}/public-keys/${t}/rotate`,s??{})}};var ke=class{constructor(e){this.http=e}getPublicPrefix(){return this.http.hasPublicKey()?"/v1/public":"/v1"}async registerDevice(e){let t=this.getPublicPrefix(),s=await this.http.post(`${t}/push/devices`,e);return S(s,{device_token:{type:"string"}},"push.registerDevice"),s}async unregisterDevice(e){let t=this.getPublicPrefix();await this.http.post(`${t}/push/devices/unregister`,{device_token:e})}async subscribeTopic(e,t){let s=this.getPublicPrefix(),r={device_token:e,topic_name:t};await this.http.post(`${s}/push/topics/subscribe`,r)}async unsubscribeTopic(e,t){let s=this.getPublicPrefix(),r={device_token:e,topic_name:t};await this.http.post(`${s}/push/topics/unsubscribe`,r)}async getVAPIDPublicKey(){let e=this.getPublicPrefix();return this.http.get(`${e}/push/vapid-public-key`)}async registerWebPush(e){let t=this.getPublicPrefix(),s;if("toJSON"in e){let i=e.toJSON();s={endpoint:i.endpoint||"",expirationTime:i.expirationTime,keys:{p256dh:i.keys?.p256dh||"",auth:i.keys?.auth||""}}}else s=e;let r={device_token:s.endpoint,platform:"web",device_id:this.generateDeviceId(),device_name:this.getBrowserName(),os_version:this.getOSInfo()};return this.http.post(`${t}/push/devices`,{...r,web_push_subscription:s})}async unregisterWebPush(e){await this.unregisterDevice(e)}async sendToMembers(e,t,s){if(this.http.hasPublicKey()&&!this.http.hasJWT())throw new Error("cb.push.sendToMembers() \uB294 User Secret Key(cb_sk_), \uCF58\uC194 JWT, \uB610\uB294 service_role(ctx.cbAdmin) \uC778\uC99D\uC774 \uD544\uC694\uD569\uB2C8\uB2E4. Public Key(cb_pk_) \uB2E8\uB3C5 SDK \uC778\uC2A4\uD134\uC2A4\uB85C\uB294 \uD638\uCD9C\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 Functions \uD658\uACBD\uC5D0\uC11C \uC0AC\uC6A9\uD558\uC138\uC694.");if(t.length===0)throw new Error("cb.push.sendToMembers(): memberIds \uAC00 \uBE44\uC5B4\uC788\uC2B5\uB2C8\uB2E4.");let r={target_type:"members",target_member_ids:t,title:s.title,body:s.body,...s.imageUrl!==void 0?{image_url:s.imageUrl}:{},...s.data!==void 0?{data:s.data}:{},...s.platforms!==void 0?{platforms:s.platforms}:{},...s.ttlSeconds!==void 0?{ttl:s.ttlSeconds}:{},...s.priority!==void 0?{priority:s.priority}:{},...s.clickAction!==void 0?{click_action:s.clickAction}:{},...s.scheduledAt!==void 0?{scheduled_at:s.scheduledAt}:{}};return this.http.post(`/v1/apps/${e}/push/send`,r)}async sendToTopic(e,t,s){if(this.http.hasPublicKey()&&!this.http.hasJWT())throw new Error("cb.push.sendToTopic() \uB294 User Secret Key(cb_sk_), \uCF58\uC194 JWT, \uB610\uB294 service_role(ctx.cbAdmin) \uC778\uC99D\uC774 \uD544\uC694\uD569\uB2C8\uB2E4. Public Key(cb_pk_) \uB2E8\uB3C5 SDK \uC778\uC2A4\uD134\uC2A4\uB85C\uB294 \uD638\uCD9C\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 Functions \uD658\uACBD\uC5D0\uC11C \uC0AC\uC6A9\uD558\uC138\uC694.");if(!t)throw new Error("cb.push.sendToTopic(): topicName \uC774 \uBE44\uC5B4\uC788\uC2B5\uB2C8\uB2E4.");let r={topic_name:t,title:s.title,body:s.body,...s.imageUrl!==void 0?{image_url:s.imageUrl}:{},...s.data!==void 0?{data:s.data}:{},...s.platforms!==void 0?{platforms:s.platforms}:{},...s.ttlSeconds!==void 0?{ttl:s.ttlSeconds}:{},...s.priority!==void 0?{priority:s.priority}:{},...s.clickAction!==void 0?{click_action:s.clickAction}:{},...s.scheduledAt!==void 0?{scheduled_at:s.scheduledAt}:{}};return this.http.post(`/v1/apps/${e}/push/send-to-topic`,r)}async createTopic(e,t,s={}){if(this.http.hasPublicKey()&&!this.http.hasJWT())throw new Error("cb.push.createTopic() \uB294 User Secret Key(cb_sk_), \uCF58\uC194 JWT, \uB610\uB294 service_role(ctx.cbAdmin) \uC778\uC99D\uC774 \uD544\uC694\uD569\uB2C8\uB2E4. Public Key(cb_pk_) \uB2E8\uB3C5 SDK \uC778\uC2A4\uD134\uC2A4\uB85C\uB294 \uD1A0\uD53D\uC744 \uB9CC\uB4E4 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 Functions \uD658\uACBD\uC5D0\uC11C \uC0AC\uC6A9\uD558\uC138\uC694.");if(!t||!t.trim())throw new Error("cb.push.createTopic(): name \uC774 \uBE44\uC5B4\uC788\uC2B5\uB2C8\uB2E4.");return this.http.post(`/v1/apps/${e}/push/topics`,{name:t,if_not_exists:!0,...s.displayName!==void 0?{display_name:s.displayName}:{},...s.description!==void 0?{description:s.description}:{}})}async getStats(e){if(this.http.hasPublicKey()&&!this.http.hasJWT())throw new Error('cb.push.getStats() \uB294 \uCF58\uC194 JWT \uB610\uB294 service_role(ctx.cbAdmin, management_scopes: ["push:read"]) \uC778\uC99D\uC774 \uD544\uC694\uD569\uB2C8\uB2E4. Public Key(cb_pk_) \uB2E8\uB3C5 SDK \uC778\uC2A4\uD134\uC2A4\uB85C\uB294 \uD638\uCD9C\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 Functions \uD658\uACBD\uC5D0\uC11C \uC0AC\uC6A9\uD558\uC138\uC694.');return this.http.get(`/v1/apps/${e}/push/stats`)}generateDeviceId(){if(typeof window>"u"||typeof localStorage>"u")return`device_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;let e="cb_push_device_id",t=localStorage.getItem(e);return t||(t=`web_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,localStorage.setItem(e,t)),t}getBrowserName(){if(typeof navigator>"u")return"Unknown Browser";let e=navigator.userAgent;return e.includes("Chrome")&&!e.includes("Edg")?"Chrome":e.includes("Safari")&&!e.includes("Chrome")?"Safari":e.includes("Firefox")?"Firefox":e.includes("Edg")?"Edge":e.includes("Opera")||e.includes("OPR")?"Opera":"Unknown Browser"}getOSInfo(){if(typeof navigator>"u")return"Unknown OS";let e=navigator.userAgent;return e.includes("Windows")?"Windows":e.includes("Mac OS")?"macOS":e.includes("Linux")?"Linux":e.includes("Android")?"Android":e.includes("iOS")||e.includes("iPhone")||e.includes("iPad")?"iOS":"Unknown OS"}};var Te=class{constructor(e){this.http=e}async publish(e,t){return this.http.post(`/v1/public/queues/${e}/messages`,t)}async publishBatch(e,t){return this.http.post(`/v1/public/queues/${e}/messages/batch`,t)}async consume(e,t){let s=new URLSearchParams;t?.max_messages&&s.set("max_messages",String(t.max_messages)),t?.visibility_timeout&&s.set("visibility_timeout",String(t.visibility_timeout)),t?.auto_ack!==void 0&&s.set("auto_ack",String(t.auto_ack));let r=s.toString(),i=await this.http.get(`/v1/public/queues/${e}/messages${r?`?${r}`:""}`);return S(i,{messages:{type:"array"}},"queue.consume"),i}async ack(e,t,s){let r={message_ids:t,ack_token:s};return this.http.post(`/v1/public/queues/${e}/messages/ack`,r)}async nack(e,t,s){return this.http.post(`/v1/public/queues/${e}/messages/${t}/nack`,s||{})}async getInfo(e){return this.http.get(`/v1/public/queues/${e}`)}};var Ps=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ss(n){if(n.event!=="error"||n.request_id)return null;let e=n.data;return!e||typeof e.close_code!="number"?null:new R({code:e.code,message:e.message||n.error,closeCode:e.close_code,retryable:e.retryable,details:e.details,retryAfterMs:typeof e.retry_after_ms=="number"&&e.retry_after_ms>0?e.retry_after_ms:void 0})}var ie=class extends Error{},Ie=class extends Error{constructor(){super("Realtime connect cancelled by disconnect()"),this.name="AbortError"}},ks=2,Ts=new Set(["rate_limited","auth_unavailable","invalid_ws_ticket","ws_ticket_unavailable"]),Cs=600,St=60,Is=3e4,Es=new Set(["TOKEN_EXPIRED","MEMBER_REVOKED"]),As=/^[A-Za-z0-9_-]{1,128}$/,xs=/^[A-Za-z0-9._-]{1,128}$/,kt=256;function $s(n,e){if(e===void 0)return n;let t=r=>typeof r=="string"?JSON.stringify(r):String(r);if(typeof e!="string"||!xs.test(e))throw new Error(`Invalid room ${t(e)}: use 1-128 characters of letters, digits, "-", "_" or "." (the realtime channel is "<category>:<room>").`);if(typeof n!="string"||!As.test(n))throw new Error(`Invalid category ${t(n)} for a room subscription: use the base category name (1-128 characters of letters, digits, "-" or "_") and pass the room separately with { room }.`);let s=`${n}:${e}`;if(s.length>kt)throw new Error(`Realtime channel "${s}" is too long (max ${kt} characters including ":").`);return s}function Ms(n){let e=n.indexOf(":");return e>0&&e<n.length-1?n.slice(e+1):void 0}function Tt(n){return It(n)}function It(n){return typeof n=="string"&&n!==""?n:void 0}function Ce(n){return Math.floor(Math.random()*Math.max(0,n))}function Os(n){return n==="upstream"||n==="publishers_only"?n:"open"}function Ct(n){return{category:n.category,persist:n.persist,historyCount:n.history_count,readReceipt:n.read_receipt,isPublisher:n.publisher===!0,sendPolicy:Os(n.send_policy)}}var Ee=class{constructor(e,t){this.ws=null;this.state="disconnected";this._connectionId=null;this._appId=null;this.activeTransport=null;this.sseFallbackActive=!1;this.sseSessions=new Map;this.options={maxRetries:5,retryInterval:1e3,userId:"",accessToken:"",timeout:3e4,debug:!1,fallback:"sse"};this.retryCount=0;this.pendingRestore=null;this.directRealtimePrimed=!1;this.connectGeneration=0;this.initialConnecting=!1;this.reconnectFloorMs=0;this.cancelConnectWait=null;this.pendingRequests=new Map;this.subscriptions=new Map;this.streamSessions=new Map;this.stateHandlers=[];this.errorHandlers=[];this.presenceHandlers=[];this.presenceSubscriptions=new Map;this.typingHandlers=new Map;this.readReceiptHandlers=new Map;this.connectPromise=null;this.tokenRefreshNegotiated=!1;this.authRefreshInFlight=null;this.authRefreshRetryTimer=null;this.closeNotice=null;this.http=e,this.socketUrl=t,this.clientId=this.generateClientId()}get connectionId(){return this._connectionId}get appId(){return this._appId}get transport(){return this.activeTransport}async connect(e={}){if(this.state!=="connected"){if(this.connectPromise)return this.connectPromise;if(this.options={...this.options,...e},e.userId&&(this.userId=e.userId),this.userId&&!this.options.accessToken&&Ps.test(this.userId))throw new Error(`Invalid userId: "${this.userId}" looks like a UUID, which is reserved for authenticated members. Pass that member's accessToken (JWT) instead of userId+publicKey, or use a non-UUID identifier for anonymous/guest connections.`);this.connectPromise=this.primeDirectRealtime().then(()=>this.connectWithRetry());try{await this.connectPromise}catch(t){if(t instanceof R||t instanceof Ie)throw t;let s=!!(this.options.accessToken||this.http.getPublicKey());if(this.options.fallback!=="none"&&s)this.activateSseFallback(t);else throw t}finally{this.connectPromise=null}}}activateSseFallback(e){if(this.sseFallbackActive)return;if(this.ws){try{this.ws.close()}catch{}this.ws=null}let t=e instanceof Error?e.message:String(e);this.sseFallbackActive=!0,this.activeTransport="sse",this.state="connected",this.retryCount=0,this.pendingRestore=null,this.log(`WS unavailable (${t}); using SSE fallback transport for AI streaming`),this.notifyStateChange(),this.notifyError(new Error(`Realtime WebSocket unavailable, downgraded to SSE fallback transport (cb.realtime.transport === 'sse'). Only realtime.stream() works in this mode \u2014 subscribe/send/setPresence/typing calls will throw. Cause: ${t}`))}disconnect(){this.connectGeneration++,this.cancelConnectWait?.(),this.state="disconnected",this.notifyStateChange(),this.ws&&(this.ws.close(),this.ws=null),this.pendingRequests.forEach(e=>{clearTimeout(e.timeout),e.reject(new Error("Connection closed"))}),this.pendingRequests.clear(),this.subscriptions.clear(),this.streamSessions.forEach((e,t)=>{e.handlers.onError&&e.handlers.onError(new T({code:"service_unavailable",message:"\uC2E4\uC2DC\uAC04 \uC5F0\uACB0\uC774 \uC885\uB8CC\uB418\uC5B4 AI \uC2A4\uD2B8\uB9AC\uBC0D\uC774 \uC911\uB2E8\uB418\uC5C8\uC2B5\uB2C8\uB2E4. \uC7AC\uC5F0\uACB0 \uD6C4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694.",retryable:!0,sessionId:t}))}),this.streamSessions.clear(),this.sseSessions.forEach(e=>{try{e.abort()}catch{}}),this.sseSessions.clear(),this.sseFallbackActive=!1,this.activeTransport=null,this.presenceHandlers=[],this.presenceSubscriptions.clear(),this.typingHandlers.clear(),this.readReceiptHandlers.clear(),this._connectionId=null,this._appId=null,this.retryCount=0,this.connectPromise=null,this.pendingRestore=null,this.clearAuthRefreshRetry(),this.tokenRefreshNegotiated=!1,this.closeNotice=null}async subscribe(e,t={}){let s=$s(e,t.room);if(this.assertBidirectional("subscribe"),this.state!=="connected")throw new Error("Not connected. Call connect() first.");let r=this.generateRequestId(),i=await this.sendRequest({category:s,action:"subscribe",request_id:r}),o=Ct(i),a=[];return this.subscriptions.set(s,{info:o,handlers:a}),{info:o,channel:s,room:Ms(s),send:async(l,u)=>{await this.sendMessage(s,l,u)},getHistory:async l=>this.getHistory(s,l??t.historyLimit),unsubscribe:async()=>{await this.unsubscribe(s)},onMessage:l=>(a.push(l),()=>{let u=a.indexOf(l);u>-1&&a.splice(u,1)})}}async unsubscribe(e){if(this.state!=="connected")return;let t=this.generateRequestId();await this.sendRequest({category:e,action:"unsubscribe",request_id:t}),this.subscriptions.delete(e)}async sendMessage(e,t,s={}){if(this.assertBidirectional("sendMessage"),this.state!=="connected")throw new Error("Not connected");let i=s.includeSelf!==!1,o=this.generateRequestId();await this.sendRequest({category:e,action:"send",data:s.to?{data:t,broadcast:i,to:s.to}:{data:t,broadcast:i},request_id:o})}async getHistory(e,t){if(this.assertBidirectional("getHistory"),this.state!=="connected")throw new Error("Not connected");let s=this.generateRequestId(),r=await this.sendRequest({category:e,action:"history",data:t?{limit:t}:void 0,request_id:s});return{category:r.category,messages:r.messages.map(i=>({id:i.id,category:i.category,from:i.from,fromMember:Tt(i.from_member),data:i.data,sentAt:i.sent_at})),total:r.total}}async stream(e,t,s={}){if(this.state==="connected"&&this.activeTransport==="ws"&&this.ws?.readyState===WebSocket.OPEN)try{return this.streamViaWS(e,t,s)}catch(i){if(this.options.fallback==="none")throw i;this.log(`WS stream send failed (${i instanceof Error?i.message:String(i)}); falling back to SSE`)}if(this.options.fallback!=="none")return this.streamViaSSE(e,t,s);throw new Error("Not connected. Call connect() first.")}streamViaWS(e,t,s){let r=this.generateRequestId(),i=s.sessionId||this.generateRequestId();this.streamSessions.set(i,{handlers:t,requestId:r});try{this.sendRaw({category:"",action:"stream",data:{provider:s.provider,model:s.model,messages:e,system:s.system,temperature:s.temperature,max_tokens:s.maxTokens,session_id:i,metadata:s.metadata,mcp_group:s.mcpGroup},request_id:r})}catch(o){throw this.streamSessions.delete(i),o}return{sessionId:i,stop:async()=>{await this.stopStream(i)}}}streamViaSSE(e,t,s){let r=s.sessionId||this.generateRequestId(),i=new AbortController;return this.sseSessions.set(r,i),s.mcpGroup&&this.log("mcpGroup is not supported in SSE fallback mode; streaming without MCP tools"),this.log(`Streaming via SSE fallback (session ${r})`),this.runSseStream(r,e,t,s,i.signal),{sessionId:r,stop:async()=>{await this.stopStream(r)}}}async runSseStream(e,t,s,r,i){let o=Date.now(),a=0,c="",l,d={messages:r.system?[{role:"system",content:r.system},...t]:t,provider:r.provider,model:r.model,temperature:r.temperature,maxTokens:r.maxTokens};try{let h=await this.http.fetchRaw("/v1/public/ai/chat/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:i});if(!h.ok){let m=await h.json().catch(()=>({error:"stream_failed"}));s.onError?.(M(m,{message:"Stream request failed",sessionId:e,status:h.status}));return}if(l=h.body?.getReader(),!l){s.onError?.(new T({code:"stream_failed",message:"ReadableStream not supported",retryable:!1,sessionId:e}));return}let p=new TextDecoder,f="";for(;;){let{done:m,value:g}=await l.read();if(m)break;f+=p.decode(g,{stream:!0});let v=f.split(`
3
3
  `);f=v.pop()||"";for(let _ of v){if(!_.startsWith("data: "))continue;let P=_.slice(6).trim();if(P==="[DONE]"){s.onDone?.({sessionId:e,fullText:c,totalTokens:0,promptTokens:0,duration:Date.now()-o});return}try{let y=JSON.parse(P);if(y.error){s.onError?.(M(y,{sessionId:e}));return}if(y.type==="tool_start"){s.onToolCall?.(y.name||"",y.arguments||{},a);continue}if(y.type==="tool_end"){s.onToolResult?.(y.name||"",y.success!==!1,y.durationMs||0,a);continue}if(y.type==="sources"||y.type==="searching"||y.type==="heartbeat")continue;if(y.content&&(c+=y.content,s.onToken?.(y.content,a++)),y.done){s.onDone?.({sessionId:e,fullText:c,totalTokens:0,promptTokens:0,duration:Date.now()-o});return}}catch{}}}}catch(h){i.aborted||h instanceof DOMException&&h.name==="AbortError"||typeof h=="object"&&h!==null&&h.name==="AbortError"||s.onError?.(new T({code:"service_unavailable",message:h instanceof Error?h.message:String(h)||"AI \uC2A4\uD2B8\uB9AC\uBC0D \uC694\uCCAD\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4",retryable:!0,sessionId:e}))}finally{if(this.sseSessions.delete(e),l)try{await l.cancel()}catch{}}}async stopStream(e){let t=this.sseSessions.get(e);if(t){t.abort(),this.sseSessions.delete(e);return}if(this.state!=="connected"||!this.ws||this.ws.readyState!==WebSocket.OPEN){this.streamSessions.delete(e);return}let s=this.generateRequestId();this.sendRaw({category:"",action:"stream_stop",data:{session_id:e},request_id:s}),this.streamSessions.delete(e)}getState(){return this.state}isConnected(){return this.state==="connected"&&this.activeTransport==="ws"}isDegraded(){return this.sseFallbackActive}isStreamReady(){return this.state==="connected"}onStateChange(e){return this.stateHandlers.push(e),()=>{let t=this.stateHandlers.indexOf(e);t>-1&&this.stateHandlers.splice(t,1)}}onError(e){return this.errorHandlers.push(e),()=>{let t=this.errorHandlers.indexOf(e);t>-1&&this.errorHandlers.splice(t,1)}}async setPresence(e,t={}){if(this.assertBidirectional("setPresence"),this.state!=="connected")throw new Error("Not connected");let s=this.generateRequestId();await this.sendRequest({category:"",action:"presence_set",data:{status:e,device:t.device,metadata:t.metadata},request_id:s})}async setPresenceOnDisconnect(e,t){if(this.assertBidirectional("setPresenceOnDisconnect"),this.state!=="connected")throw new Error("Not connected");let s=this.generateRequestId();await this.sendRequest({category:"",action:"presence_on_disconnect",data:{status:e,metadata:t},request_id:s})}async getPresence(e){if(this.assertBidirectional("getPresence"),this.state!=="connected")throw new Error("Not connected");let t=this.generateRequestId(),s=await this.sendRequest({category:"",action:"presence_get",data:{user_id:e},request_id:t});return{userId:s.user_id,status:s.status,lastSeen:s.last_seen,device:s.device,metadata:s.metadata}}async getPresenceMany(e){if(this.assertBidirectional("getPresenceMany"),this.state!=="connected")throw new Error("Not connected");let t=this.generateRequestId(),s=await this.sendRequest({category:"",action:"presence_get_many",data:{user_ids:e},request_id:t}),r={};for(let[i,o]of Object.entries(s.users))r[i]={userId:o.user_id,status:o.status,lastSeen:o.last_seen,device:o.device,metadata:o.metadata};return{users:r}}async subscribePresence(e,t){if(this.assertBidirectional("subscribePresence"),this.state!=="connected")throw new Error("Not connected");if(!this.presenceSubscriptions.has(e)){let r=this.generateRequestId();await this.sendRequest({category:"",action:"presence_subscribe",data:{user_id:e},request_id:r}),this.presenceSubscriptions.set(e,[])}let s=this.presenceSubscriptions.get(e);return s.push(t),()=>{let r=s.indexOf(t);if(r>-1&&s.splice(r,1),s.length===0&&(this.presenceSubscriptions.delete(e),this.state==="connected")){let i=this.generateRequestId();this.sendRequest({category:"",action:"presence_unsubscribe",data:{user_id:e},request_id:i}).catch(o=>{this.log(`Failed to unsubscribe presence for ${e}: ${o}`)})}}}onPresenceChange(e){return this.presenceHandlers.push(e),()=>{let t=this.presenceHandlers.indexOf(e);t>-1&&this.presenceHandlers.splice(t,1)}}async startTyping(e){if(this.assertBidirectional("startTyping"),this.state!=="connected")throw new Error("Not connected");let t=this.generateRequestId();await this.sendRequest({category:"",action:"typing_start",data:{room_id:e},request_id:t})}async stopTyping(e){if(this.assertBidirectional("stopTyping"),this.state!=="connected")throw new Error("Not connected");let t=this.generateRequestId();await this.sendRequest({category:"",action:"typing_stop",data:{room_id:e},request_id:t})}async onTypingChange(e,t){if(this.assertBidirectional("onTypingChange"),this.state!=="connected")throw new Error("Not connected");if(!this.typingHandlers.has(e)){let r=this.generateRequestId();await this.sendRequest({category:"",action:"typing_subscribe",data:{room_id:e},request_id:r}),this.typingHandlers.set(e,[])}let s=this.typingHandlers.get(e);return s.push(t),()=>{let r=s.indexOf(t);if(r>-1&&s.splice(r,1),s.length===0&&(this.typingHandlers.delete(e),this.state==="connected")){let i=this.generateRequestId();this.sendRequest({category:"",action:"typing_unsubscribe",data:{room_id:e},request_id:i}).catch(o=>{this.log(`Failed to unsubscribe typing for ${e}: ${o}`)})}}}async markRead(e,t){if(this.assertBidirectional("markRead"),this.state!=="connected")throw new Error("Not connected");let s=this.generateRequestId();await this.sendRequest({category:e,action:"mark_read",data:{message_ids:t},request_id:s})}onReadReceipt(e,t){this.readReceiptHandlers.has(e)||this.readReceiptHandlers.set(e,[]);let s=this.readReceiptHandlers.get(e);return s.push(t),()=>{let r=s.indexOf(t);r>-1&&s.splice(r,1)}}async primeDirectRealtime(){if(!this.directRealtimePrimed&&(this.directRealtimePrimed=!0,!this.http.getDirectRealtimeBaseUrl()))try{await this.http.primeEdgeHints(1500)}catch(e){this.log(`edge hint lookup failed, using default socket URL: ${e instanceof Error?e.message:String(e)}`)}}async connectWithRetry(){let e=this.connectGeneration,t=Date.now()+this.options.timeout,s=0;this.initialConnecting=!0;try{for(let r=1;;r++)try{await this.prepareConnectToken();let i=await this.connectTicket(Math.max(t-Date.now(),1));await this.doConnect(Math.max(t-Date.now(),1),i);return}catch(i){let o=null;if(i instanceof R&&i.retryable){if(i.retryAfterMs!==void 0)o=i.retryAfterMs+Ce(Math.min(100*2**r,3e3));else if(Ts.has(i.code)){let a=Math.min(500*2**(r-1),8e3);o=a/2+Ce(a/2)}}else if(i instanceof ie&&s<ks){s++;let a=500*2**(s-1);o=a/2+Ce(a/2)}if(o===null||Date.now()+o>=t)throw this.state==="connecting"&&(this.state="disconnected",this.notifyStateChange()),i;if(this.log(`Connect attempt ${r} failed (${i instanceof Error?i.message:String(i)}); retrying in ${o}ms`),await new Promise(a=>{let c=setTimeout(a,o);this.cancelConnectWait=()=>{clearTimeout(c),a()}}),this.cancelConnectWait=null,e!==this.connectGeneration)throw new Ie}}finally{this.initialConnecting=!1}}async connectTicket(e){let t=this.options.accessToken,s=t?void 0:this.http.getPublicKey();if(!t&&!s)return null;try{return await x($(this.socketUrl,"/v1/realtime/ws-ticket"),"socket.realtime",t?{kind:"access_token",value:t}:{kind:"public_key",value:s},{timeoutMs:e})}catch(r){throw r instanceof C?(this.log(`WebSocket ticket rejected: ${r.code} (${r.status})`),new R({code:r.code,message:r.message,closeCode:4e3+r.status,retryAfterMs:r.retryAfterMs})):r}}async doConnect(e=this.options.timeout,t=null){return new Promise((s,r)=>{this.state="connecting",this.notifyStateChange(),this.log("Connecting...");let i=this.http.getDirectRealtimeBaseUrl(),o=!!i,a=(i??this.socketUrl).replace(/^http/,"ws"),c,l=t?`ticket=${encodeURIComponent(t)}`:void 0;if(this.tokenRefreshNegotiated=!1,this.options.accessToken)c=`${a}/v1/realtime/auth?${l??`access_token=${encodeURIComponent(this.options.accessToken)}`}&client_id=${this.clientId}`,this.http.canRefreshMemberToken(this.options.accessToken)&&(this.tokenRefreshNegotiated=!0,c+="&token_refresh=1"),this.log("Using accessToken authentication");else{let p=this.http.getPublicKey();if(!p){let f=new Error("API Key or accessToken is required for realtime connection");this.log("Connection failed: no API Key or accessToken"),r(f);return}c=`${a}/v1/realtime/auth?${l??`public_key=${encodeURIComponent(p)}`}&client_id=${this.clientId}`,this.log("Using API Key authentication")}this.userId&&(c+=`&user_id=${encodeURIComponent(this.userId)}`),c+="&reject_mode=close";let u=!1,d=null,h=setTimeout(()=>{u||(u=!0,this.log(`Connection timeout after ${this.options.timeout}ms`),this.ws&&(this.ws.close(),this.ws=null),o&&this.http.disableDirectRealtime(),this.state="disconnected",this.notifyStateChange(),r(new Error(`Connection timeout after ${this.options.timeout}ms`)))},e);try{this.log(`Connecting to ${a}`),this.ws=new WebSocket(c),this.ws.onopen=()=>{this.log("WebSocket opened, waiting for connected event...")},this.ws.onmessage=p=>{let f=p.data.split(`
4
- `).filter(m=>m.trim());for(let m of f)try{let g=JSON.parse(m),v=Ss(g);if(v&&!u){d=v;continue}this.handleServerMessage(g,()=>{u||(u=!0,clearTimeout(h),this.log("Connected successfully"),s())})}catch(g){this.logError("Failed to parse message",{line:m,error:g})}},this.ws.onclose=p=>{if(this.log(`WebSocket closed: code=${p.code}, reason=${p.reason}`),p.code>=4e3&&p.code<=4999){let f=d??new R({code:p.reason||void 0,closeCode:p.code,message:this.closeNotice??void 0});this.closeNotice=null,this.clearAuthRefreshRetry();let m=this.state==="connected";if(u||(u=!0,clearTimeout(h)),this.ws=null,m){f.retryable||f.code==="token_expired"&&this.http.canRefreshMemberToken(this.options.accessToken)?this.handleDisconnect():this.failRealtime(f);return}this.state="disconnected",this.notifyStateChange(),r(f);return}if(!u&&this.state==="connecting"&&(u=!0,clearTimeout(h),o&&this.http.disableDirectRealtime(),r(new ie(`Connection closed: ${p.reason||"unknown reason"}`))),this.initialConnecting&&this.state==="connecting"){this.state="disconnected",this.ws=null;return}(this.state==="connected"||this.state==="connecting")&&this.handleDisconnect()},this.ws.onerror=p=>{this.log("WebSocket error occurred"),this.logError("WebSocket error",p),this.initialConnecting||this.notifyError(new Error("WebSocket connection error")),!u&&this.state==="connecting"&&(u=!0,clearTimeout(h),o&&this.http.disableDirectRealtime(),r(new ie("Failed to connect")))}}catch(p){u=!0,clearTimeout(h),o&&this.http.disableDirectRealtime(),r(p)}})}async prepareConnectToken(){let e=this.options.accessToken;if(!e||!this.http.canRefreshMemberToken(e)||!F(e,St))return;let t=await this.http.freshTokenForMember(e,St);t&&(this.options.accessToken=t)}refreshConnectionAuth(){if(!this.tokenRefreshNegotiated||this.state!=="connected"||!this.ws)return Promise.resolve(!1);if(this.authRefreshInFlight)return this.authRefreshInFlight;this.clearAuthRefreshRetry();let e=(async()=>{let t=this.options.accessToken;try{let s=await this.http.freshTokenForMember(t,Cs,{replace:!0});if(!s||s===t)throw new Error("No fresh access token from the SDK session");return await this.sendRequest({category:"",action:"auth_refresh",data:{access_token:s},request_id:this.generateRequestId()}),this.options.accessToken=s,this.closeNotice=null,this.log("Access token refreshed over the connection"),!0}catch(s){return this.logError("auth_refresh failed",s),this.http.canRefreshMemberToken(this.options.accessToken)&&this.scheduleAuthRefreshRetry(),!1}finally{this.authRefreshInFlight=null}})();return this.authRefreshInFlight=e,e}scheduleAuthRefreshRetry(){this.authRefreshRetryTimer||!this.tokenRefreshNegotiated||(this.authRefreshRetryTimer=setTimeout(()=>{this.authRefreshRetryTimer=null,this.refreshConnectionAuth()},Is))}clearAuthRefreshRetry(){this.authRefreshRetryTimer&&(clearTimeout(this.authRefreshRetryTimer),this.authRefreshRetryTimer=null)}log(e){this.options.debug&&console.log(`[Realtime] ${e}`)}logError(e,t){this.options.debug&&console.error(`[Realtime] ${e}`,t)}handleServerMessage(e,t){switch(e.event){case"connected":{let s=e.data;this._connectionId=s.connection_id,this._appId=s.app_id,this.closeNotice=null,this.clearAuthRefreshRetry(),this.state="connected",this.activeTransport="ws",this.sseFallbackActive=!1,this.retryCount=0,this.notifyStateChange(),t&&t();break}case"subscribed":case"unsubscribed":case"sent":case"result":case"history":case"token_refreshed":{if(e.request_id){let s=this.pendingRequests.get(e.request_id);s&&(clearTimeout(s.timeout),s.resolve(e.data),this.pendingRequests.delete(e.request_id))}break}case"message":{let s=e.data,r=this.subscriptions.get(s.category);if(r){let i={id:s.id,category:s.category,from:s.from,fromMember:Tt(s.from_member),fromConn:It(s.from_conn),data:s.data,sentAt:s.sent_at,fromPublisher:s.from_publisher===!0};r.handlers.forEach(o=>o(i))}break}case"error":{if(e.request_id){let s=this.pendingRequests.get(e.request_id);if(s){clearTimeout(s.timeout);let r=e.data;s.reject(new q({code:r?.code,message:e.error||"Unknown error",category:e.category})),this.pendingRequests.delete(e.request_id)}}else{let s=e.data;s?.code&&Es.has(s.code)?this.closeNotice=e.error||s.code:this.notifyError(new Error(e.error||"Unknown error"))}break}case"pong":break;case"token_expiring":case"token_expired":{this.log(`Server sent ${e.event}; refreshing the access token over the connection`),this.refreshConnectionAuth();break}case"stream_token":{let s=e.data,r=this.streamSessions.get(s.session_id);r?.handlers.onToken&&r.handlers.onToken(s.token,s.index);break}case"stream_done":{let s=e.data,r=this.streamSessions.get(s.session_id);r?.handlers.onDone&&r.handlers.onDone({sessionId:s.session_id,fullText:s.full_text,totalTokens:s.total_tokens,promptTokens:s.prompt_tokens,duration:s.duration_ms}),this.streamSessions.delete(s.session_id);break}case"stream_tool_call":{let s=e.data,r=this.streamSessions.get(s.session_id);r?.handlers.onToolCall&&r.handlers.onToolCall(s.tool_name,s.arguments||{},s.index);break}case"stream_tool_result":{let s=e.data,r=this.streamSessions.get(s.session_id);r?.handlers.onToolResult&&r.handlers.onToolResult(s.tool_name,s.success,s.duration_ms,s.index);break}case"stream_error":{if(e.request_id){for(let[s,r]of this.streamSessions)if(r.requestId===e.request_id){r.handlers.onError&&r.handlers.onError(M(e.data,{sessionId:s})),this.streamSessions.delete(s);break}}break}case"presence":case"presence_status":{let s=e.data,r={userId:s.user_id,status:s.status,lastSeen:s.last_seen,device:s.device,metadata:s.metadata,eventType:s.event_type};this.presenceHandlers.forEach(o=>o(r));let i=this.presenceSubscriptions.get(s.user_id);if(i&&i.forEach(o=>o(r)),e.request_id){let o=this.pendingRequests.get(e.request_id);o&&(clearTimeout(o.timeout),o.resolve(e.data),this.pendingRequests.delete(e.request_id))}break}case"typing":{let s=e.data,r={roomId:s.room_id,users:s.users},i=this.typingHandlers.get(s.room_id);i&&i.forEach(o=>o(r));break}case"read_receipt":{let s=e.data,r={category:s.category,messageIds:s.message_ids,readerId:s.reader_id,readAt:s.read_at},i=this.readReceiptHandlers.get(s.category);i&&i.forEach(o=>o(r));break}}}handleDisconnect(){if(this.sseFallbackActive){this.ws=null;return}if(this.ws=null,this._connectionId=null,this.streamSessions.forEach((e,t)=>{e.handlers.onError&&e.handlers.onError(new T({code:"service_unavailable",message:"\uC2E4\uC2DC\uAC04 \uC5F0\uACB0\uC774 \uB04A\uACA8 AI \uC2A4\uD2B8\uB9AC\uBC0D\uC774 \uC911\uB2E8\uB418\uC5C8\uC2B5\uB2C8\uB2E4. \uC7AC\uC5F0\uACB0 \uD6C4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694.",retryable:!0,sessionId:t}))}),this.streamSessions.clear(),!this.pendingRestore){let e=new Map,t=new Map;for(let[i,o]of this.subscriptions)e.set(i,[...o.handlers]),t.set(i,o.info);let s=new Map;for(let[i,o]of this.presenceSubscriptions)s.set(i,[...o]);let r=new Map;for(let[i,o]of this.typingHandlers)r.set(i,[...o]);this.pendingRestore={subscriptions:e,infos:t,presence:s,typing:r}}if(this.subscriptions.clear(),this.presenceSubscriptions.clear(),this.typingHandlers.clear(),this.retryCount<this.options.maxRetries){this.state="reconnecting",this.notifyStateChange(),this.retryCount++;let e=Math.min(this.options.retryInterval*2**(this.retryCount-1),3e4),t=Math.max(Math.ceil(e/2)+Ce(Math.floor(e/2)),this.reconnectFloorMs);this.reconnectFloorMs=0,setTimeout(async()=>{if(!this.sseFallbackActive&&this.state==="reconnecting")try{if(await this.prepareConnectToken(),this.state!=="reconnecting")return;let s=await this.connectTicket(this.options.timeout);if(this.state!=="reconnecting")return;await this.doConnect(void 0,s),this.log("Reconnected successfully, restoring subscriptions...");let r=this.pendingRestore;this.pendingRestore=null,r&&await this.restoreSubscriptions(r.subscriptions,r.presence,r.typing,r.infos)}catch(s){if(this.logError("Reconnect failed",s),s instanceof R){s.retryable&&this.retryCount<this.options.maxRetries?(this.reconnectFloorMs=s.retryAfterMs??0,this.handleDisconnect()):this.failRealtime(s);return}this.retryCount>=this.options.maxRetries&&this.options.fallback!=="none"&&!this.sseFallbackActive&&this.activateSseFallback(s)}},t)}else this.options.fallback!=="none"?this.activateSseFallback(new Error("Connection lost. Max WS retries exceeded.")):(this.state="disconnected",this.notifyStateChange(),this.notifyError(new Error("Connection lost. Max retries exceeded.")))}failRealtime(e){this.pendingRestore=null,this.ws=null,this._connectionId=null,this.state="disconnected",this.notifyStateChange(),this.notifyError(e)}async restoreSubscriptions(e,t,s,r){for(let[i,o]of e)try{this.log(`Restoring subscription: ${i}`);let a=this.generateRequestId(),c=await this.sendRequest({category:i,action:"subscribe",request_id:a}),l=Ct(c),u=r?.get(i)??l;Object.assign(u,l),this.subscriptions.set(i,{info:u,handlers:o}),this.log(`Restored subscription: ${i}`)}catch(a){this.logError(`Failed to restore subscription for ${i}`,a),this.notifyError(new Error(`Failed to restore subscription: ${i}`))}for(let[i,o]of t)try{this.log(`Restoring presence subscription: ${i}`);let a=this.generateRequestId();await this.sendRequest({category:"",action:"presence_subscribe",data:{user_id:i},request_id:a}),this.presenceSubscriptions.set(i,o),this.log(`Restored presence subscription: ${i}`)}catch(a){this.logError(`Failed to restore presence subscription for ${i}`,a)}for(let[i,o]of s)try{this.log(`Restoring typing subscription: ${i}`);let a=this.generateRequestId();await this.sendRequest({category:"",action:"typing_subscribe",data:{room_id:i},request_id:a}),this.typingHandlers.set(i,o),this.log(`Restored typing subscription: ${i}`)}catch(a){this.logError(`Failed to restore typing subscription for ${i}`,a)}}assertBidirectional(e){if(this.activeTransport==="sse")throw new Error(`realtime.${e}() requires a WebSocket connection, which could not be established (the network may block WebSocket, or the connection was repeatedly refused). Only AI streaming (realtime.stream) works in SSE fallback mode (cb.realtime.transport === 'sse').`)}sendRequest(e){return new Promise((t,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(new Error("Not connected"));return}let r=setTimeout(()=>{this.pendingRequests.delete(e.request_id),s(new Error("Request timeout"))},this.options.timeout);this.pendingRequests.set(e.request_id,{resolve:t,reject:s,timeout:r}),this.ws.send(JSON.stringify(e))})}sendRaw(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Not connected");this.ws.send(JSON.stringify(e))}notifyStateChange(){this.stateHandlers.forEach(e=>e(this.state))}notifyError(e){this.errorHandlers.forEach(t=>t(e))}generateClientId(){return`cb_${Math.random().toString(36).substring(2,15)}`}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}};var j=class{constructor(e){this.http=e}ensureServerAuth(e){if(this.http.hasPublicKey()&&!this.http.hasJWT())throw new Error(`cb.roles.${e}() \uB294 \uCF58\uC194 JWT \uB610\uB294 service_role(ctx.cbAdmin, management_scopes: ["role:read" | "role:manage"]) \uC778\uC99D\uC774 \uD544\uC694\uD569\uB2C8\uB2E4. Public Key(cb_pk_) \uB2E8\uB3C5 SDK \uC778\uC2A4\uD134\uC2A4\uB85C\uB294 \uD638\uCD9C\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 Functions \uD658\uACBD\uC5D0\uC11C \uC0AC\uC6A9\uD558\uC138\uC694.`)}async list(e){return this.ensureServerAuth("list"),this.http.get(`/v1/apps/${e}/app-roles`)}async get(e,t){return this.ensureServerAuth("get"),this.http.get(`/v1/apps/${e}/app-roles/${t}`)}async create(e,t){return this.ensureServerAuth("create"),this.http.post(`/v1/apps/${e}/app-roles`,{role_title:t.title,role_description:t.description,selected_permission_ids:t.permissionIds??[]})}async update(e,t,s){this.ensureServerAuth("update"),await this.http.put(`/v1/apps/${e}/app-roles/${t}`,{role_title:s.title,role_description:s.description,selected_permission_ids:s.permissionIds,selected_user_ids:s.userIds})}async assign(e,t,s){this.ensureServerAuth("assign");let r=await this.http.get(`/v1/apps/${e}/app-roles/${t}`);await this.http.put(`/v1/apps/${e}/app-roles/${t}`,{role_title:r.role_name,role_description:r.role_description,selected_permission_ids:r.permission_item.map(i=>i.id),selected_user_ids:s})}async delete(e,t){this.ensureServerAuth("delete"),await this.http.delete(`/v1/apps/${e}/app-roles/${t}`)}};var je=new Set(["localhost","127.0.0.1","::1"]),Et=2048;function At(n,e={}){let t=e.context??"external URL";if(typeof n!="string"||n.length===0)throw new b(400,`${t}: empty URL`,"INVALID_PRESIGNED_URL");if(n.length>Et)throw new b(400,`${t}: URL exceeds ${Et} chars`,"INVALID_PRESIGNED_URL");let s;try{s=new URL(n)}catch{throw new b(400,`${t}: cannot parse URL`,"INVALID_PRESIGNED_URL")}let r=e.allowLocalhost&&je.has(s.hostname);if(s.protocol!=="https:"&&!(r&&s.protocol==="http:"))throw new b(400,`${t}: scheme must be https (got ${s.protocol})`,"INVALID_PRESIGNED_URL");if(!e.allowLocalhost&&je.has(s.hostname))throw new b(400,`${t}: localhost is not allowed in production`,"INVALID_PRESIGNED_URL");if(e.allowedHosts&&e.allowedHosts.length>0){let i=s.hostname;if(!e.allowedHosts.some(a=>a===i?!0:i.endsWith(`.${a}`)))throw new b(400,`${t}: host ${i} is not in allowlist`,"INVALID_PRESIGNED_URL")}return s}function xt(){if(typeof window>"u")return!1;let n=window.location.hostname;return je.has(n)}var Ae=class{constructor(e){this.http=e}getPublicPrefix(){return this.http.hasPublicKey()?"/v1/public":"/v1"}async uploadToPresigned(e,t,s){let i=At(e,{allowLocalhost:xt(),context:"storage.presigned-url"}).toString();if(s?.onProgress&&typeof XMLHttpRequest<"u")return this.putViaXhr(i,t,s.onProgress,s);let{signal:o,cleanup:a}=A({timeout:s?.timeout,signal:s?.signal});try{s?.onProgress?.({loaded:0,total:t.size,percentage:0});let c=await fetch(i,{method:"PUT",body:t,headers:{"Content-Type":t.type||"application/octet-stream"},signal:o});if(!c.ok)throw new b(c.status,`Upload failed: ${c.statusText}`,"PRESIGNED_UPLOAD_FAILED");s?.onProgress?.({loaded:t.size,total:t.size,percentage:100})}finally{a()}}putViaXhr(e,t,s,r){return new Promise((i,o)=>{let a=r?.signal;if(a?.aborted){o(a.reason??new DOMException("Aborted","AbortError"));return}let c=new XMLHttpRequest;c.open("PUT",e,!0),c.setRequestHeader("Content-Type",t.type||"application/octet-stream");let l=r?.timeout??3e4;l>0&&Number.isFinite(l)&&(c.timeout=l);let u=null,d=()=>{a&&u&&a.removeEventListener("abort",u)};a&&(u=()=>c.abort(),a.addEventListener("abort",u,{once:!0})),c.upload.onprogress=h=>{if(!h.lengthComputable)return;let p=h.total||t.size;s({loaded:h.loaded,total:p,percentage:p>0?Math.round(h.loaded/p*100):0})},c.onload=()=>{d(),c.status>=200&&c.status<300?(s({loaded:t.size,total:t.size,percentage:100}),i()):o(new b(c.status,`Upload failed: ${c.statusText||"unknown error"}`,"PRESIGNED_UPLOAD_FAILED"))},c.onerror=()=>{d(),o(new b(0,"Upload failed: network error","PRESIGNED_UPLOAD_FAILED"))},c.ontimeout=()=>{d(),o(new DOMException(`Request timed out after ${l}ms`,"TimeoutError"))},c.onabort=()=>{d(),o(a?.reason??new DOMException("Aborted","AbortError"))},c.send(t)})}async getFiles(e,t){let s=this.getPublicPrefix(),r=t?`?parent_id=${encodeURIComponent(t)}`:"";return(await this.http.get(`${s}/storages/files/${e}/items${r}`)).files}async uploadFile(e,t,s){let r=typeof s=="string"?{parentId:s}:s??{},i=this.getPublicPrefix(),o=await this.http.post(`${i}/storages/files/${e}/presigned-url`,{file_name:t.name,file_size:t.size,mime_type:t.type||"application/octet-stream",parent_id:r.parentId});await this.uploadToPresigned(o.upload_url,t,{onProgress:r.onProgress,signal:r.signal,timeout:r.timeout});let a=await this.http.post(`${i}/storages/files/${e}/complete-upload`,{file_id:o.file_id});return{id:a.id,name:a.name,path:a.path,type:a.type,mime_type:a.mime_type,size:a.size,url:a.url,parent_id:a.parent_id,created_at:a.created_at}}async uploadFiles(e,t,s){let r=[];for(let i of t){let o=await this.uploadFile(e,i,s);r.push(o)}return r}async createFolder(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/storages/files/${e}/folders`,t)}async deleteFile(e,t){let s=this.getPublicPrefix();await this.http.delete(`${s}/storages/files/${e}/items/${t}`)}async moveFile(e,t,s){if(this.http.hasPublicKey()&&!this.http.hasJWT())throw new Error("storage.moveFile requires JWT (console token) auth; not available with Public Key alone.");await this.http.post(`/v1/storages/files/${e}/items/${t}/move`,s)}async renameFile(e,t,s){if(this.http.hasPublicKey()&&!this.http.hasJWT())throw new Error("storage.renameFile requires JWT (console token) auth; not available with Public Key alone.");return this.http.patch(`/v1/storages/files/${e}/items/${t}/rename`,s)}getFileUrl(e){return e.url||null}getPathUrl(e,t){let s=t.split("/").filter((r,i,o)=>r!==""||i===o.length-1).map(r=>encodeURIComponent(r)).join("/");return`${this.http.getBaseUrl()}/v1/file-path/${e}/${s}`}isImageFile(e){return e.mime_type?.startsWith("image/")||!1}async uploadByPath(e,t,s,r){let i=this.getPublicPrefix(),o=t.startsWith("/")?t.slice(1):t,a=r?.overwrite!==!1,c=await this.http.post(`${i}/storages/files/${e}/presigned-url/path/${o}`,{file_name:s.name,file_size:s.size,mime_type:s.type||"application/octet-stream",overwrite:a});await this.uploadToPresigned(c.upload_url,s,{onProgress:r?.onProgress,signal:r?.signal,timeout:r?.timeout});let l=await this.http.post(`${i}/storages/files/${e}/complete-upload`,{file_id:c.file_id});return{id:l.id,name:l.name,path:l.path,type:l.type,mime_type:l.mime_type,size:l.size,url:l.url,parent_id:l.parent_id,created_at:l.created_at}}async getByPath(e,t){let s=this.getPublicPrefix(),r=t.startsWith("/")?t.slice(1):t;return this.http.get(`${s}/storages/files/${e}/path/${r}`)}async getUrlByPath(e,t){try{return(await this.getByPath(e,t)).url||null}catch{return null}}async setPageMeta(e,t){let s=this.getPublicPrefix();return this.http.put(`${s}/storages/webs/${e}/page-metas`,t)}async batchSetPageMeta(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/storages/webs/${e}/page-metas/batch`,t)}async listPageMetas(e,t){let s=this.getPublicPrefix(),r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let i=r.toString();return this.http.get(`${s}/storages/webs/${e}/page-metas${i?`?${i}`:""}`)}async getPageMeta(e,t){let s=this.getPublicPrefix(),r=encodeURIComponent(t);return this.http.get(`${s}/storages/webs/${e}/page-metas/get?path=${r}`)}async deletePageMeta(e,t){let s=this.getPublicPrefix(),r=encodeURIComponent(t);await this.http.delete(`${s}/storages/webs/${e}/page-metas?path=${r}`)}async deleteAllPageMetas(e){let t=this.getPublicPrefix();await this.http.delete(`${t}/storages/webs/${e}/page-metas/all`)}};var xe=class{constructor(e){this.http=e}getPublicPrefix(){return this.http.hasPublicKey()?"/v1/public":"/v1"}async issueBillingKey(){let e=this.getPublicPrefix();return this.http.post(`${e}/subscriptions/billing-keys`,{})}async confirmBillingKey(e){let t=this.getPublicPrefix();return this.http.post(`${t}/subscriptions/billing-keys/confirm`,e)}async listBillingKeys(e){let t=this.getPublicPrefix(),s=e?`?customer_id=${e}`:"";return this.http.get(`${t}/subscriptions/billing-keys${s}`)}async getBillingKey(e){let t=this.getPublicPrefix();return this.http.get(`${t}/subscriptions/billing-keys/${e}`)}async updateBillingKey(e,t){let s=this.getPublicPrefix();return this.http.patch(`${s}/subscriptions/billing-keys/${e}`,t)}async deleteBillingKey(e){let t=this.getPublicPrefix();return this.http.delete(`${t}/subscriptions/billing-keys/${e}`)}async create(e){let t=this.getPublicPrefix(),s=await this.http.post(`${t}/subscriptions`,e);return S(s,{id:{type:"string-or-number"},status:{type:"string"}},"subscription.create"),s}async list(e){let t=this.getPublicPrefix(),s=new URLSearchParams;e?.status&&s.set("status",e.status),e?.limit&&s.set("limit",String(e.limit)),e?.offset&&s.set("offset",String(e.offset));let r=s.toString();return this.http.get(`${t}/subscriptions${r?`?${r}`:""}`)}async get(e){let t=this.getPublicPrefix();return this.http.get(`${t}/subscriptions/${e}`)}async update(e,t){let s=this.getPublicPrefix();return this.http.patch(`${s}/subscriptions/${e}`,t)}async postponeBilling(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/subscriptions/${e}/postpone-billing`,t)}async pause(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/subscriptions/${e}/pause`,t||{})}async resume(e){let t=this.getPublicPrefix();return this.http.post(`${t}/subscriptions/${e}/resume`,{})}async cancel(e,t={}){let s=this.getPublicPrefix(),r={reason:t.reason,cancel_at_end:!t.immediate};return this.http.post(`${s}/subscriptions/${e}/cancel`,r)}async changePlan(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/subscriptions/${e}/change-plan`,t)}async previewChangePlan(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/subscriptions/${e}/change-plan/preview`,t)}async listPayments(e,t){let s=this.getPublicPrefix(),r=new URLSearchParams;t?.status&&r.set("status",t.status),t?.limit&&r.set("limit",String(t.limit)),t?.offset&&r.set("offset",String(t.offset));let i=r.toString();return this.http.get(`${s}/subscriptions/${e}/payments${i?`?${i}`:""}`)}async chargeWithBillingKey(e){let t=this.getPublicPrefix();return this.http.post(`${t}/subscriptions/charge`,e)}};var $e=class{constructor(e){this.http=e}async reportIssue(e){let t={title:e.title,body:e.body,category:e.category,metadata:e.metadata};return e.anonymousEmail&&(t.anonymous_email=e.anonymousEmail),e.recaptchaToken&&(t.recaptcha_token=e.recaptchaToken),this.http.post("/v1/public/reports",t)}async reportIssueOnBehalfOfUser(e){if(!e.targetAppId)throw new Error("targetAppId is required");if(!e.accessToken)throw new Error("accessToken is required");let t={title:e.title,body:e.body};e.category&&(t.category=e.category),e.metadata&&(t.metadata=e.metadata);let s=`${this.http.getBaseUrl()}/v1/integrations/providers/${encodeURIComponent(e.targetAppId)}/issues/by-user`,r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`},body:JSON.stringify(t)});if(!r.ok){let i;try{i=await r.json()}catch{i={error:r.statusText}}let o=i??{},a=o.error_description??o.error??`HTTP ${r.status}`;throw new Error(`reportIssueOnBehalfOfUser failed (${r.status}): ${a}`)}return await r.json()}async reportPlatformBug(e){let t=e.attachAutomaticContext!==!1,s={title:e.title,body:e.body,category:e.category??"other",severity:e.severity??"medium",metadata:e.metadata};if(e.reporterEmail&&(s.reporter_email=e.reporterEmail),e.recaptchaToken&&(s.recaptcha_token=e.recaptchaToken),t){s.sdk_version=e.sdkVersion??Us(),s.sdk_platform=e.sdkPlatform??Ds(),s.environment=e.environment??"unknown",e.error?s.stack_trace=$t(e.error.stack??String(e.error)):e.stackTrace&&(s.stack_trace=$t(e.stackTrace));let r=e.recentApiCalls??this.http.getRecentCalls();r.length>0&&(s.recent_api_calls=r)}return this.http.post("/v1/public/platform-issues",s)}getRecentApiCalls(){return this.http.getRecentCalls()}clearRecentApiCalls(){this.http.clearRecentCalls()}async listPlatformIssueReplies(e){return(await this.http.get(`/v1/public/platform-issues/${e}/comments`)).comments}async replyToPlatformIssue(e,t){return this.http.post(`/v1/public/platform-issues/${e}/comments`,{body:t})}async getPlatformIssue(e){return this.http.get(`/v1/public/platform-issues/${e}`)}async listMyPlatformIssues(e={}){let t=new URLSearchParams;for(let r of e.status??[])t.append("status",r);for(let r of e.severity??[])t.append("severity",r);for(let r of e.category??[])t.append("category",r);e.sinceUpdatedAt&&t.set("since_updated_at",e.sinceUpdatedAt),e.cursor&&t.set("cursor",e.cursor),typeof e.limit=="number"&&t.set("limit",String(e.limit));let s=t.toString();return this.http.get(`/v1/public/platform-issues${s?`?${s}`:""}`)}};function Us(){return"6.16.0"}function Ds(){return typeof window<"u"&&typeof document<"u"?"web":"node"}function $t(n){let e=n;e=e.replace(/(\(|\s|^)(?:file:\/\/)?\/[^\s)]+\/([^\s/)]+)(:\d+:\d+)?/g,"$1$2$3"),e=e.replace(/(https?:\/\/[^\s)?]+)\?[^\s)]*/g,"$1");let t=32*1024;return e.length>t&&(e=`${e.slice(0,t)}
4
+ `).filter(m=>m.trim());for(let m of f)try{let g=JSON.parse(m),v=Ss(g);if(v&&!u){d=v;continue}this.handleServerMessage(g,()=>{u||(u=!0,clearTimeout(h),this.log("Connected successfully"),s())})}catch(g){this.logError("Failed to parse message",{line:m,error:g})}},this.ws.onclose=p=>{if(this.log(`WebSocket closed: code=${p.code}, reason=${p.reason}`),p.code>=4e3&&p.code<=4999){let f=d??new R({code:p.reason||void 0,closeCode:p.code,message:this.closeNotice??void 0});this.closeNotice=null,this.clearAuthRefreshRetry();let m=this.state==="connected";if(u||(u=!0,clearTimeout(h)),this.ws=null,m){f.retryable||f.code==="token_expired"&&this.http.canRefreshMemberToken(this.options.accessToken)?this.handleDisconnect():this.failRealtime(f);return}this.state="disconnected",this.notifyStateChange(),r(f);return}if(!u&&this.state==="connecting"&&(u=!0,clearTimeout(h),o&&this.http.disableDirectRealtime(),r(new ie(`Connection closed: ${p.reason||"unknown reason"}`))),this.initialConnecting&&this.state==="connecting"){this.state="disconnected",this.ws=null;return}(this.state==="connected"||this.state==="connecting")&&this.handleDisconnect()},this.ws.onerror=p=>{this.log("WebSocket error occurred"),this.logError("WebSocket error",p),this.initialConnecting||this.notifyError(new Error("WebSocket connection error")),!u&&this.state==="connecting"&&(u=!0,clearTimeout(h),o&&this.http.disableDirectRealtime(),r(new ie("Failed to connect")))}}catch(p){u=!0,clearTimeout(h),o&&this.http.disableDirectRealtime(),r(p)}})}async prepareConnectToken(){let e=this.options.accessToken;if(!e||!this.http.canRefreshMemberToken(e)||!F(e,St))return;let t=await this.http.freshTokenForMember(e,St);t&&(this.options.accessToken=t)}refreshConnectionAuth(){if(!this.tokenRefreshNegotiated||this.state!=="connected"||!this.ws)return Promise.resolve(!1);if(this.authRefreshInFlight)return this.authRefreshInFlight;this.clearAuthRefreshRetry();let e=(async()=>{let t=this.options.accessToken;try{let s=await this.http.freshTokenForMember(t,Cs,{replace:!0});if(!s||s===t)throw new Error("No fresh access token from the SDK session");return await this.sendRequest({category:"",action:"auth_refresh",data:{access_token:s},request_id:this.generateRequestId()}),this.options.accessToken=s,this.closeNotice=null,this.log("Access token refreshed over the connection"),!0}catch(s){return this.logError("auth_refresh failed",s),this.http.canRefreshMemberToken(this.options.accessToken)&&this.scheduleAuthRefreshRetry(),!1}finally{this.authRefreshInFlight=null}})();return this.authRefreshInFlight=e,e}scheduleAuthRefreshRetry(){this.authRefreshRetryTimer||!this.tokenRefreshNegotiated||(this.authRefreshRetryTimer=setTimeout(()=>{this.authRefreshRetryTimer=null,this.refreshConnectionAuth()},Is))}clearAuthRefreshRetry(){this.authRefreshRetryTimer&&(clearTimeout(this.authRefreshRetryTimer),this.authRefreshRetryTimer=null)}log(e){this.options.debug&&console.log(`[Realtime] ${e}`)}logError(e,t){this.options.debug&&console.error(`[Realtime] ${e}`,t)}handleServerMessage(e,t){switch(e.event){case"connected":{let s=e.data;this._connectionId=s.connection_id,this._appId=s.app_id,this.closeNotice=null,this.clearAuthRefreshRetry(),this.state="connected",this.activeTransport="ws",this.sseFallbackActive=!1,this.retryCount=0,this.notifyStateChange(),t&&t();break}case"subscribed":case"unsubscribed":case"sent":case"result":case"history":case"token_refreshed":{if(e.request_id){let s=this.pendingRequests.get(e.request_id);s&&(clearTimeout(s.timeout),s.resolve(e.data),this.pendingRequests.delete(e.request_id))}break}case"message":{let s=e.data,r=this.subscriptions.get(s.category);if(r){let i={id:s.id,category:s.category,from:s.from,fromMember:Tt(s.from_member),fromConn:It(s.from_conn),data:s.data,sentAt:s.sent_at,fromPublisher:s.from_publisher===!0};r.handlers.forEach(o=>o(i))}break}case"error":{if(e.request_id){let s=this.pendingRequests.get(e.request_id);if(s){clearTimeout(s.timeout);let r=e.data;s.reject(new q({code:r?.code,message:e.error||"Unknown error",category:e.category})),this.pendingRequests.delete(e.request_id)}}else{let s=e.data;s?.code&&Es.has(s.code)?this.closeNotice=e.error||s.code:this.notifyError(new Error(e.error||"Unknown error"))}break}case"pong":break;case"token_expiring":case"token_expired":{this.log(`Server sent ${e.event}; refreshing the access token over the connection`),this.refreshConnectionAuth();break}case"stream_token":{let s=e.data,r=this.streamSessions.get(s.session_id);r?.handlers.onToken&&r.handlers.onToken(s.token,s.index);break}case"stream_done":{let s=e.data,r=this.streamSessions.get(s.session_id);r?.handlers.onDone&&r.handlers.onDone({sessionId:s.session_id,fullText:s.full_text,totalTokens:s.total_tokens,promptTokens:s.prompt_tokens,duration:s.duration_ms}),this.streamSessions.delete(s.session_id);break}case"stream_tool_call":{let s=e.data,r=this.streamSessions.get(s.session_id);r?.handlers.onToolCall&&r.handlers.onToolCall(s.tool_name,s.arguments||{},s.index);break}case"stream_tool_result":{let s=e.data,r=this.streamSessions.get(s.session_id);r?.handlers.onToolResult&&r.handlers.onToolResult(s.tool_name,s.success,s.duration_ms,s.index);break}case"stream_error":{if(e.request_id){for(let[s,r]of this.streamSessions)if(r.requestId===e.request_id){r.handlers.onError&&r.handlers.onError(M(e.data,{sessionId:s})),this.streamSessions.delete(s);break}}break}case"presence":case"presence_status":{let s=e.data,r={userId:s.user_id,status:s.status,lastSeen:s.last_seen,device:s.device,metadata:s.metadata,eventType:s.event_type};this.presenceHandlers.forEach(o=>o(r));let i=this.presenceSubscriptions.get(s.user_id);if(i&&i.forEach(o=>o(r)),e.request_id){let o=this.pendingRequests.get(e.request_id);o&&(clearTimeout(o.timeout),o.resolve(e.data),this.pendingRequests.delete(e.request_id))}break}case"typing":{let s=e.data,r={roomId:s.room_id,users:s.users},i=this.typingHandlers.get(s.room_id);i&&i.forEach(o=>o(r));break}case"read_receipt":{let s=e.data,r={category:s.category,messageIds:s.message_ids,readerId:s.reader_id,readAt:s.read_at},i=this.readReceiptHandlers.get(s.category);i&&i.forEach(o=>o(r));break}}}handleDisconnect(){if(this.sseFallbackActive){this.ws=null;return}if(this.ws=null,this._connectionId=null,this.streamSessions.forEach((e,t)=>{e.handlers.onError&&e.handlers.onError(new T({code:"service_unavailable",message:"\uC2E4\uC2DC\uAC04 \uC5F0\uACB0\uC774 \uB04A\uACA8 AI \uC2A4\uD2B8\uB9AC\uBC0D\uC774 \uC911\uB2E8\uB418\uC5C8\uC2B5\uB2C8\uB2E4. \uC7AC\uC5F0\uACB0 \uD6C4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694.",retryable:!0,sessionId:t}))}),this.streamSessions.clear(),!this.pendingRestore){let e=new Map,t=new Map;for(let[i,o]of this.subscriptions)e.set(i,[...o.handlers]),t.set(i,o.info);let s=new Map;for(let[i,o]of this.presenceSubscriptions)s.set(i,[...o]);let r=new Map;for(let[i,o]of this.typingHandlers)r.set(i,[...o]);this.pendingRestore={subscriptions:e,infos:t,presence:s,typing:r}}if(this.subscriptions.clear(),this.presenceSubscriptions.clear(),this.typingHandlers.clear(),this.retryCount<this.options.maxRetries){this.state="reconnecting",this.notifyStateChange(),this.retryCount++;let e=Math.min(this.options.retryInterval*2**(this.retryCount-1),3e4),t=Math.max(Math.ceil(e/2)+Ce(Math.floor(e/2)),this.reconnectFloorMs);this.reconnectFloorMs=0,setTimeout(async()=>{if(!this.sseFallbackActive&&this.state==="reconnecting")try{if(await this.prepareConnectToken(),this.state!=="reconnecting")return;let s=await this.connectTicket(this.options.timeout);if(this.state!=="reconnecting")return;await this.doConnect(void 0,s),this.log("Reconnected successfully, restoring subscriptions...");let r=this.pendingRestore;this.pendingRestore=null,r&&await this.restoreSubscriptions(r.subscriptions,r.presence,r.typing,r.infos)}catch(s){if(this.logError("Reconnect failed",s),s instanceof R){s.retryable&&this.retryCount<this.options.maxRetries?(this.reconnectFloorMs=s.retryAfterMs??0,this.handleDisconnect()):this.failRealtime(s);return}this.retryCount>=this.options.maxRetries&&this.options.fallback!=="none"&&!this.sseFallbackActive&&this.activateSseFallback(s)}},t)}else this.options.fallback!=="none"?this.activateSseFallback(new Error("Connection lost. Max WS retries exceeded.")):(this.state="disconnected",this.notifyStateChange(),this.notifyError(new Error("Connection lost. Max retries exceeded.")))}failRealtime(e){this.pendingRestore=null,this.ws=null,this._connectionId=null,this.state="disconnected",this.notifyStateChange(),this.notifyError(e)}async restoreSubscriptions(e,t,s,r){for(let[i,o]of e)try{this.log(`Restoring subscription: ${i}`);let a=this.generateRequestId(),c=await this.sendRequest({category:i,action:"subscribe",request_id:a}),l=Ct(c),u=r?.get(i)??l;Object.assign(u,l),this.subscriptions.set(i,{info:u,handlers:o}),this.log(`Restored subscription: ${i}`)}catch(a){this.logError(`Failed to restore subscription for ${i}`,a),this.notifyError(new Error(`Failed to restore subscription: ${i}`))}for(let[i,o]of t)try{this.log(`Restoring presence subscription: ${i}`);let a=this.generateRequestId();await this.sendRequest({category:"",action:"presence_subscribe",data:{user_id:i},request_id:a}),this.presenceSubscriptions.set(i,o),this.log(`Restored presence subscription: ${i}`)}catch(a){this.logError(`Failed to restore presence subscription for ${i}`,a)}for(let[i,o]of s)try{this.log(`Restoring typing subscription: ${i}`);let a=this.generateRequestId();await this.sendRequest({category:"",action:"typing_subscribe",data:{room_id:i},request_id:a}),this.typingHandlers.set(i,o),this.log(`Restored typing subscription: ${i}`)}catch(a){this.logError(`Failed to restore typing subscription for ${i}`,a)}}assertBidirectional(e){if(this.activeTransport==="sse")throw new Error(`realtime.${e}() requires a WebSocket connection, which could not be established (the network may block WebSocket, or the connection was repeatedly refused). Only AI streaming (realtime.stream) works in SSE fallback mode (cb.realtime.transport === 'sse').`)}sendRequest(e){return new Promise((t,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(new Error("Not connected"));return}let r=setTimeout(()=>{this.pendingRequests.delete(e.request_id),s(new Error("Request timeout"))},this.options.timeout);this.pendingRequests.set(e.request_id,{resolve:t,reject:s,timeout:r}),this.ws.send(JSON.stringify(e))})}sendRaw(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Not connected");this.ws.send(JSON.stringify(e))}notifyStateChange(){this.stateHandlers.forEach(e=>e(this.state))}notifyError(e){this.errorHandlers.forEach(t=>t(e))}generateClientId(){return`cb_${Math.random().toString(36).substring(2,15)}`}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}};var j=class{constructor(e){this.http=e}ensureServerAuth(e){if(this.http.hasPublicKey()&&!this.http.hasJWT())throw new Error(`cb.roles.${e}() \uB294 \uCF58\uC194 JWT \uB610\uB294 service_role(ctx.cbAdmin, management_scopes: ["role:read" | "role:manage"]) \uC778\uC99D\uC774 \uD544\uC694\uD569\uB2C8\uB2E4. Public Key(cb_pk_) \uB2E8\uB3C5 SDK \uC778\uC2A4\uD134\uC2A4\uB85C\uB294 \uD638\uCD9C\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 Functions \uD658\uACBD\uC5D0\uC11C \uC0AC\uC6A9\uD558\uC138\uC694.`)}async list(e){return this.ensureServerAuth("list"),this.http.get(`/v1/apps/${e}/app-roles`)}async get(e,t){return this.ensureServerAuth("get"),this.http.get(`/v1/apps/${e}/app-roles/${t}`)}async create(e,t){return this.ensureServerAuth("create"),this.http.post(`/v1/apps/${e}/app-roles`,{role_title:t.title,role_description:t.description,selected_permission_ids:t.permissionIds??[]})}async update(e,t,s){this.ensureServerAuth("update"),await this.http.put(`/v1/apps/${e}/app-roles/${t}`,{role_title:s.title,role_description:s.description,selected_permission_ids:s.permissionIds,selected_user_ids:s.userIds})}async assign(e,t,s){this.ensureServerAuth("assign");let r=await this.http.get(`/v1/apps/${e}/app-roles/${t}`);await this.http.put(`/v1/apps/${e}/app-roles/${t}`,{role_title:r.role_name,role_description:r.role_description,selected_permission_ids:r.permission_item.map(i=>i.id),selected_user_ids:s})}async delete(e,t){this.ensureServerAuth("delete"),await this.http.delete(`/v1/apps/${e}/app-roles/${t}`)}};var je=new Set(["localhost","127.0.0.1","::1"]),Et=2048;function At(n,e={}){let t=e.context??"external URL";if(typeof n!="string"||n.length===0)throw new b(400,`${t}: empty URL`,"INVALID_PRESIGNED_URL");if(n.length>Et)throw new b(400,`${t}: URL exceeds ${Et} chars`,"INVALID_PRESIGNED_URL");let s;try{s=new URL(n)}catch{throw new b(400,`${t}: cannot parse URL`,"INVALID_PRESIGNED_URL")}let r=e.allowLocalhost&&je.has(s.hostname);if(s.protocol!=="https:"&&!(r&&s.protocol==="http:"))throw new b(400,`${t}: scheme must be https (got ${s.protocol})`,"INVALID_PRESIGNED_URL");if(!e.allowLocalhost&&je.has(s.hostname))throw new b(400,`${t}: localhost is not allowed in production`,"INVALID_PRESIGNED_URL");if(e.allowedHosts&&e.allowedHosts.length>0){let i=s.hostname;if(!e.allowedHosts.some(a=>a===i?!0:i.endsWith(`.${a}`)))throw new b(400,`${t}: host ${i} is not in allowlist`,"INVALID_PRESIGNED_URL")}return s}function xt(){if(typeof window>"u")return!1;let n=window.location.hostname;return je.has(n)}var Ae=class{constructor(e){this.http=e}getPublicPrefix(){return this.http.hasPublicKey()?"/v1/public":"/v1"}async uploadToPresigned(e,t,s){let i=At(e,{allowLocalhost:xt(),context:"storage.presigned-url"}).toString();if(s?.onProgress&&typeof XMLHttpRequest<"u")return this.putViaXhr(i,t,s.onProgress,s);let{signal:o,cleanup:a}=A({timeout:s?.timeout,signal:s?.signal});try{s?.onProgress?.({loaded:0,total:t.size,percentage:0});let c=await fetch(i,{method:"PUT",body:t,headers:{"Content-Type":t.type||"application/octet-stream"},signal:o});if(!c.ok)throw new b(c.status,`Upload failed: ${c.statusText}`,"PRESIGNED_UPLOAD_FAILED");s?.onProgress?.({loaded:t.size,total:t.size,percentage:100})}finally{a()}}putViaXhr(e,t,s,r){return new Promise((i,o)=>{let a=r?.signal;if(a?.aborted){o(a.reason??new DOMException("Aborted","AbortError"));return}let c=new XMLHttpRequest;c.open("PUT",e,!0),c.setRequestHeader("Content-Type",t.type||"application/octet-stream");let l=r?.timeout??3e4;l>0&&Number.isFinite(l)&&(c.timeout=l);let u=null,d=()=>{a&&u&&a.removeEventListener("abort",u)};a&&(u=()=>c.abort(),a.addEventListener("abort",u,{once:!0})),c.upload.onprogress=h=>{if(!h.lengthComputable)return;let p=h.total||t.size;s({loaded:h.loaded,total:p,percentage:p>0?Math.round(h.loaded/p*100):0})},c.onload=()=>{d(),c.status>=200&&c.status<300?(s({loaded:t.size,total:t.size,percentage:100}),i()):o(new b(c.status,`Upload failed: ${c.statusText||"unknown error"}`,"PRESIGNED_UPLOAD_FAILED"))},c.onerror=()=>{d(),o(new b(0,"Upload failed: network error","PRESIGNED_UPLOAD_FAILED"))},c.ontimeout=()=>{d(),o(new DOMException(`Request timed out after ${l}ms`,"TimeoutError"))},c.onabort=()=>{d(),o(a?.reason??new DOMException("Aborted","AbortError"))},c.send(t)})}async getFiles(e,t){let s=this.getPublicPrefix(),r=t?`?parent_id=${encodeURIComponent(t)}`:"";return(await this.http.get(`${s}/storages/files/${e}/items${r}`)).files}async uploadFile(e,t,s){let r=typeof s=="string"?{parentId:s}:s??{},i=this.getPublicPrefix(),o=await this.http.post(`${i}/storages/files/${e}/presigned-url`,{file_name:t.name,file_size:t.size,mime_type:t.type||"application/octet-stream",parent_id:r.parentId});await this.uploadToPresigned(o.upload_url,t,{onProgress:r.onProgress,signal:r.signal,timeout:r.timeout});let a=await this.http.post(`${i}/storages/files/${e}/complete-upload`,{file_id:o.file_id});return{id:a.id,name:a.name,path:a.path,type:a.type,mime_type:a.mime_type,size:a.size,url:a.url,parent_id:a.parent_id,created_at:a.created_at}}async uploadFiles(e,t,s){let r=[];for(let i of t){let o=await this.uploadFile(e,i,s);r.push(o)}return r}async createFolder(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/storages/files/${e}/folders`,t)}async deleteFile(e,t){let s=this.getPublicPrefix();await this.http.delete(`${s}/storages/files/${e}/items/${t}`)}async moveFile(e,t,s){if(this.http.hasPublicKey()&&!this.http.hasJWT())throw new Error("storage.moveFile requires JWT (console token) auth; not available with Public Key alone.");await this.http.post(`/v1/storages/files/${e}/items/${t}/move`,s)}async renameFile(e,t,s){if(this.http.hasPublicKey()&&!this.http.hasJWT())throw new Error("storage.renameFile requires JWT (console token) auth; not available with Public Key alone.");return this.http.patch(`/v1/storages/files/${e}/items/${t}/rename`,s)}getFileUrl(e){return e.url||null}getPathUrl(e,t){let s=t.split("/").filter((r,i,o)=>r!==""||i===o.length-1).map(r=>encodeURIComponent(r)).join("/");return`${this.http.getBaseUrl()}/v1/file-path/${e}/${s}`}isImageFile(e){return e.mime_type?.startsWith("image/")||!1}async uploadByPath(e,t,s,r){let i=this.getPublicPrefix(),o=t.startsWith("/")?t.slice(1):t,a=r?.overwrite!==!1,c=await this.http.post(`${i}/storages/files/${e}/presigned-url/path/${o}`,{file_name:s.name,file_size:s.size,mime_type:s.type||"application/octet-stream",overwrite:a});await this.uploadToPresigned(c.upload_url,s,{onProgress:r?.onProgress,signal:r?.signal,timeout:r?.timeout});let l=await this.http.post(`${i}/storages/files/${e}/complete-upload`,{file_id:c.file_id});return{id:l.id,name:l.name,path:l.path,type:l.type,mime_type:l.mime_type,size:l.size,url:l.url,parent_id:l.parent_id,created_at:l.created_at}}async getByPath(e,t){let s=this.getPublicPrefix(),r=t.startsWith("/")?t.slice(1):t;return this.http.get(`${s}/storages/files/${e}/path/${r}`)}async getUrlByPath(e,t){try{return(await this.getByPath(e,t)).url||null}catch{return null}}async setPageMeta(e,t){let s=this.getPublicPrefix();return this.http.put(`${s}/storages/webs/${e}/page-metas`,t)}async batchSetPageMeta(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/storages/webs/${e}/page-metas/batch`,t)}async listPageMetas(e,t){let s=this.getPublicPrefix(),r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let i=r.toString();return this.http.get(`${s}/storages/webs/${e}/page-metas${i?`?${i}`:""}`)}async getPageMeta(e,t){let s=this.getPublicPrefix(),r=encodeURIComponent(t);return this.http.get(`${s}/storages/webs/${e}/page-metas/get?path=${r}`)}async deletePageMeta(e,t){let s=this.getPublicPrefix(),r=encodeURIComponent(t);await this.http.delete(`${s}/storages/webs/${e}/page-metas?path=${r}`)}async deleteAllPageMetas(e){let t=this.getPublicPrefix();await this.http.delete(`${t}/storages/webs/${e}/page-metas/all`)}};var xe=class{constructor(e){this.http=e}getPublicPrefix(){return this.http.hasPublicKey()?"/v1/public":"/v1"}async issueBillingKey(){let e=this.getPublicPrefix();return this.http.post(`${e}/subscriptions/billing-keys`,{})}async confirmBillingKey(e){let t=this.getPublicPrefix();return this.http.post(`${t}/subscriptions/billing-keys/confirm`,e)}async listBillingKeys(e){let t=this.getPublicPrefix(),s=e?`?customer_id=${e}`:"";return this.http.get(`${t}/subscriptions/billing-keys${s}`)}async getBillingKey(e){let t=this.getPublicPrefix();return this.http.get(`${t}/subscriptions/billing-keys/${e}`)}async updateBillingKey(e,t){let s=this.getPublicPrefix();return this.http.patch(`${s}/subscriptions/billing-keys/${e}`,t)}async deleteBillingKey(e){let t=this.getPublicPrefix();return this.http.delete(`${t}/subscriptions/billing-keys/${e}`)}async create(e){let t=this.getPublicPrefix(),s=await this.http.post(`${t}/subscriptions`,e);return S(s,{id:{type:"string-or-number"},status:{type:"string"}},"subscription.create"),s}async list(e){let t=this.getPublicPrefix(),s=new URLSearchParams;e?.status&&s.set("status",e.status),e?.limit&&s.set("limit",String(e.limit)),e?.offset&&s.set("offset",String(e.offset));let r=s.toString();return this.http.get(`${t}/subscriptions${r?`?${r}`:""}`)}async get(e){let t=this.getPublicPrefix();return this.http.get(`${t}/subscriptions/${e}`)}async update(e,t){let s=this.getPublicPrefix();return this.http.patch(`${s}/subscriptions/${e}`,t)}async postponeBilling(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/subscriptions/${e}/postpone-billing`,t)}async pause(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/subscriptions/${e}/pause`,t||{})}async resume(e){let t=this.getPublicPrefix();return this.http.post(`${t}/subscriptions/${e}/resume`,{})}async cancel(e,t={}){let s=this.getPublicPrefix(),r={reason:t.reason,cancel_at_end:!t.immediate};return this.http.post(`${s}/subscriptions/${e}/cancel`,r)}async changePlan(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/subscriptions/${e}/change-plan`,t)}async previewChangePlan(e,t){let s=this.getPublicPrefix();return this.http.post(`${s}/subscriptions/${e}/change-plan/preview`,t)}async listPayments(e,t){let s=this.getPublicPrefix(),r=new URLSearchParams;t?.status&&r.set("status",t.status),t?.limit&&r.set("limit",String(t.limit)),t?.offset&&r.set("offset",String(t.offset));let i=r.toString();return this.http.get(`${s}/subscriptions/${e}/payments${i?`?${i}`:""}`)}async chargeWithBillingKey(e){let t=this.getPublicPrefix();return this.http.post(`${t}/subscriptions/charge`,e)}};var $e=class{constructor(e){this.http=e}async reportIssue(e){let t={title:e.title,body:e.body,category:e.category,metadata:e.metadata};return e.anonymousEmail&&(t.anonymous_email=e.anonymousEmail),e.recaptchaToken&&(t.recaptcha_token=e.recaptchaToken),this.http.post("/v1/public/reports",t)}async reportIssueOnBehalfOfUser(e){if(!e.targetAppId)throw new Error("targetAppId is required");if(!e.accessToken)throw new Error("accessToken is required");let t={title:e.title,body:e.body};e.category&&(t.category=e.category),e.metadata&&(t.metadata=e.metadata);let s=`${this.http.getBaseUrl()}/v1/integrations/providers/${encodeURIComponent(e.targetAppId)}/issues/by-user`,r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`},body:JSON.stringify(t)});if(!r.ok){let i;try{i=await r.json()}catch{i={error:r.statusText}}let o=i??{},a=o.error_description??o.error??`HTTP ${r.status}`;throw new Error(`reportIssueOnBehalfOfUser failed (${r.status}): ${a}`)}return await r.json()}async reportPlatformBug(e){let t=e.attachAutomaticContext!==!1,s={title:e.title,body:e.body,category:e.category??"other",severity:e.severity??"medium",metadata:e.metadata};if(e.reporterEmail&&(s.reporter_email=e.reporterEmail),e.recaptchaToken&&(s.recaptcha_token=e.recaptchaToken),t){s.sdk_version=e.sdkVersion??Us(),s.sdk_platform=e.sdkPlatform??Ds(),s.environment=e.environment??"unknown",e.error?s.stack_trace=$t(e.error.stack??String(e.error)):e.stackTrace&&(s.stack_trace=$t(e.stackTrace));let r=e.recentApiCalls??this.http.getRecentCalls();r.length>0&&(s.recent_api_calls=r)}return this.http.post("/v1/public/platform-issues",s)}getRecentApiCalls(){return this.http.getRecentCalls()}clearRecentApiCalls(){this.http.clearRecentCalls()}async listPlatformIssueReplies(e){return(await this.http.get(`/v1/public/platform-issues/${e}/comments`)).comments}async replyToPlatformIssue(e,t){return this.http.post(`/v1/public/platform-issues/${e}/comments`,{body:t})}async getPlatformIssue(e){return this.http.get(`/v1/public/platform-issues/${e}`)}async listMyPlatformIssues(e={}){let t=new URLSearchParams;for(let r of e.status??[])t.append("status",r);for(let r of e.severity??[])t.append("severity",r);for(let r of e.category??[])t.append("category",r);e.sinceUpdatedAt&&t.set("since_updated_at",e.sinceUpdatedAt),e.cursor&&t.set("cursor",e.cursor),typeof e.limit=="number"&&t.set("limit",String(e.limit));let s=t.toString();return this.http.get(`/v1/public/platform-issues${s?`?${s}`:""}`)}};function Us(){return"6.17.0"}function Ds(){return typeof window<"u"&&typeof document<"u"?"web":"node"}function $t(n){let e=n;e=e.replace(/(\(|\s|^)(?:file:\/\/)?\/[^\s)]+\/([^\s/)]+)(:\d+:\d+)?/g,"$1$2$3"),e=e.replace(/(https?:\/\/[^\s)?]+)\?[^\s)]*/g,"$1");let t=32*1024;return e.length>t&&(e=`${e.slice(0,t)}
5
5
  \u2026[truncated]`),e}var Mt=5*1024*1024,J=class extends Error{constructor(e,t){super(e),this.name="VideoProcessingError",this.video=t}},Me=class{constructor(e,t){this.http=e;this.storage={create:async e=>this.http.post("/v1/public/storages/videos",e),list:async()=>this.http.get("/v1/public/storages/videos"),get:async e=>this.http.get(`/v1/public/storages/videos/${e}`),update:async(e,t)=>this.http.put(`/v1/public/storages/videos/${e}`,t),delete:async e=>{await this.http.delete(`/v1/public/storages/videos/${e}`)},upload:async(e,t,s)=>{let r=await this.http.post(`/v1/public/storages/videos/${e}/uploads/init`,{filename:t.name,file_size:t.size,mime_type:t.type}),i=r.chunk_size||Mt,o=Math.ceil(t.size/i),a=0,c=Date.now(),l=0;for(let d=0;d<o;d++){let h=d*i,p=Math.min(h+i,t.size),f=t.slice(h,p),m=new FormData;m.append("chunk",f),await this.http.put(`/v1/public/storages/videos/${e}/uploads/${r.upload_id}/chunk?chunk_index=${d}`,m),a++;let g=Date.now(),v=(g-c)/1e3,_=p,P=_-l,y=v>0?P/v:0;c=g,l=_,s.onProgress&&s.onProgress({phase:"uploading",uploadedChunks:a,totalChunks:o,percentage:Math.round(a/o*100),currentSpeed:y})}let u=await this.http.post(`/v1/public/storages/videos/${e}/uploads/${r.upload_id}/complete`,{title:s.title,description:s.description,visibility:s.visibility||"private",tags:s.tags});return this.storage.getVideo(e,u.video_id)},listVideos:async(e,t)=>{let s=new URLSearchParams;t?.status&&s.set("status",t.status),t?.visibility&&s.set("visibility",t.visibility),t?.search&&s.set("search",t.search),t?.page&&s.set("page",String(t.page)),t?.limit&&s.set("limit",String(t.limit));let r=s.toString();return this.http.get(`/v1/public/storages/videos/${e}/videos${r?`?${r}`:""}`)},getVideo:async(e,t)=>this.http.get(`/v1/public/storages/videos/${e}/videos/${t}`),deleteVideo:async(e,t)=>{await this.http.delete(`/v1/public/storages/videos/${e}/videos/${t}`)},getStreamUrl:async(e,t)=>this.http.get(`/v1/public/storages/videos/${e}/videos/${t}/stream`),getTranscodeStatus:async(e,t)=>this.http.get(`/v1/public/storages/videos/${e}/videos/${t}/transcode`)};this.videoBaseUrl=t||this.getDefaultVideoUrl()}getDefaultVideoUrl(){if(typeof window<"u"){let e=window.location.hostname;if(e==="localhost"||e==="127.0.0.1")return"http://localhost:8089"}return"https://video.connectbase.world"}getPublicPrefix(){return this.http.hasPublicKey()?"/v1/public":"/v1"}async videoFetch(e,t,s){let r={},i=this.http.getPublicKey();i&&(r["X-Public-Key"]=i);let o=this.http.getAccessToken();o&&(r.Authorization=`Bearer ${o}`),s&&!(s instanceof FormData)&&(r["Content-Type"]="application/json");let{signal:a,cleanup:c}=A({timeout:3e4});try{let l=await fetch(`${this.videoBaseUrl}${t}`,{method:e,headers:r,body:s instanceof FormData?s:s?JSON.stringify(s):void 0,signal:a});if(!l.ok){let u=await l.json().catch(()=>({message:l.statusText})),d=u.error;if(d&&typeof d=="object"&&"message"in d)throw new b(l.status,d.message||"Unknown error",d.code,d.details);let h=typeof d=="string"?d:u.message||"Unknown error";throw new b(l.status,h)}return l.status===204||l.headers.get("content-length")==="0"?{}:await l.json()}finally{c()}}async upload(e,t){let s=this.getPublicPrefix(),r=await this.videoFetch("POST",`${s}/uploads/init`,{filename:e.name,file_size:e.size,mime_type:e.type}),i=r.chunk_size||Mt,o=Math.ceil(e.size/i),a=0,l=Date.now(),u=0;for(let h=0;h<o;h++){let p=h*i,f=Math.min(p+i,e.size),m=e.slice(p,f),g=new FormData;g.append("chunk",m),await this.videoFetch("PUT",`${s}/uploads/${r.upload_id}/chunk?chunk_index=${h}`,g),a++;let v=Date.now(),_=(v-l)/1e3,P=f,y=P-u,D=_>0?y/_:0;l=v,u=P,t.onProgress&&t.onProgress({phase:"uploading",uploadedChunks:a,totalChunks:o,percentage:Math.round(a/o*100),currentSpeed:D})}let d=await this.videoFetch("POST",`${s}/uploads/${r.upload_id}/complete`,{title:t.title,description:t.description,visibility:t.visibility||"private",tags:t.tags});return this.get(d.video_id)}async waitForReady(e,t){let s=t?.timeout||18e5,r=t?.interval||5e3,i=Date.now(),o=this.getPublicPrefix();for(;Date.now()-i<s;){let a=await this.videoFetch("GET",`${o}/videos/${e}`);if(a.status==="ready")return a;if(a.status==="failed")throw new J("Video processing failed",a);if(t?.onProgress){let c=a.qualities.filter(u=>u.status==="ready").length,l=a.qualities.length||1;t.onProgress({phase:"processing",uploadedChunks:0,totalChunks:0,percentage:Math.round(c/l*100)})}await new Promise(c=>setTimeout(c,r))}throw new J("Timeout waiting for video to be ready")}async list(e){let t=this.getPublicPrefix(),s=new URLSearchParams;e?.status&&s.set("status",e.status),e?.visibility&&s.set("visibility",e.visibility),e?.search&&s.set("search",e.search),e?.channel_id&&s.set("channel_id",e.channel_id),e?.page&&s.set("page",String(e.page)),e?.limit&&s.set("limit",String(e.limit));let r=s.toString();return this.videoFetch("GET",`${t}/videos${r?`?${r}`:""}`)}async get(e){let t=this.getPublicPrefix();return this.videoFetch("GET",`${t}/videos/${e}`)}async update(e,t){let s=this.getPublicPrefix();return this.videoFetch("PATCH",`${s}/videos/${e}`,t)}async delete(e){let t=this.getPublicPrefix();await this.videoFetch("DELETE",`${t}/videos/${e}`)}async getStreamUrl(e,t){let s=this.getPublicPrefix(),r=t?`?quality=${t}`:"";return this.videoFetch("GET",`${s}/videos/${e}/stream-url${r}`)}async getThumbnails(e){let t=this.getPublicPrefix(),s=await this.videoFetch("GET",`${t}/videos/${e}/thumbnail`),r=new Set;s.thumbnail_url&&r.add(s.thumbnail_url);for(let i of s.thumbnail_urls??[])i&&r.add(i);return[...r]}async getTranscodeStatus(e){let t=this.getPublicPrefix();return this.videoFetch("GET",`${t}/videos/${e}/transcode/status`)}async retryTranscode(e){let t=this.getPublicPrefix();await this.videoFetch("POST",`${t}/videos/${e}/transcode/retry`,{})}async createChannel(e){let t=this.getPublicPrefix();return this.videoFetch("POST",`${t}/channels`,e)}async getChannel(e){let t=this.getPublicPrefix();return this.videoFetch("GET",`${t}/channels/${e}`)}async getChannelByHandle(e){let t=this.getPublicPrefix();return this.videoFetch("GET",`${t}/channels/handle/${e}`)}async updateChannel(e,t){let s=this.getPublicPrefix();return this.videoFetch("PATCH",`${s}/channels/${e}`,t)}async subscribeChannel(e){let t=this.getPublicPrefix();await this.videoFetch("POST",`${t}/channels/${e}/subscribe`,{})}async unsubscribeChannel(e){let t=this.getPublicPrefix();await this.videoFetch("DELETE",`${t}/channels/${e}/subscribe`)}async createPlaylist(e,t){let s=this.getPublicPrefix();return this.videoFetch("POST",`${s}/playlists`,{...t,channel_id:e})}async getPlaylists(e){let t=this.getPublicPrefix();return(await this.videoFetch("GET",`${t}/playlists/public?channel_id=${encodeURIComponent(e)}`)).playlists}async getPlaylistItems(e){let t=this.getPublicPrefix();return(await this.videoFetch("GET",`${t}/playlists/${e}`)).items}async addToPlaylist(e,t,s){let r=this.getPublicPrefix();return this.videoFetch("POST",`${r}/playlists/${e}/items`,{video_id:t,position:s})}async removeFromPlaylist(e,t){let s=this.getPublicPrefix();await this.videoFetch("DELETE",`${s}/playlists/${e}/items/${t}`)}async getShortsFeed(e){let t=this.getPublicPrefix(),s=new URLSearchParams;e?.cursor&&s.set("cursor",e.cursor),e?.limit&&s.set("limit",String(e.limit));let r=s.toString();return this.videoFetch("GET",`${t}/shorts${r?`?${r}`:""}`)}async getTrendingShorts(e){let t=this.getPublicPrefix(),s=e?`?limit=${e}`:"";return this.videoFetch("GET",`${t}/shorts/trending${s}`)}async getShorts(e){let t=this.getPublicPrefix();return this.videoFetch("GET",`${t}/shorts/${e}`)}async getComments(e,t){let s=this.getPublicPrefix(),r=new URLSearchParams;t?.cursor&&r.set("cursor",t.cursor),t?.limit&&r.set("limit",String(t.limit)),t?.sort&&r.set("sort",t.sort);let i=r.toString();return this.videoFetch("GET",`${s}/videos/${e}/comments${i?`?${i}`:""}`)}async postComment(e,t,s){let r=this.getPublicPrefix();return this.videoFetch("POST",`${r}/comments`,{video_id:e,content:t,parent_id:s})}async deleteComment(e){let t=this.getPublicPrefix();await this.videoFetch("DELETE",`${t}/comments/${e}`)}async likeVideo(e){let t=this.getPublicPrefix();await this.videoFetch("POST",`${t}/videos/${e}/like`,{})}async unlikeVideo(e){let t=this.getPublicPrefix();await this.videoFetch("DELETE",`${t}/videos/${e}/like`)}async getWatchHistory(e){let t=this.getPublicPrefix(),s=new URLSearchParams;e?.cursor&&s.set("cursor",e.cursor),e?.limit&&s.set("limit",String(e.limit));let r=s.toString();return this.videoFetch("GET",`${t}/watch-history${r?`?${r}`:""}`)}async clearWatchHistory(){let e=this.getPublicPrefix();await this.videoFetch("DELETE",`${e}/watch-history`)}async reportWatchProgress(e,t,s){let r=this.getPublicPrefix();await this.videoFetch("POST",`${r}/videos/${e}/watch-progress`,{position:t,duration:s})}async getMembershipTiers(e){let t=this.getPublicPrefix();return(await this.videoFetch("GET",`${t}/channels/${e}/membership/tiers`)).tiers}async joinMembership(e,t){let s=this.getPublicPrefix();return this.videoFetch("POST",`${s}/membership/join`,{tier_id:t})}async cancelMembership(e,t){let s=this.getPublicPrefix();await this.videoFetch("POST",`${s}/membership/${t}/cancel`,{})}async sendSuperChat(e,t,s){let r=this.getPublicPrefix();return this.videoFetch("POST",`${r}/super-chats`,{channel_id:e,type:s?.type??"super_thanks",amount:t,video_id:s?.videoId,live_id:s?.liveId,currency:s?.currency??"USD",message:s?.message,sticker_id:s?.stickerId})}async getSuperChats(e){let t=this.getPublicPrefix();return(await this.videoFetch("GET",`${t}/videos/${e}/super-chats`)).super_chats}async getRecommendations(e){let t=this.getPublicPrefix(),s=e?`?limit=${e}`:"";return(await this.videoFetch("GET",`${t}/recommendations/feed${s}`)).videos}async getHomeFeed(e){let t=this.getPublicPrefix(),s=e?`?limit=${e}`:"";return(await this.videoFetch("GET",`${t}/recommendations/feed${s}`)).videos}async getRelatedVideos(e,t){let s=this.getPublicPrefix(),r=t?`?limit=${t}`:"";return(await this.videoFetch("GET",`${s}/videos/${e}/related${r}`)).videos}async getTrendingVideos(e){let t=this.getPublicPrefix(),s=e?`?limit=${e}`:"";return(await this.videoFetch("GET",`${t}/recommendations/trending${s}`)).videos}async submitFeedback(e,t){let s=this.getPublicPrefix();if(t==="not_interested"){await this.videoFetch("POST",`${s}/recommendations/not-interested/${e}`,{});return}await this.videoFetch("POST",`${s}/recommendations/interactions`,{video_id:e,type:"like"})}};var Oe=class n{constructor(e,t,s){this.ws=null;this.state="disconnected";this.stateListeners=[];this.errorListeners=[];this.peerJoinedListeners=[];this.peerLeftListeners=[];this.remoteStreamListeners=[];this.reconnectAttempts=0;this.maxReconnectAttempts=5;this.reconnectTimeout=null;this.wsGeneration=0;this.currentRoomId=null;this.currentPeerId=null;this.currentUserId=null;this.broadcasterRequested=!1;this.broadcasterGranted=!1;this.allowedMemberIds=null;this.privateRoom=!1;this.warningListeners=[];this.localStream=null;this.channelType="interactive";this.peerConnections=new Map;this.remoteStreams=new Map;this.iceServers=[];this.http=e,this.webrtcUrl=t,this.appId=s}async getICEServers(){if(!this.appId)throw new Error("WebRTC getICEServers \uC5D0\uB294 appId \uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. ConnectBase \uCD08\uAE30\uD654 \uC2DC appId \uB97C \uC124\uC815\uD558\uC138\uC694.");let e=await this.http.get(`/v1/apps/${this.appId}/ice-servers`,{baseUrl:this.webrtcUrl});return this.iceServers=e.ice_servers,e.ice_servers}async connect(e){if(this.state==="connected"||this.state==="connecting")throw new Error("\uC774\uBBF8 \uC5F0\uACB0\uB418\uC5B4 \uC788\uAC70\uB098 \uC5F0\uACB0 \uC911\uC785\uB2C8\uB2E4");if(this.setState("connecting"),this.currentRoomId=e.roomId,this.currentUserId=e.userId||null,this.broadcasterRequested=e.isBroadcaster||!1,this.broadcasterGranted=!1,this.allowedMemberIds=e.allowedMemberIds?[...e.allowedMemberIds]:null,this.privateRoom=!1,this.localStream=e.localStream||null,this.iceServers.length===0)try{await this.getICEServers()}catch{this.iceServers=[{urls:"stun:stun.l.google.com:19302"}]}return this.connectWebSocket()}async connectWebSocket(){let e=this.wsGeneration,t=await this.signalingTicket();if(this.wsGeneration!==e)throw new Error("\uC5F0\uACB0\uC774 \uCDE8\uC18C\uB418\uC5C8\uC2B5\uB2C8\uB2E4");return this.openSignalingSocket(t)}async signalingTicket(){let e=this.http.getAccessToken(),t=e?void 0:this.http.getPublicKey();return!e&&!t||!this.appId?null:x($(this.webrtcUrl,`/v1/apps/${encodeURIComponent(this.appId)}/signaling/ws-ticket`),"webrtc.signaling",e?{kind:"access_token",value:e}:{kind:"public_key",value:t})}openSignalingSocket(e){return new Promise((t,s)=>{let r=this.buildWebSocketUrl(e),i=++this.wsGeneration,o=new WebSocket(r);this.ws=o;let a=()=>this.wsGeneration!==i,c=setTimeout(()=>{a()||this.state==="connecting"&&(o.close(),s(new Error("\uC5F0\uACB0 \uC2DC\uAC04 \uCD08\uACFC")))},1e4);o.onopen=()=>{if(clearTimeout(c),a()){o.close(1e3,"superseded");return}this.reconnectAttempts=0;let l={is_broadcaster:this.broadcasterRequested};this.allowedMemberIds&&(l.allowed_member_ids=this.allowedMemberIds),this.sendSignaling({type:"join",room_id:this.currentRoomId,data:l})},o.onmessage=async l=>{if(!a())try{let u=JSON.parse(l.data);await this.handleSignalingMessage(u,t,s)}catch(u){console.error("Failed to parse signaling message:",u)}},o.onerror=l=>{clearTimeout(c),!a()&&(console.error("WebSocket error:",l),this.emitError(new Error("WebSocket \uC5F0\uACB0 \uC624\uB958")))},o.onclose=l=>{clearTimeout(c),!a()&&(this.state==="connecting"&&s(new Error("\uC5F0\uACB0\uC774 \uC885\uB8CC\uB418\uC5C8\uC2B5\uB2C8\uB2E4")),this.handleDisconnect(l))}})}static detachSocket(e){e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null}buildWebSocketUrl(e=null){let t=this.webrtcUrl.replace("https://","wss://").replace("http://","ws://"),s=this.http.getPublicKey(),r=this.http.getAccessToken(),i="";if(e?i=`ticket=${encodeURIComponent(e)}`:r?i=`access_token=${encodeURIComponent(r)}`:s&&(i=`public_key=${encodeURIComponent(s)}`),!this.appId)throw new Error("WebRTC \uC5F0\uACB0\uC5D0\uB294 appId\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. ConnectBase \uCD08\uAE30\uD654 \uC2DC appId\uB97C \uC124\uC815\uD558\uC138\uC694.");return`${t}/v1/apps/${this.appId}/signaling?${i}`}async handleSignalingMessage(e,t,s){switch(e.type){case"joined":if(this.setState("connected"),this.currentPeerId=e.peer_id||null,e.data&&typeof e.data=="object"){let r=e.data;r.channel_type&&(this.channelType=r.channel_type),this.broadcasterGranted=r.is_broadcaster===!0,this.privateRoom=r.private===!0;let i=r.peers||[];for(let o of i)o.peer_id!==this.currentPeerId&&await this.createPeerConnection(o.peer_id,!0)}t?.();break;case"peer_joined":if(e.peer_id&&e.peer_id!==this.currentPeerId){let r={peer_id:e.peer_id,...typeof e.data=="object"?e.data:{}};this.emitPeerJoined(e.peer_id,r),await this.createPeerConnection(e.peer_id,!1)}break;case"peer_left":e.peer_id&&(this.closePeerConnection(e.peer_id),this.emitPeerLeft(e.peer_id));break;case"offer":e.peer_id&&e.sdp&&await this.handleOffer(e.peer_id,e.sdp);break;case"answer":e.peer_id&&e.sdp&&await this.handleAnswer(e.peer_id,e.sdp);break;case"ice_candidate":e.peer_id&&e.candidate&&await this.handleICECandidate(e.peer_id,e.candidate);break;case"warning":{let r=e.data&&typeof e.data=="object"?e.data:{};this.emitWarning({code:typeof r.code=="string"?r.code:"unknown",message:typeof r.message=="string"?r.message:""});break}case"error":{let r=new Error(n.signalingErrorMessage(e.data));this.emitError(r),s?.(r);break}}}async createPeerConnection(e,t){this.closePeerConnection(e);let s={iceServers:this.iceServers.map(i=>({urls:i.urls,username:i.username,credential:i.credential}))},r=new RTCPeerConnection(s);if(this.peerConnections.set(e,r),this.localStream&&this.localStream.getTracks().forEach(i=>{r.addTrack(i,this.localStream)}),r.onicecandidate=i=>{i.candidate&&this.sendSignaling({type:"ice_candidate",target_id:e,candidate:i.candidate.toJSON()})},r.ontrack=i=>{let[o]=i.streams;o&&(this.remoteStreams.set(e,o),this.emitRemoteStream(e,o))},r.onconnectionstatechange=()=>{r.connectionState==="failed"&&(console.warn(`Peer connection failed: ${e}`),this.closePeerConnection(e))},t){let i=await r.createOffer();await r.setLocalDescription(i),this.sendSignaling({type:"offer",target_id:e,sdp:i.sdp})}return r}async handleOffer(e,t){let s=this.peerConnections.get(e);s||(s=await this.createPeerConnection(e,!1)),await s.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:t}));let r=await s.createAnswer();await s.setLocalDescription(r),this.sendSignaling({type:"answer",target_id:e,sdp:r.sdp})}async handleAnswer(e,t){let s=this.peerConnections.get(e);s&&await s.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:t}))}async handleICECandidate(e,t){let s=this.peerConnections.get(e);if(s)try{await s.addIceCandidate(new RTCIceCandidate(t))}catch(r){console.warn("Failed to add ICE candidate:",r)}}closePeerConnection(e){let t=this.peerConnections.get(e);t&&(t.close(),this.peerConnections.delete(e)),this.remoteStreams.delete(e)}static signalingErrorMessage(e){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object"){let t=e;if(typeof t.message=="string"&&t.message)return t.message;if(typeof t.error=="string"&&t.error)return t.error}return"Unknown error"}sendSignaling(e){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}handleDisconnect(e){let t=this.state==="connected";this.setState("disconnected"),this.peerConnections.forEach((s,r)=>{s.close(),this.emitPeerLeft(r)}),this.peerConnections.clear(),this.remoteStreams.clear(),t&&e.code!==1e3&&this.reconnectAttempts<this.maxReconnectAttempts&&this.attemptReconnect()}attemptReconnect(){this.reconnectAttempts++,this.setState("reconnecting");let e=Math.min(5e3*2**(this.reconnectAttempts-1),3e4);this.reconnectTimeout=setTimeout(async()=>{try{await this.connectWebSocket()}catch{this.reconnectAttempts<this.maxReconnectAttempts?this.attemptReconnect():(this.setState("failed"),this.emitError(new Error("\uC7AC\uC5F0\uACB0 \uC2E4\uD328: \uCD5C\uB300 \uC2DC\uB3C4 \uD69F\uC218 \uCD08\uACFC")))}},e)}disconnect(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.reconnectAttempts=0,this.wsGeneration++;let e=this.ws;if(this.ws=null,e)if(n.detachSocket(e),e.readyState===WebSocket.OPEN){try{e.send(JSON.stringify({type:"leave"}))}catch{}e.close(1e3,"User disconnected")}else e.readyState===WebSocket.CONNECTING&&e.close();this.peerConnections.forEach(t=>t.close()),this.peerConnections.clear(),this.remoteStreams.clear(),this.currentRoomId=null,this.currentPeerId=null,this.localStream=null,this.broadcasterGranted=!1,this.privateRoom=!1,this.setState("disconnected")}async switchRoom(e,t={}){let s=t.localStream??this.localStream??void 0,r=t.userId??this.currentUserId??void 0,i=t.isBroadcaster??this.broadcasterRequested;this.disconnect(),await this.connect({roomId:e,userId:r,isBroadcaster:i,localStream:s,allowedMemberIds:t.allowedMemberIds})}createSession(){return new n(this.http,this.webrtcUrl,this.appId)}getState(){return this.state}getRoomId(){return this.currentRoomId}getPeerId(){return this.currentPeerId}getChannelType(){return this.channelType}isBroadcaster(){return this.broadcasterGranted}isPrivateRoom(){return this.privateRoom}getRemoteStream(e){return this.remoteStreams.get(e)}getAllRemoteStreams(){return new Map(this.remoteStreams)}replaceLocalStream(e){this.localStream=e,this.peerConnections.forEach(t=>{let s=t.getSenders();e.getTracks().forEach(r=>{let i=s.find(o=>o.track?.kind===r.kind);i?i.replaceTrack(r):t.addTrack(r,e)})})}setAudioEnabled(e){this.localStream&&this.localStream.getAudioTracks().forEach(t=>{t.enabled=e})}setVideoEnabled(e){this.localStream&&this.localStream.getVideoTracks().forEach(t=>{t.enabled=e})}onStateChange(e){return this.stateListeners.push(e),()=>{this.stateListeners=this.stateListeners.filter(t=>t!==e)}}onError(e){return this.errorListeners.push(e),()=>{this.errorListeners=this.errorListeners.filter(t=>t!==e)}}onWarning(e){return this.warningListeners.push(e),()=>{this.warningListeners=this.warningListeners.filter(t=>t!==e)}}onPeerJoined(e){return this.peerJoinedListeners.push(e),()=>{this.peerJoinedListeners=this.peerJoinedListeners.filter(t=>t!==e)}}onPeerLeft(e){return this.peerLeftListeners.push(e),()=>{this.peerLeftListeners=this.peerLeftListeners.filter(t=>t!==e)}}onRemoteStream(e){return this.remoteStreamListeners.push(e),()=>{this.remoteStreamListeners=this.remoteStreamListeners.filter(t=>t!==e)}}setState(e){this.state!==e&&(this.state=e,this.stateListeners.forEach(t=>t(e)))}emitError(e){this.errorListeners.forEach(t=>t(e))}emitWarning(e){this.warningListeners.forEach(t=>t(e))}emitPeerJoined(e,t){this.peerJoinedListeners.forEach(s=>s(e,t))}emitPeerLeft(e){this.peerLeftListeners.forEach(t=>t(e))}emitRemoteStream(e,t){this.remoteStreamListeners.forEach(s=>s(e,t))}async validate(){if(!this.appId)throw new Error("WebRTC \uAC80\uC99D\uC5D0\uB294 appId\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. ConnectBase \uCD08\uAE30\uD654 \uC2DC appId\uB97C \uC124\uC815\uD558\uC138\uC694.");return this.http.get(`/v1/apps/${this.appId}/validate`,{baseUrl:this.webrtcUrl})}async getSFUToken(e){if(!this.appId)throw new Error("WebRTC getSFUToken \uC5D0\uB294 appId \uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. ConnectBase \uCD08\uAE30\uD654 \uC2DC appId \uB97C \uC124\uC815\uD558\uC138\uC694.");return this.http.post(`/v1/apps/${this.appId}/sfu/token`,{room_id:e.roomId,publish:e.publish,name:e.name,device:e.device},{baseUrl:this.webrtcUrl})}async getStats(e){return this.http.get(`/v1/apps/${e}/stats`,{baseUrl:this.webrtcUrl})}async getRooms(e){return this.http.get(`/v1/apps/${e}/rooms`,{baseUrl:this.webrtcUrl})}};function Ot(n){if(!n)throw new Error("cb.game: clientId is required to build a game connection URL. Pass it via `cb.game.createClient({ appId, clientId })`.");return n}var Je=class{constructor(e,t,s,r){this.type="webtransport";this.transport=null;this.writer=null;this.config=e,this.onMessage=t,this.onClose=s,this.onError=r}async connect(){let e=this.buildUrl();this.transport=new WebTransport(e),await this.transport.ready,this.config.useUnreliableDatagrams!==!1&&this.readDatagrams();let t=await this.transport.createBidirectionalStream();this.writer=t.writable.getWriter(),this.readStream(t.readable),this.transport.closed.then(()=>{this.onClose()}).catch(s=>{this.onError(s)})}buildUrl(){let t=(this.config.gameServerUrl||"https://game.connectbase.world").replace(/^ws/,"http").replace(/^http:/,"https:"),s=new URLSearchParams;return s.set("client_id",Ot(this.config.clientId)),this.config.publicKey&&s.set("public_key",this.config.publicKey),this.config.accessToken&&s.set("token",this.config.accessToken),`${t}/v1/game/webtransport?${s.toString()}`}async readDatagrams(){if(!this.transport)return;let e=this.transport.datagrams.readable.getReader();try{for(;;){let{value:t,done:s}=await e.read();if(s)break;this.onMessage(t)}}catch{}}async readStream(e){let t=e.getReader(),s=new Uint8Array(0);try{for(;;){let{value:r,done:i}=await t.read();if(i)break;let o=new Uint8Array(s.length+r.length);for(o.set(s),o.set(r,s.length),s=o;s.length>=4;){let a=new DataView(s.buffer).getUint32(0,!0);if(s.length<4+a)break;let c=s.slice(4,4+a);s=s.slice(4+a),this.onMessage(c)}}}catch{}}disconnect(){this.transport&&(this.transport.close(),this.transport=null,this.writer=null)}send(e,t=!0){if(!this.transport)throw new w({code:"NOT_CONNECTED",message:"Not connected"});let s=typeof e=="string"?new TextEncoder().encode(e):e;if(t){if(this.writer){let r=new Uint8Array(4);new DataView(r.buffer).setUint32(0,s.length,!0);let i=new Uint8Array(4+s.length);i.set(r),i.set(s,4),this.writer.write(i)}}else{let r=this.config.maxDatagramSize||1200;s.length<=r?this.transport.datagrams.writable.getWriter().write(s):(console.warn("Datagram too large, falling back to reliable stream"),this.send(e,!0))}}isConnected(){return this.transport!==null}},Ue=class{constructor(e,t,s,r){this.type="websocket";this.ws=null;this.config=e,this.onMessage=t,this.onClose=s,this.onError=r}async connect(){let e=await this.connectionTicket();return this.openSocket(e)}async connectionTicket(){let{accessToken:e,publicKey:t,appId:s}=this.config;if(!e&&!t||!s)return null;let r=this.config.gameServerUrl||"wss://game.connectbase.world";try{return await x($(r,`/v1/game/${encodeURIComponent(s)}/ws-ticket`),"game.ws",e?{kind:"access_token",value:e}:{kind:"public_key",value:t})}catch(i){throw i instanceof C?new w({code:i.code,message:i.message}):i}}openSocket(e){return new Promise((t,s)=>{try{this.ws=new WebSocket(this.buildUrl(e)),this.ws.binaryType="arraybuffer"}catch(c){s(c);return}let r=()=>{t()},i=()=>{this.onClose()},o=c=>{let l=new Error("WebSocket error");this.onError(l),s(l)},a=c=>{c.data instanceof ArrayBuffer?this.onMessage(new Uint8Array(c.data)):typeof c.data=="string"&&this.onMessage(new TextEncoder().encode(c.data))};this.ws.addEventListener("open",r,{once:!0}),this.ws.addEventListener("close",i),this.ws.addEventListener("error",o,{once:!0}),this.ws.addEventListener("message",a)})}buildUrl(e=null){let s=(this.config.gameServerUrl||"wss://game.connectbase.world").replace(/^http/,"ws"),r=new URLSearchParams;if(r.set("client_id",Ot(this.config.clientId)),e?r.set("ticket",e):(this.config.publicKey&&r.set("public_key",this.config.publicKey),this.config.accessToken&&r.set("token",this.config.accessToken)),!this.config.appId)throw new Error("cb.game: appId is required to build a game connection URL. Pass it to `new ConnectBase({ appId })` or per-client via `cb.game.createClient({ appId, clientId })`.");return`${s}/v1/game/${this.config.appId}/ws?${r.toString()}`}disconnect(){this.ws&&(this.ws.close(1e3,"Client disconnected"),this.ws=null)}send(e,t){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new w({code:"NOT_CONNECTED",message:"Not connected"});typeof e=="string"?this.ws.send(e):this.ws.send(e)}isConnected(){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN}};function Qe(){return typeof WebTransport<"u"}var De=class{constructor(e){this.transport=null;this.handlers={};this.reconnectAttempts=0;this.reconnectTimer=null;this.pingInterval=null;this.actionSequence=0;this._roomId=null;this._state=null;this._scriptName=null;this._scriptVersion=null;this._isConnected=!1;this._connectionStatus="disconnected";this._lastError=null;this._latency=0;this._transportType="websocket";this.decoder=new TextDecoder;this.pendingHandlers=new Map;this.messageId=0;this.config={gameServerUrl:this.getDefaultGameServerUrl(),autoReconnect:!0,maxReconnectAttempts:5,reconnectInterval:1e3,connectionTimeout:1e4,transport:"auto",useUnreliableDatagrams:!0,...e}}getDefaultGameServerUrl(){if(typeof window<"u"){let e=window.location.hostname;if(e==="localhost"||e==="127.0.0.1")return"ws://localhost:8087"}return"wss://game.connectbase.world"}get transportType(){return this._transportType}get roomId(){return this._roomId}get state(){return this._state}get isConnected(){return this._isConnected}get scriptName(){return this._scriptName}get scriptVersion(){return this._scriptVersion}get connectionState(){return{status:this._connectionStatus,transport:this._transportType==="auto"?null:this._transportType,roomId:this._roomId,latency:this._latency,reconnectAttempt:this.reconnectAttempts,lastError:this._lastError||void 0}}get latency(){return this._latency}on(e,t){return this.handlers[e]=t,this}async connect(e){if(this.transport?.isConnected())return;this._connectionStatus=this.reconnectAttempts>0?"reconnecting":"connecting";let t=this.config.transport||"auto",s=(t==="webtransport"||t==="auto")&&Qe(),r=a=>{this.handleMessage(this.decoder.decode(a))},i=()=>{this._isConnected=!1,this._connectionStatus="disconnected",this.stopPingInterval(),this.handlers.onDisconnect?.(new CloseEvent("close")),this.config.autoReconnect&&(this._connectionStatus="reconnecting",this.scheduleReconnect(e))},o=a=>{this._connectionStatus="error",this._lastError=a,this.handlers.onError?.(new w({code:"CONNECTION_ERROR",message:a.message}))};if(s)try{this.transport=new Je(this.config,r,i,o),await this.transport.connect(),this._transportType="webtransport"}catch{console.log("WebTransport failed, falling back to WebSocket"),this.transport=new Ue(this.config,r,i,o),await this.transport.connect(),this._transportType="websocket"}else this.transport=new Ue(this.config,r,i,o),await this.transport.connect(),this._transportType="websocket";this._isConnected=!0,this._connectionStatus="connected",this._lastError=null,this.reconnectAttempts=0,this.startPingInterval(),this.handlers.onConnect?.(),e&&await this.joinRoom(e)}disconnect(){this.stopPingInterval(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.transport&&(this.transport.disconnect(),this.transport=null),this._isConnected=!1,this._connectionStatus="disconnected",this._roomId=null,this._state=null}async createRoom(e={}){return(await this.createRoomDetailed(e)).state}async createRoomDetailed(e={}){return new Promise((t,s)=>{let r=i=>{if(i.type==="room_created"){let o=i.data;this._roomId=o.room_id,this._state=o.initial_state,this._scriptName=o.script_name??null,this._scriptVersion=o.script_version??null,t({roomId:o.room_id,state:o.initial_state,scriptName:o.script_name,scriptVersion:o.script_version})}else i.type==="error"&&s(k(i))};this.sendWithHandler("create_room",ee(e),r)})}async joinRoom(e,t){return new Promise((s,r)=>{let i=o=>{if(o.type==="room_joined"){let a=o.data;this._roomId=a.room_id,this._state=a.initial_state,this._scriptName=null,this._scriptVersion=null,s(a.initial_state)}else o.type==="error"&&r(k(o))};this.sendWithHandler("join_room",{room_id:e,metadata:t},i)})}async leaveRoom(){return new Promise((e,t)=>{if(!this._roomId){t(new w({code:"NOT_IN_ROOM",message:"Not in a room"}));return}let s=r=>{r.type==="room_left"?(this._roomId=null,this._state=null,this._scriptName=null,this._scriptVersion=null,e()):r.type==="error"&&t(k(r))};this.sendWithHandler("leave_room",{},s)})}sendAction(e,t=!1){if(!this._roomId)throw new w({code:"NOT_IN_ROOM",message:"Not in a room"});let s=JSON.stringify({type:"action",data:{type:e.type,data:e.data,client_timestamp:e.clientTimestamp??Date.now(),sequence:this.actionSequence++}}),r=t||this._transportType!=="webtransport";this.transport?.send(s,r)}sendChat(e){if(!this._roomId)throw new w({code:"NOT_IN_ROOM",message:"Not in a room"});this.send("chat",{message:e})}async requestState(){return new Promise((e,t)=>{if(!this._roomId){t(new w({code:"NOT_IN_ROOM",message:"Not in a room"}));return}let s=r=>{if(r.type==="state"){let i=r.data;this._state=i,e(i)}else r.type==="error"&&t(k(r))};this.sendWithHandler("get_state",{},s)})}async ping(){return new Promise((e,t)=>{let s=Date.now(),r=i=>{if(i.type==="pong"){let o=i.data,a=Date.now()-o.clientTimestamp;this._latency=a,this.handlers.onPong?.(o),e(a)}else i.type==="error"&&t(k(i))};this.sendWithHandler("ping",{timestamp:s},r)})}send(e,t,s){if(!this.transport?.isConnected())throw new w({code:"NOT_CONNECTED",message:"Not connected"});let r=JSON.stringify({type:e,data:t,msg_id:s});this.transport.send(r,!0)}sendWithHandler(e,t,s){let r=`msg_${this.messageId++}`;this.pendingHandlers.set(r,s),setTimeout(()=>{this.pendingHandlers.delete(r)},1e4),this.send(e,t,r)}handleMessage(e){try{let t=JSON.parse(e);if(t.msg_id&&this.pendingHandlers.has(t.msg_id)){let s=this.pendingHandlers.get(t.msg_id);this.pendingHandlers.delete(t.msg_id),s(t);return}switch(t.type){case"delta":this.handleDelta(t);break;case"state":this._state=t.data,this.handlers.onStateUpdate?.(this._state);break;case"player_event":this.handlePlayerEvent(t);break;case"chat":this.handlers.onChat?.({roomId:t.room_id||"",clientId:t.client_id||"",userId:t.user_id,message:t.message||"",serverTime:t.server_time||0});break;case"error":this.handlers.onError?.(k(t));break;case"room_stale":this.handlers.onRoomStale?this.handlers.onRoomStale({reason:t.reason||"unknown",roomId:t.room_id||"",scriptId:t.script_id,scriptVersion:t.script_version,serverTime:t.server_time||0}):console.warn("[connect-base game] room_stale received but onRoomStale handler not set:",{reason:t.reason,roomId:t.room_id,scriptVersion:t.script_version});break}}catch{console.error("Failed to parse game message:",e)}}handleDelta(e){let t=e.delta;if(!t)return;let s={fromVersion:t.from_version,toVersion:t.to_version,changes:t.changes.map(r=>({path:r.path,operation:r.operation,value:r.value,oldValue:r.old_value})),tick:t.tick};if(this._state){for(let r of s.changes)this.applyChange(r);this._state.version=s.toVersion}if(this.handlers.onAction){for(let r of s.changes)if(r.path.startsWith("actions.")&&r.operation==="set"&&r.value){let i=r.value;this.handlers.onAction({type:i.type||"",clientId:i.client_id||"",data:i.data,timestamp:i.timestamp||0})}}this.handlers.onDelta?.(s)}applyChange(e){this._state&&Ke(this._state.state,e)}handlePlayerEvent(e){let t={clientId:e.player?.client_id||"",userId:e.player?.user_id,joinedAt:e.player?.joined_at||0,metadata:e.player?.metadata};e.event==="joined"?this.handlers.onPlayerJoined?.(t):e.event==="left"&&this.handlers.onPlayerLeft?.(t)}scheduleReconnect(e){if(this.reconnectAttempts>=(this.config.maxReconnectAttempts??5)){console.error("Max reconnect attempts reached");return}let t=Math.min((this.config.reconnectInterval??1e3)*2**this.reconnectAttempts,3e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{console.log(`Reconnecting... (attempt ${this.reconnectAttempts})`),this.connect(e||this._roomId||void 0).catch(()=>{})},t)}startPingInterval(){this.pingInterval=setInterval(()=>{this.ping().catch(()=>{})},3e4)}stopPingInterval(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null)}};var Ls="$auth.member_id";var qs="https://api.connectbase.world",Ns="https://socket.connectbase.world",Bs="https://webrtc.connectbase.world",Hs="https://video.connectbase.world",Fs="https://game.connectbase.world",Le=class{constructor(e={}){let t=o=>{if(!(typeof process>"u"||!process.env))return process.env[o]},s={baseUrl:e.baseUrl||t("CB_BASE_URL")||qs,publicKey:e.publicKey,secretKey:e.secretKey,appId:e.appId,persistence:e.persistence,autoRestoreSession:e.autoRestoreSession,requestTimeoutMs:e.requestTimeoutMs,onError:e.onError,onTokenRefresh:e.onTokenRefresh,onAuthError:e.onAuthError,onTokenExpired:e.onTokenExpired,onTransientRefreshFailure:e.onTransientRefreshFailure};this.http=new pe(s),this.auth=new ce(this.http),this.database=new he(this.http),this.storage=new Ae(this.http),this.publicKey=new Se(this.http),this.functions=new ge(this.http),this.realtime=new Ee(this.http,e.socketUrl||t("CB_SOCKET_URL")||Ns),this.webrtc=new Oe(this.http,e.webrtcUrl||t("CB_WEBRTC_URL")||Bs,e.appId),this.errorTracker=new me(this.http,e.errorTracker),this.oauth=new _e(this.http),this.payment=new Pe(this.http),this.subscription=new xe(this.http),this.organizations=new z(this.http),this.push=new ke(this.http),this.roles=new j(this.http),this.appMembers=new B(this.http),this.video=new Me(this.http,e.videoUrl||t("CB_VIDEO_URL")||Hs),this.game=new W(this.http,e.gameUrl||t("CB_GAME_URL")||Fs,e.appId),this.ads=new L(this.http),this.native=new V,this.knowledge=new fe(this.http),this.ai=new N(this.http),this.queue=new Te(this.http),this.analytics=new ae(this.http),this.endpoint=new G(this.http),this.support=new $e(this.http),this.auth._attachAnalytics(this.analytics);let r=typeof window<"u"?this.oauth.captureCallbackOnBoot():"none";(e.autoRestoreSession??!0)&&typeof window<"u"&&(r==="redirect"?this.http.setBootRestorePromise(this.oauth.consumeRedirectCallbackOnBoot(),{alwaysAwait:!0}):r!=="popup"&&!this.isOAuthCallbackUrl()&&this.http.setBootRestorePromise(this.http.tryRestoreSessionFromCookie()))}isOAuthCallbackUrl(){if(typeof window>"u"||!window.location)return!1;let e=new URLSearchParams(window.location.search);return!!(e.has("code")&&e.has("state")||e.has("error")&&e.has("state"))}async restoreSession(){return this.http.tryRestoreSessionFromCookie()}setTokens(e,t){this.http.setTokens(e,t)}clearTokens(){this.http.clearTokens()}updateConfig(e){this.http.updateConfig(e)}},Gs=Le;return Ht(Ks);})();
6
6
  var ConnectBase = ConnectBaseModule.default || ConnectBaseModule.ConnectBase;
package/dist/index.d.mts CHANGED
@@ -2848,7 +2848,7 @@ interface PopulateOption {
2848
2848
  populate?: PopulateOption[];
2849
2849
  }
2850
2850
  type TriggerEvent = "create" | "update" | "delete" | "all";
2851
- type TriggerHandlerType = "function" | "workflow" | "webhook" | "inline";
2851
+ type TriggerHandlerType = "function" | "webhook" | "inline";
2852
2852
  interface Trigger {
2853
2853
  id: string;
2854
2854
  app_id: string;
package/dist/index.d.ts CHANGED
@@ -2848,7 +2848,7 @@ interface PopulateOption {
2848
2848
  populate?: PopulateOption[];
2849
2849
  }
2850
2850
  type TriggerEvent = "create" | "update" | "delete" | "all";
2851
- type TriggerHandlerType = "function" | "workflow" | "webhook" | "inline";
2851
+ type TriggerHandlerType = "function" | "webhook" | "inline";
2852
2852
  interface Trigger {
2853
2853
  id: string;
2854
2854
  app_id: string;
package/dist/index.js CHANGED
@@ -13632,8 +13632,8 @@ var SupportAPI = class {
13632
13632
  }
13633
13633
  };
13634
13634
  function detectSdkVersion() {
13635
- if ("6.16.0") {
13636
- return "6.16.0";
13635
+ if ("6.17.0") {
13636
+ return "6.17.0";
13637
13637
  }
13638
13638
  return "unknown";
13639
13639
  }
package/dist/index.mjs CHANGED
@@ -13579,8 +13579,8 @@ var SupportAPI = class {
13579
13579
  }
13580
13580
  };
13581
13581
  function detectSdkVersion() {
13582
- if ("6.16.0") {
13583
- return "6.16.0";
13582
+ if ("6.17.0") {
13583
+ return "6.17.0";
13584
13584
  }
13585
13585
  return "unknown";
13586
13586
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "connectbase-client",
3
- "version": "6.16.0",
3
+ "version": "6.17.0",
4
4
  "description": "Connect Base JavaScript/TypeScript SDK for browser and Node.js",
5
5
  "repository": {
6
6
  "type": "git",