PageSourceSearch

https://macaly-ubyvbfa1ahojzxbfzpmlnrau.macaly-app.com/_next/stati…?dpl=dpl_CvFXPM9CAFKFVogVgBbcchwpKF44

js macaly-ubyvbfa1ahojzxbfzpmlnrau.macaly-app.com collected 2026-10-03 04:59:07 UTC 74,999 bytes, 2 lines download raw bytes

1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,14001,e=>{"use strict";e.s(["version",0,"1.28.0"])},90798,95543,2082,88218,1737,3697,6689,e=>{"use strict";for(var t,s,r=[],i=[],n=Uint8Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,u=o.length;a<u;++a)r[a]=o[a],i[o.charCodeAt(a)]=a;function h(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var s=e.indexOf("=");-1===s&&(s=t);var r=s===t?0:4-s%4;return[s,r]}function l(e){var t=h(e),s=t[0],r=t[1];return(s+r)*3/4-r}function c(e){var t,s,r=h(e),o=r[0],a=r[1],u=new n((o+a)*3/4-a),l=0,c=a>0?o-4:o;for(s=0;s<c;s+=4)t=i[e.charCodeAt(s)]<<18|i[e.charCodeAt(s+1)]<<12|i[e.charCodeAt(s+2)]<<6|i[e.charCodeAt(s+3)],u[l++]=t>>16&255,u[l++]=t>>8&255,u[l++]=255&t;return 2===a&&(t=i[e.charCodeAt(s)]<<2|i[e.charCodeAt(s+1)]>>4,u[l++]=255&t),1===a&&(t=i[e.charCodeAt(s)]<<10|i[e.charCodeAt(s+1)]<<4|i[e.charCodeAt(s+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t),u}function d(e){for(var t,s=e.length,i=s%3,n=[],o=0,a=s-i;o<a;o+=16383)n.push(function(e,t,s){for(var i,n=[],o=t;o<s;o+=3)i=(e[o]<<16&0xff0000)+(e[o+1]<<8&65280)+(255&e[o+2]),n.push(r[i>>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return n.join("")}(e,o,o+16383>a?a:o+16383));return 1===i?n.push(r[(t=e[s-1])>>2]+r[t<<4&63]+"=="):2===i&&n.push(r[(t=(e[s-2]<<8)+e[s-1])>>10]+r[t>>4&63]+r[t<<2&63]+"="),n.join("")}function f(e){return d(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function g(e){if(void 0===e)return{};if(!y(e))throw Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function p(e){if(void 0===e)throw Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if("string"!=typeof e)throw Error(`Invalid deployment address: found ${e}".`);if(!(e.startsWith("http:")||e.startsWith("https:")))throw Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${e}".`);try{new URL(e)}catch{throw Error(`Invalid deployment address: "${e}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(e.endsWith(".convex.site"))throw Error(`Invalid deployment address: "${e}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function y(e){let t="object"==typeof e,s=Object.getPrototypeOf(e),r=null===s||s===Object.prototype||s?.constructor?.name==="Object";return t&&r}i[45]=62,i[95]=63,e.s(["byteLength",()=>l,"fromByteArray",()=>d,"fromByteArrayUrlSafeNoPadding",()=>f,"toByteArray",()=>c],95543),e.s(["isSimpleObject",()=>y,"parseArgs",()=>g,"validateDeploymentUrl",()=>p],2082);let m=BigInt("-9223372036854775808"),v=BigInt("9223372036854775807"),b=BigInt("0"),w=BigInt("8"),k=BigInt("256");function S(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}let C=DataView.prototype.setBigInt64?function(e){if(e<m||v<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);let t=new ArrayBuffer(8);return new DataView(t).setBigInt64(0,e,!0),d(new Uint8Array(t))}:function(e){e<b&&(e-=m+m);let t=e.toString(16);t.length%2==1&&(t="0"+t);let s=new Uint8Array(new ArrayBuffer(8)),r=0;for(let i of t.match(/.{2}/g).reverse())s.set([parseInt(i,16)],r++),e>>=w;return d(s)},A=DataView.prototype.getBigInt64?function(e){let t=c(e);if(8!==t.byteLength)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}:function(e){let t=c(e);if(8!==t.byteLength)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let s=b,r=b;for(let e of t)s+=BigInt(e)*k**r,r++;return s>v&&(s+=m+m),s};function T(e){if(e.length>1024)throw Error(`Field name ${e} exceeds maximum field name length 1024.`);if(e.startsWith("$"))throw Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){let s=e.charCodeAt(t);if(s<32||s>=127)throw Error(`Field name ${e}
1 has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function R(e){return JSON.stringify(e,(e,t)=>void 0===t?"undefined":"bigint"==typeof t?`${t.toString()}n`:t)}function x(e,t,s,r){if(void 0===e){let e=s&&` (present at path ${s} in original object ${R(t)})`;throw Error(`undefined is not a valid Convex value${e}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(null===e)return e;if("bigint"==typeof e){if(e<m||v<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:C(e)}}if("number"==typeof e)if(!S(e))return e;else{let t=new ArrayBuffer(8);return new DataView(t).setFloat64(0,e,!0),{$float:d(new Uint8Array(t))}}if("boolean"==typeof e||"string"==typeof e)return e;if(e instanceof ArrayBuffer)return{$bytes:d(new Uint8Array(e))};if(Array.isArray(e))return e.map((e,r)=>x(e,t,s+`[${r}]`,!1));if(e instanceof Set)throw Error(q(s,"Set",[...e],t));if(e instanceof Map)throw Error(q(s,"Map",[...e],t));if(!y(e)){let r=e?.constructor?.name;throw Error(q(s,r?`${r} `:"",e,t))}let i={},n=Object.entries(e);for(let[e,o]of(n.sort(([e,t],[s,r])=>e===s?0:e<s?-1:1),n))void 0!==o?(T(e),i[e]=x(o,t,s+`.${e}`,!1)):r&&(T(e),i[e]=O(o,t,s+`.${e}`));return i}function q(e,t,s,r){return e?`${t}${R(s)} is not a supported Convex type (present at path ${e} in original object ${R(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${R(s)} is not a supported Convex type.`}function O(e,t,s){if(void 0===e)return{$undefined:null};if(void 0===t)throw Error(`Programming error. Current value is ${R(e)} but original value is undefined`);return x(e,t,s,!1)}function $(e){return x(e,e,"",!1)}function E(e){return O(e,e,"")}function M(e){return x(e,e,"",!0)}e.s(["convexOrUndefinedToJson",()=>E,"convexToJson",()=>$,"jsonToConvex",()=>function e(t){if(null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t)return t;if(Array.isArray(t))return t.map(t=>e(t));if("object"!=typeof t)throw Error(`Unexpected type of ${t}`);let s=Object.entries(t);if(1===s.length){let e=s[0][0];if("$bytes"===e){if("string"!=typeof t.$bytes)throw Error(`Malformed $bytes field on ${t}`);return c(t.$bytes).buffer}if("$integer"===e){if("string"!=typeof t.$integer)throw Error(`Malformed $integer field on ${t}`);return A(t.$integer)}if("$float"===e){if("string"!=typeof t.$float)throw Error(`Malformed $float field on ${t}`);let e=c(t.$float);if(8!==e.byteLength)throw Error(`Received ${e.byteLength} bytes, expected 8 for $float`);let s=new DataView(e.buffer).getFloat64(0,!0);if(!S(s))throw Error(`Float ${s} should be encoded as a number`);return s}if("$set"===e)throw Error("Received a Set which is no longer supported as a Convex type.");if("$map"===e)throw Error("Received a Map which is no longer supported as a Convex type.")}let r={};for(let[s,i]of Object.entries(t))T(s),r[s]=e(i);return r},"patchValueToJson",()=>M,"stringifyValueForError",()=>R],88218);var I=Object.defineProperty,V=(e,t,s)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?I(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s};class P{constructor({isOptional:e}){V(this,"type"),V(this,"fieldPaths"),V(this,"isOptional"),V(this,"isConvexValidator"),this.isOptional=e,this.isConvexValidator=!0}get optional(){return"optional"===this.isOptional}}class Q extends P{constructor({isOptional:e,tableName:t}){if(super({isOptional:e}),V(this,"tableName"),V(this,"kind","id"),"string"!=typeof t)throw Error("v.id(tableName) requires a string");this.tableName=t}get json(){return{type:"id",tableName:this.tableName}}asOptional(){return new Q({isOptional:"optional",tableName:this.tableName})}}class j extends P{constructor(){super(...arguments),V(this,"kind","float64")}get json(){return{type:"number"}}asOptional(){return new j({isOptional:"optional"})}}class L extends P{constructor(){super(...arguments),V(this,"kind","int64")}get json(){return{type:"bigint"}}asOptional(){return new L({isOptional:"optional"})}}class _ extends P{constructor(){super(...arguments),V(this,"kind","boolean")}get json(){return{type:this.kind}}asOptional(){return new _({isOptional:"optional"})}}class N extends P{constructor(){super(...arguments),V(this,"kind","bytes")}get json(){return{type:this.kind}}asOptional(){return new N({isOptional:"optional"})}}class D extends P{constructor(){super(...arguments),V(this,"kind","string")}get json(){return{type:this.kind}}asOptional(){return new D({isOptional:"optional"})}}class F extends P{constructor(){super(...arguments),V(this,"kind","null")}get json(){return{type:this.kind}}asOptional(){return new F({isOptional:"optional"})}}class B extends P{constructor(){super(...arguments),V(this,"kind","any")}get json(){return{type:this.kind}}asOptional(){return new B({isOptional:"optional"})}}class U extends P{constructor({isOptional:e,fields:t}){super({isOptional:e}),V(this,"fields"),V(this,"kind","object"),globalThis.Object.values(t).forEach(e
1=>{if(!e.isConvexValidator)throw Error("v.object() entries must be validators")}),this.fields=t}get json(){return{type:this.kind,value:globalThis.Object.fromEntries(globalThis.Object.entries(this.fields).map(([e,t])=>[e,{fieldType:t.json,optional:"optional"===t.isOptional}]))}}asOptional(){return new U({isOptional:"optional",fields:this.fields})}}class J extends P{constructor({isOptional:e,value:t}){if(super({isOptional:e}),V(this,"value"),V(this,"kind","literal"),"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t&&"bigint"!=typeof t)throw Error("v.literal(value) must be a string, number, or boolean");this.value=t}get json(){return{type:this.kind,value:$(this.value)}}asOptional(){return new J({isOptional:"optional",value:this.value})}}class W extends P{constructor({isOptional:e,element:t}){super({isOptional:e}),V(this,"element"),V(this,"kind","array"),this.element=t}get json(){return{type:this.kind,value:this.element.json}}asOptional(){return new W({isOptional:"optional",element:this.element})}}class z extends P{constructor({isOptional:e,key:t,value:s}){if(super({isOptional:e}),V(this,"key"),V(this,"value"),V(this,"kind","record"),"optional"===t.isOptional)throw Error("Record validator cannot have optional keys");if("optional"===s.isOptional)throw Error("Record validator cannot have optional values");if(!t.isConvexValidator||!s.isConvexValidator)throw Error("Key and value of v.record() but be validators");this.key=t,this.value=s}get json(){return{type:this.kind,keys:this.key.json,values:{fieldType:this.value.json,optional:!1}}}asOptional(){return new z({isOptional:"optional",key:this.key,value:this.value})}}class H extends P{constructor({isOptional:e,members:t}){super({isOptional:e}),V(this,"members"),V(this,"kind","union"),t.forEach(e=>{if(!e.isConvexValidator)throw Error("All members of v.union() must be validators")}),this.members=t}get json(){return{type:this.kind,value:this.members.map(e=>e.json)}}asOptional(){return new H({isOptional:"optional",members:this.members})}}function X(e){return!!e.isConvexValidator}function G(e){return X(e)?e:K.object(e)}let K={id:e=>
1new Q({isOptional:"required",tableName:e}),null:()=>new F({isOptional:"required"}),number:()=>new j({isOptional:"required"}),float64:()=>new j({isOptional:"required"}),bigint:()=>new L({isOptional:"required"}),int64:()=>new L({isOptional:"required"}),boolean:()=>new _({isOptional:"required"}),string:()=>new D({isOptional:"required"}),bytes:()=>new N({isOptional:"required"}),literal:e=>new J({isOptional:"required",value:e}),array:e=>new W({isOptional:"required",element:e}),object:e=>new U({isOptional:"required",fields:e}),record:(e,t)=>new z({isOptional:"required",key:e,value:t}),union:(...e)=>new H({isOptional:"required",members:e}),any:()=>new B({isOptional:"required"}),optional:e=>e.asOptional()};e.s(["asObjectValidator",()=>G,"isValidator",()=>X,"v",0,K],1737),e.i(95543);var Y=Object.defineProperty,Z=(e,t,s)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?Y(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s};let ee=Symbol.for("ConvexError");class et extends(s=Error,t=ee,s){constructor(e){super("string"==typeof e?e:R(e)),Z(this,"name","ConvexError"),Z(this,"data"),Z(this,t,!0),this.data=e}}e.s(["ConvexError",()=>et],3697);let es=()=>Array.from({length:4},()=>0),er=es(),ei=es();function en(e,t){let s,r;if(e<128)return t[0]=e,1;if(e<=2047)s=1,r=192;else if(e<=65535)s=2,r=224;else if(e<=1114111)s=3,r=240;else throw Error("Invalid code point");t[0]=(e>>6*s)+r;let i=1;for(;s>0;s--){let r=e>>6*(s-1);t[i++]=128|63&r}return i}function eo(e,t){return function e(t,s){return t[0]===s[0]?function(t,s){if(null==t)return 0;if("number"==typeof t){if("number"!=typeof s)throw Error(`Unexpected type ${s}`);return function(e,t){if(isNaN(e)||isNaN(t)){let s=new ArrayBuffer(8),r=new ArrayBuffer(8);new DataView(s).setFloat64(0,e,!0),new DataView(r).setFloat64(0,t,!0);let i=BigInt(new DataView(s).getBigInt64(0,!0)),n=BigInt(new DataView(r).getBigInt64(0,!0)),o=(0x8000000000000000n&i)!==0n,a=(0x8000000000000000n&n)!==0n;return isNaN(e)!==isNaN(t)?isNaN(e)?o?-1:1:a?1:-1:o!==a?o?-1:1:i<n?-1:+(i!==n)}return Object.is(e,t)?0:Object.is(e,-0)?Object.is(t,0)?-1:-Math.sign(t):Object.is(t,-0)?Object.is(e,0)?1:Math.sign(e):e<t?-1:1}(t,s)}if("string"==typeof t){if("string"!=typeof s)throw Error(`Unexpected type ${s}`);return function(e,t){let s=e.length,r=t.length,i=Math.min(s,r);for(let s=0;s<i;){let r=e.codePointAt(s),i=t.codePointAt(s);if(r!==i){if(r<128&&i<128)return r-i;let e=en(r,er),t=en(i,ei);return function(e,t,s,r){let i=Math.min(t,r);for(let t=0;t<i;t++){let r=e[t],i=s[t];if(r!==i)return r-i}return t-r}(er,e,ei,t)}s+=r>65535?2:1}return s-r}(t,s)}if("bigint"==typeof t||"boolean"==typeof t||"string"==typeof t)return t<s?-1:+(t!==s);if(!Array.isArray(t)||!Array.isArray(s))throw Error(`Unexpected type ${t}`);for(let r=0;r<t.length&&r<s.length;r++){let i=e(t[r],s[r]);if(0!==i)return i}return t.length<s.length?-1:+(t.length>s.length)}(t[1],s[1]):t[0]<s[0]?-1:1}(ea(e),ea(t))}function ea(e){return void 0===e?[0,void 0]:null===e?[1,null]:"bigint"==typeof e?[2,e]:"number"==typeof e?[3,e]:"boolean"==typeof e?[4,e]:"string"==typeof e?[5,e]:e instanceof ArrayBuffer?[6,Array.from(new Uint8Array(e)).map(ea)]:Array.isArray(e)?[7,e.map(ea)]:[8,Object.keys(e).sort().map(t=>[t,e[t]]).map(ea)]}e.s(["compareValues",()=>eo],6689),e.s([],90798)},50711,39197,62849,71482,20344,82045,81958,e=>{"use strict";let t,s;var r=e.i(71645);e.i(90798);var i=e.i(3697),n=e.i(88218);e.s(["ConvexProvider",()=>eb,"ConvexReactClient",()=>ey,"useAction",()=>ek,"useConvex",()=>ev,"useQuery",()=>ew],82045),e.s([],20344);var o=e.i(14001),a=Object.defineProperty,u=(e,t,s)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?a(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s};function h(e){switch(e){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class l{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 c(e){let t=new l(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,r,i){let n=h(s);if("object"==typeof i&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),"info"===t){let t=i.match(/^\[.*?\] /);if(null===t)return void e.error(`[CONVEX ${n}(${r})] Could not parse console.log`);let s=i.slice(1,t[0].length-2),o=i.slice(t[0].length);e.log(`%c[CONVEX ${n}(${r})] [${s}]`,"color:rgb(0, 145, 255)",o)}else e.error(`[CONVEX ${n}(${r})] ${i}`)}function f(e,t,s){let r=h(e);return`[CONVEX ${r}(${t})] ${s.errorMessage}
2  Called by client`}function g(e,t){return t.data=e.errorData,t}
2function p(e){let t,s,r=e.split(":");return 1===r.length?(t=r[0],s="default"):(t=r.slice(0,r.length-1).join(":"),s=r[r.length-1]),t.endsWith(".js")&&(t=t.slice(0,-3)),`${t}:${s}`}function y(e,t){return JSON.stringify({udfPath:p(e),args:(0,n.convexToJson)(t)})}var m=Object.defineProperty,v=(e,t,s)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?m(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s};class b{constructor(){v(this,"nextQueryId"),v(this,"querySetVersion"),v(this,"querySet"),v(this,"queryIdToToken"),v(this,"identityVersion"),v(this,"auth"),v(this,"outstandingQueriesOlderThanRestart"),v(this,"outstandingAuthOlderThanRestart"),v(this,"paused"),v(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,r){let i=p(e),o=y(i,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:i,args:t,numSubscribers:1,journal:s,componentPath:r}),this.queryIdToToken.set(e,o);let a=this.querySetVersion,u=this.querySetVersion+1,h={type:"Add",queryId:e,udfPath:i,args:[(0,n.convexToJson)(t)],journal:s,componentPath:r};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=y(p(e),t),r=this.querySet.get(s);return void 0!==r?r.id:null}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}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 r=this.identityVersion;return this.paused||(this.identityVersion=r+1),{type:"Authenticate",baseVersion:r,...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 r={type:"Add",queryId:s.id,udfPath:s.canonicalizedUdfPath,args:[(0,n.convexToJson)(s.args)],journal:s.journal,componentPath:s.componentPath};t.push(r),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 r={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[s,r]}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,r=this.querySetVersion+1,i={type:"Remove",queryId:t.id};return this.paused?this.pendingQuerySetModifications.has(t.id)?this.pendingQuerySetModifications.delete(t.id):this.pendingQuerySetModifications.set(t.id,i):this.querySetVersion=r,{type:"ModifyQuerySet",baseVersion:s,newVersion:r,modifications:[i]}}}}var w=Object.defineProperty,k=(e,t,s)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?w(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s};class S{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,k(this,"inflightRequests"),k(this,"requestsOlderThanRestart"),k(this,"inflightMutationsCount",0),k(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,t){let s=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++});return this.markConnectionStateDirty(),s}
2onResponse(e){let t,s,r=this.inflightRequests.get(e.requestId);if(void 0===r||"Completed"===r.status.status)return null;let i="Mutation"===r.message.type?"mutation":"action",o=r.message.udfPath;for(let t of e.logLines)d(this.logger,"info",i,o,t);let a=r.status;if(e.success)t={success:!0,logLines:e.logLines,value:(0,n.jsonToConvex)(e.result)},s=()=>a.onResult(t);else{let r=e.result,{errorData:u}=e;d(this.logger,"error",i,o,r),t={success:!1,errorMessage:r,errorData:void 0!==u?(0,n.jsonToConvex)(u):void 0,logLines:e.logLines},s=()=>a.onResult(t)}return"ActionResponse"!==e.type&&e.success?(r.status={status:"Completed",result:t,ts:e.ts,onResolve:s},null):(s(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),"Action"===r.message.type?this.inflightActionsCount--:"Mutation"===r.message.type&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:t})}removeCompleted(e){let t=new Map;for(let[s,r]of this.inflightRequests.entries()){let i=r.status;"Completed"===i.status&&i.ts.lessThanOrEqual(e)&&(i.onResolve(),t.set(s,i.result),"Mutation"===r.message.type?this.inflightMutationsCount--:"Action"===r.message.type&&this.inflightActionsCount--,this.inflightRequests.delete(s),this.requestsOlderThanRestart.delete(s))}return t.size>0&&this.markConnectionStateDirty(),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 this.markConnectionStateDirty(),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}}let C=Symbol.for("functionName"),A=Symbol.for("toReferencePath");function T(e,t){e[A]=t}function R(e){let t;if("string"==typeof e)t=e.startsWith("function://")?{functionHandle:e}:{name:e};else if(e[C])t={name:e[C]};else{let s=e[A]??null;if(!s)throw Error(`${e} is not a functionReference`);t={reference:s}}return t}function x(e){let t=R(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[C];if(!s)throw Error(`${e} is not a functionReference`);return s}function q(e){return{[C]:e}}e.s(["getFunctionAddress",()=>R,"setReferencePath",()=>T,"toReferencePath",0,A],39197);let O=function e(t=[]){return new Proxy({},{get(s,r){if("string"==typeof r)return e([...t,r]);if(r===C){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}})}();e.s(["anyApi",0,O,"getFunctionName",()=>x,"makeFunctionReference",()=>q],62849);var $=e.i(2082),E=Object.defineProperty,M=(e,t,s)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?E(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s};class I{constructor(e){M(this,"queryResults"),M(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...t){let s=(0,$.parseArgs)(t[0]),r=x(e),i=this.queryResults.get(y(r,s));if(void 0!==i)return I.queryValue(i.result)}getAllQueries(e){let t=[],s=x(e);for(let e of this.queryResults.values())e.udfPath===p(s)&&t.push({args:e.args,value:I.queryValue(e.result)});return t}setQuery(e,t,s){let r=(0,$.parseArgs)(t),i=x(e),n=y(i,r);this.queryResults.set(n,{udfPath:i,args:r,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 V{constructor(){M(this,"queryResults"),M(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 r=new I(this.queryResults);for(let e of this.optimisticUpdates)e.update(r);let i=[];for(let[e,t]of this.queryResults){let r=s.get(e);(void 0===r||r.result!==t.result)&&i.push(e)}return i}applyOptimisticUpdate(e,t){this.optimisticUpdates.push({update:e,mutationId:t});let s=new I(this.queryResults);return e(s),s.modifiedQueries}rawQueryResult(e){return this.queryResults.get(e)}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 i.ConvexError(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 P=Object.defineProperty,Q=(e,t,s)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?P(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s};
2class j{constructor(e,t){Q(this,"low"),Q(this,"high"),Q(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 j(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?L:e>=N?D:new j(e%_|0,e/_|0)}toString(){return(BigInt(this.high)*BigInt(_)+BigInt(this.low)).toString()}equals(e){return j.isLong(e)||(e=j.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(j.isLong(e)||(e=j.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?j.fromNumber(e):new j(e.low,e.high)}}let L=new j(0,0),_=0x100000000,N=0xffffffffffffffff,D=new j(-1,-1);var F=Object.defineProperty,B=(e,t,s)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?F(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s};class U{constructor(e,t){B(this,"version"),B(this,"remoteQuerySet"),B(this,"queryPath"),B(this,"logger"),this.version={querySet:0,ts:j.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}:${t.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);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,n.jsonToConvex)(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,n.jsonToConvex)(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}}var J=e.i(95543),J=J;function W(e){let t=J.toByteArray(e);return j.fromBytesLE(Array.from(t))}function z(e){switch(e.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...e};case"MutationResponse":if(e.success)return{...e,ts:W(e.ts)};return{...e};case"Transition":return{...e,startVersion:{...e.startVersion,ts:W(e.startVersion.ts)},endVersion:{...e.endVersion,ts:W(e.endVersion.ts)}}}}var H=Object.defineProperty,X=(e,t,s)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?H(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s};function G(){return(void 0===t&&(t=Date.now()),"undefined"!=typeof performance&&performance.now)?Math.round(t+performance.now()):Date.now()}function K(){return`t=${Math.round((G()-t)/100)/10}s`}let Y={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};class Z{constructor(e,t,s,r,i,n){this.markConnectionStateDirty=i,this.debug=n,X(this,"socket"),X(this,"connectionCount"),X(this,"_hasEverConnected",!1),X(this,"lastCloseReason"),X(this,"transitionChunkBuffer",null),X(this,"defaultInitialBackoff"),X(this,"maxBackoff"),X(this,"retries"),X(this,"serverInactivityThreshold"),X(this,"reconnectDueToServerInactivityTimeout"),X(this,"uri"),X(this,"onOpen"),X(this,"onResume"),X(this,"onMessage"),X(this,"webSocketConstructor"),X(this,"logger"),X(this,"onServerDisconnectError"),this.webSocketConstructor=s,this.socket={state:"disconnected"},this.connectionCount=0,this.lastCloseReason="InitialConnect",this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=e,this.onOpen=t.onOpen,this.onResume=t.onResume,this.onMessage=t.onMessage,this.onServerDisconnectError=t.onServerDisconnectError,this.logger=r,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}`),this.markConnectionStateDirty()}assembleTransition(e){if(e.partNumber<0||e.partNumber>=e.totalParts||0===e.totalParts||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,Error("Invalid TransitionChunk");if(null===this.transitionChunkBuffer&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){let t=this.transitionChunkBuffer.chunks.length;
2throw this.transitionChunkBuffer=null,Error(`TransitionChunk received out of order: expected part ${t}, got ${e.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(e.chunk),this.transitionChunkBuffer.chunks.length===e.totalParts){let e=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;let t=z(JSON.parse(e));if("Transition"!==t.type)throw Error(`Expected Transition, got ${t.type} after assembling chunks`);return t}return null}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=()=>{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,clientTs:G()})),"InitialConnect"!==this.lastCloseReason&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",K(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",K())),this.connectionCount+=1,this.lastCloseReason=null},e.onerror=e=>{this.transitionChunkBuffer=null;let t=e.message;t&&this.logger.log(`WebSocket error message: ${t}`)},e.onmessage=e=>{this.resetServerInactivityTimeout();let t=e.data.length,s=z(JSON.parse(e.data));if(this._logVerbose(`received ws message with type ${s.type}`),"Ping"!==s.type){if("TransitionChunk"===s.type){let e=this.assembleTransition(s);if(!e)return;s=e,this._logVerbose(`assembled full ws message of type ${s.type}`)}null!==this.transitionChunkBuffer&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${s.type} while buffering TransitionChunks`)),"Transition"===s.type&&this.reportLargeTransition({messageLength:t,transition:s}),this.onMessage(s).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())}},e.onclose=e=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,null===this.lastCloseReason&&(this.lastCloseReason=e.reason||`closed with code ${e.code}`),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.onServerDisconnectError&&e.reason&&this.onServerDisconnectError(t)}let t=function(e){if(void 0===e)return"Unknown";for(let t of Object.keys(Y))if(e.startsWith(t))return t;return"Unknown"}(e.reason);this.scheduleReconnect(t)}}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":let t;if(void 0===e.maxObservedTimestamp)return{...e,maxObservedTimestamp:void 0};return{...e,maxObservedTimestamp:(t=new Uint8Array(e.maxObservedTimestamp.toBytesLE()),J.fromByteArray(t))}}}(e)),r=!1;try{this.socket.ws.send(s),r=!0}catch(e){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${e}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${r?"sent":"failed to send"} 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(e){this.socket={state:"disconnected"};let t=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(t)}ms`),setTimeout(()=>this.connect(),t)}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("client");return;default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{let e=this.socket.ws;return e.onmessage=e=>{this._logVerbose("Ignoring message received after close")},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;e.onmessage=e=>{this._logVerbose("Ignoring message received after close")};let 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,clientTs:G()})):"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(e){let t=("client"===e?100:"Unknown"===e?this.defaultInitialBackoff:Y[e].timeout)*Math.pow(2,this.retries);this.retries+=1;let s=Math.min(t,this.maxBackoff),r=s*(Math.random()-.5);return s+r}reportLargeTransition({transition:e,messageLength:t}){if(void 0===e.clientClockSkew||void 0===e.serverTs)return;let s=G()-e.clientClockSkew-e.serverTs/1e6,r=`${Math.round(s)}ms`,i=`${Math.round(t/1e4)/100}MB`,n=t/(s/1e3),o=`${Math.round(n/1e4)/100}MB per second`;this._logVerbose(`received ${i} transition in ${r} at ${o}`),t>2e7?this.logger.log(`received query results totaling more that 20MB (${i}
2) which will take a long time to download on slower connections`):s>2e4&&this.logger.log(`received query results totaling ${i} which took more than 20s to arrive (${r})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:s,messageLength:t}})}}class ee extends Error{}function et(e,t){let s;if("string"!=typeof e)throw new ee("Invalid token specified: must be a string");t||(t={});let r=+(!0!==t.header),i=e.split(".")[r];if("string"!=typeof i)throw new ee(`Invalid token specified: missing part #${r+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{return atob(t)}}(i)}catch(e){throw new ee(`Invalid token specified: invalid base64 for part #${r+1} (${e.message})`)}try{return JSON.parse(s)}catch(e){throw new ee(`Invalid token specified: invalid json for part #${r+1} (${e.message})`)}}ee.prototype.name="InvalidTokenError";var es=Object.defineProperty,er=(e,t,s)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?es(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s};class ei{constructor(e,t,s){er(this,"authState",{state:"noAuth"}),er(this,"configVersion",0),er(this,"syncState"),er(this,"authenticate"),er(this,"stopSocket"),er(this,"tryRestartSocket"),er(this,"pauseSocket"),er(this,"resumeSocket"),er(this,"clearAuth"),er(this,"logger"),er(this,"refreshTokenLeewaySeconds"),er(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;this.syncState.isCurrentOrNewerAuthVersion(t+1)?this.tryToReauthenticate(e):this._logVerbose("ignoring auth error for previous auth attempt")}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:r}=t;if(!s||!r)return void this.logger.error("Auth token does not have required fields, cannot refetch the token");let i=r-s;if(i<=2)return void this.logger.error("Auth token does not live long enough, cannot refetch the token");let n=Math.min(1728e6,(i-this.refreshTokenLeewaySeconds)*1e3);n<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${i}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 r=await e(t);
2return this.configVersion!==s?(this._logVerbose(`stale config version, expected ${s}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:r}}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 et(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 en=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function eo(e){let t=e.name.slice(6);return{name:t=t.charAt(0).toLowerCase()+t.slice(1),startTime:e.startTime}}var ea=Object.defineProperty,eu=(e,t,s)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?ea(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s};class eh{constructor(e,t,s){let r;if(eu(this,"address"),eu(this,"state"),eu(this,"requestManager"),eu(this,"webSocketManager"),eu(this,"authenticationManager"),eu(this,"remoteQuerySet"),eu(this,"optimisticQueryResults"),eu(this,"_transitionHandlerCounter",0),eu(this,"_nextRequestId"),eu(this,"_onTransitionFns",new Map),eu(this,"_sessionId"),eu(this,"firstMessageReceived",!1),eu(this,"debug"),eu(this,"logger"),eu(this,"maxObservedTimestamp"),eu(this,"connectionStateSubscribers",new Map),eu(this,"nextConnectionStateSubscriberId",0),eu(this,"_lastPublishedConnectionState"),eu(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{let e=this.connectionState();if(JSON.stringify(e)!==JSON.stringify(this._lastPublishedConnectionState))for(let t of(this._lastPublishedConnectionState=e,this.connectionStateSubscribers.values()))t(e)})}),eu(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,$.validateDeploymentUrl)(e);const i=(s={...s}).authRefreshTokenLeewaySeconds??2;let n=s.webSocketConstructor;if(!n&&"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");n=n||WebSocket,this.debug=s.reportDebugInfoToConvex??!1,this.address=e,this.logger=!1===s.logger?new l({verbose:s.verbose??!1}):!0!==s.logger&&s.logger?s.logger:c({verbose:s.verbose??!1});const a=e.search("://");if(-1===a)throw Error("Provided address was not an absolute URL.");const u=e.substring(a+3),h=e.substring(0,a);if("http"===h)r="ws";else if("https"===h)r="wss";else throw Error(`Unknown parent protocol ${h}`);const d=`${r}://${u}/api/${o.version}/sync`;this.state=new b,this.remoteQuerySet=new U(e=>this.state.queryPath(e),this.logger),this.requestManager=new S(this.logger,this.markConnectionStateDirty);const f=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new ei(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:f,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:i}),this.optimisticQueryResults=new V,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)});const{unsavedChangesWarning:g}=s;if("undefined"==typeof window||void 0===window.addEventListener){if(!0===g)throw Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else!1!==g&&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 Z(d,{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());
2this.remoteQuerySet=new U(e=>this.state.queryPath(e),this.logger);let[s,r]=this.state.restart(t);for(let e of(r&&this.webSocketManager.sendMessage(r),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 Map([[t.requestId,t.result]]));break}case"ActionResponse":this.requestManager.onResponse(e);break;case"AuthError":this.authenticationManager.onAuthError(e);break;case"FatalError":{var t,s;let r,i=(t=this.logger,s=e.error,r=`[CONVEX FATAL ERROR] ${s}`,t.error(r),Error(r));throw this.webSocketManager.terminate(),i}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:s.onServerDisconnectError},n,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),s.expectAuth&&f()}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,r]of t){let t=this.state.queryToken(e);if(null!==t){let i={result:r,udfPath:this.state.queryPath(e),args:this.state.queryArgs(e)};s.set(t,i)}}let r=this.optimisticQueryResults.ingestQueryResultsFromServer(s,new Set(e.keys()));this.handleTransition({queries:r.map(e=>{let t=this.optimisticQueryResults.rawQueryResult(e);return{token:e,modification:{kind:"Updated",result:t.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)}getCurrentAuthClaims(){let e=this.state.getAuth(),t={};if(e&&"User"===e.tokenType){try{t=e?et(e.value):{}}catch{t={}}return{token:e.value,decoded: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 r=(0,$.parseArgs)(t),{modification:i,queryToken:n,unsubscribe:o}=this.state.subscribe(e,r,s?.journal,s?.componentPath);return null!==i&&this.webSocketManager.sendMessage(i),{queryToken:n,unsubscribe:()=>{let e=o();e&&this.webSocketManager.sendMessage(e)}}}localQueryResult(e,t){let s=y(e,(0,$.parseArgs)(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=y(e,(0,$.parseArgs)(t));return this.optimisticQueryResults.queryLogs(s)}queryJournal(e,t){let s=y(e,(0,$.parseArgs)(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()}}subscribeToConnectionState(e){let t=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(t,e),()=>{this.connectionStateSubscribers.delete(t)}}async mutation(e,t,s){let r=await this.mutationInternal(e,t,s);if(!r.success){if(void 0!==r.errorData)throw g(r,new i.ConvexError(f("mutation",e,r)));throw Error(f("mutation",e,r))}return r.value}async mutationInternal(e,t,s,r){let{mutationPromise:i}=this.enqueueMutation(e,t,s,r);return i}enqueueMutation(e,t,s,r){let i=(0,$.parseArgs)(t);this.tryReportLongDisconnect();let o=this.nextRequestId;if(this._nextRequestId++,void 0!==s){let e=s.optimisticUpdate;if(void 0!==e){let t=t=>{e(t,i)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},s=this.optimisticQueryResults.applyOptimisticUpdate(t,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:s,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let a={type:"Mutation",requestId:o,udfPath:e,componentPath:r,args:[(0,n.convexToJson)(i)]},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 g(s,new i.ConvexError(f("action",e,s)));throw Error(f("action",e,s))}return s.value}async actionInternal(e,t,s){let r=(0,$.parseArgs)(t),i=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let o={type:"Action",requestId:i,udfPath:e,componentPath:s,args:[(0,n.convexToJson)(r)]},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}
2reportMarks(){if(this.debug){let e=function(e){if("undefined"==typeof performance||!performance.getEntriesByName)return[];let t=[];for(let s of en){let r=performance.getEntriesByName(s).filter(e=>"mark"===e.entryType).filter(t=>t.detail.sessionId===e);t.push(...r)}return t.map(eo)}(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-${o.version}`},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 el=Object.defineProperty,ec=(e,t,s)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?el(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s};class ed{constructor(e,t){if(ec(this,"address"),ec(this,"auth"),ec(this,"adminAuth"),ec(this,"encodedTsPromise"),ec(this,"debug"),ec(this,"fetchOptions"),ec(this,"logger"),ec(this,"mutationQueue",[]),ec(this,"isProcessingQueue",!1),"boolean"==typeof t)throw Error("skipConvexDeploymentUrlCheck as the second argument is no longer supported. Please pass an options object, `{ skipConvexDeploymentUrlCheck: true }`.");!0!==(t??{}).skipConvexDeploymentUrlCheck&&(0,$.validateDeploymentUrl)(e),this.logger=t?.logger===!1?new l({verbose:!1}):t?.logger!==!0&&t?.logger?t.logger:c({verbose:!1}),this.address=e,this.debug=!0,this.auth=void 0,this.adminAuth=void 0,t?.auth&&this.setAuth(t.auth)}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,$.parseArgs)(t[0]),r=this.getTimestamp();return await this.queryInner(e,s,{timestampPromise:r})}async getTimestamp(){return this.encodedTsPromise?this.encodedTsPromise:this.encodedTsPromise=this.getTimestampInner()}async getTimestampInner(){let e=s||fetch,t={"Content-Type":"application/json","Convex-Client":`npm-${o.version}`},r=await e(`${this.address}/api/query_ts`,{...this.fetchOptions,method:"POST",headers:t});if(!r.ok)throw Error(await r.text());let{ts:i}=await r.json();return i}async query(e,...t){let s=(0,$.parseArgs)(t[0]);return await this.queryInner(e,s,{})}async queryInner(e,t,r){let a=x(e),u=[(0,n.convexToJson)(t)],h={"Content-Type":"application/json","Convex-Client":`npm-${o.version}`};this.adminAuth?h.Authorization=`Convex ${this.adminAuth}`:this.auth&&(h.Authorization=`Bearer ${this.auth}`);let l=s||fetch,c=r.timestampPromise?await r.timestampPromise:void 0,f=JSON.stringify({path:a,format:"convex_encoded_json",args:u,...c?{ts:c}:{}}),g=c?`${this.address}/api/query_at_ts`:`${this.address}/api/query`,p=await l(g,{...this.fetchOptions,body:f,method:"POST",headers:h});if(!p.ok&&560!==p.status)throw Error(await p.text());let y=await p.json();if(this.debug)for(let e of y.logLines??[])d(this.logger,"info","query",a,e);switch(y.status){case"success":return(0,n.jsonToConvex)(y.value);case"error":if(void 0!==y.errorData)throw ef(y.errorData,new i.ConvexError(y.errorMessage));throw Error(y.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(y)}`)}}async mutationInner(e,t){let r=x(e),a=JSON.stringify({path:r,format:"convex_encoded_json",args:[(0,n.convexToJson)(t)]}),u={"Content-Type":"application/json","Convex-Client":`npm-${o.version}`};this.adminAuth?u.Authorization=`Convex ${this.adminAuth}`:this.auth&&(u.Authorization=`Bearer ${this.auth}`);let h=s||fetch,l=await h(`${this.address}/api/mutation`,{...this.fetchOptions,body:a,method:"POST",headers:u});if(!l.ok&&560!==l.status)throw Error(await l.text());let c=await l.json();if(this.debug)for(let e of c.logLines??[])d(this.logger,"info","mutation",r,e);switch(c.status){case"success":return(0,n.jsonToConvex)(c.value);case"error":if(void 0!==c.errorData)throw ef(c.errorData,new i.ConvexError(c.errorMessage));throw Error(c.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(c)}`)}}async processMutationQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;
2this.mutationQueue.length>0;){let{mutation:e,args:t,resolve:s,reject:r}=this.mutationQueue.shift();try{let r=await this.mutationInner(e,t);s(r)}catch(e){r(e)}}this.isProcessingQueue=!1}}enqueueMutation(e,t){return new Promise((s,r)=>{this.mutationQueue.push({mutation:e,args:t,resolve:s,reject:r}),this.processMutationQueue()})}async mutation(e,...t){let[s,r]=t,i=(0,$.parseArgs)(s);return r?.skipQueue?await this.mutationInner(e,i):await this.enqueueMutation(e,i)}async action(e,...t){let r=(0,$.parseArgs)(t[0]),a=x(e),u=JSON.stringify({path:a,format:"convex_encoded_json",args:[(0,n.convexToJson)(r)]}),h={"Content-Type":"application/json","Convex-Client":`npm-${o.version}`};this.adminAuth?h.Authorization=`Convex ${this.adminAuth}`:this.auth&&(h.Authorization=`Bearer ${this.auth}`);let l=s||fetch,c=await l(`${this.address}/api/action`,{...this.fetchOptions,body:u,method:"POST",headers:h});if(!c.ok&&560!==c.status)throw Error(await c.text());let f=await c.json();if(this.debug)for(let e of f.logLines??[])d(this.logger,"info","action",a,e);switch(f.status){case"success":return(0,n.jsonToConvex)(f.value);case"error":if(void 0!==f.errorData)throw ef(f.errorData,new i.ConvexError(f.errorMessage));throw Error(f.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(f)}`)}}async function(e,t,...r){let a=(0,$.parseArgs)(r[0]),u="string"==typeof e?e:x(e),h=JSON.stringify({componentPath:t,path:u,format:"convex_encoded_json",args:(0,n.convexToJson)(a)}),l={"Content-Type":"application/json","Convex-Client":`npm-${o.version}`};this.adminAuth?l.Authorization=`Convex ${this.adminAuth}`:this.auth&&(l.Authorization=`Bearer ${this.auth}`);let c=s||fetch,f=await c(`${this.address}/api/function`,{...this.fetchOptions,body:h,method:"POST",headers:l});if(!f.ok&&560!==f.status)throw Error(await f.text());let g=await f.json();if(this.debug)for(let e of g.logLines??[])d(this.logger,"info","any",u,e);switch(g.status){case"success":return(0,n.jsonToConvex)(g.value);case"error":if(void 0!==g.errorData)throw ef(g.errorData,new i.ConvexError(g.errorMessage));throw Error(g.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(g)}`)}}}function ef(e,t){return t.data=(0,n.jsonToConvex)(e),t}e.s(["ConvexHttpClient",()=>ed],71482);var eg=Object.defineProperty,ep=(e,t,s)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?eg(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s};if(void 0===r.default)throw Error("Required dependency 'react' not found");class ey{constructor(e,t){if(ep(this,"address"),ep(this,"cachedSync"),ep(this,"listeners"),ep(this,"options"),ep(this,"closed",!1),ep(this,"_logger"),ep(this,"adminAuth"),ep(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===!1?new l({verbose:t?.verbose??!1}):t?.logger!==!0&&t?.logger?t.logger:c({verbose:t?.verbose??!1}),this.options={...t,logger:this._logger}}get url(){return this.address}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,r]=t,i=x(e);return{onUpdate:e=>{let{queryToken:t,unsubscribe:n}=this.sync.subscribe(i,s,r),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(i,s)},localQueryLogs:()=>
2{if(this.cachedSync)return this.cachedSync.localQueryLogs(i,s)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(i,s)}}}prewarmQuery(e){let t=e.extendSubscriptionFor??5e3;setTimeout(this.watchQuery(e.query,e.args||{}).onUpdate(()=>{}),t)}mutation(e,...t){let[s,r]=t,i=x(e);return this.sync.mutation(i,s,r)}action(e,...t){let s=x(e);return this.sync.action(s,...t)}query(e,...t){let s=this.watchQuery(e,...t),r=s.localQueryResult();return void 0!==r?Promise.resolve(r):new Promise((e,t)=>{let r=s.onUpdate(()=>{r();try{e(s.localQueryResult())}catch(e){t(e)}})})}connectionState(){return this.sync.connectionState()}subscribeToConnectionState(e){return this.sync.subscribeToConnectionState(e)}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){for(let t of e){let e=this.listeners.get(t);if(e)for(let t of e)t()}}}let em=r.default.createContext(void 0);function ev(){return(0,r.useContext)(em)}let eb=({client:e,children:t})=>r.default.createElement(em.Provider,{value:e},t);function ew(e,...t){let s="skip"===t[0],i="skip"===t[0]?{}:(0,$.parseArgs)(t[0]),o="string"==typeof e?q(e):e,a=x(o),u=function(e){let t=ev();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,r.useState)(()=>new eA(t));return s.createWatch!==t&&s.setCreateWatch(t),(0,r.useEffect)(()=>()=>s.destroy(),[s]),function({getCurrentValue:e,subscribe:t}){let[s,i]=(0,r.useState)(()=>({getCurrentValue:e,subscribe:t,value:e()})),n=s.value;return(s.getCurrentValue!==e||s.subscribe!==t)&&(n=e(),i({getCurrentValue:e,subscribe:t,value:n})),(0,r.useEffect)(()=>{let s=!1,r=()=>{s||i(s=>{if(s.getCurrentValue!==e||s.subscribe!==t)return s;let r=e();return s.value===r?s:{...s,value:r}})},n=t(r);return r(),()=>{s=!0,n()}},[e,t]),n}((0,r.useMemo)(()=>({getCurrentValue:()=>s.getLocalResults(e),subscribe:t=>(s.setQueries(e),s.subscribe(t))}),[s,e]))}(e,(0,r.useMemo)(()=>(e,s,r)=>t.watchQuery(e,s,r?{journal:r}:{}),[t]))}((0,r.useMemo)(()=>s?{}:{query:{query:o,args:i}},[JSON.stringify((0,n.convexToJson)(i)),a,s])).query;if(u instanceof Error)throw u;return u}function ek(e){let t=(0,r.useContext)(em),s="string"==typeof e?q(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,r.useMemo)(()=>function(e){return t.action(s,e)},[t,x(s)])}var eS=Object.defineProperty,eC=(e,t,s)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?eS(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s};class eA{constructor(e){eC(this,"createWatch"),eC(this,"queries"),eC(this,"listeners"),this.createWatch=e,this.queries={},this.listeners=new Set}setQueries(e){for(let t of Object.keys(e)){let{query:s,args:r}=e[t];if(x(s),void 0===this.queries[t])this.addQuery(t,s,r);else{let e=this.queries[t];(x(s)!==x(e.query)||JSON.stringify((0,n.convexToJson)(r))!==JSON.stringify((0,n.convexToJson)(e.args)))&&(this.removeQuery(t),this.addQuery(t,s,r))}}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 r,{query:i,args:n}=e[s];x(i);let o=this.createWatch(i,n);try{r=o.localQueryResult()}catch(e){if(e instanceof Error)r=e;else throw e}t[s]=r}return t}setCreateWatch(e){for(let t of(this.createWatch=e,Object.keys(this.queries))){let{query:e,args:s,watch:r}=this.queries[t],i=r.journal();this.removeQuery(t),this.addQuery(t,e,s,i)}}destroy(){for(let e of Object.keys(this.queries))this.removeQuery(e);this.listeners=new Set}addQuery(e,t,s,r){if(void 0!==this.queries[e])throw Error(`Tried to add a new query with identifier ${e} when it already exists.`);let i=this.createWatch(t,s,r),n=i.onUpdate(()=>this.notifyListeners());this.queries[e]={query:t,args:s,watch:i,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()}}e.i(6689),Symbol("includePageKeys"),Symbol("page");let eT=(0,r.createContext)(void 0);function eR(){let e=(0,r.useContext)(eT);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 ex({children:e,client:t,useAuth:s}){let{isLoading:i,isAuthenticated:n,fetchAccessToken:o}=s(),[a,u]=(0,r.useState)(null);return i&&null!==a&&u(null),i||n||!1===a||u(!1),r.default.createElement(eT.Provider,{value:{isLoading:null===a,isAuthenticated:n&&(a??!1)}},r.default.createElement(eq,{authProviderAuthenticated:n,fetchAccessToken:o,authProviderLoading:i,client:t,setIsConvexAuthenticated:u}),r.default.createElement(eb,{client:t},e),r.default.createElement(eO,{authProviderAuthenticated:n,fetchAccessToken:o,authProviderLoading:i,client:t,setIsConvexAuthenticated:u}))}function eq({authProviderAuthenticated:e,fetchAccessToken:t,authProviderLoading:s,client:i,setIsConvexAuthenticated:n}){return(0,r.useEffect)(()=>{let s=!0;if(e)return i.setAuth(t,e=>{s&&n(()=>e)}
2),()=>{s=!1,n(e=>!e&&null)}},[e,t,s,i,n]),null}function eO({authProviderAuthenticated:e,fetchAccessToken:t,authProviderLoading:s,client:i,setIsConvexAuthenticated:n}){return(0,r.useEffect)(()=>{if(e)return()=>{i.clearAuth(),n(()=>null)}},[e,t,s,i,n]),null}e.s(["ConvexProviderWithAuth",()=>ex,"useConvexAuth",()=>eR],81958),e.s([],50711)}]);

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.