1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[5117],{12436:(e,t,s)=>{let i;s.d(t,{sd:()=>H,Tb:()=>ei});var r=s(23411),n=s(93968),o=s(72457);function a(e){let t,s,i=e.split(":");return 1===i.length?(t=i[0],s="default"):(t=i.slice(0,i.length-1).join(":"),s=i[i.length-1]),t.endsWith(".js")&&(t=t.slice(0,-3)),`${t}:${s}`}function u(e,t){return JSON.stringify({udfPath:a(e),args:(0,n.rz)(t)})}var h=Object.defineProperty,c=(e,t,s)=>t in e?h(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,l=(e,t,s)=>c(e,"symbol"!=typeof t?t+"":t,s);class d{constructor(){l(this,"nextQueryId"),l(this,"querySetVersion"),l(this,"querySet"),l(this,"queryIdToToken"),l(this,"identityVersion"),l(this,"auth"),l(this,"outstandingQueriesOlderThanRestart"),l(this,"outstandingAuthOlderThanRestart"),l(this,"paused"),l(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return 0===this.outstandingQueriesOlderThanRestart.size&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,t,s,i){let r=a(e),o=u(r,t),h=this.querySet.get(o);if(void 0!==h)return h.numSubscribers+=1,{queryToken:o,modification:null,unsubscribe:()=>this.removeSubscriber(o)};{let e=this.nextQueryId++;this.querySet.set(o,{id:e,canonicalizedUdfPath:r,args:t,numSubscribers:1,journal:s,componentPath:i}),this.queryIdToToken.set(e,o);let a=this.querySetVersion,u=this.querySetVersion+1,h={type:"Add",queryId:e,udfPath:r,args:[(0,n.rz)(t)],journal:s,componentPath:i};return this.paused?this.pendingQuerySetModifications.set(e,h):this.querySetVersion=u,{queryToken:o,modification:{type:"ModifyQuerySet",baseVersion:a,newVersion:u,modifications:[h]},unsubscribe:()=>this.removeSubscriber(o)}}}transition(e){for(let t of e.modifications)switch(t.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(t.queryId);let e=t.journal;if(void 0!==e){let s=this.queryIdToToken.get(t.queryId);void 0!==s&&(this.querySet.get(s).journal=e)}break}case"QueryRemoved":this.outstandingQueriesOlderThanRestart.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}}queryId(e,t){let s=u(a(e),t),i=this.querySet.get(s);return void 0!==i?i.id:null}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}setAuth(e){this.auth={tokenType:"User",value:e};let t=this.identityVersion;return this.paused||(this.identityVersion=t+1),{type:"Authenticate",baseVersion:t,...this.auth}}setAdminAuth(e,t){let s={tokenType:"Admin",value:e,impersonating:t};this.auth=s;let i=this.identityVersion;return this.paused||(this.identityVersion=i+1),{type:"Authenticate",baseVersion:i,...s}}clearAuth(){this.auth=void 0,this.markAuthCompletion();let e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:"Authenticate",tokenType:"None",baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).canonicalizedUdfPath:null}queryArgs(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(e){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let t=[];for(let s of this.querySet.values()){let i={type:"Add",queryId:s.id,udfPath:s.canonicalizedUdfPath,args:[(0,n.rz)(s.args)],journal:s.journal,componentPath:s.componentPath};t.push(i),e.has(s.id)||this.outstandingQueriesOlderThanRestart.add(s.id)}this.querySetVersion=1;let s={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:t};if(!this.auth)return this.identityVersion=0,[s,void 0];this.outstandingAuthOlderThanRestart=!0;let i={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[s,i]}pause(){this.paused=!0}resume(){let e=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,t=void 0!==this.auth?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[e,t]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){let t=this.querySet.get(e);if(t.numSubscribers>1)return t.numSubscribers-=1,null;{this.querySet.delete(e),this.queryIdToToken.delete(t.id),this.outstandingQueriesOlderThanRestart.delete(t.id);let s=this.querySetVersion,i=this.querySetVersion+1,r={type:"Remove",queryId:t.id};return this.paused?this.pendingQuerySetModifications.has(t.id)?this.pendingQuerySetModifications.delete(t.id):this.pendingQuerySetModifications.set(t.id,r):this.querySetVersion=i,{type:"ModifyQuerySet",baseVersion:s,newVersion:i,modifications:[r]}}}}var f=Object.defineProperty,g=(e,t,s)=>t in e?f(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,y=(e,t,s)=>g(e,"symbol"!=typeof t?t+"":t,s);class p{constructor(e){this.logger=e,y(this,"inflightRequests"),y(this,"requestsOlderThanRestart"),y(this,"inflightMutationsCount",0),y(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,t){return new Promise(s=>{this.inflightRequests.set(e.requestId,{message:e,status:{status:t?"Requested":"NotSent",requestedAt:new Date,onResult:s}}),"Mutation"===e.type?this.inflightMutationsCount++:"Action"===e.type&&this.inflightActionsCount++})}onResponse(e){let t,s,i=this.inflightRequests.get(e.requestId);if(void 0===i||"Completed"===i.status.status)return null;let r="Mutation"===i.message.type?"mutation":"action",a=i.message.udfPath;for(let t of e.logLines)(0,o.Y7)(this.logger,"info",r,a,t);let u=i.status;if(e.success)t={success:!0,logLines:e.logLines,value:(0,n.du)(e.result)},s=()=>u.onResult(t);else{let i=e.result,{errorData:h}=e;(0,o.Y7)(this.logger,"error",r,a,i),t={success:!1,errorMessage:i,errorData:void 0!==h?(0,n.du)(h):void 0,logLines:e.logLines},s=()=>u.onResult(t)}return"ActionResponse"!==e.type&&e.success?(i.status={status:"Completed",result:t,ts:e.ts,onRes
1olve:s},null):(s(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),"Action"===i.message.type?this.inflightActionsCount--:"Mutation"===i.message.type&&this.inflightMutationsCount--,{requestId:e.requestId,result:t})}removeCompleted(e){let t=new Map;for(let[s,i]of this.inflightRequests.entries()){let r=i.status;"Completed"===r.status&&r.ts.lessThanOrEqual(e)&&(r.onResolve(),t.set(s,r.result),"Mutation"===i.message.type?this.inflightMutationsCount--:"Action"===i.message.type&&this.inflightActionsCount--,this.inflightRequests.delete(s),this.requestsOlderThanRestart.delete(s))}return t}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());let e=[];for(let[t,s]of this.inflightRequests){if("NotSent"===s.status.status){s.status.status="Requested",e.push(s.message);continue}if("Mutation"===s.message.type)e.push(s.message);else if("Action"===s.message.type){if(this.inflightRequests.delete(t),this.requestsOlderThanRestart.delete(t),this.inflightActionsCount--,"Completed"===s.status.status)throw Error("Action should never be in 'Completed' state");s.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return e}resume(){let e=[];for(let[,t]of this.inflightRequests)if("NotSent"===t.status.status){t.status.status="Requested",e.push(t.message);continue}return e}hasIncompleteRequests(){for(let e of this.inflightRequests.values())if("Requested"===e.status.status)return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return 0===this.requestsOlderThanRestart.size}timeOfOldestInflightRequest(){if(0===this.inflightRequests.size)return null;let e=Date.now();for(let t of this.inflightRequests.values())"Completed"!==t.status.status&&t.status.requestedAt.getTime()<e&&(e=t.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}}var m=s(33757),v=s(6431),b=s(76711),w=Object.defineProperty,S=(e,t,s)=>t in e?w(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,k=(e,t,s)=>S(e,"symbol"!=typeof t?t+"":t,s);class q{constructor(e){k(this,"queryResults"),k(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...t){let s=(0,v.Zy)(t[0]),i=(0,m.qQ)(e),r=this.queryResults.get(u(i,s));if(void 0!==r)return q.queryValue(r.result)}getAllQueries(e){let t=[],s=(0,m.qQ)(e);for(let e of this.queryResults.values())e.udfPath===a(s)&&t.push({args:e.args,value:q.queryValue(e.result)});return t}setQuery(e,t,s){let i=(0,v.Zy)(t),r=(0,m.qQ)(e),n=u(r,i);this.queryResults.set(n,{udfPath:r,args:i,result:void 0===s?void 0:{success:!0,value:s,logLines:[]}}),this.modifiedQueries.push(n)}static queryValue(e){return void 0===e?void 0:e.success?e.value:void 0}}class C{constructor(){k(this,"queryResults"),k(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,t){this.optimisticUpdates=this.optimisticUpdates.filter(e=>!t.has(e.mutationId));let s=this.queryResults;this.queryResults=new Map(e);let i=new q(this.queryResults);for(let e of this.optimisticUpdates)e.update(i);let r=[];for(let[e,t]of this.queryResults){let i=s.get(e);(void 0===i||i.result!==t.result)&&r.push(e)}return r}applyOptimisticUpdate(e,t){this.optimisticUpdates.push({update:e,mutationId:t});let s=new q(this.queryResults);return e(s),s.modifiedQueries}queryResult(e){let t=this.queryResults.get(e);if(void 0===t)return;let s=t.result;if(void 0!==s){if(s.success)return s.value;if(void 0!==s.errorData)throw(0,o.sA)(s,new b.i((0,o.i7)("query",t.udfPath,s)));throw Error((0,o.i7)("query",t.udfPath,s))}}hasQueryResult(e){return void 0!==this.queryResults.get(e)}queryLogs(e){let t=this.queryResults.get(e);return t?.result?.logLines}}var R=Object.defineProperty,x=(e,t,s)=>t in e?R(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,A=(e,t,s)=>x(e,"symbol"!=typeof t?t+"":t,s);class T{constructor(e,t){A(this,"low"),A(this,"high"),A(this,"__isUnsignedLong__"),this.low=0|e,this.high=0|t,this.__isUnsignedLong__=!0}static isLong(e){return!0===(e&&e.__isUnsignedLong__)}static fromBytesLE(e){return new T(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24)}toBytesLE(){let e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(e){return isNaN(e)||e<0?O:e>=E?I:new T(e%M|0,e/M|0)}toString(){return(BigInt(this.high)*BigInt(M)+BigInt(this.low)).toString()}equals(e){return T.isLong(e)||(e=T.fromValue(e)),(this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low}notEquals(e){return!this.equals(e)}comp(e){return(T.isLong(e)||(e=T.fromValue(e)),this.equals(e))?0:e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return 0>=this.comp(e)}static fromValue(e){return"number"==typeof e?T.fromNumber(e):new T(e.low,e.high)}}let O=new T(0,0),M=0x100000000,E=0xffffffffffffffff,I=new T(-1,-1);var Q=Object.defineProperty,$=(e,t,s)=>t in e?Q(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,P=(e,t,s)=>$(e,"symbol"!=typeof t?t+"":t,s);class _{constructor(e,t){P(this,"version"),P(this,"remoteQuerySet"),P(this,"queryPath"),P(this,"logger"),this.version={querySet:0,ts:T.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=t}transition(e){let t=e.startVersion;if(this.version.querySet!==t.querySet||this.version.ts.notEquals(t.ts)||this.version.identity!==t.identity)throw Error(`Invalid start version: ${t.ts.toString()}:${t.querySet}`);for(let t of e.modifications)switch(t.type){case"QueryUpdated":{let e=this.queryPath(t.queryId);if(e)for(let s of t.logLines)(0,o.Y7)(this.logger,"info","query",e,s);let s=(0,n.du)(t.value??null);this.remoteQuerySet.set(t.queryId,{success:!0,value:s,logLines:t.logLines});break}case"QueryFailed":{let e=this.queryPath(t.queryId);if(e)for(let s of t.logLines)(0,o.Y7)(this.logger,"info","query",e,s);let{errorData:s}=t;this.remoteQuerySet.set(t.queryId,{success:!1,errorMessage:t.errorMessage,errorData:void 0!==s?(0,n.du)(s):void 0,logLines:t.logLines});break}case"QueryRemoved":this.remoteQuerySet.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}function V(e){let t=n.o4.toByteArray(e);return T.fromBytesLE(Array.from(t))}var L=Object.defineProperty,j=(e,t,s)=>t in e?L(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,N=(e,t,s)=>j(e,"symbol"!=typeof t?t+"":t,s);class F{constructor(e,t,s,i){N(this,"socket"),N(this,"connectionCount"),N(this,"_hasEverConnected",!1),N(this,"lastCloseReason"),N(this,"initialBackoff"),N(this,"maxBackoff"),N(this,"retries"),N(this,"serverInactivityThreshold"),N(this,"reconnectDueToServerInactivityTimeout"),N(this,"uri"),N(this,"onOpen"),N(this,"onResume"),N(this,"onMessage"),N(this,"webSocketConstructor"),N(this,"logger"),this.webSocketConstructor=s,this.socket={state:"disconnected"},this.connectionCount=0,this.lastCloseReason="InitialConnect",this.initialBackoff=100,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=3e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=e,this.onOpen=t.onOpen,this.onResume=t.onResume,this.onMessage=t.onMessage,this.logger=i,this.connect()}setSocketState(e){this.socket=e,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}`)}connect(){if("terminated"===this.socket.state)return;if("disconnected"!==this.socket.state&&"stopped"!==this.socket.state)throw Error("Didn't start connection from disconnected state: "+this.socket.state);let e=new this.webSocketConstructor(this.uri);this._logVerbose("constructed WebSocket"),this.setSocketState({state:"connecting",ws:e,paused:"no"}),this.resetServerInactivityTimeout(),e.onopen=()=>
1{if(this.logger.logVerbose("begin ws.onopen"),"connecting"!==this.socket.state)throw Error("onopen called with socket not in connecting state");this.setSocketState({state:"ready",ws:e,paused:"yes"===this.socket.paused?"uninitialized":"no"}),this.resetServerInactivityTimeout(),"no"===this.socket.paused&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason})),"InitialConnect"!==this.lastCloseReason&&this.logger.log("WebSocket reconnected"),this.connectionCount+=1,this.lastCloseReason=null},e.onerror=e=>{let t=e.message;this.logger.log(`WebSocket error: ${t}`)},e.onmessage=e=>{this.resetServerInactivityTimeout();let t=function(e){switch(e.type){case"FatalError":case"AuthError":case"ActionResponse":case"Ping":return{...e};case"MutationResponse":if(e.success)return{...e,ts:V(e.ts)};return{...e};case"Transition":return{...e,startVersion:{...e.startVersion,ts:V(e.startVersion.ts)},endVersion:{...e.endVersion,ts:V(e.endVersion.ts)}}}}(JSON.parse(e.data));this._logVerbose(`received ws message with type ${t.type}`),this.onMessage(t).hasSyncedPastLastReconnect&&(this.retries=0)},e.onclose=e=>{if(this._logVerbose("begin ws.onclose"),null===this.lastCloseReason&&(this.lastCloseReason=e.reason??"OnCloseInvoked"),1e3!==e.code&&1001!==e.code&&1005!==e.code&&4040!==e.code){let t=`WebSocket closed with code ${e.code}`;e.reason&&(t+=`: ${e.reason}`),this.logger.log(t)}this.scheduleReconnect()}}socketState(){return this.socket.state}sendMessage(e){let t={type:e.type,..."Authenticate"===e.type&&"User"===e.tokenType?{value:`...${e.value.slice(-7)}`}:{}};if("ready"===this.socket.state&&"no"===this.socket.paused){let s=JSON.stringify(function(e){switch(e.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...e};case"Connect":if(void 0!==e.maxObservedTimestamp)return{...e,maxObservedTimestamp:function(e){let t=new Uint8Array(e.toBytesLE());return n.o4.fromByteArray(t)}(e.maxObservedTimestamp)};return{...e,maxObservedTimestamp:void 0}}}(e));try{this.socket.ws.send(s)}catch(e){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${e}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`sent message with type ${e.type}: ${JSON.stringify(t)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(t)}`),!1}resetServerInactivityTimeout(){"terminated"!==this.socket.state&&(null!==this.reconnectDueToServerInactivityTimeout&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(){this.socket={state:"disconnected"};let e=this.nextBackoff();this.logger.log(`Attempting reconnect in ${e}ms`),setTimeout(()=>this.connect(),e)}closeAndReconnect(e){switch(this._logVerbose(`begin closeAndReconnect with reason ${e}`),this.socket.state){case"disconnected":case"terminated":case"stopped":return;case"connecting":case"ready":this.lastCloseReason=e,this.close(),this.scheduleReconnect();return;default:this.socket}}close(){switch(this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{let e=this.socket.ws;return new Promise(t=>{e.onclose=()=>{this._logVerbose("Closed after connecting"),t()},e.onopen=()=>{this._logVerbose("Opened after connecting"),e.close()}})}case"ready":{this._logVerbose("ws.close called");let e=this.socket.ws,t=new Promise(t=>{e.onclose=()=>{t()}});return e.close(),t}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.socket.state){case"terminated":case"stopped":case"disconnected":case"connecting":case"ready":{let e=this.close();return this.setSocketState({state:"terminated"}),e}default:throw this.socket,Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case"terminated":return Promise.resolve();case"connecting":case"stopped":case"disconnected":case"ready":{let e=this.close();return this.socket={state:"stopped"},e}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case"stopped":break;case"terminated":case"connecting":case"ready":case"disconnected":this.logger.logVerbose("Restart called without stopping first");return;default:this.socket}this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":this.socket={...this.socket,paused:"yes"};return;default:return void this.socket}}resume(){switch(this.socket.state){case"connecting":this.socket={...this.socket,paused:"no"};return;case"ready":"uninitialized"===this.socket.paused?(this.socket={...this.socket,paused:"no"},this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason})):"yes"===this.socket.paused&&(this.socket={...this.socket,paused:"no"},this.onResume());return;case"terminated":case"stopped":case"disconnected":return;default:this.socket}this.connect()}connectionState(){return{isConnected:"ready"===this.socket.state,hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(){let e=this.initialBackoff*Math.pow(2,this.retries);this.retries+=1;let t=Math.min(e,this.maxBackoff),s=t*(Math.random()-.5);return t+s}}
1class D extends Error{}D.prototype.name="InvalidTokenError";var J=Object.defineProperty,z=(e,t,s)=>t in e?J(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,U=(e,t,s)=>z(e,"symbol"!=typeof t?t+"":t,s);class W{constructor(e,t,s){U(this,"authState",{state:"noAuth"}),U(this,"configVersion",0),U(this,"syncState"),U(this,"authenticate"),U(this,"stopSocket"),U(this,"tryRestartSocket"),U(this,"pauseSocket"),U(this,"resumeSocket"),U(this,"clearAuth"),U(this,"logger"),U(this,"refreshTokenLeewaySeconds"),U(this,"tokenConfirmationAttempts",0),this.syncState=e,this.authenticate=t.authenticate,this.stopSocket=t.stopSocket,this.tryRestartSocket=t.tryRestartSocket,this.pauseSocket=t.pauseSocket,this.resumeSocket=t.resumeSocket,this.clearAuth=t.clearAuth,this.logger=s.logger,this.refreshTokenLeewaySeconds=s.refreshTokenLeewaySeconds}async setConfig(e,t){this.resetAuthState(),this._logVerbose("pausing WS for auth token fetch"),this.pauseSocket();let s=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});s.isFromOutdatedConfig||(s.value?(this.setAuthState({state:"waitingForServerConfirmationOfCachedToken",config:{fetchToken:e,onAuthChange:t},hasRetried:!1}),this.authenticate(s.value)):(this.setAuthState({state:"initialRefetch",config:{fetchToken:e,onAuthChange:t}}),await this.refetchToken()),this._logVerbose("resuming WS after auth token fetch"),this.resumeSocket())}onTransition(e){if(this.syncState.isCurrentOrNewerAuthVersion(e.endVersion.identity)&&!(e.endVersion.identity<=e.startVersion.identity)){if("waitingForServerConfirmationOfCachedToken"===this.authState.state){this._logVerbose("server confirmed auth token is valid"),this.refetchToken(),this.authState.config.onAuthChange(!0);return}"waitingForServerConfirmationOfFreshToken"===this.authState.state&&(this._logVerbose("server confirmed new auth token is valid"),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(!1===e.authUpdateAttempted&&("waitingForServerConfirmationOfFreshToken"===this.authState.state||"waitingForServerConfirmationOfCachedToken"===this.authState.state))return void this._logVerbose("ignoring non-auth token expired error");let{baseVersion:t}=e;if(!this.syncState.isCurrentOrNewerAuthVersion(t+1))return void this._logVerbose("ignoring auth error for previous auth attempt");this.tryToReauthenticate(e)}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),"noAuth"===this.authState.state||"waitingForServerConfirmationOfFreshToken"===this.authState.state&&this.tokenConfirmationAttempts>=2){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),"noAuth"!==this.authState.state&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}"waitingForServerConfirmationOfFreshToken"===this.authState.state&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${2-this.tokenConfirmationAttempts} attempts remaining`)),await this.stopSocket();let t=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});t.isFromOutdatedConfig||(t.value&&this.syncState.isNewAuth(t.value)?(this.authenticate(t.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:t.value,hadAuth:"notRefetching"===this.authState.state||"waitingForScheduledRefetch"===this.authState.state})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if("noAuth"===this.authState.state)return;this._logVerbose("refetching auth token");let e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(e){if("noAuth"===this.authState.state)return;let t=this.decodeToken(e);if(!t)return void this.logger.error("Auth token is not a valid JWT, cannot refetch the token");let{iat:s,exp:i}=t;if(!s||!i)return void this.logger.error("Auth token does not have required fields, cannot refetch the token");let r=i-s;if(r<=2)return void this.logger.error("Auth token does not live long enough, cannot refetch the token");let n=Math.min(1728e6,(r-this.refreshTokenLeewaySeconds)*1e3);n<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${r}s`),n=0);let o=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},n);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:o,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${n}ms`)}async fetchTokenAndGuardAgainstRace(e,t){let s=++this.configVersion;this._logVerbose(`fetching token with config version ${s}`);let i=await e(t);
1return this.configVersion!==s?(this._logVerbose(`stale config version, expected ${s}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:i}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.setAuthState({state:"noAuth"})}setAuthState(e){let t="waitingForServerConfirmationOfFreshToken"===e.state?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(t)}`),e.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0}"waitingForScheduledRefetch"===this.authState.state&&(clearTimeout(this.authState.refetchTokenTimeoutId),this.syncState.markAuthCompletion()),this.authState=e}decodeToken(e){try{return function(e,t){let s;if("string"!=typeof e)throw new D("Invalid token specified: must be a string");t||(t={});let i=+(!0!==t.header),r=e.split(".")[i];if("string"!=typeof r)throw new D(`Invalid token specified: missing part #${i+1}`);try{s=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw Error("base64 string is not of the correct length")}try{var s;return s=t,decodeURIComponent(atob(s).replace(/(.)/g,(e,t)=>{let s=t.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}catch(e){return atob(t)}}(r)}catch(e){throw new D(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(s)}catch(e){throw new D(`Invalid token specified: invalid json for part #${i+1} (${e.message})`)}}(e)}catch(e){return this._logVerbose(`Error decoding token: ${e instanceof Error?e.message:"Unknown error"}`),null}}_logVerbose(e){this.logger.logVerbose(`${e} [v${this.configVersion}]`)}}let B=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function K(e){let t=e.name.slice(6);return{name:t=t.charAt(0).toLowerCase()+t.slice(1),startTime:e.startTime}}var Z=Object.defineProperty,Y=(e,t,s)=>t in e?Z(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,G=(e,t,s)=>Y(e,"symbol"!=typeof t?t+"":t,s);class H{constructor(e,t,s){let i;if(G(this,"address"),G(this,"state"),G(this,"requestManager"),G(this,"webSocketManager"),G(this,"authenticationManager"),G(this,"remoteQuerySet"),G(this,"optimisticQueryResults"),G(this,"_transitionHandlerCounter",0),G(this,"_nextRequestId"),G(this,"_onTransitionFns",new Map),G(this,"_sessionId"),G(this,"firstMessageReceived",!1),G(this,"debug"),G(this,"logger"),G(this,"maxObservedTimestamp"),G(this,"mark",e=>{var t;this.debug&&(t=this.sessionId,"undefined"!=typeof performance&&performance.mark&&performance.mark(e,{detail:{sessionId:t}}))}),"object"==typeof e)throw Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");s?.skipConvexDeploymentUrlCheck!==!0&&(0,v.R6)(e);let n=(s={...s}).authRefreshTokenLeewaySeconds??2,a=s.webSocketConstructor;if(!a&&"undefined"==typeof WebSocket)throw Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");a=a||WebSocket,this.debug=s.reportDebugInfoToConvex??!1,this.address=e,this.logger=s.logger??(0,o.y4)({verbose:s.verbose??!1});let u=e.search("://");if(-1===u)throw Error("Provided address was not an absolute URL.");let h=e.substring(u+3),c=e.substring(0,u);if("http"===c)i="ws";else if("https"===c)i="wss";else throw Error(`Unknown parent protocol ${c}`);let l=`${i}://${h}/api/${r.r}/sync`;this.state=new d,this.remoteQuerySet=new _(e=>this.state.queryPath(e),this.logger),this.requestManager=new p(this.logger),this.authenticationManager=new W(this.state,{authenticate:e=>{let t=this.state.setAuth(e);return this.webSocketManager.sendMessage(t),t.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:()=>{this.webSocketManager.pause(),this.state.pause()},resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:n}),this.optimisticQueryResults=new C,this.addOnTransitionHandler(e=>{t(e.queries.map(e=>e.token))}),this._nextRequestId=0,this._sessionId="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)});let{unsavedChangesWarning:f}=s;if("undefined"==typeof window||void 0===window.addEventListener){if(!0===f)throw Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else!1!==f&&window.addEventListener("beforeunload",e=>{if(this.requestManager.hasIncompleteRequests()){e.preventDefault();let t="Are you sure you want to leave? Your changes may not be saved.";return(e||window.event).returnValue=t,t}});this.webSocketManager=new F(l,{onOpen:e=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...e,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp});let t=new Set(this.remoteQuerySet.remoteQueryResults().keys());this.remoteQuerySet=new _(e=>this.state.queryPath(e),this.logger);let[s,i]=this.state.restart(t);for(let e of(i&&this.webSocketManager.sendMessage(i),this.webSocketManager.sendMessage(s),this.requestManager.restart()))this.webSocketManager.sendMessage(e)},onResume:()=>{let[e,t]=this.state.resume();for(let s of(t&&this.webSocketManager.sendMessage(t),e&&this.webSocketManager.sendMessage(e),this.requestManager.resume()))this.webSocketManager.sendMessage(s)},onMessage:e=>{switch(!this.firstMessageReceived&&(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMar
1ks()),e.type){case"Transition":{this.observedTimestamp(e.endVersion.ts),this.authenticationManager.onTransition(e),this.remoteQuerySet.transition(e),this.state.transition(e);let t=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(t);break}case"MutationResponse":{e.success&&this.observedTimestamp(e.ts);let t=this.requestManager.onResponse(e);null!==t&&this.notifyOnQueryResultChanges(new Map([[t.requestId,t.result]]));break}case"ActionResponse":this.requestManager.onResponse(e);break;case"AuthError":this.authenticationManager.onAuthError(e);break;case"FatalError":{let t=(0,o.Z4)(this.logger,e.error);throw this.webSocketManager.terminate(),t}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}}},a,this.logger),this.mark("convexClientConstructed")}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()||this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(void 0===this.maxObservedTimestamp||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){let t=this.remoteQuerySet.remoteQueryResults(),s=new Map;for(let[e,i]of t){let t=this.state.queryToken(e);if(null!==t){let r={result:i,udfPath:this.state.queryPath(e),args:this.state.queryArgs(e)};s.set(t,r)}}let i=this.optimisticQueryResults.ingestQueryResultsFromServer(s,new Set(e.keys()));this.handleTransition({queries:i.map(e=>({token:e,modification:{kind:"Updated",result:s.get(e).result}})),reflectedMutations:Array.from(e).map(([e,t])=>({requestId:e,result:t})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(let t of this._onTransitionFns.values())t(e)}addOnTransitionHandler(e){let t=this._transitionHandlerCounter++;return this._onTransitionFns.set(t,e),()=>this._onTransitionFns.delete(t)}setAuth(e,t){this.authenticationManager.setConfig(e,t)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,t){let s=this.state.setAdminAuth(e,t);this.webSocketManager.sendMessage(s)}clearAuth(){let e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,t,s){let i=(0,v.Zy)(t),{modification:r,queryToken:n,unsubscribe:o}=this.state.subscribe(e,i,s?.journal,s?.componentPath);return null!==r&&this.webSocketManager.sendMessage(r),{queryToken:n,unsubscribe:()=>{let e=o();e&&this.webSocketManager.sendMessage(e)}}}localQueryResult(e,t){let s=u(e,(0,v.Zy)(t));return this.optimisticQueryResults.queryResult(s)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,t){let s=u(e,(0,v.Zy)(t));return this.optimisticQueryResults.queryLogs(s)}queryJournal(e,t){let s=u(e,(0,v.Zy)(t));return this.state.queryJournal(s)}connectionState(){let e=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:e.isConnected,hasEverConnected:e.hasEverConnected,connectionCount:e.connectionCount,connectionRetries:e.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}async mutation(e,t,s){let i=await this.mutationInternal(e,t,s);if(!i.success){if(void 0!==i.errorData)throw(0,o.sA)(i,new b.i((0,o.i7)("mutation",e,i)));throw Error((0,o.i7)("mutation",e,i))}return i.value}async mutationInternal(e,t,s,i){let{mutationPromise:r}=this.enqueueMutation(e,t,s,i);return r}enqueueMutation(e,t,s,i){let r=(0,v.Zy)(t);this.tryReportLongDisconnect();let o=this.nextRequestId;if(this._nextRequestId++,void 0!==s){let e=s.optimisticUpdate;if(void 0!==e){let t=this.optimisticQueryResults.applyOptimisticUpdate(t=>{e(t,r)},o).map(e=>{let t=this.localQueryResultByToken(e);return{token:e,modification:{kind:"Updated",result:void 0===t?void 0:{success:!0,value:t,logLines:[]}}}});this.handleTransition({queries:t,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let a={type:"Mutation",requestId:o,udfPath:e,componentPath:i,args:[(0,n.rz)(r)]},u=this.webSocketManager.sendMessage(a);return{requestId:o,mutationPromise:this.requestManager.request(a,u)}}async action(e,t){let s=await this.actionInternal(e,t);if(!s.success){if(void 0!==s.errorData)throw(0,o.sA)(s,new b.i((0,o.i7)("action",e,s)));throw Error((0,o.i7)("action",e,s))}return s.value}async actionInternal(e,t,s){let i=(0,v.Zy)(t),r=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let o={type:"Action",requestId:r,udfPath:e,componentPath:s,args:[(0,n.rz)(i)]},a=this.webSocketManager.sendMessage(o);return this.requestManager.request(o,a)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}
1reportMarks(){if(this.debug){let e=function(e){if("undefined"==typeof performance||!performance.getEntriesByName)return[];let t=[];for(let s of B){let i=performance.getEntriesByName(s).filter(e=>"mark"===e.entryType).filter(t=>t.detail.sessionId===e);t.push(...i)}return t.map(K)}(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:e})}}tryReportLongDisconnect(){if(!this.debug)return;let e=this.connectionState().timeOfOldestInflightRequest;null===e||Date.now()-e.getTime()<=6e4||fetch(`${this.address}/api/debug_event`,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${r.r}`},body:JSON.stringify({event:"LongWebsocketDisconnect"})}).then(e=>{e.ok||this.logger.warn("Analytics request failed with response:",e.body)}).catch(e=>{this.logger.warn("Analytics response failed with error:",e)})}}var X=Object.defineProperty,ee=Object.defineProperty,et=(e,t,s)=>t in e?ee(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,es=(e,t,s)=>et(e,"symbol"!=typeof t?t+"":t,s);class ei{constructor(e,t){if(es(this,"address"),es(this,"auth"),es(this,"adminAuth"),es(this,"encodedTsPromise"),es(this,"debug"),es(this,"fetchOptions"),es(this,"logger"),"boolean"==typeof t)throw Error("skipConvexDeploymentUrlCheck as the second argument is no longer supported. Please pass an options object, `{ skipConvexDeploymentUrlCheck: true }`.");let s=t??{};!0!==s.skipConvexDeploymentUrlCheck&&(0,v.R6)(e),this.logger=s.logger??(0,o.y4)({verbose:!1}),this.address=e,this.debug=!0}backendUrl(){return`${this.address}/api`}get url(){return this.address}setAuth(e){this.clearAuth(),this.auth=e}setAdminAuth(e,t){if(this.clearAuth(),void 0!==t){let s=btoa(String.fromCodePoint(...new TextEncoder().encode(JSON.stringify(t))));this.adminAuth=`${e}:${s}`}else this.adminAuth=e}clearAuth(){this.auth=void 0,this.adminAuth=void 0}setDebug(e){this.debug=e}setFetchOptions(e){this.fetchOptions=e}async consistentQuery(e,...t){let s=(0,v.Zy)(t[0]),i=this.getTimestamp();return await this.queryInner(e,s,{timestampPromise:i})}async getTimestamp(){return this.encodedTsPromise?this.encodedTsPromise:this.encodedTsPromise=this.getTimestampInner()}async getTimestampInner(){let e=i||fetch,t={"Content-Type":"application/json","Convex-Client":`npm-${r.r}`},s=await e(`${this.address}/api/query_ts`,{...this.fetchOptions,method:"POST",headers:t});if(!s.ok)throw Error(await s.text());let{ts:n}=await s.json();return n}async query(e,...t){let s=(0,v.Zy)(t[0]);return await this.queryInner(e,s,{})}async queryInner(e,t,s){let a=(0,m.qQ)(e),u=[(0,n.rz)(t)],h={"Content-Type":"application/json","Convex-Client":`npm-${r.r}`};this.adminAuth?h.Authorization=`Convex ${this.adminAuth}`:this.auth&&(h.Authorization=`Bearer ${this.auth}`);let c=i||fetch,l=s.timestampPromise?await s.timestampPromise:void 0,d=JSON.stringify({path:a,format:"convex_encoded_json",args:u,...l?{ts:l}:{}}),f=l?`${this.address}/api/query_at_ts`:`${this.address}/api/query`,g=await c(f,{...this.fetchOptions,body:d,method:"POST",headers:h});if(!g.ok&&560!==g.status)throw Error(await g.text());let y=await g.json();if(this.debug)for(let e of y.logLines??[])(0,o.Y7)(this.logger,"info","query",a,e);switch(y.status){case"success":return(0,n.du)(y.value);case"error":if(void 0!==y.errorData)throw er(y.errorData,new n.ik(y.errorMessage));throw Error(y.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(y)}`)}}async mutation(e,...t){let s=(0,v.Zy)(t[0]),a=(0,m.qQ)(e),u=JSON.stringify({path:a,format:"convex_encoded_json",args:[(0,n.rz)(s)]}),h={"Content-Type":"application/json","Convex-Client":`npm-${r.r}`};this.adminAuth?h.Authorization=`Convex ${this.adminAuth}`:this.auth&&(h.Authorization=`Bearer ${this.auth}`);let c=i||fetch,l=await c(`${this.address}/api/mutation`,{...this.fetchOptions,body:u,method:"POST",headers:h});if(!l.ok&&560!==l.status)throw Error(await l.text());let d=await l.json();if(this.debug)for(let e of d.logLines??[])(0,o.Y7)(this.logger,"info","mutation",a,e);switch(d.status){case"success":return(0,n.du)(d.value);case"error":if(void 0!==d.errorData)throw er(d.errorData,new n.ik(d.errorMessage));throw Error(d.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(d)}`)}}async action(e,...t){let s=(0,v.Zy)(t[0]),a=(0,m.qQ)(e),u=JSON.stringify({path:a,format:"convex_encoded_json",args:[(0,n.rz)(s)]}),h={"Content-Type":"application/json","Convex-Client":`npm-${r.r}`};this.adminAuth?h.Authorization=`Convex ${this.adminAuth}`:this.auth&&(h.Authorization=`Bearer ${this.auth}`);let c=i||fetch,l=await c(`${this.address}/api/action`,{...this.fetchOptions,body:u,method:"POST",headers:h});if(!l.ok&&560!==l.status)throw Error(await l.text());let d=await l.json();if(this.debug)for(let e of d.logLines??[])(0,o.Y7)(this.logger,"info","action",a,e);switch(d.status){case"success":return(0,n.du)(d.value);case"error":if(void 0!==d.errorData)throw er(d.errorData,new n.ik(d.errorMessage));throw Error(d.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(d)}`)}}async function(e,t,...s){let a=(0,v.Zy)(s[0]),u="string"==typeof e?e:(0,m.qQ)(e),h=JSON.stringify({componentPath:t,path:u,format:"convex_encoded_json",args:(0,n.rz)(a)}),c={"Content-Type":"application/json","Convex-Client":`npm-${r.r}`};this.adminAuth?c.Authorization=`Convex ${this.adminAuth}`:this.auth&&(c.Authorization=`Bearer ${this.auth}`);let l=i||fetch,d=await l(`${this.address}/api/function`,{...this.fetchOptions,body:h,method:"POST",headers:c});if(!d.ok&&560!==d.status)throw Error(await d.text());let f=await d.json();if(this.debug)for(let e of f.logLines??[])(0,o.Y7)(this.logger,"info","any",u,e);switch(f.status){case"success":return(0,n.du)(f.value);case"error":if(void 0!==f.errorData)throw er(f.errorData,new n.ik(f.errorMessage));throw Error(f.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(f)}`)}}}function er(e,t){return t.data=(0,n.du)(e),t}},23411:(e,t,s)=>{s.d(t,{r:()=>i});let i="1.23.0"},33757:(e,t,s)=>{s.d(t,{Gg:()=>o,dp:()=>a,qQ:()=>n});var i=s(88764),r=s(73016);function n(e){let t=(0,r.Jc)(e);if(void 0===t.name){if(void 0!==t.functionHandle)throw Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${t.functionHandle}`);if(void 0!==t.reference)throw Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${t.reference}`);throw Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(t)}`)}if("string"==typeof e)return e;let s=e[i.A];if(!s)throw Error(`${e} is not a functionReference`);return s}function o(e){return{[i.A]:e}}let a=function e(t=[]){return new Proxy({},{get(s,r){if("string"==typeof r)return e([...t,r]);if(r===i.A){if(t.length<2){let e=["api",...t].join(".");throw Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${e}\``)}let e=t.slice(0,-1).join("/"),s=t[t.length-1];return"default"===s?e:e+":"+s}return r===Symbol.toStringTag?"FunctionReference":void 0}})}()},72457:(e,t,s)=>{s.d(t,{Y7:()=>h,Z4:()=>c,i7:()=>l,sA:()=>d,y4:()=>u});var i=Object.defineProperty,r=(e,t,s)=>t in e?i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,n=(e,t,s)=>r(e,"symbol"!=typeof t?t+"":t,s);function o(e){switch(e){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class a{constructor(e){n(this,"_onLogLineFuncs"),n(this,"_verbose"),this._onLogLineFuncs={},this._verbose=e.verbose}addLogLineListener(e){let t=Math.random().toString(36).substring(2,15);for(let e=0;e<10&&void 0!==this._onLogLineFuncs[t];e++)t=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[t]=e,()=>{delete this._onLogLineFuncs[t]}}logVerbose(...e){if(this._verbose)for(let t of Object.values(this._onLogLineFuncs))t("debug",`${new Date().toISOString()}`,...e)}log(...e){for(let t of Object.values(this._onLogLineFuncs))t("info",...e)}warn(...e){for(let t of Object.values(this._onLogLineFuncs))t("warn",...e)}error(...e){for(let t of Object.values(this._onLogLineFuncs))t("error",...e)}}function u(e){let t=new a(e);return t.addLogLineListener((e,...t)=>{switch(e){case"debug":console.debug(...t);break;case"info":default:console.log(...t);break;case"warn":console.warn(...t);break;case"error":console.error(...t)}}),t}function h(e,t,s,i,r){let n=o(s);if("object"==typeof r&&(r=`ConvexError ${JSON.stringify(r.errorData,null,2)}`),"info"===t){let t=r.match(/^\[.*?\] /);if(null===t)return void e.error(`[CONVEX ${n}(${i})] Could not parse console.log`);let s=r.slice(1,t[0].length-2),o=r.slice(t[0].length);e.log(`%c[CONVEX ${n}(${i})] [${s}]`,"color:rgb(0, 145, 255)",o)}else e.error(`[CONVEX ${n}(${i})] ${r}`)}function c(e,t){let s=`[CONVEX FATAL ERROR] ${t}`;return e.error(s),Error(s)}function l(e,t,s){let i=o(e);return`[CONVEX ${i}(${t})] ${s.errorMessage} 2 Called by client`}function d(e,t){return t.data=e.errorData,t}},73016:(e,t,s)=>{s.d(t,{Jc:()=>n});var i=s(88764);let r=Symbol.for("toReferencePath");function n(e){let t;if("string"==typeof e)t=e.startsWith("function://")?{functionHandle:e}:{name:e};else if(e[i.A])t={name:e[i.A]};else{let s=e[r]??null;if(!s)throw Error(`${e} is not a functionReference`);t={reference:s}}return t}},83647:(e,t,s)=>{s.d(t,{dp:()=>ei.dp,qQ:()=>ei.qQ});var i=s(93968),r=s(76711),n=s(56241);function o(e,t){if("undefined"==typeof Convex||void 0===Convex.syscall)throw Error("The Convex database and auth objects are being used outside of a Convex backend. Did you mean to use `useQuery` or `useMutation` to call a Convex function?");return JSON.parse(Convex.syscall(e,JSON.stringify(t)))}async function a(e,t){let s;if("undefined"==typeof Convex||void 0===Convex.asyncSyscall)throw Error("The Convex database and auth objects are being used outside of a Convex backend. Did you mean to use `useQuery` or `useMutation` to call a Convex function?");try{s=await Convex.asyncSyscall(e,JSON.stringify(t))}catch(e){if(void 0!==e.data){let t=new r.i(e.message);throw t.data=(0,n.du)(e.data),t}throw Error(e.message)}return JSON.parse(s)}s(73016);var u=Object.defineProperty,h=(e,t,s)=>t in e?u(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,c=(e,t,s)=>h(e,"symbol"!=typeof t?t+"":t,s);class l{constructor(){c(this,"_isExpression"),c(this,"_value")}}var d=Object.defineProperty,f=(e,t,s)=>t in e?d(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,g=(e,t,s)=>f(e,"symbol"!=typeof t?t+"":t,s);class y extends l{constructor(e){super(),g(this,"inner"),this.inner=e}serialize(){return this.inner}}function p(e){return e instanceof y?e.serialize():{$literal:(0,n.cy)(e)}}let m={eq(e,t){if("string"!=typeof e)throw Error("The first argument to `q.eq` must be a field name.");return new y({$eq:[p(new y({$field:e})),p(t)]})},or:(...e)=>new y({$or:e.map(p)})};var v=Object.defineProperty,b=(e,t,s)=>t in e?v(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,w=(e,t,s)=>b(e,"symbol"!=typeof t?t+"":t,s);class S{constructor(){w(this,"_isExpression"),w(this,"_value")}}var k=Object.defineProperty,q=(e,t,s)=>t in e?k(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,C=(e,t,s)=>q(e,"symbol"!=typeof t?t+"":t,s);class R extends S{constructor(e){super(),C(this,"inner"),this.inner=e}serialize(){return this.inner}}function x(e){return e instanceof R?e.serialize():{$literal:(0,n.cy)(e)}}let A={eq:(e,t)=>
2new R({$eq:[x(e),x(t)]}),neq:(e,t)=>new R({$neq:[x(e),x(t)]}),lt:(e,t)=>new R({$lt:[x(e),x(t)]}),lte:(e,t)=>new R({$lte:[x(e),x(t)]}),gt:(e,t)=>new R({$gt:[x(e),x(t)]}),gte:(e,t)=>new R({$gte:[x(e),x(t)]}),add:(e,t)=>new R({$add:[x(e),x(t)]}),sub:(e,t)=>new R({$sub:[x(e),x(t)]}),mul:(e,t)=>new R({$mul:[x(e),x(t)]}),div:(e,t)=>new R({$div:[x(e),x(t)]}),mod:(e,t)=>new R({$mod:[x(e),x(t)]}),neg:e=>new R({$neg:x(e)}),and:(...e)=>new R({$and:e.map(x)}),or:(...e)=>new R({$or:e.map(x)}),not:e=>new R({$not:x(e)}),field:e=>new R({$field:e})};var T=Object.defineProperty,O=(e,t,s)=>t in e?T(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,M=(e,t,s)=>O(e,"symbol"!=typeof t?t+"":t,s);class E{constructor(){M(this,"_isIndexRange")}}var I=Object.defineProperty,Q=(e,t,s)=>t in e?I(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,$=(e,t,s)=>Q(e,"symbol"!=typeof t?t+"":t,s);class P extends E{constructor(e){super(),$(this,"rangeExpressions"),$(this,"isConsumed"),this.rangeExpressions=e,this.isConsumed=!1}static new(){return new P([])}consume(){if(this.isConsumed)throw Error("IndexRangeBuilder has already been used! Chain your method calls like `q => q.eq(...).eq(...)`. See https://docs.convex.dev/using/indexes");this.isConsumed=!0}eq(e,t){return this.consume(),new P(this.rangeExpressions.concat({type:"Eq",fieldPath:e,value:(0,n.cy)(t)}))}gt(e,t){return this.consume(),new P(this.rangeExpressions.concat({type:"Gt",fieldPath:e,value:(0,i.rz)(t)}))}gte(e,t){return this.consume(),new P(this.rangeExpressions.concat({type:"Gte",fieldPath:e,value:(0,i.rz)(t)}))}lt(e,t){return this.consume(),new P(this.rangeExpressions.concat({type:"Lt",fieldPath:e,value:(0,i.rz)(t)}))}lte(e,t){return this.consume(),new P(this.rangeExpressions.concat({type:"Lte",fieldPath:e,value:(0,i.rz)(t)}))}export(){return this.consume(),this.rangeExpressions}}var _=Object.defineProperty,V=(e,t,s)=>t in e?_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,L=(e,t,s)=>V(e,"symbol"!=typeof t?t+"":t,s);class j{constructor(){L(this,"_isSearchFilter")}}function N(e,t,s,i){if(void 0===e)throw TypeError(`Must provide arg ${t} \`${i}\` to \`${s}\``)}var F=Object.defineProperty,D=(e,t,s)=>t in e?F(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,J=(e,t,s)=>D(e,"symbol"!=typeof t?t+"":t,s);class z extends j{constructor(e){super(),J(this,"filters"),J(this,"isConsumed"),this.filters=e,this.isConsumed=!1}static new(){return new z([])}consume(){if(this.isConsumed)throw Error("SearchFilterBuilder has already been used! Chain your method calls like `q => q.search(...).eq(...)`.");this.isConsumed=!0}search(e,t){return N(e,1,"search","fieldName"),N(t,2,"search","query"),this.consume(),new z(this.filters.concat({type:"Search",fieldPath:e,value:t}))}eq(e,t){return N(e,1,"eq","fieldName"),2!=arguments.length&&N(t,2,"search","value"),this.consume(),new z(this.filters.concat({type:"Eq",fieldPath:e,value:(0,n.cy)(t)}))}export(){return this.consume(),this.filters}}var U=s(23411),W=Object.defineProperty,B=(e,t,s)=>t in e?W(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,K=(e,t,s)=>B(e,"symbol"!=typeof t?t+"":t,s);function Z(e){throw Error("consumed"===e?"This query is closed and can't emit any more values.":"This query has been chained with another operator and can't be reused.")}Symbol.asyncIterator;class Y{constructor(e){K(this,"state"),this.state={type:"preparing",query:e}}takeQuery(){if("preparing"!==this.state.type)throw Error("A query can only be chained once and can't be chained after iteration begins.");let e=this.state.query;return this.state={type:"closed"},e}startQuery(){if("executing"===this.state.type)throw Error("Iteration can only begin on a query once.");("closed"===this.state.type||"consumed"===this.state.type)&&Z(this.state.type);let{queryId:e}=o("1.0/queryStream",{query:this.state.query,version:U.r});return this.state={type:"executing",queryId:e},e}closeQuery(){"executing"===this.state.type&&o("1.0/queryCleanup",{queryId:this.state.queryId}),this.state={type:"consumed"}}order(e){N(e,1,"order","order");let t=this.takeQuery();
2if("Search"===t.source.type)throw Error("Search queries must always be in relevance order. Can not set order manually.");if(null!==t.source.order)throw Error("Queries may only specify order at most once");return t.source.order=e,new Y(t)}filter(e){N(e,1,"filter","predicate");let t=this.takeQuery();return t.operators.push({filter:x(e(A))}),new Y(t)}limit(e){N(e,1,"limit","n");let t=this.takeQuery();return t.operators.push({limit:e}),new Y(t)}[Symbol.asyncIterator](){return this.startQuery(),this}async next(){("closed"===this.state.type||"consumed"===this.state.type)&&Z(this.state.type);let e="preparing"===this.state.type?this.startQuery():this.state.queryId,{value:t,done:s}=await a("1.0/queryStreamNext",{queryId:e});return s&&this.closeQuery(),{value:(0,i.du)(t),done:s}}return(){return this.closeQuery(),Promise.resolve({done:!0,value:void 0})}async paginate(e){if(N(e,1,"paginate","options"),"number"!=typeof e?.numItems||e.numItems<0)throw Error(`\`options.numItems\` must be a positive number. Received \`${e?.numItems}\`.`);let t=this.takeQuery(),s=e.numItems,r=e.cursor,n=e?.endCursor??null,o=e.maximumRowsRead??null,{page:u,isDone:h,continueCursor:c,splitCursor:l,pageStatus:d}=await a("1.0/queryPage",{query:t,cursor:r,endCursor:n,pageSize:s,maximumRowsRead:o,maximumBytesRead:e.maximumBytesRead,version:U.r});return{page:u.map(e=>(0,i.du)(e)),isDone:h,continueCursor:c,splitCursor:l,pageStatus:d}}async collect(){let e=[];for await(let t of this)e.push(t);return e}async take(e){N(e,1,"take","n");if(!Number.isInteger(e)||e<0)throw TypeError("Arg 1 `n` to `take` must be a non-negative integer");return this.limit(e).collect()}async first(){let e=await this.take(1);return 0===e.length?null:e[0]}async unique(){let e=await this.take(2);if(0===e.length)return null;if(2===e.length)throw Error(`unique() query returned more than one result: 3 [${e[0]._id}, ${e[1]._id}, ...]`);return e[0]}}async function G(e,t){if(validateArg(e,1,"get","id"),"string"!=typeof e)throw Error(`Invalid argument \`id\` for \`db.get\`, expected string but got '${typeof e}': ${e}`);let s={id:convexToJson(e),isSystem:t,version};return jsonToConvex(await performAsyncSyscall("1.0/get",s))}async function H(e,t){if(e.startsWith("_"))throw Error("System tables (prefixed with `_`) are read-only.");return validateArg(e,1,"insert","table"),validateArg(t,2,"insert","value"),jsonToConvex(await performAsyncSyscall("1.0/insert",{table:e,value:convexToJson(t)}))._id}async function X(e,t){validateArg(e,1,"patch","id"),validateArg(t,2,"patch","value"),await performAsyncSyscall("1.0/shallowMerge",{id:convexToJson(e),value:patchValueToJson(t)})}async function ee(e,t){validateArg(e,1,"replace","id"),validateArg(t,2,"replace","value"),await performAsyncSyscall("1.0/replace",{id:convexToJson(e),value:convexToJson(t)})}async function et(e){validateArg(e,1,"delete","id"),await performAsyncSyscall("1.0/remove",{id:convexToJson(e)})}var es=s(96480);es.v.object({numItems:es.v.number(),cursor:es.v.union(es.v.string(),es.v.null()),endCursor:es.v.optional(es.v.union(es.v.string(),es.v.null())),id:es.v.optional(es.v.number()),maximumRowsRead:es.v.optional(es.v.number()),maximumBytesRead:es.v.optional(es.v.number())});var ei=s(33757),er=Object.defineProperty,en=Object.defineProperty,eo=Object.defineProperty,ea=(e,t,s)=>t in e?eo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,eu=(e,t,s)=>ea(e,"symbol"!=typeof t?t+"":t,s);class eh{constructor(e,t){eu(this,"_definition"),eu(this,"_name"),this._definition=e,this._name=t,setReferencePath(this,`_reference/childComponent/${t}`)}get exports(){return function e(t,s){return new Proxy({},{get(i,r){if("string"==typeof r)return e(t,[...s,r]);if(r===toReferencePath){let e=`_reference/childComponent/${t}`;for(let t of s)e+=`/${t}`;return e}}})}(this._name,[])}}function ec(e){let t=[];for(let[s,i]of Object.entries(e)){let e;e="string"==typeof i?{type:"leaf",leaf:i}:ec(i),t.push([s,e])}return{type:"branch",branch:t}}function el(e){return e.map(([e,t,s])=>{let i=null;if(null!==s)for(let[e,t]of(i=[],Object.entries(s)))void 0!==t&&i.push([e,{type:"value",value:JSON.stringify(convexToJson(t))}]);let r=t.componentDefinitionPath;
3if(!r)throw Error("no .componentPath for component definition "+JSON.stringify(t,null,2));return{name:e,path:r,args:i}})}var ed=Object.defineProperty,ef=(e,t,s)=>t in e?ed(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,eg=(e,t,s)=>ef(e,"symbol"!=typeof t?t+"":t,s);class ey{constructor(e){eg(this,"indexes"),eg(this,"searchIndexes"),eg(this,"vectorIndexes"),eg(this,"validator"),this.indexes=[],this.searchIndexes=[],this.vectorIndexes=[],this.validator=e}index(e,t){return this.indexes.push({indexDescriptor:e,fields:t}),this}searchIndex(e,t){return this.searchIndexes.push({indexDescriptor:e,searchField:t.searchField,filterFields:t.filterFields||[]}),this}vectorIndex(e,t){return this.vectorIndexes.push({indexDescriptor:e,vectorField:t.vectorField,dimensions:t.dimensions,filterFields:t.filterFields||[]}),this}self(){return this}export(){return{indexes:this.indexes,searchIndexes:this.searchIndexes,vectorIndexes:this.vectorIndexes,documentType:this.validator.json}}}function ep(e){return new ey((0,es.d)(e)?e:es.v.object(e))}class em{constructor(e,t){eg(this,"tables"),eg(this,"strictTableNameTypes"),eg(this,"schemaValidation"),this.tables=e,this.schemaValidation=t?.schemaValidation===void 0||t.schemaValidation}export(){return JSON.stringify({tables:Object.entries(this.tables).map(([e,t])=>{let{indexes:s,searchIndexes:i,vectorIndexes:r,documentType:n}=t.export();return{tableName:e,indexes:s,searchIndexes:i,vectorIndexes:r,documentType:n}}),schemaValidation:this.schemaValidation})}}new em({_scheduled_functions:ep({name:es.v.string(),args:es.v.array(es.v.any()),scheduledTime:es.v.float64(),completedTime:es.v.optional(es.v.float64()),state:es.v.union(es.v.object({kind:es.v.literal("pending")}),es.v.object({kind:es.v.literal("inProgress")}),es.v.object({kind:es.v.literal("success")}),es.v.object({kind:es.v.literal("failed"),error:es.v.string()}),es.v.object({kind:es.v.literal("canceled")}))}),_storage:ep({sha256:es.v.string(),size:es.v.float64(),contentType:es.v.optional(es.v.string())})},void 0)},88764:(e,t,s)=>{s.d(t,{A:()=>i});let i=Symbol.for("functionName")},99331:(e,t,s)=>{s.d(t,{Yz:()=>$,N2:()=>E,eH:()=>f,hE:()=>P,y3:()=>b,Z:()=>M,n_:()=>v,fz:()=>A,En:()=>C,IT:()=>m});var i=s(7620),r=s(93968),n=s(12436),o=s(97509),a=s(6431),u=s(33757),h=s(72457),c=Object.defineProperty,l=(e,t,s)=>t in e?c(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,d=(e,t,s)=>l(e,"symbol"!=typeof t?t+"":t,s);if(void 0===i)throw Error("Required dependency 'react' not found");if(void 0===o)throw Error("Required dependency 'react-dom' not found");class f{constructor(e,t){if(d(this,"address"),d(this,"cachedSync"),d(this,"listeners"),d(this,"options"),d(this,"closed",!1),d(this,"_logger"),d(this,"adminAuth"),d(this,"fakeUserIdentity"),void 0===e)throw Error("No address provided to ConvexReactClient.\nIf trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\nIf running locally, make sure to run `convex dev` and ensure the .env.local file is populated.");if("string"!=typeof e)throw Error(`ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof e} instead.`);if(!e.includes("://"))throw Error("Provided address was not an absolute URL.");this.address=e,this.listeners=new Map,this._logger=t?.logger??(0,h.y4)({verbose:t?.verbose??!1}),this.options={...t,logger:this._logger}}get sync(){if(this.closed)throw Error("ConvexReactClient has already been closed.");return this.cachedSync||(this.cachedSync=new n.sd(this.address,e=>this.transition(e),this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity)),this.cachedSync}setAuth(e,t){if("string"==typeof e)throw Error("Passing a string to ConvexReactClient.setAuth is no longer supported, please upgrade to passing in an async function to handle reauthentication.");this.sync.setAuth(e,t??(()=>{}))}clearAuth(){this.sync.clearAuth()}setAdminAuth(e,t){if(this.adminAuth=e,this.fakeUserIdentity=t,this.closed)throw Error("ConvexReactClient has already been closed.");this.cachedSync&&this.sync.setAdminAuth(e,t)}watchQuery(e,...t){let[s,i]=t,r=(0,u.qQ)(e);return{onUpdate:e=>{let{queryToken:t,unsubscribe:n}=this.sync.subscribe(r,s,i),o=this.listeners.get(t);return void 0!==o?o.add(e):this.listeners.set(t,new Set([e])),()=>{if(this.closed)return;let s=this.listeners.get(t);s.delete(e),0===s.size&&this.listeners.delete(t),n()}},localQueryResult:()=>{if(this.cachedSync)return this.cachedSync.localQueryResult(r,s)},localQueryLogs:()=>
3{if(this.cachedSync)return this.cachedSync.localQueryLogs(r,s)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(r,s)}}}mutation(e,...t){let[s,i]=t,r=(0,u.qQ)(e);return this.sync.mutation(r,s,i)}action(e,...t){let s=(0,u.qQ)(e);return this.sync.action(s,...t)}query(e,...t){let s=this.watchQuery(e,...t),i=s.localQueryResult();return void 0!==i?Promise.resolve(i):new Promise((e,t)=>{let i=s.onUpdate(()=>{i();try{e(s.localQueryResult())}catch(e){t(e)}})})}connectionState(){return this.sync.connectionState()}get logger(){return this._logger}async close(){if(this.closed=!0,this.listeners=new Map,this.cachedSync){let e=this.cachedSync;this.cachedSync=void 0,await e.close()}}transition(e){o.unstable_batchedUpdates(()=>{for(let t of e){let e=this.listeners.get(t);if(e)for(let t of e)t()}})}}let g=i.createContext(void 0);function y(){return(0,i.useContext)(g)}let p=({client:e,children:t})=>i.createElement(g.Provider,{value:e},t);function m(e,...t){let s="skip"===t[0],n="skip"===t[0]?{}:(0,a.Zy)(t[0]),o="string"==typeof e?(0,u.Gg)(e):e,h=(0,u.qQ)(o),c=C((0,i.useMemo)(()=>s?{}:{query:{query:o,args:n}},[JSON.stringify((0,r.rz)(n)),h,s])).query;if(c instanceof Error)throw c;return c}function v(e){let t="string"==typeof e?(0,u.Gg)(e):e,s=(0,i.useContext)(g);if(void 0===s)throw Error("Could not find Convex client! `useMutation` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");return(0,i.useMemo)(()=>(function e(t,s,i){function r(e){return function(e){if("object"==typeof e&&null!==e&&"bubbles"in e&&"persist"in e&&"isDefaultPrevented"in e)throw Error("Convex function called with SyntheticEvent object. Did you use a Convex function as an event handler directly? Event handlers like onClick receive an event object as their first argument. These SyntheticEvent objects are not valid Convex values. Try wrapping the function like `const handler = () => myMutation();` and using `handler` in the event handler.")}(e),s.mutation(t,e,{optimisticUpdate:i})}return r.withOptimisticUpdate=function(r){if(void 0!==i)throw Error(`Already specified optimistic update for mutation ${(0,u.qQ)(t)}`);return e(t,s,r)},r})(t,s),[s,(0,u.qQ)(t)])}function b(e){let t=(0,i.useContext)(g),s="string"==typeof e?(0,u.Gg)(e):e;if(void 0===t)throw Error("Could not find Convex client! `useAction` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");return(0,i.useMemo)(()=>function(e){return t.action(s,e)},[t,(0,u.qQ)(s)])}var w=Object.defineProperty,S=(e,t,s)=>t in e?w(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,k=(e,t,s)=>S(e,"symbol"!=typeof t?t+"":t,s);class q{constructor(e){k(this,"createWatch"),k(this,"queries"),k(this,"listeners"),this.createWatch=e,this.queries={},this.listeners=new Set}setQueries(e){for(let t of Object.keys(e)){let{query:s,args:i}=e[t];if((0,u.qQ)(s),void 0===this.queries[t])this.addQuery(t,s,i);else{let e=this.queries[t];((0,u.qQ)(s)!==(0,u.qQ)(e.query)||JSON.stringify((0,r.rz)(i))!==JSON.stringify((0,r.rz)(e.args)))&&(this.removeQuery(t),this.addQuery(t,s,i))}}for(let t of Object.keys(this.queries))void 0===e[t]&&this.removeQuery(t)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getLocalResults(e){let t={};for(let s of Object.keys(e)){let i,{query:r,args:n}=e[s];(0,u.qQ)(r);let o=this.createWatch(r,n);try{i=o.localQueryResult()}catch(e){if(e instanceof Error)i=e;else throw e}t[s]=i}return t}setCreateWatch(e){for(let t of(this.createWatch=e,Object.keys(this.queries))){let{query:e,args:s,watch:i}=this.queries[t],r=i.journal();this.removeQuery(t),this.addQuery(t,e,s,r)}}destroy(){for(let e of Object.keys(this.queries))this.removeQuery(e);this.listeners=new Set}addQuery(e,t,s,i){if(void 0!==this.queries[e])throw Error(`Tried to add a new query with identifier ${e} when it already exists.`);let r=this.createWatch(t,s,i),n=r.onUpdate(()=>this.notifyListeners());this.queries[e]={query:t,args:s,watch:r,unsubscribe:n}}removeQuery(e){let t=this.queries[e];if(void 0===t)throw Error(`No query found with identifier ${e}.`);t.unsubscribe(),delete this.queries[e]}notifyListeners(){for(let e of this.listeners)e()}}function C(e){let t=y();if(void 0===t)throw Error("Could not find Convex client! `useQuery` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");var s=e,r=(0,i.useMemo)(()=>(e,s,i)=>t.watchQuery(e,s,{journal:i}),[t]);let[n]=(0,i.useState)(()=>new q(r));return n.createWatch!==r&&n.setCreateWatch(r),(0,i.useEffect)(()=>()=>n.destroy(),[n]),function({getCurrentValue:e,subscribe:t}){let[s,r]=(0,i.useState)(()=>({getCurrentValue:e,subscribe:t,value:e()})),n=s.value;return(s.getCurrentValue!==e||s.subscribe!==t)&&(n=e(),r({getCurrentValue:e,subscribe:t,value:n})),(0,i.useEffect)(()=>{let s=!1,i=()=>{s||r(s=>{if(s.getCurrentValue!==e||s.subscribe!==t)return s;let i=e();return s.value===i?s:{...s,value:i}})},n=t(i);return i(),()=>{s=!0,n()}},[e,t]),n}((0,i.useMemo)(()=>({getCurrentValue:()=>
3n.getLocalResults(s),subscribe:e=>(n.setQueries(s),n.subscribe(e))}),[n,s]))}let R=(e,t,s)=>i=>{let r={...i.queries},n=i.nextPageKey,o=i.nextPageKey+1,a=i.nextPageKey+2;r[n]={query:i.query,args:{...i.args,paginationOpts:{...i.queries[e].args.paginationOpts,endCursor:t}}},r[o]={query:i.query,args:{...i.args,paginationOpts:{...i.queries[e].args.paginationOpts,cursor:t,endCursor:s}}};let u={...i.ongoingSplits};return u[e]=[n,o],{...i,nextPageKey:a,queries:r,ongoingSplits:u}},x=e=>t=>{let s=t.ongoingSplits[e];if(void 0===s)return t;let i={...t.queries};delete i[e];let r={...t.ongoingSplits};delete r[e];let n=t.pageKeys.slice(),o=t.pageKeys.findIndex(t=>t===e);return o>=0&&(n=[...t.pageKeys.slice(0,o),...s,...t.pageKeys.slice(o+1)]),{...t,queries:i,pageKeys:n,ongoingSplits:r}};function A(e,t,s){if("number"!=typeof s?.initialNumItems||s.initialNumItems<0)throw Error(`\`options.initialNumItems\` must be a positive number. Received \`${s?.initialNumItems}\`.`);let n="skip"===t,o=n?{}:t,a=(0,u.qQ)(e),h=(0,i.useMemo)(()=>()=>{let t=++T;return{query:e,args:o,id:t,nextPageKey:1,pageKeys:n?[]:[0],queries:n?{}:{0:{query:e,args:{...o,paginationOpts:{numItems:s.initialNumItems,cursor:null,id:t}}}},ongoingSplits:{},skip:n}},[JSON.stringify((0,r.rz)(o)),a,s.initialNumItems,n]),[c,l]=(0,i.useState)(h),d=c;((0,u.qQ)(e)!==(0,u.qQ)(c.query)||JSON.stringify((0,r.rz)(o))!==JSON.stringify((0,r.rz)(c.args))||n!==c.skip)&&l(d=h());let f=y().logger,g=C(d.queries),[p,m]=(0,i.useMemo)(()=>{let e,t=[];for(let i of d.pageKeys){if(void 0===(e=g[i]))break;if(e instanceof Error)if(e.message.includes("InvalidCursor")||e instanceof r.ik&&"object"==typeof e.data&&e.data?.isConvexSystemError===!0&&e.data?.paginationError==="InvalidCursor")return f.warn("usePaginatedQuery hit error, resetting pagination state: "+e.message),l(h),[[],void 0];else throw e;let n=d.ongoingSplits[i];if(void 0!==n?void 0!==g[n[0]]&&void 0!==g[n[1]]&&l(x(i)):e.splitCursor&&("SplitRecommended"===e.pageStatus||"SplitRequired"===e.pageStatus||e.page.length>2*s.initialNumItems)&&l(R(i,e.splitCursor,e.continueCursor)),"SplitRequired"===e.pageStatus)return[t,void 0];t.push(...e.page)}return[t,e]},[g,d.pageKeys,d.ongoingSplits,s.initialNumItems,h,f]);return{results:p,...(0,i.useMemo)(()=>{if(void 0===m)if(1===d.nextPageKey)return{status:"LoadingFirstPage",isLoading:!0,loadMore:e=>{}};else return{status:"LoadingMore",isLoading:!0,loadMore:e=>{}};if(m.isDone)return{status:"Exhausted",isLoading:!1,loadMore:e=>{}};let e=m.continueCursor,t=!1;return{status:"CanLoadMore",isLoading:!1,loadMore:s=>{t||(t=!0,l(t=>{let i=[...t.pageKeys,t.nextPageKey],r={...t.queries};return r[t.nextPageKey]={query:t.query,args:{...t.args,paginationOpts:{numItems:s,cursor:e,id:t.id}}},{...t,nextPageKey:t.nextPageKey+1,pageKeys:i,queries:r}}))}}},[m,d.nextPageKey])}}let T=0,O=(0,i.createContext)(void 0);function M(){let e=(0,i.useContext)(O);if(void 0===e)throw Error("Could not find `ConvexProviderWithAuth` (or `ConvexProviderWithClerk` or `ConvexProviderWithAuth0`) as an ancestor component. This component may be missing, or you might have two instances of the `convex/react` module loaded in your project.");return e}function E({children:e,client:t,useAuth:s}){let{isLoading:r,isAuthenticated:n,fetchAccessToken:o}=s(),[a,u]=(0,i.useState)(null);return r&&null!==a&&u(null),r||n||!1===a||u(!1),i.createElement(O.Provider,{value:{isLoading:null===a,isAuthenticated:n&&(a??!1)}},i.createElement(I,{authProviderAuthenticated:n,fetchAccessToken:o,authProviderLoading:r,client:t,setIsConvexAuthenticated:u}),i.createElement(p,{client:t},e),i.createElement(Q,{authProviderAuthenticated:n,fetchAccessToken:o,authProviderLoading:r,client:t,setIsConvexAuthenticated:u}))}function I({authProviderAuthenticated:e,fetchAccessToken:t,authProviderLoading:s,client:r,setIsConvexAuthenticated:n}){return(0,i.useEffect)(()=>{let s=!0;if(e)return r.setAuth(t,e=>{s&&n(()=>e)}),()=>{s=!1,n(e=>!e&&null)}},[e,t,s,r,n]),null}function Q({authProviderAuthenticated:e,fetchAccessToken:t,authProviderLoading:s,client:r,setIsConvexAuthenticated:n}){return(0,i.useEffect)(()=>
3{if(e)return()=>{r.clearAuth(),n(()=>null)}},[e,t,s,r,n]),null}function $({children:e}){let{isLoading:t,isAuthenticated:s}=M();return t||!s?null:i.createElement(i.Fragment,null,e)}function P({children:e}){let{isLoading:t,isAuthenticated:s}=M();return t||s?null:i.createElement(i.Fragment,null,e)}}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.