{"version":3,"file":"server.Cy7Q9_P4.mjs","names":["len","arr","i","i","Base64.fromByteArray","Base64.toByteArray","v","__defProp","__defNormalProp","__publicField","v","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","i","functionName","__defProp","__defNormalProp","__publicField","version","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","Base64.toByteArray","Base64.fromByteArray","__defProp","__defNormalProp","__publicField","code","e","__defProp","__defNormalProp","__publicField","e","__defProp","__defNormalProp","__publicField","i","e","__defProp","__defNormalProp","__publicField","useState","useContext","useMemo","__defProp","__defNormalProp","__publicField","React","e","__defProp","__defNormalProp","__publicField","e","useMemo","useState","createContext","e","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField","__defProp","__defNormalProp","__publicField"],"sources":["https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/values/base64.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/common/index.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/values/value.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/values/validators.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/values/validator.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/values/errors.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/values/compare_utf8.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/values/compare.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/values/index.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/index.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/logging.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/sync/udf_path_utils.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/sync/local_state.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/sync/request_manager.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/functionName.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/components/paths.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/api.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/sync/optimistic_updates_impl.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/vendor/long.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/sync/remote_query_set.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/sync/protocol.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/sync/web_socket_manager.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/sync/session.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/vendor/jwt-decode/index.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/sync/authentication_manager.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/sync/metrics.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/sync/client.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/sync/pagination.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/sync/paginated_query_client.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/simple_client.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/http_client.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/browser/index.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/react/use_subscription.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/react/client.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/react/queries_observer.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/react/use_queries.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/react/use_paginated_query.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/react/use_paginated_query2.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/react/ConvexAuthState.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/react/auth_helpers.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/react/hydration.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/react/index.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/database.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/impl/syscall.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/impl/actions_impl.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/impl/validate.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/impl/vector_search_impl.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/impl/authentication_impl.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/filter_builder.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/impl/filter_builder_impl.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/index_range_builder.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/impl/index_range_builder_impl.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/search_filter_builder.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/impl/search_filter_builder_impl.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/impl/query_impl.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/impl/database_impl.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/impl/scheduler_impl.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/impl/storage_impl.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/impl/registration_impl.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/pagination.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/storage.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/cron.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/router.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/components/index.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/schema.js","https:/cdn.jsdelivr.net/npm/convex@1.31.7/dist/esm/server/index.js"],"sourcesContent":["\"use strict\";\nvar lookup = [];\nvar revLookup = [];\nvar Arr = Uint8Array;\nvar code = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nfor (var i = 0, len = code.length; i < len; ++i) {\n  lookup[i] = code[i];\n  revLookup[code.charCodeAt(i)] = i;\n}\nrevLookup[\"-\".charCodeAt(0)] = 62;\nrevLookup[\"_\".charCodeAt(0)] = 63;\nfunction getLens(b64) {\n  var len = b64.length;\n  if (len % 4 > 0) {\n    throw new Error(\"Invalid string. Length must be a multiple of 4\");\n  }\n  var validLen = b64.indexOf(\"=\");\n  if (validLen === -1) validLen = len;\n  var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;\n  return [validLen, placeHoldersLen];\n}\nexport function byteLength(b64) {\n  var lens = getLens(b64);\n  var validLen = lens[0];\n  var placeHoldersLen = lens[1];\n  return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;\n}\nfunction _byteLength(_b64, validLen, placeHoldersLen) {\n  return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;\n}\nexport function toByteArray(b64) {\n  var tmp;\n  var lens = getLens(b64);\n  var validLen = lens[0];\n  var placeHoldersLen = lens[1];\n  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));\n  var curByte = 0;\n  var len = placeHoldersLen > 0 ? validLen - 4 : validLen;\n  var i;\n  for (i = 0; i < len; i += 4) {\n    tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];\n    arr[curByte++] = tmp >> 16 & 255;\n    arr[curByte++] = tmp >> 8 & 255;\n    arr[curByte++] = tmp & 255;\n  }\n  if (placeHoldersLen === 2) {\n    tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;\n    arr[curByte++] = tmp & 255;\n  }\n  if (placeHoldersLen === 1) {\n    tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;\n    arr[curByte++] = tmp >> 8 & 255;\n    arr[curByte++] = tmp & 255;\n  }\n  return arr;\n}\nfunction tripletToBase64(num) {\n  return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];\n}\nfunction encodeChunk(uint8, start, end) {\n  var tmp;\n  var output = [];\n  for (var i = start; i < end; i += 3) {\n    tmp = (uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (uint8[i + 2] & 255);\n    output.push(tripletToBase64(tmp));\n  }\n  return output.join(\"\");\n}\nexport function fromByteArray(uint8) {\n  var tmp;\n  var len = uint8.length;\n  var extraBytes = len % 3;\n  var parts = [];\n  var maxChunkLength = 16383;\n  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n    parts.push(\n      encodeChunk(\n        uint8,\n        i,\n        i + maxChunkLength > len2 ? len2 : i + maxChunkLength\n      )\n    );\n  }\n  if (extraBytes === 1) {\n    tmp = uint8[len - 1];\n    parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + \"==\");\n  } else if (extraBytes === 2) {\n    tmp = (uint8[len - 2] << 8) + uint8[len - 1];\n    parts.push(\n      lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + \"=\"\n    );\n  }\n  return parts.join(\"\");\n}\nexport function fromByteArrayUrlSafeNoPadding(uint8) {\n  return fromByteArray(uint8).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\n//# sourceMappingURL=base64.js.map\n","\"use strict\";\nexport function parseArgs(args) {\n  if (args === void 0) {\n    return {};\n  }\n  if (!isSimpleObject(args)) {\n    throw new Error(\n      `The arguments to a Convex function must be an object. Received: ${args}`\n    );\n  }\n  return args;\n}\nexport function validateDeploymentUrl(deploymentUrl) {\n  if (typeof deploymentUrl === \"undefined\") {\n    throw new Error(\n      `Client created with undefined deployment address. If you used an environment variable, check that it's set.`\n    );\n  }\n  if (typeof deploymentUrl !== \"string\") {\n    throw new Error(\n      `Invalid deployment address: found ${deploymentUrl}\".`\n    );\n  }\n  if (!(deploymentUrl.startsWith(\"http:\") || deploymentUrl.startsWith(\"https:\"))) {\n    throw new Error(\n      `Invalid deployment address: Must start with \"https://\" or \"http://\". Found \"${deploymentUrl}\".`\n    );\n  }\n  try {\n    new URL(deploymentUrl);\n  } catch {\n    throw new Error(\n      `Invalid deployment address: \"${deploymentUrl}\" is not a valid URL. If you believe this URL is correct, use the \\`skipConvexDeploymentUrlCheck\\` option to bypass this.`\n    );\n  }\n  if (deploymentUrl.endsWith(\".convex.site\")) {\n    throw new Error(\n      `Invalid deployment address: \"${deploymentUrl}\" 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.`\n    );\n  }\n}\nexport function isSimpleObject(value) {\n  const isObject = typeof value === \"object\";\n  const prototype = Object.getPrototypeOf(value);\n  const isSimple = prototype === null || prototype === Object.prototype || // Objects generated from other contexts (e.g. across Node.js `vm` modules) will not satisfy the previous\n  // conditions but are still simple objects.\n  prototype?.constructor?.name === \"Object\";\n  return isObject && isSimple;\n}\n//# sourceMappingURL=index.js.map\n","\"use strict\";\nimport * as Base64 from \"./base64.js\";\nimport { isSimpleObject } from \"../common/index.js\";\nconst LITTLE_ENDIAN = true;\nconst MIN_INT64 = BigInt(\"-9223372036854775808\");\nconst MAX_INT64 = BigInt(\"9223372036854775807\");\nconst ZERO = BigInt(\"0\");\nconst EIGHT = BigInt(\"8\");\nconst TWOFIFTYSIX = BigInt(\"256\");\nfunction isSpecial(n) {\n  return Number.isNaN(n) || !Number.isFinite(n) || Object.is(n, -0);\n}\nexport function slowBigIntToBase64(value) {\n  if (value < ZERO) {\n    value -= MIN_INT64 + MIN_INT64;\n  }\n  let hex = value.toString(16);\n  if (hex.length % 2 === 1) hex = \"0\" + hex;\n  const bytes = new Uint8Array(new ArrayBuffer(8));\n  let i = 0;\n  for (const hexByte of hex.match(/.{2}/g).reverse()) {\n    bytes.set([parseInt(hexByte, 16)], i++);\n    value >>= EIGHT;\n  }\n  return Base64.fromByteArray(bytes);\n}\nexport function slowBase64ToBigInt(encoded) {\n  const integerBytes = Base64.toByteArray(encoded);\n  if (integerBytes.byteLength !== 8) {\n    throw new Error(\n      `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`\n    );\n  }\n  let value = ZERO;\n  let power = ZERO;\n  for (const byte of integerBytes) {\n    value += BigInt(byte) * TWOFIFTYSIX ** power;\n    power++;\n  }\n  if (value > MAX_INT64) {\n    value += MIN_INT64 + MIN_INT64;\n  }\n  return value;\n}\nexport function modernBigIntToBase64(value) {\n  if (value < MIN_INT64 || MAX_INT64 < value) {\n    throw new Error(\n      `BigInt ${value} does not fit into a 64-bit signed integer.`\n    );\n  }\n  const buffer = new ArrayBuffer(8);\n  new DataView(buffer).setBigInt64(0, value, true);\n  return Base64.fromByteArray(new Uint8Array(buffer));\n}\nexport function modernBase64ToBigInt(encoded) {\n  const integerBytes = Base64.toByteArray(encoded);\n  if (integerBytes.byteLength !== 8) {\n    throw new Error(\n      `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`\n    );\n  }\n  const intBytesView = new DataView(integerBytes.buffer);\n  return intBytesView.getBigInt64(0, true);\n}\nexport const bigIntToBase64 = DataView.prototype.setBigInt64 ? modernBigIntToBase64 : slowBigIntToBase64;\nexport const base64ToBigInt = DataView.prototype.getBigInt64 ? modernBase64ToBigInt : slowBase64ToBigInt;\nconst MAX_IDENTIFIER_LEN = 1024;\nfunction validateObjectField(k) {\n  if (k.length > MAX_IDENTIFIER_LEN) {\n    throw new Error(\n      `Field name ${k} exceeds maximum field name length ${MAX_IDENTIFIER_LEN}.`\n    );\n  }\n  if (k.startsWith(\"$\")) {\n    throw new Error(`Field name ${k} starts with a '$', which is reserved.`);\n  }\n  for (let i = 0; i < k.length; i += 1) {\n    const charCode = k.charCodeAt(i);\n    if (charCode < 32 || charCode >= 127) {\n      throw new Error(\n        `Field name ${k} has invalid character '${k[i]}': Field names can only contain non-control ASCII characters`\n      );\n    }\n  }\n}\nexport function jsonToConvex(value) {\n  if (value === null) {\n    return value;\n  }\n  if (typeof value === \"boolean\") {\n    return value;\n  }\n  if (typeof value === \"number\") {\n    return value;\n  }\n  if (typeof value === \"string\") {\n    return value;\n  }\n  if (Array.isArray(value)) {\n    return value.map((value2) => jsonToConvex(value2));\n  }\n  if (typeof value !== \"object\") {\n    throw new Error(`Unexpected type of ${value}`);\n  }\n  const entries = Object.entries(value);\n  if (entries.length === 1) {\n    const key = entries[0][0];\n    if (key === \"$bytes\") {\n      if (typeof value.$bytes !== \"string\") {\n        throw new Error(`Malformed $bytes field on ${value}`);\n      }\n      return Base64.toByteArray(value.$bytes).buffer;\n    }\n    if (key === \"$integer\") {\n      if (typeof value.$integer !== \"string\") {\n        throw new Error(`Malformed $integer field on ${value}`);\n      }\n      return base64ToBigInt(value.$integer);\n    }\n    if (key === \"$float\") {\n      if (typeof value.$float !== \"string\") {\n        throw new Error(`Malformed $float field on ${value}`);\n      }\n      const floatBytes = Base64.toByteArray(value.$float);\n      if (floatBytes.byteLength !== 8) {\n        throw new Error(\n          `Received ${floatBytes.byteLength} bytes, expected 8 for $float`\n        );\n      }\n      const floatBytesView = new DataView(floatBytes.buffer);\n      const float = floatBytesView.getFloat64(0, LITTLE_ENDIAN);\n      if (!isSpecial(float)) {\n        throw new Error(`Float ${float} should be encoded as a number`);\n      }\n      return float;\n    }\n    if (key === \"$set\") {\n      throw new Error(\n        `Received a Set which is no longer supported as a Convex type.`\n      );\n    }\n    if (key === \"$map\") {\n      throw new Error(\n        `Received a Map which is no longer supported as a Convex type.`\n      );\n    }\n  }\n  const out = {};\n  for (const [k, v] of Object.entries(value)) {\n    validateObjectField(k);\n    out[k] = jsonToConvex(v);\n  }\n  return out;\n}\nconst MAX_VALUE_FOR_ERROR_LEN = 16384;\nexport function stringifyValueForError(value) {\n  const str = JSON.stringify(value, (_key, value2) => {\n    if (value2 === void 0) {\n      return \"undefined\";\n    }\n    if (typeof value2 === \"bigint\") {\n      return `${value2.toString()}n`;\n    }\n    return value2;\n  });\n  if (str.length > MAX_VALUE_FOR_ERROR_LEN) {\n    const rest = \"[...truncated]\";\n    let truncateAt = MAX_VALUE_FOR_ERROR_LEN - rest.length;\n    const codePoint = str.codePointAt(truncateAt - 1);\n    if (codePoint !== void 0 && codePoint > 65535) {\n      truncateAt -= 1;\n    }\n    return str.substring(0, truncateAt) + rest;\n  }\n  return str;\n}\nfunction convexToJsonInternal(value, originalValue, context, includeTopLevelUndefined) {\n  if (value === void 0) {\n    const contextText = context && ` (present at path ${context} in original object ${stringifyValueForError(\n      originalValue\n    )})`;\n    throw new Error(\n      `undefined is not a valid Convex value${contextText}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`\n    );\n  }\n  if (value === null) {\n    return value;\n  }\n  if (typeof value === \"bigint\") {\n    if (value < MIN_INT64 || MAX_INT64 < value) {\n      throw new Error(\n        `BigInt ${value} does not fit into a 64-bit signed integer.`\n      );\n    }\n    return { $integer: bigIntToBase64(value) };\n  }\n  if (typeof value === \"number\") {\n    if (isSpecial(value)) {\n      const buffer = new ArrayBuffer(8);\n      new DataView(buffer).setFloat64(0, value, LITTLE_ENDIAN);\n      return { $float: Base64.fromByteArray(new Uint8Array(buffer)) };\n    } else {\n      return value;\n    }\n  }\n  if (typeof value === \"boolean\") {\n    return value;\n  }\n  if (typeof value === \"string\") {\n    return value;\n  }\n  if (value instanceof ArrayBuffer) {\n    return { $bytes: Base64.fromByteArray(new Uint8Array(value)) };\n  }\n  if (Array.isArray(value)) {\n    return value.map(\n      (value2, i) => convexToJsonInternal(value2, originalValue, context + `[${i}]`, false)\n    );\n  }\n  if (value instanceof Set) {\n    throw new Error(\n      errorMessageForUnsupportedType(context, \"Set\", [...value], originalValue)\n    );\n  }\n  if (value instanceof Map) {\n    throw new Error(\n      errorMessageForUnsupportedType(context, \"Map\", [...value], originalValue)\n    );\n  }\n  if (!isSimpleObject(value)) {\n    const theType = value?.constructor?.name;\n    const typeName = theType ? `${theType} ` : \"\";\n    throw new Error(\n      errorMessageForUnsupportedType(context, typeName, value, originalValue)\n    );\n  }\n  const out = {};\n  const entries = Object.entries(value);\n  entries.sort(([k1, _v1], [k2, _v2]) => k1 === k2 ? 0 : k1 < k2 ? -1 : 1);\n  for (const [k, v] of entries) {\n    if (v !== void 0) {\n      validateObjectField(k);\n      out[k] = convexToJsonInternal(v, originalValue, context + `.${k}`, false);\n    } else if (includeTopLevelUndefined) {\n      validateObjectField(k);\n      out[k] = convexOrUndefinedToJsonInternal(\n        v,\n        originalValue,\n        context + `.${k}`\n      );\n    }\n  }\n  return out;\n}\nfunction errorMessageForUnsupportedType(context, typeName, value, originalValue) {\n  if (context) {\n    return `${typeName}${stringifyValueForError(\n      value\n    )} is not a supported Convex type (present at path ${context} in original object ${stringifyValueForError(\n      originalValue\n    )}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`;\n  } else {\n    return `${typeName}${stringifyValueForError(\n      value\n    )} is not a supported Convex type.`;\n  }\n}\nfunction convexOrUndefinedToJsonInternal(value, originalValue, context) {\n  if (value === void 0) {\n    return { $undefined: null };\n  } else {\n    if (originalValue === void 0) {\n      throw new Error(\n        `Programming error. Current value is ${stringifyValueForError(\n          value\n        )} but original value is undefined`\n      );\n    }\n    return convexToJsonInternal(value, originalValue, context, false);\n  }\n}\nexport function convexToJson(value) {\n  return convexToJsonInternal(value, value, \"\", false);\n}\nexport function convexOrUndefinedToJson(value) {\n  return convexOrUndefinedToJsonInternal(value, value, \"\");\n}\nexport function patchValueToJson(value) {\n  return convexToJsonInternal(value, value, \"\", true);\n}\n//# sourceMappingURL=value.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { convexToJson } from \"./value.js\";\nconst UNDEFINED_VALIDATOR_ERROR_URL = \"https://docs.convex.dev/error#undefined-validator\";\nfunction throwUndefinedValidatorError(context, fieldName) {\n  const fieldInfo = fieldName !== void 0 ? ` for field \"${fieldName}\"` : \"\";\n  throw new Error(\n    `A validator is undefined${fieldInfo} in ${context}. This is often caused by circular imports. See ${UNDEFINED_VALIDATOR_ERROR_URL} for details.`\n  );\n}\nclass BaseValidator {\n  constructor({ isOptional }) {\n    /**\n     * Only for TypeScript, the TS type of the JS values validated\n     * by this validator.\n     */\n    __publicField(this, \"type\");\n    /**\n     * Only for TypeScript, if this an Object validator, then\n     * this is the TS type of its property names.\n     */\n    __publicField(this, \"fieldPaths\");\n    /**\n     * Whether this is an optional Object property value validator.\n     */\n    __publicField(this, \"isOptional\");\n    /**\n     * Always `\"true\"`.\n     */\n    __publicField(this, \"isConvexValidator\");\n    this.isOptional = isOptional;\n    this.isConvexValidator = true;\n  }\n}\nexport class VId extends BaseValidator {\n  /**\n   * Usually you'd use `v.id(tableName)` instead.\n   */\n  constructor({\n    isOptional,\n    tableName\n  }) {\n    super({ isOptional });\n    /**\n     * The name of the table that the validated IDs must belong to.\n     */\n    __publicField(this, \"tableName\");\n    /**\n     * The kind of validator, `\"id\"`.\n     */\n    __publicField(this, \"kind\", \"id\");\n    if (typeof tableName !== \"string\") {\n      throw new Error(\"v.id(tableName) requires a string\");\n    }\n    this.tableName = tableName;\n  }\n  /** @internal */\n  get json() {\n    return { type: \"id\", tableName: this.tableName };\n  }\n  /** @internal */\n  asOptional() {\n    return new VId({\n      isOptional: \"optional\",\n      tableName: this.tableName\n    });\n  }\n}\nexport class VFloat64 extends BaseValidator {\n  constructor() {\n    super(...arguments);\n    /**\n     * The kind of validator, `\"float64\"`.\n     */\n    __publicField(this, \"kind\", \"float64\");\n  }\n  /** @internal */\n  get json() {\n    return { type: \"number\" };\n  }\n  /** @internal */\n  asOptional() {\n    return new VFloat64({\n      isOptional: \"optional\"\n    });\n  }\n}\nexport class VInt64 extends BaseValidator {\n  constructor() {\n    super(...arguments);\n    /**\n     * The kind of validator, `\"int64\"`.\n     */\n    __publicField(this, \"kind\", \"int64\");\n  }\n  /** @internal */\n  get json() {\n    return { type: \"bigint\" };\n  }\n  /** @internal */\n  asOptional() {\n    return new VInt64({ isOptional: \"optional\" });\n  }\n}\nexport class VBoolean extends BaseValidator {\n  constructor() {\n    super(...arguments);\n    /**\n     * The kind of validator, `\"boolean\"`.\n     */\n    __publicField(this, \"kind\", \"boolean\");\n  }\n  /** @internal */\n  get json() {\n    return { type: this.kind };\n  }\n  /** @internal */\n  asOptional() {\n    return new VBoolean({\n      isOptional: \"optional\"\n    });\n  }\n}\nexport class VBytes extends BaseValidator {\n  constructor() {\n    super(...arguments);\n    /**\n     * The kind of validator, `\"bytes\"`.\n     */\n    __publicField(this, \"kind\", \"bytes\");\n  }\n  /** @internal */\n  get json() {\n    return { type: this.kind };\n  }\n  /** @internal */\n  asOptional() {\n    return new VBytes({ isOptional: \"optional\" });\n  }\n}\nexport class VString extends BaseValidator {\n  constructor() {\n    super(...arguments);\n    /**\n     * The kind of validator, `\"string\"`.\n     */\n    __publicField(this, \"kind\", \"string\");\n  }\n  /** @internal */\n  get json() {\n    return { type: this.kind };\n  }\n  /** @internal */\n  asOptional() {\n    return new VString({\n      isOptional: \"optional\"\n    });\n  }\n}\nexport class VNull extends BaseValidator {\n  constructor() {\n    super(...arguments);\n    /**\n     * The kind of validator, `\"null\"`.\n     */\n    __publicField(this, \"kind\", \"null\");\n  }\n  /** @internal */\n  get json() {\n    return { type: this.kind };\n  }\n  /** @internal */\n  asOptional() {\n    return new VNull({ isOptional: \"optional\" });\n  }\n}\nexport class VAny extends BaseValidator {\n  constructor() {\n    super(...arguments);\n    /**\n     * The kind of validator, `\"any\"`.\n     */\n    __publicField(this, \"kind\", \"any\");\n  }\n  /** @internal */\n  get json() {\n    return {\n      type: this.kind\n    };\n  }\n  /** @internal */\n  asOptional() {\n    return new VAny({\n      isOptional: \"optional\"\n    });\n  }\n}\nexport class VObject extends BaseValidator {\n  /**\n   * Usually you'd use `v.object({ ... })` instead.\n   */\n  constructor({\n    isOptional,\n    fields\n  }) {\n    super({ isOptional });\n    /**\n     * An object with the validator for each property.\n     */\n    __publicField(this, \"fields\");\n    /**\n     * The kind of validator, `\"object\"`.\n     */\n    __publicField(this, \"kind\", \"object\");\n    globalThis.Object.entries(fields).forEach(([fieldName, validator]) => {\n      if (validator === void 0) {\n        throwUndefinedValidatorError(\"v.object()\", fieldName);\n      }\n      if (!validator.isConvexValidator) {\n        throw new Error(\"v.object() entries must be validators\");\n      }\n    });\n    this.fields = fields;\n  }\n  /** @internal */\n  get json() {\n    return {\n      type: this.kind,\n      value: globalThis.Object.fromEntries(\n        globalThis.Object.entries(this.fields).map(([k, v]) => [\n          k,\n          {\n            fieldType: v.json,\n            optional: v.isOptional === \"optional\" ? true : false\n          }\n        ])\n      )\n    };\n  }\n  /** @internal */\n  asOptional() {\n    return new VObject({\n      isOptional: \"optional\",\n      fields: this.fields\n    });\n  }\n  /**\n   * Create a new VObject with the specified fields omitted.\n   * @param fields The field names to omit from this VObject.\n   */\n  omit(...fields) {\n    const newFields = { ...this.fields };\n    for (const field of fields) {\n      delete newFields[field];\n    }\n    return new VObject({\n      isOptional: this.isOptional,\n      fields: newFields\n    });\n  }\n  /**\n   * Create a new VObject with only the specified fields.\n   * @param fields The field names to pick from this VObject.\n   */\n  pick(...fields) {\n    const newFields = {};\n    for (const field of fields) {\n      newFields[field] = this.fields[field];\n    }\n    return new VObject({\n      isOptional: this.isOptional,\n      fields: newFields\n    });\n  }\n  /**\n   * Create a new VObject with all fields marked as optional.\n   */\n  partial() {\n    const newFields = {};\n    for (const [key, validator] of globalThis.Object.entries(this.fields)) {\n      newFields[key] = validator.asOptional();\n    }\n    return new VObject({\n      isOptional: this.isOptional,\n      fields: newFields\n    });\n  }\n  /**\n   * Create a new VObject with additional fields merged in.\n   * @param fields An object with additional validators to merge into this VObject.\n   */\n  extend(fields) {\n    return new VObject({\n      isOptional: this.isOptional,\n      fields: { ...this.fields, ...fields }\n    });\n  }\n}\nexport class VLiteral extends BaseValidator {\n  /**\n   * Usually you'd use `v.literal(value)` instead.\n   */\n  constructor({ isOptional, value }) {\n    super({ isOptional });\n    /**\n     * The value that the validated values must be equal to.\n     */\n    __publicField(this, \"value\");\n    /**\n     * The kind of validator, `\"literal\"`.\n     */\n    __publicField(this, \"kind\", \"literal\");\n    if (typeof value !== \"string\" && typeof value !== \"boolean\" && typeof value !== \"number\" && typeof value !== \"bigint\") {\n      throw new Error(\"v.literal(value) must be a string, number, or boolean\");\n    }\n    this.value = value;\n  }\n  /** @internal */\n  get json() {\n    return {\n      type: this.kind,\n      value: convexToJson(this.value)\n    };\n  }\n  /** @internal */\n  asOptional() {\n    return new VLiteral({\n      isOptional: \"optional\",\n      value: this.value\n    });\n  }\n}\nexport class VArray extends BaseValidator {\n  /**\n   * Usually you'd use `v.array(element)` instead.\n   */\n  constructor({\n    isOptional,\n    element\n  }) {\n    super({ isOptional });\n    /**\n     * The validator for the elements of the array.\n     */\n    __publicField(this, \"element\");\n    /**\n     * The kind of validator, `\"array\"`.\n     */\n    __publicField(this, \"kind\", \"array\");\n    if (element === void 0) {\n      throwUndefinedValidatorError(\"v.array()\");\n    }\n    this.element = element;\n  }\n  /** @internal */\n  get json() {\n    return {\n      type: this.kind,\n      value: this.element.json\n    };\n  }\n  /** @internal */\n  asOptional() {\n    return new VArray({\n      isOptional: \"optional\",\n      element: this.element\n    });\n  }\n}\nexport class VRecord extends BaseValidator {\n  /**\n   * Usually you'd use `v.record(key, value)` instead.\n   */\n  constructor({\n    isOptional,\n    key,\n    value\n  }) {\n    super({ isOptional });\n    /**\n     * The validator for the keys of the record.\n     */\n    __publicField(this, \"key\");\n    /**\n     * The validator for the values of the record.\n     */\n    __publicField(this, \"value\");\n    /**\n     * The kind of validator, `\"record\"`.\n     */\n    __publicField(this, \"kind\", \"record\");\n    if (key === void 0) {\n      throwUndefinedValidatorError(\"v.record()\", \"key\");\n    }\n    if (value === void 0) {\n      throwUndefinedValidatorError(\"v.record()\", \"value\");\n    }\n    if (key.isOptional === \"optional\") {\n      throw new Error(\"Record validator cannot have optional keys\");\n    }\n    if (value.isOptional === \"optional\") {\n      throw new Error(\"Record validator cannot have optional values\");\n    }\n    if (!key.isConvexValidator || !value.isConvexValidator) {\n      throw new Error(\"Key and value of v.record() but be validators\");\n    }\n    this.key = key;\n    this.value = value;\n  }\n  /** @internal */\n  get json() {\n    return {\n      type: this.kind,\n      // This cast is needed because TypeScript thinks the key type is too wide\n      keys: this.key.json,\n      values: {\n        fieldType: this.value.json,\n        optional: false\n      }\n    };\n  }\n  /** @internal */\n  asOptional() {\n    return new VRecord({\n      isOptional: \"optional\",\n      key: this.key,\n      value: this.value\n    });\n  }\n}\nexport class VUnion extends BaseValidator {\n  /**\n   * Usually you'd use `v.union(...members)` instead.\n   */\n  constructor({ isOptional, members }) {\n    super({ isOptional });\n    /**\n     * The array of validators, one of which must match the value.\n     */\n    __publicField(this, \"members\");\n    /**\n     * The kind of validator, `\"union\"`.\n     */\n    __publicField(this, \"kind\", \"union\");\n    members.forEach((member, index) => {\n      if (member === void 0) {\n        throwUndefinedValidatorError(\"v.union()\", `member at index ${index}`);\n      }\n      if (!member.isConvexValidator) {\n        throw new Error(\"All members of v.union() must be validators\");\n      }\n    });\n    this.members = members;\n  }\n  /** @internal */\n  get json() {\n    return {\n      type: this.kind,\n      value: this.members.map((v) => v.json)\n    };\n  }\n  /** @internal */\n  asOptional() {\n    return new VUnion({\n      isOptional: \"optional\",\n      members: this.members\n    });\n  }\n}\n//# sourceMappingURL=validators.js.map\n","\"use strict\";\nimport {\n  VAny,\n  VArray,\n  VBoolean,\n  VBytes,\n  VFloat64,\n  VId,\n  VInt64,\n  VLiteral,\n  VNull,\n  VObject,\n  VRecord,\n  VString,\n  VUnion\n} from \"./validators.js\";\nexport function isValidator(v2) {\n  return !!v2.isConvexValidator;\n}\nexport function asObjectValidator(obj) {\n  if (isValidator(obj)) {\n    return obj;\n  } else {\n    return v.object(obj);\n  }\n}\nexport const v = {\n  /**\n   * Validates that the value corresponds to an ID of a document in given table.\n   * @param tableName The name of the table.\n   */\n  id: (tableName) => {\n    return new VId({\n      isOptional: \"required\",\n      tableName\n    });\n  },\n  /**\n   * Validates that the value is of type Null.\n   */\n  null: () => {\n    return new VNull({ isOptional: \"required\" });\n  },\n  /**\n   * Validates that the value is of Convex type Float64 (Number in JS).\n   *\n   * Alias for `v.float64()`\n   */\n  number: () => {\n    return new VFloat64({ isOptional: \"required\" });\n  },\n  /**\n   * Validates that the value is of Convex type Float64 (Number in JS).\n   */\n  float64: () => {\n    return new VFloat64({ isOptional: \"required\" });\n  },\n  /**\n   * @deprecated Use `v.int64()` instead\n   */\n  bigint: () => {\n    return new VInt64({ isOptional: \"required\" });\n  },\n  /**\n   * Validates that the value is of Convex type Int64 (BigInt in JS).\n   */\n  int64: () => {\n    return new VInt64({ isOptional: \"required\" });\n  },\n  /**\n   * Validates that the value is of type Boolean.\n   */\n  boolean: () => {\n    return new VBoolean({ isOptional: \"required\" });\n  },\n  /**\n   * Validates that the value is of type String.\n   */\n  string: () => {\n    return new VString({ isOptional: \"required\" });\n  },\n  /**\n   * Validates that the value is of Convex type Bytes (constructed in JS via `ArrayBuffer`).\n   */\n  bytes: () => {\n    return new VBytes({ isOptional: \"required\" });\n  },\n  /**\n   * Validates that the value is equal to the given literal value.\n   * @param literal The literal value to compare against.\n   */\n  literal: (literal) => {\n    return new VLiteral({ isOptional: \"required\", value: literal });\n  },\n  /**\n   * Validates that the value is an Array of the given element type.\n   * @param element The validator for the elements of the array.\n   */\n  array: (element) => {\n    return new VArray({ isOptional: \"required\", element });\n  },\n  /**\n   * Validates that the value is an Object with the given properties.\n   * @param fields An object specifying the validator for each property.\n   */\n  object: (fields) => {\n    return new VObject({ isOptional: \"required\", fields });\n  },\n  /**\n   * Validates that the value is a Record with keys and values that match the given types.\n   * @param keys The validator for the keys of the record. This cannot contain string literals.\n   * @param values The validator for the values of the record.\n   */\n  record: (keys, values) => {\n    return new VRecord({\n      isOptional: \"required\",\n      key: keys,\n      value: values\n    });\n  },\n  /**\n   * Validates that the value matches one of the given validators.\n   * @param members The validators to match against.\n   */\n  union: (...members) => {\n    return new VUnion({\n      isOptional: \"required\",\n      members\n    });\n  },\n  /**\n   * Does not validate the value.\n   */\n  any: () => {\n    return new VAny({ isOptional: \"required\" });\n  },\n  /**\n   * Allows not specifying a value for a property in an Object.\n   * @param value The property value validator to make optional.\n   *\n   * ```typescript\n   * const objectWithOptionalFields = v.object({\n   *   requiredField: v.string(),\n   *   optionalField: v.optional(v.string()),\n   * });\n   * ```\n   */\n  optional: (value) => {\n    return value.asOptional();\n  },\n  /**\n   * Allows specifying a value or null.\n   */\n  nullable: (value) => {\n    return v.union(value, v.null());\n  }\n};\n//# sourceMappingURL=validator.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nvar _a, _b;\nimport { stringifyValueForError } from \"./value.js\";\nconst IDENTIFYING_FIELD = Symbol.for(\"ConvexError\");\nexport class ConvexError extends (_b = Error, _a = IDENTIFYING_FIELD, _b) {\n  constructor(data) {\n    super(typeof data === \"string\" ? data : stringifyValueForError(data));\n    __publicField(this, \"name\", \"ConvexError\");\n    __publicField(this, \"data\");\n    __publicField(this, _a, true);\n    this.data = data;\n  }\n}\n//# sourceMappingURL=errors.js.map\n","\"use strict\";\nexport function compareUTF8(a, b) {\n  const aLength = a.length;\n  const bLength = b.length;\n  const length = Math.min(aLength, bLength);\n  for (let i = 0; i < length; ) {\n    const aCodePoint = a.codePointAt(i);\n    const bCodePoint = b.codePointAt(i);\n    if (aCodePoint !== bCodePoint) {\n      if (aCodePoint < 128 && bCodePoint < 128) {\n        return aCodePoint - bCodePoint;\n      }\n      const aLength2 = utf8Bytes(aCodePoint, aBytes);\n      const bLength2 = utf8Bytes(bCodePoint, bBytes);\n      return compareArrays(aBytes, aLength2, bBytes, bLength2);\n    }\n    i += utf16LengthForCodePoint(aCodePoint);\n  }\n  return aLength - bLength;\n}\nfunction compareArrays(a, aLength, b, bLength) {\n  const length = Math.min(aLength, bLength);\n  for (let i = 0; i < length; i++) {\n    const aValue = a[i];\n    const bValue = b[i];\n    if (aValue !== bValue) {\n      return aValue - bValue;\n    }\n  }\n  return aLength - bLength;\n}\nexport function utf16LengthForCodePoint(aCodePoint) {\n  return aCodePoint > 65535 ? 2 : 1;\n}\nconst arr = () => Array.from({ length: 4 }, () => 0);\nconst aBytes = arr();\nconst bBytes = arr();\nfunction utf8Bytes(codePoint, bytes) {\n  if (codePoint < 128) {\n    bytes[0] = codePoint;\n    return 1;\n  }\n  let count;\n  let offset;\n  if (codePoint <= 2047) {\n    count = 1;\n    offset = 192;\n  } else if (codePoint <= 65535) {\n    count = 2;\n    offset = 224;\n  } else if (codePoint <= 1114111) {\n    count = 3;\n    offset = 240;\n  } else {\n    throw new Error(\"Invalid code point\");\n  }\n  bytes[0] = (codePoint >> 6 * count) + offset;\n  let i = 1;\n  for (; count > 0; count--) {\n    const temp = codePoint >> 6 * (count - 1);\n    bytes[i++] = 128 | temp & 63;\n  }\n  return i;\n}\nexport function greaterThan(a, b) {\n  return compareUTF8(a, b) > 0;\n}\nexport function greaterThanEq(a, b) {\n  return compareUTF8(a, b) >= 0;\n}\nexport function lessThan(a, b) {\n  return compareUTF8(a, b) < 0;\n}\nexport function lessThanEq(a, b) {\n  return compareUTF8(a, b) <= 0;\n}\n//# sourceMappingURL=compare_utf8.js.map\n","\"use strict\";\nimport { compareUTF8 } from \"./compare_utf8.js\";\nexport function compareValues(k1, k2) {\n  return compareAsTuples(makeComparable(k1), makeComparable(k2));\n}\nfunction compareAsTuples(a, b) {\n  if (a[0] === b[0]) {\n    return compareSameTypeValues(a[1], b[1]);\n  } else if (a[0] < b[0]) {\n    return -1;\n  }\n  return 1;\n}\nfunction compareSameTypeValues(v1, v2) {\n  if (v1 === void 0 || v1 === null) {\n    return 0;\n  }\n  if (typeof v1 === \"number\") {\n    if (typeof v2 !== \"number\") {\n      throw new Error(`Unexpected type ${v2}`);\n    }\n    return compareNumbers(v1, v2);\n  }\n  if (typeof v1 === \"string\") {\n    if (typeof v2 !== \"string\") {\n      throw new Error(`Unexpected type ${v2}`);\n    }\n    return compareUTF8(v1, v2);\n  }\n  if (typeof v1 === \"bigint\" || typeof v1 === \"boolean\" || typeof v1 === \"string\") {\n    return v1 < v2 ? -1 : v1 === v2 ? 0 : 1;\n  }\n  if (!Array.isArray(v1) || !Array.isArray(v2)) {\n    throw new Error(`Unexpected type ${v1}`);\n  }\n  for (let i = 0; i < v1.length && i < v2.length; i++) {\n    const cmp = compareAsTuples(v1[i], v2[i]);\n    if (cmp !== 0) {\n      return cmp;\n    }\n  }\n  if (v1.length < v2.length) {\n    return -1;\n  }\n  if (v1.length > v2.length) {\n    return 1;\n  }\n  return 0;\n}\nfunction compareNumbers(v1, v2) {\n  if (isNaN(v1) || isNaN(v2)) {\n    const buffer1 = new ArrayBuffer(8);\n    const buffer2 = new ArrayBuffer(8);\n    new DataView(buffer1).setFloat64(\n      0,\n      v1,\n      /* little-endian */\n      true\n    );\n    new DataView(buffer2).setFloat64(\n      0,\n      v2,\n      /* little-endian */\n      true\n    );\n    const v1Bits = BigInt(\n      new DataView(buffer1).getBigInt64(\n        0,\n        /* little-endian */\n        true\n      )\n    );\n    const v2Bits = BigInt(\n      new DataView(buffer2).getBigInt64(\n        0,\n        /* little-endian */\n        true\n      )\n    );\n    const v1Sign = (v1Bits & 0x8000000000000000n) !== 0n;\n    const v2Sign = (v2Bits & 0x8000000000000000n) !== 0n;\n    if (isNaN(v1) !== isNaN(v2)) {\n      if (isNaN(v1)) {\n        return v1Sign ? -1 : 1;\n      }\n      return v2Sign ? 1 : -1;\n    }\n    if (v1Sign !== v2Sign) {\n      return v1Sign ? -1 : 1;\n    }\n    return v1Bits < v2Bits ? -1 : v1Bits === v2Bits ? 0 : 1;\n  }\n  if (Object.is(v1, v2)) {\n    return 0;\n  }\n  if (Object.is(v1, -0)) {\n    return Object.is(v2, 0) ? -1 : -Math.sign(v2);\n  }\n  if (Object.is(v2, -0)) {\n    return Object.is(v1, 0) ? 1 : Math.sign(v1);\n  }\n  return v1 < v2 ? -1 : 1;\n}\nfunction makeComparable(v) {\n  if (v === void 0) {\n    return [0, void 0];\n  }\n  if (v === null) {\n    return [1, null];\n  }\n  if (typeof v === \"bigint\") {\n    return [2, v];\n  }\n  if (typeof v === \"number\") {\n    return [3, v];\n  }\n  if (typeof v === \"boolean\") {\n    return [4, v];\n  }\n  if (typeof v === \"string\") {\n    return [5, v];\n  }\n  if (v instanceof ArrayBuffer) {\n    return [6, Array.from(new Uint8Array(v)).map(makeComparable)];\n  }\n  if (Array.isArray(v)) {\n    return [7, v.map(makeComparable)];\n  }\n  const keys = Object.keys(v).sort();\n  const pojo = keys.map((k) => [k, v[k]]);\n  return [8, pojo.map(makeComparable)];\n}\n//# sourceMappingURL=compare.js.map\n","\"use strict\";\nexport { convexToJson, jsonToConvex } from \"./value.js\";\nexport { v, asObjectValidator } from \"./validator.js\";\nimport * as Base64 from \"./base64.js\";\nexport { Base64 };\nexport * from \"./errors.js\";\nexport { compareValues } from \"./compare.js\";\nexport { getConvexSize, getDocumentSize } from \"./size.js\";\n//# sourceMappingURL=index.js.map\n","\"use strict\";\nexport const version = \"1.31.7\";\n//# sourceMappingURL=index.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nconst INFO_COLOR = \"color:rgb(0, 145, 255)\";\nfunction prefix_for_source(source) {\n  switch (source) {\n    case \"query\":\n      return \"Q\";\n    case \"mutation\":\n      return \"M\";\n    case \"action\":\n      return \"A\";\n    case \"any\":\n      return \"?\";\n  }\n}\nexport class DefaultLogger {\n  constructor(options) {\n    __publicField(this, \"_onLogLineFuncs\");\n    __publicField(this, \"_verbose\");\n    this._onLogLineFuncs = {};\n    this._verbose = options.verbose;\n  }\n  addLogLineListener(func) {\n    let id = Math.random().toString(36).substring(2, 15);\n    for (let i = 0; i < 10; i++) {\n      if (this._onLogLineFuncs[id] === void 0) {\n        break;\n      }\n      id = Math.random().toString(36).substring(2, 15);\n    }\n    this._onLogLineFuncs[id] = func;\n    return () => {\n      delete this._onLogLineFuncs[id];\n    };\n  }\n  logVerbose(...args) {\n    if (this._verbose) {\n      for (const func of Object.values(this._onLogLineFuncs)) {\n        func(\"debug\", `${(/* @__PURE__ */ new Date()).toISOString()}`, ...args);\n      }\n    }\n  }\n  log(...args) {\n    for (const func of Object.values(this._onLogLineFuncs)) {\n      func(\"info\", ...args);\n    }\n  }\n  warn(...args) {\n    for (const func of Object.values(this._onLogLineFuncs)) {\n      func(\"warn\", ...args);\n    }\n  }\n  error(...args) {\n    for (const func of Object.values(this._onLogLineFuncs)) {\n      func(\"error\", ...args);\n    }\n  }\n}\nexport function instantiateDefaultLogger(options) {\n  const logger = new DefaultLogger(options);\n  logger.addLogLineListener((level, ...args) => {\n    switch (level) {\n      case \"debug\":\n        console.debug(...args);\n        break;\n      case \"info\":\n        console.log(...args);\n        break;\n      case \"warn\":\n        console.warn(...args);\n        break;\n      case \"error\":\n        console.error(...args);\n        break;\n      default: {\n        level;\n        console.log(...args);\n      }\n    }\n  });\n  return logger;\n}\nexport function instantiateNoopLogger(options) {\n  return new DefaultLogger(options);\n}\nexport function logForFunction(logger, type, source, udfPath, message) {\n  const prefix = prefix_for_source(source);\n  if (typeof message === \"object\") {\n    message = `ConvexError ${JSON.stringify(message.errorData, null, 2)}`;\n  }\n  if (type === \"info\") {\n    const match = message.match(/^\\[.*?\\] /);\n    if (match === null) {\n      logger.error(\n        `[CONVEX ${prefix}(${udfPath})] Could not parse console.log`\n      );\n      return;\n    }\n    const level = message.slice(1, match[0].length - 2);\n    const args = message.slice(match[0].length);\n    logger.log(`%c[CONVEX ${prefix}(${udfPath})] [${level}]`, INFO_COLOR, args);\n  } else {\n    logger.error(`[CONVEX ${prefix}(${udfPath})] ${message}`);\n  }\n}\nexport function logFatalError(logger, message) {\n  const errorMessage = `[CONVEX FATAL ERROR] ${message}`;\n  logger.error(errorMessage);\n  return new Error(errorMessage);\n}\nexport function createHybridErrorStacktrace(source, udfPath, result) {\n  const prefix = prefix_for_source(source);\n  return `[CONVEX ${prefix}(${udfPath})] ${result.errorMessage}\n  Called by client`;\n}\nexport function forwardData(result, error) {\n  error.data = result.errorData;\n  return error;\n}\n//# sourceMappingURL=logging.js.map\n","\"use strict\";\nimport { convexToJson } from \"../../values/index.js\";\nexport function canonicalizeUdfPath(udfPath) {\n  const pieces = udfPath.split(\":\");\n  let moduleName;\n  let functionName;\n  if (pieces.length === 1) {\n    moduleName = pieces[0];\n    functionName = \"default\";\n  } else {\n    moduleName = pieces.slice(0, pieces.length - 1).join(\":\");\n    functionName = pieces[pieces.length - 1];\n  }\n  if (moduleName.endsWith(\".js\")) {\n    moduleName = moduleName.slice(0, -3);\n  }\n  return `${moduleName}:${functionName}`;\n}\nexport function serializePathAndArgs(udfPath, args) {\n  return JSON.stringify({\n    udfPath: canonicalizeUdfPath(udfPath),\n    args: convexToJson(args)\n  });\n}\nexport function serializePaginatedPathAndArgs(udfPath, args, options) {\n  const { initialNumItems, id } = options;\n  const result = JSON.stringify({\n    type: \"paginated\",\n    udfPath: canonicalizeUdfPath(udfPath),\n    args: convexToJson(args),\n    options: convexToJson({ initialNumItems, id })\n  });\n  return result;\n}\nexport function serializedQueryTokenIsPaginated(token) {\n  return JSON.parse(token).type === \"paginated\";\n}\n//# sourceMappingURL=udf_path_utils.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { convexToJson } from \"../../values/index.js\";\nimport {\n  canonicalizeUdfPath,\n  serializePathAndArgs\n} from \"./udf_path_utils.js\";\nexport class LocalSyncState {\n  constructor() {\n    __publicField(this, \"nextQueryId\");\n    __publicField(this, \"querySetVersion\");\n    __publicField(this, \"querySet\");\n    __publicField(this, \"queryIdToToken\");\n    __publicField(this, \"identityVersion\");\n    __publicField(this, \"auth\");\n    __publicField(this, \"outstandingQueriesOlderThanRestart\");\n    __publicField(this, \"outstandingAuthOlderThanRestart\");\n    __publicField(this, \"paused\");\n    __publicField(this, \"pendingQuerySetModifications\");\n    this.nextQueryId = 0;\n    this.querySetVersion = 0;\n    this.identityVersion = 0;\n    this.querySet = /* @__PURE__ */ new Map();\n    this.queryIdToToken = /* @__PURE__ */ new Map();\n    this.outstandingQueriesOlderThanRestart = /* @__PURE__ */ new Set();\n    this.outstandingAuthOlderThanRestart = false;\n    this.paused = false;\n    this.pendingQuerySetModifications = /* @__PURE__ */ new Map();\n  }\n  hasSyncedPastLastReconnect() {\n    return this.outstandingQueriesOlderThanRestart.size === 0 && !this.outstandingAuthOlderThanRestart;\n  }\n  markAuthCompletion() {\n    this.outstandingAuthOlderThanRestart = false;\n  }\n  subscribe(udfPath, args, journal, componentPath) {\n    const canonicalizedUdfPath = canonicalizeUdfPath(udfPath);\n    const queryToken = serializePathAndArgs(canonicalizedUdfPath, args);\n    const existingEntry = this.querySet.get(queryToken);\n    if (existingEntry !== void 0) {\n      existingEntry.numSubscribers += 1;\n      return {\n        queryToken,\n        modification: null,\n        unsubscribe: () => this.removeSubscriber(queryToken)\n      };\n    } else {\n      const queryId = this.nextQueryId++;\n      const query = {\n        id: queryId,\n        canonicalizedUdfPath,\n        args,\n        numSubscribers: 1,\n        journal,\n        componentPath\n      };\n      this.querySet.set(queryToken, query);\n      this.queryIdToToken.set(queryId, queryToken);\n      const baseVersion = this.querySetVersion;\n      const newVersion = this.querySetVersion + 1;\n      const add = {\n        type: \"Add\",\n        queryId,\n        udfPath: canonicalizedUdfPath,\n        args: [convexToJson(args)],\n        journal,\n        componentPath\n      };\n      if (this.paused) {\n        this.pendingQuerySetModifications.set(queryId, add);\n      } else {\n        this.querySetVersion = newVersion;\n      }\n      const modification = {\n        type: \"ModifyQuerySet\",\n        baseVersion,\n        newVersion,\n        modifications: [add]\n      };\n      return {\n        queryToken,\n        modification,\n        unsubscribe: () => this.removeSubscriber(queryToken)\n      };\n    }\n  }\n  transition(transition) {\n    for (const modification of transition.modifications) {\n      switch (modification.type) {\n        case \"QueryUpdated\":\n        case \"QueryFailed\": {\n          this.outstandingQueriesOlderThanRestart.delete(modification.queryId);\n          const journal = modification.journal;\n          if (journal !== void 0) {\n            const queryToken = this.queryIdToToken.get(modification.queryId);\n            if (queryToken !== void 0) {\n              this.querySet.get(queryToken).journal = journal;\n            }\n          }\n          break;\n        }\n        case \"QueryRemoved\": {\n          this.outstandingQueriesOlderThanRestart.delete(modification.queryId);\n          break;\n        }\n        default: {\n          modification;\n          throw new Error(`Invalid modification ${modification.type}`);\n        }\n      }\n    }\n  }\n  queryId(udfPath, args) {\n    const canonicalizedUdfPath = canonicalizeUdfPath(udfPath);\n    const queryToken = serializePathAndArgs(canonicalizedUdfPath, args);\n    const existingEntry = this.querySet.get(queryToken);\n    if (existingEntry !== void 0) {\n      return existingEntry.id;\n    }\n    return null;\n  }\n  isCurrentOrNewerAuthVersion(version) {\n    return version >= this.identityVersion;\n  }\n  getAuth() {\n    return this.auth;\n  }\n  setAuth(value) {\n    this.auth = {\n      tokenType: \"User\",\n      value\n    };\n    const baseVersion = this.identityVersion;\n    if (!this.paused) {\n      this.identityVersion = baseVersion + 1;\n    }\n    return {\n      type: \"Authenticate\",\n      baseVersion,\n      ...this.auth\n    };\n  }\n  setAdminAuth(value, actingAs) {\n    const auth = {\n      tokenType: \"Admin\",\n      value,\n      impersonating: actingAs\n    };\n    this.auth = auth;\n    const baseVersion = this.identityVersion;\n    if (!this.paused) {\n      this.identityVersion = baseVersion + 1;\n    }\n    return {\n      type: \"Authenticate\",\n      baseVersion,\n      ...auth\n    };\n  }\n  clearAuth() {\n    this.auth = void 0;\n    this.markAuthCompletion();\n    const baseVersion = this.identityVersion;\n    if (!this.paused) {\n      this.identityVersion = baseVersion + 1;\n    }\n    return {\n      type: \"Authenticate\",\n      tokenType: \"None\",\n      baseVersion\n    };\n  }\n  hasAuth() {\n    return !!this.auth;\n  }\n  isNewAuth(value) {\n    return this.auth?.value !== value;\n  }\n  queryPath(queryId) {\n    const pathAndArgs = this.queryIdToToken.get(queryId);\n    if (pathAndArgs) {\n      return this.querySet.get(pathAndArgs).canonicalizedUdfPath;\n    }\n    return null;\n  }\n  queryArgs(queryId) {\n    const pathAndArgs = this.queryIdToToken.get(queryId);\n    if (pathAndArgs) {\n      return this.querySet.get(pathAndArgs).args;\n    }\n    return null;\n  }\n  queryToken(queryId) {\n    return this.queryIdToToken.get(queryId) ?? null;\n  }\n  queryJournal(queryToken) {\n    return this.querySet.get(queryToken)?.journal;\n  }\n  restart(oldRemoteQueryResults) {\n    this.unpause();\n    this.outstandingQueriesOlderThanRestart.clear();\n    const modifications = [];\n    for (const localQuery of this.querySet.values()) {\n      const add = {\n        type: \"Add\",\n        queryId: localQuery.id,\n        udfPath: localQuery.canonicalizedUdfPath,\n        args: [convexToJson(localQuery.args)],\n        journal: localQuery.journal,\n        componentPath: localQuery.componentPath\n      };\n      modifications.push(add);\n      if (!oldRemoteQueryResults.has(localQuery.id)) {\n        this.outstandingQueriesOlderThanRestart.add(localQuery.id);\n      }\n    }\n    this.querySetVersion = 1;\n    const querySet = {\n      type: \"ModifyQuerySet\",\n      baseVersion: 0,\n      newVersion: 1,\n      modifications\n    };\n    if (!this.auth) {\n      this.identityVersion = 0;\n      return [querySet, void 0];\n    }\n    this.outstandingAuthOlderThanRestart = true;\n    const authenticate = {\n      type: \"Authenticate\",\n      baseVersion: 0,\n      ...this.auth\n    };\n    this.identityVersion = 1;\n    return [querySet, authenticate];\n  }\n  pause() {\n    this.paused = true;\n  }\n  resume() {\n    const querySet = this.pendingQuerySetModifications.size > 0 ? {\n      type: \"ModifyQuerySet\",\n      baseVersion: this.querySetVersion,\n      newVersion: ++this.querySetVersion,\n      modifications: Array.from(\n        this.pendingQuerySetModifications.values()\n      )\n    } : void 0;\n    const authenticate = this.auth !== void 0 ? {\n      type: \"Authenticate\",\n      baseVersion: this.identityVersion++,\n      ...this.auth\n    } : void 0;\n    this.unpause();\n    return [querySet, authenticate];\n  }\n  unpause() {\n    this.paused = false;\n    this.pendingQuerySetModifications.clear();\n  }\n  removeSubscriber(queryToken) {\n    const localQuery = this.querySet.get(queryToken);\n    if (localQuery.numSubscribers > 1) {\n      localQuery.numSubscribers -= 1;\n      return null;\n    } else {\n      this.querySet.delete(queryToken);\n      this.queryIdToToken.delete(localQuery.id);\n      this.outstandingQueriesOlderThanRestart.delete(localQuery.id);\n      const baseVersion = this.querySetVersion;\n      const newVersion = this.querySetVersion + 1;\n      const remove = {\n        type: \"Remove\",\n        queryId: localQuery.id\n      };\n      if (this.paused) {\n        if (this.pendingQuerySetModifications.has(localQuery.id)) {\n          this.pendingQuerySetModifications.delete(localQuery.id);\n        } else {\n          this.pendingQuerySetModifications.set(localQuery.id, remove);\n        }\n      } else {\n        this.querySetVersion = newVersion;\n      }\n      return {\n        type: \"ModifyQuerySet\",\n        baseVersion,\n        newVersion,\n        modifications: [remove]\n      };\n    }\n  }\n}\n//# sourceMappingURL=local_state.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { jsonToConvex } from \"../../values/index.js\";\nimport { logForFunction } from \"../logging.js\";\nexport class RequestManager {\n  constructor(logger, markConnectionStateDirty) {\n    this.logger = logger;\n    this.markConnectionStateDirty = markConnectionStateDirty;\n    __publicField(this, \"inflightRequests\");\n    __publicField(this, \"requestsOlderThanRestart\");\n    __publicField(this, \"inflightMutationsCount\", 0);\n    __publicField(this, \"inflightActionsCount\", 0);\n    this.inflightRequests = /* @__PURE__ */ new Map();\n    this.requestsOlderThanRestart = /* @__PURE__ */ new Set();\n  }\n  request(message, sent) {\n    const result = new Promise((resolve) => {\n      const status = sent ? \"Requested\" : \"NotSent\";\n      this.inflightRequests.set(message.requestId, {\n        message,\n        status: { status, requestedAt: /* @__PURE__ */ new Date(), onResult: resolve }\n      });\n      if (message.type === \"Mutation\") {\n        this.inflightMutationsCount++;\n      } else if (message.type === \"Action\") {\n        this.inflightActionsCount++;\n      }\n    });\n    this.markConnectionStateDirty();\n    return result;\n  }\n  /**\n   * Update the state after receiving a response.\n   *\n   * @returns A RequestId if the request is complete and its optimistic update\n   * can be dropped, null otherwise.\n   */\n  onResponse(response) {\n    const requestInfo = this.inflightRequests.get(response.requestId);\n    if (requestInfo === void 0) {\n      return null;\n    }\n    if (requestInfo.status.status === \"Completed\") {\n      return null;\n    }\n    const udfType = requestInfo.message.type === \"Mutation\" ? \"mutation\" : \"action\";\n    const udfPath = requestInfo.message.udfPath;\n    for (const line of response.logLines) {\n      logForFunction(this.logger, \"info\", udfType, udfPath, line);\n    }\n    const status = requestInfo.status;\n    let result;\n    let onResolve;\n    if (response.success) {\n      result = {\n        success: true,\n        logLines: response.logLines,\n        value: jsonToConvex(response.result)\n      };\n      onResolve = () => status.onResult(result);\n    } else {\n      const errorMessage = response.result;\n      const { errorData } = response;\n      logForFunction(this.logger, \"error\", udfType, udfPath, errorMessage);\n      result = {\n        success: false,\n        errorMessage,\n        errorData: errorData !== void 0 ? jsonToConvex(errorData) : void 0,\n        logLines: response.logLines\n      };\n      onResolve = () => status.onResult(result);\n    }\n    if (response.type === \"ActionResponse\" || !response.success) {\n      onResolve();\n      this.inflightRequests.delete(response.requestId);\n      this.requestsOlderThanRestart.delete(response.requestId);\n      if (requestInfo.message.type === \"Action\") {\n        this.inflightActionsCount--;\n      } else if (requestInfo.message.type === \"Mutation\") {\n        this.inflightMutationsCount--;\n      }\n      this.markConnectionStateDirty();\n      return { requestId: response.requestId, result };\n    }\n    requestInfo.status = {\n      status: \"Completed\",\n      result,\n      ts: response.ts,\n      onResolve\n    };\n    return null;\n  }\n  // Remove and returns completed requests.\n  removeCompleted(ts) {\n    const completeRequests = /* @__PURE__ */ new Map();\n    for (const [requestId, requestInfo] of this.inflightRequests.entries()) {\n      const status = requestInfo.status;\n      if (status.status === \"Completed\" && status.ts.lessThanOrEqual(ts)) {\n        status.onResolve();\n        completeRequests.set(requestId, status.result);\n        if (requestInfo.message.type === \"Mutation\") {\n          this.inflightMutationsCount--;\n        } else if (requestInfo.message.type === \"Action\") {\n          this.inflightActionsCount--;\n        }\n        this.inflightRequests.delete(requestId);\n        this.requestsOlderThanRestart.delete(requestId);\n      }\n    }\n    if (completeRequests.size > 0) {\n      this.markConnectionStateDirty();\n    }\n    return completeRequests;\n  }\n  restart() {\n    this.requestsOlderThanRestart = new Set(this.inflightRequests.keys());\n    const allMessages = [];\n    for (const [requestId, value] of this.inflightRequests) {\n      if (value.status.status === \"NotSent\") {\n        value.status.status = \"Requested\";\n        allMessages.push(value.message);\n        continue;\n      }\n      if (value.message.type === \"Mutation\") {\n        allMessages.push(value.message);\n      } else if (value.message.type === \"Action\") {\n        this.inflightRequests.delete(requestId);\n        this.requestsOlderThanRestart.delete(requestId);\n        this.inflightActionsCount--;\n        if (value.status.status === \"Completed\") {\n          throw new Error(\"Action should never be in 'Completed' state\");\n        }\n        value.status.onResult({\n          success: false,\n          errorMessage: \"Connection lost while action was in flight\",\n          logLines: []\n        });\n      }\n    }\n    this.markConnectionStateDirty();\n    return allMessages;\n  }\n  resume() {\n    const allMessages = [];\n    for (const [, value] of this.inflightRequests) {\n      if (value.status.status === \"NotSent\") {\n        value.status.status = \"Requested\";\n        allMessages.push(value.message);\n        continue;\n      }\n    }\n    return allMessages;\n  }\n  /**\n   * @returns true if there are any requests that have been requested but have\n   * not be completed yet.\n   */\n  hasIncompleteRequests() {\n    for (const requestInfo of this.inflightRequests.values()) {\n      if (requestInfo.status.status === \"Requested\") {\n        return true;\n      }\n    }\n    return false;\n  }\n  /**\n   * @returns true if there are any inflight requests, including ones that have\n   * completed on the server, but have not been applied.\n   */\n  hasInflightRequests() {\n    return this.inflightRequests.size > 0;\n  }\n  /**\n   * @returns true if there are any inflight requests, that have been hanging around\n   * since prior to the most recent restart.\n   */\n  hasSyncedPastLastReconnect() {\n    return this.requestsOlderThanRestart.size === 0;\n  }\n  timeOfOldestInflightRequest() {\n    if (this.inflightRequests.size === 0) {\n      return null;\n    }\n    let oldestInflightRequest = Date.now();\n    for (const request of this.inflightRequests.values()) {\n      if (request.status.status !== \"Completed\") {\n        if (request.status.requestedAt.getTime() < oldestInflightRequest) {\n          oldestInflightRequest = request.status.requestedAt.getTime();\n        }\n      }\n    }\n    return new Date(oldestInflightRequest);\n  }\n  /**\n   * @returns The number of mutations currently in flight.\n   */\n  inflightMutations() {\n    return this.inflightMutationsCount;\n  }\n  /**\n   * @returns The number of actions currently in flight.\n   */\n  inflightActions() {\n    return this.inflightActionsCount;\n  }\n}\n//# sourceMappingURL=request_manager.js.map\n","\"use strict\";\nexport const functionName = Symbol.for(\"functionName\");\n//# sourceMappingURL=functionName.js.map\n","\"use strict\";\nimport { functionName } from \"../functionName.js\";\nexport const toReferencePath = Symbol.for(\"toReferencePath\");\nexport function setReferencePath(obj, value) {\n  obj[toReferencePath] = value;\n}\nexport function extractReferencePath(reference) {\n  return reference[toReferencePath] ?? null;\n}\nexport function isFunctionHandle(s) {\n  return s.startsWith(\"function://\");\n}\nexport function getFunctionAddress(functionReference) {\n  let functionAddress;\n  if (typeof functionReference === \"string\") {\n    if (isFunctionHandle(functionReference)) {\n      functionAddress = { functionHandle: functionReference };\n    } else {\n      functionAddress = { name: functionReference };\n    }\n  } else if (functionReference[functionName]) {\n    functionAddress = { name: functionReference[functionName] };\n  } else {\n    const referencePath = extractReferencePath(functionReference);\n    if (!referencePath) {\n      throw new Error(`${functionReference} is not a functionReference`);\n    }\n    functionAddress = { reference: referencePath };\n  }\n  return functionAddress;\n}\n//# sourceMappingURL=paths.js.map\n","\"use strict\";\nimport { functionName } from \"./functionName.js\";\nimport { getFunctionAddress } from \"./components/paths.js\";\nexport function getFunctionName(functionReference) {\n  const address = getFunctionAddress(functionReference);\n  if (address.name === void 0) {\n    if (address.functionHandle !== void 0) {\n      throw new Error(\n        `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received function handle ${address.functionHandle}`\n      );\n    } else if (address.reference !== void 0) {\n      throw new Error(\n        `Expected function reference in the current component like \"api.file.func\" or \"internal.file.func\", but received reference ${address.reference}`\n      );\n    }\n    throw new Error(\n      `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received ${JSON.stringify(address)}`\n    );\n  }\n  if (typeof functionReference === \"string\") return functionReference;\n  const name = functionReference[functionName];\n  if (!name) {\n    throw new Error(`${functionReference} is not a functionReference`);\n  }\n  return name;\n}\nexport function makeFunctionReference(name) {\n  return { [functionName]: name };\n}\nfunction createApi(pathParts = []) {\n  const handler = {\n    get(_, prop) {\n      if (typeof prop === \"string\") {\n        const newParts = [...pathParts, prop];\n        return createApi(newParts);\n      } else if (prop === functionName) {\n        if (pathParts.length < 2) {\n          const found = [\"api\", ...pathParts].join(\".\");\n          throw new Error(\n            `API path is expected to be of the form \\`api.moduleName.functionName\\`. Found: \\`${found}\\``\n          );\n        }\n        const path = pathParts.slice(0, -1).join(\"/\");\n        const exportName = pathParts[pathParts.length - 1];\n        if (exportName === \"default\") {\n          return path;\n        } else {\n          return path + \":\" + exportName;\n        }\n      } else if (prop === Symbol.toStringTag) {\n        return \"FunctionReference\";\n      } else {\n        return void 0;\n      }\n    }\n  };\n  return new Proxy({}, handler);\n}\nexport function filterApi(api) {\n  return api;\n}\nexport function justInternal(api) {\n  return api;\n}\nexport function justPublic(api) {\n  return api;\n}\nexport function justQueries(api) {\n  return api;\n}\nexport function justMutations(api) {\n  return api;\n}\nexport function justActions(api) {\n  return api;\n}\nexport function justPaginatedQueries(api) {\n  return api;\n}\nexport function justSchedulable(api) {\n  return api;\n}\nexport const anyApi = createApi();\n//# sourceMappingURL=api.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport {\n  getFunctionName\n} from \"../../server/api.js\";\nimport { parseArgs } from \"../../common/index.js\";\nimport { createHybridErrorStacktrace, forwardData } from \"../logging.js\";\nimport {\n  canonicalizeUdfPath,\n  serializePathAndArgs\n} from \"./udf_path_utils.js\";\nimport { ConvexError } from \"../../values/errors.js\";\nclass OptimisticLocalStoreImpl {\n  constructor(queryResults) {\n    // A references of the query results in OptimisticQueryResults\n    __publicField(this, \"queryResults\");\n    // All of the queries modified by this class\n    __publicField(this, \"modifiedQueries\");\n    this.queryResults = queryResults;\n    this.modifiedQueries = [];\n  }\n  getQuery(query, ...args) {\n    const queryArgs = parseArgs(args[0]);\n    const name = getFunctionName(query);\n    const queryResult = this.queryResults.get(\n      serializePathAndArgs(name, queryArgs)\n    );\n    if (queryResult === void 0) {\n      return void 0;\n    }\n    return OptimisticLocalStoreImpl.queryValue(queryResult.result);\n  }\n  getAllQueries(query) {\n    const queriesWithName = [];\n    const name = getFunctionName(query);\n    for (const queryResult of this.queryResults.values()) {\n      if (queryResult.udfPath === canonicalizeUdfPath(name)) {\n        queriesWithName.push({\n          args: queryResult.args,\n          value: OptimisticLocalStoreImpl.queryValue(queryResult.result)\n        });\n      }\n    }\n    return queriesWithName;\n  }\n  setQuery(queryReference, args, value) {\n    const queryArgs = parseArgs(args);\n    const name = getFunctionName(queryReference);\n    const queryToken = serializePathAndArgs(name, queryArgs);\n    let result;\n    if (value === void 0) {\n      result = void 0;\n    } else {\n      result = {\n        success: true,\n        value,\n        // It's an optimistic update, so there are no function logs to show.\n        logLines: []\n      };\n    }\n    const query = {\n      udfPath: name,\n      args: queryArgs,\n      result\n    };\n    this.queryResults.set(queryToken, query);\n    this.modifiedQueries.push(queryToken);\n  }\n  static queryValue(result) {\n    if (result === void 0) {\n      return void 0;\n    } else if (result.success) {\n      return result.value;\n    } else {\n      return void 0;\n    }\n  }\n}\nexport class OptimisticQueryResults {\n  constructor() {\n    __publicField(this, \"queryResults\");\n    __publicField(this, \"optimisticUpdates\");\n    this.queryResults = /* @__PURE__ */ new Map();\n    this.optimisticUpdates = [];\n  }\n  /**\n   * Apply all optimistic updates on top of server query results\n   */\n  ingestQueryResultsFromServer(serverQueryResults, optimisticUpdatesToDrop) {\n    this.optimisticUpdates = this.optimisticUpdates.filter((updateAndId) => {\n      return !optimisticUpdatesToDrop.has(updateAndId.mutationId);\n    });\n    const oldQueryResults = this.queryResults;\n    this.queryResults = new Map(serverQueryResults);\n    const localStore = new OptimisticLocalStoreImpl(this.queryResults);\n    for (const updateAndId of this.optimisticUpdates) {\n      updateAndId.update(localStore);\n    }\n    const changedQueries = [];\n    for (const [queryToken, query] of this.queryResults) {\n      const oldQuery = oldQueryResults.get(queryToken);\n      if (oldQuery === void 0 || oldQuery.result !== query.result) {\n        changedQueries.push(queryToken);\n      }\n    }\n    return changedQueries;\n  }\n  applyOptimisticUpdate(update, mutationId) {\n    this.optimisticUpdates.push({\n      update,\n      mutationId\n    });\n    const localStore = new OptimisticLocalStoreImpl(this.queryResults);\n    update(localStore);\n    return localStore.modifiedQueries;\n  }\n  /**\n   * \"Raw\" with respect to errors vs values, but query results still have\n   * optimistic updates applied.\n   *\n   * @internal\n   */\n  rawQueryResult(queryToken) {\n    const query = this.queryResults.get(queryToken);\n    if (query === void 0) {\n      return void 0;\n    }\n    return query.result;\n  }\n  queryResult(queryToken) {\n    const query = this.queryResults.get(queryToken);\n    if (query === void 0) {\n      return void 0;\n    }\n    const result = query.result;\n    if (result === void 0) {\n      return void 0;\n    } else if (result.success) {\n      return result.value;\n    } else {\n      if (result.errorData !== void 0) {\n        throw forwardData(\n          result,\n          new ConvexError(\n            createHybridErrorStacktrace(\"query\", query.udfPath, result)\n          )\n        );\n      }\n      throw new Error(\n        createHybridErrorStacktrace(\"query\", query.udfPath, result)\n      );\n    }\n  }\n  hasQueryResult(queryToken) {\n    return this.queryResults.get(queryToken) !== void 0;\n  }\n  /**\n   * @internal\n   */\n  queryLogs(queryToken) {\n    const query = this.queryResults.get(queryToken);\n    return query?.result?.logLines;\n  }\n}\n//# sourceMappingURL=optimistic_updates_impl.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nexport class Long {\n  constructor(low, high) {\n    __publicField(this, \"low\");\n    __publicField(this, \"high\");\n    __publicField(this, \"__isUnsignedLong__\");\n    this.low = low | 0;\n    this.high = high | 0;\n    this.__isUnsignedLong__ = true;\n  }\n  static isLong(obj) {\n    return (obj && obj.__isUnsignedLong__) === true;\n  }\n  // prettier-ignore\n  static fromBytesLE(bytes) {\n    return new Long(\n      bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24,\n      bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24\n    );\n  }\n  // prettier-ignore\n  toBytesLE() {\n    const hi = this.high;\n    const lo = this.low;\n    return [\n      lo & 255,\n      lo >>> 8 & 255,\n      lo >>> 16 & 255,\n      lo >>> 24,\n      hi & 255,\n      hi >>> 8 & 255,\n      hi >>> 16 & 255,\n      hi >>> 24\n    ];\n  }\n  static fromNumber(value) {\n    if (isNaN(value)) return UZERO;\n    if (value < 0) return UZERO;\n    if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE;\n    return new Long(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0);\n  }\n  toString() {\n    return (BigInt(this.high) * BigInt(TWO_PWR_32_DBL) + BigInt(this.low)).toString();\n  }\n  equals(other) {\n    if (!Long.isLong(other)) other = Long.fromValue(other);\n    if (this.high >>> 31 === 1 && other.high >>> 31 === 1) return false;\n    return this.high === other.high && this.low === other.low;\n  }\n  notEquals(other) {\n    return !this.equals(other);\n  }\n  comp(other) {\n    if (!Long.isLong(other)) other = Long.fromValue(other);\n    if (this.equals(other)) return 0;\n    return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1;\n  }\n  lessThanOrEqual(other) {\n    return this.comp(\n      /* validates */\n      other\n    ) <= 0;\n  }\n  static fromValue(val) {\n    if (typeof val === \"number\") return Long.fromNumber(val);\n    return new Long(val.low, val.high);\n  }\n}\nconst UZERO = new Long(0, 0);\nconst TWO_PWR_16_DBL = 1 << 16;\nconst TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;\nconst TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;\nconst MAX_UNSIGNED_VALUE = new Long(4294967295 | 0, 4294967295 | 0);\n//# sourceMappingURL=long.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { jsonToConvex } from \"../../values/index.js\";\nimport { Long } from \"../../vendor/long.js\";\nimport { logForFunction } from \"../logging.js\";\nexport class RemoteQuerySet {\n  constructor(queryPath, logger) {\n    __publicField(this, \"version\");\n    __publicField(this, \"remoteQuerySet\");\n    __publicField(this, \"queryPath\");\n    __publicField(this, \"logger\");\n    this.version = { querySet: 0, ts: Long.fromNumber(0), identity: 0 };\n    this.remoteQuerySet = /* @__PURE__ */ new Map();\n    this.queryPath = queryPath;\n    this.logger = logger;\n  }\n  transition(transition) {\n    const start = transition.startVersion;\n    if (this.version.querySet !== start.querySet || this.version.ts.notEquals(start.ts) || this.version.identity !== start.identity) {\n      throw new Error(\n        `Invalid start version: ${start.ts.toString()}:${start.querySet}:${start.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`\n      );\n    }\n    for (const modification of transition.modifications) {\n      switch (modification.type) {\n        case \"QueryUpdated\": {\n          const queryPath = this.queryPath(modification.queryId);\n          if (queryPath) {\n            for (const line of modification.logLines) {\n              logForFunction(this.logger, \"info\", \"query\", queryPath, line);\n            }\n          }\n          const value = jsonToConvex(modification.value ?? null);\n          this.remoteQuerySet.set(modification.queryId, {\n            success: true,\n            value,\n            logLines: modification.logLines\n          });\n          break;\n        }\n        case \"QueryFailed\": {\n          const queryPath = this.queryPath(modification.queryId);\n          if (queryPath) {\n            for (const line of modification.logLines) {\n              logForFunction(this.logger, \"info\", \"query\", queryPath, line);\n            }\n          }\n          const { errorData } = modification;\n          this.remoteQuerySet.set(modification.queryId, {\n            success: false,\n            errorMessage: modification.errorMessage,\n            errorData: errorData !== void 0 ? jsonToConvex(errorData) : void 0,\n            logLines: modification.logLines\n          });\n          break;\n        }\n        case \"QueryRemoved\": {\n          this.remoteQuerySet.delete(modification.queryId);\n          break;\n        }\n        default: {\n          modification;\n          throw new Error(`Invalid modification ${modification.type}`);\n        }\n      }\n    }\n    this.version = transition.endVersion;\n  }\n  remoteQueryResults() {\n    return this.remoteQuerySet;\n  }\n  timestamp() {\n    return this.version.ts;\n  }\n}\n//# sourceMappingURL=remote_query_set.js.map\n","\"use strict\";\nimport { Base64 } from \"../../values/index.js\";\nimport { Long } from \"../../vendor/long.js\";\nexport function u64ToLong(encoded) {\n  const integerBytes = Base64.toByteArray(encoded);\n  return Long.fromBytesLE(Array.from(integerBytes));\n}\nexport function longToU64(raw) {\n  const integerBytes = new Uint8Array(raw.toBytesLE());\n  return Base64.fromByteArray(integerBytes);\n}\nexport function parseServerMessage(encoded) {\n  switch (encoded.type) {\n    case \"FatalError\":\n    case \"AuthError\":\n    case \"ActionResponse\":\n    case \"TransitionChunk\":\n    case \"Ping\": {\n      return { ...encoded };\n    }\n    case \"MutationResponse\": {\n      if (encoded.success) {\n        return { ...encoded, ts: u64ToLong(encoded.ts) };\n      } else {\n        return { ...encoded };\n      }\n    }\n    case \"Transition\": {\n      return {\n        ...encoded,\n        startVersion: {\n          ...encoded.startVersion,\n          ts: u64ToLong(encoded.startVersion.ts)\n        },\n        endVersion: {\n          ...encoded.endVersion,\n          ts: u64ToLong(encoded.endVersion.ts)\n        }\n      };\n    }\n    default: {\n      encoded;\n    }\n  }\n  return void 0;\n}\nexport function encodeClientMessage(message) {\n  switch (message.type) {\n    case \"Authenticate\":\n    case \"ModifyQuerySet\":\n    case \"Mutation\":\n    case \"Action\":\n    case \"Event\": {\n      return { ...message };\n    }\n    case \"Connect\": {\n      if (message.maxObservedTimestamp !== void 0) {\n        return {\n          ...message,\n          maxObservedTimestamp: longToU64(message.maxObservedTimestamp)\n        };\n      } else {\n        return { ...message, maxObservedTimestamp: void 0 };\n      }\n    }\n    default: {\n      message;\n    }\n  }\n  return void 0;\n}\n//# sourceMappingURL=protocol.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport {\n  encodeClientMessage,\n  parseServerMessage\n} from \"./protocol.js\";\nconst CLOSE_NORMAL = 1e3;\nconst CLOSE_GOING_AWAY = 1001;\nconst CLOSE_NO_STATUS = 1005;\nconst CLOSE_NOT_FOUND = 4040;\nlet firstTime;\nfunction monotonicMillis() {\n  if (firstTime === void 0) {\n    firstTime = Date.now();\n  }\n  if (typeof performance === \"undefined\" || !performance.now) {\n    return Date.now();\n  }\n  return Math.round(firstTime + performance.now());\n}\nfunction prettyNow() {\n  return `t=${Math.round((monotonicMillis() - firstTime) / 100) / 10}s`;\n}\nconst serverDisconnectErrors = {\n  // A known error, e.g. during a restart or push\n  InternalServerError: { timeout: 1e3 },\n  // ErrorMetadata::overloaded() messages that we realy should back off\n  SubscriptionsWorkerFullError: { timeout: 3e3 },\n  TooManyConcurrentRequests: { timeout: 3e3 },\n  CommitterFullError: { timeout: 3e3 },\n  AwsTooManyRequestsException: { timeout: 3e3 },\n  ExecuteFullError: { timeout: 3e3 },\n  SystemTimeoutError: { timeout: 3e3 },\n  ExpiredInQueue: { timeout: 3e3 },\n  // ErrorMetadata::feature_temporarily_unavailable() that typically indicate a deploy just happened\n  VectorIndexesUnavailable: { timeout: 1e3 },\n  SearchIndexesUnavailable: { timeout: 1e3 },\n  TableSummariesUnavailable: { timeout: 1e3 },\n  // More ErrorMetadata::overloaded()\n  VectorIndexTooLarge: { timeout: 3e3 },\n  SearchIndexTooLarge: { timeout: 3e3 },\n  TooManyWritesInTimePeriod: { timeout: 3e3 }\n};\nfunction classifyDisconnectError(s) {\n  if (s === void 0) return \"Unknown\";\n  for (const prefix of Object.keys(\n    serverDisconnectErrors\n  )) {\n    if (s.startsWith(prefix)) {\n      return prefix;\n    }\n  }\n  return \"Unknown\";\n}\nexport class WebSocketManager {\n  constructor(uri, callbacks, webSocketConstructor, logger, markConnectionStateDirty, debug) {\n    this.markConnectionStateDirty = markConnectionStateDirty;\n    this.debug = debug;\n    __publicField(this, \"socket\");\n    __publicField(this, \"connectionCount\");\n    __publicField(this, \"_hasEverConnected\", false);\n    __publicField(this, \"lastCloseReason\");\n    // State for assembling the split-up Transition currently being received.\n    __publicField(this, \"transitionChunkBuffer\", null);\n    /** Upon HTTPS/WSS failure, the first jittered backoff duration, in ms. */\n    __publicField(this, \"defaultInitialBackoff\");\n    /** We backoff exponentially, but we need to cap that--this is the jittered max. */\n    __publicField(this, \"maxBackoff\");\n    /** How many times have we failed consecutively? */\n    __publicField(this, \"retries\");\n    /** How long before lack of server response causes us to initiate a reconnect,\n     * in ms */\n    __publicField(this, \"serverInactivityThreshold\");\n    __publicField(this, \"reconnectDueToServerInactivityTimeout\");\n    /** Scheduled reconnect state: timeout handle and timing info */\n    __publicField(this, \"scheduledReconnect\", null);\n    __publicField(this, \"networkOnlineHandler\", null);\n    /** Pending event to send after reconnecting due to network recovery */\n    __publicField(this, \"pendingNetworkRecoveryInfo\", null);\n    __publicField(this, \"uri\");\n    __publicField(this, \"onOpen\");\n    __publicField(this, \"onResume\");\n    __publicField(this, \"onMessage\");\n    __publicField(this, \"webSocketConstructor\");\n    __publicField(this, \"logger\");\n    __publicField(this, \"onServerDisconnectError\");\n    this.webSocketConstructor = webSocketConstructor;\n    this.socket = { state: \"disconnected\" };\n    this.connectionCount = 0;\n    this.lastCloseReason = \"InitialConnect\";\n    this.defaultInitialBackoff = 1e3;\n    this.maxBackoff = 16e3;\n    this.retries = 0;\n    this.serverInactivityThreshold = 6e4;\n    this.reconnectDueToServerInactivityTimeout = null;\n    this.uri = uri;\n    this.onOpen = callbacks.onOpen;\n    this.onResume = callbacks.onResume;\n    this.onMessage = callbacks.onMessage;\n    this.onServerDisconnectError = callbacks.onServerDisconnectError;\n    this.logger = logger;\n    this.setupNetworkListener();\n    this.connect();\n  }\n  setSocketState(state) {\n    this.socket = state;\n    this._logVerbose(\n      `socket state changed: ${this.socket.state}, paused: ${\"paused\" in this.socket ? this.socket.paused : void 0}`\n    );\n    this.markConnectionStateDirty();\n  }\n  setupNetworkListener() {\n    if (typeof window === \"undefined\" || typeof window.addEventListener !== \"function\") {\n      return;\n    }\n    if (this.networkOnlineHandler !== null) {\n      return;\n    }\n    this.networkOnlineHandler = () => {\n      this._logVerbose(\"network online event detected\");\n      this.tryReconnectImmediately();\n    };\n    window.addEventListener(\"online\", this.networkOnlineHandler);\n    this._logVerbose(\"network online event listener registered\");\n  }\n  cleanupNetworkListener() {\n    if (this.networkOnlineHandler && typeof window !== \"undefined\" && typeof window.removeEventListener === \"function\") {\n      window.removeEventListener(\"online\", this.networkOnlineHandler);\n      this.networkOnlineHandler = null;\n      this._logVerbose(\"network online event listener removed\");\n    }\n  }\n  assembleTransition(chunk) {\n    if (chunk.partNumber < 0 || chunk.partNumber >= chunk.totalParts || chunk.totalParts === 0 || this.transitionChunkBuffer && (this.transitionChunkBuffer.totalParts !== chunk.totalParts || this.transitionChunkBuffer.transitionId !== chunk.transitionId)) {\n      this.transitionChunkBuffer = null;\n      throw new Error(\"Invalid TransitionChunk\");\n    }\n    if (this.transitionChunkBuffer === null) {\n      this.transitionChunkBuffer = {\n        chunks: [],\n        totalParts: chunk.totalParts,\n        transitionId: chunk.transitionId\n      };\n    }\n    if (chunk.partNumber !== this.transitionChunkBuffer.chunks.length) {\n      const expectedLength = this.transitionChunkBuffer.chunks.length;\n      this.transitionChunkBuffer = null;\n      throw new Error(\n        `TransitionChunk received out of order: expected part ${expectedLength}, got ${chunk.partNumber}`\n      );\n    }\n    this.transitionChunkBuffer.chunks.push(chunk.chunk);\n    if (this.transitionChunkBuffer.chunks.length === chunk.totalParts) {\n      const fullJson = this.transitionChunkBuffer.chunks.join(\"\");\n      this.transitionChunkBuffer = null;\n      const transition = parseServerMessage(JSON.parse(fullJson));\n      if (transition.type !== \"Transition\") {\n        throw new Error(\n          `Expected Transition, got ${transition.type} after assembling chunks`\n        );\n      }\n      return transition;\n    }\n    return null;\n  }\n  connect() {\n    if (this.socket.state === \"terminated\") {\n      return;\n    }\n    if (this.socket.state !== \"disconnected\" && this.socket.state !== \"stopped\") {\n      throw new Error(\n        \"Didn't start connection from disconnected state: \" + this.socket.state\n      );\n    }\n    const ws = new this.webSocketConstructor(this.uri);\n    this._logVerbose(\"constructed WebSocket\");\n    this.setSocketState({\n      state: \"connecting\",\n      ws,\n      paused: \"no\"\n    });\n    this.resetServerInactivityTimeout();\n    ws.onopen = () => {\n      this.logger.logVerbose(\"begin ws.onopen\");\n      if (this.socket.state !== \"connecting\") {\n        throw new Error(\"onopen called with socket not in connecting state\");\n      }\n      this.setSocketState({\n        state: \"ready\",\n        ws,\n        paused: this.socket.paused === \"yes\" ? \"uninitialized\" : \"no\"\n      });\n      this.resetServerInactivityTimeout();\n      if (this.socket.paused === \"no\") {\n        this._hasEverConnected = true;\n        this.onOpen({\n          connectionCount: this.connectionCount,\n          lastCloseReason: this.lastCloseReason,\n          clientTs: monotonicMillis()\n        });\n      }\n      if (this.lastCloseReason !== \"InitialConnect\") {\n        if (this.lastCloseReason) {\n          this.logger.log(\n            \"WebSocket reconnected at\",\n            prettyNow(),\n            \"after disconnect due to\",\n            this.lastCloseReason\n          );\n        } else {\n          this.logger.log(\"WebSocket reconnected at\", prettyNow());\n        }\n      }\n      this.connectionCount += 1;\n      this.lastCloseReason = null;\n      if (this.pendingNetworkRecoveryInfo !== null) {\n        const { timeSavedMs } = this.pendingNetworkRecoveryInfo;\n        this.pendingNetworkRecoveryInfo = null;\n        this.sendMessage({\n          type: \"Event\",\n          eventType: \"NetworkRecoveryReconnect\",\n          event: { timeSavedMs }\n        });\n        this.logger.log(\n          `Network recovery reconnect saved ~${Math.round(timeSavedMs / 1e3)}s of waiting`\n        );\n      }\n    };\n    ws.onerror = (error) => {\n      this.transitionChunkBuffer = null;\n      const message = error.message;\n      if (message) {\n        this.logger.log(`WebSocket error message: ${message}`);\n      }\n    };\n    ws.onmessage = (message) => {\n      this.resetServerInactivityTimeout();\n      const messageLength = message.data.length;\n      let serverMessage = parseServerMessage(JSON.parse(message.data));\n      this._logVerbose(`received ws message with type ${serverMessage.type}`);\n      if (serverMessage.type === \"Ping\") {\n        return;\n      }\n      if (serverMessage.type === \"TransitionChunk\") {\n        const transition = this.assembleTransition(serverMessage);\n        if (!transition) {\n          return;\n        }\n        serverMessage = transition;\n        this._logVerbose(\n          `assembled full ws message of type ${serverMessage.type}`\n        );\n      }\n      if (this.transitionChunkBuffer !== null) {\n        this.transitionChunkBuffer = null;\n        this.logger.log(\n          `Received unexpected ${serverMessage.type} while buffering TransitionChunks`\n        );\n      }\n      if (serverMessage.type === \"Transition\") {\n        this.reportLargeTransition({\n          messageLength,\n          transition: serverMessage\n        });\n      }\n      const response = this.onMessage(serverMessage);\n      if (response.hasSyncedPastLastReconnect) {\n        this.retries = 0;\n        this.markConnectionStateDirty();\n      }\n    };\n    ws.onclose = (event) => {\n      this._logVerbose(\"begin ws.onclose\");\n      this.transitionChunkBuffer = null;\n      if (this.lastCloseReason === null) {\n        this.lastCloseReason = event.reason || `closed with code ${event.code}`;\n      }\n      if (event.code !== CLOSE_NORMAL && event.code !== CLOSE_GOING_AWAY && // This commonly gets fired on mobile apps when the app is backgrounded\n      event.code !== CLOSE_NO_STATUS && event.code !== CLOSE_NOT_FOUND) {\n        let msg = `WebSocket closed with code ${event.code}`;\n        if (event.reason) {\n          msg += `: ${event.reason}`;\n        }\n        this.logger.log(msg);\n        if (this.onServerDisconnectError && event.reason) {\n          this.onServerDisconnectError(msg);\n        }\n      }\n      const reason = classifyDisconnectError(event.reason);\n      this.scheduleReconnect(reason);\n      return;\n    };\n  }\n  /**\n   * @returns The state of the {@link Socket}.\n   */\n  socketState() {\n    return this.socket.state;\n  }\n  /**\n   * @param message - A ClientMessage to send.\n   * @returns Whether the message (might have been) sent.\n   */\n  sendMessage(message) {\n    const messageForLog = {\n      type: message.type,\n      ...message.type === \"Authenticate\" && message.tokenType === \"User\" ? {\n        value: `...${message.value.slice(-7)}`\n      } : {}\n    };\n    if (this.socket.state === \"ready\" && this.socket.paused === \"no\") {\n      const encodedMessage = encodeClientMessage(message);\n      const request = JSON.stringify(encodedMessage);\n      let sent = false;\n      try {\n        this.socket.ws.send(request);\n        sent = true;\n      } catch (error) {\n        this.logger.log(\n          `Failed to send message on WebSocket, reconnecting: ${error}`\n        );\n        this.closeAndReconnect(\"FailedToSendMessage\");\n      }\n      this._logVerbose(\n        `${sent ? \"sent\" : \"failed to send\"} message with type ${message.type}: ${JSON.stringify(\n          messageForLog\n        )}`\n      );\n      return true;\n    }\n    this._logVerbose(\n      `message not sent (socket state: ${this.socket.state}, paused: ${\"paused\" in this.socket ? this.socket.paused : void 0}): ${JSON.stringify(\n        messageForLog\n      )}`\n    );\n    return false;\n  }\n  resetServerInactivityTimeout() {\n    if (this.socket.state === \"terminated\") {\n      return;\n    }\n    if (this.reconnectDueToServerInactivityTimeout !== null) {\n      clearTimeout(this.reconnectDueToServerInactivityTimeout);\n      this.reconnectDueToServerInactivityTimeout = null;\n    }\n    this.reconnectDueToServerInactivityTimeout = setTimeout(() => {\n      this.closeAndReconnect(\"InactiveServer\");\n    }, this.serverInactivityThreshold);\n  }\n  scheduleReconnect(reason) {\n    if (this.scheduledReconnect) {\n      clearTimeout(this.scheduledReconnect.timeout);\n      this.scheduledReconnect = null;\n    }\n    this.socket = { state: \"disconnected\" };\n    const backoff = this.nextBackoff(reason);\n    this.markConnectionStateDirty();\n    this.logger.log(`Attempting reconnect in ${Math.round(backoff)}ms`);\n    const scheduledAt = monotonicMillis();\n    const timeoutId = setTimeout(() => {\n      if (this.scheduledReconnect?.timeout === timeoutId) {\n        this.scheduledReconnect = null;\n        this.connect();\n      }\n    }, backoff);\n    this.scheduledReconnect = {\n      timeout: timeoutId,\n      scheduledAt,\n      backoffMs: backoff\n    };\n  }\n  /**\n   * Close the WebSocket and schedule a reconnect.\n   *\n   * This should be used when we hit an error and would like to restart the session.\n   */\n  closeAndReconnect(closeReason) {\n    this._logVerbose(`begin closeAndReconnect with reason ${closeReason}`);\n    switch (this.socket.state) {\n      case \"disconnected\":\n      case \"terminated\":\n      case \"stopped\":\n        return;\n      case \"connecting\":\n      case \"ready\": {\n        this.lastCloseReason = closeReason;\n        void this.close();\n        this.scheduleReconnect(\"client\");\n        return;\n      }\n      default: {\n        this.socket;\n      }\n    }\n  }\n  /**\n   * Close the WebSocket, being careful to clear the onclose handler to avoid re-entrant\n   * calls. Use this instead of directly calling `ws.close()`\n   *\n   * It is the callers responsibility to update the state after this method is called so that the\n   * closed socket is not accessible or used again after this method is called\n   */\n  close() {\n    this.transitionChunkBuffer = null;\n    switch (this.socket.state) {\n      case \"disconnected\":\n      case \"terminated\":\n      case \"stopped\":\n        return Promise.resolve();\n      case \"connecting\": {\n        const ws = this.socket.ws;\n        ws.onmessage = (_message) => {\n          this._logVerbose(\"Ignoring message received after close\");\n        };\n        return new Promise((r) => {\n          ws.onclose = () => {\n            this._logVerbose(\"Closed after connecting\");\n            r();\n          };\n          ws.onopen = () => {\n            this._logVerbose(\"Opened after connecting\");\n            ws.close();\n          };\n        });\n      }\n      case \"ready\": {\n        this._logVerbose(\"ws.close called\");\n        const ws = this.socket.ws;\n        ws.onmessage = (_message) => {\n          this._logVerbose(\"Ignoring message received after close\");\n        };\n        const result = new Promise((r) => {\n          ws.onclose = () => {\n            r();\n          };\n        });\n        ws.close();\n        return result;\n      }\n      default: {\n        this.socket;\n        return Promise.resolve();\n      }\n    }\n  }\n  /**\n   * Close the WebSocket and do not reconnect.\n   * @returns A Promise that resolves when the WebSocket `onClose` callback is called.\n   */\n  terminate() {\n    if (this.reconnectDueToServerInactivityTimeout) {\n      clearTimeout(this.reconnectDueToServerInactivityTimeout);\n    }\n    if (this.scheduledReconnect) {\n      clearTimeout(this.scheduledReconnect.timeout);\n      this.scheduledReconnect = null;\n    }\n    this.cleanupNetworkListener();\n    switch (this.socket.state) {\n      case \"terminated\":\n      case \"stopped\":\n      case \"disconnected\":\n      case \"connecting\":\n      case \"ready\": {\n        const result = this.close();\n        this.setSocketState({ state: \"terminated\" });\n        return result;\n      }\n      default: {\n        this.socket;\n        throw new Error(\n          `Invalid websocket state: ${this.socket.state}`\n        );\n      }\n    }\n  }\n  stop() {\n    switch (this.socket.state) {\n      case \"terminated\":\n        return Promise.resolve();\n      case \"connecting\":\n      case \"stopped\":\n      case \"disconnected\":\n      case \"ready\": {\n        this.cleanupNetworkListener();\n        const result = this.close();\n        this.socket = { state: \"stopped\" };\n        return result;\n      }\n      default: {\n        this.socket;\n        return Promise.resolve();\n      }\n    }\n  }\n  /**\n   * Create a new WebSocket after a previous `stop()`, unless `terminate()` was\n   * called before.\n   */\n  tryRestart() {\n    switch (this.socket.state) {\n      case \"stopped\":\n        break;\n      case \"terminated\":\n      case \"connecting\":\n      case \"ready\":\n      case \"disconnected\":\n        this.logger.logVerbose(\"Restart called without stopping first\");\n        return;\n      default: {\n        this.socket;\n      }\n    }\n    this.setupNetworkListener();\n    this.connect();\n  }\n  pause() {\n    switch (this.socket.state) {\n      case \"disconnected\":\n      case \"stopped\":\n      case \"terminated\":\n        return;\n      case \"connecting\":\n      case \"ready\": {\n        this.socket = { ...this.socket, paused: \"yes\" };\n        return;\n      }\n      default: {\n        this.socket;\n        return;\n      }\n    }\n  }\n  /**\n   * Try to reconnect immediately, canceling any scheduled reconnect.\n   * This is useful when detecting network recovery.\n   * Only takes action if we're in disconnected state (waiting to reconnect).\n   */\n  tryReconnectImmediately() {\n    this._logVerbose(\"tryReconnectImmediately called\");\n    if (this.socket.state !== \"disconnected\") {\n      this._logVerbose(\n        `tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`\n      );\n      return;\n    }\n    let timeSavedMs = null;\n    if (this.scheduledReconnect) {\n      const elapsed = monotonicMillis() - this.scheduledReconnect.scheduledAt;\n      timeSavedMs = Math.max(0, this.scheduledReconnect.backoffMs - elapsed);\n      this._logVerbose(\n        `would have waited ${Math.round(timeSavedMs)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(elapsed)}ms)`\n      );\n      clearTimeout(this.scheduledReconnect.timeout);\n      this.scheduledReconnect = null;\n      this._logVerbose(\"canceled scheduled reconnect\");\n    }\n    this.logger.log(\"Network recovery detected, reconnecting immediately\");\n    this.pendingNetworkRecoveryInfo = timeSavedMs !== null ? { timeSavedMs } : null;\n    this.connect();\n  }\n  /**\n   * Resume the state machine if previously paused.\n   */\n  resume() {\n    switch (this.socket.state) {\n      case \"connecting\":\n        this.socket = { ...this.socket, paused: \"no\" };\n        return;\n      case \"ready\":\n        if (this.socket.paused === \"uninitialized\") {\n          this.socket = { ...this.socket, paused: \"no\" };\n          this.onOpen({\n            connectionCount: this.connectionCount,\n            lastCloseReason: this.lastCloseReason,\n            clientTs: monotonicMillis()\n          });\n        } else if (this.socket.paused === \"yes\") {\n          this.socket = { ...this.socket, paused: \"no\" };\n          this.onResume();\n        }\n        return;\n      case \"terminated\":\n      case \"stopped\":\n      case \"disconnected\":\n        return;\n      default: {\n        this.socket;\n      }\n    }\n    this.connect();\n  }\n  connectionState() {\n    return {\n      isConnected: this.socket.state === \"ready\",\n      hasEverConnected: this._hasEverConnected,\n      connectionCount: this.connectionCount,\n      connectionRetries: this.retries\n    };\n  }\n  _logVerbose(message) {\n    this.logger.logVerbose(message);\n  }\n  nextBackoff(reason) {\n    const initialBackoff = reason === \"client\" ? 100 : reason === \"Unknown\" ? this.defaultInitialBackoff : serverDisconnectErrors[reason].timeout;\n    const baseBackoff = initialBackoff * Math.pow(2, this.retries);\n    this.retries += 1;\n    const actualBackoff = Math.min(baseBackoff, this.maxBackoff);\n    const jitter = actualBackoff * (Math.random() - 0.5);\n    return actualBackoff + jitter;\n  }\n  reportLargeTransition({\n    transition,\n    messageLength\n  }) {\n    if (transition.clientClockSkew === void 0 || transition.serverTs === void 0) {\n      return;\n    }\n    const transitionTransitTime = monotonicMillis() - // client time now\n    // clientClockSkew = (server time + upstream latency) - client time\n    // clientClockSkew is \"how many milliseconds behind (slow) is the client clock\"\n    // but the latency of the Connect message inflates this, making it appear further behind\n    transition.clientClockSkew - transition.serverTs / 1e6;\n    const prettyTransitionTime = `${Math.round(transitionTransitTime)}ms`;\n    const prettyMessageMB = `${Math.round(messageLength / 1e4) / 100}MB`;\n    const bytesPerSecond = messageLength / (transitionTransitTime / 1e3);\n    const prettyBytesPerSecond = `${Math.round(bytesPerSecond / 1e4) / 100}MB per second`;\n    this._logVerbose(\n      `received ${prettyMessageMB} transition in ${prettyTransitionTime} at ${prettyBytesPerSecond}`\n    );\n    if (messageLength > 2e7) {\n      this.logger.log(\n        `received query results totaling more that 20MB (${prettyMessageMB}) which will take a long time to download on slower connections`\n      );\n    } else if (transitionTransitTime > 2e4) {\n      this.logger.log(\n        `received query results totaling ${prettyMessageMB} which took more than 20s to arrive (${prettyTransitionTime})`\n      );\n    }\n    if (this.debug) {\n      this.sendMessage({\n        type: \"Event\",\n        eventType: \"ClientReceivedTransition\",\n        event: { transitionTransitTime, messageLength }\n      });\n    }\n  }\n}\n//# sourceMappingURL=web_socket_manager.js.map\n","\"use strict\";\nexport function newSessionId() {\n  return uuidv4();\n}\nfunction uuidv4() {\n  return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n    const r = Math.random() * 16 | 0, v = c === \"x\" ? r : r & 3 | 8;\n    return v.toString(16);\n  });\n}\n//# sourceMappingURL=session.js.map\n","\"use strict\";\nexport class InvalidTokenError extends Error {\n}\nInvalidTokenError.prototype.name = \"InvalidTokenError\";\nfunction b64DecodeUnicode(str) {\n  return decodeURIComponent(\n    atob(str).replace(/(.)/g, (_m, p) => {\n      let code = p.charCodeAt(0).toString(16).toUpperCase();\n      if (code.length < 2) {\n        code = \"0\" + code;\n      }\n      return \"%\" + code;\n    })\n  );\n}\nfunction base64UrlDecode(str) {\n  let output = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n  switch (output.length % 4) {\n    case 0:\n      break;\n    case 2:\n      output += \"==\";\n      break;\n    case 3:\n      output += \"=\";\n      break;\n    default:\n      throw new Error(\"base64 string is not of the correct length\");\n  }\n  try {\n    return b64DecodeUnicode(output);\n  } catch {\n    return atob(output);\n  }\n}\nexport function jwtDecode(token, options) {\n  if (typeof token !== \"string\") {\n    throw new InvalidTokenError(\"Invalid token specified: must be a string\");\n  }\n  options || (options = {});\n  const pos = options.header === true ? 0 : 1;\n  const part = token.split(\".\")[pos];\n  if (typeof part !== \"string\") {\n    throw new InvalidTokenError(\n      `Invalid token specified: missing part #${pos + 1}`\n    );\n  }\n  let decoded;\n  try {\n    decoded = base64UrlDecode(part);\n  } catch (e) {\n    throw new InvalidTokenError(\n      `Invalid token specified: invalid base64 for part #${pos + 1} (${e.message})`\n    );\n  }\n  try {\n    return JSON.parse(decoded);\n  } catch (e) {\n    throw new InvalidTokenError(\n      `Invalid token specified: invalid json for part #${pos + 1} (${e.message})`\n    );\n  }\n}\n//# sourceMappingURL=index.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { jwtDecode } from \"../../vendor/jwt-decode/index.js\";\nconst MAXIMUM_REFRESH_DELAY = 20 * 24 * 60 * 60 * 1e3;\nconst MAX_TOKEN_CONFIRMATION_ATTEMPTS = 2;\nexport class AuthenticationManager {\n  constructor(syncState, callbacks, config) {\n    __publicField(this, \"authState\", { state: \"noAuth\" });\n    // Used to detect races involving `setConfig` calls\n    // while a token is being fetched.\n    __publicField(this, \"configVersion\", 0);\n    // Shared by the BaseClient so that the auth manager can easily inspect it\n    __publicField(this, \"syncState\");\n    // Passed down by BaseClient, sends a message to the server\n    __publicField(this, \"authenticate\");\n    __publicField(this, \"stopSocket\");\n    __publicField(this, \"tryRestartSocket\");\n    __publicField(this, \"pauseSocket\");\n    __publicField(this, \"resumeSocket\");\n    // Passed down by BaseClient, sends a message to the server\n    __publicField(this, \"clearAuth\");\n    __publicField(this, \"logger\");\n    __publicField(this, \"refreshTokenLeewaySeconds\");\n    // Number of times we have attempted to confirm the latest token. We retry up\n    // to `MAX_TOKEN_CONFIRMATION_ATTEMPTS` times.\n    __publicField(this, \"tokenConfirmationAttempts\", 0);\n    this.syncState = syncState;\n    this.authenticate = callbacks.authenticate;\n    this.stopSocket = callbacks.stopSocket;\n    this.tryRestartSocket = callbacks.tryRestartSocket;\n    this.pauseSocket = callbacks.pauseSocket;\n    this.resumeSocket = callbacks.resumeSocket;\n    this.clearAuth = callbacks.clearAuth;\n    this.logger = config.logger;\n    this.refreshTokenLeewaySeconds = config.refreshTokenLeewaySeconds;\n  }\n  async setConfig(fetchToken, onChange) {\n    this.resetAuthState();\n    this._logVerbose(\"pausing WS for auth token fetch\");\n    this.pauseSocket();\n    const token = await this.fetchTokenAndGuardAgainstRace(fetchToken, {\n      forceRefreshToken: false\n    });\n    if (token.isFromOutdatedConfig) {\n      return;\n    }\n    if (token.value) {\n      this.setAuthState({\n        state: \"waitingForServerConfirmationOfCachedToken\",\n        config: { fetchToken, onAuthChange: onChange },\n        hasRetried: false\n      });\n      this.authenticate(token.value);\n    } else {\n      this.setAuthState({\n        state: \"initialRefetch\",\n        config: { fetchToken, onAuthChange: onChange }\n      });\n      await this.refetchToken();\n    }\n    this._logVerbose(\"resuming WS after auth token fetch\");\n    this.resumeSocket();\n  }\n  onTransition(serverMessage) {\n    if (!this.syncState.isCurrentOrNewerAuthVersion(\n      serverMessage.endVersion.identity\n    )) {\n      return;\n    }\n    if (serverMessage.endVersion.identity <= serverMessage.startVersion.identity) {\n      return;\n    }\n    if (this.authState.state === \"waitingForServerConfirmationOfCachedToken\") {\n      this._logVerbose(\"server confirmed auth token is valid\");\n      void this.refetchToken();\n      this.authState.config.onAuthChange(true);\n      return;\n    }\n    if (this.authState.state === \"waitingForServerConfirmationOfFreshToken\") {\n      this._logVerbose(\"server confirmed new auth token is valid\");\n      this.scheduleTokenRefetch(this.authState.token);\n      this.tokenConfirmationAttempts = 0;\n      if (!this.authState.hadAuth) {\n        this.authState.config.onAuthChange(true);\n      }\n    }\n  }\n  onAuthError(serverMessage) {\n    if (serverMessage.authUpdateAttempted === false && (this.authState.state === \"waitingForServerConfirmationOfFreshToken\" || this.authState.state === \"waitingForServerConfirmationOfCachedToken\")) {\n      this._logVerbose(\"ignoring non-auth token expired error\");\n      return;\n    }\n    const { baseVersion } = serverMessage;\n    if (!this.syncState.isCurrentOrNewerAuthVersion(baseVersion + 1)) {\n      this._logVerbose(\"ignoring auth error for previous auth attempt\");\n      return;\n    }\n    void this.tryToReauthenticate(serverMessage);\n    return;\n  }\n  // This is similar to `refetchToken` defined below, in fact we\n  // don't represent them as different states, but it is different\n  // in that we pause the WebSocket so that mutations\n  // don't retry with bad auth.\n  async tryToReauthenticate(serverMessage) {\n    this._logVerbose(`attempting to reauthenticate: ${serverMessage.error}`);\n    if (\n      // No way to fetch another token, kaboom\n      this.authState.state === \"noAuth\" || // We failed on a fresh token. After a small number of retries, we give up\n      // and clear the auth state to avoid infinite retries.\n      this.authState.state === \"waitingForServerConfirmationOfFreshToken\" && this.tokenConfirmationAttempts >= MAX_TOKEN_CONFIRMATION_ATTEMPTS\n    ) {\n      this.logger.error(\n        `Failed to authenticate: \"${serverMessage.error}\", check your server auth config`\n      );\n      if (this.syncState.hasAuth()) {\n        this.syncState.clearAuth();\n      }\n      if (this.authState.state !== \"noAuth\") {\n        this.setAndReportAuthFailed(this.authState.config.onAuthChange);\n      }\n      return;\n    }\n    if (this.authState.state === \"waitingForServerConfirmationOfFreshToken\") {\n      this.tokenConfirmationAttempts++;\n      this._logVerbose(\n        `retrying reauthentication, ${MAX_TOKEN_CONFIRMATION_ATTEMPTS - this.tokenConfirmationAttempts} attempts remaining`\n      );\n    }\n    await this.stopSocket();\n    const token = await this.fetchTokenAndGuardAgainstRace(\n      this.authState.config.fetchToken,\n      {\n        forceRefreshToken: true\n      }\n    );\n    if (token.isFromOutdatedConfig) {\n      return;\n    }\n    if (token.value && this.syncState.isNewAuth(token.value)) {\n      this.authenticate(token.value);\n      this.setAuthState({\n        state: \"waitingForServerConfirmationOfFreshToken\",\n        config: this.authState.config,\n        token: token.value,\n        hadAuth: this.authState.state === \"notRefetching\" || this.authState.state === \"waitingForScheduledRefetch\"\n      });\n    } else {\n      this._logVerbose(\"reauthentication failed, could not fetch a new token\");\n      if (this.syncState.hasAuth()) {\n        this.syncState.clearAuth();\n      }\n      this.setAndReportAuthFailed(this.authState.config.onAuthChange);\n    }\n    this.tryRestartSocket();\n  }\n  // Force refetch the token and schedule another refetch\n  // before the token expires - an active client should never\n  // need to reauthenticate.\n  async refetchToken() {\n    if (this.authState.state === \"noAuth\") {\n      return;\n    }\n    this._logVerbose(\"refetching auth token\");\n    const token = await this.fetchTokenAndGuardAgainstRace(\n      this.authState.config.fetchToken,\n      {\n        forceRefreshToken: true\n      }\n    );\n    if (token.isFromOutdatedConfig) {\n      return;\n    }\n    if (token.value) {\n      if (this.syncState.isNewAuth(token.value)) {\n        this.setAuthState({\n          state: \"waitingForServerConfirmationOfFreshToken\",\n          hadAuth: this.syncState.hasAuth(),\n          token: token.value,\n          config: this.authState.config\n        });\n        this.authenticate(token.value);\n      } else {\n        this.setAuthState({\n          state: \"notRefetching\",\n          config: this.authState.config\n        });\n      }\n    } else {\n      this._logVerbose(\"refetching token failed\");\n      if (this.syncState.hasAuth()) {\n        this.clearAuth();\n      }\n      this.setAndReportAuthFailed(this.authState.config.onAuthChange);\n    }\n    this._logVerbose(\n      \"restarting WS after auth token fetch (if currently stopped)\"\n    );\n    this.tryRestartSocket();\n  }\n  scheduleTokenRefetch(token) {\n    if (this.authState.state === \"noAuth\") {\n      return;\n    }\n    const decodedToken = this.decodeToken(token);\n    if (!decodedToken) {\n      this.logger.error(\n        \"Auth token is not a valid JWT, cannot refetch the token\"\n      );\n      return;\n    }\n    const { iat, exp } = decodedToken;\n    if (!iat || !exp) {\n      this.logger.error(\n        \"Auth token does not have required fields, cannot refetch the token\"\n      );\n      return;\n    }\n    const tokenValiditySeconds = exp - iat;\n    if (tokenValiditySeconds <= 2) {\n      this.logger.error(\n        \"Auth token does not live long enough, cannot refetch the token\"\n      );\n      return;\n    }\n    let delay = Math.min(\n      MAXIMUM_REFRESH_DELAY,\n      (tokenValiditySeconds - this.refreshTokenLeewaySeconds) * 1e3\n    );\n    if (delay <= 0) {\n      this.logger.warn(\n        `Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${tokenValiditySeconds}s`\n      );\n      delay = 0;\n    }\n    const refetchTokenTimeoutId = setTimeout(() => {\n      this._logVerbose(\"running scheduled token refetch\");\n      void this.refetchToken();\n    }, delay);\n    this.setAuthState({\n      state: \"waitingForScheduledRefetch\",\n      refetchTokenTimeoutId,\n      config: this.authState.config\n    });\n    this._logVerbose(\n      `scheduled preemptive auth token refetching in ${delay}ms`\n    );\n  }\n  // Protects against simultaneous calls to `setConfig`\n  // while we're fetching a token\n  async fetchTokenAndGuardAgainstRace(fetchToken, fetchArgs) {\n    const originalConfigVersion = ++this.configVersion;\n    this._logVerbose(\n      `fetching token with config version ${originalConfigVersion}`\n    );\n    const token = await fetchToken(fetchArgs);\n    if (this.configVersion !== originalConfigVersion) {\n      this._logVerbose(\n        `stale config version, expected ${originalConfigVersion}, got ${this.configVersion}`\n      );\n      return { isFromOutdatedConfig: true };\n    }\n    return { isFromOutdatedConfig: false, value: token };\n  }\n  stop() {\n    this.resetAuthState();\n    this.configVersion++;\n    this._logVerbose(`config version bumped to ${this.configVersion}`);\n  }\n  setAndReportAuthFailed(onAuthChange) {\n    onAuthChange(false);\n    this.resetAuthState();\n  }\n  resetAuthState() {\n    this.setAuthState({ state: \"noAuth\" });\n  }\n  setAuthState(newAuth) {\n    const authStateForLog = newAuth.state === \"waitingForServerConfirmationOfFreshToken\" ? {\n      hadAuth: newAuth.hadAuth,\n      state: newAuth.state,\n      token: `...${newAuth.token.slice(-7)}`\n    } : { state: newAuth.state };\n    this._logVerbose(\n      `setting auth state to ${JSON.stringify(authStateForLog)}`\n    );\n    switch (newAuth.state) {\n      case \"waitingForScheduledRefetch\":\n      case \"notRefetching\":\n      case \"noAuth\":\n        this.tokenConfirmationAttempts = 0;\n        break;\n      case \"waitingForServerConfirmationOfFreshToken\":\n      case \"waitingForServerConfirmationOfCachedToken\":\n      case \"initialRefetch\":\n        break;\n      default: {\n        newAuth;\n      }\n    }\n    if (this.authState.state === \"waitingForScheduledRefetch\") {\n      clearTimeout(this.authState.refetchTokenTimeoutId);\n      this.syncState.markAuthCompletion();\n    }\n    this.authState = newAuth;\n  }\n  decodeToken(token) {\n    try {\n      return jwtDecode(token);\n    } catch (e) {\n      this._logVerbose(\n        `Error decoding token: ${e instanceof Error ? e.message : \"Unknown error\"}`\n      );\n      return null;\n    }\n  }\n  _logVerbose(message) {\n    this.logger.logVerbose(`${message} [v${this.configVersion}]`);\n  }\n}\n//# sourceMappingURL=authentication_manager.js.map\n","\"use strict\";\nconst markNames = [\n  \"convexClientConstructed\",\n  \"convexWebSocketOpen\",\n  \"convexFirstMessageReceived\"\n];\nexport function mark(name, sessionId) {\n  const detail = { sessionId };\n  if (typeof performance === \"undefined\" || !performance.mark) return;\n  performance.mark(name, { detail });\n}\nfunction performanceMarkToJson(mark2) {\n  let name = mark2.name.slice(\"convex\".length);\n  name = name.charAt(0).toLowerCase() + name.slice(1);\n  return {\n    name,\n    startTime: mark2.startTime\n  };\n}\nexport function getMarksReport(sessionId) {\n  if (typeof performance === \"undefined\" || !performance.getEntriesByName) {\n    return [];\n  }\n  const allMarks = [];\n  for (const name of markNames) {\n    const marks = performance.getEntriesByName(name).filter((entry) => entry.entryType === \"mark\").filter((mark2) => mark2.detail.sessionId === sessionId);\n    allMarks.push(...marks);\n  }\n  return allMarks.map(performanceMarkToJson);\n}\n//# sourceMappingURL=metrics.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { version } from \"../../index.js\";\nimport { convexToJson } from \"../../values/index.js\";\nimport {\n  createHybridErrorStacktrace,\n  forwardData,\n  instantiateDefaultLogger,\n  instantiateNoopLogger,\n  logFatalError\n} from \"../logging.js\";\nimport { LocalSyncState } from \"./local_state.js\";\nimport { RequestManager } from \"./request_manager.js\";\nimport {\n  OptimisticQueryResults\n} from \"./optimistic_updates_impl.js\";\nimport { RemoteQuerySet } from \"./remote_query_set.js\";\nimport { serializePathAndArgs } from \"./udf_path_utils.js\";\nimport { WebSocketManager } from \"./web_socket_manager.js\";\nimport { newSessionId } from \"./session.js\";\nimport {\n  AuthenticationManager\n} from \"./authentication_manager.js\";\nimport { getMarksReport, mark } from \"./metrics.js\";\nimport { parseArgs, validateDeploymentUrl } from \"../../common/index.js\";\nimport { ConvexError } from \"../../values/errors.js\";\nimport { jwtDecode } from \"../../vendor/jwt-decode/index.js\";\nexport class BaseConvexClient {\n  /**\n   * @param address - The url of your Convex deployment, often provided\n   * by an environment variable. E.g. `https://small-mouse-123.convex.cloud`.\n   * @param onTransition - A callback receiving an array of query tokens\n   * corresponding to query results that have changed -- additional handlers\n   * can be added via `addOnTransitionHandler`.\n   * @param options - See {@link BaseConvexClientOptions} for a full description.\n   */\n  constructor(address, onTransition, options) {\n    __publicField(this, \"address\");\n    __publicField(this, \"state\");\n    __publicField(this, \"requestManager\");\n    __publicField(this, \"webSocketManager\");\n    __publicField(this, \"authenticationManager\");\n    __publicField(this, \"remoteQuerySet\");\n    __publicField(this, \"optimisticQueryResults\");\n    __publicField(this, \"_transitionHandlerCounter\", 0);\n    __publicField(this, \"_nextRequestId\");\n    __publicField(this, \"_onTransitionFns\", /* @__PURE__ */ new Map());\n    __publicField(this, \"_sessionId\");\n    __publicField(this, \"firstMessageReceived\", false);\n    __publicField(this, \"debug\");\n    __publicField(this, \"logger\");\n    __publicField(this, \"maxObservedTimestamp\");\n    __publicField(this, \"connectionStateSubscribers\", /* @__PURE__ */ new Map());\n    __publicField(this, \"nextConnectionStateSubscriberId\", 0);\n    __publicField(this, \"_lastPublishedConnectionState\");\n    /**\n     * Call this whenever the connection state may have changed in a way that could\n     * require publishing it. Schedules a possibly update.\n     */\n    __publicField(this, \"markConnectionStateDirty\", () => {\n      void Promise.resolve().then(() => {\n        const curConnectionState = this.connectionState();\n        if (JSON.stringify(curConnectionState) !== JSON.stringify(this._lastPublishedConnectionState)) {\n          this._lastPublishedConnectionState = curConnectionState;\n          for (const cb of this.connectionStateSubscribers.values()) {\n            cb(curConnectionState);\n          }\n        }\n      });\n    });\n    // Instance property so that `mark()` doesn't need to be called as a method.\n    __publicField(this, \"mark\", (name) => {\n      if (this.debug) {\n        mark(name, this.sessionId);\n      }\n    });\n    if (typeof address === \"object\") {\n      throw new Error(\n        \"Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.\"\n      );\n    }\n    if (options?.skipConvexDeploymentUrlCheck !== true) {\n      validateDeploymentUrl(address);\n    }\n    options = { ...options };\n    const authRefreshTokenLeewaySeconds = options.authRefreshTokenLeewaySeconds ?? 2;\n    let webSocketConstructor = options.webSocketConstructor;\n    if (!webSocketConstructor && typeof WebSocket === \"undefined\") {\n      throw new Error(\n        \"No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient\"\n      );\n    }\n    webSocketConstructor = webSocketConstructor || WebSocket;\n    this.debug = options.reportDebugInfoToConvex ?? false;\n    this.address = address;\n    this.logger = options.logger === false ? instantiateNoopLogger({ verbose: options.verbose ?? false }) : options.logger !== true && options.logger ? options.logger : instantiateDefaultLogger({ verbose: options.verbose ?? false });\n    const i = address.search(\"://\");\n    if (i === -1) {\n      throw new Error(\"Provided address was not an absolute URL.\");\n    }\n    const origin = address.substring(i + 3);\n    const protocol = address.substring(0, i);\n    let wsProtocol;\n    if (protocol === \"http\") {\n      wsProtocol = \"ws\";\n    } else if (protocol === \"https\") {\n      wsProtocol = \"wss\";\n    } else {\n      throw new Error(`Unknown parent protocol ${protocol}`);\n    }\n    const wsUri = `${wsProtocol}://${origin}/api/${version}/sync`;\n    this.state = new LocalSyncState();\n    this.remoteQuerySet = new RemoteQuerySet(\n      (queryId) => this.state.queryPath(queryId),\n      this.logger\n    );\n    this.requestManager = new RequestManager(\n      this.logger,\n      this.markConnectionStateDirty\n    );\n    const pauseSocket = () => {\n      this.webSocketManager.pause();\n      this.state.pause();\n    };\n    this.authenticationManager = new AuthenticationManager(\n      this.state,\n      {\n        authenticate: (token) => {\n          const message = this.state.setAuth(token);\n          this.webSocketManager.sendMessage(message);\n          return message.baseVersion;\n        },\n        stopSocket: () => this.webSocketManager.stop(),\n        tryRestartSocket: () => this.webSocketManager.tryRestart(),\n        pauseSocket,\n        resumeSocket: () => this.webSocketManager.resume(),\n        clearAuth: () => {\n          this.clearAuth();\n        }\n      },\n      {\n        logger: this.logger,\n        refreshTokenLeewaySeconds: authRefreshTokenLeewaySeconds\n      }\n    );\n    this.optimisticQueryResults = new OptimisticQueryResults();\n    this.addOnTransitionHandler((transition) => {\n      onTransition(transition.queries.map((q) => q.token));\n    });\n    this._nextRequestId = 0;\n    this._sessionId = newSessionId();\n    const { unsavedChangesWarning } = options;\n    if (typeof window === \"undefined\" || typeof window.addEventListener === \"undefined\") {\n      if (unsavedChangesWarning === true) {\n        throw new Error(\n          \"unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.\"\n        );\n      }\n    } else if (unsavedChangesWarning !== false) {\n      window.addEventListener(\"beforeunload\", (e) => {\n        if (this.requestManager.hasIncompleteRequests()) {\n          e.preventDefault();\n          const confirmationMessage = \"Are you sure you want to leave? Your changes may not be saved.\";\n          (e || window.event).returnValue = confirmationMessage;\n          return confirmationMessage;\n        }\n      });\n    }\n    this.webSocketManager = new WebSocketManager(\n      wsUri,\n      {\n        onOpen: (reconnectMetadata) => {\n          this.mark(\"convexWebSocketOpen\");\n          this.webSocketManager.sendMessage({\n            ...reconnectMetadata,\n            type: \"Connect\",\n            sessionId: this._sessionId,\n            maxObservedTimestamp: this.maxObservedTimestamp\n          });\n          const oldRemoteQueryResults = new Set(\n            this.remoteQuerySet.remoteQueryResults().keys()\n          );\n          this.remoteQuerySet = new RemoteQuerySet(\n            (queryId) => this.state.queryPath(queryId),\n            this.logger\n          );\n          const [querySetModification, authModification] = this.state.restart(\n            oldRemoteQueryResults\n          );\n          if (authModification) {\n            this.webSocketManager.sendMessage(authModification);\n          }\n          this.webSocketManager.sendMessage(querySetModification);\n          for (const message of this.requestManager.restart()) {\n            this.webSocketManager.sendMessage(message);\n          }\n        },\n        onResume: () => {\n          const [querySetModification, authModification] = this.state.resume();\n          if (authModification) {\n            this.webSocketManager.sendMessage(authModification);\n          }\n          if (querySetModification) {\n            this.webSocketManager.sendMessage(querySetModification);\n          }\n          for (const message of this.requestManager.resume()) {\n            this.webSocketManager.sendMessage(message);\n          }\n        },\n        onMessage: (serverMessage) => {\n          if (!this.firstMessageReceived) {\n            this.firstMessageReceived = true;\n            this.mark(\"convexFirstMessageReceived\");\n            this.reportMarks();\n          }\n          switch (serverMessage.type) {\n            case \"Transition\": {\n              this.observedTimestamp(serverMessage.endVersion.ts);\n              this.authenticationManager.onTransition(serverMessage);\n              this.remoteQuerySet.transition(serverMessage);\n              this.state.transition(serverMessage);\n              const completedRequests = this.requestManager.removeCompleted(\n                this.remoteQuerySet.timestamp()\n              );\n              this.notifyOnQueryResultChanges(completedRequests);\n              break;\n            }\n            case \"MutationResponse\": {\n              if (serverMessage.success) {\n                this.observedTimestamp(serverMessage.ts);\n              }\n              const completedMutationInfo = this.requestManager.onResponse(serverMessage);\n              if (completedMutationInfo !== null) {\n                this.notifyOnQueryResultChanges(\n                  /* @__PURE__ */ new Map([\n                    [\n                      completedMutationInfo.requestId,\n                      completedMutationInfo.result\n                    ]\n                  ])\n                );\n              }\n              break;\n            }\n            case \"ActionResponse\": {\n              this.requestManager.onResponse(serverMessage);\n              break;\n            }\n            case \"AuthError\": {\n              this.authenticationManager.onAuthError(serverMessage);\n              break;\n            }\n            case \"FatalError\": {\n              const error = logFatalError(this.logger, serverMessage.error);\n              void this.webSocketManager.terminate();\n              throw error;\n            }\n            default: {\n              serverMessage;\n            }\n          }\n          return {\n            hasSyncedPastLastReconnect: this.hasSyncedPastLastReconnect()\n          };\n        },\n        onServerDisconnectError: options.onServerDisconnectError\n      },\n      webSocketConstructor,\n      this.logger,\n      this.markConnectionStateDirty,\n      this.debug\n    );\n    this.mark(\"convexClientConstructed\");\n    if (options.expectAuth) {\n      pauseSocket();\n    }\n  }\n  /**\n   * Return true if there is outstanding work from prior to the time of the most recent restart.\n   * This indicates that the client has not proven itself to have gotten past the issue that\n   * potentially led to the restart. Use this to influence when to reset backoff after a failure.\n   */\n  hasSyncedPastLastReconnect() {\n    const hasSyncedPastLastReconnect = this.requestManager.hasSyncedPastLastReconnect() || this.state.hasSyncedPastLastReconnect();\n    return hasSyncedPastLastReconnect;\n  }\n  observedTimestamp(observedTs) {\n    if (this.maxObservedTimestamp === void 0 || this.maxObservedTimestamp.lessThanOrEqual(observedTs)) {\n      this.maxObservedTimestamp = observedTs;\n    }\n  }\n  getMaxObservedTimestamp() {\n    return this.maxObservedTimestamp;\n  }\n  /**\n   * Compute the current query results based on the remoteQuerySet and the\n   * current optimistic updates and call `onTransition` for all the changed\n   * queries.\n   *\n   * @param completedMutations - A set of mutation IDs whose optimistic updates\n   * are no longer needed.\n   */\n  notifyOnQueryResultChanges(completedRequests) {\n    const remoteQueryResults = this.remoteQuerySet.remoteQueryResults();\n    const queryTokenToValue = /* @__PURE__ */ new Map();\n    for (const [queryId, result] of remoteQueryResults) {\n      const queryToken = this.state.queryToken(queryId);\n      if (queryToken !== null) {\n        const query = {\n          result,\n          udfPath: this.state.queryPath(queryId),\n          args: this.state.queryArgs(queryId)\n        };\n        queryTokenToValue.set(queryToken, query);\n      }\n    }\n    const changedQueryTokens = this.optimisticQueryResults.ingestQueryResultsFromServer(\n      queryTokenToValue,\n      new Set(completedRequests.keys())\n    );\n    this.handleTransition({\n      queries: changedQueryTokens.map((token) => {\n        const optimisticResult = this.optimisticQueryResults.rawQueryResult(token);\n        return {\n          token,\n          modification: {\n            kind: \"Updated\",\n            result: optimisticResult\n          }\n        };\n      }),\n      reflectedMutations: Array.from(completedRequests).map(\n        ([requestId, result]) => ({\n          requestId,\n          result\n        })\n      ),\n      timestamp: this.remoteQuerySet.timestamp()\n    });\n  }\n  handleTransition(transition) {\n    for (const fn of this._onTransitionFns.values()) {\n      fn(transition);\n    }\n  }\n  /**\n   * Add a handler that will be called on a transition.\n   *\n   * Any external side effects (e.g. setting React state) should be handled here.\n   *\n   * @param fn\n   *\n   * @returns\n   */\n  addOnTransitionHandler(fn) {\n    const id = this._transitionHandlerCounter++;\n    this._onTransitionFns.set(id, fn);\n    return () => this._onTransitionFns.delete(id);\n  }\n  /**\n   * Get the current JWT auth token and decoded claims.\n   */\n  getCurrentAuthClaims() {\n    const authToken = this.state.getAuth();\n    let decoded = {};\n    if (authToken && authToken.tokenType === \"User\") {\n      try {\n        decoded = authToken ? jwtDecode(authToken.value) : {};\n      } catch {\n        decoded = {};\n      }\n    } else {\n      return void 0;\n    }\n    return { token: authToken.value, decoded };\n  }\n  /**\n   * Set the authentication token to be used for subsequent queries and mutations.\n   * `fetchToken` will be called automatically again if a token expires.\n   * `fetchToken` should return `null` if the token cannot be retrieved, for example\n   * when the user's rights were permanently revoked.\n   * @param fetchToken - an async function returning the JWT-encoded OpenID Connect Identity Token\n   * @param onChange - a callback that will be called when the authentication status changes\n   */\n  setAuth(fetchToken, onChange) {\n    void this.authenticationManager.setConfig(fetchToken, onChange);\n  }\n  hasAuth() {\n    return this.state.hasAuth();\n  }\n  /** @internal */\n  setAdminAuth(value, fakeUserIdentity) {\n    const message = this.state.setAdminAuth(value, fakeUserIdentity);\n    this.webSocketManager.sendMessage(message);\n  }\n  clearAuth() {\n    const message = this.state.clearAuth();\n    this.webSocketManager.sendMessage(message);\n  }\n  /**\n     * Subscribe to a query function.\n     *\n     * Whenever this query's result changes, the `onTransition` callback\n     * passed into the constructor will be called.\n     *\n     * @param name - The name of the query.\n     * @param args - An arguments object for the query. If this is omitted, the\n     * arguments will be `{}`.\n     * @param options - A {@link SubscribeOptions} options object for this query.\n  \n     * @returns An object containing a {@link QueryToken} corresponding to this\n     * query and an `unsubscribe` callback.\n     */\n  subscribe(name, args, options) {\n    const argsObject = parseArgs(args);\n    const { modification, queryToken, unsubscribe } = this.state.subscribe(\n      name,\n      argsObject,\n      options?.journal,\n      options?.componentPath\n    );\n    if (modification !== null) {\n      this.webSocketManager.sendMessage(modification);\n    }\n    return {\n      queryToken,\n      unsubscribe: () => {\n        const modification2 = unsubscribe();\n        if (modification2) {\n          this.webSocketManager.sendMessage(modification2);\n        }\n      }\n    };\n  }\n  /**\n   * A query result based only on the current, local state.\n   *\n   * The only way this will return a value is if we're already subscribed to the\n   * query or its value has been set optimistically.\n   */\n  localQueryResult(udfPath, args) {\n    const argsObject = parseArgs(args);\n    const queryToken = serializePathAndArgs(udfPath, argsObject);\n    return this.optimisticQueryResults.queryResult(queryToken);\n  }\n  /**\n   * Get query result by query token based on current, local state\n   *\n   * The only way this will return a value is if we're already subscribed to the\n   * query or its value has been set optimistically.\n   *\n   * @internal\n   */\n  localQueryResultByToken(queryToken) {\n    return this.optimisticQueryResults.queryResult(queryToken);\n  }\n  /**\n   * Whether local query result is available for a token.\n   *\n   * This method does not throw if the result is an error.\n   *\n   * @internal\n   */\n  hasLocalQueryResultByToken(queryToken) {\n    return this.optimisticQueryResults.hasQueryResult(queryToken);\n  }\n  /**\n   * @internal\n   */\n  localQueryLogs(udfPath, args) {\n    const argsObject = parseArgs(args);\n    const queryToken = serializePathAndArgs(udfPath, argsObject);\n    return this.optimisticQueryResults.queryLogs(queryToken);\n  }\n  /**\n   * Retrieve the current {@link QueryJournal} for this query function.\n   *\n   * If we have not yet received a result for this query, this will be `undefined`.\n   *\n   * @param name - The name of the query.\n   * @param args - The arguments object for this query.\n   * @returns The query's {@link QueryJournal} or `undefined`.\n   */\n  queryJournal(name, args) {\n    const argsObject = parseArgs(args);\n    const queryToken = serializePathAndArgs(name, argsObject);\n    return this.state.queryJournal(queryToken);\n  }\n  /**\n   * Get the current {@link ConnectionState} between the client and the Convex\n   * backend.\n   *\n   * @returns The {@link ConnectionState} with the Convex backend.\n   */\n  connectionState() {\n    const wsConnectionState = this.webSocketManager.connectionState();\n    return {\n      hasInflightRequests: this.requestManager.hasInflightRequests(),\n      isWebSocketConnected: wsConnectionState.isConnected,\n      hasEverConnected: wsConnectionState.hasEverConnected,\n      connectionCount: wsConnectionState.connectionCount,\n      connectionRetries: wsConnectionState.connectionRetries,\n      timeOfOldestInflightRequest: this.requestManager.timeOfOldestInflightRequest(),\n      inflightMutations: this.requestManager.inflightMutations(),\n      inflightActions: this.requestManager.inflightActions()\n    };\n  }\n  /**\n   * Subscribe to the {@link ConnectionState} between the client and the Convex\n   * backend, calling a callback each time it changes.\n   *\n   * Subscribed callbacks will be called when any part of ConnectionState changes.\n   * ConnectionState may grow in future versions (e.g. to provide a array of\n   * inflight requests) in which case callbacks would be called more frequently.\n   *\n   * @returns An unsubscribe function to stop listening.\n   */\n  subscribeToConnectionState(cb) {\n    const id = this.nextConnectionStateSubscriberId++;\n    this.connectionStateSubscribers.set(id, cb);\n    return () => {\n      this.connectionStateSubscribers.delete(id);\n    };\n  }\n  /**\n     * Execute a mutation function.\n     *\n     * @param name - The name of the mutation.\n     * @param args - An arguments object for the mutation. If this is omitted,\n     * the arguments will be `{}`.\n     * @param options - A {@link MutationOptions} options object for this mutation.\n  \n     * @returns - A promise of the mutation's result.\n     */\n  async mutation(name, args, options) {\n    const result = await this.mutationInternal(name, args, options);\n    if (!result.success) {\n      if (result.errorData !== void 0) {\n        throw forwardData(\n          result,\n          new ConvexError(\n            createHybridErrorStacktrace(\"mutation\", name, result)\n          )\n        );\n      }\n      throw new Error(createHybridErrorStacktrace(\"mutation\", name, result));\n    }\n    return result.value;\n  }\n  /**\n   * @internal\n   */\n  async mutationInternal(udfPath, args, options, componentPath) {\n    const { mutationPromise } = this.enqueueMutation(\n      udfPath,\n      args,\n      options,\n      componentPath\n    );\n    return mutationPromise;\n  }\n  /**\n   * @internal\n   */\n  enqueueMutation(udfPath, args, options, componentPath) {\n    const mutationArgs = parseArgs(args);\n    this.tryReportLongDisconnect();\n    const requestId = this.nextRequestId;\n    this._nextRequestId++;\n    if (options !== void 0) {\n      const optimisticUpdate = options.optimisticUpdate;\n      if (optimisticUpdate !== void 0) {\n        const wrappedUpdate = (localQueryStore) => {\n          const result = optimisticUpdate(\n            localQueryStore,\n            mutationArgs\n          );\n          if (result instanceof Promise) {\n            this.logger.warn(\n              \"Optimistic update handler returned a Promise. Optimistic updates should be synchronous.\"\n            );\n          }\n        };\n        const changedQueryTokens = this.optimisticQueryResults.applyOptimisticUpdate(\n          wrappedUpdate,\n          requestId\n        );\n        const changedQueries = changedQueryTokens.map((token) => {\n          const localResult = this.localQueryResultByToken(token);\n          return {\n            token,\n            modification: {\n              kind: \"Updated\",\n              result: localResult === void 0 ? void 0 : {\n                success: true,\n                value: localResult,\n                logLines: []\n              }\n            }\n          };\n        });\n        this.handleTransition({\n          queries: changedQueries,\n          reflectedMutations: [],\n          timestamp: this.remoteQuerySet.timestamp()\n        });\n      }\n    }\n    const message = {\n      type: \"Mutation\",\n      requestId,\n      udfPath,\n      componentPath,\n      args: [convexToJson(mutationArgs)]\n    };\n    const mightBeSent = this.webSocketManager.sendMessage(message);\n    const mutationPromise = this.requestManager.request(message, mightBeSent);\n    return {\n      requestId,\n      mutationPromise\n    };\n  }\n  /**\n   * Execute an action function.\n   *\n   * @param name - The name of the action.\n   * @param args - An arguments object for the action. If this is omitted,\n   * the arguments will be `{}`.\n   * @returns A promise of the action's result.\n   */\n  async action(name, args) {\n    const result = await this.actionInternal(name, args);\n    if (!result.success) {\n      if (result.errorData !== void 0) {\n        throw forwardData(\n          result,\n          new ConvexError(createHybridErrorStacktrace(\"action\", name, result))\n        );\n      }\n      throw new Error(createHybridErrorStacktrace(\"action\", name, result));\n    }\n    return result.value;\n  }\n  /**\n   * @internal\n   */\n  async actionInternal(udfPath, args, componentPath) {\n    const actionArgs = parseArgs(args);\n    const requestId = this.nextRequestId;\n    this._nextRequestId++;\n    this.tryReportLongDisconnect();\n    const message = {\n      type: \"Action\",\n      requestId,\n      udfPath,\n      componentPath,\n      args: [convexToJson(actionArgs)]\n    };\n    const mightBeSent = this.webSocketManager.sendMessage(message);\n    return this.requestManager.request(message, mightBeSent);\n  }\n  /**\n   * Close any network handles associated with this client and stop all subscriptions.\n   *\n   * Call this method when you're done with an {@link BaseConvexClient} to\n   * dispose of its sockets and resources.\n   *\n   * @returns A `Promise` fulfilled when the connection has been completely closed.\n   */\n  async close() {\n    this.authenticationManager.stop();\n    return this.webSocketManager.terminate();\n  }\n  /**\n   * Return the address for this client, useful for creating a new client.\n   *\n   * Not guaranteed to match the address with which this client was constructed:\n   * it may be canonicalized.\n   */\n  get url() {\n    return this.address;\n  }\n  /**\n   * @internal\n   */\n  get nextRequestId() {\n    return this._nextRequestId;\n  }\n  /**\n   * @internal\n   */\n  get sessionId() {\n    return this._sessionId;\n  }\n  /**\n   * Reports performance marks to the server. This should only be called when\n   * we have a functional websocket.\n   */\n  reportMarks() {\n    if (this.debug) {\n      const report = getMarksReport(this.sessionId);\n      this.webSocketManager.sendMessage({\n        type: \"Event\",\n        eventType: \"ClientConnect\",\n        event: report\n      });\n    }\n  }\n  tryReportLongDisconnect() {\n    if (!this.debug) {\n      return;\n    }\n    const timeOfOldestRequest = this.connectionState().timeOfOldestInflightRequest;\n    if (timeOfOldestRequest === null || Date.now() - timeOfOldestRequest.getTime() <= 60 * 1e3) {\n      return;\n    }\n    const endpoint = `${this.address}/api/debug_event`;\n    fetch(endpoint, {\n      method: \"POST\",\n      headers: {\n        \"Content-Type\": \"application/json\",\n        \"Convex-Client\": `npm-${version}`\n      },\n      body: JSON.stringify({ event: \"LongWebsocketDisconnect\" })\n    }).then((response) => {\n      if (!response.ok) {\n        this.logger.warn(\n          \"Analytics request failed with response:\",\n          response.body\n        );\n      }\n    }).catch((error) => {\n      this.logger.warn(\"Analytics response failed with error:\", error);\n    });\n  }\n}\n//# sourceMappingURL=client.js.map\n","\"use strict\";\nexport function asPaginationArgs(value) {\n  if (typeof value.paginationOpts.numItems !== \"number\") {\n    throw new Error(`Not valid paginated query args: ${JSON.stringify(value)}`);\n  }\n  return value;\n}\nexport function asPaginationResult(value) {\n  if (typeof value !== \"object\" || value === null || !Array.isArray(value.page) || typeof value.isDone !== \"boolean\" || typeof value.continueCursor !== \"string\") {\n    throw new Error(`Not a valid paginated query result: ${value?.toString()}`);\n  }\n  return value;\n}\n//# sourceMappingURL=pagination.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport {\n  serializePaginatedPathAndArgs,\n  canonicalizeUdfPath\n} from \"./udf_path_utils.js\";\nimport {\n  asPaginationResult\n} from \"./pagination.js\";\nimport { Long } from \"../../vendor/long.js\";\nexport class PaginatedQueryClient {\n  constructor(client, onTransition) {\n    this.client = client;\n    this.onTransition = onTransition;\n    __publicField(this, \"paginatedQuerySet\", /* @__PURE__ */ new Map());\n    // hold onto a real Transition so we can construct synthetic ones with that timestamp\n    __publicField(this, \"lastTransitionTs\");\n    this.lastTransitionTs = Long.fromNumber(0);\n    this.client.addOnTransitionHandler(\n      (transition) => this.onBaseTransition(transition)\n    );\n  }\n  /**\n   * Subscribe to a paginated query.\n   *\n   * @param name - The name of the paginated query function\n   * @param args - Arguments for the query (excluding paginationOpts)\n   * @param options - Pagination options including initialNumItems\n   * @returns Object with paginatedQueryToken and unsubscribe function\n   */\n  subscribe(name, args, options) {\n    const canonicalizedUdfPath = canonicalizeUdfPath(name);\n    const token = serializePaginatedPathAndArgs(\n      canonicalizedUdfPath,\n      args,\n      options\n    );\n    const unsubscribe = () => this.removePaginatedQuerySubscriber(token);\n    const existingEntry = this.paginatedQuerySet.get(token);\n    if (existingEntry) {\n      existingEntry.numSubscribers += 1;\n      return {\n        paginatedQueryToken: token,\n        unsubscribe\n      };\n    }\n    this.paginatedQuerySet.set(token, {\n      token,\n      canonicalizedUdfPath,\n      args,\n      numSubscribers: 1,\n      options: { initialNumItems: options.initialNumItems },\n      nextPageKey: 0,\n      pageKeys: [],\n      pageKeyToQuery: /* @__PURE__ */ new Map(),\n      ongoingSplits: /* @__PURE__ */ new Map(),\n      skip: false,\n      id: options.id\n    });\n    this.addPageToPaginatedQuery(token, null, options.initialNumItems);\n    return {\n      paginatedQueryToken: token,\n      unsubscribe\n    };\n  }\n  /**\n   * Get current results for a paginated query based on local state.\n   *\n   * Throws an error when one of the pages has errored.\n   */\n  localQueryResult(name, args, options) {\n    const canonicalizedUdfPath = canonicalizeUdfPath(name);\n    const token = serializePaginatedPathAndArgs(\n      canonicalizedUdfPath,\n      args,\n      options\n    );\n    return this.localQueryResultByToken(token);\n  }\n  /**\n   * @internal\n   */\n  localQueryResultByToken(token) {\n    const paginatedQuery = this.paginatedQuerySet.get(token);\n    if (!paginatedQuery) {\n      return void 0;\n    }\n    const activePages = this.activePageQueryTokens(paginatedQuery);\n    if (activePages.length === 0) {\n      return {\n        results: [],\n        status: \"LoadingFirstPage\",\n        loadMore: (numItems) => {\n          return this.loadMoreOfPaginatedQuery(token, numItems);\n        }\n      };\n    }\n    let allResults = [];\n    let hasUndefined = false;\n    let isDone = false;\n    for (const pageToken of activePages) {\n      const result = this.client.localQueryResultByToken(pageToken);\n      if (result === void 0) {\n        hasUndefined = true;\n        isDone = false;\n        continue;\n      }\n      const paginationResult = asPaginationResult(result);\n      allResults = allResults.concat(paginationResult.page);\n      isDone = !!paginationResult.isDone;\n    }\n    let status;\n    if (hasUndefined) {\n      status = allResults.length === 0 ? \"LoadingFirstPage\" : \"LoadingMore\";\n    } else if (isDone) {\n      status = \"Exhausted\";\n    } else {\n      status = \"CanLoadMore\";\n    }\n    return {\n      results: allResults,\n      status,\n      loadMore: (numItems) => {\n        return this.loadMoreOfPaginatedQuery(token, numItems);\n      }\n    };\n  }\n  onBaseTransition(transition) {\n    const changedBaseTokens = transition.queries.map((q) => q.token);\n    const changed = this.queriesContainingTokens(changedBaseTokens);\n    let paginatedQueries = [];\n    if (changed.length > 0) {\n      this.processPaginatedQuerySplits(\n        changed,\n        (token) => this.client.localQueryResultByToken(token)\n      );\n      paginatedQueries = changed.map((token) => ({\n        token,\n        modification: {\n          kind: \"Updated\",\n          result: this.localQueryResultByToken(token)\n        }\n      }));\n    }\n    const extendedTransition = {\n      ...transition,\n      paginatedQueries\n    };\n    this.onTransition(extendedTransition);\n  }\n  /**\n   * Load more items for a paginated query.\n   *\n   * This *always* causes a transition, the status of the query\n   * has probably changed from \"CanLoadMore\" to \"LoadingMore\".\n   * Data might have changed too: maybe a subscription to this page\n   * query already exists (unlikely but possible) or this page query\n   * has an optimistic update providing some initial data.\n   *\n   * @internal\n   */\n  loadMoreOfPaginatedQuery(token, numItems) {\n    this.mustGetPaginatedQuery(token);\n    const lastPageToken = this.queryTokenForLastPageOfPaginatedQuery(token);\n    const lastPageResult = this.client.localQueryResultByToken(lastPageToken);\n    if (!lastPageResult) {\n      return false;\n    }\n    const paginationResult = asPaginationResult(lastPageResult);\n    if (paginationResult.isDone) {\n      return false;\n    }\n    this.addPageToPaginatedQuery(\n      token,\n      paginationResult.continueCursor,\n      numItems\n    );\n    const loadMoreTransition = {\n      timestamp: this.lastTransitionTs,\n      reflectedMutations: [],\n      queries: [],\n      paginatedQueries: [\n        {\n          token,\n          modification: {\n            kind: \"Updated\",\n            result: this.localQueryResultByToken(token)\n          }\n        }\n      ]\n    };\n    this.onTransition(loadMoreTransition);\n    return true;\n  }\n  /**\n   * @internal\n   */\n  queriesContainingTokens(queryTokens) {\n    if (queryTokens.length === 0) {\n      return [];\n    }\n    const changed = [];\n    const queryTokenSet = new Set(queryTokens);\n    for (const [paginatedToken, paginatedQuery] of this.paginatedQuerySet) {\n      for (const pageToken of this.allQueryTokens(paginatedQuery)) {\n        if (queryTokenSet.has(pageToken)) {\n          changed.push(paginatedToken);\n          break;\n        }\n      }\n    }\n    return changed;\n  }\n  /**\n   * @internal\n   */\n  processPaginatedQuerySplits(changed, getResult) {\n    for (const paginatedQueryToken of changed) {\n      const paginatedQuery = this.mustGetPaginatedQuery(paginatedQueryToken);\n      const { ongoingSplits, pageKeyToQuery, pageKeys } = paginatedQuery;\n      for (const [pageKey, [splitKey1, splitKey2]] of ongoingSplits) {\n        const bothNewPagesLoaded = getResult(pageKeyToQuery.get(splitKey1).queryToken) !== void 0 && getResult(pageKeyToQuery.get(splitKey2).queryToken) !== void 0;\n        if (bothNewPagesLoaded) {\n          this.completePaginatedQuerySplit(\n            paginatedQuery,\n            pageKey,\n            splitKey1,\n            splitKey2\n          );\n        }\n      }\n      for (const pageKey of pageKeys) {\n        if (ongoingSplits.has(pageKey)) {\n          continue;\n        }\n        const pageToken = pageKeyToQuery.get(pageKey).queryToken;\n        const pageResult = getResult(pageToken);\n        if (!pageResult) {\n          continue;\n        }\n        const result = asPaginationResult(pageResult);\n        const shouldSplit = result.splitCursor && (result.pageStatus === \"SplitRecommended\" || result.pageStatus === \"SplitRequired\" || // This client-driven page splitting condition will change in the future.\n        result.page.length > paginatedQuery.options.initialNumItems * 2);\n        if (shouldSplit) {\n          this.splitPaginatedQueryPage(\n            paginatedQuery,\n            pageKey,\n            result.splitCursor,\n            // we just checked\n            result.continueCursor\n          );\n        }\n      }\n    }\n  }\n  splitPaginatedQueryPage(paginatedQuery, pageKey, splitCursor, continueCursor) {\n    const splitKey1 = paginatedQuery.nextPageKey++;\n    const splitKey2 = paginatedQuery.nextPageKey++;\n    const paginationOpts = {\n      cursor: continueCursor,\n      numItems: paginatedQuery.options.initialNumItems,\n      id: paginatedQuery.id\n    };\n    const firstSubscription = this.client.subscribe(\n      paginatedQuery.canonicalizedUdfPath,\n      {\n        ...paginatedQuery.args,\n        paginationOpts: {\n          ...paginationOpts,\n          cursor: null,\n          // Start from beginning for first split\n          endCursor: splitCursor\n        }\n      }\n    );\n    paginatedQuery.pageKeyToQuery.set(splitKey1, firstSubscription);\n    const secondSubscription = this.client.subscribe(\n      paginatedQuery.canonicalizedUdfPath,\n      {\n        ...paginatedQuery.args,\n        paginationOpts: {\n          ...paginationOpts,\n          cursor: splitCursor,\n          endCursor: continueCursor\n        }\n      }\n    );\n    paginatedQuery.pageKeyToQuery.set(splitKey2, secondSubscription);\n    paginatedQuery.ongoingSplits.set(pageKey, [splitKey1, splitKey2]);\n  }\n  /**\n   * @internal\n   */\n  addPageToPaginatedQuery(token, continueCursor, numItems) {\n    const paginatedQuery = this.mustGetPaginatedQuery(token);\n    const pageKey = paginatedQuery.nextPageKey++;\n    const paginationOpts = {\n      cursor: continueCursor,\n      numItems,\n      id: paginatedQuery.id\n    };\n    const pageArgs = {\n      ...paginatedQuery.args,\n      paginationOpts\n    };\n    const subscription = this.client.subscribe(\n      paginatedQuery.canonicalizedUdfPath,\n      pageArgs\n    );\n    paginatedQuery.pageKeys.push(pageKey);\n    paginatedQuery.pageKeyToQuery.set(pageKey, subscription);\n    return subscription;\n  }\n  removePaginatedQuerySubscriber(token) {\n    const paginatedQuery = this.paginatedQuerySet.get(token);\n    if (!paginatedQuery) {\n      return;\n    }\n    paginatedQuery.numSubscribers -= 1;\n    if (paginatedQuery.numSubscribers > 0) {\n      return;\n    }\n    for (const subscription of paginatedQuery.pageKeyToQuery.values()) {\n      subscription.unsubscribe();\n    }\n    this.paginatedQuerySet.delete(token);\n  }\n  completePaginatedQuerySplit(paginatedQuery, pageKey, splitKey1, splitKey2) {\n    const originalQuery = paginatedQuery.pageKeyToQuery.get(pageKey);\n    paginatedQuery.pageKeyToQuery.delete(pageKey);\n    const pageIndex = paginatedQuery.pageKeys.indexOf(pageKey);\n    paginatedQuery.pageKeys.splice(pageIndex, 1, splitKey1, splitKey2);\n    paginatedQuery.ongoingSplits.delete(pageKey);\n    originalQuery.unsubscribe();\n  }\n  /** The query tokens for all active pages, in result order */\n  activePageQueryTokens(paginatedQuery) {\n    return paginatedQuery.pageKeys.map(\n      (pageKey) => paginatedQuery.pageKeyToQuery.get(pageKey).queryToken\n    );\n  }\n  allQueryTokens(paginatedQuery) {\n    return Array.from(paginatedQuery.pageKeyToQuery.values()).map(\n      (sub) => sub.queryToken\n    );\n  }\n  queryTokenForLastPageOfPaginatedQuery(token) {\n    const paginatedQuery = this.mustGetPaginatedQuery(token);\n    const lastPageKey = paginatedQuery.pageKeys[paginatedQuery.pageKeys.length - 1];\n    if (lastPageKey === void 0) {\n      throw new Error(`No pages for paginated query ${token}`);\n    }\n    return paginatedQuery.pageKeyToQuery.get(lastPageKey).queryToken;\n  }\n  mustGetPaginatedQuery(token) {\n    const paginatedQuery = this.paginatedQuerySet.get(token);\n    if (!paginatedQuery) {\n      throw new Error(\"paginated query no longer exists for token \" + token);\n    }\n    return paginatedQuery;\n  }\n}\n//# sourceMappingURL=paginated_query_client.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { validateDeploymentUrl } from \"../common/index.js\";\nimport {\n  BaseConvexClient\n} from \"./index.js\";\nimport { getFunctionName } from \"../server/api.js\";\nimport {\n  PaginatedQueryClient\n} from \"./sync/paginated_query_client.js\";\nimport { serializedQueryTokenIsPaginated } from \"./sync/udf_path_utils.js\";\nlet defaultWebSocketConstructor;\nexport function setDefaultWebSocketConstructor(ws) {\n  defaultWebSocketConstructor = ws;\n}\nexport class ConvexClient {\n  /**\n   * Construct a client and immediately initiate a WebSocket connection to the passed address.\n   *\n   * @public\n   */\n  constructor(address, options = {}) {\n    __publicField(this, \"listeners\");\n    __publicField(this, \"_client\");\n    __publicField(this, \"_paginatedClient\");\n    // A synthetic server event to run callbacks the first time\n    __publicField(this, \"callNewListenersWithCurrentValuesTimer\");\n    __publicField(this, \"_closed\");\n    __publicField(this, \"_disabled\");\n    if (options.skipConvexDeploymentUrlCheck !== true) {\n      validateDeploymentUrl(address);\n    }\n    const { disabled, ...baseOptions } = options;\n    this._closed = false;\n    this._disabled = !!disabled;\n    if (defaultWebSocketConstructor && !(\"webSocketConstructor\" in baseOptions) && typeof WebSocket === \"undefined\") {\n      baseOptions.webSocketConstructor = defaultWebSocketConstructor;\n    }\n    if (typeof window === \"undefined\" && !(\"unsavedChangesWarning\" in baseOptions)) {\n      baseOptions.unsavedChangesWarning = false;\n    }\n    if (!this.disabled) {\n      this._client = new BaseConvexClient(\n        address,\n        () => {\n        },\n        // NOP, let the paginated query client do it all\n        baseOptions\n      );\n      this._paginatedClient = new PaginatedQueryClient(\n        this._client,\n        (transition) => this._transition(transition)\n      );\n    }\n    this.listeners = /* @__PURE__ */ new Set();\n  }\n  /**\n   * Once closed no registered callbacks will fire again.\n   */\n  get closed() {\n    return this._closed;\n  }\n  get client() {\n    if (this._client) return this._client;\n    throw new Error(\"ConvexClient is disabled\");\n  }\n  /**\n   * @internal\n   */\n  get paginatedClient() {\n    if (this._paginatedClient) return this._paginatedClient;\n    throw new Error(\"ConvexClient is disabled\");\n  }\n  get disabled() {\n    return this._disabled;\n  }\n  /**\n   * Call a callback whenever a new result for a query is received. The callback\n   * will run soon after being registered if a result for the query is already\n   * in memory.\n   *\n   * The return value is an {@link Unsubscribe} object which is both a function\n   * an an object with properties. Both of the patterns below work with this object:\n   *\n   *```ts\n   * // call the return value as a function\n   * const unsubscribe = client.onUpdate(api.messages.list, {}, (messages) => {\n   *   console.log(messages);\n   * });\n   * unsubscribe();\n   *\n   * // unpack the return value into its properties\n   * const {\n   *   getCurrentValue,\n   *   unsubscribe,\n   * } = client.onUpdate(api.messages.list, {}, (messages) => {\n   *   console.log(messages);\n   * });\n   *```\n   *\n   * @param query - A {@link server.FunctionReference} for the public query to run.\n   * @param args - The arguments to run the query with.\n   * @param callback - Function to call when the query result updates.\n   * @param onError - Function to call when the query result updates with an error.\n   * If not provided, errors will be thrown instead of calling the callback.\n   *\n   * @return an {@link Unsubscribe} function to stop calling the onUpdate function.\n   */\n  onUpdate(query, args, callback, onError) {\n    if (this.disabled) {\n      return this.createDisabledUnsubscribe();\n    }\n    const { queryToken, unsubscribe } = this.client.subscribe(\n      getFunctionName(query),\n      args\n    );\n    const queryInfo = {\n      queryToken,\n      callback,\n      onError,\n      unsubscribe,\n      hasEverRun: false,\n      query,\n      args,\n      paginationOptions: void 0\n    };\n    this.listeners.add(queryInfo);\n    if (this.queryResultReady(queryToken) && this.callNewListenersWithCurrentValuesTimer === void 0) {\n      this.callNewListenersWithCurrentValuesTimer = setTimeout(\n        () => this.callNewListenersWithCurrentValues(),\n        0\n      );\n    }\n    const unsubscribeProps = {\n      unsubscribe: () => {\n        if (this.closed) {\n          return;\n        }\n        this.listeners.delete(queryInfo);\n        unsubscribe();\n      },\n      getCurrentValue: () => this.client.localQueryResultByToken(queryToken),\n      getQueryLogs: () => this.client.localQueryLogs(queryToken)\n    };\n    const ret = unsubscribeProps.unsubscribe;\n    Object.assign(ret, unsubscribeProps);\n    return ret;\n  }\n  /**\n   * Call a callback whenever a new result for a paginated query is received.\n   *\n   * This is an experimental preview: the final API may change.\n   * In particular, caching behavior, page splitting, and required paginated query options\n   * may change.\n   *\n   * @param query - A {@link server.FunctionReference} for the public query to run.\n   * @param args - The arguments to run the query with.\n   * @param options - Options for the paginated query including initialNumItems and id.\n   * @param callback - Function to call when the query result updates.\n   * @param onError - Function to call when the query result updates with an error.\n   *\n   * @return an {@link Unsubscribe} function to stop calling the callback.\n   */\n  onPaginatedUpdate_experimental(query, args, options, callback, onError) {\n    if (this.disabled) {\n      return this.createDisabledUnsubscribe();\n    }\n    const paginationOptions = {\n      initialNumItems: options.initialNumItems,\n      id: -1\n    };\n    const { paginatedQueryToken, unsubscribe } = this.paginatedClient.subscribe(\n      getFunctionName(query),\n      args,\n      // Simple client doesn't use IDs, there's no expectation that these queries remain separate.\n      paginationOptions\n    );\n    const queryInfo = {\n      queryToken: paginatedQueryToken,\n      callback,\n      onError,\n      unsubscribe,\n      hasEverRun: false,\n      query,\n      args,\n      paginationOptions\n    };\n    this.listeners.add(queryInfo);\n    if (!!this.paginatedClient.localQueryResultByToken(paginatedQueryToken) && this.callNewListenersWithCurrentValuesTimer === void 0) {\n      this.callNewListenersWithCurrentValuesTimer = setTimeout(\n        () => this.callNewListenersWithCurrentValues(),\n        0\n      );\n    }\n    const unsubscribeProps = {\n      unsubscribe: () => {\n        if (this.closed) {\n          return;\n        }\n        this.listeners.delete(queryInfo);\n        unsubscribe();\n      },\n      getCurrentValue: () => {\n        const result = this.paginatedClient.localQueryResult(\n          getFunctionName(query),\n          args,\n          paginationOptions\n        );\n        return result;\n      },\n      getQueryLogs: () => []\n      // Paginated queries don't aggregate their logs\n    };\n    const ret = unsubscribeProps.unsubscribe;\n    Object.assign(ret, unsubscribeProps);\n    return ret;\n  }\n  // Run all callbacks that have never been run before if they have a query\n  // result available now.\n  callNewListenersWithCurrentValues() {\n    this.callNewListenersWithCurrentValuesTimer = void 0;\n    this._transition({ queries: [], paginatedQueries: [] }, true);\n  }\n  queryResultReady(queryToken) {\n    return this.client.hasLocalQueryResultByToken(queryToken);\n  }\n  createDisabledUnsubscribe() {\n    const disabledUnsubscribe = (() => {\n    });\n    const unsubscribeProps = {\n      unsubscribe: disabledUnsubscribe,\n      getCurrentValue: () => void 0,\n      getQueryLogs: () => void 0\n    };\n    Object.assign(disabledUnsubscribe, unsubscribeProps);\n    return disabledUnsubscribe;\n  }\n  async close() {\n    if (this.disabled) return;\n    this.listeners.clear();\n    this._closed = true;\n    if (this._paginatedClient) {\n      this._paginatedClient = void 0;\n    }\n    return this.client.close();\n  }\n  /**\n   * Get the current JWT auth token and decoded claims.\n   */\n  getAuth() {\n    if (this.disabled) return;\n    return this.client.getCurrentAuthClaims();\n  }\n  /**\n   * Set the authentication token to be used for subsequent queries and mutations.\n   * `fetchToken` will be called automatically again if a token expires.\n   * `fetchToken` should return `null` if the token cannot be retrieved, for example\n   * when the user's rights were permanently revoked.\n   * @param fetchToken - an async function returning the JWT (typically an OpenID Connect Identity Token)\n   * @param onChange - a callback that will be called when the authentication status changes\n   */\n  setAuth(fetchToken, onChange) {\n    if (this.disabled) return;\n    this.client.setAuth(\n      fetchToken,\n      onChange ?? (() => {\n      })\n    );\n  }\n  /**\n   * @internal\n   */\n  setAdminAuth(token, identity) {\n    if (this.closed) {\n      throw new Error(\"ConvexClient has already been closed.\");\n    }\n    if (this.disabled) return;\n    this.client.setAdminAuth(token, identity);\n  }\n  /**\n   * @internal\n   */\n  _transition({\n    queries,\n    paginatedQueries\n  }, callNewListeners = false) {\n    const updatedQueries = [\n      ...queries.map((q) => q.token),\n      ...paginatedQueries.map((q) => q.token)\n    ];\n    for (const queryInfo of this.listeners) {\n      const { callback, queryToken, onError, hasEverRun } = queryInfo;\n      const isPaginatedQuery = serializedQueryTokenIsPaginated(queryToken);\n      const hasResultReady = isPaginatedQuery ? !!this.paginatedClient.localQueryResultByToken(queryToken) : this.client.hasLocalQueryResultByToken(queryToken);\n      if (updatedQueries.includes(queryToken) || callNewListeners && !hasEverRun && hasResultReady) {\n        queryInfo.hasEverRun = true;\n        let newValue;\n        try {\n          if (isPaginatedQuery) {\n            newValue = this.paginatedClient.localQueryResultByToken(queryToken);\n          } else {\n            newValue = this.client.localQueryResultByToken(queryToken);\n          }\n        } catch (error) {\n          if (!(error instanceof Error)) throw error;\n          if (onError) {\n            onError(\n              error,\n              \"Second argument to onUpdate onError is reserved for later use\"\n            );\n          } else {\n            void Promise.reject(error);\n          }\n          continue;\n        }\n        callback(\n          newValue,\n          \"Second argument to onUpdate callback is reserved for later use\"\n        );\n      }\n    }\n  }\n  /**\n   * Execute a mutation function.\n   *\n   * @param mutation - A {@link server.FunctionReference} for the public mutation\n   * to run.\n   * @param args - An arguments object for the mutation.\n   * @param options - A {@link MutationOptions} options object for the mutation.\n   * @returns A promise of the mutation's result.\n   */\n  async mutation(mutation, args, options) {\n    if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n    return await this.client.mutation(getFunctionName(mutation), args, options);\n  }\n  /**\n   * Execute an action function.\n   *\n   * @param action - A {@link server.FunctionReference} for the public action\n   * to run.\n   * @param args - An arguments object for the action.\n   * @returns A promise of the action's result.\n   */\n  async action(action, args) {\n    if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n    return await this.client.action(getFunctionName(action), args);\n  }\n  /**\n   * Fetch a query result once.\n   *\n   * @param query - A {@link server.FunctionReference} for the public query\n   * to run.\n   * @param args - An arguments object for the query.\n   * @returns A promise of the query's result.\n   */\n  async query(query, args) {\n    if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n    const value = this.client.localQueryResult(getFunctionName(query), args);\n    if (value !== void 0) return Promise.resolve(value);\n    return new Promise((resolve, reject) => {\n      const { unsubscribe } = this.onUpdate(\n        query,\n        args,\n        (value2) => {\n          unsubscribe();\n          resolve(value2);\n        },\n        (e) => {\n          unsubscribe();\n          reject(e);\n        }\n      );\n    });\n  }\n  /**\n   * Get the current {@link ConnectionState} between the client and the Convex\n   * backend.\n   *\n   * @returns The {@link ConnectionState} with the Convex backend.\n   */\n  connectionState() {\n    if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n    return this.client.connectionState();\n  }\n  /**\n   * Subscribe to the {@link ConnectionState} between the client and the Convex\n   * backend, calling a callback each time it changes.\n   *\n   * Subscribed callbacks will be called when any part of ConnectionState changes.\n   * ConnectionState may grow in future versions (e.g. to provide a array of\n   * inflight requests) in which case callbacks would be called more frequently.\n   *\n   * @returns An unsubscribe function to stop listening.\n   */\n  subscribeToConnectionState(cb) {\n    if (this.disabled) return () => {\n    };\n    return this.client.subscribeToConnectionState(cb);\n  }\n}\n//# sourceMappingURL=simple_client.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport {\n  getFunctionName\n} from \"../server/api.js\";\nimport { parseArgs, validateDeploymentUrl } from \"../common/index.js\";\nimport { version } from \"../index.js\";\nimport {\n  ConvexError,\n  convexToJson,\n  jsonToConvex\n} from \"../values/index.js\";\nimport {\n  instantiateDefaultLogger,\n  instantiateNoopLogger,\n  logForFunction\n} from \"./logging.js\";\nexport const STATUS_CODE_OK = 200;\nexport const STATUS_CODE_BAD_REQUEST = 400;\nexport const STATUS_CODE_UDF_FAILED = 560;\nlet specifiedFetch = void 0;\nexport function setFetch(f) {\n  specifiedFetch = f;\n}\nexport class ConvexHttpClient {\n  /**\n   * Create a new {@link ConvexHttpClient}.\n   *\n   * @param address - The url of your Convex deployment, often provided\n   * by an environment variable. E.g. `https://small-mouse-123.convex.cloud`.\n   * @param options - An object of options.\n   * - `skipConvexDeploymentUrlCheck` - Skip validating that the Convex deployment URL looks like\n   * `https://happy-animal-123.convex.cloud` or localhost. This can be useful if running a self-hosted\n   * Convex backend that uses a different URL.\n   * - `logger` - A logger or a boolean. If not provided, logs to the console.\n   * You can construct your own logger to customize logging to log elsewhere\n   * or not log at all, or use `false` as a shorthand for a no-op logger.\n   * A logger is an object with 4 methods: log(), warn(), error(), and logVerbose().\n   * These methods can receive multiple arguments of any types, like console.log().\n   * - `auth` - A JWT containing identity claims accessible in Convex functions.\n   * This identity may expire so it may be necessary to call `setAuth()` later,\n   * but for short-lived clients it's convenient to specify this value here.\n   * - `fetch` - A custom fetch implementation to use for all HTTP requests made by this client.\n   */\n  constructor(address, options) {\n    __publicField(this, \"address\");\n    __publicField(this, \"auth\");\n    __publicField(this, \"adminAuth\");\n    __publicField(this, \"encodedTsPromise\");\n    __publicField(this, \"debug\");\n    __publicField(this, \"fetchOptions\");\n    __publicField(this, \"fetch\");\n    __publicField(this, \"logger\");\n    __publicField(this, \"mutationQueue\", []);\n    __publicField(this, \"isProcessingQueue\", false);\n    if (typeof options === \"boolean\") {\n      throw new Error(\n        \"skipConvexDeploymentUrlCheck as the second argument is no longer supported. Please pass an options object, `{ skipConvexDeploymentUrlCheck: true }`.\"\n      );\n    }\n    const opts = options ?? {};\n    if (opts.skipConvexDeploymentUrlCheck !== true) {\n      validateDeploymentUrl(address);\n    }\n    this.logger = options?.logger === false ? instantiateNoopLogger({ verbose: false }) : options?.logger !== true && options?.logger ? options.logger : instantiateDefaultLogger({ verbose: false });\n    this.address = address;\n    this.debug = true;\n    this.auth = void 0;\n    this.adminAuth = void 0;\n    this.fetch = options?.fetch;\n    if (options?.auth) {\n      this.setAuth(options.auth);\n    }\n  }\n  /**\n   * Obtain the {@link ConvexHttpClient}'s URL to its backend.\n   * @deprecated Use url, which returns the url without /api at the end.\n   *\n   * @returns The URL to the Convex backend, including the client's API version.\n   */\n  backendUrl() {\n    return `${this.address}/api`;\n  }\n  /**\n   * Return the address for this client, useful for creating a new client.\n   *\n   * Not guaranteed to match the address with which this client was constructed:\n   * it may be canonicalized.\n   */\n  get url() {\n    return this.address;\n  }\n  /**\n   * Set the authentication token to be used for subsequent queries and mutations.\n   *\n   * Should be called whenever the token changes (i.e. due to expiration and refresh).\n   *\n   * @param value - JWT-encoded OpenID Connect identity token.\n   */\n  setAuth(value) {\n    this.clearAuth();\n    this.auth = value;\n  }\n  /**\n   * Set admin auth token to allow calling internal queries, mutations, and actions\n   * and acting as an identity.\n   *\n   * @internal\n   */\n  setAdminAuth(token, actingAsIdentity) {\n    this.clearAuth();\n    if (actingAsIdentity !== void 0) {\n      const bytes = new TextEncoder().encode(JSON.stringify(actingAsIdentity));\n      const actingAsIdentityEncoded = btoa(String.fromCodePoint(...bytes));\n      this.adminAuth = `${token}:${actingAsIdentityEncoded}`;\n    } else {\n      this.adminAuth = token;\n    }\n  }\n  /**\n   * Clear the current authentication token if set.\n   */\n  clearAuth() {\n    this.auth = void 0;\n    this.adminAuth = void 0;\n  }\n  /**\n   * Sets whether the result log lines should be printed on the console or not.\n   *\n   * @internal\n   */\n  setDebug(debug) {\n    this.debug = debug;\n  }\n  /**\n   * Used to customize the fetch behavior in some runtimes.\n   *\n   * @internal\n   */\n  setFetchOptions(fetchOptions) {\n    this.fetchOptions = fetchOptions;\n  }\n  /**\n   * This API is experimental: it may change or disappear.\n   *\n   * Execute a Convex query function at the same timestamp as every other\n   * consistent query execution run by this HTTP client.\n   *\n   * This doesn't make sense for long-lived ConvexHttpClients as Convex\n   * backends can read a limited amount into the past: beyond 30 seconds\n   * in the past may not be available.\n   *\n   * Create a new client to use a consistent time.\n   *\n   * @param name - The name of the query.\n   * @param args - The arguments object for the query. If this is omitted,\n   * the arguments will be `{}`.\n   * @returns A promise of the query's result.\n   *\n   * @deprecated This API is experimental: it may change or disappear.\n   */\n  async consistentQuery(query, ...args) {\n    const queryArgs = parseArgs(args[0]);\n    const timestampPromise = this.getTimestamp();\n    return await this.queryInner(query, queryArgs, { timestampPromise });\n  }\n  async getTimestamp() {\n    if (this.encodedTsPromise) {\n      return this.encodedTsPromise;\n    }\n    return this.encodedTsPromise = this.getTimestampInner();\n  }\n  async getTimestampInner() {\n    const localFetch = this.fetch || specifiedFetch || fetch;\n    const headers = {\n      \"Content-Type\": \"application/json\",\n      \"Convex-Client\": `npm-${version}`\n    };\n    const response = await localFetch(`${this.address}/api/query_ts`, {\n      ...this.fetchOptions,\n      method: \"POST\",\n      headers\n    });\n    if (!response.ok) {\n      throw new Error(await response.text());\n    }\n    const { ts } = await response.json();\n    return ts;\n  }\n  /**\n   * Execute a Convex query function.\n   *\n   * @param name - The name of the query.\n   * @param args - The arguments object for the query. If this is omitted,\n   * the arguments will be `{}`.\n   * @returns A promise of the query's result.\n   */\n  async query(query, ...args) {\n    const queryArgs = parseArgs(args[0]);\n    return await this.queryInner(query, queryArgs, {});\n  }\n  async queryInner(query, queryArgs, options) {\n    const name = getFunctionName(query);\n    const args = [convexToJson(queryArgs)];\n    const headers = {\n      \"Content-Type\": \"application/json\",\n      \"Convex-Client\": `npm-${version}`\n    };\n    if (this.adminAuth) {\n      headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n    } else if (this.auth) {\n      headers[\"Authorization\"] = `Bearer ${this.auth}`;\n    }\n    const localFetch = this.fetch || specifiedFetch || fetch;\n    const timestamp = options.timestampPromise ? await options.timestampPromise : void 0;\n    const body = JSON.stringify({\n      path: name,\n      format: \"convex_encoded_json\",\n      args,\n      ...timestamp ? { ts: timestamp } : {}\n    });\n    const endpoint = timestamp ? `${this.address}/api/query_at_ts` : `${this.address}/api/query`;\n    const response = await localFetch(endpoint, {\n      ...this.fetchOptions,\n      body,\n      method: \"POST\",\n      headers\n    });\n    if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n      throw new Error(await response.text());\n    }\n    const respJSON = await response.json();\n    if (this.debug) {\n      for (const line of respJSON.logLines ?? []) {\n        logForFunction(this.logger, \"info\", \"query\", name, line);\n      }\n    }\n    switch (respJSON.status) {\n      case \"success\":\n        return jsonToConvex(respJSON.value);\n      case \"error\":\n        if (respJSON.errorData !== void 0) {\n          throw forwardErrorData(\n            respJSON.errorData,\n            new ConvexError(respJSON.errorMessage)\n          );\n        }\n        throw new Error(respJSON.errorMessage);\n      default:\n        throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n    }\n  }\n  async mutationInner(mutation, mutationArgs) {\n    const name = getFunctionName(mutation);\n    const body = JSON.stringify({\n      path: name,\n      format: \"convex_encoded_json\",\n      args: [convexToJson(mutationArgs)]\n    });\n    const headers = {\n      \"Content-Type\": \"application/json\",\n      \"Convex-Client\": `npm-${version}`\n    };\n    if (this.adminAuth) {\n      headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n    } else if (this.auth) {\n      headers[\"Authorization\"] = `Bearer ${this.auth}`;\n    }\n    const localFetch = this.fetch || specifiedFetch || fetch;\n    const response = await localFetch(`${this.address}/api/mutation`, {\n      ...this.fetchOptions,\n      body,\n      method: \"POST\",\n      headers\n    });\n    if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n      throw new Error(await response.text());\n    }\n    const respJSON = await response.json();\n    if (this.debug) {\n      for (const line of respJSON.logLines ?? []) {\n        logForFunction(this.logger, \"info\", \"mutation\", name, line);\n      }\n    }\n    switch (respJSON.status) {\n      case \"success\":\n        return jsonToConvex(respJSON.value);\n      case \"error\":\n        if (respJSON.errorData !== void 0) {\n          throw forwardErrorData(\n            respJSON.errorData,\n            new ConvexError(respJSON.errorMessage)\n          );\n        }\n        throw new Error(respJSON.errorMessage);\n      default:\n        throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n    }\n  }\n  async processMutationQueue() {\n    if (this.isProcessingQueue) {\n      return;\n    }\n    this.isProcessingQueue = true;\n    while (this.mutationQueue.length > 0) {\n      const { mutation, args, resolve, reject } = this.mutationQueue.shift();\n      try {\n        const result = await this.mutationInner(mutation, args);\n        resolve(result);\n      } catch (error) {\n        reject(error);\n      }\n    }\n    this.isProcessingQueue = false;\n  }\n  enqueueMutation(mutation, args) {\n    return new Promise((resolve, reject) => {\n      this.mutationQueue.push({ mutation, args, resolve, reject });\n      void this.processMutationQueue();\n    });\n  }\n  /**\n   * Execute a Convex mutation function. Mutations are queued by default.\n   *\n   * @param name - The name of the mutation.\n   * @param args - The arguments object for the mutation. If this is omitted,\n   * the arguments will be `{}`.\n   * @param options - An optional object containing\n   * @returns A promise of the mutation's result.\n   */\n  async mutation(mutation, ...args) {\n    const [fnArgs, options] = args;\n    const mutationArgs = parseArgs(fnArgs);\n    const queued = !options?.skipQueue;\n    if (queued) {\n      return await this.enqueueMutation(mutation, mutationArgs);\n    } else {\n      return await this.mutationInner(mutation, mutationArgs);\n    }\n  }\n  /**\n   * Execute a Convex action function. Actions are not queued.\n   *\n   * @param name - The name of the action.\n   * @param args - The arguments object for the action. If this is omitted,\n   * the arguments will be `{}`.\n   * @returns A promise of the action's result.\n   */\n  async action(action, ...args) {\n    const actionArgs = parseArgs(args[0]);\n    const name = getFunctionName(action);\n    const body = JSON.stringify({\n      path: name,\n      format: \"convex_encoded_json\",\n      args: [convexToJson(actionArgs)]\n    });\n    const headers = {\n      \"Content-Type\": \"application/json\",\n      \"Convex-Client\": `npm-${version}`\n    };\n    if (this.adminAuth) {\n      headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n    } else if (this.auth) {\n      headers[\"Authorization\"] = `Bearer ${this.auth}`;\n    }\n    const localFetch = this.fetch || specifiedFetch || fetch;\n    const response = await localFetch(`${this.address}/api/action`, {\n      ...this.fetchOptions,\n      body,\n      method: \"POST\",\n      headers\n    });\n    if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n      throw new Error(await response.text());\n    }\n    const respJSON = await response.json();\n    if (this.debug) {\n      for (const line of respJSON.logLines ?? []) {\n        logForFunction(this.logger, \"info\", \"action\", name, line);\n      }\n    }\n    switch (respJSON.status) {\n      case \"success\":\n        return jsonToConvex(respJSON.value);\n      case \"error\":\n        if (respJSON.errorData !== void 0) {\n          throw forwardErrorData(\n            respJSON.errorData,\n            new ConvexError(respJSON.errorMessage)\n          );\n        }\n        throw new Error(respJSON.errorMessage);\n      default:\n        throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n    }\n  }\n  /**\n   * Execute a Convex function of an unknown type. These function calls are not queued.\n   *\n   * @param name - The name of the function.\n   * @param args - The arguments object for the function. If this is omitted,\n   * the arguments will be `{}`.\n   * @returns A promise of the function's result.\n   *\n   * @internal\n   */\n  async function(anyFunction, componentPath, ...args) {\n    const functionArgs = parseArgs(args[0]);\n    const name = typeof anyFunction === \"string\" ? anyFunction : getFunctionName(anyFunction);\n    const body = JSON.stringify({\n      componentPath,\n      path: name,\n      format: \"convex_encoded_json\",\n      args: convexToJson(functionArgs)\n    });\n    const headers = {\n      \"Content-Type\": \"application/json\",\n      \"Convex-Client\": `npm-${version}`\n    };\n    if (this.adminAuth) {\n      headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n    } else if (this.auth) {\n      headers[\"Authorization\"] = `Bearer ${this.auth}`;\n    }\n    const localFetch = this.fetch || specifiedFetch || fetch;\n    const response = await localFetch(`${this.address}/api/function`, {\n      ...this.fetchOptions,\n      body,\n      method: \"POST\",\n      headers\n    });\n    if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n      throw new Error(await response.text());\n    }\n    const respJSON = await response.json();\n    if (this.debug) {\n      for (const line of respJSON.logLines ?? []) {\n        logForFunction(this.logger, \"info\", \"any\", name, line);\n      }\n    }\n    switch (respJSON.status) {\n      case \"success\":\n        return jsonToConvex(respJSON.value);\n      case \"error\":\n        if (respJSON.errorData !== void 0) {\n          throw forwardErrorData(\n            respJSON.errorData,\n            new ConvexError(respJSON.errorMessage)\n          );\n        }\n        throw new Error(respJSON.errorMessage);\n      default:\n        throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n    }\n  }\n}\nfunction forwardErrorData(errorData, error) {\n  error.data = jsonToConvex(errorData);\n  return error;\n}\n//# sourceMappingURL=http_client.js.map\n","\"use strict\";\nexport { BaseConvexClient } from \"./sync/client.js\";\nexport { ConvexClient } from \"./simple_client.js\";\nexport { ConvexHttpClient } from \"./http_client.js\";\n//# sourceMappingURL=index.js.map\n","\"use strict\";\nimport { useEffect, useState } from \"react\";\nexport function useSubscription({\n  // (Synchronously) returns the current value of our subscription.\n  getCurrentValue,\n  // This function is passed an event handler to attach to the subscription.\n  // It should return an unsubscribe function that removes the handler.\n  subscribe\n}) {\n  const [state, setState] = useState(() => ({\n    getCurrentValue,\n    subscribe,\n    value: getCurrentValue()\n  }));\n  let valueToReturn = state.value;\n  if (state.getCurrentValue !== getCurrentValue || state.subscribe !== subscribe) {\n    valueToReturn = getCurrentValue();\n    setState({\n      getCurrentValue,\n      subscribe,\n      value: valueToReturn\n    });\n  }\n  useEffect(() => {\n    let didUnsubscribe = false;\n    const checkForUpdates = () => {\n      if (didUnsubscribe) {\n        return;\n      }\n      setState((prevState) => {\n        if (prevState.getCurrentValue !== getCurrentValue || prevState.subscribe !== subscribe) {\n          return prevState;\n        }\n        const value = getCurrentValue();\n        if (prevState.value === value) {\n          return prevState;\n        }\n        return { ...prevState, value };\n      });\n    };\n    const unsubscribe = subscribe(checkForUpdates);\n    checkForUpdates();\n    return () => {\n      didUnsubscribe = true;\n      unsubscribe();\n    };\n  }, [getCurrentValue, subscribe]);\n  return valueToReturn;\n}\n//# sourceMappingURL=use_subscription.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { BaseConvexClient } from \"../browser/index.js\";\nimport React, { useCallback, useContext, useMemo } from \"react\";\nimport { convexToJson } from \"../values/index.js\";\nimport { useQueries } from \"./use_queries.js\";\nimport { useSubscription } from \"./use_subscription.js\";\nimport { parseArgs } from \"../common/index.js\";\nimport {\n  getFunctionName,\n  makeFunctionReference\n} from \"../server/api.js\";\nimport {\n  instantiateDefaultLogger,\n  instantiateNoopLogger\n} from \"../browser/logging.js\";\nimport {\n  PaginatedQueryClient\n} from \"../browser/sync/paginated_query_client.js\";\nconst DEFAULT_EXTEND_SUBSCRIPTION_FOR = 5e3;\nif (typeof React === \"undefined\") {\n  throw new Error(\"Required dependency 'react' not found\");\n}\nexport function createMutation(mutationReference, client, update) {\n  function mutation(args) {\n    assertNotAccidentalArgument(args);\n    return client.mutation(mutationReference, args, {\n      optimisticUpdate: update\n    });\n  }\n  mutation.withOptimisticUpdate = function withOptimisticUpdate(optimisticUpdate) {\n    if (update !== void 0) {\n      throw new Error(\n        `Already specified optimistic update for mutation ${getFunctionName(\n          mutationReference\n        )}`\n      );\n    }\n    return createMutation(mutationReference, client, optimisticUpdate);\n  };\n  return mutation;\n}\nfunction createAction(actionReference, client) {\n  return function(args) {\n    return client.action(actionReference, args);\n  };\n}\nexport class ConvexReactClient {\n  /**\n   * @param address - The url of your Convex deployment, often provided\n   * by an environment variable. E.g. `https://small-mouse-123.convex.cloud`.\n   * @param options - See {@link ConvexReactClientOptions} for a full description.\n   */\n  constructor(address, options) {\n    __publicField(this, \"address\");\n    __publicField(this, \"cachedSync\");\n    __publicField(this, \"cachedPaginatedQueryClient\");\n    __publicField(this, \"listeners\");\n    __publicField(this, \"options\");\n    // \"closed\" means this client is done, not just that the underlying WS connection is closed.\n    __publicField(this, \"closed\", false);\n    __publicField(this, \"_logger\");\n    __publicField(this, \"adminAuth\");\n    __publicField(this, \"fakeUserIdentity\");\n    if (address === void 0) {\n      throw new Error(\n        \"No address provided to ConvexReactClient.\\nIf trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\\nIf running locally, make sure to run `convex dev` and ensure the .env.local file is populated.\"\n      );\n    }\n    if (typeof address !== \"string\") {\n      throw new Error(\n        `ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof address} instead.`\n      );\n    }\n    if (!address.includes(\"://\")) {\n      throw new Error(\"Provided address was not an absolute URL.\");\n    }\n    this.address = address;\n    this.listeners = /* @__PURE__ */ new Map();\n    this._logger = options?.logger === false ? instantiateNoopLogger({ verbose: options?.verbose ?? false }) : options?.logger !== true && options?.logger ? options.logger : instantiateDefaultLogger({ verbose: options?.verbose ?? false });\n    this.options = { ...options, logger: this._logger };\n  }\n  /**\n   * Return the address for this client, useful for creating a new client.\n   *\n   * Not guaranteed to match the address with which this client was constructed:\n   * it may be canonicalized.\n   */\n  get url() {\n    return this.address;\n  }\n  /**\n   * Lazily instantiate the `BaseConvexClient` so we don't create the WebSocket\n   * when server-side rendering.\n   *\n   * @internal\n   */\n  get sync() {\n    if (this.closed) {\n      throw new Error(\"ConvexReactClient has already been closed.\");\n    }\n    if (this.cachedSync) {\n      return this.cachedSync;\n    }\n    this.cachedSync = new BaseConvexClient(\n      this.address,\n      () => {\n      },\n      // Use the PaginatedQueryClient's transition instead.\n      this.options\n    );\n    if (this.adminAuth) {\n      this.cachedSync.setAdminAuth(this.adminAuth, this.fakeUserIdentity);\n    }\n    this.cachedPaginatedQueryClient = new PaginatedQueryClient(\n      this.cachedSync,\n      (transition) => this.handleTransition(transition)\n    );\n    return this.cachedSync;\n  }\n  /**\n   * Lazily instantiate the `PaginatedQueryClient` so we don't create it\n   * when server-side rendering.\n   *\n   * @internal\n   */\n  get paginatedQueryClient() {\n    this.sync;\n    if (this.cachedPaginatedQueryClient) {\n      return this.cachedPaginatedQueryClient;\n    }\n    throw new Error(\"Should already be instantiated\");\n  }\n  /**\n   * Set the authentication token to be used for subsequent queries and mutations.\n   * `fetchToken` will be called automatically again if a token expires.\n   * `fetchToken` should return `null` if the token cannot be retrieved, for example\n   * when the user's rights were permanently revoked.\n   * @param fetchToken - an async function returning the JWT-encoded OpenID Connect Identity Token\n   * @param onChange - a callback that will be called when the authentication status changes\n   */\n  setAuth(fetchToken, onChange) {\n    if (typeof fetchToken === \"string\") {\n      throw new Error(\n        \"Passing a string to ConvexReactClient.setAuth is no longer supported, please upgrade to passing in an async function to handle reauthentication.\"\n      );\n    }\n    this.sync.setAuth(\n      fetchToken,\n      onChange ?? (() => {\n      })\n    );\n  }\n  /**\n   * Clear the current authentication token if set.\n   */\n  clearAuth() {\n    this.sync.clearAuth();\n  }\n  /**\n   * @internal\n   */\n  setAdminAuth(token, identity) {\n    this.adminAuth = token;\n    this.fakeUserIdentity = identity;\n    if (this.closed) {\n      throw new Error(\"ConvexReactClient has already been closed.\");\n    }\n    if (this.cachedSync) {\n      this.sync.setAdminAuth(token, identity);\n    }\n  }\n  /**\n   * Construct a new {@link Watch} on a Convex query function.\n   *\n   * **Most application code should not call this method directly. Instead use\n   * the {@link useQuery} hook.**\n   *\n   * The act of creating a watch does nothing, a Watch is stateless.\n   *\n   * @param query - A {@link server.FunctionReference} for the public query to run.\n   * @param args - An arguments object for the query. If this is omitted,\n   * the arguments will be `{}`.\n   * @param options - A {@link WatchQueryOptions} options object for this query.\n   *\n   * @returns The {@link Watch} object.\n   */\n  watchQuery(query, ...argsAndOptions) {\n    const [args, options] = argsAndOptions;\n    const name = getFunctionName(query);\n    return {\n      onUpdate: (callback) => {\n        const { queryToken, unsubscribe } = this.sync.subscribe(\n          name,\n          args,\n          options\n        );\n        const currentListeners = this.listeners.get(queryToken);\n        if (currentListeners !== void 0) {\n          currentListeners.add(callback);\n        } else {\n          this.listeners.set(queryToken, /* @__PURE__ */ new Set([callback]));\n        }\n        return () => {\n          if (this.closed) {\n            return;\n          }\n          const currentListeners2 = this.listeners.get(queryToken);\n          currentListeners2.delete(callback);\n          if (currentListeners2.size === 0) {\n            this.listeners.delete(queryToken);\n          }\n          unsubscribe();\n        };\n      },\n      localQueryResult: () => {\n        if (this.cachedSync) {\n          return this.cachedSync.localQueryResult(name, args);\n        }\n        return void 0;\n      },\n      localQueryLogs: () => {\n        if (this.cachedSync) {\n          return this.cachedSync.localQueryLogs(name, args);\n        }\n        return void 0;\n      },\n      journal: () => {\n        if (this.cachedSync) {\n          return this.cachedSync.queryJournal(name, args);\n        }\n        return void 0;\n      }\n    };\n  }\n  // Let's try out a queryOptions-style API.\n  // This method is similar to the React Query API `queryClient.prefetchQuery()`.\n  // In the future an ensureQueryData(): Promise<Data> method could exist.\n  /**\n   * Indicates likely future interest in a query subscription.\n   *\n   * The implementation currently immediately subscribes to a query. In the future this method\n   * may prioritize some queries over others, fetch the query result without subscribing, or\n   * do nothing in slow network connections or high load scenarios.\n   *\n   * To use this in a React component, call useQuery() and ignore the return value.\n   *\n   * @param queryOptions - A query (function reference from an api object) and its args, plus\n   * an optional extendSubscriptionFor for how long to subscribe to the query.\n   */\n  prewarmQuery(queryOptions) {\n    const extendSubscriptionFor = queryOptions.extendSubscriptionFor ?? DEFAULT_EXTEND_SUBSCRIPTION_FOR;\n    const watch = this.watchQuery(queryOptions.query, queryOptions.args || {});\n    const unsubscribe = watch.onUpdate(() => {\n    });\n    setTimeout(unsubscribe, extendSubscriptionFor);\n  }\n  /**\n   * Construct a new {@link PaginatedWatch} on a Convex paginated query function.\n   *\n   * **Most application code should not call this method directly. Instead use\n   * the {@link usePaginatedQuery} hook.**\n   *\n   * The act of creating a watch does nothing, a Watch is stateless.\n   *\n   * @param query - A {@link server.FunctionReference} for the public query to run.\n   * @param args - An arguments object for the query. If this is omitted,\n   * the arguments will be `{}`.\n   * @param options - A {@link WatchPaginatedQueryOptions} options object for this query.\n   *\n   * @returns The {@link PaginatedWatch} object.\n   *\n   * @internal\n   */\n  watchPaginatedQuery(query, args, options) {\n    const name = getFunctionName(query);\n    return {\n      onUpdate: (callback) => {\n        const { paginatedQueryToken, unsubscribe } = this.paginatedQueryClient.subscribe(name, args || {}, options);\n        const currentListeners = this.listeners.get(paginatedQueryToken);\n        if (currentListeners !== void 0) {\n          currentListeners.add(callback);\n        } else {\n          this.listeners.set(paginatedQueryToken, /* @__PURE__ */ new Set([callback]));\n        }\n        return () => {\n          if (this.closed) {\n            return;\n          }\n          const currentListeners2 = this.listeners.get(paginatedQueryToken);\n          currentListeners2.delete(callback);\n          if (currentListeners2.size === 0) {\n            this.listeners.delete(paginatedQueryToken);\n          }\n          unsubscribe();\n        };\n      },\n      localQueryResult: () => {\n        return this.paginatedQueryClient.localQueryResult(name, args, options);\n      }\n    };\n  }\n  /**\n   * Execute a mutation function.\n   *\n   * @param mutation - A {@link server.FunctionReference} for the public mutation\n   * to run.\n   * @param args - An arguments object for the mutation. If this is omitted,\n   * the arguments will be `{}`.\n   * @param options - A {@link MutationOptions} options object for the mutation.\n   * @returns A promise of the mutation's result.\n   */\n  mutation(mutation, ...argsAndOptions) {\n    const [args, options] = argsAndOptions;\n    const name = getFunctionName(mutation);\n    return this.sync.mutation(name, args, options);\n  }\n  /**\n   * Execute an action function.\n   *\n   * @param action - A {@link server.FunctionReference} for the public action\n   * to run.\n   * @param args - An arguments object for the action. If this is omitted,\n   * the arguments will be `{}`.\n   * @returns A promise of the action's result.\n   */\n  action(action, ...args) {\n    const name = getFunctionName(action);\n    return this.sync.action(name, ...args);\n  }\n  /**\n   * Fetch a query result once.\n   *\n   * **Most application code should subscribe to queries instead, using\n   * the {@link useQuery} hook.**\n   *\n   * @param query - A {@link server.FunctionReference} for the public query\n   * to run.\n   * @param args - An arguments object for the query. If this is omitted,\n   * the arguments will be `{}`.\n   * @returns A promise of the query's result.\n   */\n  query(query, ...args) {\n    const watch = this.watchQuery(query, ...args);\n    const existingResult = watch.localQueryResult();\n    if (existingResult !== void 0) {\n      return Promise.resolve(existingResult);\n    }\n    return new Promise((resolve, reject) => {\n      const unsubscribe = watch.onUpdate(() => {\n        unsubscribe();\n        try {\n          resolve(watch.localQueryResult());\n        } catch (e) {\n          reject(e);\n        }\n      });\n    });\n  }\n  /**\n   * Get the current {@link ConnectionState} between the client and the Convex\n   * backend.\n   *\n   * @returns The {@link ConnectionState} with the Convex backend.\n   */\n  connectionState() {\n    return this.sync.connectionState();\n  }\n  /**\n   * Subscribe to the {@link ConnectionState} between the client and the Convex\n   * backend, calling a callback each time it changes.\n   *\n   * Subscribed callbacks will be called when any part of ConnectionState changes.\n   * ConnectionState may grow in future versions (e.g. to provide a array of\n   * inflight requests) in which case callbacks would be called more frequently.\n   * ConnectionState may also *lose* properties in future versions as we figure\n   * out what information is most useful. As such this API is considered unstable.\n   *\n   * @returns An unsubscribe function to stop listening.\n   */\n  subscribeToConnectionState(cb) {\n    return this.sync.subscribeToConnectionState(cb);\n  }\n  /**\n   * Get the logger for this client.\n   *\n   * @returns The {@link Logger} for this client.\n   */\n  get logger() {\n    return this._logger;\n  }\n  /**\n   * Close any network handles associated with this client and stop all subscriptions.\n   *\n   * Call this method when you're done with a {@link ConvexReactClient} to\n   * dispose of its sockets and resources.\n   *\n   * @returns A `Promise` fulfilled when the connection has been completely closed.\n   */\n  async close() {\n    this.closed = true;\n    this.listeners = /* @__PURE__ */ new Map();\n    if (this.cachedPaginatedQueryClient) {\n      this.cachedPaginatedQueryClient = void 0;\n    }\n    if (this.cachedSync) {\n      const sync = this.cachedSync;\n      this.cachedSync = void 0;\n      await sync.close();\n    }\n  }\n  /**\n   * Handle transitions from both base client and paginated client.\n   * This ensures all transitions are processed synchronously and in order.\n   */\n  handleTransition(transition) {\n    const simple = transition.queries.map((q) => q.token);\n    const paginated = transition.paginatedQueries.map((q) => q.token);\n    this.transition([...simple, ...paginated]);\n  }\n  transition(updatedQueries) {\n    for (const queryToken of updatedQueries) {\n      const callbacks = this.listeners.get(queryToken);\n      if (callbacks) {\n        for (const callback of callbacks) {\n          callback();\n        }\n      }\n    }\n  }\n}\nconst ConvexContext = React.createContext(\n  void 0\n  // in the future this will be a mocked client for testing\n);\nexport function useConvex() {\n  return useContext(ConvexContext);\n}\nexport const ConvexProvider = ({ client, children }) => {\n  return React.createElement(\n    ConvexContext.Provider,\n    { value: client },\n    children\n  );\n};\nexport function useQuery(query, ...args) {\n  const skip = args[0] === \"skip\";\n  const argsObject = args[0] === \"skip\" ? {} : parseArgs(args[0]);\n  const queryReference = typeof query === \"string\" ? makeFunctionReference(query) : query;\n  const queryName = getFunctionName(queryReference);\n  const queries = useMemo(\n    () => skip ? {} : { query: { query: queryReference, args: argsObject } },\n    // Stringify args so args that are semantically the same don't trigger a\n    // rerender. Saves developers from adding `useMemo` on every args usage.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [JSON.stringify(convexToJson(argsObject)), queryName, skip]\n  );\n  const results = useQueries(queries);\n  const result = results[\"query\"];\n  if (result instanceof Error) {\n    throw result;\n  }\n  return result;\n}\nexport function useMutation(mutation) {\n  const mutationReference = typeof mutation === \"string\" ? makeFunctionReference(mutation) : mutation;\n  const convex = useContext(ConvexContext);\n  if (convex === void 0) {\n    throw new Error(\n      \"Could not find Convex client! `useMutation` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\"\n    );\n  }\n  return useMemo(\n    () => createMutation(mutationReference, convex),\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [convex, getFunctionName(mutationReference)]\n  );\n}\nexport function useAction(action) {\n  const convex = useContext(ConvexContext);\n  const actionReference = typeof action === \"string\" ? makeFunctionReference(action) : action;\n  if (convex === void 0) {\n    throw new Error(\n      \"Could not find Convex client! `useAction` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\"\n    );\n  }\n  return useMemo(\n    () => createAction(actionReference, convex),\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [convex, getFunctionName(actionReference)]\n  );\n}\nexport function useConvexConnectionState() {\n  const convex = useContext(ConvexContext);\n  if (convex === void 0) {\n    throw new Error(\n      \"Could not find Convex client! `useConvexConnectionState` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\"\n    );\n  }\n  const getCurrentValue = useCallback(() => {\n    return convex.connectionState();\n  }, [convex]);\n  const subscribe = useCallback(\n    (callback) => {\n      return convex.subscribeToConnectionState(() => {\n        callback();\n      });\n    },\n    [convex]\n  );\n  return useSubscription({ getCurrentValue, subscribe });\n}\nfunction assertNotAccidentalArgument(value) {\n  if (typeof value === \"object\" && value !== null && \"bubbles\" in value && \"persist\" in value && \"isDefaultPrevented\" in value) {\n    throw new Error(\n      `Convex function called with SyntheticEvent object. Did you use a Convex function as an event handler directly? Event handlers like onClick receive an event object as their first argument. These SyntheticEvent objects are not valid Convex values. Try wrapping the function like \\`const handler = () => myMutation();\\` and using \\`handler\\` in the event handler.`\n    );\n  }\n}\n//# sourceMappingURL=client.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { convexToJson } from \"../values/index.js\";\nimport { getFunctionName } from \"../server/api.js\";\nexport class QueriesObserver {\n  constructor(createWatch) {\n    __publicField(this, \"createWatch\");\n    __publicField(this, \"queries\");\n    __publicField(this, \"listeners\");\n    this.createWatch = createWatch;\n    this.queries = {};\n    this.listeners = /* @__PURE__ */ new Set();\n  }\n  setQueries(newQueries) {\n    for (const identifier of Object.keys(newQueries)) {\n      const { query, args, paginationOptions } = newQueries[identifier];\n      getFunctionName(query);\n      if (this.queries[identifier] === void 0) {\n        this.addQuery(\n          identifier,\n          query,\n          args,\n          paginationOptions ? { paginationOptions } : {}\n        );\n      } else {\n        const existingInfo = this.queries[identifier];\n        if (getFunctionName(query) !== getFunctionName(existingInfo.query) || JSON.stringify(convexToJson(args)) !== JSON.stringify(convexToJson(existingInfo.args)) || JSON.stringify(paginationOptions) !== JSON.stringify(existingInfo.paginationOptions)) {\n          this.removeQuery(identifier);\n          this.addQuery(\n            identifier,\n            query,\n            args,\n            paginationOptions ? { paginationOptions } : {}\n          );\n        }\n      }\n    }\n    for (const identifier of Object.keys(this.queries)) {\n      if (newQueries[identifier] === void 0) {\n        this.removeQuery(identifier);\n      }\n    }\n  }\n  subscribe(listener) {\n    this.listeners.add(listener);\n    return () => {\n      this.listeners.delete(listener);\n    };\n  }\n  getLocalResults(queries) {\n    const result = {};\n    for (const identifier of Object.keys(queries)) {\n      const { query, args } = queries[identifier];\n      const paginationOptions = queries[identifier].paginationOptions;\n      getFunctionName(query);\n      const watch = this.createWatch(\n        query,\n        args,\n        paginationOptions ? { paginationOptions } : {}\n      );\n      let value;\n      try {\n        value = watch.localQueryResult();\n      } catch (e) {\n        if (e instanceof Error) {\n          value = e;\n        } else {\n          throw e;\n        }\n      }\n      result[identifier] = value;\n    }\n    return result;\n  }\n  setCreateWatch(createWatch) {\n    this.createWatch = createWatch;\n    for (const identifier of Object.keys(this.queries)) {\n      const { query, args, watch, paginationOptions } = this.queries[identifier];\n      const journal = \"journal\" in watch ? watch.journal() : void 0;\n      this.removeQuery(identifier);\n      this.addQuery(identifier, query, args, {\n        ...journal ? { journal } : [],\n        ...paginationOptions ? { paginationOptions } : {}\n      });\n    }\n  }\n  destroy() {\n    for (const identifier of Object.keys(this.queries)) {\n      this.removeQuery(identifier);\n    }\n    this.listeners = /* @__PURE__ */ new Set();\n  }\n  addQuery(identifier, query, args, {\n    paginationOptions,\n    journal\n  }) {\n    if (this.queries[identifier] !== void 0) {\n      throw new Error(\n        `Tried to add a new query with identifier ${identifier} when it already exists.`\n      );\n    }\n    const watch = this.createWatch(query, args, {\n      ...journal ? { journal } : [],\n      ...paginationOptions ? { paginationOptions } : {}\n    });\n    const unsubscribe = watch.onUpdate(() => this.notifyListeners());\n    this.queries[identifier] = {\n      query,\n      args,\n      watch,\n      unsubscribe,\n      ...paginationOptions ? { paginationOptions } : {}\n    };\n  }\n  removeQuery(identifier) {\n    const info = this.queries[identifier];\n    if (info === void 0) {\n      throw new Error(`No query found with identifier ${identifier}.`);\n    }\n    info.unsubscribe();\n    delete this.queries[identifier];\n  }\n  notifyListeners() {\n    for (const listener of this.listeners) {\n      listener();\n    }\n  }\n}\n//# sourceMappingURL=queries_observer.js.map\n","\"use strict\";\nimport { useEffect, useMemo, useState } from \"react\";\nimport { useConvex } from \"./client.js\";\nimport { QueriesObserver } from \"./queries_observer.js\";\nimport { useSubscription } from \"./use_subscription.js\";\nexport function useQueries(queries) {\n  const convex = useConvex();\n  if (convex === void 0) {\n    throw new Error(\n      \"Could not find Convex client! `useQuery` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\"\n    );\n  }\n  const createWatch = useMemo(() => {\n    return (query, args, {\n      journal,\n      paginationOptions\n    }) => {\n      if (paginationOptions) {\n        return convex.watchPaginatedQuery(query, args, paginationOptions);\n      } else {\n        return convex.watchQuery(query, args, journal ? { journal } : {});\n      }\n    };\n  }, [convex]);\n  return useQueriesHelper(queries, createWatch);\n}\nexport function useQueriesHelper(queries, createWatch) {\n  const [observer] = useState(() => new QueriesObserver(createWatch));\n  if (observer.createWatch !== createWatch) {\n    observer.setCreateWatch(createWatch);\n  }\n  useEffect(() => () => observer.destroy(), [observer]);\n  const subscription = useMemo(\n    () => ({\n      getCurrentValue: () => {\n        return observer.getLocalResults(queries);\n      },\n      subscribe: (callback) => {\n        observer.setQueries(queries);\n        return observer.subscribe(callback);\n      }\n    }),\n    [observer, queries]\n  );\n  return useSubscription(subscription);\n}\n//# sourceMappingURL=use_queries.js.map\n","\"use strict\";\nimport { useMemo, useState } from \"react\";\nimport { ConvexError, convexToJson } from \"../values/index.js\";\nimport { useQueries } from \"./use_queries.js\";\nimport {\n  getFunctionName\n} from \"../server/api.js\";\nimport { useConvex } from \"./client.js\";\nimport { compareValues } from \"../values/compare.js\";\nconst splitQuery = (key, splitCursor, continueCursor) => (prevState) => {\n  const queries = { ...prevState.queries };\n  const splitKey1 = prevState.nextPageKey;\n  const splitKey2 = prevState.nextPageKey + 1;\n  const nextPageKey = prevState.nextPageKey + 2;\n  queries[splitKey1] = {\n    query: prevState.query,\n    args: {\n      ...prevState.args,\n      paginationOpts: {\n        ...prevState.queries[key].args.paginationOpts,\n        endCursor: splitCursor\n      }\n    }\n  };\n  queries[splitKey2] = {\n    query: prevState.query,\n    args: {\n      ...prevState.args,\n      paginationOpts: {\n        ...prevState.queries[key].args.paginationOpts,\n        cursor: splitCursor,\n        endCursor: continueCursor\n      }\n    }\n  };\n  const ongoingSplits = { ...prevState.ongoingSplits };\n  ongoingSplits[key] = [splitKey1, splitKey2];\n  return {\n    ...prevState,\n    nextPageKey,\n    queries,\n    ongoingSplits\n  };\n};\nconst completeSplitQuery = (key) => (prevState) => {\n  const completedSplit = prevState.ongoingSplits[key];\n  if (completedSplit === void 0) {\n    return prevState;\n  }\n  const queries = { ...prevState.queries };\n  delete queries[key];\n  const ongoingSplits = { ...prevState.ongoingSplits };\n  delete ongoingSplits[key];\n  let pageKeys = prevState.pageKeys.slice();\n  const pageIndex = prevState.pageKeys.findIndex((v) => v === key);\n  if (pageIndex >= 0) {\n    pageKeys = [\n      ...prevState.pageKeys.slice(0, pageIndex),\n      ...completedSplit,\n      ...prevState.pageKeys.slice(pageIndex + 1)\n    ];\n  }\n  return {\n    ...prevState,\n    queries,\n    pageKeys,\n    ongoingSplits\n  };\n};\nexport function usePaginatedQuery(query, args, options) {\n  const { user } = usePaginatedQueryInternal(query, args, options);\n  return user;\n}\nexport const includePage = Symbol(\"includePageKeys\");\nexport const page = Symbol(\"page\");\nexport function usePaginatedQueryInternal(query, args, options) {\n  if (typeof options?.initialNumItems !== \"number\" || options.initialNumItems < 0) {\n    throw new Error(\n      `\\`options.initialNumItems\\` must be a positive number. Received \\`${options?.initialNumItems}\\`.`\n    );\n  }\n  const skip = args === \"skip\";\n  const argsObject = skip ? {} : args;\n  const queryName = getFunctionName(query);\n  const createInitialState = useMemo(() => {\n    return () => {\n      const id = nextPaginationId();\n      return {\n        query,\n        args: argsObject,\n        id,\n        nextPageKey: 1,\n        pageKeys: skip ? [] : [0],\n        queries: skip ? {} : {\n          0: {\n            query,\n            args: {\n              ...argsObject,\n              paginationOpts: {\n                numItems: options.initialNumItems,\n                cursor: null,\n                id\n              }\n            }\n          }\n        },\n        ongoingSplits: {},\n        skip\n      };\n    };\n  }, [\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    JSON.stringify(convexToJson(argsObject)),\n    queryName,\n    options.initialNumItems,\n    skip\n  ]);\n  const [state, setState] = useState(createInitialState);\n  let currState = state;\n  if (getFunctionName(query) !== getFunctionName(state.query) || JSON.stringify(convexToJson(argsObject)) !== JSON.stringify(convexToJson(state.args)) || skip !== state.skip) {\n    currState = createInitialState();\n    setState(currState);\n  }\n  const convexClient = useConvex();\n  const logger = convexClient.logger;\n  const resultsObject = useQueries(currState.queries);\n  const isIncludingPageKeys = options[includePage] ?? false;\n  const [results, maybeLastResult] = useMemo(() => {\n    let currResult = void 0;\n    const allItems = [];\n    for (const pageKey of currState.pageKeys) {\n      currResult = resultsObject[pageKey];\n      if (currResult === void 0) {\n        break;\n      }\n      if (currResult instanceof Error) {\n        if (currResult.message.includes(\"InvalidCursor\") || currResult instanceof ConvexError && typeof currResult.data === \"object\" && currResult.data?.isConvexSystemError === true && currResult.data?.paginationError === \"InvalidCursor\") {\n          logger.warn(\n            \"usePaginatedQuery hit error, resetting pagination state: \" + currResult.message\n          );\n          setState(createInitialState);\n          return [[], void 0];\n        } else {\n          throw currResult;\n        }\n      }\n      const ongoingSplit = currState.ongoingSplits[pageKey];\n      if (ongoingSplit !== void 0) {\n        if (resultsObject[ongoingSplit[0]] !== void 0 && resultsObject[ongoingSplit[1]] !== void 0) {\n          setState(completeSplitQuery(pageKey));\n        }\n      } else if (currResult.splitCursor && (currResult.pageStatus === \"SplitRecommended\" || currResult.pageStatus === \"SplitRequired\" || currResult.page.length > options.initialNumItems * 2)) {\n        setState(\n          splitQuery(\n            pageKey,\n            currResult.splitCursor,\n            currResult.continueCursor\n          )\n        );\n      }\n      if (currResult.pageStatus === \"SplitRequired\") {\n        return [allItems, void 0];\n      }\n      allItems.push(\n        ...isIncludingPageKeys ? currResult.page.map((i) => ({\n          ...i,\n          [page]: pageKey.toString()\n        })) : currResult.page\n      );\n    }\n    return [allItems, currResult];\n  }, [\n    resultsObject,\n    currState.pageKeys,\n    currState.ongoingSplits,\n    options.initialNumItems,\n    createInitialState,\n    logger,\n    isIncludingPageKeys\n  ]);\n  const statusObject = useMemo(() => {\n    if (maybeLastResult === void 0) {\n      if (currState.nextPageKey === 1) {\n        return {\n          status: \"LoadingFirstPage\",\n          isLoading: true,\n          loadMore: (_numItems) => {\n          }\n        };\n      } else {\n        return {\n          status: \"LoadingMore\",\n          isLoading: true,\n          loadMore: (_numItems) => {\n          }\n        };\n      }\n    }\n    if (maybeLastResult.isDone) {\n      return {\n        status: \"Exhausted\",\n        isLoading: false,\n        loadMore: (_numItems) => {\n        }\n      };\n    }\n    const continueCursor = maybeLastResult.continueCursor;\n    let alreadyLoadingMore = false;\n    return {\n      status: \"CanLoadMore\",\n      isLoading: false,\n      loadMore: (numItems) => {\n        if (!alreadyLoadingMore) {\n          alreadyLoadingMore = true;\n          setState((prevState) => {\n            const pageKeys = [...prevState.pageKeys, prevState.nextPageKey];\n            const queries = { ...prevState.queries };\n            queries[prevState.nextPageKey] = {\n              query: prevState.query,\n              args: {\n                ...prevState.args,\n                paginationOpts: {\n                  numItems,\n                  cursor: continueCursor,\n                  id: prevState.id\n                }\n              }\n            };\n            return {\n              ...prevState,\n              nextPageKey: prevState.nextPageKey + 1,\n              pageKeys,\n              queries\n            };\n          });\n        }\n      }\n    };\n  }, [maybeLastResult, currState.nextPageKey]);\n  return {\n    user: {\n      results,\n      ...statusObject\n    },\n    internal: { state: currState }\n  };\n}\nlet paginationId = 0;\nfunction nextPaginationId() {\n  paginationId++;\n  return paginationId;\n}\nexport function resetPaginationId() {\n  paginationId = 0;\n}\nexport function optimisticallyUpdateValueInPaginatedQuery(localStore, query, args, updateValue) {\n  const expectedArgs = JSON.stringify(convexToJson(args));\n  for (const queryResult of localStore.getAllQueries(query)) {\n    if (queryResult.value !== void 0) {\n      const { paginationOpts: _, ...innerArgs } = queryResult.args;\n      if (JSON.stringify(convexToJson(innerArgs)) === expectedArgs) {\n        const value = queryResult.value;\n        if (typeof value === \"object\" && value !== null && Array.isArray(value.page)) {\n          localStore.setQuery(query, queryResult.args, {\n            ...value,\n            page: value.page.map(updateValue)\n          });\n        }\n      }\n    }\n  }\n}\nexport function insertAtTop(options) {\n  const { paginatedQuery, argsToMatch, localQueryStore, item } = options;\n  const queries = localQueryStore.getAllQueries(paginatedQuery);\n  const queriesThatMatch = queries.filter((q) => {\n    if (argsToMatch === void 0) {\n      return true;\n    }\n    return Object.keys(argsToMatch).every(\n      // @ts-expect-error -- This should be safe since both should be plain objects\n      (k) => compareValues(argsToMatch[k], q.args[k]) === 0\n    );\n  });\n  const firstPage = queriesThatMatch.find(\n    (q) => q.args.paginationOpts.cursor === null\n  );\n  if (firstPage === void 0 || firstPage.value === void 0) {\n    return;\n  }\n  localQueryStore.setQuery(paginatedQuery, firstPage.args, {\n    ...firstPage.value,\n    page: [item, ...firstPage.value.page]\n  });\n}\nexport function insertAtBottomIfLoaded(options) {\n  const { paginatedQuery, localQueryStore, item, argsToMatch } = options;\n  const queries = localQueryStore.getAllQueries(paginatedQuery);\n  const queriesThatMatch = queries.filter((q) => {\n    if (argsToMatch === void 0) {\n      return true;\n    }\n    return Object.keys(argsToMatch).every(\n      // @ts-expect-error -- This should be safe since both should be plain objects\n      (k) => compareValues(argsToMatch[k], q.args[k]) === 0\n    );\n  });\n  const lastPage = queriesThatMatch.find(\n    (q) => q.value !== void 0 && q.value.isDone\n  );\n  if (lastPage === void 0) {\n    return;\n  }\n  localQueryStore.setQuery(paginatedQuery, lastPage.args, {\n    ...lastPage.value,\n    page: [...lastPage.value.page, item]\n  });\n}\nexport function insertAtPosition(options) {\n  const {\n    paginatedQuery,\n    sortOrder,\n    sortKeyFromItem,\n    localQueryStore,\n    item,\n    argsToMatch\n  } = options;\n  const queries = localQueryStore.getAllQueries(paginatedQuery);\n  const queryGroups = {};\n  for (const query of queries) {\n    if (argsToMatch !== void 0 && !Object.keys(argsToMatch).every(\n      (k) => (\n        // @ts-ignore why is this not working?\n        argsToMatch[k] === query.args[k]\n      )\n    )) {\n      continue;\n    }\n    const key = JSON.stringify(\n      Object.fromEntries(\n        Object.entries(query.args).map(([k, v]) => [\n          k,\n          k === \"paginationOpts\" ? v.id : v\n        ])\n      )\n    );\n    queryGroups[key] ?? (queryGroups[key] = []);\n    queryGroups[key].push(query);\n  }\n  for (const pageQueries of Object.values(queryGroups)) {\n    insertAtPositionInPages({\n      pageQueries,\n      paginatedQuery,\n      sortOrder,\n      sortKeyFromItem,\n      localQueryStore,\n      item\n    });\n  }\n}\nfunction insertAtPositionInPages(options) {\n  const {\n    pageQueries,\n    sortOrder,\n    sortKeyFromItem,\n    localQueryStore,\n    item,\n    paginatedQuery\n  } = options;\n  const insertedKey = sortKeyFromItem(item);\n  const loadedPages = pageQueries.filter(\n    (q) => q.value !== void 0 && q.value.page.length > 0\n  );\n  const sortedPages = loadedPages.sort((a, b) => {\n    const aKey = sortKeyFromItem(a.value.page[0]);\n    const bKey = sortKeyFromItem(b.value.page[0]);\n    if (sortOrder === \"asc\") {\n      return compareValues(aKey, bKey);\n    } else {\n      return compareValues(bKey, aKey);\n    }\n  });\n  const firstLoadedPage = sortedPages[0];\n  if (firstLoadedPage === void 0) {\n    return;\n  }\n  const firstPageKey = sortKeyFromItem(firstLoadedPage.value.page[0]);\n  const isBeforeFirstPage = sortOrder === \"asc\" ? compareValues(insertedKey, firstPageKey) <= 0 : compareValues(insertedKey, firstPageKey) >= 0;\n  if (isBeforeFirstPage) {\n    if (firstLoadedPage.args.paginationOpts.cursor === null) {\n      localQueryStore.setQuery(paginatedQuery, firstLoadedPage.args, {\n        ...firstLoadedPage.value,\n        page: [item, ...firstLoadedPage.value.page]\n      });\n    } else {\n      return;\n    }\n    return;\n  }\n  const lastLoadedPage = sortedPages[sortedPages.length - 1];\n  if (lastLoadedPage === void 0) {\n    return;\n  }\n  const lastPageKey = sortKeyFromItem(\n    lastLoadedPage.value.page[lastLoadedPage.value.page.length - 1]\n  );\n  const isAfterLastPage = sortOrder === \"asc\" ? compareValues(insertedKey, lastPageKey) >= 0 : compareValues(insertedKey, lastPageKey) <= 0;\n  if (isAfterLastPage) {\n    if (lastLoadedPage.value.isDone) {\n      localQueryStore.setQuery(paginatedQuery, lastLoadedPage.args, {\n        ...lastLoadedPage.value,\n        page: [...lastLoadedPage.value.page, item]\n      });\n    }\n    return;\n  }\n  const successorPageIndex = sortedPages.findIndex(\n    (p) => sortOrder === \"asc\" ? compareValues(sortKeyFromItem(p.value.page[0]), insertedKey) > 0 : compareValues(sortKeyFromItem(p.value.page[0]), insertedKey) < 0\n  );\n  const pageToUpdate = successorPageIndex === -1 ? sortedPages[sortedPages.length - 1] : sortedPages[successorPageIndex - 1];\n  if (pageToUpdate === void 0) {\n    return;\n  }\n  const indexWithinPage = pageToUpdate.value.page.findIndex(\n    (e) => sortOrder === \"asc\" ? compareValues(sortKeyFromItem(e), insertedKey) >= 0 : compareValues(sortKeyFromItem(e), insertedKey) <= 0\n  );\n  const newPage = indexWithinPage === -1 ? [...pageToUpdate.value.page, item] : [\n    ...pageToUpdate.value.page.slice(0, indexWithinPage),\n    item,\n    ...pageToUpdate.value.page.slice(indexWithinPage)\n  ];\n  localQueryStore.setQuery(paginatedQuery, pageToUpdate.args, {\n    ...pageToUpdate.value,\n    page: newPage\n  });\n}\n//# sourceMappingURL=use_paginated_query.js.map\n","\"use strict\";\nimport { useState } from \"react\";\nimport { getFunctionName } from \"../server/api.js\";\nimport { convexToJson } from \"../values/value.js\";\nimport { useQueries } from \"./use_queries.js\";\nimport { ConvexError } from \"../values/errors.js\";\nimport { useConvex } from \"./client.js\";\nexport function usePaginatedQuery_experimental(query, args, options) {\n  if (typeof options?.initialNumItems !== \"number\" || options.initialNumItems < 0) {\n    throw new Error(\n      `\\`options.initialNumItems\\` must be a positive number. Received \\`${options?.initialNumItems}\\`.`\n    );\n  }\n  const skip = args === \"skip\";\n  const argsObject = skip ? {} : args;\n  const convexClient = useConvex();\n  const logger = convexClient.logger;\n  const createInitialState = () => {\n    const id = nextPaginationId();\n    return {\n      query,\n      args: argsObject,\n      id,\n      // Queries will contain zero or one queries forever.\n      queries: skip ? {} : {\n        paginatedQuery: {\n          query,\n          args: {\n            ...argsObject\n          },\n          paginationOptions: {\n            initialNumItems: options.initialNumItems,\n            id\n          }\n        }\n      },\n      skip\n    };\n  };\n  const [state, setState] = useState(createInitialState);\n  let currState = state;\n  if (getFunctionName(query) !== getFunctionName(state.query) || JSON.stringify(convexToJson(argsObject)) !== JSON.stringify(convexToJson(state.args)) || skip !== state.skip) {\n    currState = createInitialState();\n    setState(currState);\n  }\n  const resultsObject = useQueries(currState.queries);\n  if (!(\"paginatedQuery\" in resultsObject)) {\n    if (!skip) {\n      throw new Error(\"Why is it missing?\");\n    }\n    return {\n      results: [],\n      status: \"LoadingFirstPage\",\n      isLoading: true,\n      loadMore: function skipNOP(_numItems) {\n        return false;\n      }\n    };\n  }\n  const result = resultsObject.paginatedQuery;\n  if (result === void 0) {\n    return {\n      results: [],\n      loadMore: () => false,\n      isLoading: true,\n      status: \"LoadingFirstPage\"\n    };\n  }\n  if (result instanceof Error) {\n    if (result.message.includes(\"InvalidCursor\") || result instanceof ConvexError && typeof result.data === \"object\" && result.data?.isConvexSystemError === true && result.data?.paginationError === \"InvalidCursor\") {\n      logger.warn(\n        \"usePaginatedQuery hit error, resetting pagination state: \" + result.message\n      );\n      setState(createInitialState);\n      return {\n        results: [],\n        loadMore: () => false,\n        isLoading: true,\n        status: \"LoadingFirstPage\"\n      };\n    } else {\n      throw result;\n    }\n  }\n  return {\n    ...result,\n    loadMore: (num) => {\n      return result.loadMore(num);\n    },\n    isLoading: result.status === \"LoadingFirstPage\" ? true : result.status === \"LoadingMore\" ? true : false\n  };\n}\nlet paginationId = 0;\nfunction nextPaginationId() {\n  paginationId++;\n  return paginationId;\n}\nexport function resetPaginationId() {\n  paginationId = 0;\n}\n//# sourceMappingURL=use_paginated_query2.js.map\n","\"use strict\";\nimport React, {\n  createContext,\n  useContext,\n  useEffect,\n  useState\n} from \"react\";\nimport { ConvexProvider } from \"./client.js\";\nconst ConvexAuthContext = createContext(void 0);\nexport function useConvexAuth() {\n  const authContext = useContext(ConvexAuthContext);\n  if (authContext === void 0) {\n    throw new Error(\n      \"Could not find `ConvexProviderWithAuth` (or `ConvexProviderWithClerk` or `ConvexProviderWithAuth0`) as an ancestor component. This component may be missing, or you might have two instances of the `convex/react` module loaded in your project.\"\n    );\n  }\n  return authContext;\n}\nexport function ConvexProviderWithAuth({\n  children,\n  client,\n  useAuth\n}) {\n  const {\n    isLoading: authProviderLoading,\n    isAuthenticated: authProviderAuthenticated,\n    fetchAccessToken\n  } = useAuth();\n  const [isConvexAuthenticated, setIsConvexAuthenticated] = useState(null);\n  if (authProviderLoading && isConvexAuthenticated !== null) {\n    setIsConvexAuthenticated(null);\n  }\n  if (!authProviderLoading && !authProviderAuthenticated && isConvexAuthenticated !== false) {\n    setIsConvexAuthenticated(false);\n  }\n  return /* @__PURE__ */ React.createElement(\n    ConvexAuthContext.Provider,\n    {\n      value: {\n        isLoading: isConvexAuthenticated === null,\n        isAuthenticated: authProviderAuthenticated && (isConvexAuthenticated ?? false)\n      }\n    },\n    /* @__PURE__ */ React.createElement(\n      ConvexAuthStateFirstEffect,\n      {\n        authProviderAuthenticated,\n        fetchAccessToken,\n        authProviderLoading,\n        client,\n        setIsConvexAuthenticated\n      }\n    ),\n    /* @__PURE__ */ React.createElement(ConvexProvider, { client }, children),\n    /* @__PURE__ */ React.createElement(\n      ConvexAuthStateLastEffect,\n      {\n        authProviderAuthenticated,\n        fetchAccessToken,\n        authProviderLoading,\n        client,\n        setIsConvexAuthenticated\n      }\n    )\n  );\n}\nfunction ConvexAuthStateFirstEffect({\n  authProviderAuthenticated,\n  fetchAccessToken,\n  authProviderLoading,\n  client,\n  setIsConvexAuthenticated\n}) {\n  useEffect(() => {\n    let isThisEffectRelevant = true;\n    if (authProviderAuthenticated) {\n      client.setAuth(fetchAccessToken, (backendReportsIsAuthenticated) => {\n        if (isThisEffectRelevant) {\n          setIsConvexAuthenticated(() => backendReportsIsAuthenticated);\n        }\n      });\n      return () => {\n        isThisEffectRelevant = false;\n        setIsConvexAuthenticated(\n          (isConvexAuthenticated) => isConvexAuthenticated ? false : null\n        );\n      };\n    }\n  }, [\n    authProviderAuthenticated,\n    fetchAccessToken,\n    authProviderLoading,\n    client,\n    setIsConvexAuthenticated\n  ]);\n  return null;\n}\nfunction ConvexAuthStateLastEffect({\n  authProviderAuthenticated,\n  fetchAccessToken,\n  authProviderLoading,\n  client,\n  setIsConvexAuthenticated\n}) {\n  useEffect(() => {\n    if (authProviderAuthenticated) {\n      return () => {\n        client.clearAuth();\n        setIsConvexAuthenticated(() => null);\n      };\n    }\n  }, [\n    authProviderAuthenticated,\n    fetchAccessToken,\n    authProviderLoading,\n    client,\n    setIsConvexAuthenticated\n  ]);\n  return null;\n}\n//# sourceMappingURL=ConvexAuthState.js.map\n","\"use strict\";\nimport React from \"react\";\nimport { useConvexAuth } from \"./ConvexAuthState.js\";\nexport function Authenticated({ children }) {\n  const { isLoading, isAuthenticated } = useConvexAuth();\n  if (isLoading || !isAuthenticated) {\n    return null;\n  }\n  return /* @__PURE__ */ React.createElement(React.Fragment, null, children);\n}\nexport function Unauthenticated({ children }) {\n  const { isLoading, isAuthenticated } = useConvexAuth();\n  if (isLoading || isAuthenticated) {\n    return null;\n  }\n  return /* @__PURE__ */ React.createElement(React.Fragment, null, children);\n}\nexport function AuthLoading({ children }) {\n  const { isLoading } = useConvexAuth();\n  if (!isLoading) {\n    return null;\n  }\n  return /* @__PURE__ */ React.createElement(React.Fragment, null, children);\n}\n//# sourceMappingURL=auth_helpers.js.map\n","\"use strict\";\nimport { useMemo } from \"react\";\nimport { useQuery } from \"../react/client.js\";\nimport { makeFunctionReference } from \"../server/api.js\";\nimport { jsonToConvex } from \"../values/index.js\";\nexport function usePreloadedQuery(preloadedQuery) {\n  const args = useMemo(\n    () => jsonToConvex(preloadedQuery._argsJSON),\n    [preloadedQuery._argsJSON]\n  );\n  const preloadedResult = useMemo(\n    () => jsonToConvex(preloadedQuery._valueJSON),\n    [preloadedQuery._valueJSON]\n  );\n  const result = useQuery(\n    makeFunctionReference(preloadedQuery._name),\n    args\n  );\n  return result === void 0 ? preloadedResult : result;\n}\n//# sourceMappingURL=hydration.js.map\n","\"use strict\";\nexport * from \"./use_paginated_query.js\";\nexport { usePaginatedQuery_experimental } from \"./use_paginated_query2.js\";\nexport { usePaginatedQuery } from \"./use_paginated_query.js\";\nexport { useQueries } from \"./use_queries.js\";\nexport * from \"./auth_helpers.js\";\nexport * from \"./ConvexAuthState.js\";\nexport * from \"./hydration.js\";\nexport { useSubscription } from \"./use_subscription.js\";\nexport {\n  ConvexReactClient,\n  useConvex,\n  ConvexProvider,\n  useQuery,\n  useMutation,\n  useAction,\n  useConvexConnectionState\n} from \"./client.js\";\n//# sourceMappingURL=index.js.map\n","\"use strict\";\n//# sourceMappingURL=database.js.map\n","\"use strict\";\nimport { ConvexError } from \"../../values/errors.js\";\nimport { jsonToConvex } from \"../../values/value.js\";\nexport function performSyscall(op, arg) {\n  if (typeof Convex === \"undefined\" || Convex.syscall === void 0) {\n    throw new Error(\n      \"The Convex database and auth objects are being used outside of a Convex backend. Did you mean to use `useQuery` or `useMutation` to call a Convex function?\"\n    );\n  }\n  const resultStr = Convex.syscall(op, JSON.stringify(arg));\n  return JSON.parse(resultStr);\n}\nexport async function performAsyncSyscall(op, arg) {\n  if (typeof Convex === \"undefined\" || Convex.asyncSyscall === void 0) {\n    throw new Error(\n      \"The Convex database and auth objects are being used outside of a Convex backend. Did you mean to use `useQuery` or `useMutation` to call a Convex function?\"\n    );\n  }\n  let resultStr;\n  try {\n    resultStr = await Convex.asyncSyscall(op, JSON.stringify(arg));\n  } catch (e) {\n    if (e.data !== void 0) {\n      const rethrown = new ConvexError(e.message);\n      rethrown.data = jsonToConvex(e.data);\n      throw rethrown;\n    }\n    throw new Error(e.message);\n  }\n  return JSON.parse(resultStr);\n}\nexport function performJsSyscall(op, arg) {\n  if (typeof Convex === \"undefined\" || Convex.jsSyscall === void 0) {\n    throw new Error(\n      \"The Convex database and auth objects are being used outside of a Convex backend. Did you mean to use `useQuery` or `useMutation` to call a Convex function?\"\n    );\n  }\n  return Convex.jsSyscall(op, arg);\n}\n//# sourceMappingURL=syscall.js.map\n","\"use strict\";\nimport { convexToJson, jsonToConvex } from \"../../values/index.js\";\nimport { version } from \"../../index.js\";\nimport { performAsyncSyscall } from \"./syscall.js\";\nimport { parseArgs } from \"../../common/index.js\";\nimport { getFunctionAddress } from \"../components/paths.js\";\nfunction syscallArgs(requestId, functionReference, args) {\n  const address = getFunctionAddress(functionReference);\n  return {\n    ...address,\n    args: convexToJson(parseArgs(args)),\n    version,\n    requestId\n  };\n}\nexport function setupActionCalls(requestId) {\n  return {\n    runQuery: async (query, args) => {\n      const result = await performAsyncSyscall(\n        \"1.0/actions/query\",\n        syscallArgs(requestId, query, args)\n      );\n      return jsonToConvex(result);\n    },\n    runMutation: async (mutation, args) => {\n      const result = await performAsyncSyscall(\n        \"1.0/actions/mutation\",\n        syscallArgs(requestId, mutation, args)\n      );\n      return jsonToConvex(result);\n    },\n    runAction: async (action, args) => {\n      const result = await performAsyncSyscall(\n        \"1.0/actions/action\",\n        syscallArgs(requestId, action, args)\n      );\n      return jsonToConvex(result);\n    }\n  };\n}\n//# sourceMappingURL=actions_impl.js.map\n","\"use strict\";\nexport function validateArg(arg, idx, method, argName) {\n  if (arg === void 0) {\n    throw new TypeError(\n      `Must provide arg ${idx} \\`${argName}\\` to \\`${method}\\``\n    );\n  }\n}\nexport function validateArgIsInteger(arg, idx, method, argName) {\n  if (!Number.isInteger(arg)) {\n    throw new TypeError(\n      `Arg ${idx} \\`${argName}\\` to \\`${method}\\` must be an integer`\n    );\n  }\n}\nexport function validateArgIsNonNegativeInteger(arg, idx, method, argName) {\n  if (!Number.isInteger(arg) || arg < 0) {\n    throw new TypeError(\n      `Arg ${idx} \\`${argName}\\` to \\`${method}\\` must be a non-negative integer`\n    );\n  }\n}\n//# sourceMappingURL=validate.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { performAsyncSyscall } from \"./syscall.js\";\nimport { version } from \"../../index.js\";\nimport {\n  FilterExpression\n} from \"../vector_search.js\";\nimport { validateArg } from \"./validate.js\";\nimport { convexOrUndefinedToJson } from \"../../values/value.js\";\nexport function setupActionVectorSearch(requestId) {\n  return async (tableName, indexName, query) => {\n    validateArg(tableName, 1, \"vectorSearch\", \"tableName\");\n    validateArg(indexName, 2, \"vectorSearch\", \"indexName\");\n    validateArg(query, 3, \"vectorSearch\", \"query\");\n    if (!query.vector || !Array.isArray(query.vector) || query.vector.length === 0) {\n      throw Error(\"`vector` must be a non-empty Array in vectorSearch\");\n    }\n    return await new VectorQueryImpl(\n      requestId,\n      tableName + \".\" + indexName,\n      query\n    ).collect();\n  };\n}\nexport class VectorQueryImpl {\n  constructor(requestId, indexName, query) {\n    __publicField(this, \"requestId\");\n    __publicField(this, \"state\");\n    this.requestId = requestId;\n    const filters = query.filter ? serializeExpression(query.filter(filterBuilderImpl)) : null;\n    this.state = {\n      type: \"preparing\",\n      query: {\n        indexName,\n        limit: query.limit,\n        vector: query.vector,\n        expressions: filters\n      }\n    };\n  }\n  async collect() {\n    if (this.state.type === \"consumed\") {\n      throw new Error(\"This query is closed and can't emit any more values.\");\n    }\n    const query = this.state.query;\n    this.state = { type: \"consumed\" };\n    const { results } = await performAsyncSyscall(\"1.0/actions/vectorSearch\", {\n      requestId: this.requestId,\n      version,\n      query\n    });\n    return results;\n  }\n}\nexport class ExpressionImpl extends FilterExpression {\n  constructor(inner) {\n    super();\n    __publicField(this, \"inner\");\n    this.inner = inner;\n  }\n  serialize() {\n    return this.inner;\n  }\n}\nexport function serializeExpression(expr) {\n  if (expr instanceof ExpressionImpl) {\n    return expr.serialize();\n  } else {\n    return { $literal: convexOrUndefinedToJson(expr) };\n  }\n}\nexport const filterBuilderImpl = {\n  //  Comparisons  /////////////////////////////////////////////////////////////\n  eq(fieldName, value) {\n    if (typeof fieldName !== \"string\") {\n      throw new Error(\"The first argument to `q.eq` must be a field name.\");\n    }\n    return new ExpressionImpl({\n      $eq: [\n        serializeExpression(new ExpressionImpl({ $field: fieldName })),\n        serializeExpression(value)\n      ]\n    });\n  },\n  //  Logic  ///////////////////////////////////////////////////////////////////\n  or(...exprs) {\n    return new ExpressionImpl({ $or: exprs.map(serializeExpression) });\n  }\n};\n//# sourceMappingURL=vector_search_impl.js.map\n","\"use strict\";\nimport { performAsyncSyscall } from \"./syscall.js\";\nexport function setupAuth(requestId) {\n  return {\n    getUserIdentity: async () => {\n      return await performAsyncSyscall(\"1.0/getUserIdentity\", {\n        requestId\n      });\n    }\n  };\n}\n//# sourceMappingURL=authentication_impl.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nexport class Expression {\n  /**\n   * @internal\n   */\n  constructor() {\n    // Property for nominal type support.\n    __publicField(this, \"_isExpression\");\n    // Property to distinguish expressions by the type they resolve to.\n    __publicField(this, \"_value\");\n  }\n}\n//# sourceMappingURL=filter_builder.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { convexOrUndefinedToJson } from \"../../values/value.js\";\nimport {\n  Expression\n} from \"../filter_builder.js\";\nexport class ExpressionImpl extends Expression {\n  constructor(inner) {\n    super();\n    __publicField(this, \"inner\");\n    this.inner = inner;\n  }\n  serialize() {\n    return this.inner;\n  }\n}\nexport function serializeExpression(expr) {\n  if (expr instanceof ExpressionImpl) {\n    return expr.serialize();\n  } else {\n    return { $literal: convexOrUndefinedToJson(expr) };\n  }\n}\nexport const filterBuilderImpl = {\n  //  Comparisons  /////////////////////////////////////////////////////////////\n  eq(l, r) {\n    return new ExpressionImpl({\n      $eq: [serializeExpression(l), serializeExpression(r)]\n    });\n  },\n  neq(l, r) {\n    return new ExpressionImpl({\n      $neq: [serializeExpression(l), serializeExpression(r)]\n    });\n  },\n  lt(l, r) {\n    return new ExpressionImpl({\n      $lt: [serializeExpression(l), serializeExpression(r)]\n    });\n  },\n  lte(l, r) {\n    return new ExpressionImpl({\n      $lte: [serializeExpression(l), serializeExpression(r)]\n    });\n  },\n  gt(l, r) {\n    return new ExpressionImpl({\n      $gt: [serializeExpression(l), serializeExpression(r)]\n    });\n  },\n  gte(l, r) {\n    return new ExpressionImpl({\n      $gte: [serializeExpression(l), serializeExpression(r)]\n    });\n  },\n  //  Arithmetic  //////////////////////////////////////////////////////////////\n  add(l, r) {\n    return new ExpressionImpl({\n      $add: [serializeExpression(l), serializeExpression(r)]\n    });\n  },\n  sub(l, r) {\n    return new ExpressionImpl({\n      $sub: [serializeExpression(l), serializeExpression(r)]\n    });\n  },\n  mul(l, r) {\n    return new ExpressionImpl({\n      $mul: [serializeExpression(l), serializeExpression(r)]\n    });\n  },\n  div(l, r) {\n    return new ExpressionImpl({\n      $div: [serializeExpression(l), serializeExpression(r)]\n    });\n  },\n  mod(l, r) {\n    return new ExpressionImpl({\n      $mod: [serializeExpression(l), serializeExpression(r)]\n    });\n  },\n  neg(x) {\n    return new ExpressionImpl({ $neg: serializeExpression(x) });\n  },\n  //  Logic  ///////////////////////////////////////////////////////////////////\n  and(...exprs) {\n    return new ExpressionImpl({ $and: exprs.map(serializeExpression) });\n  },\n  or(...exprs) {\n    return new ExpressionImpl({ $or: exprs.map(serializeExpression) });\n  },\n  not(x) {\n    return new ExpressionImpl({ $not: serializeExpression(x) });\n  },\n  //  Other  ///////////////////////////////////////////////////////////////////\n  field(fieldPath) {\n    return new ExpressionImpl({ $field: fieldPath });\n  }\n};\n//# sourceMappingURL=filter_builder_impl.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nexport class IndexRange {\n  /**\n   * @internal\n   */\n  constructor() {\n    // Property for nominal type support.\n    __publicField(this, \"_isIndexRange\");\n  }\n}\n//# sourceMappingURL=index_range_builder.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { convexOrUndefinedToJson } from \"../../values/value.js\";\nimport {\n  IndexRange\n} from \"../index_range_builder.js\";\nexport class IndexRangeBuilderImpl extends IndexRange {\n  constructor(rangeExpressions) {\n    super();\n    __publicField(this, \"rangeExpressions\");\n    __publicField(this, \"isConsumed\");\n    this.rangeExpressions = rangeExpressions;\n    this.isConsumed = false;\n  }\n  static new() {\n    return new IndexRangeBuilderImpl([]);\n  }\n  consume() {\n    if (this.isConsumed) {\n      throw new Error(\n        \"IndexRangeBuilder has already been used! Chain your method calls like `q => q.eq(...).eq(...)`. See https://docs.convex.dev/using/indexes\"\n      );\n    }\n    this.isConsumed = true;\n  }\n  eq(fieldName, value) {\n    this.consume();\n    return new IndexRangeBuilderImpl(\n      this.rangeExpressions.concat({\n        type: \"Eq\",\n        fieldPath: fieldName,\n        value: convexOrUndefinedToJson(value)\n      })\n    );\n  }\n  gt(fieldName, value) {\n    this.consume();\n    return new IndexRangeBuilderImpl(\n      this.rangeExpressions.concat({\n        type: \"Gt\",\n        fieldPath: fieldName,\n        value: convexOrUndefinedToJson(value)\n      })\n    );\n  }\n  gte(fieldName, value) {\n    this.consume();\n    return new IndexRangeBuilderImpl(\n      this.rangeExpressions.concat({\n        type: \"Gte\",\n        fieldPath: fieldName,\n        value: convexOrUndefinedToJson(value)\n      })\n    );\n  }\n  lt(fieldName, value) {\n    this.consume();\n    return new IndexRangeBuilderImpl(\n      this.rangeExpressions.concat({\n        type: \"Lt\",\n        fieldPath: fieldName,\n        value: convexOrUndefinedToJson(value)\n      })\n    );\n  }\n  lte(fieldName, value) {\n    this.consume();\n    return new IndexRangeBuilderImpl(\n      this.rangeExpressions.concat({\n        type: \"Lte\",\n        fieldPath: fieldName,\n        value: convexOrUndefinedToJson(value)\n      })\n    );\n  }\n  export() {\n    this.consume();\n    return this.rangeExpressions;\n  }\n}\n//# sourceMappingURL=index_range_builder_impl.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nexport class SearchFilter {\n  /**\n   * @internal\n   */\n  constructor() {\n    // Property for nominal type support.\n    __publicField(this, \"_isSearchFilter\");\n  }\n}\n//# sourceMappingURL=search_filter_builder.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { convexOrUndefinedToJson } from \"../../values/value.js\";\nimport {\n  SearchFilter\n} from \"../search_filter_builder.js\";\nimport { validateArg } from \"./validate.js\";\nexport class SearchFilterBuilderImpl extends SearchFilter {\n  constructor(filters) {\n    super();\n    __publicField(this, \"filters\");\n    __publicField(this, \"isConsumed\");\n    this.filters = filters;\n    this.isConsumed = false;\n  }\n  static new() {\n    return new SearchFilterBuilderImpl([]);\n  }\n  consume() {\n    if (this.isConsumed) {\n      throw new Error(\n        \"SearchFilterBuilder has already been used! Chain your method calls like `q => q.search(...).eq(...)`.\"\n      );\n    }\n    this.isConsumed = true;\n  }\n  search(fieldName, query) {\n    validateArg(fieldName, 1, \"search\", \"fieldName\");\n    validateArg(query, 2, \"search\", \"query\");\n    this.consume();\n    return new SearchFilterBuilderImpl(\n      this.filters.concat({\n        type: \"Search\",\n        fieldPath: fieldName,\n        value: query\n      })\n    );\n  }\n  eq(fieldName, value) {\n    validateArg(fieldName, 1, \"eq\", \"fieldName\");\n    if (arguments.length !== 2) {\n      validateArg(value, 2, \"search\", \"value\");\n    }\n    this.consume();\n    return new SearchFilterBuilderImpl(\n      this.filters.concat({\n        type: \"Eq\",\n        fieldPath: fieldName,\n        value: convexOrUndefinedToJson(value)\n      })\n    );\n  }\n  export() {\n    this.consume();\n    return this.filters;\n  }\n}\n//# sourceMappingURL=search_filter_builder_impl.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { jsonToConvex } from \"../../values/index.js\";\nimport { performAsyncSyscall, performSyscall } from \"./syscall.js\";\nimport {\n  filterBuilderImpl,\n  serializeExpression\n} from \"./filter_builder_impl.js\";\nimport {\n  IndexRangeBuilderImpl\n} from \"./index_range_builder_impl.js\";\nimport {\n  SearchFilterBuilderImpl\n} from \"./search_filter_builder_impl.js\";\nimport { validateArg, validateArgIsNonNegativeInteger } from \"./validate.js\";\nimport { version } from \"../../index.js\";\nconst MAX_QUERY_OPERATORS = 256;\nexport class QueryInitializerImpl {\n  constructor(tableName) {\n    __publicField(this, \"tableName\");\n    this.tableName = tableName;\n  }\n  withIndex(indexName, indexRange) {\n    validateArg(indexName, 1, \"withIndex\", \"indexName\");\n    let rangeBuilder = IndexRangeBuilderImpl.new();\n    if (indexRange !== void 0) {\n      rangeBuilder = indexRange(rangeBuilder);\n    }\n    return new QueryImpl({\n      source: {\n        type: \"IndexRange\",\n        indexName: this.tableName + \".\" + indexName,\n        range: rangeBuilder.export(),\n        order: null\n      },\n      operators: []\n    });\n  }\n  withSearchIndex(indexName, searchFilter) {\n    validateArg(indexName, 1, \"withSearchIndex\", \"indexName\");\n    validateArg(searchFilter, 2, \"withSearchIndex\", \"searchFilter\");\n    const searchFilterBuilder = SearchFilterBuilderImpl.new();\n    return new QueryImpl({\n      source: {\n        type: \"Search\",\n        indexName: this.tableName + \".\" + indexName,\n        filters: searchFilter(searchFilterBuilder).export()\n      },\n      operators: []\n    });\n  }\n  fullTableScan() {\n    return new QueryImpl({\n      source: {\n        type: \"FullTableScan\",\n        tableName: this.tableName,\n        order: null\n      },\n      operators: []\n    });\n  }\n  order(order) {\n    return this.fullTableScan().order(order);\n  }\n  // This is internal API and should not be exposed to developers yet.\n  async count() {\n    const syscallJSON = await performAsyncSyscall(\"1.0/count\", {\n      table: this.tableName\n    });\n    const syscallResult = jsonToConvex(syscallJSON);\n    return syscallResult;\n  }\n  filter(predicate) {\n    return this.fullTableScan().filter(predicate);\n  }\n  limit(n) {\n    return this.fullTableScan().limit(n);\n  }\n  collect() {\n    return this.fullTableScan().collect();\n  }\n  take(n) {\n    return this.fullTableScan().take(n);\n  }\n  paginate(paginationOpts) {\n    return this.fullTableScan().paginate(paginationOpts);\n  }\n  first() {\n    return this.fullTableScan().first();\n  }\n  unique() {\n    return this.fullTableScan().unique();\n  }\n  [Symbol.asyncIterator]() {\n    return this.fullTableScan()[Symbol.asyncIterator]();\n  }\n}\nfunction throwClosedError(type) {\n  throw new Error(\n    type === \"consumed\" ? \"This query is closed and can't emit any more values.\" : \"This query has been chained with another operator and can't be reused.\"\n  );\n}\nexport class QueryImpl {\n  constructor(query) {\n    __publicField(this, \"state\");\n    __publicField(this, \"tableNameForErrorMessages\");\n    this.state = { type: \"preparing\", query };\n    if (query.source.type === \"FullTableScan\") {\n      this.tableNameForErrorMessages = query.source.tableName;\n    } else {\n      this.tableNameForErrorMessages = query.source.indexName.split(\".\")[0];\n    }\n  }\n  takeQuery() {\n    if (this.state.type !== \"preparing\") {\n      throw new Error(\n        \"A query can only be chained once and can't be chained after iteration begins.\"\n      );\n    }\n    const query = this.state.query;\n    this.state = { type: \"closed\" };\n    return query;\n  }\n  startQuery() {\n    if (this.state.type === \"executing\") {\n      throw new Error(\"Iteration can only begin on a query once.\");\n    }\n    if (this.state.type === \"closed\" || this.state.type === \"consumed\") {\n      throwClosedError(this.state.type);\n    }\n    const query = this.state.query;\n    const { queryId } = performSyscall(\"1.0/queryStream\", { query, version });\n    this.state = { type: \"executing\", queryId };\n    return queryId;\n  }\n  closeQuery() {\n    if (this.state.type === \"executing\") {\n      const queryId = this.state.queryId;\n      performSyscall(\"1.0/queryCleanup\", { queryId });\n    }\n    this.state = { type: \"consumed\" };\n  }\n  order(order) {\n    validateArg(order, 1, \"order\", \"order\");\n    const query = this.takeQuery();\n    if (query.source.type === \"Search\") {\n      throw new Error(\n        \"Search queries must always be in relevance order. Can not set order manually.\"\n      );\n    }\n    if (query.source.order !== null) {\n      throw new Error(\"Queries may only specify order at most once\");\n    }\n    query.source.order = order;\n    return new QueryImpl(query);\n  }\n  filter(predicate) {\n    validateArg(predicate, 1, \"filter\", \"predicate\");\n    const query = this.takeQuery();\n    if (query.operators.length >= MAX_QUERY_OPERATORS) {\n      throw new Error(\n        `Can't construct query with more than ${MAX_QUERY_OPERATORS} operators`\n      );\n    }\n    query.operators.push({\n      filter: serializeExpression(predicate(filterBuilderImpl))\n    });\n    return new QueryImpl(query);\n  }\n  limit(n) {\n    validateArg(n, 1, \"limit\", \"n\");\n    const query = this.takeQuery();\n    query.operators.push({ limit: n });\n    return new QueryImpl(query);\n  }\n  [Symbol.asyncIterator]() {\n    this.startQuery();\n    return this;\n  }\n  async next() {\n    if (this.state.type === \"closed\" || this.state.type === \"consumed\") {\n      throwClosedError(this.state.type);\n    }\n    const queryId = this.state.type === \"preparing\" ? this.startQuery() : this.state.queryId;\n    const { value, done } = await performAsyncSyscall(\"1.0/queryStreamNext\", {\n      queryId\n    });\n    if (done) {\n      this.closeQuery();\n    }\n    const convexValue = jsonToConvex(value);\n    return { value: convexValue, done };\n  }\n  return() {\n    this.closeQuery();\n    return Promise.resolve({ done: true, value: void 0 });\n  }\n  async paginate(paginationOpts) {\n    validateArg(paginationOpts, 1, \"paginate\", \"options\");\n    if (typeof paginationOpts?.numItems !== \"number\" || paginationOpts.numItems < 0) {\n      throw new Error(\n        `\\`options.numItems\\` must be a positive number. Received \\`${paginationOpts?.numItems}\\`.`\n      );\n    }\n    const query = this.takeQuery();\n    const pageSize = paginationOpts.numItems;\n    const cursor = paginationOpts.cursor;\n    const endCursor = paginationOpts?.endCursor ?? null;\n    const maximumRowsRead = paginationOpts.maximumRowsRead ?? null;\n    const { page, isDone, continueCursor, splitCursor, pageStatus } = await performAsyncSyscall(\"1.0/queryPage\", {\n      query,\n      cursor,\n      endCursor,\n      pageSize,\n      maximumRowsRead,\n      maximumBytesRead: paginationOpts.maximumBytesRead,\n      version\n    });\n    return {\n      page: page.map((json) => jsonToConvex(json)),\n      isDone,\n      continueCursor,\n      splitCursor,\n      pageStatus\n    };\n  }\n  async collect() {\n    const out = [];\n    for await (const item of this) {\n      out.push(item);\n    }\n    return out;\n  }\n  async take(n) {\n    validateArg(n, 1, \"take\", \"n\");\n    validateArgIsNonNegativeInteger(n, 1, \"take\", \"n\");\n    return this.limit(n).collect();\n  }\n  async first() {\n    const first_array = await this.take(1);\n    return first_array.length === 0 ? null : first_array[0];\n  }\n  async unique() {\n    const first_two_array = await this.take(2);\n    if (first_two_array.length === 0) {\n      return null;\n    }\n    if (first_two_array.length === 2) {\n      throw new Error(`unique() query returned more than one result from table ${this.tableNameForErrorMessages}:\n [${first_two_array[0]._id}, ${first_two_array[1]._id}, ...]`);\n    }\n    return first_two_array[0];\n  }\n}\n//# sourceMappingURL=query_impl.js.map\n","\"use strict\";\nimport {\n  convexToJson,\n  jsonToConvex\n} from \"../../values/index.js\";\nimport { performAsyncSyscall, performSyscall } from \"./syscall.js\";\nimport { QueryInitializerImpl } from \"./query_impl.js\";\nimport { validateArg } from \"./validate.js\";\nimport { version } from \"../../index.js\";\nimport { patchValueToJson } from \"../../values/value.js\";\nasync function get(table, id, isSystem) {\n  validateArg(id, 1, \"get\", \"id\");\n  if (typeof id !== \"string\") {\n    throw new Error(\n      `Invalid argument \\`id\\` for \\`db.get\\`, expected string but got '${typeof id}': ${id}`\n    );\n  }\n  const args = {\n    id: convexToJson(id),\n    isSystem,\n    version,\n    table\n  };\n  const syscallJSON = await performAsyncSyscall(\"1.0/get\", args);\n  return jsonToConvex(syscallJSON);\n}\nexport function setupReader() {\n  const reader = (isSystem = false) => {\n    return {\n      get: async (arg0, arg1) => {\n        return arg1 !== void 0 ? await get(arg0, arg1, isSystem) : await get(void 0, arg0, isSystem);\n      },\n      query: (tableName) => {\n        return new TableReader(tableName, isSystem).query();\n      },\n      normalizeId: (tableName, id) => {\n        validateArg(tableName, 1, \"normalizeId\", \"tableName\");\n        validateArg(id, 2, \"normalizeId\", \"id\");\n        const accessingSystemTable = tableName.startsWith(\"_\");\n        if (accessingSystemTable !== isSystem) {\n          throw new Error(\n            `${accessingSystemTable ? \"System\" : \"User\"} tables can only be accessed from db.${isSystem ? \"\" : \"system.\"}normalizeId().`\n          );\n        }\n        const syscallJSON = performSyscall(\"1.0/db/normalizeId\", {\n          table: tableName,\n          idString: id\n        });\n        const syscallResult = jsonToConvex(syscallJSON);\n        return syscallResult.id;\n      },\n      // We set the system reader on the next line\n      system: null,\n      table: (tableName) => {\n        return new TableReader(tableName, isSystem);\n      }\n    };\n  };\n  const { system: _, ...rest } = reader(true);\n  const r = reader();\n  r.system = rest;\n  return r;\n}\nasync function insert(tableName, value) {\n  if (tableName.startsWith(\"_\")) {\n    throw new Error(\"System tables (prefixed with `_`) are read-only.\");\n  }\n  validateArg(tableName, 1, \"insert\", \"table\");\n  validateArg(value, 2, \"insert\", \"value\");\n  const syscallJSON = await performAsyncSyscall(\"1.0/insert\", {\n    table: tableName,\n    value: convexToJson(value)\n  });\n  const syscallResult = jsonToConvex(syscallJSON);\n  return syscallResult._id;\n}\nasync function patch(table, id, value) {\n  validateArg(id, 1, \"patch\", \"id\");\n  validateArg(value, 2, \"patch\", \"value\");\n  await performAsyncSyscall(\"1.0/shallowMerge\", {\n    id: convexToJson(id),\n    value: patchValueToJson(value),\n    table\n  });\n}\nasync function replace(table, id, value) {\n  validateArg(id, 1, \"replace\", \"id\");\n  validateArg(value, 2, \"replace\", \"value\");\n  await performAsyncSyscall(\"1.0/replace\", {\n    id: convexToJson(id),\n    value: convexToJson(value),\n    table\n  });\n}\nasync function delete_(table, id) {\n  validateArg(id, 1, \"delete\", \"id\");\n  await performAsyncSyscall(\"1.0/remove\", {\n    id: convexToJson(id),\n    table\n  });\n}\nexport function setupWriter() {\n  const reader = setupReader();\n  return {\n    get: reader.get,\n    query: reader.query,\n    normalizeId: reader.normalizeId,\n    system: reader.system,\n    insert: async (table, value) => {\n      return await insert(table, value);\n    },\n    patch: async (arg0, arg1, arg2) => {\n      return arg2 !== void 0 ? await patch(arg0, arg1, arg2) : await patch(void 0, arg0, arg1);\n    },\n    replace: async (arg0, arg1, arg2) => {\n      return arg2 !== void 0 ? await replace(arg0, arg1, arg2) : await replace(void 0, arg0, arg1);\n    },\n    delete: async (arg0, arg1) => {\n      return arg1 !== void 0 ? await delete_(arg0, arg1) : await delete_(void 0, arg0);\n    },\n    table: (tableName) => {\n      return new TableWriter(tableName, false);\n    }\n  };\n}\nclass TableReader {\n  constructor(tableName, isSystem) {\n    this.tableName = tableName;\n    this.isSystem = isSystem;\n  }\n  async get(id) {\n    return get(this.tableName, id, this.isSystem);\n  }\n  query() {\n    const accessingSystemTable = this.tableName.startsWith(\"_\");\n    if (accessingSystemTable !== this.isSystem) {\n      throw new Error(\n        `${accessingSystemTable ? \"System\" : \"User\"} tables can only be accessed from db.${this.isSystem ? \"\" : \"system.\"}query().`\n      );\n    }\n    return new QueryInitializerImpl(this.tableName);\n  }\n}\nclass TableWriter extends TableReader {\n  async insert(value) {\n    return insert(this.tableName, value);\n  }\n  async patch(id, value) {\n    return patch(this.tableName, id, value);\n  }\n  async replace(id, value) {\n    return replace(this.tableName, id, value);\n  }\n  async delete(id) {\n    return delete_(this.tableName, id);\n  }\n}\n//# sourceMappingURL=database_impl.js.map\n","\"use strict\";\nimport { convexToJson } from \"../../values/index.js\";\nimport { version } from \"../../index.js\";\nimport { performAsyncSyscall } from \"./syscall.js\";\nimport { parseArgs } from \"../../common/index.js\";\nimport { validateArg } from \"./validate.js\";\nimport { getFunctionAddress } from \"../components/paths.js\";\nexport function setupMutationScheduler() {\n  return {\n    runAfter: async (delayMs, functionReference, args) => {\n      const syscallArgs = runAfterSyscallArgs(delayMs, functionReference, args);\n      return await performAsyncSyscall(\"1.0/schedule\", syscallArgs);\n    },\n    runAt: async (ms_since_epoch_or_date, functionReference, args) => {\n      const syscallArgs = runAtSyscallArgs(\n        ms_since_epoch_or_date,\n        functionReference,\n        args\n      );\n      return await performAsyncSyscall(\"1.0/schedule\", syscallArgs);\n    },\n    cancel: async (id) => {\n      validateArg(id, 1, \"cancel\", \"id\");\n      const args = { id: convexToJson(id) };\n      await performAsyncSyscall(\"1.0/cancel_job\", args);\n    }\n  };\n}\nexport function setupActionScheduler(requestId) {\n  return {\n    runAfter: async (delayMs, functionReference, args) => {\n      const syscallArgs = {\n        requestId,\n        ...runAfterSyscallArgs(delayMs, functionReference, args)\n      };\n      return await performAsyncSyscall(\"1.0/actions/schedule\", syscallArgs);\n    },\n    runAt: async (ms_since_epoch_or_date, functionReference, args) => {\n      const syscallArgs = {\n        requestId,\n        ...runAtSyscallArgs(ms_since_epoch_or_date, functionReference, args)\n      };\n      return await performAsyncSyscall(\"1.0/actions/schedule\", syscallArgs);\n    },\n    cancel: async (id) => {\n      validateArg(id, 1, \"cancel\", \"id\");\n      const syscallArgs = { id: convexToJson(id) };\n      return await performAsyncSyscall(\"1.0/actions/cancel_job\", syscallArgs);\n    }\n  };\n}\nfunction runAfterSyscallArgs(delayMs, functionReference, args) {\n  if (typeof delayMs !== \"number\") {\n    throw new Error(\"`delayMs` must be a number\");\n  }\n  if (!isFinite(delayMs)) {\n    throw new Error(\"`delayMs` must be a finite number\");\n  }\n  if (delayMs < 0) {\n    throw new Error(\"`delayMs` must be non-negative\");\n  }\n  const functionArgs = parseArgs(args);\n  const address = getFunctionAddress(functionReference);\n  const ts = (Date.now() + delayMs) / 1e3;\n  return {\n    ...address,\n    ts,\n    args: convexToJson(functionArgs),\n    version\n  };\n}\nfunction runAtSyscallArgs(ms_since_epoch_or_date, functionReference, args) {\n  let ts;\n  if (ms_since_epoch_or_date instanceof Date) {\n    ts = ms_since_epoch_or_date.valueOf() / 1e3;\n  } else if (typeof ms_since_epoch_or_date === \"number\") {\n    ts = ms_since_epoch_or_date / 1e3;\n  } else {\n    throw new Error(\"The invoke time must a Date or a timestamp\");\n  }\n  const address = getFunctionAddress(functionReference);\n  const functionArgs = parseArgs(args);\n  return {\n    ...address,\n    ts,\n    args: convexToJson(functionArgs),\n    version\n  };\n}\n//# sourceMappingURL=scheduler_impl.js.map\n","\"use strict\";\nimport { version } from \"../../index.js\";\nimport { performAsyncSyscall, performJsSyscall } from \"./syscall.js\";\nimport { validateArg } from \"./validate.js\";\nexport function setupStorageReader(requestId) {\n  return {\n    getUrl: async (storageId) => {\n      validateArg(storageId, 1, \"getUrl\", \"storageId\");\n      return await performAsyncSyscall(\"1.0/storageGetUrl\", {\n        requestId,\n        version,\n        storageId\n      });\n    },\n    getMetadata: async (storageId) => {\n      return await performAsyncSyscall(\"1.0/storageGetMetadata\", {\n        requestId,\n        version,\n        storageId\n      });\n    }\n  };\n}\nexport function setupStorageWriter(requestId) {\n  const reader = setupStorageReader(requestId);\n  return {\n    generateUploadUrl: async () => {\n      return await performAsyncSyscall(\"1.0/storageGenerateUploadUrl\", {\n        requestId,\n        version\n      });\n    },\n    delete: async (storageId) => {\n      await performAsyncSyscall(\"1.0/storageDelete\", {\n        requestId,\n        version,\n        storageId\n      });\n    },\n    getUrl: reader.getUrl,\n    getMetadata: reader.getMetadata\n  };\n}\nexport function setupStorageActionWriter(requestId) {\n  const writer = setupStorageWriter(requestId);\n  return {\n    ...writer,\n    store: async (blob, options) => {\n      return await performJsSyscall(\"storage/storeBlob\", {\n        requestId,\n        version,\n        blob,\n        options\n      });\n    },\n    get: async (storageId) => {\n      return await performJsSyscall(\"storage/getBlob\", {\n        requestId,\n        version,\n        storageId\n      });\n    }\n  };\n}\n//# sourceMappingURL=storage_impl.js.map\n","\"use strict\";\nimport {\n  convexToJson,\n  jsonToConvex,\n  v\n} from \"../../values/index.js\";\nimport { setupActionCalls } from \"./actions_impl.js\";\nimport { setupActionVectorSearch } from \"./vector_search_impl.js\";\nimport { setupAuth } from \"./authentication_impl.js\";\nimport { setupReader, setupWriter } from \"./database_impl.js\";\nimport { QueryImpl, QueryInitializerImpl } from \"./query_impl.js\";\nimport {\n  setupActionScheduler,\n  setupMutationScheduler\n} from \"./scheduler_impl.js\";\nimport {\n  setupStorageActionWriter,\n  setupStorageReader,\n  setupStorageWriter\n} from \"./storage_impl.js\";\nimport { parseArgs } from \"../../common/index.js\";\nimport { performAsyncSyscall } from \"./syscall.js\";\nimport { asObjectValidator } from \"../../values/validator.js\";\nimport { getFunctionAddress } from \"../components/paths.js\";\nasync function invokeMutation(func, argsStr) {\n  const requestId = \"\";\n  const args = jsonToConvex(JSON.parse(argsStr));\n  const mutationCtx = {\n    db: setupWriter(),\n    auth: setupAuth(requestId),\n    storage: setupStorageWriter(requestId),\n    scheduler: setupMutationScheduler(),\n    runQuery: (reference, args2) => runUdf(\"query\", reference, args2),\n    runMutation: (reference, args2) => runUdf(\"mutation\", reference, args2)\n  };\n  const result = await invokeFunction(func, mutationCtx, args);\n  validateReturnValue(result);\n  return JSON.stringify(convexToJson(result === void 0 ? null : result));\n}\nexport function validateReturnValue(v2) {\n  if (v2 instanceof QueryInitializerImpl || v2 instanceof QueryImpl) {\n    throw new Error(\n      \"Return value is a Query. Results must be retrieved with `.collect()`, `.take(n), `.unique()`, or `.first()`.\"\n    );\n  }\n}\nexport async function invokeFunction(func, ctx, args) {\n  let result;\n  try {\n    result = await Promise.resolve(func(ctx, ...args));\n  } catch (thrown) {\n    throw serializeConvexErrorData(thrown);\n  }\n  return result;\n}\nfunction dontCallDirectly(funcType, handler) {\n  return (ctx, args) => {\n    globalThis.console.warn(\n      `Convex functions should not directly call other Convex functions. Consider calling a helper function instead. e.g. \\`export const foo = ${funcType}(...); await foo(ctx);\\` is not supported. See https://docs.convex.dev/production/best-practices/#use-helper-functions-to-write-shared-code`\n    );\n    return handler(ctx, args);\n  };\n}\nfunction serializeConvexErrorData(thrown) {\n  if (typeof thrown === \"object\" && thrown !== null && Symbol.for(\"ConvexError\") in thrown) {\n    const error = thrown;\n    error.data = JSON.stringify(\n      convexToJson(error.data === void 0 ? null : error.data)\n    );\n    error.ConvexErrorSymbol = Symbol.for(\"ConvexError\");\n    return error;\n  } else {\n    return thrown;\n  }\n}\nfunction assertNotBrowser() {\n  if (typeof window === \"undefined\" || window.__convexAllowFunctionsInBrowser) {\n    return;\n  }\n  const isRealBrowser = Object.getOwnPropertyDescriptor(globalThis, \"window\")?.get?.toString().includes(\"[native code]\") ?? false;\n  if (isRealBrowser) {\n    console.error(\n      \"Convex functions should not be imported in the browser. This will throw an error in future versions of `convex`. If this is a false negative, please report it to Convex support.\"\n    );\n  }\n}\nfunction strictReplacer(key, value) {\n  if (value === void 0) {\n    throw new Error(\n      `A validator is undefined for field \"${key}\". This is often caused by circular imports. See https://docs.convex.dev/error#undefined-validator for details.`\n    );\n  }\n  return value;\n}\nfunction exportArgs(functionDefinition) {\n  return () => {\n    let args = v.any();\n    if (typeof functionDefinition === \"object\" && functionDefinition.args !== void 0) {\n      args = asObjectValidator(functionDefinition.args);\n    }\n    return JSON.stringify(args.json, strictReplacer);\n  };\n}\nfunction exportReturns(functionDefinition) {\n  return () => {\n    let returns;\n    if (typeof functionDefinition === \"object\" && functionDefinition.returns !== void 0) {\n      returns = asObjectValidator(functionDefinition.returns);\n    }\n    return JSON.stringify(returns ? returns.json : null, strictReplacer);\n  };\n}\nexport const mutationGeneric = ((functionDefinition) => {\n  const handler = typeof functionDefinition === \"function\" ? functionDefinition : functionDefinition.handler;\n  const func = dontCallDirectly(\"mutation\", handler);\n  assertNotBrowser();\n  func.isMutation = true;\n  func.isPublic = true;\n  func.invokeMutation = (argsStr) => invokeMutation(handler, argsStr);\n  func.exportArgs = exportArgs(functionDefinition);\n  func.exportReturns = exportReturns(functionDefinition);\n  func._handler = handler;\n  return func;\n});\nexport const internalMutationGeneric = ((functionDefinition) => {\n  const handler = typeof functionDefinition === \"function\" ? functionDefinition : functionDefinition.handler;\n  const func = dontCallDirectly(\n    \"internalMutation\",\n    handler\n  );\n  assertNotBrowser();\n  func.isMutation = true;\n  func.isInternal = true;\n  func.invokeMutation = (argsStr) => invokeMutation(handler, argsStr);\n  func.exportArgs = exportArgs(functionDefinition);\n  func.exportReturns = exportReturns(functionDefinition);\n  func._handler = handler;\n  return func;\n});\nasync function invokeQuery(func, argsStr) {\n  const requestId = \"\";\n  const args = jsonToConvex(JSON.parse(argsStr));\n  const queryCtx = {\n    db: setupReader(),\n    auth: setupAuth(requestId),\n    storage: setupStorageReader(requestId),\n    runQuery: (reference, args2) => runUdf(\"query\", reference, args2)\n  };\n  const result = await invokeFunction(func, queryCtx, args);\n  validateReturnValue(result);\n  return JSON.stringify(convexToJson(result === void 0 ? null : result));\n}\nexport const queryGeneric = ((functionDefinition) => {\n  const handler = typeof functionDefinition === \"function\" ? functionDefinition : functionDefinition.handler;\n  const func = dontCallDirectly(\"query\", handler);\n  assertNotBrowser();\n  func.isQuery = true;\n  func.isPublic = true;\n  func.invokeQuery = (argsStr) => invokeQuery(handler, argsStr);\n  func.exportArgs = exportArgs(functionDefinition);\n  func.exportReturns = exportReturns(functionDefinition);\n  func._handler = handler;\n  return func;\n});\nexport const internalQueryGeneric = ((functionDefinition) => {\n  const handler = typeof functionDefinition === \"function\" ? functionDefinition : functionDefinition.handler;\n  const func = dontCallDirectly(\"internalQuery\", handler);\n  assertNotBrowser();\n  func.isQuery = true;\n  func.isInternal = true;\n  func.invokeQuery = (argsStr) => invokeQuery(handler, argsStr);\n  func.exportArgs = exportArgs(functionDefinition);\n  func.exportReturns = exportReturns(functionDefinition);\n  func._handler = handler;\n  return func;\n});\nasync function invokeAction(func, requestId, argsStr) {\n  const args = jsonToConvex(JSON.parse(argsStr));\n  const calls = setupActionCalls(requestId);\n  const ctx = {\n    ...calls,\n    auth: setupAuth(requestId),\n    scheduler: setupActionScheduler(requestId),\n    storage: setupStorageActionWriter(requestId),\n    vectorSearch: setupActionVectorSearch(requestId)\n  };\n  const result = await invokeFunction(func, ctx, args);\n  return JSON.stringify(convexToJson(result === void 0 ? null : result));\n}\nexport const actionGeneric = ((functionDefinition) => {\n  const handler = typeof functionDefinition === \"function\" ? functionDefinition : functionDefinition.handler;\n  const func = dontCallDirectly(\"action\", handler);\n  assertNotBrowser();\n  func.isAction = true;\n  func.isPublic = true;\n  func.invokeAction = (requestId, argsStr) => invokeAction(handler, requestId, argsStr);\n  func.exportArgs = exportArgs(functionDefinition);\n  func.exportReturns = exportReturns(functionDefinition);\n  func._handler = handler;\n  return func;\n});\nexport const internalActionGeneric = ((functionDefinition) => {\n  const handler = typeof functionDefinition === \"function\" ? functionDefinition : functionDefinition.handler;\n  const func = dontCallDirectly(\"internalAction\", handler);\n  assertNotBrowser();\n  func.isAction = true;\n  func.isInternal = true;\n  func.invokeAction = (requestId, argsStr) => invokeAction(handler, requestId, argsStr);\n  func.exportArgs = exportArgs(functionDefinition);\n  func.exportReturns = exportReturns(functionDefinition);\n  func._handler = handler;\n  return func;\n});\nasync function invokeHttpAction(func, request) {\n  const requestId = \"\";\n  const calls = setupActionCalls(requestId);\n  const ctx = {\n    ...calls,\n    auth: setupAuth(requestId),\n    storage: setupStorageActionWriter(requestId),\n    scheduler: setupActionScheduler(requestId),\n    vectorSearch: setupActionVectorSearch(requestId)\n  };\n  return await invokeFunction(func, ctx, [request]);\n}\nexport const httpActionGeneric = (func) => {\n  const q = dontCallDirectly(\"httpAction\", func);\n  assertNotBrowser();\n  q.isHttp = true;\n  q.invokeHttpAction = (request) => invokeHttpAction(func, request);\n  q._handler = func;\n  return q;\n};\nasync function runUdf(udfType, f, args) {\n  const queryArgs = parseArgs(args);\n  const syscallArgs = {\n    udfType,\n    args: convexToJson(queryArgs),\n    ...getFunctionAddress(f)\n  };\n  const result = await performAsyncSyscall(\"1.0/runUdf\", syscallArgs);\n  return jsonToConvex(result);\n}\n//# sourceMappingURL=registration_impl.js.map\n","\"use strict\";\nimport { v } from \"../values/validator.js\";\nexport const paginationOptsValidator = v.object({\n  numItems: v.number(),\n  cursor: v.union(v.string(), v.null()),\n  endCursor: v.optional(v.union(v.string(), v.null())),\n  id: v.optional(v.number()),\n  maximumRowsRead: v.optional(v.number()),\n  maximumBytesRead: v.optional(v.number())\n});\nexport function paginationResultValidator(itemValidator) {\n  return v.object({\n    page: v.array(itemValidator),\n    continueCursor: v.string(),\n    isDone: v.boolean(),\n    splitCursor: v.optional(v.union(v.string(), v.null())),\n    pageStatus: v.optional(\n      v.union(\n        v.literal(\"SplitRecommended\"),\n        v.literal(\"SplitRequired\"),\n        v.null()\n      )\n    )\n  });\n}\n//# sourceMappingURL=pagination.js.map\n","\"use strict\";\n//# sourceMappingURL=storage.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { getFunctionName } from \"../server/api.js\";\nimport { parseArgs } from \"../common/index.js\";\nimport { convexToJson } from \"../values/index.js\";\nconst DAYS_OF_WEEK = [\n  \"sunday\",\n  \"monday\",\n  \"tuesday\",\n  \"wednesday\",\n  \"thursday\",\n  \"friday\",\n  \"saturday\"\n];\nexport const cronJobs = () => new Crons();\nfunction validateIntervalNumber(n) {\n  if (!Number.isInteger(n) || n <= 0) {\n    throw new Error(\"Interval must be an integer greater than 0\");\n  }\n}\nfunction validatedDayOfMonth(n) {\n  if (!Number.isInteger(n) || n < 1 || n > 31) {\n    throw new Error(\"Day of month must be an integer from 1 to 31\");\n  }\n  return n;\n}\nfunction validatedDayOfWeek(s) {\n  if (!DAYS_OF_WEEK.includes(s)) {\n    throw new Error('Day of week must be a string like \"monday\".');\n  }\n  return s;\n}\nfunction validatedHourOfDay(n) {\n  if (!Number.isInteger(n) || n < 0 || n > 23) {\n    throw new Error(\"Hour of day must be an integer from 0 to 23\");\n  }\n  return n;\n}\nfunction validatedMinuteOfHour(n) {\n  if (!Number.isInteger(n) || n < 0 || n > 59) {\n    throw new Error(\"Minute of hour must be an integer from 0 to 59\");\n  }\n  return n;\n}\nfunction validatedCronString(s) {\n  return s;\n}\nfunction validatedCronIdentifier(s) {\n  if (!s.match(/^[ -~]*$/)) {\n    throw new Error(\n      `Invalid cron identifier ${s}: use ASCII letters that are not control characters`\n    );\n  }\n  return s;\n}\nexport class Crons {\n  constructor() {\n    __publicField(this, \"crons\");\n    __publicField(this, \"isCrons\");\n    this.isCrons = true;\n    this.crons = {};\n  }\n  /** @internal */\n  schedule(cronIdentifier, schedule, functionReference, args) {\n    const cronArgs = parseArgs(args);\n    validatedCronIdentifier(cronIdentifier);\n    if (cronIdentifier in this.crons) {\n      throw new Error(`Cron identifier registered twice: ${cronIdentifier}`);\n    }\n    this.crons[cronIdentifier] = {\n      name: getFunctionName(functionReference),\n      args: [convexToJson(cronArgs)],\n      schedule\n    };\n  }\n  /**\n   * Schedule a mutation or action to run at some interval.\n   *\n   * ```js\n   * crons.interval(\"Clear presence data\", {seconds: 30}, api.presence.clear);\n   * ```\n   *\n   * @param identifier - A unique name for this scheduled job.\n   * @param schedule - The time between runs for this scheduled job.\n   * @param functionReference - A {@link FunctionReference} for the function\n   * to schedule.\n   * @param args - The arguments to the function.\n   */\n  interval(cronIdentifier, schedule, functionReference, ...args) {\n    const s = schedule;\n    const hasSeconds = +(\"seconds\" in s && s.seconds !== void 0);\n    const hasMinutes = +(\"minutes\" in s && s.minutes !== void 0);\n    const hasHours = +(\"hours\" in s && s.hours !== void 0);\n    const total = hasSeconds + hasMinutes + hasHours;\n    if (total !== 1) {\n      throw new Error(\"Must specify one of seconds, minutes, or hours\");\n    }\n    if (hasSeconds) {\n      validateIntervalNumber(schedule.seconds);\n    } else if (hasMinutes) {\n      validateIntervalNumber(schedule.minutes);\n    } else if (hasHours) {\n      validateIntervalNumber(schedule.hours);\n    }\n    this.schedule(\n      cronIdentifier,\n      { ...schedule, type: \"interval\" },\n      functionReference,\n      ...args\n    );\n  }\n  /**\n   * Schedule a mutation or action to run on an hourly basis.\n   *\n   * ```js\n   * crons.hourly(\n   *   \"Reset high scores\",\n   *   {\n   *     minuteUTC: 30,\n   *   },\n   *   api.scores.reset\n   * )\n   * ```\n   *\n   * @param cronIdentifier - A unique name for this scheduled job.\n   * @param schedule - What time (UTC) each day to run this function.\n   * @param functionReference - A {@link FunctionReference} for the function\n   * to schedule.\n   * @param args - The arguments to the function.\n   */\n  hourly(cronIdentifier, schedule, functionReference, ...args) {\n    const minuteUTC = validatedMinuteOfHour(schedule.minuteUTC);\n    this.schedule(\n      cronIdentifier,\n      { minuteUTC, type: \"hourly\" },\n      functionReference,\n      ...args\n    );\n  }\n  /**\n   * Schedule a mutation or action to run on a daily basis.\n   *\n   * ```js\n   * crons.daily(\n   *   \"Reset high scores\",\n   *   {\n   *     hourUTC: 17, // (9:30am Pacific/10:30am Daylight Savings Pacific)\n   *     minuteUTC: 30,\n   *   },\n   *   api.scores.reset\n   * )\n   * ```\n   *\n   * @param cronIdentifier - A unique name for this scheduled job.\n   * @param schedule - What time (UTC) each day to run this function.\n   * @param functionReference - A {@link FunctionReference} for the function\n   * to schedule.\n   * @param args - The arguments to the function.\n   */\n  daily(cronIdentifier, schedule, functionReference, ...args) {\n    const hourUTC = validatedHourOfDay(schedule.hourUTC);\n    const minuteUTC = validatedMinuteOfHour(schedule.minuteUTC);\n    this.schedule(\n      cronIdentifier,\n      { hourUTC, minuteUTC, type: \"daily\" },\n      functionReference,\n      ...args\n    );\n  }\n  /**\n   * Schedule a mutation or action to run on a weekly basis.\n   *\n   * ```js\n   * crons.weekly(\n   *   \"Weekly re-engagement email\",\n   *   {\n   *     dayOfWeek: \"Tuesday\",\n   *     hourUTC: 17, // (9:30am Pacific/10:30am Daylight Savings Pacific)\n   *     minuteUTC: 30,\n   *   },\n   *   api.emails.send\n   * )\n   * ```\n   *\n   * @param cronIdentifier - A unique name for this scheduled job.\n   * @param schedule - What day and time (UTC) each week to run this function.\n   * @param functionReference - A {@link FunctionReference} for the function\n   * to schedule.\n   */\n  weekly(cronIdentifier, schedule, functionReference, ...args) {\n    const dayOfWeek = validatedDayOfWeek(schedule.dayOfWeek);\n    const hourUTC = validatedHourOfDay(schedule.hourUTC);\n    const minuteUTC = validatedMinuteOfHour(schedule.minuteUTC);\n    this.schedule(\n      cronIdentifier,\n      { dayOfWeek, hourUTC, minuteUTC, type: \"weekly\" },\n      functionReference,\n      ...args\n    );\n  }\n  /**\n   * Schedule a mutation or action to run on a monthly basis.\n   *\n   * Note that some months have fewer days than others, so e.g. a function\n   * scheduled to run on the 30th will not run in February.\n   *\n   * ```js\n   * crons.monthly(\n   *   \"Bill customers at \",\n   *   {\n   *     hourUTC: 17, // (9:30am Pacific/10:30am Daylight Savings Pacific)\n   *     minuteUTC: 30,\n   *     day: 1,\n   *   },\n   *   api.billing.billCustomers\n   * )\n   * ```\n   *\n   * @param cronIdentifier - A unique name for this scheduled job.\n   * @param schedule - What day and time (UTC) each month to run this function.\n   * @param functionReference - A {@link FunctionReference} for the function\n   * to schedule.\n   * @param args - The arguments to the function.\n   */\n  monthly(cronIdentifier, schedule, functionReference, ...args) {\n    const day = validatedDayOfMonth(schedule.day);\n    const hourUTC = validatedHourOfDay(schedule.hourUTC);\n    const minuteUTC = validatedMinuteOfHour(schedule.minuteUTC);\n    this.schedule(\n      cronIdentifier,\n      { day, hourUTC, minuteUTC, type: \"monthly\" },\n      functionReference,\n      ...args\n    );\n  }\n  /**\n   * Schedule a mutation or action to run on a recurring basis.\n   *\n   * Like the unix command `cron`, Sunday is 0, Monday is 1, etc.\n   *\n   * ```\n   *  ┌─ minute (0 - 59)\n   *  │ ┌─ hour (0 - 23)\n   *  │ │ ┌─ day of the month (1 - 31)\n   *  │ │ │ ┌─ month (1 - 12)\n   *  │ │ │ │ ┌─ day of the week (0 - 6) (Sunday to Saturday)\n   * \"* * * * *\"\n   * ```\n   *\n   * @param cronIdentifier - A unique name for this scheduled job.\n   * @param cron - Cron string like `\"15 7 * * *\"` (Every day at 7:15 UTC)\n   * @param functionReference - A {@link FunctionReference} for the function\n   * to schedule.\n   * @param args - The arguments to the function.\n   */\n  cron(cronIdentifier, cron, functionReference, ...args) {\n    const c = validatedCronString(cron);\n    this.schedule(\n      cronIdentifier,\n      { cron: c, type: \"cron\" },\n      functionReference,\n      ...args\n    );\n  }\n  /** @internal */\n  export() {\n    return JSON.stringify(this.crons);\n  }\n}\n//# sourceMappingURL=cron.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { performJsSyscall } from \"./impl/syscall.js\";\nexport const ROUTABLE_HTTP_METHODS = [\n  \"GET\",\n  \"POST\",\n  \"PUT\",\n  \"DELETE\",\n  \"OPTIONS\",\n  \"PATCH\"\n];\nexport function normalizeMethod(method) {\n  if (method === \"HEAD\") return \"GET\";\n  return method;\n}\nexport const httpRouter = () => new HttpRouter();\nexport class HttpRouter {\n  constructor() {\n    __publicField(this, \"exactRoutes\", /* @__PURE__ */ new Map());\n    __publicField(this, \"prefixRoutes\", /* @__PURE__ */ new Map());\n    __publicField(this, \"isRouter\", true);\n    /**\n     * Specify an HttpAction to be used to respond to requests\n     * for an HTTP method (e.g. \"GET\") and a path or pathPrefix.\n     *\n     * Paths must begin with a slash. Path prefixes must also end in a slash.\n     *\n     * ```js\n     * // matches `/profile` (but not `/profile/`)\n     * http.route({ path: \"/profile\", method: \"GET\", handler: getProfile})\n     *\n     * // matches `/profiles/`, `/profiles/abc`, and `/profiles/a/c/b` (but not `/profile`)\n     * http.route({ pathPrefix: \"/profile/\", method: \"GET\", handler: getProfile})\n     * ```\n     */\n    __publicField(this, \"route\", (spec) => {\n      if (!spec.handler) throw new Error(`route requires handler`);\n      if (!spec.method) throw new Error(`route requires method`);\n      const { method, handler } = spec;\n      if (!ROUTABLE_HTTP_METHODS.includes(method)) {\n        throw new Error(\n          `'${method}' is not an allowed HTTP method (like GET, POST, PUT etc.)`\n        );\n      }\n      if (\"path\" in spec) {\n        if (\"pathPrefix\" in spec) {\n          throw new Error(\n            `Invalid httpRouter route: cannot contain both 'path' and 'pathPrefix'`\n          );\n        }\n        if (!spec.path.startsWith(\"/\")) {\n          throw new Error(`path '${spec.path}' does not start with a /`);\n        }\n        if (spec.path.startsWith(\"/.files/\") || spec.path === \"/.files\") {\n          throw new Error(`path '${spec.path}' is reserved`);\n        }\n        const methods = this.exactRoutes.has(spec.path) ? this.exactRoutes.get(spec.path) : /* @__PURE__ */ new Map();\n        if (methods.has(method)) {\n          throw new Error(\n            `Path '${spec.path}' for method ${method} already in use`\n          );\n        }\n        methods.set(method, handler);\n        this.exactRoutes.set(spec.path, methods);\n      } else if (\"pathPrefix\" in spec) {\n        if (!spec.pathPrefix.startsWith(\"/\")) {\n          throw new Error(\n            `pathPrefix '${spec.pathPrefix}' does not start with a /`\n          );\n        }\n        if (!spec.pathPrefix.endsWith(\"/\")) {\n          throw new Error(`pathPrefix ${spec.pathPrefix} must end with a /`);\n        }\n        if (spec.pathPrefix.startsWith(\"/.files/\")) {\n          throw new Error(`pathPrefix '${spec.pathPrefix}' is reserved`);\n        }\n        const prefixes = this.prefixRoutes.get(method) || /* @__PURE__ */ new Map();\n        if (prefixes.has(spec.pathPrefix)) {\n          throw new Error(\n            `${spec.method} pathPrefix ${spec.pathPrefix} is already defined`\n          );\n        }\n        prefixes.set(spec.pathPrefix, handler);\n        this.prefixRoutes.set(method, prefixes);\n      } else {\n        throw new Error(\n          `Invalid httpRouter route entry: must contain either field 'path' or 'pathPrefix'`\n        );\n      }\n    });\n    /**\n     * Returns a list of routed HTTP actions.\n     *\n     * These are used to populate the list of routes shown in the Functions page of the Convex dashboard.\n     *\n     * @returns - an array of [path, method, endpoint] tuples.\n     */\n    __publicField(this, \"getRoutes\", () => {\n      const exactPaths = [...this.exactRoutes.keys()].sort();\n      const exact = exactPaths.flatMap(\n        (path) => [...this.exactRoutes.get(path).keys()].sort().map(\n          (method) => [path, method, this.exactRoutes.get(path).get(method)]\n        )\n      );\n      const prefixPathMethods = [...this.prefixRoutes.keys()].sort();\n      const prefixes = prefixPathMethods.flatMap(\n        (method) => [...this.prefixRoutes.get(method).keys()].sort().map(\n          (pathPrefix) => [\n            `${pathPrefix}*`,\n            method,\n            this.prefixRoutes.get(method).get(pathPrefix)\n          ]\n        )\n      );\n      return [...exact, ...prefixes];\n    });\n    /**\n     * Returns the appropriate HTTP action and its routed request path and method.\n     *\n     * The path and method returned are used for logging and metrics, and should\n     * match up with one of the routes returned by `getRoutes`.\n     *\n     * For example,\n     *\n     * ```js\n     * http.route({ pathPrefix: \"/profile/\", method: \"GET\", handler: getProfile});\n     *\n     * http.lookup(\"/profile/abc\", \"GET\") // returns [getProfile, \"GET\", \"/profile/*\"]\n     *```\n     *\n     * @returns - a tuple [{@link PublicHttpAction}, method, path] or null.\n     */\n    __publicField(this, \"lookup\", (path, method) => {\n      method = normalizeMethod(method);\n      const exactMatch = this.exactRoutes.get(path)?.get(method);\n      if (exactMatch) return [exactMatch, method, path];\n      const prefixes = this.prefixRoutes.get(method) || /* @__PURE__ */ new Map();\n      const prefixesSorted = [...prefixes.entries()].sort(\n        ([prefixA, _a], [prefixB, _b]) => prefixB.length - prefixA.length\n      );\n      for (const [pathPrefix, endpoint] of prefixesSorted) {\n        if (path.startsWith(pathPrefix)) {\n          return [endpoint, method, `${pathPrefix}*`];\n        }\n      }\n      return null;\n    });\n    /**\n     * Given a JSON string representation of a Request object, return a Response\n     * by routing the request and running the appropriate endpoint or returning\n     * a 404 Response.\n     *\n     * @param argsStr - a JSON string representing a Request object.\n     *\n     * @returns - a Response object.\n     */\n    __publicField(this, \"runRequest\", async (argsStr, requestRoute) => {\n      const request = performJsSyscall(\"requestFromConvexJson\", {\n        convexJson: JSON.parse(argsStr)\n      });\n      let pathname = requestRoute;\n      if (!pathname || typeof pathname !== \"string\") {\n        pathname = new URL(request.url).pathname;\n      }\n      const method = request.method;\n      const match = this.lookup(pathname, method);\n      if (!match) {\n        const response2 = new Response(`No HttpAction routed for ${pathname}`, {\n          status: 404\n        });\n        return JSON.stringify(\n          performJsSyscall(\"convexJsonFromResponse\", { response: response2 })\n        );\n      }\n      const [endpoint, _method, _path] = match;\n      const response = await endpoint.invokeHttpAction(request);\n      return JSON.stringify(\n        performJsSyscall(\"convexJsonFromResponse\", { response })\n      );\n    });\n  }\n}\n//# sourceMappingURL=router.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport { convexToJson } from \"../../values/index.js\";\nimport { version } from \"../../index.js\";\nimport { performAsyncSyscall } from \"../impl/syscall.js\";\nimport {\n  getFunctionAddress,\n  setReferencePath,\n  toReferencePath\n} from \"./paths.js\";\nexport { getFunctionAddress } from \"./paths.js\";\nexport async function createFunctionHandle(functionReference) {\n  const address = getFunctionAddress(functionReference);\n  return await performAsyncSyscall(\"1.0/createFunctionHandle\", {\n    ...address,\n    version\n  });\n}\nclass InstalledComponent {\n  constructor(definition, name) {\n    /**\n     * @internal\n     */\n    __publicField(this, \"_definition\");\n    /**\n     * @internal\n     */\n    __publicField(this, \"_name\");\n    this._definition = definition;\n    this._name = name;\n    setReferencePath(this, `_reference/childComponent/${name}`);\n  }\n  get exports() {\n    return createExports(this._name, []);\n  }\n}\nfunction createExports(name, pathParts) {\n  const handler = {\n    get(_, prop) {\n      if (typeof prop === \"string\") {\n        const newParts = [...pathParts, prop];\n        return createExports(name, newParts);\n      } else if (prop === toReferencePath) {\n        let reference = `_reference/childComponent/${name}`;\n        for (const part of pathParts) {\n          reference += `/${part}`;\n        }\n        return reference;\n      } else {\n        return void 0;\n      }\n    }\n  };\n  return new Proxy({}, handler);\n}\nfunction use(definition, options) {\n  const importedComponentDefinition = definition;\n  if (typeof importedComponentDefinition.componentDefinitionPath !== \"string\") {\n    throw new Error(\n      \"Component definition does not have the required componentDefinitionPath property. This code only works in Convex runtime.\"\n    );\n  }\n  const name = options?.name ?? // added recently\n  importedComponentDefinition.defaultName ?? // can be removed once backend is out\n  importedComponentDefinition.componentDefinitionPath.split(\"/\").pop();\n  if (typeof name !== \"string\") {\n    throw new Error(\n      `Component name must be a string. Received: ${typeof name}`\n    );\n  }\n  if (name.length === 0) {\n    throw new Error(\"Component name cannot be empty.\");\n  }\n  this._childComponents.push([name, importedComponentDefinition, {}]);\n  return new InstalledComponent(definition, name);\n}\nfunction exportAppForAnalysis() {\n  const definitionType = { type: \"app\" };\n  const childComponents = serializeChildComponents(this._childComponents);\n  return {\n    definitionType,\n    childComponents,\n    httpMounts: {},\n    exports: serializeExportTree(this._exportTree)\n  };\n}\nfunction serializeExportTree(tree) {\n  const branch = [];\n  for (const [key, child] of Object.entries(tree)) {\n    let node;\n    if (typeof child === \"string\") {\n      node = { type: \"leaf\", leaf: child };\n    } else {\n      node = serializeExportTree(child);\n    }\n    branch.push([key, node]);\n  }\n  return { type: \"branch\", branch };\n}\nfunction serializeChildComponents(childComponents) {\n  return childComponents.map(([name, definition, p]) => {\n    let args = null;\n    if (p !== null) {\n      args = [];\n      for (const [name2, value] of Object.entries(p)) {\n        if (value !== void 0) {\n          args.push([\n            name2,\n            { type: \"value\", value: JSON.stringify(convexToJson(value)) }\n          ]);\n        }\n      }\n    }\n    const path = definition.componentDefinitionPath;\n    if (!path)\n      throw new Error(\n        \"no .componentPath for component definition \" + JSON.stringify(definition, null, 2)\n      );\n    return {\n      name,\n      path,\n      args\n    };\n  });\n}\nfunction exportComponentForAnalysis() {\n  const args = Object.entries(\n    this._args\n  ).map(([name, validator]) => [\n    name,\n    {\n      type: \"value\",\n      value: JSON.stringify(validator.json)\n    }\n  ]);\n  const definitionType = {\n    type: \"childComponent\",\n    name: this._name,\n    args\n  };\n  const childComponents = serializeChildComponents(this._childComponents);\n  return {\n    name: this._name,\n    definitionType,\n    childComponents,\n    httpMounts: {},\n    exports: serializeExportTree(this._exportTree)\n  };\n}\nexport function defineComponent(name) {\n  const ret = {\n    _isRoot: false,\n    _name: name,\n    _args: {},\n    _childComponents: [],\n    _exportTree: {},\n    _onInitCallbacks: {},\n    export: exportComponentForAnalysis,\n    use,\n    // pretend to conform to ComponentDefinition, which temporarily expects __args\n    ...{}\n  };\n  return ret;\n}\nexport function defineApp() {\n  const ret = {\n    _isRoot: true,\n    _childComponents: [],\n    _exportTree: {},\n    export: exportAppForAnalysis,\n    use\n  };\n  return ret;\n}\nexport function currentSystemUdfInComponent(componentId) {\n  return {\n    [toReferencePath]: `_reference/currentSystemUdfInComponent/${componentId}`\n  };\n}\nfunction createChildComponents(root, pathParts) {\n  const handler = {\n    get(_, prop) {\n      if (typeof prop === \"string\") {\n        const newParts = [...pathParts, prop];\n        return createChildComponents(root, newParts);\n      } else if (prop === toReferencePath) {\n        if (pathParts.length < 1) {\n          const found = [root, ...pathParts].join(\".\");\n          throw new Error(\n            `API path is expected to be of the form \\`${root}.childComponent.functionName\\`. Found: \\`${found}\\``\n          );\n        }\n        return `_reference/childComponent/` + pathParts.join(\"/\");\n      } else {\n        return void 0;\n      }\n    }\n  };\n  return new Proxy({}, handler);\n}\nexport const componentsGeneric = () => createChildComponents(\"components\", []);\n//# sourceMappingURL=index.js.map\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport {\n  isValidator,\n  v\n} from \"../values/validator.js\";\nexport class TableDefinition {\n  /**\n   * @internal\n   */\n  constructor(documentType) {\n    __publicField(this, \"indexes\");\n    __publicField(this, \"stagedDbIndexes\");\n    __publicField(this, \"searchIndexes\");\n    __publicField(this, \"stagedSearchIndexes\");\n    __publicField(this, \"vectorIndexes\");\n    __publicField(this, \"stagedVectorIndexes\");\n    // The type of documents stored in this table.\n    __publicField(this, \"validator\");\n    this.indexes = [];\n    this.stagedDbIndexes = [];\n    this.searchIndexes = [];\n    this.stagedSearchIndexes = [];\n    this.vectorIndexes = [];\n    this.stagedVectorIndexes = [];\n    this.validator = documentType;\n  }\n  /**\n   * This API is experimental: it may change or disappear.\n   *\n   * Returns indexes defined on this table.\n   * Intended for the advanced use cases of dynamically deciding which index to use for a query.\n   * If you think you need this, please chime in on ths issue in the Convex JS GitHub repo.\n   * https://github.com/get-convex/convex-js/issues/49\n   */\n  \" indexes\"() {\n    return this.indexes;\n  }\n  index(name, indexConfig) {\n    if (Array.isArray(indexConfig)) {\n      this.indexes.push({\n        indexDescriptor: name,\n        fields: indexConfig\n      });\n    } else if (indexConfig.staged) {\n      this.stagedDbIndexes.push({\n        indexDescriptor: name,\n        fields: indexConfig.fields\n      });\n    } else {\n      this.indexes.push({\n        indexDescriptor: name,\n        fields: indexConfig.fields\n      });\n    }\n    return this;\n  }\n  searchIndex(name, indexConfig) {\n    if (indexConfig.staged) {\n      this.stagedSearchIndexes.push({\n        indexDescriptor: name,\n        searchField: indexConfig.searchField,\n        filterFields: indexConfig.filterFields || []\n      });\n    } else {\n      this.searchIndexes.push({\n        indexDescriptor: name,\n        searchField: indexConfig.searchField,\n        filterFields: indexConfig.filterFields || []\n      });\n    }\n    return this;\n  }\n  vectorIndex(name, indexConfig) {\n    if (indexConfig.staged) {\n      this.stagedVectorIndexes.push({\n        indexDescriptor: name,\n        vectorField: indexConfig.vectorField,\n        dimensions: indexConfig.dimensions,\n        filterFields: indexConfig.filterFields || []\n      });\n    } else {\n      this.vectorIndexes.push({\n        indexDescriptor: name,\n        vectorField: indexConfig.vectorField,\n        dimensions: indexConfig.dimensions,\n        filterFields: indexConfig.filterFields || []\n      });\n    }\n    return this;\n  }\n  /**\n   * Work around for https://github.com/microsoft/TypeScript/issues/57035\n   */\n  self() {\n    return this;\n  }\n  /**\n   * Export the contents of this definition.\n   *\n   * This is called internally by the Convex framework.\n   * @internal\n   */\n  export() {\n    const documentType = this.validator.json;\n    if (typeof documentType !== \"object\") {\n      throw new Error(\n        \"Invalid validator: please make sure that the parameter of `defineTable` is valid (see https://docs.convex.dev/database/schemas)\"\n      );\n    }\n    return {\n      indexes: this.indexes,\n      stagedDbIndexes: this.stagedDbIndexes,\n      searchIndexes: this.searchIndexes,\n      stagedSearchIndexes: this.stagedSearchIndexes,\n      vectorIndexes: this.vectorIndexes,\n      stagedVectorIndexes: this.stagedVectorIndexes,\n      documentType\n    };\n  }\n}\nexport function defineTable(documentSchema) {\n  if (isValidator(documentSchema)) {\n    return new TableDefinition(documentSchema);\n  } else {\n    return new TableDefinition(v.object(documentSchema));\n  }\n}\nexport class SchemaDefinition {\n  /**\n   * @internal\n   */\n  constructor(tables, options) {\n    __publicField(this, \"tables\");\n    __publicField(this, \"strictTableNameTypes\");\n    __publicField(this, \"schemaValidation\");\n    this.tables = tables;\n    this.schemaValidation = options?.schemaValidation === void 0 ? true : options.schemaValidation;\n  }\n  /**\n   * Export the contents of this definition.\n   *\n   * This is called internally by the Convex framework.\n   * @internal\n   */\n  export() {\n    return JSON.stringify({\n      tables: Object.entries(this.tables).map(([tableName, definition]) => {\n        const {\n          indexes,\n          stagedDbIndexes,\n          searchIndexes,\n          stagedSearchIndexes,\n          vectorIndexes,\n          stagedVectorIndexes,\n          documentType\n        } = definition.export();\n        return {\n          tableName,\n          indexes,\n          stagedDbIndexes,\n          searchIndexes,\n          stagedSearchIndexes,\n          vectorIndexes,\n          stagedVectorIndexes,\n          documentType\n        };\n      }),\n      schemaValidation: this.schemaValidation\n    });\n  }\n}\nexport function defineSchema(schema, options) {\n  return new SchemaDefinition(schema, options);\n}\nconst _systemSchema = defineSchema({\n  _scheduled_functions: defineTable({\n    name: v.string(),\n    args: v.array(v.any()),\n    scheduledTime: v.float64(),\n    completedTime: v.optional(v.float64()),\n    state: v.union(\n      v.object({ kind: v.literal(\"pending\") }),\n      v.object({ kind: v.literal(\"inProgress\") }),\n      v.object({ kind: v.literal(\"success\") }),\n      v.object({ kind: v.literal(\"failed\"), error: v.string() }),\n      v.object({ kind: v.literal(\"canceled\") })\n    )\n  }),\n  _storage: defineTable({\n    sha256: v.string(),\n    size: v.float64(),\n    contentType: v.optional(v.string())\n  })\n});\n//# sourceMappingURL=schema.js.map\n","\"use strict\";\nexport * from \"./database.js\";\nexport {\n  actionGeneric,\n  httpActionGeneric,\n  mutationGeneric,\n  queryGeneric,\n  internalActionGeneric,\n  internalMutationGeneric,\n  internalQueryGeneric\n} from \"./impl/registration_impl.js\";\nexport * from \"./pagination.js\";\nexport * from \"./search_filter_builder.js\";\nexport * from \"./storage.js\";\nexport { cronJobs } from \"./cron.js\";\nexport { httpRouter, HttpRouter, ROUTABLE_HTTP_METHODS } from \"./router.js\";\nexport {\n  anyApi,\n  getFunctionName,\n  makeFunctionReference,\n  filterApi\n} from \"./api.js\";\nexport {\n  defineApp,\n  defineComponent,\n  componentsGeneric,\n  createFunctionHandle\n} from \"./components/index.js\";\nexport { currentSystemUdfInComponent } from \"./components/index.js\";\nexport { getFunctionAddress } from \"./components/index.js\";\nexport { defineTable, defineSchema } from \"./schema.js\";\n//# sourceMappingURL=index.js.map\n"],"mappings":"qJAWA,SAAS,GAAQ,EAAK,CACpB,IAAIA,EAAM,EAAI,OACd,GAAIA,EAAM,EAAI,EACZ,MAAU,MAAM,iDAAiD,CAEnE,IAAI,EAAW,EAAI,QAAQ,IAAI,CAC3B,IAAa,KAAI,EAAWA,GAChC,IAAI,EAAkB,IAAaA,EAAM,EAAI,EAAI,EAAW,EAC5D,MAAO,CAAC,EAAU,EAAgB,CAQpC,SAAS,GAAY,EAAM,EAAU,EAAiB,CACpD,OAAQ,EAAW,GAAmB,EAAI,EAAI,EAEhD,SAAgB,EAAY,EAAK,CAC/B,IAAI,EACA,EAAO,GAAQ,EAAI,CACnB,EAAW,EAAK,GAChB,EAAkB,EAAK,GACvBC,EAAM,IAAI,GAAI,GAAY,EAAK,EAAU,EAAgB,CAAC,CAC1D,EAAU,EACVD,EAAM,EAAkB,EAAI,EAAW,EAAI,EAC3CE,EACJ,IAAK,EAAI,EAAGA,EAAIF,EAAK,GAAK,EACxB,EAAM,EAAU,EAAI,WAAWE,EAAE,GA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