"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[3610],{2736:function(e,t,s){s.d(t,{i:function(){return i}});let i="1.17.0"},13610:function(e,t,s){s.d(t,{P9:function(){return em},Zj:function(){return eg},CC:function(){return ep},Db:function(){return eS},hu:function(){return eq},aM:function(){return ev}});var i=s(40606),r=s(97742),n=s(2736),o=Object.defineProperty,a=(e,t,s)=>t in e?o(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,u=(e,t,s)=>a(e,"symbol"!=typeof t?t+"":t,s);function h(e){switch(e){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class c{constructor(e){u(this,"_onLogLineFuncs"),u(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 l(e){let t=new c(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 d(e,t,s,i,r){let n=h(s);if("object"==typeof r&&(r=`ConvexError ${JSON.stringify(r.errorData,null,2)}`),"info"===t){let t=r.match(/^\[.*?\] /);if(null===t){e.error(`[CONVEX ${n}(${i})] Could not parse console.log`);return}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 f(e,t,s){let i=h(e);return`[CONVEX ${i}(${t})] ${s.errorMessage}
  Called by client`}function g(e,t){return t.data=e.errorData,t}function y(e){let t,s;let 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 p(e,t){return JSON.stringify({udfPath:y(e),args:(0,r.D2)(t)})}var m=Object.defineProperty,v=(e,t,s)=>t in e?m(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,S=(e,t,s)=>v(e,"symbol"!=typeof t?t+"":t,s);class b{constructor(){S(this,"nextQueryId"),S(this,"querySetVersion"),S(this,"querySet"),S(this,"queryIdToToken"),S(this,"identityVersion"),S(this,"auth"),S(this,"outstandingQueriesOlderThanRestart"),S(this,"outstandingAuthOlderThanRestart"),S(this,"paused"),S(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 n=y(e),o=p(n,t),a=this.querySet.get(o);if(void 0!==a)return a.numSubscribers+=1,{queryToken:o,modification:null,unsubscribe:()=>this.removeSubscriber(o)};{let e=this.nextQueryId++;this.querySet.set(o,{id:e,canonicalizedUdfPath:n,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:n,args:[(0,r.D2)(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=p(y(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,r.D2)(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 w=Object.defineProperty,k=(e,t,s)=>t in e?w(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,R=(e,t,s)=>k(e,"symbol"!=typeof t?t+"":t,s);class q{constructor(e){this.logger=e,R(this,"inflightRequests"),R(this,"requestsOlderThanRestart"),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}})})}onResponse(e){let t;let s=this.inflightRequests.get(e.requestId);if(void 0===s||"Completed"===s.status.status)return null;let i="Mutation"===s.message.type?"mutation":"action",n=s.message.udfPath;for(let t of e.logLines)d(this.logger,"info",i,n,t);let o=s.status;if(e.success)t=()=>o.onResult({success:!0,logLines:e.logLines,value:(0,r.sq)(e.result)});else{let s=e.result,{errorData:a}=e;d(this.logger,"error",i,n,s),t=()=>o.onResult({success:!1,errorMessage:s,errorData:void 0!==a?(0,r.sq)(a):void 0,logLines:e.logLines})}return"ActionResponse"!==e.type&&e.success?(s.status={status:"Completed",ts:e.ts,onResolve:t},null):(t(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),e.requestId)}removeCompleted(e){let t=new Set;for(let[s,i]of this.inflightRequests.entries()){let r=i.status;"Completed"===r.status&&r.ts.lessThanOrEqual(e)&&(r.onResolve(),t.add(s),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(this.inflightRequests.delete(t),this.requestsOlderThanRestart.delete(t),"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)}}var T=s(25727),A=s(22687),C=s(20654),M=Object.defineProperty,O=(e,t,s)=>t in e?M(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,x=(e,t,s)=>O(e,"symbol"!=typeof t?t+"":t,s);class Q{constructor(e){x(this,"queryResults"),x(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...t){let s=(0,A.Op)(t[0]),i=(0,T.$P)(e),r=this.queryResults.get(p(i,s));if(void 0!==r)return Q.queryValue(r.result)}getAllQueries(e){let t=[],s=(0,T.$P)(e);for(let e of this.queryResults.values())e.udfPath===y(s)&&t.push({args:e.args,value:Q.queryValue(e.result)});return t}setQuery(e,t,s){let i=(0,A.Op)(t),r=(0,T.$P)(e),n=p(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 I{constructor(){x(this,"queryResults"),x(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 g(s,new C.P(f("query",t.udfPath,s)));throw Error(f("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 V=Object.defineProperty,L=(e,t,s)=>t in e?V(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,E=(e,t,s)=>L(e,"symbol"!=typeof t?t+"":t,s);class P{constructor(e,t){E(this,"low"),E(this,"high"),E(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 P(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?$:e>=F?D:new P(e%_|0,e/_|0)}toString(){return(BigInt(this.high)*BigInt(_)+BigInt(this.low)).toString()}equals(e){return P.isLong(e)||(e=P.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(P.isLong(e)||(e=P.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?P.fromNumber(e):new P(e.low,e.high)}}let $=new P(0,0),_=4294967296,F=18446744073709552e3,D=new P(-1,-1);var j=Object.defineProperty,N=(e,t,s)=>t in e?j(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,U=(e,t,s)=>N(e,"symbol"!=typeof t?t+"":t,s);class W{constructor(e,t){U(this,"version"),U(this,"remoteQuerySet"),U(this,"queryPath"),U(this,"logger"),this.version={querySet:0,ts:P.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)d(this.logger,"info","query",e,s);let s=(0,r.sq)(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)d(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,r.sq)(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 B(e){let t=r.DS.toByteArray(e);return P.fromBytesLE(Array.from(t))}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,H=(e,t,s)=>z(e,"symbol"!=typeof t?t+"":t,s);class X{constructor(e,t,s,i){H(this,"socket"),H(this,"connectionCount"),H(this,"lastCloseReason"),H(this,"initialBackoff"),H(this,"maxBackoff"),H(this,"retries"),H(this,"serverInactivityThreshold"),H(this,"reconnectDueToServerInactivityTimeout"),H(this,"uri"),H(this,"onOpen"),H(this,"onResume"),H(this,"onMessage"),H(this,"webSocketConstructor"),H(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()}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.socket={state:"connecting",ws:e,paused:"no"},this.resetServerInactivityTimeout(),e.onopen=()=>{if(this.logger.logVerbose("begin ws.onopen"),"connecting"!==this.socket.state)throw Error("onopen called with socket not in connecting state");this.socket={state:"ready",ws:e,paused:"yes"===this.socket.paused?"uninitialized":"no"},this.resetServerInactivityTimeout(),"no"===this.socket.paused&&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:B(e.ts)};return{...e};case"Transition":return{...e,startVersion:{...e.startVersion,ts:B(e.startVersion.ts)},endVersion:{...e.endVersion,ts:B(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){if(this._logVerbose(`sending message with type ${e.type}`),"ready"===this.socket.state&&"no"===this.socket.paused){let t=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 r.DS.fromByteArray(t)}(e.maxObservedTimestamp)};return{...e,maxObservedTimestamp:void 0}}}(e));try{this.socket.ws.send(t)}catch(e){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${e}`),this.closeAndReconnect("FailedToSendMessage")}return!0}return!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.socket={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()}}restart(){switch(this.socket.state){case"stopped":break;case"terminated":return;case"connecting":case"ready":case"disconnected":throw Error("`restart()` is only valid after `stop()`");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:this.socket;return}}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()}_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);return t+t*(Math.random()-.5)}}function G(e){this.message=e}G.prototype=Error(),G.prototype.name="InvalidCharacterError";var Y="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new G("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,i,r=0,n=0,o="";i=t.charAt(n++);~i&&(s=r%4?64*s+i:i,r++%4)&&(o+=String.fromCharCode(255&s>>(-2*r&6))))i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o};function Z(e){this.message=e}Z.prototype=Error(),Z.prototype.name="InvalidTokenError";var K=function(e,t){if("string"!=typeof e)throw new Z("Invalid token specified");var s=!0===(t=t||{}).header?0:1;try{return JSON.parse(function(e){var t,s=e.replace(/-/g,"+").replace(/_/g,"/");switch(s.length%4){case 0:break;case 2:s+="==";break;case 3:s+="=";break;default:throw"Illegal base64url string!"}try{return t=s,decodeURIComponent(Y(t).replace(/(.)/g,function(e,t){var s=t.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}catch(e){return Y(s)}}(e.split(".")[s]))}catch(e){throw new Z("Invalid token specified: "+e.message)}},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,s){es(this,"authState",{state:"noAuth"}),es(this,"configVersion",0),es(this,"syncState"),es(this,"authenticate"),es(this,"stopSocket"),es(this,"restartSocket"),es(this,"pauseSocket"),es(this,"resumeSocket"),es(this,"clearAuth"),es(this,"logger"),es(this,"refreshTokenLeewaySeconds"),this.syncState=e,this.authenticate=t.authenticate,this.stopSocket=t.stopSocket,this.restartSocket=t.restartSocket,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._logVerbose("resuming WS after auth token fetch"),this.resumeSocket()):(this.setAuthState({state:"initialRefetch",config:{fetchToken:e,onAuthChange:t}}),await this.refetchToken()))}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.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){let{baseVersion:t}=e;if(null!=t){if(!this.syncState.isCurrentOrNewerAuthVersion(t+1)){this._logVerbose("ignoring auth error for previous auth attempt");return}this.tryToReauthenticate(e);return}this.tryToReauthenticate(e)}async tryToReauthenticate(e){if("noAuth"===this.authState.state||"waitingForServerConfirmationOfFreshToken"===this.authState.state){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}this._logVerbose("attempting to reauthenticate"),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.restartSocket())}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("resuming WS after auth token fetch (if currently paused)"),this.resumeSocket())}scheduleTokenRefetch(e){if("noAuth"===this.authState.state)return;let t=this.decodeToken(e);if(!t){this.logger.error("Auth token is not a valid JWT, cannot refetch the token");return}let{iat:s,exp:i}=t;if(!s||!i){this.logger.error("Auth token does not have required fields, cannot refetch the token");return}let r=i-s;if(r<=2){this.logger.error("Auth token does not live long enough, cannot refetch the token");return}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.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,i=await e(t);return this.configVersion!==s?{isFromOutdatedConfig:!0}:{isFromOutdatedConfig:!1,value:i}}stop(){this.resetAuthState(),this.configVersion++}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.setAuthState({state:"noAuth"})}setAuthState(e){"waitingForScheduledRefetch"===this.authState.state&&(clearTimeout(this.authState.refetchTokenTimeoutId),this.syncState.markAuthCompletion()),this.authState=e}decodeToken(e){try{return K(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 er=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function en(e){let t=e.name.slice(6);return{name:t=t.charAt(0).toLowerCase()+t.slice(1),startTime:e.startTime}}var 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,s){let i;if(eu(this,"address"),eu(this,"state"),eu(this,"requestManager"),eu(this,"webSocketManager"),eu(this,"authenticationManager"),eu(this,"remoteQuerySet"),eu(this,"optimisticQueryResults"),eu(this,"onTransition"),eu(this,"_nextRequestId"),eu(this,"_sessionId"),eu(this,"firstMessageReceived",!1),eu(this,"debug"),eu(this,"logger"),eu(this,"maxObservedTimestamp"),eu(this,"mark",e=>{if(this.debug){var t;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,A.a0)(e);let r=(s={...s}).authRefreshTokenLeewaySeconds??2,o=s.webSocketConstructor;if(!o&&"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");o=o||WebSocket,this.debug=s.reportDebugInfoToConvex??!1,this.address=e,this.logger=s.logger??l({verbose:s.verbose??!1});let a=e.search("://");if(-1===a)throw Error("Provided address was not an absolute URL.");let u=e.substring(a+3),h=e.substring(0,a);if("http"===h)i="ws";else if("https"===h)i="wss";else throw Error(`Unknown parent protocol ${h}`);let c=`${i}://${u}/api/${n.i}/sync`;this.state=new b,this.remoteQuerySet=new W(e=>this.state.queryPath(e),this.logger),this.requestManager=new q(this.logger),this.authenticationManager=new ei(this.state,{authenticate:e=>{let t=this.state.setAuth(e);this.webSocketManager.sendMessage(t)},stopSocket:()=>this.webSocketManager.stop(),restartSocket:()=>this.webSocketManager.restart(),pauseSocket:()=>{this.webSocketManager.pause(),this.state.pause()},resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:r}),this.optimisticQueryResults=new I,this.onTransition=t,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:d}=s;if("undefined"==typeof window||void 0===window.addEventListener){if(!0===d)throw Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else!1!==d&&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 X(c,{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 W(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.reportMarks()),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 Set([t]));break}case"ActionResponse":this.requestManager.onResponse(e);break;case"AuthError":this.authenticationManager.onAuthError(e);break;case"FatalError":{let t=function(e,t){let s=`[CONVEX FATAL ERROR] ${t}`;return e.error(s),Error(s)}(this.logger,e.error);throw this.webSocketManager.terminate(),t}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}}},o,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)}}this.onTransition(this.optimisticQueryResults.ingestQueryResultsFromServer(s,e))}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,A.Op)(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=p(e,(0,A.Op)(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=p(e,(0,A.Op)(t));return this.optimisticQueryResults.queryLogs(s)}queryJournal(e,t){let s=p(e,(0,A.Op)(t));return this.state.queryJournal(s)}connectionState(){return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:"ready"===this.webSocketManager.socketState(),timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest()}}async mutation(e,t,s){let i=await this.mutationInternal(e,t,s);if(!i.success){if(void 0!==i.errorData)throw g(i,new C.P(f("mutation",e,i)));throw Error(f("mutation",e,i))}return i.value}async mutationInternal(e,t,s,i){let n=(0,A.Op)(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,n)},o);this.onTransition(t)}}let a={type:"Mutation",requestId:o,udfPath:e,componentPath:i,args:[(0,r.D2)(n)]},u=this.webSocketManager.sendMessage(a);return 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 g(s,new C.P(f("action",e,s)));throw Error(f("action",e,s))}return s.value}async actionInternal(e,t,s){let i=(0,A.Op)(t),n=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let o={type:"Action",requestId:n,udfPath:e,componentPath:s,args:[(0,r.D2)(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}reportMarks(){if(this.debug){let e=function(e){if("undefined"==typeof performance||!performance.getEntriesByName)return[];let t=[];for(let s of er){let i=performance.getEntriesByName(s).filter(e=>"mark"===e.entryType).filter(t=>t.detail.sessionId===e);t.push(...i)}return t.map(en)}(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-${n.i}`},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 ec=s(64623),el=Object.defineProperty,ed=(e,t,s)=>t in e?el(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,ef=(e,t,s)=>ed(e,"symbol"!=typeof t?t+"":t,s);if(void 0===i)throw Error("Required dependency 'react' not found");if(void 0===ec)throw Error("Required dependency 'react-dom' not found");class eg{constructor(e,t){if(ef(this,"address"),ef(this,"cachedSync"),ef(this,"listeners"),ef(this,"options"),ef(this,"closed",!1),ef(this,"_logger"),ef(this,"adminAuth"),ef(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??l({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 eh(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,T.$P)(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:()=>{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,T.$P)(e);return this.sync.mutation(r,s,i)}action(e,...t){let s=(0,T.$P)(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){ec.unstable_batchedUpdates(()=>{for(let t of e){let e=this.listeners.get(t);if(e)for(let t of e)t()}})}}let ey=i.createContext(void 0);function ep(){return(0,i.useContext)(ey)}let em=({client:e,children:t})=>i.createElement(ey.Provider,{value:e},t);function ev(e,...t){let s="skip"===t[0],n="skip"===t[0]?{}:(0,A.Op)(t[0]),o="string"==typeof e?(0,T.r8)(e):e,a=(0,T.$P)(o),u=eq((0,i.useMemo)(()=>s?{}:{query:{query:o,args:n}},[JSON.stringify((0,r.D2)(n)),a,s])).query;if(u instanceof Error)throw u;return u}function eS(e){let t="string"==typeof e?(0,T.r8)(e):e,s=(0,i.useContext)(ey);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,T.$P)(t)}`);return e(t,s,r)},r})(t,s),[s,(0,T.$P)(t)])}var eb=Object.defineProperty,ew=(e,t,s)=>t in e?eb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,ek=(e,t,s)=>ew(e,"symbol"!=typeof t?t+"":t,s);class eR{constructor(e){ek(this,"createWatch"),ek(this,"queries"),ek(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,T.$P)(s),void 0===this.queries[t])this.addQuery(t,s,i);else{let e=this.queries[t];((0,T.$P)(s)!==(0,T.$P)(e.query)||JSON.stringify((0,r.D2)(i))!==JSON.stringify((0,r.D2)(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;let{query:r,args:n}=e[s];(0,T.$P)(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 eq(e){let t=ep();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");return function(e,t){let[s]=(0,i.useState)(()=>new eR(t));return s.createWatch!==t&&s.setCreateWatch(t),(0,i.useEffect)(()=>()=>s.destroy(),[s]),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:()=>s.getLocalResults(e),subscribe:t=>(s.setQueries(e),s.subscribe(t))}),[s,e]))}(e,(0,i.useMemo)(()=>(e,s,i)=>t.watchQuery(e,s,{journal:i}),[t]))}(0,i.createContext)(void 0)},25727:function(e,t,s){s.d(t,{$P:function(){return n},qL:function(){return a},r8:function(){return o}});var i=s(64792),r=s(73936);function n(e){let t=(0,r.wP)(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.Q];if(!s)throw Error(`${e} is not a functionReference`);return s}function o(e){return{[i.Q]:e}}let a=function e(t=[]){return new Proxy({},{get(s,r){if("string"==typeof r)return e([...t,r]);if(r===i.Q){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}})}()},73936:function(e,t,s){s.d(t,{wP:function(){return n}});var i=s(64792);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.Q])t={name:e[i.Q]};else{let s=e[r]??null;if(!s)throw Error(`${e} is not a functionReference`);t={reference:s}}return t}},64792:function(e,t,s){s.d(t,{Q:function(){return i}});let i=Symbol.for("functionName")}}]);