@01.works/visual-review 0.16.0 → 0.17.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/active-review-mount-CMXKUMnp.js +4 -0
- package/dist/cli.js +39 -6
- package/dist/{convex-runtime-B43ycxNU.js → convex-runtime-CpgGS5hl.js} +2 -2
- package/dist/{cursor-chat-repository-DWfIYLEK.js → cursor-chat-repository-CaF-65Xc.js} +1 -1
- package/dist/{hosted-runtime-DpU5J79N.js → hosted-runtime--Sa_y6as.js} +2 -2
- package/dist/index.d.ts +14 -2
- package/dist/index.js +1 -1
- package/dist/{install-DmtmFNiz.js → install-9w7UR92S.js} +1 -1
- package/dist/mcp.js +8 -8
- package/dist/react.js +1 -1
- package/package.json +1 -1
- package/dist/active-review-mount-A2iVUJfc.js +0 -2106
package/dist/cli.js
CHANGED
|
@@ -111,7 +111,8 @@ function createHandoffPayload(payload) {
|
|
|
111
111
|
source: payload.source,
|
|
112
112
|
componentStack: payload.componentStack,
|
|
113
113
|
stale: payload.stale,
|
|
114
|
-
replies: payload.replies
|
|
114
|
+
replies: payload.replies,
|
|
115
|
+
...payload.replyContext ? { replyContext: payload.replyContext } : {}
|
|
115
116
|
};
|
|
116
117
|
}
|
|
117
118
|
function createBoundedPayload(input) {
|
|
@@ -146,11 +147,18 @@ function sanitizePayload(input, caps, forceTruncated = false) {
|
|
|
146
147
|
const rawStack = array(root.componentStack);
|
|
147
148
|
const rawReplies = array(root.replies);
|
|
148
149
|
const rawElements = array(target.elements);
|
|
150
|
+
const inheritedReplyContext = record(root.replyContext);
|
|
149
151
|
if (rawStack.length > caps.stackFrames || rawReplies.length > caps.replies) {
|
|
150
152
|
state.truncated = true;
|
|
151
153
|
}
|
|
152
154
|
const elements = sanitizeTargetElements(rawElements, caps, state);
|
|
153
155
|
const firstElement = elements[0];
|
|
156
|
+
const selectedReplies = caps.replies <= 0 ? [] : rawReplies.slice(-caps.replies);
|
|
157
|
+
const totalReplyCount = inheritedReplyContext.totalCount === null ? null : Number.isSafeInteger(inheritedReplyContext.totalCount) && inheritedReplyContext.totalCount >= rawReplies.length ? inheritedReplyContext.totalCount : rawReplies.length;
|
|
158
|
+
const upstreamReplyWindowTruncated = inheritedReplyContext.hasMore === true;
|
|
159
|
+
const latestReplyAvailable = rawReplies.length === 0 || inheritedReplyContext.latestIncluded !== false;
|
|
160
|
+
const latestIncluded = latestReplyAvailable && (rawReplies.length === 0 || selectedReplies.length > 0);
|
|
161
|
+
if (upstreamReplyWindowTruncated || !latestIncluded) state.truncated = true;
|
|
154
162
|
const sanitized = {
|
|
155
163
|
schemaVersion: 3,
|
|
156
164
|
trust: trustMetadata(false, false),
|
|
@@ -188,14 +196,28 @@ function sanitizePayload(input, caps, forceTruncated = false) {
|
|
|
188
196
|
componentStack: firstElement?.componentStack ?? rawStack.slice(0, caps.stackFrames).map((frame) => sanitizeSourceLocation(frame, caps, state)).filter((frame) => frame !== null),
|
|
189
197
|
provenance: sanitizeProvenance(root.provenance, caps, state),
|
|
190
198
|
stale: root.stale === null || typeof root.stale === "boolean" ? root.stale : null,
|
|
191
|
-
replies:
|
|
199
|
+
replies: selectedReplies.map((value, index) => {
|
|
192
200
|
const reply = record(value);
|
|
193
201
|
return {
|
|
194
202
|
author: sanitizeText(reply.author, caps.author, state),
|
|
195
|
-
|
|
203
|
+
// The newest reply is the one an agent must not lose before completing
|
|
204
|
+
// work. Preserve its full domain-bounded body even when older context is
|
|
205
|
+
// compacted to fit the export budget.
|
|
206
|
+
body: sanitizeText(
|
|
207
|
+
reply.body,
|
|
208
|
+
index === selectedReplies.length - 1 ? Math.max(caps.replyBody, 2e4) : caps.replyBody,
|
|
209
|
+
state
|
|
210
|
+
),
|
|
196
211
|
createdAt: sanitizeTimestamp(reply.createdAt, state)
|
|
197
212
|
};
|
|
198
|
-
})
|
|
213
|
+
}),
|
|
214
|
+
replyContext: {
|
|
215
|
+
totalCount: totalReplyCount,
|
|
216
|
+
shownCount: selectedReplies.length,
|
|
217
|
+
hasMore: upstreamReplyWindowTruncated || totalReplyCount === null || totalReplyCount > selectedReplies.length,
|
|
218
|
+
window: "latest",
|
|
219
|
+
latestIncluded
|
|
220
|
+
}
|
|
199
221
|
};
|
|
200
222
|
if (!(root.stale === null || typeof root.stale === "boolean")) {
|
|
201
223
|
state.truncated = true;
|
|
@@ -466,7 +488,14 @@ function emergencyPayload() {
|
|
|
466
488
|
componentStack: [],
|
|
467
489
|
provenance: null,
|
|
468
490
|
stale: null,
|
|
469
|
-
replies: []
|
|
491
|
+
replies: [],
|
|
492
|
+
replyContext: {
|
|
493
|
+
totalCount: null,
|
|
494
|
+
shownCount: 0,
|
|
495
|
+
hasMore: true,
|
|
496
|
+
window: "latest",
|
|
497
|
+
latestIncluded: false
|
|
498
|
+
}
|
|
470
499
|
};
|
|
471
500
|
}
|
|
472
501
|
function createEmergencyMarkdown() {
|
|
@@ -1908,6 +1937,10 @@ function summarize(payload) {
|
|
|
1908
1937
|
element: element ? `${element.tagName.toLowerCase()} ${element.selector}` : target.selector,
|
|
1909
1938
|
...describeSource(source, payload.componentStack),
|
|
1910
1939
|
replyCount: payload.replies.length,
|
|
1940
|
+
...payload.replyContext ? {
|
|
1941
|
+
totalReplyCount: payload.replyContext.totalCount,
|
|
1942
|
+
hasMoreReplies: payload.replyContext.hasMore
|
|
1943
|
+
} : {},
|
|
1911
1944
|
imageCount: payload.images?.length ?? 0,
|
|
1912
1945
|
// A capture taken against a build that is no longer deployed can point at
|
|
1913
1946
|
// a line that has since moved; saying so beats a confident wrong file.
|
|
@@ -2019,7 +2052,7 @@ Revokes the remote session before removing the local credential unless --local-o
|
|
|
2019
2052
|
`
|
|
2020
2053
|
};
|
|
2021
2054
|
var CLI_COMMAND_NAMES = Object.keys(CLI_HELP_TOPICS);
|
|
2022
|
-
var CLI_VERSION = "0.
|
|
2055
|
+
var CLI_VERSION = "0.17.1";
|
|
2023
2056
|
var CliUsageError = class extends Error {
|
|
2024
2057
|
};
|
|
2025
2058
|
function parseCliCommand(args) {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{i as e,n as t,r as n}from"./src-IC5X3zme.js";for(var r=[],i=[],a=Uint8Array,o=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,s=0,c=o.length;s<c;++s)r[s]=o[s],i[o.charCodeAt(s)]=s;i[45]=62,i[95]=63;function l(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function u(e,t,n){return(t+n)*3/4-n}function d(e){var t,n=l(e),r=n[0],o=n[1],s=new a(u(e,r,o)),c=0,d=o>0?r-4:r,f;for(f=0;f<d;f+=4)t=i[e.charCodeAt(f)]<<18|i[e.charCodeAt(f+1)]<<12|i[e.charCodeAt(f+2)]<<6|i[e.charCodeAt(f+3)],s[c++]=t>>16&255,s[c++]=t>>8&255,s[c++]=t&255;return o===2&&(t=i[e.charCodeAt(f)]<<2|i[e.charCodeAt(f+1)]>>4,s[c++]=t&255),o===1&&(t=i[e.charCodeAt(f)]<<10|i[e.charCodeAt(f+1)]<<4|i[e.charCodeAt(f+2)]>>2,s[c++]=t>>8&255,s[c++]=t&255),s}function f(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[e&63]}function ee(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(f(r));return i.join(``)}function p(e){for(var t,n=e.length,i=n%3,a=[],o=16383,s=0,c=n-i;s<c;s+=o)a.push(ee(e,s,s+o>c?c:s+o));return i===1?(t=e[n-1],a.push(r[t>>2]+r[t<<4&63]+`==`)):i===2&&(t=(e[n-2]<<8)+e[n-1],a.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+`=`)),a.join(``)}function m(e){if(e===void 0)return{};if(!ne(e))throw Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function te(e){if(e===void 0)throw Error(`Client created with undefined deployment address. If you used an environment variable, check that it's set.`);if(typeof e!=`string`)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 ne(e){let t=typeof e==`object`,n=Object.getPrototypeOf(e),r=n===null||n===Object.prototype||n?.constructor?.name===`Object`;return t&&r}const h=BigInt(`-9223372036854775808`),g=BigInt(`9223372036854775807`),_=BigInt(`0`),re=BigInt(`8`),ie=BigInt(`256`),v=`This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.`;var ae=class{[Symbol.toPrimitive](e){if(e===`string`)return this.toString();throw Error(v)}valueOf(){throw Error(v)}toJSON(){throw Error(v)}toString(){return`[unresolved commit timestamp]`}};const oe=new ae;function se(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}function ce(e){e<_&&(e-=h+h);let t=e.toString(16);t.length%2==1&&(t=`0`+t);let n=new Uint8Array(new ArrayBuffer(8)),r=0;for(let i of t.match(/.{2}/g).reverse())n.set([parseInt(i,16)],r++),e>>=re;return p(n)}function le(e){let t=d(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let n=_,r=_;for(let e of t)n+=BigInt(e)*ie**r,r++;return n>g&&(n+=h+h),n}function ue(e){if(e<h||g<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),p(new Uint8Array(t))}function de(e){let t=d(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}const fe=DataView.prototype.setBigInt64?ue:ce,pe=DataView.prototype.getBigInt64?de:le,me=1024;function y(e){if(e.length>me)throw Error(`Field name ${e} exceeds maximum field name length ${me}.`);if(e.startsWith(`$`))throw Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<32||n>=127)throw Error(`Field name ${e} has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function b(e){if(e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`)return e;if(Array.isArray(e))return e.map(e=>b(e));if(typeof e!=`object`)throw Error(`Unexpected type of ${e}`);let t=Object.entries(e);if(t.length===1){let n=t[0][0];if(n===`$bytes`){if(typeof e.$bytes!=`string`)throw Error(`Malformed $bytes field on ${e}`);return d(e.$bytes).buffer}if(n===`$integer`){if(typeof e.$integer!=`string`)throw Error(`Malformed $integer field on ${e}`);return pe(e.$integer)}if(n===`$float`){if(typeof e.$float!=`string`)throw Error(`Malformed $float field on ${e}`);let t=d(e.$float);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $float`);let n=new DataView(t.buffer).getFloat64(0,!0);if(!se(n))throw Error(`Float ${n} should be encoded as a number`);return n}if(n===`$commitTs`){if(e.$commitTs!==null)throw Error(`Malformed $commitTs field on ${e}`);return oe}if(n===`$set`)throw Error(`Received a Set which is no longer supported as a Convex type.`);if(n===`$map`)throw Error(`Received a Map which is no longer supported as a Convex type.`)}let n={};for(let[t,r]of Object.entries(e))y(t),n[t]=b(r);return n}function x(e){let t=JSON.stringify(e,(e,t)=>t===void 0?`undefined`:typeof t==`bigint`?`${t.toString()}n`:t);if(t.length>16384){let e=16370,n=t.codePointAt(e-1);return n!==void 0&&n>65535&&--e,t.substring(0,e)+`[...truncated]`}return t}function S(e,t,n,r){if(e===void 0){let e=n&&` (present at path ${n} in original object ${x(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(e===null)return e;if(typeof e==`bigint`){if(e<h||g<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:fe(e)}}if(typeof e==`number`){if(se(e)){let t=new ArrayBuffer(8);return new DataView(t).setFloat64(0,e,!0),{$float:p(new Uint8Array(t))}}return e}if(typeof e==`boolean`||typeof e==`string`)return e;if(e instanceof ArrayBuffer)return{$bytes:p(new Uint8Array(e))};if(e instanceof ae)return{$commitTs:null};if(Array.isArray(e))return e.map((e,r)=>S(e,t,n+`[${r}]`,!1));if(e instanceof Set)throw Error(C(n,`Set`,[...e],t));if(e instanceof Map)throw Error(C(n,`Map`,[...e],t));if(!ne(e)){let r=e?.constructor?.name,i=r?`${r} `:``;throw Error(C(n,i,e,t))}let i={},a=Object.entries(e);a.sort(([e,t],[n,r])=>e===n?0:e<n?-1:1);for(let[e,o]of a)o===void 0?r&&(y(e),i[e]=he(o,t,n+`.${e}`)):(y(e),i[e]=S(o,t,n+`.${e}`,!1));return i}function C(e,t,n,r){return e?`${t}${x(n)} is not a supported Convex type (present at path ${e} in original object ${x(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${x(n)} is not a supported Convex type.`}function he(e,t,n){if(e===void 0)return{$undefined:null};if(t===void 0)throw Error(`Programming error. Current value is ${x(e)} but original value is undefined`);return S(e,t,n,!1)}function w(e){return S(e,e,``,!1)}var ge=Object.defineProperty,_e=(e,t,n)=>t in e?ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,T=(e,t,n)=>_e(e,typeof t==`symbol`?t:t+``,n),ve,ye;const be=Symbol.for(`ConvexError`);var E=class extends (ye=Error,ve=be,ye){constructor(e){super(typeof e==`string`?e:x(e)),T(this,`name`,`ConvexError`),T(this,`data`),T(this,ve,!0),this.data=e}};const xe=`1.45.0`,D=Symbol.for(`functionName`),Se=Symbol.for(`toReferencePath`);function Ce(e){return e[Se]??null}function we(e){return e.startsWith(`function://`)}function Te(e){let t;if(typeof e==`string`)t=we(e)?{functionHandle:e}:{name:e};else if(e[D])t={name:e[D]};else{let n=Ce(e);if(!n)throw Error(`${e} is not a functionReference`);t={reference:n}}return t}function O(e){let t=Te(e);if(t.name===void 0)throw t.functionHandle===void 0?t.reference===void 0?Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(t)}`):Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${t.reference}`):Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${t.functionHandle}`);if(typeof e==`string`)return e;let n=e[D];if(!n)throw Error(`${e} is not a functionReference`);return n}function k(e){return{[D]:e}}function Ee(e=[]){return new Proxy({},{get(t,n){if(typeof n==`string`)return Ee([...e,n]);if(n===D){if(e.length<2){let t=[`api`,...e].join(`.`);throw Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${t}\``)}let t=e.slice(0,-1).join(`/`),n=e[e.length-1];return n==="default"?t:t+`:`+n}if(n===Symbol.toStringTag)return`FunctionReference`}})}Ee();const A=Object.freeze({resolveSession:k(`reviews:resolveSession`),pageSnapshot:k(`reviews:pageSnapshot`),projectSnapshot:k(`reviews:projectSnapshot`),markFeedbackRead:k(`reviews:markFeedbackRead`),createComment:k(`reviews:createComment`),createReply:k(`reviews:createReply`),setCommentStatus:k(`reviews:setCommentStatus`),setCommentLabels:k(`reviews:setCommentLabels`),moveCommentPin:k(`reviews:moveCommentPin`),presenceList:k(`presence:list`),presenceUpdate:k(`presence:update`),presenceDisconnect:k(`presence:disconnect`),screenshotUploadUrl:k(`screenshots:generateUploadUrl`),screenshotCommit:k(`screenshots:commitUpload`),screenshotDiscard:k(`screenshots:discardUpload`)});Object.freeze({catalog:k(`owners:catalog`),listProjects:k(`owners:listProjects`),projectOverview:k(`owners:projectOverview`),feedbackPage:k(`owners:feedbackPage`),markFeedbackRead:k(`owners:markFeedbackRead`),createProject:k(`owners:createProject`),createProjectWithOrigins:k(`owners:createProjectWithOrigins`),configureProjectLinkAccess:k(`owners:configureProjectLinkAccess`),setProjectBranding:k(`owners:setProjectBranding`),deleteProject:k(`owners:deleteProject`),addOrigin:k(`owners:addOrigin`),removeOrigin:k(`owners:removeOrigin`),replaceOrigins:k(`owners:replaceOrigins`),createPage:k(`owners:createPage`),deletePage:k(`owners:deletePage`),upsertPageBuild:k(`owners:upsertPageBuild`),createInvitation:k(`owners:createInvitation`),revokeInvitation:k(`owners:revokeInvitation`),revokeReviewerAccess:k(`owners:revokeReviewerAccess`),setCommentStatus:k(`owners:setCommentStatus`),setCommentLabels:k(`owners:setCommentLabels`),setProjectFeedbackLabels:k(`owners:setProjectFeedbackLabels`),createReply:k(`owners:createReply`),deleteComment:k(`owners:deleteComment`),deleteReply:k(`owners:deleteReply`),screenshotDownload:k(`screenshots:ownerDownload`)});var De=class{client;session;#e;#t;#n;constructor(e,t,n){this.client=e,this.session=t,this.#e=M(n.invitationId??t.invitationId,`invitationId`),this.#t=je(n.origin),this.#n=n.fetch??globalThis.fetch.bind(globalThis)}async attachScreenshot(e,t,n){return this.attachImage(e,t,n,{id:crypto.randomUUID(),source:`capture`})}async attachImage(e,t,n,r){M(e,`pageId`);let i=M(t,`commentId`),a=M(r.id,`image id`);if(n.bytes.byteLength===0||n.bytes.byteLength>15e5)throw Error(`Image size is invalid`);let o={commentId:i,imageId:a,source:r.source,...r.replyId===void 0?{}:{replyId:M(r.replyId,`reply id`)}},s=await this.client.mutation(A.screenshotUploadUrl,{...this.#r(),...o});if(`committed`in s)return;let c=await this.#n(s.uploadUrl,{method:`POST`,headers:{"content-type":n.contentType},body:Oe(n.bytes)});if(!c.ok)throw Error(`Image upload failed`);let l=await c.json();if(typeof l.storageId!=`string`||!l.storageId)throw Error(`Image upload returned an invalid storage ID`);try{await this.client.action(A.screenshotCommit,{...this.#r(),...o,grantId:s.grantId,storageId:l.storageId,contentType:n.contentType,width:n.width,height:n.height})}catch(e){throw await this.client.mutation(A.screenshotDiscard,{...this.#r(),...o,grantId:s.grantId,storageId:l.storageId}).catch(()=>void 0),e}}async getSnapshot(e){return Ae(await this.client.query(A.pageSnapshot,{...this.#r(),pageId:M(e,`pageId`)}))}async moveCommentPin(e,t,n,r){return this.client.mutation(A.moveCommentPin,{...this.#r(),pageId:M(e,`pageId`),commentId:M(t,`commentId`),anchorJson:JSON.stringify(n),expectedRevision:r})}async getProjectSnapshot(e){return this.#i(e),structuredClone(await this.client.query(A.projectSnapshot,{...this.#r(),projectId:e}))}async markFeedbackRead(e){return this.client.mutation(A.markFeedbackRead,{...this.#r(),commentId:M(e,`commentId`)})}subscribe(e,t,n){return this.client.onUpdate(A.pageSnapshot,{...this.#r(),pageId:M(e,`pageId`)},e=>t(Ae(e)),e=>n?.(j(e)))}subscribeProject(e,t,n){return this.#i(e),this.client.onUpdate(A.projectSnapshot,{...this.#r(),projectId:e},e=>t(structuredClone(e)),e=>n?.(j(e)))}async mutate(r,i){switch(i.type){case`comment.upsert`:{let a=i.comment;if(a.pageId!==r)throw Error(`Comment page mismatch`);if(a.authorId!==this.session.reviewerId)throw Error(`Comment author mismatch`);if(a.status!==`open`||a.resolvedAt!==void 0||a.resolvedById!==void 0||a.createdAt!==a.updatedAt)throw Error(`Only new open comments can be created by a reviewer`);let o=n(a.body).trim(),s=t(a.target),c=a.scope===void 0?void 0:e(a.scope);await this.client.mutation(A.createComment,{...this.#r(),pageId:r,commentId:a.id,body:o,targetJson:JSON.stringify(s.publicTarget),sourceContextJson:s.sourceContextJson,...c===void 0?{}:{scopeJson:JSON.stringify(c)}});return}case`reply.upsert`:{let e=i.reply;if(e.authorId!==this.session.reviewerId)throw Error(`Reply author mismatch`);if(e.createdAt!==e.updatedAt)throw Error(`Reply edits require an owner command`);await this.client.mutation(A.createReply,{...this.#r(),commentId:e.commentId,replyId:e.id,body:n(e.body,`Reply body`).trim(),...i.requestReopen?{requestReopen:!0}:{}});return}case`comment.delete`:throw Error(`Comment deletion requires an owner command`);case`reply.delete`:throw Error(`Reply deletion requires an owner command`)}}async updateCommentStatus(e,t){M(e,`pageId`);let n=await this.client.mutation(A.setCommentStatus,{...this.#r(),commentId:M(t.commentId,`commentId`),status:t.status,expectedWorkflowRevision:t.expectedWorkflowRevision,expectedThreadRevision:t.expectedThreadRevision});return{commentId:n.commentId,status:n.status,workflowRevision:n.workflowRevision,threadRevision:n.threadRevision,updatedAt:n.updatedAt,...n.resolvedAt===null?{}:{resolvedAt:n.resolvedAt}}}async updateCommentLabels(e,t){M(e,`pageId`);let n=await this.client.mutation(A.setCommentLabels,{...this.#r(),commentId:M(t.commentId,`commentId`),labels:t.labels.map(e=>M(e,`label`)),expectedWorkflowRevision:t.expectedWorkflowRevision,expectedThreadRevision:t.expectedThreadRevision});return structuredClone(n)}#r(){return{invitationId:this.#e,origin:this.#t}}#i(e){if(!e.trim()||e!==this.session.projectId)throw Error(`Project does not belong to the reviewer session`)}};function Oe(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function j(e){let t=ke(e);return t===`UNAUTHENTICATED`||t===`INVITATION_EXPIRED`?{type:`access-lost`,code:`session-expired`,recovery:`reauthenticate`,clearSnapshot:!0}:t===`INVITATION_REVOKED`||t===`MEMBERSHIP_REVOKED`?{type:`access-lost`,code:`membership-revoked`,recovery:`reauthenticate`,clearSnapshot:!0}:t===`ORIGIN_MISMATCH`||t===`ORIGIN_NOT_ALLOWED`||t===`INVITATION_REQUIRED`?{type:`access-lost`,code:`permission-denied`,recovery:`reauthenticate`,clearSnapshot:!0}:{type:`error`,code:e instanceof Error?`transport`:`unknown`,recovery:`retry`,clearSnapshot:!0}}function ke(e){if(!e||typeof e!=`object`)return;let t=e.data;if(typeof t==`string`)return t;if(t&&typeof t==`object`){let e=t.code;if(typeof e==`string`)return e}}function Ae(e){return structuredClone(e)}function M(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function je(e){let t=M(e,`origin`);try{let e=new URL(t);if(e.origin!==t)throw Error();return e.origin}catch{throw Error(`A valid browser origin is required`)}}var Me=Object.defineProperty,Ne=(e,t,n)=>t in e?Me(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Pe=(e,t,n)=>Ne(e,typeof t==`symbol`?t:t+``,n);function Fe(e){switch(e){case`query`:return`Q`;case`mutation`:return`M`;case`action`:return`A`;case`any`:return`?`}}var Ie=class{constructor(e){Pe(this,`_onLogLineFuncs`),Pe(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&&this._onLogLineFuncs[t]!==void 0;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 Le(e){let t=new Ie(e);return t.addLogLineListener((e,...t)=>{switch(e){case`debug`:console.debug(...t);break;case`info`:console.log(...t);break;case`warn`:console.warn(...t);break;case`error`:console.error(...t);break;default:console.log(...t)}}),t}function Re(e){return new Ie(e)}function N(e,t,n,r,i){let a=Fe(n);if(typeof i==`object`&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),t===`info`){let t=i.match(/^\[.*?\] /);if(t===null){e.error(`[CONVEX ${a}(${r})] Could not parse console.log`);return}let n=i.slice(1,t[0].length-2),o=i.slice(t[0].length);e.log(`%c[CONVEX ${a}(${r})] [${n}]`,`color:rgb(0, 145, 255)`,o)}else e.error(`[CONVEX ${a}(${r})] ${i}`)}function ze(e,t){let n=`[CONVEX FATAL ERROR] ${t}`;return e.error(n),Error(n)}function P(e,t,n){return`[CONVEX ${Fe(e)}(${t})] ${n.errorMessage}
|
|
2
|
-
Called by client`}function F(e,t){return t.data=e.errorData,t}function I(e){let t=e.split(`:`),n,r;return t.length===1?(n=t[0],r=`default`):(n=t.slice(0,t.length-1).join(`:`),r=t[t.length-1]),n.endsWith(`.js`)&&(n=n.slice(0,-3)),`${n}:${r}`}function L(e,t){return JSON.stringify({udfPath:I(e),args:w(t)})}function Be(e,t,n){let{initialNumItems:r,id:i}=n;return JSON.stringify({type:`paginated`,udfPath:I(e),args:w(t),options:w({initialNumItems:r,id:i})})}function Ve(e){return JSON.parse(e).type===`paginated`}var He=Object.defineProperty,Ue=(e,t,n)=>t in e?He(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,R=(e,t,n)=>Ue(e,typeof t==`symbol`?t:t+``,n),We=class{constructor(){R(this,`nextQueryId`),R(this,`querySetVersion`),R(this,`querySet`),R(this,`queryIdToToken`),R(this,`identityVersion`),R(this,`auth`),R(this,`outstandingQueriesOlderThanRestart`),R(this,`outstandingAuthOlderThanRestart`),R(this,`paused`),R(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 this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,t,n,r){let i=I(e),a=L(i,t),o=this.querySet.get(a);if(o!==void 0)return o.numSubscribers+=1,{queryToken:a,modification:null,unsubscribe:()=>this.removeSubscriber(a)};{let e=this.nextQueryId++,o={id:e,canonicalizedUdfPath:i,args:t,numSubscribers:1,journal:n,componentPath:r};this.querySet.set(a,o),this.queryIdToToken.set(e,a);let s=this.querySetVersion,c=this.querySetVersion+1,l={type:`Add`,queryId:e,udfPath:i,args:[w(t)],journal:n,componentPath:r};return this.paused?this.pendingQuerySetModifications.set(e,l):this.querySetVersion=c,{queryToken:a,modification:{type:`ModifyQuerySet`,baseVersion:s,newVersion:c,modifications:[l]},unsubscribe:()=>this.removeSubscriber(a)}}}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(e!==void 0){let n=this.queryIdToToken.get(t.queryId);n!==void 0&&(this.querySet.get(n).journal=e)}break}case`QueryRemoved`:this.outstandingQueriesOlderThanRestart.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}}queryId(e,t){let n=L(I(e),t),r=this.querySet.get(n);return r===void 0?null:r.id}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 n={tokenType:`Admin`,value:e,impersonating:t};this.auth=n;let r=this.identityVersion;return this.paused||(this.identityVersion=r+1),{type:`Authenticate`,baseVersion:r,...n}}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(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let e=[];for(let t of this.querySet.values()){let n={type:`Add`,queryId:t.id,udfPath:t.canonicalizedUdfPath,args:[w(t.args)],journal:t.journal,componentPath:t.componentPath};e.push(n),this.outstandingQueriesOlderThanRestart.add(t.id)}this.querySetVersion=1;let t={type:`ModifyQuerySet`,baseVersion:0,newVersion:1,modifications:e};if(!this.auth)return this.identityVersion=0,[t,void 0];this.outstandingAuthOlderThanRestart=!0;let n={type:`Authenticate`,baseVersion:0,...this.auth};return this.identityVersion=1,[t,n]}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=this.auth===void 0?void 0:{type:`Authenticate`,baseVersion:this.identityVersion++,...this.auth};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,null;{this.querySet.delete(e),this.queryIdToToken.delete(t.id),this.outstandingQueriesOlderThanRestart.delete(t.id);let n=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:n,newVersion:r,modifications:[i]}}}},Ge=Object.defineProperty,Ke=(e,t,n)=>t in e?Ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,z=(e,t,n)=>Ke(e,typeof t==`symbol`?t:t+``,n),qe=class{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,z(this,`inflightRequests`),z(this,`requestsOlderThanRestart`),z(this,`inflightMutationsCount`,0),z(this,`inflightActionsCount`,0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,t){let n=new Promise(n=>{let r=t?`Requested`:`NotSent`;this.inflightRequests.set(e.requestId,{message:e,status:{status:r,requestedAt:new Date,onResult:n}}),e.type===`Mutation`?this.inflightMutationsCount++:e.type===`Action`&&this.inflightActionsCount++});return this.markConnectionStateDirty(),n}onResponse(e){let t=this.inflightRequests.get(e.requestId);if(t===void 0||t.status.status===`Completed`)return null;let n=t.message.type===`Mutation`?`mutation`:`action`,r=t.message.udfPath;for(let t of e.logLines)N(this.logger,`info`,n,r,t);let i=t.status,a,o;if(e.success)a={success:!0,logLines:e.logLines,value:b(e.result)},o=()=>i.onResult(a);else{let t=e.result,{errorData:s}=e;N(this.logger,`error`,n,r,t),a={success:!1,errorMessage:t,errorData:s===void 0?void 0:b(s),logLines:e.logLines},o=()=>i.onResult(a)}return e.type===`ActionResponse`||!e.success?(o(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),t.message.type===`Action`?this.inflightActionsCount--:t.message.type===`Mutation`&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:a}):(t.status={status:`Completed`,result:a,ts:e.ts,onResolve:o},null)}removeCompleted(e){let t=new Map;for(let[n,r]of this.inflightRequests.entries()){let i=r.status;i.status===`Completed`&&i.ts.lessThanOrEqual(e)&&(i.onResolve(),t.set(n,i.result),r.message.type===`Mutation`?this.inflightMutationsCount--:r.message.type===`Action`&&this.inflightActionsCount--,this.inflightRequests.delete(n),this.requestsOlderThanRestart.delete(n))}return t.size>0&&this.markConnectionStateDirty(),t}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());let e=[];for(let[t,n]of this.inflightRequests){if(n.status.status===`NotSent`){n.status.status=`Requested`,e.push(n.message);continue}if(n.message.type===`Mutation`)e.push(n.message);else if(n.message.type===`Action`){if(this.inflightRequests.delete(t),this.requestsOlderThanRestart.delete(t),this.inflightActionsCount--,n.status.status===`Completed`)throw Error(`Action should never be in 'Completed' state`);n.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(t.status.status===`NotSent`){t.status.status=`Requested`,e.push(t.message);continue}return e}hasIncompleteRequests(){for(let e of this.inflightRequests.values())if(e.status.status===`Requested`)return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(let t of this.inflightRequests.values())t.status.status!==`Completed`&&t.status.requestedAt.getTime()<e&&(e=t.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}},Je=Object.defineProperty,Ye=(e,t,n)=>t in e?Je(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,B=(e,t,n)=>Ye(e,typeof t==`symbol`?t:t+``,n),Xe=class e{constructor(e){B(this,`queryResults`),B(this,`modifiedQueries`),this.queryResults=e,this.modifiedQueries=[]}getQuery(t,...n){let r=m(n[0]),i=O(t),a=this.queryResults.get(L(i,r));if(a!==void 0)return e.queryValue(a.result)}getAllQueries(t){let n=[],r=O(t);for(let t of this.queryResults.values())t.udfPath===I(r)&&n.push({args:t.args,value:e.queryValue(t.result)});return n}setQuery(e,t,n){let r=m(t),i=O(e),a=L(i,r),o;o=n===void 0?void 0:{success:!0,value:n,logLines:[]};let s={udfPath:i,args:r,result:o};this.queryResults.set(a,s),this.modifiedQueries.push(a)}static queryValue(e){if(e!==void 0&&e.success)return e.value}},Ze=class{constructor(){B(this,`queryResults`),B(this,`optimisticUpdates`),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,t){this.optimisticUpdates=this.optimisticUpdates.filter(e=>!t.has(e.mutationId));let n=this.queryResults;this.queryResults=new Map(e);let r=new Xe(this.queryResults);for(let e of this.optimisticUpdates)e.update(r);let i=[];for(let[e,t]of this.queryResults){let r=n.get(e);(r===void 0||r.result!==t.result)&&i.push(e)}return i}applyOptimisticUpdate(e,t){this.optimisticUpdates.push({update:e,mutationId:t});let n=new Xe(this.queryResults);return e(n),n.modifiedQueries}rawQueryResult(e){let t=this.queryResults.get(e);if(t!==void 0)return t.result}queryResult(e){let t=this.queryResults.get(e);if(t===void 0)return;let n=t.result;if(n!==void 0){if(n.success)return n.value;throw n.errorData===void 0?Error(P(`query`,t.udfPath,n)):F(n,new E(P(`query`,t.udfPath,n)))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}},Qe=Object.defineProperty,$e=(e,t,n)=>t in e?Qe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,V=(e,t,n)=>$e(e,typeof t==`symbol`?t:t+``,n),H=class e{constructor(e,t){V(this,`low`),V(this,`high`),V(this,`__isUnsignedLong__`),this.low=e|0,this.high=t|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(t){return new e(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24)}toBytesLE(){let e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(t){return isNaN(t)||t<0?et:t>=nt?rt:new e(t%U|0,t/U|0)}toString(){return(BigInt(this.high)*BigInt(U)+BigInt(this.low)).toString()}equals(t){return e.isLong(t)||(t=e.fromValue(t)),this.high>>>31==1&&t.high>>>31==1?!1:this.high===t.high&&this.low===t.low}notEquals(e){return!this.equals(e)}comp(t){return e.isLong(t)||(t=e.fromValue(t)),this.equals(t)?0:t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(t){return typeof t==`number`?e.fromNumber(t):new e(t.low,t.high)}};const et=new H(0,0),tt=65536,U=tt*tt,nt=U*U,rt=new H(-1,-1);var it=Object.defineProperty,at=(e,t,n)=>t in e?it(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,W=(e,t,n)=>at(e,typeof t==`symbol`?t:t+``,n),ot=class{constructor(e,t){W(this,`version`),W(this,`remoteQuerySet`),W(this,`queryPath`),W(this,`logger`),this.version={querySet:0,ts:H.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 n of t.logLines)N(this.logger,`info`,`query`,e,n);let n=b(t.value??null);this.remoteQuerySet.set(t.queryId,{success:!0,value:n,logLines:t.logLines});break}case`QueryFailed`:{let e=this.queryPath(t.queryId);if(e)for(let n of t.logLines)N(this.logger,`info`,`query`,e,n);let{errorData:n}=t;this.remoteQuerySet.set(t.queryId,{success:!1,errorMessage:t.errorMessage,errorData:n===void 0?void 0:b(n),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 G(e){let t=d(e);return H.fromBytesLE(Array.from(t))}function st(e){return p(new Uint8Array(e.toBytesLE()))}function ct(e){switch(e.type){case`FatalError`:case`AuthError`:case`ActionResponse`:case`TransitionChunk`:case`Ping`:return{...e};case`MutationResponse`:return e.success?{...e,ts:G(e.ts)}:{...e};case`Transition`:return{...e,startVersion:{...e.startVersion,ts:G(e.startVersion.ts)},endVersion:{...e.endVersion,ts:G(e.endVersion.ts)}}}}function lt(e){switch(e.type){case`Authenticate`:case`ModifyQuerySet`:case`Mutation`:case`Action`:case`Event`:return{...e};case`Connect`:return e.maxObservedTimestamp===void 0?{...e,maxObservedTimestamp:void 0}:{...e,maxObservedTimestamp:st(e.maxObservedTimestamp)}}}var ut=Object.defineProperty,dt=(e,t,n)=>t in e?ut(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,K=(e,t,n)=>dt(e,typeof t==`symbol`?t:t+``,n);let q;function J(){return q===void 0&&(q=Date.now()),typeof performance>`u`||!performance.now?Date.now():Math.round(q+performance.now())}function ft(){return`t=${Math.round((J()-q)/100)/10}s`}const pt={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}};function mt(e){if(e===void 0)return`Unknown`;for(let t of Object.keys(pt))if(e.startsWith(t))return t;return`Unknown`}var ht=class{constructor(e,t,n,r,i,a){this.markConnectionStateDirty=i,this.debug=a,K(this,`socket`),K(this,`connectionCount`),K(this,`_hasEverConnected`,!1),K(this,`lastCloseReason`),K(this,`transitionChunkBuffer`,null),K(this,`defaultInitialBackoff`),K(this,`maxBackoff`),K(this,`retries`),K(this,`serverInactivityThreshold`),K(this,`reconnectDueToServerInactivityTimeout`),K(this,`scheduledReconnect`,null),K(this,`networkOnlineHandler`,null),K(this,`pendingNetworkRecoveryInfo`,null),K(this,`uri`),K(this,`onOpen`),K(this,`onResume`),K(this,`onMessage`),K(this,`webSocketConstructor`),K(this,`logger`),K(this,`onServerDisconnectError`),this.webSocketConstructor=n,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.setupNetworkListener(),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()}setupNetworkListener(){typeof window>`u`||typeof window.addEventListener!=`function`||this.networkOnlineHandler===null&&(this.networkOnlineHandler=()=>{this._logVerbose(`network online event detected`),this.tryReconnectImmediately()},window.addEventListener(`online`,this.networkOnlineHandler),this._logVerbose(`network online event listener registered`))}cleanupNetworkListener(){this.networkOnlineHandler&&typeof window<`u`&&typeof window.removeEventListener==`function`&&(window.removeEventListener(`online`,this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose(`network online event listener removed`))}assembleTransition(e){if(e.partNumber<0||e.partNumber>=e.totalParts||e.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,Error(`Invalid TransitionChunk`);if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){let t=this.transitionChunkBuffer.chunks.length;throw 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=ct(JSON.parse(e));if(t.type!==`Transition`)throw Error(`Expected Transition, got ${t.type} after assembling chunks`);return t}return null}connect(){if(this.socket.state===`terminated`)return;if(this.socket.state!==`disconnected`&&this.socket.state!==`stopped`)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`),this.socket.state!==`connecting`)throw Error(`onopen called with socket not in connecting state`);if(this.setSocketState({state:`ready`,ws:e,paused:this.socket.paused===`yes`?`uninitialized`:`no`}),this.resetServerInactivityTimeout(),this.socket.paused===`no`&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:J()})),this.lastCloseReason!==`InitialConnect`&&(this.lastCloseReason?this.logger.log(`WebSocket reconnected at`,ft(),`after disconnect due to`,this.lastCloseReason):this.logger.log(`WebSocket reconnected at`,ft())),this.connectionCount+=1,this.lastCloseReason=null,this.pendingNetworkRecoveryInfo!==null){let{timeSavedMs:e}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:`Event`,eventType:`NetworkRecoveryReconnect`,event:{timeSavedMs:e}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(e/1e3)}s of waiting`)}},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,n=ct(JSON.parse(e.data));if(this._logVerbose(`received ws message with type ${n.type}`),n.type!==`Ping`){if(n.type===`TransitionChunk`){let e=this.assembleTransition(n);if(!e)return;n=e,this._logVerbose(`assembled full ws message of type ${n.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${n.type} while buffering TransitionChunks`)),n.type===`Transition`&&this.reportLargeTransition({messageLength:t,transition:n}),this.onMessage(n).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())}},e.onclose=e=>{if(this._logVerbose(`begin ws.onclose`),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=e.reason||`closed with code ${e.code}`),e.code!==1e3&&e.code!==1001&&e.code!==1005&&e.code!==4040){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=mt(e.reason);this.scheduleReconnect(t)}}socketState(){return this.socket.state}sendMessage(e){let t={type:e.type,...e.type===`Authenticate`&&e.tokenType===`User`?{value:`...${e.value.slice(-7)}`}:{}};if(this.socket.state===`ready`&&this.socket.paused===`no`){let n=lt(e),r=JSON.stringify(n),i=!1;try{this.socket.ws.send(r),i=!0}catch(e){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${e}`),this.closeAndReconnect(`FailedToSendMessage`)}return this._logVerbose(`${i?`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(){this.socket.state!==`terminated`&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect(`InactiveServer`)},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&=(clearTimeout(this.scheduledReconnect.timeout),null),this.socket={state:`disconnected`};let t=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(t)}ms`);let n=J(),r=setTimeout(()=>{this.scheduledReconnect?.timeout===r&&(this.scheduledReconnect=null,this.connect())},t);this.scheduledReconnect={timeout:r,scheduledAt:n,backoffMs: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.scheduledReconnect&&=(clearTimeout(this.scheduledReconnect.timeout),null),this.cleanupNetworkListener(),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`:{this.cleanupNetworkListener();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.setupNetworkListener(),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}}tryReconnectImmediately(){if(this._logVerbose(`tryReconnectImmediately called`),this.socket.state!==`disconnected`){this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);return}let e=null;if(this.scheduledReconnect){let t=J()-this.scheduledReconnect.scheduledAt;e=Math.max(0,this.scheduledReconnect.backoffMs-t),this._logVerbose(`would have waited ${Math.round(e)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(t)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose(`canceled scheduled reconnect`)}this.logger.log(`Network recovery detected, reconnecting immediately`),this.pendingNetworkRecoveryInfo=e===null?null:{timeSavedMs:e},this.connect()}resume(){switch(this.socket.state){case`connecting`:this.socket={...this.socket,paused:`no`};return;case`ready`:this.socket.paused===`uninitialized`?(this.socket={...this.socket,paused:`no`},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:J()})):this.socket.paused===`yes`&&(this.socket={...this.socket,paused:`no`},this.onResume());return;case`terminated`:case`stopped`:case`disconnected`:return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state===`ready`,hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){let t=(e===`client`?100:e===`Unknown`?this.defaultInitialBackoff:pt[e].timeout)*2**this.retries;this.retries+=1;let n=Math.min(t,this.maxBackoff);return n+n*(Math.random()-.5)}reportLargeTransition({transition:e,messageLength:t}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;let n=J()-e.clientClockSkew-e.serverTs/1e6,r=`${Math.round(n)}ms`,i=`${Math.round(t/1e4)/100}MB`,a=t/(n/1e3),o=`${Math.round(a/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}) which will take a long time to download on slower connections`):n>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:n,messageLength:t}})}};function gt(){return _t()}function _t(){return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}var Y=class extends Error{};Y.prototype.name=`InvalidTokenError`;function vt(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n=`0`+n),`%`+n}))}function yt(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{return vt(t)}catch{return atob(t)}}function bt(e,t){if(typeof e!=`string`)throw new Y(`Invalid token specified: must be a string`);t||={};let n=t.header===!0?0:1,r=e.split(`.`)[n];if(typeof r!=`string`)throw new Y(`Invalid token specified: missing part #${n+1}`);let i;try{i=yt(r)}catch(e){throw new Y(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new Y(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}var xt=Object.defineProperty,St=(e,t,n)=>t in e?xt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,X=(e,t,n)=>St(e,typeof t==`symbol`?t:t+``,n),Ct=class{constructor(e,t,n){X(this,`authState`,{state:`noAuth`}),X(this,`configVersion`,0),X(this,`syncState`),X(this,`authenticate`),X(this,`stopSocket`),X(this,`tryRestartSocket`),X(this,`pauseSocket`),X(this,`resumeSocket`),X(this,`clearAuth`),X(this,`logger`),X(this,`refreshTokenLeewaySeconds`),X(this,`initialAuthTokenReuse`),X(this,`lastRefreshChange`),X(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=n.logger,this.refreshTokenLeewaySeconds=n.refreshTokenLeewaySeconds,this.initialAuthTokenReuse=n.initialAuthTokenReuse,this.lastRefreshChange=!1}notifyRefreshChange(e){this.authState.state!==`noAuth`&&this.authState.state!==`initialRefetch`&&this.authState.config.onRefreshChange&&this.lastRefreshChange!==e&&(this.lastRefreshChange=e,this.authState.config.onRefreshChange(e))}async setConfig(e,t,n){this.resetAuthState(),this._logVerbose(`pausing WS for auth token fetch`),this.pauseSocket();let r=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});if(r.isFromOutdatedConfig)return;let i={fetchToken:e,onAuthChange:t,onRefreshChange:n};r.value?(this.setAuthState({state:`waitingForServerConfirmationOfCachedToken`,config:i,hasRetried:!1}),this.authenticate(r.value)):(this.setAuthState({state:`initialRefetch`,config:i}),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(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),this.authState.state===`waitingForServerConfirmationOfCachedToken`){this._logVerbose(`server confirmed auth token is valid`);let t=this.syncState.getAuth()?.value;this.initialAuthTokenReuse&&t?this.scheduleTokenRefetch(t,e.clientClockSkew):this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state===`waitingForServerConfirmationOfFreshToken`&&(this._logVerbose(`server confirmed new auth token is valid`),this.notifyRefreshChange(!1),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(e.authUpdateAttempted===!1&&(this.authState.state===`waitingForServerConfirmationOfFreshToken`||this.authState.state===`waitingForServerConfirmationOfCachedToken`)){this._logVerbose(`ignoring non-auth token expired error`);return}let{baseVersion:t}=e;if(!this.syncState.isCurrentOrNewerAuthVersion(t+1)){this._logVerbose(`ignoring auth error for previous auth attempt`);return}this.tryToReauthenticate(e)}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),this.authState.state===`noAuth`||this.authState.state===`waitingForServerConfirmationOfFreshToken`&&this.tokenConfirmationAttempts>=2){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!==`noAuth`&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}if(this.authState.state===`waitingForServerConfirmationOfFreshToken`&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${2-this.tokenConfirmationAttempts} attempts remaining`)),this.notifyRefreshChange(!0),await this.stopSocket(),this.authState.state===`noAuth`)return;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:this.authState.state===`notRefetching`||this.authState.state===`waitingForScheduledRefetch`})):(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(this.authState.state===`noAuth`)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,t){if(this.authState.state===`noAuth`)return;let n=this.decodeToken(e);if(!n){this.logger.error(`Auth token is not a valid JWT, cannot refetch the token`);return}let{iat:r,exp:i}=n;if(!r||!i){this.logger.error(`Auth token does not have required fields, cannot refetch the token`);return}let a=i-r;if(a<=2){this.logger.error(`Auth token does not live long enough, cannot refetch the token`);return}let o;t===void 0?o=a:(o=i-(Date.now()-t)/1e3,o<=0&&(o=0));let s=Math.min(1728e6,(o-this.refreshTokenLeewaySeconds)*1e3);s<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${o}s`),s=0);let c=setTimeout(()=>{this._logVerbose(`running scheduled token refetch`),this.refetchToken()},s);this.setAuthState({state:`waitingForScheduledRefetch`,refetchTokenTimeoutId:c,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${s}ms`)}async fetchTokenAndGuardAgainstRace(e,t){let n=++this.configVersion;this._logVerbose(`fetching token with config version ${n}`);let r=await e(t);return this.configVersion===n?{isFromOutdatedConfig:!1,value:r}:(this._logVerbose(`stale config version, expected ${n}, got ${this.configVersion}`),{isFromOutdatedConfig:!0})}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.notifyRefreshChange(!1),this.setAuthState({state:`noAuth`})}setAuthState(e){let t=e.state===`waitingForServerConfirmationOfFreshToken`?{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}this.authState.state===`waitingForScheduledRefetch`&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=e}decodeToken(e){try{return bt(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}]`)}};const wt=[`convexClientConstructed`,`convexWebSocketOpen`,`convexFirstMessageReceived`];function Tt(e,t){let n={sessionId:t};typeof performance>`u`||!performance.mark||performance.mark(e,{detail:n})}function Et(e){let t=e.name.slice(6);return t=t.charAt(0).toLowerCase()+t.slice(1),{name:t,startTime:e.startTime}}function Dt(e){if(typeof performance>`u`||!performance.getEntriesByName)return[];let t=[];for(let n of wt){let r=performance.getEntriesByName(n).filter(e=>e.entryType===`mark`).filter(t=>t.detail.sessionId===e);t.push(...r)}return t.map(Et)}var Ot=Object.defineProperty,kt=(e,t,n)=>t in e?Ot(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Z=(e,t,n)=>kt(e,typeof t==`symbol`?t:t+``,n),At=class{constructor(e,t,n){if(Z(this,`address`),Z(this,`state`),Z(this,`requestManager`),Z(this,`webSocketManager`),Z(this,`authenticationManager`),Z(this,`remoteQuerySet`),Z(this,`optimisticQueryResults`),Z(this,`_transitionHandlerCounter`,0),Z(this,`_nextRequestId`),Z(this,`_onTransitionFns`,new Map),Z(this,`_sessionId`),Z(this,`firstMessageReceived`,!1),Z(this,`debug`),Z(this,`logger`),Z(this,`maxObservedTimestamp`),Z(this,`connectionStateSubscribers`,new Map),Z(this,`nextConnectionStateSubscriberId`,0),Z(this,`_lastPublishedConnectionState`),Z(this,`markConnectionStateDirty`,()=>{Promise.resolve().then(()=>{let e=this.connectionState();if(JSON.stringify(e)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=e;for(let t of this.connectionStateSubscribers.values())t(e)}})}),Z(this,`mark`,e=>{this.debug&&Tt(e,this.sessionId)}),typeof e==`object`)throw Error(`Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.`);n?.skipConvexDeploymentUrlCheck!==!0&&te(e),n={...n};let r=n.authRefreshTokenLeewaySeconds??10,i=n.webSocketConstructor;if(!i&&typeof WebSocket>`u`)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`);i||=WebSocket,this.debug=n.reportDebugInfoToConvex??!1,this.address=e,this.logger=n.logger===!1?Re({verbose:n.verbose??!1}):n.logger!==!0&&n.logger?n.logger:Le({verbose:n.verbose??!1});let a=e.search(`://`);if(a===-1)throw Error(`Provided address was not an absolute URL.`);let o=e.substring(a+3),s=e.substring(0,a),c;if(s===`http`)c=`ws`;else if(s===`https`)c=`wss`;else throw Error(`Unknown parent protocol ${s}`);let l=`${c}://${o}/api/${xe}/sync`;this.state=new We,this.remoteQuerySet=new ot(e=>this.state.queryPath(e),this.logger),this.requestManager=new qe(this.logger,this.markConnectionStateDirty);let u=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new Ct(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:u,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:r,initialAuthTokenReuse:n.initialAuthTokenReuse??!1}),this.optimisticQueryResults=new Ze,this.addOnTransitionHandler(e=>{t(e.queries.map(e=>e.token))}),this._nextRequestId=0,this._sessionId=gt();let{unsavedChangesWarning:d}=n;if(typeof window>`u`||window.addEventListener===void 0){if(d===!0)throw Error(`unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.`)}else d!==!1&&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 ht(l,{onOpen:e=>{this.mark(`convexWebSocketOpen`),this.webSocketManager.sendMessage({...e,type:`Connect`,sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new ot(e=>this.state.queryPath(e),this.logger);let[t,n]=this.state.restart();n&&this.webSocketManager.sendMessage(n),this.webSocketManager.sendMessage(t);for(let e of this.requestManager.restart())this.webSocketManager.sendMessage(e)},onResume:()=>{let[e,t]=this.state.resume();t&&this.webSocketManager.sendMessage(t),e&&this.webSocketManager.sendMessage(e);for(let e of this.requestManager.resume())this.webSocketManager.sendMessage(e)},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);t!==null&&this.notifyOnQueryResultChanges(new Map([[t.requestId,t.result]]));break}case`ActionResponse`:this.requestManager.onResponse(e);break;case`AuthError`:this.authenticationManager.onAuthError(e);break;case`FatalError`:{let t=ze(this.logger,e.error);throw this.webSocketManager.terminate(),t}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:n.onServerDisconnectError},i,this.logger,this.markConnectionStateDirty,this.debug),this.mark(`convexClientConstructed`),n.expectAuth&&u()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){let t=this.remoteQuerySet.remoteQueryResults(),n=new Map;for(let[e,r]of t){let t=this.state.queryToken(e);if(t!==null){let i={result:r,udfPath:this.state.queryPath(e),args:this.state.queryArgs(e)};n.set(t,i)}}let r=this.optimisticQueryResults.ingestQueryResultsFromServer(n,new Set(e.keys()));this.handleTransition({queries:r.map(e=>({token:e,modification:{kind:`Updated`,result:this.optimisticQueryResults.rawQueryResult(e)}})),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&&e.tokenType===`User`)try{t=e?bt(e.value):{}}catch{t={}}else return;return{token:e.value,decoded:t}}setAuth(e,t,n){this.authenticationManager.setConfig(e,t,n)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,t){let n=this.state.setAdminAuth(e,t);this.webSocketManager.sendMessage(n)}clearAuth(){let e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,t,n){let r=m(t),{modification:i,queryToken:a,unsubscribe:o}=this.state.subscribe(e,r,n?.journal,n?.componentPath);return i!==null&&this.webSocketManager.sendMessage(i),{queryToken:a,unsubscribe:()=>{let e=o();e&&this.webSocketManager.sendMessage(e)}}}localQueryResult(e,t){let n=L(e,m(t));return this.optimisticQueryResults.queryResult(n)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,t){let n=L(e,m(t));return this.optimisticQueryResults.queryLogs(n)}queryJournal(e,t){let n=L(e,m(t));return this.state.queryJournal(n)}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,n){let r=await this.mutationInternal(e,t,n);if(!r.success)throw r.errorData===void 0?Error(P(`mutation`,e,r)):F(r,new E(P(`mutation`,e,r)));return r.value}async mutationInternal(e,t,n,r){let{mutationPromise:i}=this.enqueueMutation(e,t,n,r);return i}enqueueMutation(e,t,n,r){let i=m(t);this.tryReportLongDisconnect();let a=this.nextRequestId;if(this._nextRequestId++,n!==void 0){let e=n.optimisticUpdate;if(e!==void 0){let t=this.optimisticQueryResults.applyOptimisticUpdate(t=>{e(t,i)instanceof Promise&&this.logger.warn(`Optimistic update handler returned a Promise. Optimistic updates should be synchronous.`)},a).map(e=>{let t=this.localQueryResultByToken(e);return{token:e,modification:{kind:`Updated`,result:t===void 0?void 0:{success:!0,value:t,logLines:[]}}}});this.handleTransition({queries:t,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let o={type:`Mutation`,requestId:a,udfPath:e,componentPath:r,args:[w(i)]},s=this.webSocketManager.sendMessage(o);return{requestId:a,mutationPromise:this.requestManager.request(o,s)}}async action(e,t){let n=await this.actionInternal(e,t);if(!n.success)throw n.errorData===void 0?Error(P(`action`,e,n)):F(n,new E(P(`action`,e,n)));return n.value}async actionInternal(e,t,n){let r=m(t),i=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let a={type:`Action`,requestId:i,udfPath:e,componentPath:n,args:[w(r)]},o=this.webSocketManager.sendMessage(a);return this.requestManager.request(a,o)}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=Dt(this.sessionId);this.webSocketManager.sendMessage({type:`Event`,eventType:`ClientConnect`,event:e})}}tryReportLongDisconnect(){if(!this.debug)return;let e=this.connectionState().timeOfOldestInflightRequest;if(e===null||Date.now()-e.getTime()<=6e4)return;let t=`${this.address}/api/debug_event`;fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,"Convex-Client":`npm-${xe}`},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)})}};function Q(e){if(typeof e!=`object`||!e||!Array.isArray(e.page)||typeof e.isDone!=`boolean`||typeof e.continueCursor!=`string`)throw Error(`Not a valid paginated query result: ${e?.toString()}`);return e}var jt=Object.defineProperty,Mt=(e,t,n)=>t in e?jt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Nt=(e,t,n)=>Mt(e,typeof t==`symbol`?t:t+``,n),Pt=class{constructor(e,t){this.client=e,this.onTransition=t,Nt(this,`paginatedQuerySet`,new Map),Nt(this,`lastTransitionTs`),this.lastTransitionTs=H.fromNumber(0),this.client.addOnTransitionHandler(e=>this.onBaseTransition(e))}subscribe(e,t,n){let r=I(e),i=Be(r,t,n),a=()=>this.removePaginatedQuerySubscriber(i),o=this.paginatedQuerySet.get(i);return o?(o.numSubscribers+=1,{paginatedQueryToken:i,unsubscribe:a}):(this.paginatedQuerySet.set(i,{token:i,canonicalizedUdfPath:r,args:t,numSubscribers:1,options:{initialNumItems:n.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:n.id}),this.addPageToPaginatedQuery(i,null,n.initialNumItems),{paginatedQueryToken:i,unsubscribe:a})}localQueryResult(e,t,n){let r=Be(I(e),t,n);return this.localQueryResultByToken(r)}localQueryResultByToken(e){let t=this.paginatedQuerySet.get(e);if(!t)return;let n=this.activePageQueryTokens(t);if(n.length===0)return{results:[],status:`LoadingFirstPage`,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)};let r=[],i=!1,a=!1;for(let e of n){let t=this.client.localQueryResultByToken(e);if(t===void 0){i=!0,a=!1;continue}let n=Q(t);r=r.concat(n.page),a=!!n.isDone}let o;return o=i?r.length===0?`LoadingFirstPage`:`LoadingMore`:a?`Exhausted`:`CanLoadMore`,{results:r,status:o,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)}}onBaseTransition(e){let t=e.queries.map(e=>e.token),n=this.queriesContainingTokens(t),r=[];n.length>0&&(this.processPaginatedQuerySplits(n,e=>this.client.localQueryResultByToken(e)),r=n.map(e=>({token:e,modification:{kind:`Updated`,result:this.localQueryResultByToken(e)}})));let i={...e,paginatedQueries:r};this.onTransition(i)}loadMoreOfPaginatedQuery(e,t){this.mustGetPaginatedQuery(e);let n=this.queryTokenForLastPageOfPaginatedQuery(e),r=this.client.localQueryResultByToken(n);if(!r)return!1;let i=Q(r);if(i.isDone)return!1;this.addPageToPaginatedQuery(e,i.continueCursor,t);let a={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:`Updated`,result:this.localQueryResultByToken(e)}}]};return this.onTransition(a),!0}queriesContainingTokens(e){if(e.length===0)return[];let t=[],n=new Set(e);for(let[e,r]of this.paginatedQuerySet)for(let i of this.allQueryTokens(r))if(n.has(i)){t.push(e);break}return t}processPaginatedQuerySplits(e,t){for(let n of e){let e=this.mustGetPaginatedQuery(n),{ongoingSplits:r,pageKeyToQuery:i,pageKeys:a}=e;for(let[n,[a,o]]of r)t(i.get(a).queryToken)!==void 0&&t(i.get(o).queryToken)!==void 0&&this.completePaginatedQuerySplit(e,n,a,o);for(let n of a){if(r.has(n))continue;let a=i.get(n);if(!a)throw Error(`No page query for active pageKey ${n}`);let o=t(a.queryToken);if(!o)continue;let s=Q(o);s.splitCursor&&(s.pageStatus===`SplitRecommended`||s.pageStatus===`SplitRequired`||s.page.length>e.options.initialNumItems*2)&&this.splitPaginatedQueryPage(e,n,a.cursor,s.splitCursor,s.continueCursor)}}}splitPaginatedQueryPage(e,t,n,r,i){let a=e.nextPageKey++,o=e.nextPageKey++,s={numItems:e.options.initialNumItems,id:e.id},c=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...s,cursor:n,endCursor:r}});e.pageKeyToQuery.set(a,{...c,cursor:n});let l=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...s,cursor:r,endCursor:i}});e.pageKeyToQuery.set(o,{...l,cursor:r}),e.ongoingSplits.set(t,[a,o])}addPageToPaginatedQuery(e,t,n){let r=this.mustGetPaginatedQuery(e),i=r.nextPageKey++,a={cursor:t,numItems:n,id:r.id},o={...r.args,paginationOpts:a},s=this.client.subscribe(r.canonicalizedUdfPath,o);return r.pageKeys.push(i),r.pageKeyToQuery.set(i,{...s,cursor:t}),s}removePaginatedQuerySubscriber(e){let t=this.paginatedQuerySet.get(e);if(t&&(--t.numSubscribers,!(t.numSubscribers>0))){for(let e of t.pageKeyToQuery.values())e.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,t,n,r){let i=e.pageKeyToQuery.get(t);e.pageKeyToQuery.delete(t);let a=e.pageKeys.indexOf(t);e.pageKeys.splice(a,1,n,r),e.ongoingSplits.delete(t),i.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(t=>e.pageKeyToQuery.get(t).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(e=>e.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){let t=this.mustGetPaginatedQuery(e),n=t.pageKeys[t.pageKeys.length-1];if(n===void 0)throw Error(`No pages for paginated query ${e}`);return t.pageKeyToQuery.get(n).queryToken}mustGetPaginatedQuery(e){let t=this.paginatedQuerySet.get(e);if(!t)throw Error(`paginated query no longer exists for token `+e);return t}},Ft=Object.defineProperty,It=(e,t,n)=>t in e?Ft(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,$=(e,t,n)=>It(e,typeof t==`symbol`?t:t+``,n),Lt=class{constructor(e,t={}){$(this,`listeners`),$(this,`_client`),$(this,`_paginatedClient`),$(this,`callNewListenersWithCurrentValuesTimer`),$(this,`_closed`),$(this,`_disabled`),t.skipConvexDeploymentUrlCheck!==!0&&te(e);let{disabled:n,...r}=t;this._closed=!1,this._disabled=!!n,typeof window>`u`&&!(`unsavedChangesWarning`in r)&&(r.unsavedChangesWarning=!1),this.disabled||(this._client=new At(e,()=>{},r),this._paginatedClient=new Pt(this._client,e=>this._transition(e))),this.listeners=new Set}get closed(){return this._closed}get client(){if(this._client)return this._client;throw Error(`ConvexClient is disabled`)}get paginatedClient(){if(this._paginatedClient)return this._paginatedClient;throw Error(`ConvexClient is disabled`)}get disabled(){return this._disabled}onUpdate(e,t,n,r){if(this.disabled)return this.createDisabledUnsubscribe();let{queryToken:i,unsubscribe:a}=this.client.subscribe(O(e),t),o={queryToken:i,callback:n,onError:r,unsubscribe:a,hasEverRun:!1,query:e,args:t,paginationOptions:void 0};this.listeners.add(o),this.queryResultReady(i)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let s={unsubscribe:()=>{this.closed||(this.listeners.delete(o),a())},getCurrentValue:()=>this.client.localQueryResultByToken(i),getQueryLogs:()=>this.client.localQueryLogs(i)},c=s.unsubscribe;return Object.assign(c,s),c}onPaginatedUpdate_experimental(e,t,n,r,i){if(this.disabled)return this.createDisabledUnsubscribe();let a={initialNumItems:n.initialNumItems,id:-1},{paginatedQueryToken:o,unsubscribe:s}=this.paginatedClient.subscribe(O(e),t,a),c={queryToken:o,callback:r,onError:i,unsubscribe:s,hasEverRun:!1,query:e,args:t,paginationOptions:a};this.listeners.add(c),this.paginatedClient.localQueryResultByToken(o)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let l={unsubscribe:()=>{this.closed||(this.listeners.delete(c),s())},getCurrentValue:()=>this.paginatedClient.localQueryResult(O(e),t,a),getQueryLogs:()=>[]},u=l.unsubscribe;return Object.assign(u,l),u}callNewListenersWithCurrentValues(){this.callNewListenersWithCurrentValuesTimer=void 0,this._transition({queries:[],paginatedQueries:[]},!0)}queryResultReady(e){return this.client.hasLocalQueryResultByToken(e)}createDisabledUnsubscribe(){let e=(()=>{});return Object.assign(e,{unsubscribe:e,getCurrentValue:()=>void 0,getQueryLogs:()=>void 0}),e}async close(){if(!this.disabled)return this.listeners.clear(),this._closed=!0,this._paginatedClient&&=void 0,this.client.close()}getAuth(){if(!this.disabled)return this.client.getCurrentAuthClaims()}setAuth(e,t){this.disabled||this.client.setAuth(e,t??(()=>{}))}setAdminAuth(e,t){if(this.closed)throw Error(`ConvexClient has already been closed.`);this.disabled||this.client.setAdminAuth(e,t)}_transition({queries:e,paginatedQueries:t},n=!1){let r=[...e.map(e=>e.token),...t.map(e=>e.token)];for(let e of this.listeners){let{callback:t,queryToken:i,onError:a,hasEverRun:o}=e,s=Ve(i),c=s?!!this.paginatedClient.localQueryResultByToken(i):this.client.hasLocalQueryResultByToken(i);if(r.includes(i)||n&&!o&&c){e.hasEverRun=!0;let n;try{n=s?this.paginatedClient.localQueryResultByToken(i):this.client.localQueryResultByToken(i)}catch(e){if(!(e instanceof Error))throw e;a?a(e,`Second argument to onUpdate onError is reserved for later use`):Promise.reject(e);continue}t(n,`Second argument to onUpdate callback is reserved for later use`)}}}async mutation(e,t,n){if(this.disabled)throw Error(`ConvexClient is disabled`);return await this.client.mutation(O(e),t,n)}async action(e,t){if(this.disabled)throw Error(`ConvexClient is disabled`);return await this.client.action(O(e),t)}async query(e,t){if(this.disabled)throw Error(`ConvexClient is disabled`);let n=this.client.localQueryResult(O(e),t);return n===void 0?new Promise((n,r)=>{let{unsubscribe:i}=this.onUpdate(e,t,e=>{i(),n(e)},e=>{i(),r(e)})}):Promise.resolve(n)}connectionState(){if(this.disabled)throw Error(`ConvexClient is disabled`);return this.client.connectionState()}subscribeToConnectionState(e){return this.disabled?()=>{}:this.client.subscribeToConnectionState(e)}};function Rt(e,t){let n=e.trim();if(!/^https:\/\/[^/]+$/.test(n))throw Error(`A valid HTTPS Convex deployment URL is required`);let r=new Lt(n);return r.setAuth(t),r}function zt(e,t){let n=e.trim();if(!n)throw Error(`Convex deployment URL is required`);return{async resolve(e){let r=await t.fetchAccessToken(Wt(e,!1));if(!r)throw Error(`Convex review authentication is required`);let i=r,a=(t.clientFactory??Rt)(n,async({forceRefreshToken:n})=>{if(!n&&i){let e=i;return i=null,e}return t.fetchAccessToken({...Wt(e,n),signal:new AbortController().signal})}),o=await a.mutation(A.resolveSession,{invitationId:e.invitationId,origin:e.location.origin,pathname:e.location.pathname,...e.routeKey===void 0?{}:{routeKey:e.routeKey}}),s=Gt(o.session,e.invitationId),c=0;return Bt({client:a,session:s,request:e,pageId:o.pageId,resolvePage:async t=>{if(t.location.origin!==e.location.origin)throw Error(`Convex review session cannot move to another origin`);let n=++c,r=await a.mutation(A.resolveSession,{invitationId:e.invitationId,origin:t.location.origin,pathname:t.location.pathname,...t.routeKey===void 0?{}:{routeKey:t.routeKey}});if(t.signal.aborted||n!==c)throw Kt();return{pageId:r.pageId,...t.cursorChat?{cursorChatRoomId:Ut(r.pageId)}:{}}},cursorChatRepositoryFactory:t.cursorChatRepositoryFactory})}}}async function Bt(e){let t=new De(e.client,e.session,{origin:e.request.location.origin}),n;if(e.request.cursorChat)try{n=await Vt(e.client,e.session,e.request.location.origin,e.cursorChatRepositoryFactory)}catch{}return{pageId:e.pageId,session:e.session,repository:t,...n?{cursorChatRepository:n,cursorChatRoomId:Ut(e.pageId)}:{},resolvePage:e.resolvePage,allowedStagingHosts:[e.request.location.hostname]}}async function Vt(e,t,n,r=Ht){return r(e,t,n)}async function Ht(e,t,n){let{ConvexReviewCursorChatRepository:r}=await import(`./cursor-chat-repository-DWfIYLEK.js`);return new r(e,t,{origin:n})}function Ut(e){return`cursor-chat:${e}`}function Wt(e,t){return{invitationId:e.invitationId,origin:e.location.origin,pathname:e.location.pathname,...e.emailToken===void 0?{}:{emailToken:e.emailToken},forceRefreshToken:t,signal:e.signal}}function Gt(e,t){if(!e||e.invitationId!==t||!e.authUserId||!e.reviewerId||!e.projectId)throw Error(`Convex returned an invalid reviewer session`);return structuredClone(e)}function Kt(){return Object.assign(Error(`Review page resolution was superseded`),{code:`PAGE_SWAP_SUPERSEDED`})}export{zt as createConvexReviewRuntime,A as n,j as t};
|
|
1
|
+
import{i as e,n as t,r as n}from"./src-IC5X3zme.js";for(var r=[],i=[],a=Uint8Array,o=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,s=0,c=o.length;s<c;++s)r[s]=o[s],i[o.charCodeAt(s)]=s;i[45]=62,i[95]=63;function l(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function u(e,t,n){return(t+n)*3/4-n}function d(e){var t,n=l(e),r=n[0],o=n[1],s=new a(u(e,r,o)),c=0,d=o>0?r-4:r,f;for(f=0;f<d;f+=4)t=i[e.charCodeAt(f)]<<18|i[e.charCodeAt(f+1)]<<12|i[e.charCodeAt(f+2)]<<6|i[e.charCodeAt(f+3)],s[c++]=t>>16&255,s[c++]=t>>8&255,s[c++]=t&255;return o===2&&(t=i[e.charCodeAt(f)]<<2|i[e.charCodeAt(f+1)]>>4,s[c++]=t&255),o===1&&(t=i[e.charCodeAt(f)]<<10|i[e.charCodeAt(f+1)]<<4|i[e.charCodeAt(f+2)]>>2,s[c++]=t>>8&255,s[c++]=t&255),s}function f(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[e&63]}function ee(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(f(r));return i.join(``)}function p(e){for(var t,n=e.length,i=n%3,a=[],o=16383,s=0,c=n-i;s<c;s+=o)a.push(ee(e,s,s+o>c?c:s+o));return i===1?(t=e[n-1],a.push(r[t>>2]+r[t<<4&63]+`==`)):i===2&&(t=(e[n-2]<<8)+e[n-1],a.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+`=`)),a.join(``)}function m(e){if(e===void 0)return{};if(!ne(e))throw Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function te(e){if(e===void 0)throw Error(`Client created with undefined deployment address. If you used an environment variable, check that it's set.`);if(typeof e!=`string`)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 ne(e){let t=typeof e==`object`,n=Object.getPrototypeOf(e),r=n===null||n===Object.prototype||n?.constructor?.name===`Object`;return t&&r}const h=BigInt(`-9223372036854775808`),g=BigInt(`9223372036854775807`),_=BigInt(`0`),re=BigInt(`8`),ie=BigInt(`256`),v=`This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.`;var ae=class{[Symbol.toPrimitive](e){if(e===`string`)return this.toString();throw Error(v)}valueOf(){throw Error(v)}toJSON(){throw Error(v)}toString(){return`[unresolved commit timestamp]`}};const oe=new ae;function se(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}function ce(e){e<_&&(e-=h+h);let t=e.toString(16);t.length%2==1&&(t=`0`+t);let n=new Uint8Array(new ArrayBuffer(8)),r=0;for(let i of t.match(/.{2}/g).reverse())n.set([parseInt(i,16)],r++),e>>=re;return p(n)}function le(e){let t=d(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let n=_,r=_;for(let e of t)n+=BigInt(e)*ie**r,r++;return n>g&&(n+=h+h),n}function ue(e){if(e<h||g<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),p(new Uint8Array(t))}function de(e){let t=d(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}const fe=DataView.prototype.setBigInt64?ue:ce,pe=DataView.prototype.getBigInt64?de:le,me=1024;function y(e){if(e.length>me)throw Error(`Field name ${e} exceeds maximum field name length ${me}.`);if(e.startsWith(`$`))throw Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<32||n>=127)throw Error(`Field name ${e} has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function b(e){if(e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`)return e;if(Array.isArray(e))return e.map(e=>b(e));if(typeof e!=`object`)throw Error(`Unexpected type of ${e}`);let t=Object.entries(e);if(t.length===1){let n=t[0][0];if(n===`$bytes`){if(typeof e.$bytes!=`string`)throw Error(`Malformed $bytes field on ${e}`);return d(e.$bytes).buffer}if(n===`$integer`){if(typeof e.$integer!=`string`)throw Error(`Malformed $integer field on ${e}`);return pe(e.$integer)}if(n===`$float`){if(typeof e.$float!=`string`)throw Error(`Malformed $float field on ${e}`);let t=d(e.$float);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $float`);let n=new DataView(t.buffer).getFloat64(0,!0);if(!se(n))throw Error(`Float ${n} should be encoded as a number`);return n}if(n===`$commitTs`){if(e.$commitTs!==null)throw Error(`Malformed $commitTs field on ${e}`);return oe}if(n===`$set`)throw Error(`Received a Set which is no longer supported as a Convex type.`);if(n===`$map`)throw Error(`Received a Map which is no longer supported as a Convex type.`)}let n={};for(let[t,r]of Object.entries(e))y(t),n[t]=b(r);return n}function x(e){let t=JSON.stringify(e,(e,t)=>t===void 0?`undefined`:typeof t==`bigint`?`${t.toString()}n`:t);if(t.length>16384){let e=16370,n=t.codePointAt(e-1);return n!==void 0&&n>65535&&--e,t.substring(0,e)+`[...truncated]`}return t}function S(e,t,n,r){if(e===void 0){let e=n&&` (present at path ${n} in original object ${x(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(e===null)return e;if(typeof e==`bigint`){if(e<h||g<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:fe(e)}}if(typeof e==`number`){if(se(e)){let t=new ArrayBuffer(8);return new DataView(t).setFloat64(0,e,!0),{$float:p(new Uint8Array(t))}}return e}if(typeof e==`boolean`||typeof e==`string`)return e;if(e instanceof ArrayBuffer)return{$bytes:p(new Uint8Array(e))};if(e instanceof ae)return{$commitTs:null};if(Array.isArray(e))return e.map((e,r)=>S(e,t,n+`[${r}]`,!1));if(e instanceof Set)throw Error(C(n,`Set`,[...e],t));if(e instanceof Map)throw Error(C(n,`Map`,[...e],t));if(!ne(e)){let r=e?.constructor?.name,i=r?`${r} `:``;throw Error(C(n,i,e,t))}let i={},a=Object.entries(e);a.sort(([e,t],[n,r])=>e===n?0:e<n?-1:1);for(let[e,o]of a)o===void 0?r&&(y(e),i[e]=he(o,t,n+`.${e}`)):(y(e),i[e]=S(o,t,n+`.${e}`,!1));return i}function C(e,t,n,r){return e?`${t}${x(n)} is not a supported Convex type (present at path ${e} in original object ${x(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${x(n)} is not a supported Convex type.`}function he(e,t,n){if(e===void 0)return{$undefined:null};if(t===void 0)throw Error(`Programming error. Current value is ${x(e)} but original value is undefined`);return S(e,t,n,!1)}function w(e){return S(e,e,``,!1)}var ge=Object.defineProperty,_e=(e,t,n)=>t in e?ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,T=(e,t,n)=>_e(e,typeof t==`symbol`?t:t+``,n),ve,ye;const be=Symbol.for(`ConvexError`);var E=class extends (ye=Error,ve=be,ye){constructor(e){super(typeof e==`string`?e:x(e)),T(this,`name`,`ConvexError`),T(this,`data`),T(this,ve,!0),this.data=e}};const xe=`1.45.0`,D=Symbol.for(`functionName`),Se=Symbol.for(`toReferencePath`);function Ce(e){return e[Se]??null}function we(e){return e.startsWith(`function://`)}function Te(e){let t;if(typeof e==`string`)t=we(e)?{functionHandle:e}:{name:e};else if(e[D])t={name:e[D]};else{let n=Ce(e);if(!n)throw Error(`${e} is not a functionReference`);t={reference:n}}return t}function O(e){let t=Te(e);if(t.name===void 0)throw t.functionHandle===void 0?t.reference===void 0?Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(t)}`):Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${t.reference}`):Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${t.functionHandle}`);if(typeof e==`string`)return e;let n=e[D];if(!n)throw Error(`${e} is not a functionReference`);return n}function k(e){return{[D]:e}}function Ee(e=[]){return new Proxy({},{get(t,n){if(typeof n==`string`)return Ee([...e,n]);if(n===D){if(e.length<2){let t=[`api`,...e].join(`.`);throw Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${t}\``)}let t=e.slice(0,-1).join(`/`),n=e[e.length-1];return n==="default"?t:t+`:`+n}if(n===Symbol.toStringTag)return`FunctionReference`}})}Ee();const A=Object.freeze({resolveSession:k(`reviews:resolveSession`),pageSnapshot:k(`reviews:pageSnapshot`),projectSnapshot:k(`reviews:projectSnapshot`),markFeedbackRead:k(`reviews:markFeedbackRead`),createComment:k(`reviews:createComment`),createReply:k(`reviews:createReply`),setCommentStatus:k(`reviews:setCommentStatus`),setCommentLabels:k(`reviews:setCommentLabels`),moveCommentPin:k(`reviews:moveCommentPin`),presenceList:k(`presence:list`),presenceUpdate:k(`presence:update`),presenceDisconnect:k(`presence:disconnect`),screenshotUploadUrl:k(`screenshots:generateUploadUrl`),screenshotCommit:k(`screenshots:commitUpload`),screenshotDiscard:k(`screenshots:discardUpload`),finalizeAttachments:k(`screenshots:finalizeAttachments`)});Object.freeze({catalog:k(`owners:catalog`),listProjects:k(`owners:listProjects`),projectOverview:k(`owners:projectOverview`),feedbackPage:k(`owners:feedbackPage`),markFeedbackRead:k(`owners:markFeedbackRead`),createProject:k(`owners:createProject`),createProjectWithOrigins:k(`owners:createProjectWithOrigins`),configureProjectLinkAccess:k(`owners:configureProjectLinkAccess`),setProjectBranding:k(`owners:setProjectBranding`),deleteProject:k(`owners:deleteProject`),addOrigin:k(`owners:addOrigin`),removeOrigin:k(`owners:removeOrigin`),replaceOrigins:k(`owners:replaceOrigins`),createPage:k(`owners:createPage`),deletePage:k(`owners:deletePage`),upsertPageBuild:k(`owners:upsertPageBuild`),createInvitation:k(`owners:createInvitation`),revokeInvitation:k(`owners:revokeInvitation`),revokeReviewerAccess:k(`owners:revokeReviewerAccess`),setCommentStatus:k(`owners:setCommentStatus`),setCommentLabels:k(`owners:setCommentLabels`),setProjectFeedbackLabels:k(`owners:setProjectFeedbackLabels`),createReply:k(`owners:createReply`),deleteComment:k(`owners:deleteComment`),deleteReply:k(`owners:deleteReply`),screenshotDownload:k(`screenshots:ownerDownload`)});var De=class{client;session;#e;#t;#n;constructor(e,t,n){this.client=e,this.session=t,this.#e=M(n.invitationId??t.invitationId,`invitationId`),this.#t=je(n.origin),this.#n=n.fetch??globalThis.fetch.bind(globalThis)}async attachScreenshot(e,t,n){return this.attachImage(e,t,n,{id:crypto.randomUUID(),source:`capture`})}async attachImage(e,t,n,r){M(e,`pageId`);let i=M(t,`commentId`),a=M(r.id,`image id`);if(n.bytes.byteLength===0||n.bytes.byteLength>15e5)throw Error(`Image size is invalid`);let o={commentId:i,imageId:a,source:r.source,...r.replyId===void 0?{}:{replyId:M(r.replyId,`reply id`)}},s=await this.client.mutation(A.screenshotUploadUrl,{...this.#r(),...o});if(`committed`in s)return;let c=await this.#n(s.uploadUrl,{method:`POST`,headers:{"content-type":n.contentType},body:Oe(n.bytes)});if(!c.ok)throw Error(`Image upload failed`);let l=await c.json();if(typeof l.storageId!=`string`||!l.storageId)throw Error(`Image upload returned an invalid storage ID`);try{await this.client.action(A.screenshotCommit,{...this.#r(),...o,grantId:s.grantId,storageId:l.storageId,contentType:n.contentType,width:n.width,height:n.height})}catch(e){throw await this.client.mutation(A.screenshotDiscard,{...this.#r(),...o,grantId:s.grantId,storageId:l.storageId}).catch(()=>void 0),e}}async finalizeAttachments(e,t,n){M(e,`pageId`),await this.client.mutation(A.finalizeAttachments,{...this.#r(),commentId:M(t,`commentId`),expectedAttachmentCount:n.expectedAttachmentCount,...n.replyId===void 0?{}:{replyId:M(n.replyId,`reply id`)}})}async getSnapshot(e){return Ae(await this.client.query(A.pageSnapshot,{...this.#r(),pageId:M(e,`pageId`)}))}async moveCommentPin(e,t,n,r){return this.client.mutation(A.moveCommentPin,{...this.#r(),pageId:M(e,`pageId`),commentId:M(t,`commentId`),anchorJson:JSON.stringify(n),expectedRevision:r})}async getProjectSnapshot(e){return this.#i(e),structuredClone(await this.client.query(A.projectSnapshot,{...this.#r(),projectId:e}))}async markFeedbackRead(e){return this.client.mutation(A.markFeedbackRead,{...this.#r(),commentId:M(e,`commentId`)})}subscribe(e,t,n){return this.client.onUpdate(A.pageSnapshot,{...this.#r(),pageId:M(e,`pageId`)},e=>t(Ae(e)),e=>n?.(j(e)))}subscribeProject(e,t,n){return this.#i(e),this.client.onUpdate(A.projectSnapshot,{...this.#r(),projectId:e},e=>t(structuredClone(e)),e=>n?.(j(e)))}async mutate(r,i){switch(i.type){case`comment.upsert`:{let a=i.comment;if(a.pageId!==r)throw Error(`Comment page mismatch`);if(a.authorId!==this.session.reviewerId)throw Error(`Comment author mismatch`);if(a.status!==`open`||a.resolvedAt!==void 0||a.resolvedById!==void 0||a.createdAt!==a.updatedAt)throw Error(`Only new open comments can be created by a reviewer`);let o=n(a.body).trim(),s=t(a.target),c=a.scope===void 0?void 0:e(a.scope);await this.client.mutation(A.createComment,{...this.#r(),pageId:r,commentId:a.id,body:o,targetJson:JSON.stringify(s.publicTarget),sourceContextJson:s.sourceContextJson,...c===void 0?{}:{scopeJson:JSON.stringify(c)},...i.expectedAttachmentCount===void 0?{}:{expectedAttachmentCount:i.expectedAttachmentCount}});return}case`reply.upsert`:{let e=i.reply;if(e.authorId!==this.session.reviewerId)throw Error(`Reply author mismatch`);if(e.createdAt!==e.updatedAt)throw Error(`Reply edits require an owner command`);await this.client.mutation(A.createReply,{...this.#r(),commentId:e.commentId,replyId:e.id,body:n(e.body,`Reply body`).trim(),...i.requestReopen?{requestReopen:!0}:{},...i.expectedAttachmentCount===void 0?{}:{expectedAttachmentCount:i.expectedAttachmentCount}});return}case`comment.delete`:throw Error(`Comment deletion requires an owner command`);case`reply.delete`:throw Error(`Reply deletion requires an owner command`)}}async updateCommentStatus(e,t){M(e,`pageId`);let n=await this.client.mutation(A.setCommentStatus,{...this.#r(),commentId:M(t.commentId,`commentId`),status:t.status,expectedWorkflowRevision:t.expectedWorkflowRevision,expectedThreadRevision:t.expectedThreadRevision});return{commentId:n.commentId,status:n.status,workflowRevision:n.workflowRevision,threadRevision:n.threadRevision,updatedAt:n.updatedAt,...n.resolvedAt===null?{}:{resolvedAt:n.resolvedAt}}}async updateCommentLabels(e,t){M(e,`pageId`);let n=await this.client.mutation(A.setCommentLabels,{...this.#r(),commentId:M(t.commentId,`commentId`),labels:t.labels.map(e=>M(e,`label`)),expectedWorkflowRevision:t.expectedWorkflowRevision,expectedThreadRevision:t.expectedThreadRevision});return structuredClone(n)}#r(){return{invitationId:this.#e,origin:this.#t}}#i(e){if(!e.trim()||e!==this.session.projectId)throw Error(`Project does not belong to the reviewer session`)}};function Oe(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function j(e){let t=ke(e);return t===`UNAUTHENTICATED`||t===`INVITATION_EXPIRED`?{type:`access-lost`,code:`session-expired`,recovery:`reauthenticate`,clearSnapshot:!0}:t===`INVITATION_REVOKED`||t===`MEMBERSHIP_REVOKED`?{type:`access-lost`,code:`membership-revoked`,recovery:`reauthenticate`,clearSnapshot:!0}:t===`ORIGIN_MISMATCH`||t===`ORIGIN_NOT_ALLOWED`||t===`INVITATION_REQUIRED`?{type:`access-lost`,code:`permission-denied`,recovery:`reauthenticate`,clearSnapshot:!0}:{type:`error`,code:e instanceof Error?`transport`:`unknown`,recovery:`retry`,clearSnapshot:!0}}function ke(e){if(!e||typeof e!=`object`)return;let t=e.data;if(typeof t==`string`)return t;if(t&&typeof t==`object`){let e=t.code;if(typeof e==`string`)return e}}function Ae(e){return structuredClone(e)}function M(e,t){let n=e.trim();if(!n)throw Error(`${t} is required`);return n}function je(e){let t=M(e,`origin`);try{let e=new URL(t);if(e.origin!==t)throw Error();return e.origin}catch{throw Error(`A valid browser origin is required`)}}var Me=Object.defineProperty,Ne=(e,t,n)=>t in e?Me(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Pe=(e,t,n)=>Ne(e,typeof t==`symbol`?t:t+``,n);function Fe(e){switch(e){case`query`:return`Q`;case`mutation`:return`M`;case`action`:return`A`;case`any`:return`?`}}var Ie=class{constructor(e){Pe(this,`_onLogLineFuncs`),Pe(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&&this._onLogLineFuncs[t]!==void 0;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 Le(e){let t=new Ie(e);return t.addLogLineListener((e,...t)=>{switch(e){case`debug`:console.debug(...t);break;case`info`:console.log(...t);break;case`warn`:console.warn(...t);break;case`error`:console.error(...t);break;default:console.log(...t)}}),t}function Re(e){return new Ie(e)}function N(e,t,n,r,i){let a=Fe(n);if(typeof i==`object`&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),t===`info`){let t=i.match(/^\[.*?\] /);if(t===null){e.error(`[CONVEX ${a}(${r})] Could not parse console.log`);return}let n=i.slice(1,t[0].length-2),o=i.slice(t[0].length);e.log(`%c[CONVEX ${a}(${r})] [${n}]`,`color:rgb(0, 145, 255)`,o)}else e.error(`[CONVEX ${a}(${r})] ${i}`)}function ze(e,t){let n=`[CONVEX FATAL ERROR] ${t}`;return e.error(n),Error(n)}function P(e,t,n){return`[CONVEX ${Fe(e)}(${t})] ${n.errorMessage}
|
|
2
|
+
Called by client`}function F(e,t){return t.data=e.errorData,t}function I(e){let t=e.split(`:`),n,r;return t.length===1?(n=t[0],r=`default`):(n=t.slice(0,t.length-1).join(`:`),r=t[t.length-1]),n.endsWith(`.js`)&&(n=n.slice(0,-3)),`${n}:${r}`}function L(e,t){return JSON.stringify({udfPath:I(e),args:w(t)})}function Be(e,t,n){let{initialNumItems:r,id:i}=n;return JSON.stringify({type:`paginated`,udfPath:I(e),args:w(t),options:w({initialNumItems:r,id:i})})}function Ve(e){return JSON.parse(e).type===`paginated`}var He=Object.defineProperty,Ue=(e,t,n)=>t in e?He(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,R=(e,t,n)=>Ue(e,typeof t==`symbol`?t:t+``,n),We=class{constructor(){R(this,`nextQueryId`),R(this,`querySetVersion`),R(this,`querySet`),R(this,`queryIdToToken`),R(this,`identityVersion`),R(this,`auth`),R(this,`outstandingQueriesOlderThanRestart`),R(this,`outstandingAuthOlderThanRestart`),R(this,`paused`),R(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 this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,t,n,r){let i=I(e),a=L(i,t),o=this.querySet.get(a);if(o!==void 0)return o.numSubscribers+=1,{queryToken:a,modification:null,unsubscribe:()=>this.removeSubscriber(a)};{let e=this.nextQueryId++,o={id:e,canonicalizedUdfPath:i,args:t,numSubscribers:1,journal:n,componentPath:r};this.querySet.set(a,o),this.queryIdToToken.set(e,a);let s=this.querySetVersion,c=this.querySetVersion+1,l={type:`Add`,queryId:e,udfPath:i,args:[w(t)],journal:n,componentPath:r};return this.paused?this.pendingQuerySetModifications.set(e,l):this.querySetVersion=c,{queryToken:a,modification:{type:`ModifyQuerySet`,baseVersion:s,newVersion:c,modifications:[l]},unsubscribe:()=>this.removeSubscriber(a)}}}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(e!==void 0){let n=this.queryIdToToken.get(t.queryId);n!==void 0&&(this.querySet.get(n).journal=e)}break}case`QueryRemoved`:this.outstandingQueriesOlderThanRestart.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}}queryId(e,t){let n=L(I(e),t),r=this.querySet.get(n);return r===void 0?null:r.id}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 n={tokenType:`Admin`,value:e,impersonating:t};this.auth=n;let r=this.identityVersion;return this.paused||(this.identityVersion=r+1),{type:`Authenticate`,baseVersion:r,...n}}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(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let e=[];for(let t of this.querySet.values()){let n={type:`Add`,queryId:t.id,udfPath:t.canonicalizedUdfPath,args:[w(t.args)],journal:t.journal,componentPath:t.componentPath};e.push(n),this.outstandingQueriesOlderThanRestart.add(t.id)}this.querySetVersion=1;let t={type:`ModifyQuerySet`,baseVersion:0,newVersion:1,modifications:e};if(!this.auth)return this.identityVersion=0,[t,void 0];this.outstandingAuthOlderThanRestart=!0;let n={type:`Authenticate`,baseVersion:0,...this.auth};return this.identityVersion=1,[t,n]}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=this.auth===void 0?void 0:{type:`Authenticate`,baseVersion:this.identityVersion++,...this.auth};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,null;{this.querySet.delete(e),this.queryIdToToken.delete(t.id),this.outstandingQueriesOlderThanRestart.delete(t.id);let n=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:n,newVersion:r,modifications:[i]}}}},Ge=Object.defineProperty,Ke=(e,t,n)=>t in e?Ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,z=(e,t,n)=>Ke(e,typeof t==`symbol`?t:t+``,n),qe=class{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,z(this,`inflightRequests`),z(this,`requestsOlderThanRestart`),z(this,`inflightMutationsCount`,0),z(this,`inflightActionsCount`,0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,t){let n=new Promise(n=>{let r=t?`Requested`:`NotSent`;this.inflightRequests.set(e.requestId,{message:e,status:{status:r,requestedAt:new Date,onResult:n}}),e.type===`Mutation`?this.inflightMutationsCount++:e.type===`Action`&&this.inflightActionsCount++});return this.markConnectionStateDirty(),n}onResponse(e){let t=this.inflightRequests.get(e.requestId);if(t===void 0||t.status.status===`Completed`)return null;let n=t.message.type===`Mutation`?`mutation`:`action`,r=t.message.udfPath;for(let t of e.logLines)N(this.logger,`info`,n,r,t);let i=t.status,a,o;if(e.success)a={success:!0,logLines:e.logLines,value:b(e.result)},o=()=>i.onResult(a);else{let t=e.result,{errorData:s}=e;N(this.logger,`error`,n,r,t),a={success:!1,errorMessage:t,errorData:s===void 0?void 0:b(s),logLines:e.logLines},o=()=>i.onResult(a)}return e.type===`ActionResponse`||!e.success?(o(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),t.message.type===`Action`?this.inflightActionsCount--:t.message.type===`Mutation`&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:a}):(t.status={status:`Completed`,result:a,ts:e.ts,onResolve:o},null)}removeCompleted(e){let t=new Map;for(let[n,r]of this.inflightRequests.entries()){let i=r.status;i.status===`Completed`&&i.ts.lessThanOrEqual(e)&&(i.onResolve(),t.set(n,i.result),r.message.type===`Mutation`?this.inflightMutationsCount--:r.message.type===`Action`&&this.inflightActionsCount--,this.inflightRequests.delete(n),this.requestsOlderThanRestart.delete(n))}return t.size>0&&this.markConnectionStateDirty(),t}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());let e=[];for(let[t,n]of this.inflightRequests){if(n.status.status===`NotSent`){n.status.status=`Requested`,e.push(n.message);continue}if(n.message.type===`Mutation`)e.push(n.message);else if(n.message.type===`Action`){if(this.inflightRequests.delete(t),this.requestsOlderThanRestart.delete(t),this.inflightActionsCount--,n.status.status===`Completed`)throw Error(`Action should never be in 'Completed' state`);n.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(t.status.status===`NotSent`){t.status.status=`Requested`,e.push(t.message);continue}return e}hasIncompleteRequests(){for(let e of this.inflightRequests.values())if(e.status.status===`Requested`)return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(let t of this.inflightRequests.values())t.status.status!==`Completed`&&t.status.requestedAt.getTime()<e&&(e=t.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}},Je=Object.defineProperty,Ye=(e,t,n)=>t in e?Je(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,B=(e,t,n)=>Ye(e,typeof t==`symbol`?t:t+``,n),Xe=class e{constructor(e){B(this,`queryResults`),B(this,`modifiedQueries`),this.queryResults=e,this.modifiedQueries=[]}getQuery(t,...n){let r=m(n[0]),i=O(t),a=this.queryResults.get(L(i,r));if(a!==void 0)return e.queryValue(a.result)}getAllQueries(t){let n=[],r=O(t);for(let t of this.queryResults.values())t.udfPath===I(r)&&n.push({args:t.args,value:e.queryValue(t.result)});return n}setQuery(e,t,n){let r=m(t),i=O(e),a=L(i,r),o;o=n===void 0?void 0:{success:!0,value:n,logLines:[]};let s={udfPath:i,args:r,result:o};this.queryResults.set(a,s),this.modifiedQueries.push(a)}static queryValue(e){if(e!==void 0&&e.success)return e.value}},Ze=class{constructor(){B(this,`queryResults`),B(this,`optimisticUpdates`),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,t){this.optimisticUpdates=this.optimisticUpdates.filter(e=>!t.has(e.mutationId));let n=this.queryResults;this.queryResults=new Map(e);let r=new Xe(this.queryResults);for(let e of this.optimisticUpdates)e.update(r);let i=[];for(let[e,t]of this.queryResults){let r=n.get(e);(r===void 0||r.result!==t.result)&&i.push(e)}return i}applyOptimisticUpdate(e,t){this.optimisticUpdates.push({update:e,mutationId:t});let n=new Xe(this.queryResults);return e(n),n.modifiedQueries}rawQueryResult(e){let t=this.queryResults.get(e);if(t!==void 0)return t.result}queryResult(e){let t=this.queryResults.get(e);if(t===void 0)return;let n=t.result;if(n!==void 0){if(n.success)return n.value;throw n.errorData===void 0?Error(P(`query`,t.udfPath,n)):F(n,new E(P(`query`,t.udfPath,n)))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}},Qe=Object.defineProperty,$e=(e,t,n)=>t in e?Qe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,V=(e,t,n)=>$e(e,typeof t==`symbol`?t:t+``,n),H=class e{constructor(e,t){V(this,`low`),V(this,`high`),V(this,`__isUnsignedLong__`),this.low=e|0,this.high=t|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(t){return new e(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24)}toBytesLE(){let e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(t){return isNaN(t)||t<0?et:t>=nt?rt:new e(t%U|0,t/U|0)}toString(){return(BigInt(this.high)*BigInt(U)+BigInt(this.low)).toString()}equals(t){return e.isLong(t)||(t=e.fromValue(t)),this.high>>>31==1&&t.high>>>31==1?!1:this.high===t.high&&this.low===t.low}notEquals(e){return!this.equals(e)}comp(t){return e.isLong(t)||(t=e.fromValue(t)),this.equals(t)?0:t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(t){return typeof t==`number`?e.fromNumber(t):new e(t.low,t.high)}};const et=new H(0,0),tt=65536,U=tt*tt,nt=U*U,rt=new H(-1,-1);var it=Object.defineProperty,at=(e,t,n)=>t in e?it(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,W=(e,t,n)=>at(e,typeof t==`symbol`?t:t+``,n),ot=class{constructor(e,t){W(this,`version`),W(this,`remoteQuerySet`),W(this,`queryPath`),W(this,`logger`),this.version={querySet:0,ts:H.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 n of t.logLines)N(this.logger,`info`,`query`,e,n);let n=b(t.value??null);this.remoteQuerySet.set(t.queryId,{success:!0,value:n,logLines:t.logLines});break}case`QueryFailed`:{let e=this.queryPath(t.queryId);if(e)for(let n of t.logLines)N(this.logger,`info`,`query`,e,n);let{errorData:n}=t;this.remoteQuerySet.set(t.queryId,{success:!1,errorMessage:t.errorMessage,errorData:n===void 0?void 0:b(n),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 G(e){let t=d(e);return H.fromBytesLE(Array.from(t))}function st(e){return p(new Uint8Array(e.toBytesLE()))}function ct(e){switch(e.type){case`FatalError`:case`AuthError`:case`ActionResponse`:case`TransitionChunk`:case`Ping`:return{...e};case`MutationResponse`:return e.success?{...e,ts:G(e.ts)}:{...e};case`Transition`:return{...e,startVersion:{...e.startVersion,ts:G(e.startVersion.ts)},endVersion:{...e.endVersion,ts:G(e.endVersion.ts)}}}}function lt(e){switch(e.type){case`Authenticate`:case`ModifyQuerySet`:case`Mutation`:case`Action`:case`Event`:return{...e};case`Connect`:return e.maxObservedTimestamp===void 0?{...e,maxObservedTimestamp:void 0}:{...e,maxObservedTimestamp:st(e.maxObservedTimestamp)}}}var ut=Object.defineProperty,dt=(e,t,n)=>t in e?ut(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,K=(e,t,n)=>dt(e,typeof t==`symbol`?t:t+``,n);let q;function J(){return q===void 0&&(q=Date.now()),typeof performance>`u`||!performance.now?Date.now():Math.round(q+performance.now())}function ft(){return`t=${Math.round((J()-q)/100)/10}s`}const pt={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}};function mt(e){if(e===void 0)return`Unknown`;for(let t of Object.keys(pt))if(e.startsWith(t))return t;return`Unknown`}var ht=class{constructor(e,t,n,r,i,a){this.markConnectionStateDirty=i,this.debug=a,K(this,`socket`),K(this,`connectionCount`),K(this,`_hasEverConnected`,!1),K(this,`lastCloseReason`),K(this,`transitionChunkBuffer`,null),K(this,`defaultInitialBackoff`),K(this,`maxBackoff`),K(this,`retries`),K(this,`serverInactivityThreshold`),K(this,`reconnectDueToServerInactivityTimeout`),K(this,`scheduledReconnect`,null),K(this,`networkOnlineHandler`,null),K(this,`pendingNetworkRecoveryInfo`,null),K(this,`uri`),K(this,`onOpen`),K(this,`onResume`),K(this,`onMessage`),K(this,`webSocketConstructor`),K(this,`logger`),K(this,`onServerDisconnectError`),this.webSocketConstructor=n,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.setupNetworkListener(),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()}setupNetworkListener(){typeof window>`u`||typeof window.addEventListener!=`function`||this.networkOnlineHandler===null&&(this.networkOnlineHandler=()=>{this._logVerbose(`network online event detected`),this.tryReconnectImmediately()},window.addEventListener(`online`,this.networkOnlineHandler),this._logVerbose(`network online event listener registered`))}cleanupNetworkListener(){this.networkOnlineHandler&&typeof window<`u`&&typeof window.removeEventListener==`function`&&(window.removeEventListener(`online`,this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose(`network online event listener removed`))}assembleTransition(e){if(e.partNumber<0||e.partNumber>=e.totalParts||e.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,Error(`Invalid TransitionChunk`);if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){let t=this.transitionChunkBuffer.chunks.length;throw 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=ct(JSON.parse(e));if(t.type!==`Transition`)throw Error(`Expected Transition, got ${t.type} after assembling chunks`);return t}return null}connect(){if(this.socket.state===`terminated`)return;if(this.socket.state!==`disconnected`&&this.socket.state!==`stopped`)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`),this.socket.state!==`connecting`)throw Error(`onopen called with socket not in connecting state`);if(this.setSocketState({state:`ready`,ws:e,paused:this.socket.paused===`yes`?`uninitialized`:`no`}),this.resetServerInactivityTimeout(),this.socket.paused===`no`&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:J()})),this.lastCloseReason!==`InitialConnect`&&(this.lastCloseReason?this.logger.log(`WebSocket reconnected at`,ft(),`after disconnect due to`,this.lastCloseReason):this.logger.log(`WebSocket reconnected at`,ft())),this.connectionCount+=1,this.lastCloseReason=null,this.pendingNetworkRecoveryInfo!==null){let{timeSavedMs:e}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:`Event`,eventType:`NetworkRecoveryReconnect`,event:{timeSavedMs:e}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(e/1e3)}s of waiting`)}},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,n=ct(JSON.parse(e.data));if(this._logVerbose(`received ws message with type ${n.type}`),n.type!==`Ping`){if(n.type===`TransitionChunk`){let e=this.assembleTransition(n);if(!e)return;n=e,this._logVerbose(`assembled full ws message of type ${n.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${n.type} while buffering TransitionChunks`)),n.type===`Transition`&&this.reportLargeTransition({messageLength:t,transition:n}),this.onMessage(n).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())}},e.onclose=e=>{if(this._logVerbose(`begin ws.onclose`),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=e.reason||`closed with code ${e.code}`),e.code!==1e3&&e.code!==1001&&e.code!==1005&&e.code!==4040){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=mt(e.reason);this.scheduleReconnect(t)}}socketState(){return this.socket.state}sendMessage(e){let t={type:e.type,...e.type===`Authenticate`&&e.tokenType===`User`?{value:`...${e.value.slice(-7)}`}:{}};if(this.socket.state===`ready`&&this.socket.paused===`no`){let n=lt(e),r=JSON.stringify(n),i=!1;try{this.socket.ws.send(r),i=!0}catch(e){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${e}`),this.closeAndReconnect(`FailedToSendMessage`)}return this._logVerbose(`${i?`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(){this.socket.state!==`terminated`&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect(`InactiveServer`)},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&=(clearTimeout(this.scheduledReconnect.timeout),null),this.socket={state:`disconnected`};let t=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(t)}ms`);let n=J(),r=setTimeout(()=>{this.scheduledReconnect?.timeout===r&&(this.scheduledReconnect=null,this.connect())},t);this.scheduledReconnect={timeout:r,scheduledAt:n,backoffMs: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.scheduledReconnect&&=(clearTimeout(this.scheduledReconnect.timeout),null),this.cleanupNetworkListener(),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`:{this.cleanupNetworkListener();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.setupNetworkListener(),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}}tryReconnectImmediately(){if(this._logVerbose(`tryReconnectImmediately called`),this.socket.state!==`disconnected`){this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);return}let e=null;if(this.scheduledReconnect){let t=J()-this.scheduledReconnect.scheduledAt;e=Math.max(0,this.scheduledReconnect.backoffMs-t),this._logVerbose(`would have waited ${Math.round(e)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(t)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose(`canceled scheduled reconnect`)}this.logger.log(`Network recovery detected, reconnecting immediately`),this.pendingNetworkRecoveryInfo=e===null?null:{timeSavedMs:e},this.connect()}resume(){switch(this.socket.state){case`connecting`:this.socket={...this.socket,paused:`no`};return;case`ready`:this.socket.paused===`uninitialized`?(this.socket={...this.socket,paused:`no`},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:J()})):this.socket.paused===`yes`&&(this.socket={...this.socket,paused:`no`},this.onResume());return;case`terminated`:case`stopped`:case`disconnected`:return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state===`ready`,hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){let t=(e===`client`?100:e===`Unknown`?this.defaultInitialBackoff:pt[e].timeout)*2**this.retries;this.retries+=1;let n=Math.min(t,this.maxBackoff);return n+n*(Math.random()-.5)}reportLargeTransition({transition:e,messageLength:t}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;let n=J()-e.clientClockSkew-e.serverTs/1e6,r=`${Math.round(n)}ms`,i=`${Math.round(t/1e4)/100}MB`,a=t/(n/1e3),o=`${Math.round(a/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}) which will take a long time to download on slower connections`):n>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:n,messageLength:t}})}};function gt(){return _t()}function _t(){return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}var Y=class extends Error{};Y.prototype.name=`InvalidTokenError`;function vt(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n=`0`+n),`%`+n}))}function yt(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{return vt(t)}catch{return atob(t)}}function bt(e,t){if(typeof e!=`string`)throw new Y(`Invalid token specified: must be a string`);t||={};let n=t.header===!0?0:1,r=e.split(`.`)[n];if(typeof r!=`string`)throw new Y(`Invalid token specified: missing part #${n+1}`);let i;try{i=yt(r)}catch(e){throw new Y(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new Y(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}var xt=Object.defineProperty,St=(e,t,n)=>t in e?xt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,X=(e,t,n)=>St(e,typeof t==`symbol`?t:t+``,n),Ct=class{constructor(e,t,n){X(this,`authState`,{state:`noAuth`}),X(this,`configVersion`,0),X(this,`syncState`),X(this,`authenticate`),X(this,`stopSocket`),X(this,`tryRestartSocket`),X(this,`pauseSocket`),X(this,`resumeSocket`),X(this,`clearAuth`),X(this,`logger`),X(this,`refreshTokenLeewaySeconds`),X(this,`initialAuthTokenReuse`),X(this,`lastRefreshChange`),X(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=n.logger,this.refreshTokenLeewaySeconds=n.refreshTokenLeewaySeconds,this.initialAuthTokenReuse=n.initialAuthTokenReuse,this.lastRefreshChange=!1}notifyRefreshChange(e){this.authState.state!==`noAuth`&&this.authState.state!==`initialRefetch`&&this.authState.config.onRefreshChange&&this.lastRefreshChange!==e&&(this.lastRefreshChange=e,this.authState.config.onRefreshChange(e))}async setConfig(e,t,n){this.resetAuthState(),this._logVerbose(`pausing WS for auth token fetch`),this.pauseSocket();let r=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});if(r.isFromOutdatedConfig)return;let i={fetchToken:e,onAuthChange:t,onRefreshChange:n};r.value?(this.setAuthState({state:`waitingForServerConfirmationOfCachedToken`,config:i,hasRetried:!1}),this.authenticate(r.value)):(this.setAuthState({state:`initialRefetch`,config:i}),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(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),this.authState.state===`waitingForServerConfirmationOfCachedToken`){this._logVerbose(`server confirmed auth token is valid`);let t=this.syncState.getAuth()?.value;this.initialAuthTokenReuse&&t?this.scheduleTokenRefetch(t,e.clientClockSkew):this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state===`waitingForServerConfirmationOfFreshToken`&&(this._logVerbose(`server confirmed new auth token is valid`),this.notifyRefreshChange(!1),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(e.authUpdateAttempted===!1&&(this.authState.state===`waitingForServerConfirmationOfFreshToken`||this.authState.state===`waitingForServerConfirmationOfCachedToken`)){this._logVerbose(`ignoring non-auth token expired error`);return}let{baseVersion:t}=e;if(!this.syncState.isCurrentOrNewerAuthVersion(t+1)){this._logVerbose(`ignoring auth error for previous auth attempt`);return}this.tryToReauthenticate(e)}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),this.authState.state===`noAuth`||this.authState.state===`waitingForServerConfirmationOfFreshToken`&&this.tokenConfirmationAttempts>=2){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!==`noAuth`&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}if(this.authState.state===`waitingForServerConfirmationOfFreshToken`&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${2-this.tokenConfirmationAttempts} attempts remaining`)),this.notifyRefreshChange(!0),await this.stopSocket(),this.authState.state===`noAuth`)return;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:this.authState.state===`notRefetching`||this.authState.state===`waitingForScheduledRefetch`})):(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(this.authState.state===`noAuth`)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,t){if(this.authState.state===`noAuth`)return;let n=this.decodeToken(e);if(!n){this.logger.error(`Auth token is not a valid JWT, cannot refetch the token`);return}let{iat:r,exp:i}=n;if(!r||!i){this.logger.error(`Auth token does not have required fields, cannot refetch the token`);return}let a=i-r;if(a<=2){this.logger.error(`Auth token does not live long enough, cannot refetch the token`);return}let o;t===void 0?o=a:(o=i-(Date.now()-t)/1e3,o<=0&&(o=0));let s=Math.min(1728e6,(o-this.refreshTokenLeewaySeconds)*1e3);s<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${o}s`),s=0);let c=setTimeout(()=>{this._logVerbose(`running scheduled token refetch`),this.refetchToken()},s);this.setAuthState({state:`waitingForScheduledRefetch`,refetchTokenTimeoutId:c,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${s}ms`)}async fetchTokenAndGuardAgainstRace(e,t){let n=++this.configVersion;this._logVerbose(`fetching token with config version ${n}`);let r=await e(t);return this.configVersion===n?{isFromOutdatedConfig:!1,value:r}:(this._logVerbose(`stale config version, expected ${n}, got ${this.configVersion}`),{isFromOutdatedConfig:!0})}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.notifyRefreshChange(!1),this.setAuthState({state:`noAuth`})}setAuthState(e){let t=e.state===`waitingForServerConfirmationOfFreshToken`?{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}this.authState.state===`waitingForScheduledRefetch`&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=e}decodeToken(e){try{return bt(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}]`)}};const wt=[`convexClientConstructed`,`convexWebSocketOpen`,`convexFirstMessageReceived`];function Tt(e,t){let n={sessionId:t};typeof performance>`u`||!performance.mark||performance.mark(e,{detail:n})}function Et(e){let t=e.name.slice(6);return t=t.charAt(0).toLowerCase()+t.slice(1),{name:t,startTime:e.startTime}}function Dt(e){if(typeof performance>`u`||!performance.getEntriesByName)return[];let t=[];for(let n of wt){let r=performance.getEntriesByName(n).filter(e=>e.entryType===`mark`).filter(t=>t.detail.sessionId===e);t.push(...r)}return t.map(Et)}var Ot=Object.defineProperty,kt=(e,t,n)=>t in e?Ot(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Z=(e,t,n)=>kt(e,typeof t==`symbol`?t:t+``,n),At=class{constructor(e,t,n){if(Z(this,`address`),Z(this,`state`),Z(this,`requestManager`),Z(this,`webSocketManager`),Z(this,`authenticationManager`),Z(this,`remoteQuerySet`),Z(this,`optimisticQueryResults`),Z(this,`_transitionHandlerCounter`,0),Z(this,`_nextRequestId`),Z(this,`_onTransitionFns`,new Map),Z(this,`_sessionId`),Z(this,`firstMessageReceived`,!1),Z(this,`debug`),Z(this,`logger`),Z(this,`maxObservedTimestamp`),Z(this,`connectionStateSubscribers`,new Map),Z(this,`nextConnectionStateSubscriberId`,0),Z(this,`_lastPublishedConnectionState`),Z(this,`markConnectionStateDirty`,()=>{Promise.resolve().then(()=>{let e=this.connectionState();if(JSON.stringify(e)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=e;for(let t of this.connectionStateSubscribers.values())t(e)}})}),Z(this,`mark`,e=>{this.debug&&Tt(e,this.sessionId)}),typeof e==`object`)throw Error(`Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.`);n?.skipConvexDeploymentUrlCheck!==!0&&te(e),n={...n};let r=n.authRefreshTokenLeewaySeconds??10,i=n.webSocketConstructor;if(!i&&typeof WebSocket>`u`)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`);i||=WebSocket,this.debug=n.reportDebugInfoToConvex??!1,this.address=e,this.logger=n.logger===!1?Re({verbose:n.verbose??!1}):n.logger!==!0&&n.logger?n.logger:Le({verbose:n.verbose??!1});let a=e.search(`://`);if(a===-1)throw Error(`Provided address was not an absolute URL.`);let o=e.substring(a+3),s=e.substring(0,a),c;if(s===`http`)c=`ws`;else if(s===`https`)c=`wss`;else throw Error(`Unknown parent protocol ${s}`);let l=`${c}://${o}/api/${xe}/sync`;this.state=new We,this.remoteQuerySet=new ot(e=>this.state.queryPath(e),this.logger),this.requestManager=new qe(this.logger,this.markConnectionStateDirty);let u=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new Ct(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:u,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:r,initialAuthTokenReuse:n.initialAuthTokenReuse??!1}),this.optimisticQueryResults=new Ze,this.addOnTransitionHandler(e=>{t(e.queries.map(e=>e.token))}),this._nextRequestId=0,this._sessionId=gt();let{unsavedChangesWarning:d}=n;if(typeof window>`u`||window.addEventListener===void 0){if(d===!0)throw Error(`unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.`)}else d!==!1&&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 ht(l,{onOpen:e=>{this.mark(`convexWebSocketOpen`),this.webSocketManager.sendMessage({...e,type:`Connect`,sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new ot(e=>this.state.queryPath(e),this.logger);let[t,n]=this.state.restart();n&&this.webSocketManager.sendMessage(n),this.webSocketManager.sendMessage(t);for(let e of this.requestManager.restart())this.webSocketManager.sendMessage(e)},onResume:()=>{let[e,t]=this.state.resume();t&&this.webSocketManager.sendMessage(t),e&&this.webSocketManager.sendMessage(e);for(let e of this.requestManager.resume())this.webSocketManager.sendMessage(e)},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);t!==null&&this.notifyOnQueryResultChanges(new Map([[t.requestId,t.result]]));break}case`ActionResponse`:this.requestManager.onResponse(e);break;case`AuthError`:this.authenticationManager.onAuthError(e);break;case`FatalError`:{let t=ze(this.logger,e.error);throw this.webSocketManager.terminate(),t}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:n.onServerDisconnectError},i,this.logger,this.markConnectionStateDirty,this.debug),this.mark(`convexClientConstructed`),n.expectAuth&&u()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){let t=this.remoteQuerySet.remoteQueryResults(),n=new Map;for(let[e,r]of t){let t=this.state.queryToken(e);if(t!==null){let i={result:r,udfPath:this.state.queryPath(e),args:this.state.queryArgs(e)};n.set(t,i)}}let r=this.optimisticQueryResults.ingestQueryResultsFromServer(n,new Set(e.keys()));this.handleTransition({queries:r.map(e=>({token:e,modification:{kind:`Updated`,result:this.optimisticQueryResults.rawQueryResult(e)}})),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&&e.tokenType===`User`)try{t=e?bt(e.value):{}}catch{t={}}else return;return{token:e.value,decoded:t}}setAuth(e,t,n){this.authenticationManager.setConfig(e,t,n)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,t){let n=this.state.setAdminAuth(e,t);this.webSocketManager.sendMessage(n)}clearAuth(){let e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,t,n){let r=m(t),{modification:i,queryToken:a,unsubscribe:o}=this.state.subscribe(e,r,n?.journal,n?.componentPath);return i!==null&&this.webSocketManager.sendMessage(i),{queryToken:a,unsubscribe:()=>{let e=o();e&&this.webSocketManager.sendMessage(e)}}}localQueryResult(e,t){let n=L(e,m(t));return this.optimisticQueryResults.queryResult(n)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,t){let n=L(e,m(t));return this.optimisticQueryResults.queryLogs(n)}queryJournal(e,t){let n=L(e,m(t));return this.state.queryJournal(n)}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,n){let r=await this.mutationInternal(e,t,n);if(!r.success)throw r.errorData===void 0?Error(P(`mutation`,e,r)):F(r,new E(P(`mutation`,e,r)));return r.value}async mutationInternal(e,t,n,r){let{mutationPromise:i}=this.enqueueMutation(e,t,n,r);return i}enqueueMutation(e,t,n,r){let i=m(t);this.tryReportLongDisconnect();let a=this.nextRequestId;if(this._nextRequestId++,n!==void 0){let e=n.optimisticUpdate;if(e!==void 0){let t=this.optimisticQueryResults.applyOptimisticUpdate(t=>{e(t,i)instanceof Promise&&this.logger.warn(`Optimistic update handler returned a Promise. Optimistic updates should be synchronous.`)},a).map(e=>{let t=this.localQueryResultByToken(e);return{token:e,modification:{kind:`Updated`,result:t===void 0?void 0:{success:!0,value:t,logLines:[]}}}});this.handleTransition({queries:t,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let o={type:`Mutation`,requestId:a,udfPath:e,componentPath:r,args:[w(i)]},s=this.webSocketManager.sendMessage(o);return{requestId:a,mutationPromise:this.requestManager.request(o,s)}}async action(e,t){let n=await this.actionInternal(e,t);if(!n.success)throw n.errorData===void 0?Error(P(`action`,e,n)):F(n,new E(P(`action`,e,n)));return n.value}async actionInternal(e,t,n){let r=m(t),i=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let a={type:`Action`,requestId:i,udfPath:e,componentPath:n,args:[w(r)]},o=this.webSocketManager.sendMessage(a);return this.requestManager.request(a,o)}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=Dt(this.sessionId);this.webSocketManager.sendMessage({type:`Event`,eventType:`ClientConnect`,event:e})}}tryReportLongDisconnect(){if(!this.debug)return;let e=this.connectionState().timeOfOldestInflightRequest;if(e===null||Date.now()-e.getTime()<=6e4)return;let t=`${this.address}/api/debug_event`;fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,"Convex-Client":`npm-${xe}`},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)})}};function Q(e){if(typeof e!=`object`||!e||!Array.isArray(e.page)||typeof e.isDone!=`boolean`||typeof e.continueCursor!=`string`)throw Error(`Not a valid paginated query result: ${e?.toString()}`);return e}var jt=Object.defineProperty,Mt=(e,t,n)=>t in e?jt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Nt=(e,t,n)=>Mt(e,typeof t==`symbol`?t:t+``,n),Pt=class{constructor(e,t){this.client=e,this.onTransition=t,Nt(this,`paginatedQuerySet`,new Map),Nt(this,`lastTransitionTs`),this.lastTransitionTs=H.fromNumber(0),this.client.addOnTransitionHandler(e=>this.onBaseTransition(e))}subscribe(e,t,n){let r=I(e),i=Be(r,t,n),a=()=>this.removePaginatedQuerySubscriber(i),o=this.paginatedQuerySet.get(i);return o?(o.numSubscribers+=1,{paginatedQueryToken:i,unsubscribe:a}):(this.paginatedQuerySet.set(i,{token:i,canonicalizedUdfPath:r,args:t,numSubscribers:1,options:{initialNumItems:n.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:n.id}),this.addPageToPaginatedQuery(i,null,n.initialNumItems),{paginatedQueryToken:i,unsubscribe:a})}localQueryResult(e,t,n){let r=Be(I(e),t,n);return this.localQueryResultByToken(r)}localQueryResultByToken(e){let t=this.paginatedQuerySet.get(e);if(!t)return;let n=this.activePageQueryTokens(t);if(n.length===0)return{results:[],status:`LoadingFirstPage`,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)};let r=[],i=!1,a=!1;for(let e of n){let t=this.client.localQueryResultByToken(e);if(t===void 0){i=!0,a=!1;continue}let n=Q(t);r=r.concat(n.page),a=!!n.isDone}let o;return o=i?r.length===0?`LoadingFirstPage`:`LoadingMore`:a?`Exhausted`:`CanLoadMore`,{results:r,status:o,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)}}onBaseTransition(e){let t=e.queries.map(e=>e.token),n=this.queriesContainingTokens(t),r=[];n.length>0&&(this.processPaginatedQuerySplits(n,e=>this.client.localQueryResultByToken(e)),r=n.map(e=>({token:e,modification:{kind:`Updated`,result:this.localQueryResultByToken(e)}})));let i={...e,paginatedQueries:r};this.onTransition(i)}loadMoreOfPaginatedQuery(e,t){this.mustGetPaginatedQuery(e);let n=this.queryTokenForLastPageOfPaginatedQuery(e),r=this.client.localQueryResultByToken(n);if(!r)return!1;let i=Q(r);if(i.isDone)return!1;this.addPageToPaginatedQuery(e,i.continueCursor,t);let a={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:`Updated`,result:this.localQueryResultByToken(e)}}]};return this.onTransition(a),!0}queriesContainingTokens(e){if(e.length===0)return[];let t=[],n=new Set(e);for(let[e,r]of this.paginatedQuerySet)for(let i of this.allQueryTokens(r))if(n.has(i)){t.push(e);break}return t}processPaginatedQuerySplits(e,t){for(let n of e){let e=this.mustGetPaginatedQuery(n),{ongoingSplits:r,pageKeyToQuery:i,pageKeys:a}=e;for(let[n,[a,o]]of r)t(i.get(a).queryToken)!==void 0&&t(i.get(o).queryToken)!==void 0&&this.completePaginatedQuerySplit(e,n,a,o);for(let n of a){if(r.has(n))continue;let a=i.get(n);if(!a)throw Error(`No page query for active pageKey ${n}`);let o=t(a.queryToken);if(!o)continue;let s=Q(o);s.splitCursor&&(s.pageStatus===`SplitRecommended`||s.pageStatus===`SplitRequired`||s.page.length>e.options.initialNumItems*2)&&this.splitPaginatedQueryPage(e,n,a.cursor,s.splitCursor,s.continueCursor)}}}splitPaginatedQueryPage(e,t,n,r,i){let a=e.nextPageKey++,o=e.nextPageKey++,s={numItems:e.options.initialNumItems,id:e.id},c=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...s,cursor:n,endCursor:r}});e.pageKeyToQuery.set(a,{...c,cursor:n});let l=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...s,cursor:r,endCursor:i}});e.pageKeyToQuery.set(o,{...l,cursor:r}),e.ongoingSplits.set(t,[a,o])}addPageToPaginatedQuery(e,t,n){let r=this.mustGetPaginatedQuery(e),i=r.nextPageKey++,a={cursor:t,numItems:n,id:r.id},o={...r.args,paginationOpts:a},s=this.client.subscribe(r.canonicalizedUdfPath,o);return r.pageKeys.push(i),r.pageKeyToQuery.set(i,{...s,cursor:t}),s}removePaginatedQuerySubscriber(e){let t=this.paginatedQuerySet.get(e);if(t&&(--t.numSubscribers,!(t.numSubscribers>0))){for(let e of t.pageKeyToQuery.values())e.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,t,n,r){let i=e.pageKeyToQuery.get(t);e.pageKeyToQuery.delete(t);let a=e.pageKeys.indexOf(t);e.pageKeys.splice(a,1,n,r),e.ongoingSplits.delete(t),i.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(t=>e.pageKeyToQuery.get(t).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(e=>e.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){let t=this.mustGetPaginatedQuery(e),n=t.pageKeys[t.pageKeys.length-1];if(n===void 0)throw Error(`No pages for paginated query ${e}`);return t.pageKeyToQuery.get(n).queryToken}mustGetPaginatedQuery(e){let t=this.paginatedQuerySet.get(e);if(!t)throw Error(`paginated query no longer exists for token `+e);return t}},Ft=Object.defineProperty,It=(e,t,n)=>t in e?Ft(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,$=(e,t,n)=>It(e,typeof t==`symbol`?t:t+``,n),Lt=class{constructor(e,t={}){$(this,`listeners`),$(this,`_client`),$(this,`_paginatedClient`),$(this,`callNewListenersWithCurrentValuesTimer`),$(this,`_closed`),$(this,`_disabled`),t.skipConvexDeploymentUrlCheck!==!0&&te(e);let{disabled:n,...r}=t;this._closed=!1,this._disabled=!!n,typeof window>`u`&&!(`unsavedChangesWarning`in r)&&(r.unsavedChangesWarning=!1),this.disabled||(this._client=new At(e,()=>{},r),this._paginatedClient=new Pt(this._client,e=>this._transition(e))),this.listeners=new Set}get closed(){return this._closed}get client(){if(this._client)return this._client;throw Error(`ConvexClient is disabled`)}get paginatedClient(){if(this._paginatedClient)return this._paginatedClient;throw Error(`ConvexClient is disabled`)}get disabled(){return this._disabled}onUpdate(e,t,n,r){if(this.disabled)return this.createDisabledUnsubscribe();let{queryToken:i,unsubscribe:a}=this.client.subscribe(O(e),t),o={queryToken:i,callback:n,onError:r,unsubscribe:a,hasEverRun:!1,query:e,args:t,paginationOptions:void 0};this.listeners.add(o),this.queryResultReady(i)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let s={unsubscribe:()=>{this.closed||(this.listeners.delete(o),a())},getCurrentValue:()=>this.client.localQueryResultByToken(i),getQueryLogs:()=>this.client.localQueryLogs(i)},c=s.unsubscribe;return Object.assign(c,s),c}onPaginatedUpdate_experimental(e,t,n,r,i){if(this.disabled)return this.createDisabledUnsubscribe();let a={initialNumItems:n.initialNumItems,id:-1},{paginatedQueryToken:o,unsubscribe:s}=this.paginatedClient.subscribe(O(e),t,a),c={queryToken:o,callback:r,onError:i,unsubscribe:s,hasEverRun:!1,query:e,args:t,paginationOptions:a};this.listeners.add(c),this.paginatedClient.localQueryResultByToken(o)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let l={unsubscribe:()=>{this.closed||(this.listeners.delete(c),s())},getCurrentValue:()=>this.paginatedClient.localQueryResult(O(e),t,a),getQueryLogs:()=>[]},u=l.unsubscribe;return Object.assign(u,l),u}callNewListenersWithCurrentValues(){this.callNewListenersWithCurrentValuesTimer=void 0,this._transition({queries:[],paginatedQueries:[]},!0)}queryResultReady(e){return this.client.hasLocalQueryResultByToken(e)}createDisabledUnsubscribe(){let e=(()=>{});return Object.assign(e,{unsubscribe:e,getCurrentValue:()=>void 0,getQueryLogs:()=>void 0}),e}async close(){if(!this.disabled)return this.listeners.clear(),this._closed=!0,this._paginatedClient&&=void 0,this.client.close()}getAuth(){if(!this.disabled)return this.client.getCurrentAuthClaims()}setAuth(e,t){this.disabled||this.client.setAuth(e,t??(()=>{}))}setAdminAuth(e,t){if(this.closed)throw Error(`ConvexClient has already been closed.`);this.disabled||this.client.setAdminAuth(e,t)}_transition({queries:e,paginatedQueries:t},n=!1){let r=[...e.map(e=>e.token),...t.map(e=>e.token)];for(let e of this.listeners){let{callback:t,queryToken:i,onError:a,hasEverRun:o}=e,s=Ve(i),c=s?!!this.paginatedClient.localQueryResultByToken(i):this.client.hasLocalQueryResultByToken(i);if(r.includes(i)||n&&!o&&c){e.hasEverRun=!0;let n;try{n=s?this.paginatedClient.localQueryResultByToken(i):this.client.localQueryResultByToken(i)}catch(e){if(!(e instanceof Error))throw e;a?a(e,`Second argument to onUpdate onError is reserved for later use`):Promise.reject(e);continue}t(n,`Second argument to onUpdate callback is reserved for later use`)}}}async mutation(e,t,n){if(this.disabled)throw Error(`ConvexClient is disabled`);return await this.client.mutation(O(e),t,n)}async action(e,t){if(this.disabled)throw Error(`ConvexClient is disabled`);return await this.client.action(O(e),t)}async query(e,t){if(this.disabled)throw Error(`ConvexClient is disabled`);let n=this.client.localQueryResult(O(e),t);return n===void 0?new Promise((n,r)=>{let{unsubscribe:i}=this.onUpdate(e,t,e=>{i(),n(e)},e=>{i(),r(e)})}):Promise.resolve(n)}connectionState(){if(this.disabled)throw Error(`ConvexClient is disabled`);return this.client.connectionState()}subscribeToConnectionState(e){return this.disabled?()=>{}:this.client.subscribeToConnectionState(e)}};function Rt(e,t){let n=e.trim();if(!/^https:\/\/[^/]+$/.test(n))throw Error(`A valid HTTPS Convex deployment URL is required`);let r=new Lt(n);return r.setAuth(t),r}function zt(e,t){let n=e.trim();if(!n)throw Error(`Convex deployment URL is required`);return{async resolve(e){let r=await t.fetchAccessToken(Wt(e,!1));if(!r)throw Error(`Convex review authentication is required`);let i=r,a=(t.clientFactory??Rt)(n,async({forceRefreshToken:n})=>{if(!n&&i){let e=i;return i=null,e}return t.fetchAccessToken({...Wt(e,n),signal:new AbortController().signal})}),o=await a.mutation(A.resolveSession,{invitationId:e.invitationId,origin:e.location.origin,pathname:e.location.pathname,...e.routeKey===void 0?{}:{routeKey:e.routeKey}}),s=Gt(o.session,e.invitationId),c=0;return Bt({client:a,session:s,request:e,pageId:o.pageId,resolvePage:async t=>{if(t.location.origin!==e.location.origin)throw Error(`Convex review session cannot move to another origin`);let n=++c,r=await a.mutation(A.resolveSession,{invitationId:e.invitationId,origin:t.location.origin,pathname:t.location.pathname,...t.routeKey===void 0?{}:{routeKey:t.routeKey}});if(t.signal.aborted||n!==c)throw Kt();return{pageId:r.pageId,...t.cursorChat?{cursorChatRoomId:Ut(r.pageId)}:{}}},cursorChatRepositoryFactory:t.cursorChatRepositoryFactory})}}}async function Bt(e){let t=new De(e.client,e.session,{origin:e.request.location.origin}),n;if(e.request.cursorChat)try{n=await Vt(e.client,e.session,e.request.location.origin,e.cursorChatRepositoryFactory)}catch{}return{pageId:e.pageId,session:e.session,repository:t,...n?{cursorChatRepository:n,cursorChatRoomId:Ut(e.pageId)}:{},resolvePage:e.resolvePage,allowedStagingHosts:[e.request.location.hostname]}}async function Vt(e,t,n,r=Ht){return r(e,t,n)}async function Ht(e,t,n){let{ConvexReviewCursorChatRepository:r}=await import(`./cursor-chat-repository-CaF-65Xc.js`);return new r(e,t,{origin:n})}function Ut(e){return`cursor-chat:${e}`}function Wt(e,t){return{invitationId:e.invitationId,origin:e.location.origin,pathname:e.location.pathname,...e.emailToken===void 0?{}:{emailToken:e.emailToken},forceRefreshToken:t,signal:e.signal}}function Gt(e,t){if(!e||e.invitationId!==t||!e.authUserId||!e.reviewerId||!e.projectId)throw Error(`Convex returned an invalid reviewer session`);return structuredClone(e)}function Kt(){return Object.assign(Error(`Review page resolution was superseded`),{code:`PAGE_SWAP_SUPERSEDED`})}export{zt as createConvexReviewRuntime,A as n,j as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,t}from"./convex-runtime-
|
|
1
|
+
import{n as e,t}from"./convex-runtime-CpgGS5hl.js";var n=class{client;#e=new Map;#t;#n;#r;#i;#a;#o;constructor(e,t,n){this.client=e,this.#t=t.invitationId.trim(),this.#n=new URL(n.origin).origin,this.#r=i(n.cursorThrottleMs??80,40,1e3),this.#i=i(n.heartbeatMs??1e4,2e3,2e4),this.#a=n.now??Date.now,this.#o=n.sessionId??(()=>globalThis.crypto.randomUUID())}subscribe(n,r,i,a){let o=!1,s=[],c=this.#s(n,r.roomId,a),l=()=>{o||i({pageId:n,peers:structuredClone(s)})},u;try{u=this.client.onUpdate(e.presenceList,{...this.#d(),pageId:n,roomId:r.roomId},e=>{let t=this.#a();s=e.filter(({peerId:e,expiresAt:n})=>e!==c.sessionId&&n>t).map(({expiresAt:e,...t})=>t).sort((e,t)=>e.displayName.localeCompare(t.displayName)||e.peerId.localeCompare(t.peerId)),l()},e=>a?.(t(e)))}catch(e){throw this.#u(c),e}return queueMicrotask(l),()=>{o||(o=!0,u(),this.#u(c))}}publishPresence(e,t,n){let i=this.#e.get(r(e,t));!i||i.stopped||(i.current={...n},i.latest={...i.current},this.#c(i))}#s(e,t,n){let i=r(e,t),a=this.#e.get(i);a&&this.#u(a);let o={pageId:e,roomId:t,sessionId:this.#o(),stopped:!1,lastSentAt:-1/0,inFlight:!1,onFailure:n};return o.heartbeatTimer=setInterval(()=>{o.stopped||!o.current||(o.latest??={...o.current},this.#c(o))},this.#i),this.#e.set(i,o),o}#c(e){if(e.inFlight||e.flushTimer||e.stopped)return;let t=Math.max(0,this.#r-(this.#a()-e.lastSentAt));if(t===0){this.#l(e);return}e.flushTimer=setTimeout(()=>{e.flushTimer=void 0,this.#l(e)},t)}async#l(n){if(n.stopped||n.inFlight||!n.latest)return;n.inFlight=!0;let r=n.latest;n.latest=void 0;try{await this.client.mutation(e.presenceUpdate,{...this.#d(),pageId:n.pageId,roomId:n.roomId,sessionId:n.sessionId,active:r.active,...r.pathname===void 0?{}:{pathname:r.pathname},...r.cursorX===void 0?{}:{cursorX:r.cursorX},...r.cursorY===void 0?{}:{cursorY:r.cursorY},...r.viewportWidth===void 0?{}:{viewportWidth:r.viewportWidth},...r.viewportHeight===void 0?{}:{viewportHeight:r.viewportHeight},...r.cursorChat===void 0?{}:{cursorChat:r.cursorChat}}),n.lastSentAt=this.#a()}catch(e){n.onFailure?.(t(e))}finally{n.inFlight=!1,n.latest&&this.#c(n)}}#u(t){t.stopped||(t.stopped=!0,t.current=void 0,t.latest=void 0,t.flushTimer&&clearTimeout(t.flushTimer),t.heartbeatTimer&&clearInterval(t.heartbeatTimer),this.#e.delete(r(t.pageId,t.roomId)),this.client.mutation(e.presenceDisconnect,{...this.#d(),sessionId:t.sessionId}).catch(()=>void 0))}#d(){return{invitationId:this.#t,origin:this.#n}}};function r(e,t){return`${e}\u0000${t}`}function i(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,Math.round(e))):t}export{n as ConvexReviewCursorChatRepository};
|