{"version":3,"file":"dosha-calculator.umd.cjs","sources":["../../../node_modules/react/cjs/react-jsx-runtime.production.min.js","../../../node_modules/react/cjs/react-jsx-runtime.development.js","../../../node_modules/react/jsx-runtime.js","../src/analytics.ts","../../../node_modules/@supabase/supabase-js/dist/tracingRegistry.mjs","../../../node_modules/tslib/tslib.es6.mjs","../../../node_modules/@supabase/functions-js/dist/module/helper.js","../../../node_modules/@supabase/functions-js/dist/module/types.js","../../../node_modules/@supabase/functions-js/dist/module/FunctionsClient.js","../../../node_modules/@supabase/postgrest-js/dist/index.mjs","../../../node_modules/@supabase/realtime-js/dist/module/lib/websocket-factory.js","../../../node_modules/@supabase/realtime-js/dist/module/lib/constants.js","../../../node_modules/@supabase/realtime-js/dist/module/lib/serializer.js","../../../node_modules/@supabase/realtime-js/dist/module/lib/transformers.js","../../../node_modules/@supabase/phoenix/priv/static/phoenix.mjs","../../../node_modules/@supabase/realtime-js/dist/module/phoenix/presenceAdapter.js","../../../node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js","../../../node_modules/@supabase/realtime-js/dist/module/lib/normalizeChannelError.js","../../../node_modules/@supabase/realtime-js/dist/module/phoenix/channelAdapter.js","../../../node_modules/@supabase/realtime-js/dist/module/RealtimePostgresFilterBuilder.js","../../../node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js","../../../node_modules/@supabase/realtime-js/dist/module/phoenix/socketAdapter.js","../../../node_modules/@supabase/realtime-js/dist/module/RealtimeClient.js","../../../node_modules/iceberg-js/dist/index.mjs","../../../node_modules/@supabase/storage-js/dist/index.mjs","../../../node_modules/@supabase/auth-js/dist/module/lib/version.js","../../../node_modules/@supabase/auth-js/dist/module/lib/constants.js","../../../node_modules/@supabase/auth-js/dist/module/lib/errors.js","../../../node_modules/@supabase/auth-js/dist/module/lib/base64url.js","../../../node_modules/@supabase/auth-js/dist/module/lib/helpers.js","../../../node_modules/@supabase/auth-js/dist/module/lib/fetch.js","../../../node_modules/@supabase/auth-js/dist/module/lib/types.js","../../../node_modules/@supabase/auth-js/dist/module/GoTrueAdminApi.js","../../../node_modules/@supabase/auth-js/dist/module/lib/local-storage.js","../../../node_modules/@supabase/auth-js/dist/module/lib/locks.js","../../../node_modules/@supabase/auth-js/dist/module/lib/polyfills.js","../../../node_modules/@supabase/auth-js/dist/module/lib/web3/ethereum.js","../../../node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.js","../../../node_modules/@supabase/auth-js/dist/module/lib/webauthn.js","../../../node_modules/@supabase/auth-js/dist/module/GoTrueClient.js","../../../node_modules/@supabase/auth-js/dist/module/AuthClient.js","../../../node_modules/@supabase/supabase-js/dist/index.mjs","../src/lib/supabase-helpers.ts","../src/lib/puja-recommendation.ts","../src/lib/sriMandirPujaHelpers.ts","../src/i18n/translations.ts","../src/i18n/I18nContext.tsx","../src/components/FooterTrustBadge/FooterTrustBadge.tsx","../src/components/icons.tsx","../src/types/image.ts","../src/components/DoshaFooterCTA/DoshaFooterCTA.tsx","../src/components/DoshaBanner/DoshaBanner.tsx","../src/components/SectionWithImpression/SectionWithImpression.tsx","../src/components/DoshaDateField/DoshaDateField.tsx","../src/components/DoshaTimeField/DoshaTimeField.tsx","../src/lib/supabase-dosha.ts","../src/hooks/useGooglePlacesAutocomplete.ts","../src/components/DoshaFormSection/DoshaFormSection.tsx","../src/components/ui/Skeleton.tsx","../src/components/ui/Card.tsx","../src/components/ui/Button.tsx","../src/components/SriMandirPujaVerticalCard/SriMandirPujaVerticalCard.tsx","../src/components/WhatFromAnalysis/WhatFromAnalysis.tsx","../src/constants/bannerConfig.ts","../src/utils/queryParams.ts","../src/components/DoshaCalculator/DoshaCalculator.tsx","../src/components/DoshaResultsView/DoshaResultsView.tsx","../src/components/ui/Badge.tsx","../src/components/ui/Accordion.tsx","../src/lib/kundaliChart.ts","../src/components/KundaliCard/KundaliCard.tsx","../src/components/DoshaResultsFull/DoshaResultsFull.tsx","../src/lib/google-maps-helpers.ts"],"sourcesContent":["/**\n * @license React\n * react-jsx-runtime.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var f=require(\"react\"),k=Symbol.for(\"react.element\"),l=Symbol.for(\"react.fragment\"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};\nfunction q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=\"\"+g);void 0!==a.key&&(e=\"\"+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}exports.Fragment=l;exports.jsx=q;exports.jsxs=q;\n","/**\n * @license React\n * react-jsx-runtime.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n  (function() {\n'use strict';\n\nvar React = require('react');\n\n// ATTENTION\n// When adding new symbols to this file,\n// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'\n// The Symbol used to tag the ReactElement-like types.\nvar REACT_ELEMENT_TYPE = Symbol.for('react.element');\nvar REACT_PORTAL_TYPE = Symbol.for('react.portal');\nvar REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');\nvar REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');\nvar REACT_PROFILER_TYPE = Symbol.for('react.profiler');\nvar REACT_PROVIDER_TYPE = Symbol.for('react.provider');\nvar REACT_CONTEXT_TYPE = Symbol.for('react.context');\nvar REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');\nvar REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');\nvar REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');\nvar REACT_MEMO_TYPE = Symbol.for('react.memo');\nvar REACT_LAZY_TYPE = Symbol.for('react.lazy');\nvar REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');\nvar MAYBE_ITERATOR_SYMBOL = Symbol.iterator;\nvar FAUX_ITERATOR_SYMBOL = '@@iterator';\nfunction getIteratorFn(maybeIterable) {\n  if (maybeIterable === null || typeof maybeIterable !== 'object') {\n    return null;\n  }\n\n  var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];\n\n  if (typeof maybeIterator === 'function') {\n    return maybeIterator;\n  }\n\n  return null;\n}\n\nvar ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n\nfunction error(format) {\n  {\n    {\n      for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n        args[_key2 - 1] = arguments[_key2];\n      }\n\n      printWarning('error', format, args);\n    }\n  }\n}\n\nfunction printWarning(level, format, args) {\n  // When changing this logic, you might want to also\n  // update consoleWithStackDev.www.js as well.\n  {\n    var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n    var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n    if (stack !== '') {\n      format += '%s';\n      args = args.concat([stack]);\n    } // eslint-disable-next-line react-internal/safe-string-coercion\n\n\n    var argsWithFormat = args.map(function (item) {\n      return String(item);\n    }); // Careful: RN currently depends on this prefix\n\n    argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n    // breaks IE9: https://github.com/facebook/react/issues/13610\n    // eslint-disable-next-line react-internal/no-production-logging\n\n    Function.prototype.apply.call(console[level], console, argsWithFormat);\n  }\n}\n\n// -----------------------------------------------------------------------------\n\nvar enableScopeAPI = false; // Experimental Create Event Handle API.\nvar enableCacheElement = false;\nvar enableTransitionTracing = false; // No known bugs, but needs performance testing\n\nvar enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber\n// stuff. Intended to enable React core members to more easily debug scheduling\n// issues in DEV builds.\n\nvar enableDebugTracing = false; // Track which Fiber(s) schedule render work.\n\nvar REACT_MODULE_REFERENCE;\n\n{\n  REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');\n}\n\nfunction isValidElementType(type) {\n  if (typeof type === 'string' || typeof type === 'function') {\n    return true;\n  } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).\n\n\n  if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing  || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden  || type === REACT_OFFSCREEN_TYPE || enableScopeAPI  || enableCacheElement  || enableTransitionTracing ) {\n    return true;\n  }\n\n  if (typeof type === 'object' && type !== null) {\n    if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object\n    // types supported by any Flight configuration anywhere since\n    // we don't know which Flight build this will end up being used\n    // with.\n    type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n  var displayName = outerType.displayName;\n\n  if (displayName) {\n    return displayName;\n  }\n\n  var functionName = innerType.displayName || innerType.name || '';\n  return functionName !== '' ? wrapperName + \"(\" + functionName + \")\" : wrapperName;\n} // Keep in sync with react-reconciler/getComponentNameFromFiber\n\n\nfunction getContextName(type) {\n  return type.displayName || 'Context';\n} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.\n\n\nfunction getComponentNameFromType(type) {\n  if (type == null) {\n    // Host root, text node or just invalid type.\n    return null;\n  }\n\n  {\n    if (typeof type.tag === 'number') {\n      error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');\n    }\n  }\n\n  if (typeof type === 'function') {\n    return type.displayName || type.name || null;\n  }\n\n  if (typeof type === 'string') {\n    return type;\n  }\n\n  switch (type) {\n    case REACT_FRAGMENT_TYPE:\n      return 'Fragment';\n\n    case REACT_PORTAL_TYPE:\n      return 'Portal';\n\n    case REACT_PROFILER_TYPE:\n      return 'Profiler';\n\n    case REACT_STRICT_MODE_TYPE:\n      return 'StrictMode';\n\n    case REACT_SUSPENSE_TYPE:\n      return 'Suspense';\n\n    case REACT_SUSPENSE_LIST_TYPE:\n      return 'SuspenseList';\n\n  }\n\n  if (typeof type === 'object') {\n    switch (type.$$typeof) {\n      case REACT_CONTEXT_TYPE:\n        var context = type;\n        return getContextName(context) + '.Consumer';\n\n      case REACT_PROVIDER_TYPE:\n        var provider = type;\n        return getContextName(provider._context) + '.Provider';\n\n      case REACT_FORWARD_REF_TYPE:\n        return getWrappedName(type, type.render, 'ForwardRef');\n\n      case REACT_MEMO_TYPE:\n        var outerName = type.displayName || null;\n\n        if (outerName !== null) {\n          return outerName;\n        }\n\n        return getComponentNameFromType(type.type) || 'Memo';\n\n      case REACT_LAZY_TYPE:\n        {\n          var lazyComponent = type;\n          var payload = lazyComponent._payload;\n          var init = lazyComponent._init;\n\n          try {\n            return getComponentNameFromType(init(payload));\n          } catch (x) {\n            return null;\n          }\n        }\n\n      // eslint-disable-next-line no-fallthrough\n    }\n  }\n\n  return null;\n}\n\nvar assign = Object.assign;\n\n// Helpers to patch console.logs to avoid logging during side-effect free\n// replaying on render function. This currently only patches the object\n// lazily which won't cover if the log function was extracted eagerly.\n// We could also eagerly patch the method.\nvar disabledDepth = 0;\nvar prevLog;\nvar prevInfo;\nvar prevWarn;\nvar prevError;\nvar prevGroup;\nvar prevGroupCollapsed;\nvar prevGroupEnd;\n\nfunction disabledLog() {}\n\ndisabledLog.__reactDisabledLog = true;\nfunction disableLogs() {\n  {\n    if (disabledDepth === 0) {\n      /* eslint-disable react-internal/no-production-logging */\n      prevLog = console.log;\n      prevInfo = console.info;\n      prevWarn = console.warn;\n      prevError = console.error;\n      prevGroup = console.group;\n      prevGroupCollapsed = console.groupCollapsed;\n      prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099\n\n      var props = {\n        configurable: true,\n        enumerable: true,\n        value: disabledLog,\n        writable: true\n      }; // $FlowFixMe Flow thinks console is immutable.\n\n      Object.defineProperties(console, {\n        info: props,\n        log: props,\n        warn: props,\n        error: props,\n        group: props,\n        groupCollapsed: props,\n        groupEnd: props\n      });\n      /* eslint-enable react-internal/no-production-logging */\n    }\n\n    disabledDepth++;\n  }\n}\nfunction reenableLogs() {\n  {\n    disabledDepth--;\n\n    if (disabledDepth === 0) {\n      /* eslint-disable react-internal/no-production-logging */\n      var props = {\n        configurable: true,\n        enumerable: true,\n        writable: true\n      }; // $FlowFixMe Flow thinks console is immutable.\n\n      Object.defineProperties(console, {\n        log: assign({}, props, {\n          value: prevLog\n        }),\n        info: assign({}, props, {\n          value: prevInfo\n        }),\n        warn: assign({}, props, {\n          value: prevWarn\n        }),\n        error: assign({}, props, {\n          value: prevError\n        }),\n        group: assign({}, props, {\n          value: prevGroup\n        }),\n        groupCollapsed: assign({}, props, {\n          value: prevGroupCollapsed\n        }),\n        groupEnd: assign({}, props, {\n          value: prevGroupEnd\n        })\n      });\n      /* eslint-enable react-internal/no-production-logging */\n    }\n\n    if (disabledDepth < 0) {\n      error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');\n    }\n  }\n}\n\nvar ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;\nvar prefix;\nfunction describeBuiltInComponentFrame(name, source, ownerFn) {\n  {\n    if (prefix === undefined) {\n      // Extract the VM specific prefix used by each line.\n      try {\n        throw Error();\n      } catch (x) {\n        var match = x.stack.trim().match(/\\n( *(at )?)/);\n        prefix = match && match[1] || '';\n      }\n    } // We use the prefix to ensure our stacks line up with native stack frames.\n\n\n    return '\\n' + prefix + name;\n  }\n}\nvar reentry = false;\nvar componentFrameCache;\n\n{\n  var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;\n  componentFrameCache = new PossiblyWeakMap();\n}\n\nfunction describeNativeComponentFrame(fn, construct) {\n  // If something asked for a stack inside a fake render, it should get ignored.\n  if ( !fn || reentry) {\n    return '';\n  }\n\n  {\n    var frame = componentFrameCache.get(fn);\n\n    if (frame !== undefined) {\n      return frame;\n    }\n  }\n\n  var control;\n  reentry = true;\n  var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.\n\n  Error.prepareStackTrace = undefined;\n  var previousDispatcher;\n\n  {\n    previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function\n    // for warnings.\n\n    ReactCurrentDispatcher.current = null;\n    disableLogs();\n  }\n\n  try {\n    // This should throw.\n    if (construct) {\n      // Something should be setting the props in the constructor.\n      var Fake = function () {\n        throw Error();\n      }; // $FlowFixMe\n\n\n      Object.defineProperty(Fake.prototype, 'props', {\n        set: function () {\n          // We use a throwing setter instead of frozen or non-writable props\n          // because that won't throw in a non-strict mode function.\n          throw Error();\n        }\n      });\n\n      if (typeof Reflect === 'object' && Reflect.construct) {\n        // We construct a different control for this case to include any extra\n        // frames added by the construct call.\n        try {\n          Reflect.construct(Fake, []);\n        } catch (x) {\n          control = x;\n        }\n\n        Reflect.construct(fn, [], Fake);\n      } else {\n        try {\n          Fake.call();\n        } catch (x) {\n          control = x;\n        }\n\n        fn.call(Fake.prototype);\n      }\n    } else {\n      try {\n        throw Error();\n      } catch (x) {\n        control = x;\n      }\n\n      fn();\n    }\n  } catch (sample) {\n    // This is inlined manually because closure doesn't do it for us.\n    if (sample && control && typeof sample.stack === 'string') {\n      // This extracts the first frame from the sample that isn't also in the control.\n      // Skipping one frame that we assume is the frame that calls the two.\n      var sampleLines = sample.stack.split('\\n');\n      var controlLines = control.stack.split('\\n');\n      var s = sampleLines.length - 1;\n      var c = controlLines.length - 1;\n\n      while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {\n        // We expect at least one stack frame to be shared.\n        // Typically this will be the root most one. However, stack frames may be\n        // cut off due to maximum stack limits. In this case, one maybe cut off\n        // earlier than the other. We assume that the sample is longer or the same\n        // and there for cut off earlier. So we should find the root most frame in\n        // the sample somewhere in the control.\n        c--;\n      }\n\n      for (; s >= 1 && c >= 0; s--, c--) {\n        // Next we find the first one that isn't the same which should be the\n        // frame that called our sample function and the control.\n        if (sampleLines[s] !== controlLines[c]) {\n          // In V8, the first line is describing the message but other VMs don't.\n          // If we're about to return the first line, and the control is also on the same\n          // line, that's a pretty good indicator that our sample threw at same line as\n          // the control. I.e. before we entered the sample frame. So we ignore this result.\n          // This can happen if you passed a class to function component, or non-function.\n          if (s !== 1 || c !== 1) {\n            do {\n              s--;\n              c--; // We may still have similar intermediate frames from the construct call.\n              // The next one that isn't the same should be our match though.\n\n              if (c < 0 || sampleLines[s] !== controlLines[c]) {\n                // V8 adds a \"new\" prefix for native classes. Let's remove it to make it prettier.\n                var _frame = '\\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled \"<anonymous>\"\n                // but we have a user-provided \"displayName\"\n                // splice it in to make the stack more readable.\n\n\n                if (fn.displayName && _frame.includes('<anonymous>')) {\n                  _frame = _frame.replace('<anonymous>', fn.displayName);\n                }\n\n                {\n                  if (typeof fn === 'function') {\n                    componentFrameCache.set(fn, _frame);\n                  }\n                } // Return the line we found.\n\n\n                return _frame;\n              }\n            } while (s >= 1 && c >= 0);\n          }\n\n          break;\n        }\n      }\n    }\n  } finally {\n    reentry = false;\n\n    {\n      ReactCurrentDispatcher.current = previousDispatcher;\n      reenableLogs();\n    }\n\n    Error.prepareStackTrace = previousPrepareStackTrace;\n  } // Fallback to just using the name if we couldn't make it throw.\n\n\n  var name = fn ? fn.displayName || fn.name : '';\n  var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';\n\n  {\n    if (typeof fn === 'function') {\n      componentFrameCache.set(fn, syntheticFrame);\n    }\n  }\n\n  return syntheticFrame;\n}\nfunction describeFunctionComponentFrame(fn, source, ownerFn) {\n  {\n    return describeNativeComponentFrame(fn, false);\n  }\n}\n\nfunction shouldConstruct(Component) {\n  var prototype = Component.prototype;\n  return !!(prototype && prototype.isReactComponent);\n}\n\nfunction describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {\n\n  if (type == null) {\n    return '';\n  }\n\n  if (typeof type === 'function') {\n    {\n      return describeNativeComponentFrame(type, shouldConstruct(type));\n    }\n  }\n\n  if (typeof type === 'string') {\n    return describeBuiltInComponentFrame(type);\n  }\n\n  switch (type) {\n    case REACT_SUSPENSE_TYPE:\n      return describeBuiltInComponentFrame('Suspense');\n\n    case REACT_SUSPENSE_LIST_TYPE:\n      return describeBuiltInComponentFrame('SuspenseList');\n  }\n\n  if (typeof type === 'object') {\n    switch (type.$$typeof) {\n      case REACT_FORWARD_REF_TYPE:\n        return describeFunctionComponentFrame(type.render);\n\n      case REACT_MEMO_TYPE:\n        // Memo may contain any component type so we recursively resolve it.\n        return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);\n\n      case REACT_LAZY_TYPE:\n        {\n          var lazyComponent = type;\n          var payload = lazyComponent._payload;\n          var init = lazyComponent._init;\n\n          try {\n            // Lazy may contain any component type so we recursively resolve it.\n            return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);\n          } catch (x) {}\n        }\n    }\n  }\n\n  return '';\n}\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar loggedTypeFailures = {};\nvar ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement(element) {\n  {\n    if (element) {\n      var owner = element._owner;\n      var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n      ReactDebugCurrentFrame.setExtraStackFrame(stack);\n    } else {\n      ReactDebugCurrentFrame.setExtraStackFrame(null);\n    }\n  }\n}\n\nfunction checkPropTypes(typeSpecs, values, location, componentName, element) {\n  {\n    // $FlowFixMe This is okay but Flow doesn't know it.\n    var has = Function.call.bind(hasOwnProperty);\n\n    for (var typeSpecName in typeSpecs) {\n      if (has(typeSpecs, typeSpecName)) {\n        var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to\n        // fail the render phase where it didn't fail before. So we log it.\n        // After these have been cleaned up, we'll let them throw.\n\n        try {\n          // This is intentionally an invariant that gets caught. It's the same\n          // behavior as without this statement except with a better message.\n          if (typeof typeSpecs[typeSpecName] !== 'function') {\n            // eslint-disable-next-line react-internal/prod-error-codes\n            var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');\n            err.name = 'Invariant Violation';\n            throw err;\n          }\n\n          error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');\n        } catch (ex) {\n          error$1 = ex;\n        }\n\n        if (error$1 && !(error$1 instanceof Error)) {\n          setCurrentlyValidatingElement(element);\n\n          error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);\n\n          setCurrentlyValidatingElement(null);\n        }\n\n        if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {\n          // Only monitor this failure once because there tends to be a lot of the\n          // same error.\n          loggedTypeFailures[error$1.message] = true;\n          setCurrentlyValidatingElement(element);\n\n          error('Failed %s type: %s', location, error$1.message);\n\n          setCurrentlyValidatingElement(null);\n        }\n      }\n    }\n  }\n}\n\nvar isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare\n\nfunction isArray(a) {\n  return isArrayImpl(a);\n}\n\n/*\n * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol\n * and Temporal.* types. See https://github.com/facebook/react/pull/22064.\n *\n * The functions in this module will throw an easier-to-understand,\n * easier-to-debug exception with a clear errors message message explaining the\n * problem. (Instead of a confusing exception thrown inside the implementation\n * of the `value` object).\n */\n// $FlowFixMe only called in DEV, so void return is not possible.\nfunction typeName(value) {\n  {\n    // toStringTag is needed for namespaced types like Temporal.Instant\n    var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;\n    var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';\n    return type;\n  }\n} // $FlowFixMe only called in DEV, so void return is not possible.\n\n\nfunction willCoercionThrow(value) {\n  {\n    try {\n      testStringCoercion(value);\n      return false;\n    } catch (e) {\n      return true;\n    }\n  }\n}\n\nfunction testStringCoercion(value) {\n  // If you ended up here by following an exception call stack, here's what's\n  // happened: you supplied an object or symbol value to React (as a prop, key,\n  // DOM attribute, CSS property, string ref, etc.) and when React tried to\n  // coerce it to a string using `'' + value`, an exception was thrown.\n  //\n  // The most common types that will cause this exception are `Symbol` instances\n  // and Temporal objects like `Temporal.Instant`. But any object that has a\n  // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this\n  // exception. (Library authors do this to prevent users from using built-in\n  // numeric operators like `+` or comparison operators like `>=` because custom\n  // methods are needed to perform accurate arithmetic or comparison.)\n  //\n  // To fix the problem, coerce this object or symbol value to a string before\n  // passing it to React. The most reliable way is usually `String(value)`.\n  //\n  // To find which value is throwing, check the browser or debugger console.\n  // Before this exception was thrown, there should be `console.error` output\n  // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the\n  // problem and how that type was used: key, atrribute, input value prop, etc.\n  // In most cases, this console output also shows the component and its\n  // ancestor components where the exception happened.\n  //\n  // eslint-disable-next-line react-internal/safe-string-coercion\n  return '' + value;\n}\nfunction checkKeyStringCoercion(value) {\n  {\n    if (willCoercionThrow(value)) {\n      error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));\n\n      return testStringCoercion(value); // throw (to help callers find troubleshooting comments)\n    }\n  }\n}\n\nvar ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;\nvar RESERVED_PROPS = {\n  key: true,\n  ref: true,\n  __self: true,\n  __source: true\n};\nvar specialPropKeyWarningShown;\nvar specialPropRefWarningShown;\nvar didWarnAboutStringRefs;\n\n{\n  didWarnAboutStringRefs = {};\n}\n\nfunction hasValidRef(config) {\n  {\n    if (hasOwnProperty.call(config, 'ref')) {\n      var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;\n\n      if (getter && getter.isReactWarning) {\n        return false;\n      }\n    }\n  }\n\n  return config.ref !== undefined;\n}\n\nfunction hasValidKey(config) {\n  {\n    if (hasOwnProperty.call(config, 'key')) {\n      var getter = Object.getOwnPropertyDescriptor(config, 'key').get;\n\n      if (getter && getter.isReactWarning) {\n        return false;\n      }\n    }\n  }\n\n  return config.key !== undefined;\n}\n\nfunction warnIfStringRefCannotBeAutoConverted(config, self) {\n  {\n    if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {\n      var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);\n\n      if (!didWarnAboutStringRefs[componentName]) {\n        error('Component \"%s\" contains the string ref \"%s\". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref);\n\n        didWarnAboutStringRefs[componentName] = true;\n      }\n    }\n  }\n}\n\nfunction defineKeyPropWarningGetter(props, displayName) {\n  {\n    var warnAboutAccessingKey = function () {\n      if (!specialPropKeyWarningShown) {\n        specialPropKeyWarningShown = true;\n\n        error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);\n      }\n    };\n\n    warnAboutAccessingKey.isReactWarning = true;\n    Object.defineProperty(props, 'key', {\n      get: warnAboutAccessingKey,\n      configurable: true\n    });\n  }\n}\n\nfunction defineRefPropWarningGetter(props, displayName) {\n  {\n    var warnAboutAccessingRef = function () {\n      if (!specialPropRefWarningShown) {\n        specialPropRefWarningShown = true;\n\n        error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);\n      }\n    };\n\n    warnAboutAccessingRef.isReactWarning = true;\n    Object.defineProperty(props, 'ref', {\n      get: warnAboutAccessingRef,\n      configurable: true\n    });\n  }\n}\n/**\n * Factory method to create a new React element. This no longer adheres to\n * the class pattern, so do not use new to call it. Also, instanceof check\n * will not work. Instead test $$typeof field against Symbol.for('react.element') to check\n * if something is a React Element.\n *\n * @param {*} type\n * @param {*} props\n * @param {*} key\n * @param {string|object} ref\n * @param {*} owner\n * @param {*} self A *temporary* helper to detect places where `this` is\n * different from the `owner` when React.createElement is called, so that we\n * can warn. We want to get rid of owner and replace string `ref`s with arrow\n * functions, and as long as `this` and owner are the same, there will be no\n * change in behavior.\n * @param {*} source An annotation object (added by a transpiler or otherwise)\n * indicating filename, line number, and/or other information.\n * @internal\n */\n\n\nvar ReactElement = function (type, key, ref, self, source, owner, props) {\n  var element = {\n    // This tag allows us to uniquely identify this as a React Element\n    $$typeof: REACT_ELEMENT_TYPE,\n    // Built-in properties that belong on the element\n    type: type,\n    key: key,\n    ref: ref,\n    props: props,\n    // Record the component responsible for creating this element.\n    _owner: owner\n  };\n\n  {\n    // The validation flag is currently mutative. We put it on\n    // an external backing store so that we can freeze the whole object.\n    // This can be replaced with a WeakMap once they are implemented in\n    // commonly used development environments.\n    element._store = {}; // To make comparing ReactElements easier for testing purposes, we make\n    // the validation flag non-enumerable (where possible, which should\n    // include every environment we run tests in), so the test framework\n    // ignores it.\n\n    Object.defineProperty(element._store, 'validated', {\n      configurable: false,\n      enumerable: false,\n      writable: true,\n      value: false\n    }); // self and source are DEV only properties.\n\n    Object.defineProperty(element, '_self', {\n      configurable: false,\n      enumerable: false,\n      writable: false,\n      value: self\n    }); // Two elements created in two different places should be considered\n    // equal for testing purposes and therefore we hide it from enumeration.\n\n    Object.defineProperty(element, '_source', {\n      configurable: false,\n      enumerable: false,\n      writable: false,\n      value: source\n    });\n\n    if (Object.freeze) {\n      Object.freeze(element.props);\n      Object.freeze(element);\n    }\n  }\n\n  return element;\n};\n/**\n * https://github.com/reactjs/rfcs/pull/107\n * @param {*} type\n * @param {object} props\n * @param {string} key\n */\n\nfunction jsxDEV(type, config, maybeKey, source, self) {\n  {\n    var propName; // Reserved names are extracted\n\n    var props = {};\n    var key = null;\n    var ref = null; // Currently, key can be spread in as a prop. This causes a potential\n    // issue if key is also explicitly declared (ie. <div {...props} key=\"Hi\" />\n    // or <div key=\"Hi\" {...props} /> ). We want to deprecate key spread,\n    // but as an intermediary step, we will use jsxDEV for everything except\n    // <div {...props} key=\"Hi\" />, because we aren't currently able to tell if\n    // key is explicitly declared to be undefined or not.\n\n    if (maybeKey !== undefined) {\n      {\n        checkKeyStringCoercion(maybeKey);\n      }\n\n      key = '' + maybeKey;\n    }\n\n    if (hasValidKey(config)) {\n      {\n        checkKeyStringCoercion(config.key);\n      }\n\n      key = '' + config.key;\n    }\n\n    if (hasValidRef(config)) {\n      ref = config.ref;\n      warnIfStringRefCannotBeAutoConverted(config, self);\n    } // Remaining properties are added to a new props object\n\n\n    for (propName in config) {\n      if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n        props[propName] = config[propName];\n      }\n    } // Resolve default props\n\n\n    if (type && type.defaultProps) {\n      var defaultProps = type.defaultProps;\n\n      for (propName in defaultProps) {\n        if (props[propName] === undefined) {\n          props[propName] = defaultProps[propName];\n        }\n      }\n    }\n\n    if (key || ref) {\n      var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;\n\n      if (key) {\n        defineKeyPropWarningGetter(props, displayName);\n      }\n\n      if (ref) {\n        defineRefPropWarningGetter(props, displayName);\n      }\n    }\n\n    return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);\n  }\n}\n\nvar ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;\nvar ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement$1(element) {\n  {\n    if (element) {\n      var owner = element._owner;\n      var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n      ReactDebugCurrentFrame$1.setExtraStackFrame(stack);\n    } else {\n      ReactDebugCurrentFrame$1.setExtraStackFrame(null);\n    }\n  }\n}\n\nvar propTypesMisspellWarningShown;\n\n{\n  propTypesMisspellWarningShown = false;\n}\n/**\n * Verifies the object is a ReactElement.\n * See https://reactjs.org/docs/react-api.html#isvalidelement\n * @param {?object} object\n * @return {boolean} True if `object` is a ReactElement.\n * @final\n */\n\n\nfunction isValidElement(object) {\n  {\n    return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n  }\n}\n\nfunction getDeclarationErrorAddendum() {\n  {\n    if (ReactCurrentOwner$1.current) {\n      var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);\n\n      if (name) {\n        return '\\n\\nCheck the render method of `' + name + '`.';\n      }\n    }\n\n    return '';\n  }\n}\n\nfunction getSourceInfoErrorAddendum(source) {\n  {\n    if (source !== undefined) {\n      var fileName = source.fileName.replace(/^.*[\\\\\\/]/, '');\n      var lineNumber = source.lineNumber;\n      return '\\n\\nCheck your code at ' + fileName + ':' + lineNumber + '.';\n    }\n\n    return '';\n  }\n}\n/**\n * Warn if there's no key explicitly set on dynamic arrays of children or\n * object keys are not valid. This allows us to keep track of children between\n * updates.\n */\n\n\nvar ownerHasKeyUseWarning = {};\n\nfunction getCurrentComponentErrorInfo(parentType) {\n  {\n    var info = getDeclarationErrorAddendum();\n\n    if (!info) {\n      var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;\n\n      if (parentName) {\n        info = \"\\n\\nCheck the top-level render call using <\" + parentName + \">.\";\n      }\n    }\n\n    return info;\n  }\n}\n/**\n * Warn if the element doesn't have an explicit key assigned to it.\n * This element is in an array. The array could grow and shrink or be\n * reordered. All children that haven't already been validated are required to\n * have a \"key\" property assigned to it. Error statuses are cached so a warning\n * will only be shown once.\n *\n * @internal\n * @param {ReactElement} element Element that requires a key.\n * @param {*} parentType element's parent's type.\n */\n\n\nfunction validateExplicitKey(element, parentType) {\n  {\n    if (!element._store || element._store.validated || element.key != null) {\n      return;\n    }\n\n    element._store.validated = true;\n    var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);\n\n    if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {\n      return;\n    }\n\n    ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a\n    // property, it may be the creator of the child that's responsible for\n    // assigning it a key.\n\n    var childOwner = '';\n\n    if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {\n      // Give the component that originally created this child.\n      childOwner = \" It was passed a child from \" + getComponentNameFromType(element._owner.type) + \".\";\n    }\n\n    setCurrentlyValidatingElement$1(element);\n\n    error('Each child in a list should have a unique \"key\" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);\n\n    setCurrentlyValidatingElement$1(null);\n  }\n}\n/**\n * Ensure that every element either is passed in a static location, in an\n * array with an explicit keys property defined, or in an object literal\n * with valid key property.\n *\n * @internal\n * @param {ReactNode} node Statically passed child of any type.\n * @param {*} parentType node's parent's type.\n */\n\n\nfunction validateChildKeys(node, parentType) {\n  {\n    if (typeof node !== 'object') {\n      return;\n    }\n\n    if (isArray(node)) {\n      for (var i = 0; i < node.length; i++) {\n        var child = node[i];\n\n        if (isValidElement(child)) {\n          validateExplicitKey(child, parentType);\n        }\n      }\n    } else if (isValidElement(node)) {\n      // This element was passed in a valid location.\n      if (node._store) {\n        node._store.validated = true;\n      }\n    } else if (node) {\n      var iteratorFn = getIteratorFn(node);\n\n      if (typeof iteratorFn === 'function') {\n        // Entry iterators used to provide implicit keys,\n        // but now we print a separate warning for them later.\n        if (iteratorFn !== node.entries) {\n          var iterator = iteratorFn.call(node);\n          var step;\n\n          while (!(step = iterator.next()).done) {\n            if (isValidElement(step.value)) {\n              validateExplicitKey(step.value, parentType);\n            }\n          }\n        }\n      }\n    }\n  }\n}\n/**\n * Given an element, validate that its props follow the propTypes definition,\n * provided by the type.\n *\n * @param {ReactElement} element\n */\n\n\nfunction validatePropTypes(element) {\n  {\n    var type = element.type;\n\n    if (type === null || type === undefined || typeof type === 'string') {\n      return;\n    }\n\n    var propTypes;\n\n    if (typeof type === 'function') {\n      propTypes = type.propTypes;\n    } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.\n    // Inner props are checked in the reconciler.\n    type.$$typeof === REACT_MEMO_TYPE)) {\n      propTypes = type.propTypes;\n    } else {\n      return;\n    }\n\n    if (propTypes) {\n      // Intentionally inside to avoid triggering lazy initializers:\n      var name = getComponentNameFromType(type);\n      checkPropTypes(propTypes, element.props, 'prop', name, element);\n    } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {\n      propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:\n\n      var _name = getComponentNameFromType(type);\n\n      error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');\n    }\n\n    if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {\n      error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');\n    }\n  }\n}\n/**\n * Given a fragment, validate that it can only be provided with fragment props\n * @param {ReactElement} fragment\n */\n\n\nfunction validateFragmentProps(fragment) {\n  {\n    var keys = Object.keys(fragment.props);\n\n    for (var i = 0; i < keys.length; i++) {\n      var key = keys[i];\n\n      if (key !== 'children' && key !== 'key') {\n        setCurrentlyValidatingElement$1(fragment);\n\n        error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);\n\n        setCurrentlyValidatingElement$1(null);\n        break;\n      }\n    }\n\n    if (fragment.ref !== null) {\n      setCurrentlyValidatingElement$1(fragment);\n\n      error('Invalid attribute `ref` supplied to `React.Fragment`.');\n\n      setCurrentlyValidatingElement$1(null);\n    }\n  }\n}\n\nvar didWarnAboutKeySpread = {};\nfunction jsxWithValidation(type, props, key, isStaticChildren, source, self) {\n  {\n    var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to\n    // succeed and there will likely be errors in render.\n\n    if (!validType) {\n      var info = '';\n\n      if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {\n        info += ' You likely forgot to export your component from the file ' + \"it's defined in, or you might have mixed up default and named imports.\";\n      }\n\n      var sourceInfo = getSourceInfoErrorAddendum(source);\n\n      if (sourceInfo) {\n        info += sourceInfo;\n      } else {\n        info += getDeclarationErrorAddendum();\n      }\n\n      var typeString;\n\n      if (type === null) {\n        typeString = 'null';\n      } else if (isArray(type)) {\n        typeString = 'array';\n      } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {\n        typeString = \"<\" + (getComponentNameFromType(type.type) || 'Unknown') + \" />\";\n        info = ' Did you accidentally export a JSX literal instead of a component?';\n      } else {\n        typeString = typeof type;\n      }\n\n      error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);\n    }\n\n    var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.\n    // TODO: Drop this when these are no longer allowed as the type argument.\n\n    if (element == null) {\n      return element;\n    } // Skip key warning if the type isn't valid since our key validation logic\n    // doesn't expect a non-string/function type and can throw confusing errors.\n    // We don't want exception behavior to differ between dev and prod.\n    // (Rendering will throw with a helpful message and as soon as the type is\n    // fixed, the key warnings will appear.)\n\n\n    if (validType) {\n      var children = props.children;\n\n      if (children !== undefined) {\n        if (isStaticChildren) {\n          if (isArray(children)) {\n            for (var i = 0; i < children.length; i++) {\n              validateChildKeys(children[i], type);\n            }\n\n            if (Object.freeze) {\n              Object.freeze(children);\n            }\n          } else {\n            error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');\n          }\n        } else {\n          validateChildKeys(children, type);\n        }\n      }\n    }\n\n    {\n      if (hasOwnProperty.call(props, 'key')) {\n        var componentName = getComponentNameFromType(type);\n        var keys = Object.keys(props).filter(function (k) {\n          return k !== 'key';\n        });\n        var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';\n\n        if (!didWarnAboutKeySpread[componentName + beforeExample]) {\n          var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';\n\n          error('A props object containing a \"key\" prop is being spread into JSX:\\n' + '  let props = %s;\\n' + '  <%s {...props} />\\n' + 'React keys must be passed directly to JSX without using spread:\\n' + '  let props = %s;\\n' + '  <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);\n\n          didWarnAboutKeySpread[componentName + beforeExample] = true;\n        }\n      }\n    }\n\n    if (type === REACT_FRAGMENT_TYPE) {\n      validateFragmentProps(element);\n    } else {\n      validatePropTypes(element);\n    }\n\n    return element;\n  }\n} // These two functions exist to still get child warnings in dev\n// even with the prod transform. This means that jsxDEV is purely\n// opt-in behavior for better messages but that we won't stop\n// giving you warnings if you use production apis.\n\nfunction jsxWithValidationStatic(type, props, key) {\n  {\n    return jsxWithValidation(type, props, key, true);\n  }\n}\nfunction jsxWithValidationDynamic(type, props, key) {\n  {\n    return jsxWithValidation(type, props, key, false);\n  }\n}\n\nvar jsx =  jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.\n// for now we can ship identical prod functions\n\nvar jsxs =  jsxWithValidationStatic ;\n\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsx;\nexports.jsxs = jsxs;\n  })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('./cjs/react-jsx-runtime.production.min.js');\n} else {\n  module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","/**\n * Analytics interface for DoshaCalculator.\n * Host app (e.g. hanuman) should pass an implementation via the analytics prop.\n */\n\nexport const FLOATING_CTA_STATUS = {\n  all_fields_filled: 'all_fields_filled',\n  fields_not_filled: 'fields_not_filled',\n  puja_clicked: 'puja_clicked',\n} as const\n\nexport type FloatingCtaStatus = (typeof FLOATING_CTA_STATUS)[keyof typeof FLOATING_CTA_STATUS]\n\nexport interface DoshaAnalytics {\n  trackDoshaCalculatorWebView?(): void\n  trackDoshaSectionImpression?(params: { section: string; timestamp?: string }): void\n  trackFloatingCtaClicked?(status: FloatingCtaStatus): void\n  trackFormFillInitiated?(): void\n  trackNameSectionClicked?(): void\n  trackNameSectionFilled?(): void\n  trackDobClicked?(): void\n  trackDobFilled?(): void\n  trackTimeClicked?(): void\n  trackTimeFilled?(): void\n  trackTimeCheckboxClicked?(): void\n  trackPlaceOfBirthClicked?(): void\n  trackPlaceOfBirthChosen?(placeValue: string): void\n  trackReadMoreReviewsClicked?(): void\n  trackFaqQuestionClicked?(questionText: string): void\n  trackLanguageClicked?(selectedLanguage: string): void\n  trackLanguageChanged?(lang: string): void\n  trackDoshaCalculatorResultBookCtaClicked?(params: {\n    position: string\n    url: string\n    isOldDosha?: boolean\n  }): void\n  trackDoshaCalculatorResultPageView?(): void\n  trackDoshaCalculatorResultViewKundliClick?(): void\n}\n","//#region src/lib/tracingRegistry.ts\nconst EXTRACTOR_KEY = Symbol.for(\"@supabase/supabase-js.traceContextExtractor\");\n/**\n* Register the trace context extractor used by all Supabase clients in this\n* process. Called by the `@supabase/supabase-js/tracing` subpath as an import\n* side effect; the last registration wins.\n*/\nfunction registerTraceContextExtractor(extractor) {\n\tglobalThis[EXTRACTOR_KEY] = extractor;\n}\n/**\n* The currently registered trace context extractor, if any.\n*/\nfunction getTraceContextExtractor() {\n\treturn globalThis[EXTRACTOR_KEY];\n}\n\n//#endregion\nexport { registerTraceContextExtractor as n, getTraceContextExtractor as t };\n//# sourceMappingURL=tracingRegistry.mjs.map","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n  extendStatics = Object.setPrototypeOf ||\n      ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n      function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n  return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n  if (typeof b !== \"function\" && b !== null)\n      throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n  extendStatics(d, b);\n  function __() { this.constructor = d; }\n  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n  __assign = Object.assign || function __assign(t) {\n      for (var s, i = 1, n = arguments.length; i < n; i++) {\n          s = arguments[i];\n          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n      }\n      return t;\n  }\n  return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n  var t = {};\n  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n      t[p] = s[p];\n  if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n      for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n          if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n              t[p[i]] = s[p[i]];\n      }\n  return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n  if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n  return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n  return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n  function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n  var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n  var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n  var _, done = false;\n  for (var i = decorators.length - 1; i >= 0; i--) {\n      var context = {};\n      for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n      for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n      context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n      var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n      if (kind === \"accessor\") {\n          if (result === void 0) continue;\n          if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n          if (_ = accept(result.get)) descriptor.get = _;\n          if (_ = accept(result.set)) descriptor.set = _;\n          if (_ = accept(result.init)) initializers.unshift(_);\n      }\n      else if (_ = accept(result)) {\n          if (kind === \"field\") initializers.unshift(_);\n          else descriptor[key] = _;\n      }\n  }\n  if (target) Object.defineProperty(target, contextIn.name, descriptor);\n  done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n  var useValue = arguments.length > 2;\n  for (var i = 0; i < initializers.length; i++) {\n      value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n  }\n  return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n  return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n  if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n  return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n  if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n  return new (P || (P = Promise))(function (resolve, reject) {\n      function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n      function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n      function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n      step((generator = generator.apply(thisArg, _arguments || [])).next());\n  });\n}\n\nexport function __generator(thisArg, body) {\n  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n  return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n  function verb(n) { return function (v) { return step([n, v]); }; }\n  function step(op) {\n      if (f) throw new TypeError(\"Generator is already executing.\");\n      while (g && (g = 0, op[0] && (_ = 0)), _) try {\n          if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n          if (y = 0, t) op = [op[0] & 2, t.value];\n          switch (op[0]) {\n              case 0: case 1: t = op; break;\n              case 4: _.label++; return { value: op[1], done: false };\n              case 5: _.label++; y = op[1]; op = [0]; continue;\n              case 7: op = _.ops.pop(); _.trys.pop(); continue;\n              default:\n                  if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n                  if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n                  if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n                  if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n                  if (t[2]) _.ops.pop();\n                  _.trys.pop(); continue;\n          }\n          op = body.call(thisArg, _);\n      } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n      if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n  }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n  if (k2 === undefined) k2 = k;\n  var desc = Object.getOwnPropertyDescriptor(m, k);\n  if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n      desc = { enumerable: true, get: function() { return m[k]; } };\n  }\n  Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n  if (k2 === undefined) k2 = k;\n  o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n  for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n  var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n  if (m) return m.call(o);\n  if (o && typeof o.length === \"number\") return {\n      next: function () {\n          if (o && i >= o.length) o = void 0;\n          return { value: o && o[i++], done: !o };\n      }\n  };\n  throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n  var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n  if (!m) return o;\n  var i = m.call(o), r, ar = [], e;\n  try {\n      while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n  }\n  catch (error) { e = { error: error }; }\n  finally {\n      try {\n          if (r && !r.done && (m = i[\"return\"])) m.call(i);\n      }\n      finally { if (e) throw e.error; }\n  }\n  return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n  for (var ar = [], i = 0; i < arguments.length; i++)\n      ar = ar.concat(__read(arguments[i]));\n  return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n  for (var r = Array(s), k = 0, i = 0; i < il; i++)\n      for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n          r[k] = a[j];\n  return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n      if (ar || !(i in from)) {\n          if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n          ar[i] = from[i];\n      }\n  }\n  return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n  return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n  if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n  var g = generator.apply(thisArg, _arguments || []), i, q = [];\n  return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n  function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n  function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n  function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n  function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n  function fulfill(value) { resume(\"next\", value); }\n  function reject(value) { resume(\"throw\", value); }\n  function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n  var i, p;\n  return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n  function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n  if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n  var m = o[Symbol.asyncIterator], i;\n  return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n  function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n  if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n  return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n  Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n  o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n  ownKeys = Object.getOwnPropertyNames || function (o) {\n    var ar = [];\n    for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n    return ar;\n  };\n  return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n  if (mod && mod.__esModule) return mod;\n  var result = {};\n  if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n  __setModuleDefault(result, mod);\n  return result;\n}\n\nexport function __importDefault(mod) {\n  return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n  if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n  if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n  return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n  if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n  if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n  if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n  return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n  if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n  return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n  if (value !== null && value !== void 0) {\n    if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n    var dispose, inner;\n    if (async) {\n      if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n      dispose = value[Symbol.asyncDispose];\n    }\n    if (dispose === void 0) {\n      if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n      dispose = value[Symbol.dispose];\n      if (async) inner = dispose;\n    }\n    if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n    if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n    env.stack.push({ value: value, dispose: dispose, async: async });\n  }\n  else if (async) {\n    env.stack.push({ async: true });\n  }\n  return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n  var e = new Error(message);\n  return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n  function fail(e) {\n    env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n    env.hasError = true;\n  }\n  var r, s = 0;\n  function next() {\n    while (r = env.stack.pop()) {\n      try {\n        if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n        if (r.dispose) {\n          var result = r.dispose.call(r.value);\n          if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n        }\n        else s |= 1;\n      }\n      catch (e) {\n        fail(e);\n      }\n    }\n    if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n    if (env.hasError) throw env.error;\n  }\n  return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n  if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n      return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n          return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n      });\n  }\n  return path;\n}\n\nexport default {\n  __extends,\n  __assign,\n  __rest,\n  __decorate,\n  __param,\n  __esDecorate,\n  __runInitializers,\n  __propKey,\n  __setFunctionName,\n  __metadata,\n  __awaiter,\n  __generator,\n  __createBinding,\n  __exportStar,\n  __values,\n  __read,\n  __spread,\n  __spreadArrays,\n  __spreadArray,\n  __await,\n  __asyncGenerator,\n  __asyncDelegator,\n  __asyncValues,\n  __makeTemplateObject,\n  __importStar,\n  __importDefault,\n  __classPrivateFieldGet,\n  __classPrivateFieldSet,\n  __classPrivateFieldIn,\n  __addDisposableResource,\n  __disposeResources,\n  __rewriteRelativeImportExtension,\n};\n","export const resolveFetch = (customFetch) => {\n    if (customFetch) {\n        return (...args) => customFetch(...args);\n    }\n    return (...args) => fetch(...args);\n};\n//# sourceMappingURL=helper.js.map","/**\n * Base error for Supabase Edge Function invocations.\n *\n * @example\n * ```ts\n * import { FunctionsError } from '@supabase/functions-js'\n *\n * throw new FunctionsError('Unexpected error invoking function', 'FunctionsError', {\n *   requestId: 'abc123',\n * })\n * ```\n */\nexport class FunctionsError extends Error {\n    constructor(message, name = 'FunctionsError', context) {\n        super(message);\n        this.name = name;\n        this.context = context;\n    }\n    toJSON() {\n        return {\n            name: this.name,\n            message: this.message,\n            context: this.context,\n        };\n    }\n}\n/**\n * Error thrown when the network request to an Edge Function fails.\n *\n * @example\n * ```ts\n * import { FunctionsFetchError } from '@supabase/functions-js'\n *\n * throw new FunctionsFetchError({ requestId: 'abc123' })\n * ```\n */\nexport class FunctionsFetchError extends FunctionsError {\n    constructor(context) {\n        super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context);\n    }\n}\n/**\n * Error thrown when the Supabase relay cannot reach the Edge Function.\n *\n * @example\n * ```ts\n * import { FunctionsRelayError } from '@supabase/functions-js'\n *\n * throw new FunctionsRelayError({ region: 'us-east-1' })\n * ```\n */\nexport class FunctionsRelayError extends FunctionsError {\n    constructor(context) {\n        super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context);\n    }\n}\n/**\n * Error thrown when the Edge Function returns a non-2xx status code.\n *\n * @example\n * ```ts\n * import { FunctionsHttpError } from '@supabase/functions-js'\n *\n * throw new FunctionsHttpError({ status: 500 })\n * ```\n */\nexport class FunctionsHttpError extends FunctionsError {\n    constructor(context) {\n        super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context);\n    }\n}\n// Define the enum for the 'region' property\nexport var FunctionRegion;\n(function (FunctionRegion) {\n    FunctionRegion[\"Any\"] = \"any\";\n    FunctionRegion[\"ApNortheast1\"] = \"ap-northeast-1\";\n    FunctionRegion[\"ApNortheast2\"] = \"ap-northeast-2\";\n    FunctionRegion[\"ApSouth1\"] = \"ap-south-1\";\n    FunctionRegion[\"ApSoutheast1\"] = \"ap-southeast-1\";\n    FunctionRegion[\"ApSoutheast2\"] = \"ap-southeast-2\";\n    FunctionRegion[\"CaCentral1\"] = \"ca-central-1\";\n    FunctionRegion[\"EuCentral1\"] = \"eu-central-1\";\n    FunctionRegion[\"EuWest1\"] = \"eu-west-1\";\n    FunctionRegion[\"EuWest2\"] = \"eu-west-2\";\n    FunctionRegion[\"EuWest3\"] = \"eu-west-3\";\n    FunctionRegion[\"SaEast1\"] = \"sa-east-1\";\n    FunctionRegion[\"UsEast1\"] = \"us-east-1\";\n    FunctionRegion[\"UsWest1\"] = \"us-west-1\";\n    FunctionRegion[\"UsWest2\"] = \"us-west-2\";\n})(FunctionRegion || (FunctionRegion = {}));\n//# sourceMappingURL=types.js.map","import { __awaiter } from \"tslib\";\nimport { resolveFetch } from './helper';\nimport { FunctionRegion, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError, } from './types';\n/**\n * Client for invoking Supabase Edge Functions.\n */\nexport class FunctionsClient {\n    /**\n     * Creates a new Functions client bound to an Edge Functions URL.\n     *\n     * @example Using supabase-js (recommended)\n     * ```ts\n     * import { createClient } from '@supabase/supabase-js'\n     *\n     * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n     * const { data, error } = await supabase.functions.invoke('hello-world')\n     * ```\n     *\n     * @category Edge Functions\n     *\n     * @example Standalone import for bundle-sensitive environments\n     * ```ts\n     * import { FunctionsClient, FunctionRegion } from '@supabase/functions-js'\n     *\n     * const functions = new FunctionsClient('https://xyzcompany.supabase.co/functions/v1', {\n     *   headers: { apikey: 'your-publishable-key' },\n     *   region: FunctionRegion.UsEast1,\n     * })\n     * ```\n     */\n    constructor(url, { headers = {}, customFetch, region = FunctionRegion.Any, } = {}) {\n        this.url = url;\n        this.headers = headers;\n        this.region = region;\n        this.fetch = resolveFetch(customFetch);\n    }\n    /**\n     * Updates the authorization header\n     * @param token - the new jwt token sent in the authorisation header\n     *\n     * @category Edge Functions\n     *\n     * @example Setting the authorization header\n     * ```ts\n     * functions.setAuth(session.access_token)\n     * ```\n     */\n    setAuth(token) {\n        this.headers.Authorization = `Bearer ${token}`;\n    }\n    /**\n     * Invokes a function\n     * @param functionName - The name of the Function to invoke.\n     * @param options - Options for invoking the Function.\n     * @example\n     * ```ts\n     * const { data, error } = await functions.invoke('hello-world', {\n     *   body: { name: 'Ada' },\n     * })\n     * ```\n     *\n     * @category Edge Functions\n     *\n     * @remarks\n     * - The API key is sent in the `apikey` header. The `Authorization` header is reserved\n     *   for the signed-in user's JWT (or a custom auth token) — when there is no session, a\n     *   new-format API key (`sb_publishable_…` / `sb_secret_…`) is not sent as a Bearer token.\n     * - Invoke params generally match the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) spec.\n     * - When you pass in a body to your function, we automatically attach the Content-Type header for `Blob`, `ArrayBuffer`, `File`, `FormData` and `String`. If it doesn't match any of these types we assume the payload is `json`, serialize it and attach the `Content-Type` header as `application/json`. You can override this behavior by passing in a `Content-Type` header of your own.\n     * - Responses are automatically parsed as `json`, `blob` and `form-data` depending on the `Content-Type` header sent by your function. Responses are parsed as `text` by default.\n     *\n     * @example Basic invocation\n     * ```js\n     * const { data, error } = await supabase.functions.invoke('hello', {\n     *   body: { foo: 'bar' }\n     * })\n     * ```\n     *\n     * @exampleDescription Error handling\n     * A `FunctionsHttpError` error is returned if your function throws an error, `FunctionsRelayError` if the Supabase Relay has an error processing your function and `FunctionsFetchError` if there is a network error in calling your function. Log the full error object so fields like `name`, `context`, and any structured body aren't hidden.\n     *\n     * @example Error handling\n     * ```js\n     * import { FunctionsHttpError, FunctionsRelayError, FunctionsFetchError } from \"@supabase/supabase-js\";\n     *\n     * const { data, error } = await supabase.functions.invoke('hello', {\n     *   headers: {\n     *     \"my-custom-header\": 'my-custom-header-value'\n     *   },\n     *   body: { foo: 'bar' }\n     * })\n     *\n     * if (error instanceof FunctionsHttpError) {\n     *   const errorMessage = await error.context.json()\n     *   console.error('Function returned an error', errorMessage)\n     * } else if (error instanceof FunctionsRelayError) {\n     *   console.error('Relay error:', error)\n     * } else if (error instanceof FunctionsFetchError) {\n     *   console.error('Fetch error:', error)\n     * }\n     * ```\n     *\n     * @exampleDescription Passing custom headers\n     * You can pass custom headers to your function. Note: supabase-js automatically passes the `Authorization` header with the signed in user's JWT.\n     *\n     * @example Passing custom headers\n     * ```js\n     * const { data, error } = await supabase.functions.invoke('hello', {\n     *   headers: {\n     *     \"my-custom-header\": 'my-custom-header-value'\n     *   },\n     *   body: { foo: 'bar' }\n     * })\n     * ```\n     *\n     * @exampleDescription Calling with DELETE HTTP verb\n     * You can also set the HTTP verb to `DELETE` when calling your Edge Function.\n     *\n     * @example Calling with DELETE HTTP verb\n     * ```js\n     * const { data, error } = await supabase.functions.invoke('hello', {\n     *   headers: {\n     *     \"my-custom-header\": 'my-custom-header-value'\n     *   },\n     *   body: { foo: 'bar' },\n     *   method: 'DELETE'\n     * })\n     * ```\n     *\n     * @exampleDescription Invoking a Function in the UsEast1 region\n     * Here are the available regions:\n     * - `FunctionRegion.Any`\n     * - `FunctionRegion.ApNortheast1`\n     * - `FunctionRegion.ApNortheast2`\n     * - `FunctionRegion.ApSouth1`\n     * - `FunctionRegion.ApSoutheast1`\n     * - `FunctionRegion.ApSoutheast2`\n     * - `FunctionRegion.CaCentral1`\n     * - `FunctionRegion.EuCentral1`\n     * - `FunctionRegion.EuWest1`\n     * - `FunctionRegion.EuWest2`\n     * - `FunctionRegion.EuWest3`\n     * - `FunctionRegion.SaEast1`\n     * - `FunctionRegion.UsEast1`\n     * - `FunctionRegion.UsWest1`\n     * - `FunctionRegion.UsWest2`\n     *\n     * @example Invoking a Function in the UsEast1 region\n     * ```js\n     * import { createClient, FunctionRegion } from '@supabase/supabase-js'\n     *\n     * const { data, error } = await supabase.functions.invoke('hello', {\n     *   body: { foo: 'bar' },\n     *   region: FunctionRegion.UsEast1\n     * })\n     * ```\n     *\n     * @exampleDescription Calling with GET HTTP verb\n     * You can also set the HTTP verb to `GET` when calling your Edge Function.\n     *\n     * @example Calling with GET HTTP verb\n     * ```js\n     * const { data, error } = await supabase.functions.invoke('hello', {\n     *   headers: {\n     *     \"my-custom-header\": 'my-custom-header-value'\n     *   },\n     *   method: 'GET'\n     * })\n     * ```\n     *\n     * @example Standalone client invoke\n     * ```ts\n     * const { data, error } = await functions.invoke('hello-world', {\n     *   body: { name: 'Ada' },\n     * })\n     * ```\n     */\n    invoke(functionName_1) {\n        return __awaiter(this, arguments, void 0, function* (functionName, options = {}) {\n            var _a, _b;\n            let timeoutId;\n            let timeoutController;\n            let onAbort;\n            try {\n                const { headers, method, body: functionArgs, signal, timeout } = options;\n                let _headers = {};\n                let { region } = options;\n                if (!region) {\n                    region = this.region;\n                }\n                // Add region as query parameter using URL API\n                const url = new URL(`${this.url}/${functionName}`);\n                if (region && region !== 'any') {\n                    _headers['x-region'] = region;\n                    url.searchParams.set('forceFunctionRegion', region);\n                }\n                let body;\n                // HTTP header names are case-insensitive, so detect a caller-supplied Content-Type\n                // regardless of casing — otherwise the SDK injects a second, conflicting Content-Type.\n                const hasContentTypeHeader = !!headers && Object.keys(headers).some((key) => key.toLowerCase() === 'content-type');\n                if (functionArgs && !hasContentTypeHeader) {\n                    if ((typeof Blob !== 'undefined' && functionArgs instanceof Blob) ||\n                        functionArgs instanceof ArrayBuffer) {\n                        // will work for File as File inherits Blob\n                        // also works for ArrayBuffer as it is the same underlying structure as a Blob\n                        _headers['Content-Type'] = 'application/octet-stream';\n                        body = functionArgs;\n                    }\n                    else if (typeof functionArgs === 'string') {\n                        // plain string\n                        _headers['Content-Type'] = 'text/plain';\n                        body = functionArgs;\n                    }\n                    else if (typeof FormData !== 'undefined' && functionArgs instanceof FormData) {\n                        // don't set content-type headers\n                        // Request will automatically add the right boundary value\n                        body = functionArgs;\n                    }\n                    else {\n                        // default, assume this is JSON\n                        _headers['Content-Type'] = 'application/json';\n                        body = JSON.stringify(functionArgs);\n                    }\n                }\n                else {\n                    if (functionArgs &&\n                        typeof functionArgs !== 'string' &&\n                        !(typeof Blob !== 'undefined' && functionArgs instanceof Blob) &&\n                        !(functionArgs instanceof ArrayBuffer) &&\n                        !(typeof FormData !== 'undefined' && functionArgs instanceof FormData)) {\n                        body = JSON.stringify(functionArgs);\n                    }\n                    else {\n                        body = functionArgs;\n                    }\n                }\n                // Handle timeout by creating an AbortController\n                let effectiveSignal = signal;\n                if (timeout) {\n                    timeoutController = new AbortController();\n                    timeoutId = setTimeout(() => timeoutController.abort(), timeout);\n                    // If user provided their own signal, we need to respect both\n                    if (signal) {\n                        effectiveSignal = timeoutController.signal;\n                        // If the user's signal is aborted, abort our timeout controller too.\n                        // Store the listener so we can clean it up in finally.\n                        onAbort = () => timeoutController.abort();\n                        signal.addEventListener('abort', onAbort);\n                    }\n                    else {\n                        effectiveSignal = timeoutController.signal;\n                    }\n                }\n                const response = yield this.fetch(url.toString(), {\n                    method: method || 'POST',\n                    // headers priority is (high to low):\n                    // 1. invoke-level headers\n                    // 2. client-level headers\n                    // 3. default Content-Type header\n                    headers: Object.assign(Object.assign(Object.assign({}, _headers), this.headers), headers),\n                    body,\n                    signal: effectiveSignal,\n                }).catch((fetchError) => {\n                    throw new FunctionsFetchError(fetchError);\n                });\n                const isRelayError = response.headers.get('x-relay-error');\n                if (isRelayError && isRelayError === 'true') {\n                    throw new FunctionsRelayError(response);\n                }\n                if (!response.ok) {\n                    throw new FunctionsHttpError(response);\n                }\n                // HTTP media types are case-insensitive (RFC 9110), so normalize before\n                // matching — otherwise an \"Application/JSON\" response falls through to text.\n                let responseType = ((_a = response.headers.get('Content-Type')) !== null && _a !== void 0 ? _a : 'text/plain')\n                    .split(';')[0]\n                    .trim()\n                    .toLowerCase();\n                let data;\n                if (responseType === 'application/json') {\n                    data = yield response.json();\n                }\n                else if (responseType === 'application/octet-stream' ||\n                    responseType === 'application/pdf') {\n                    data = yield response.blob();\n                }\n                else if (responseType === 'text/event-stream') {\n                    data = response;\n                }\n                else if (responseType === 'multipart/form-data') {\n                    data = yield response.formData();\n                }\n                else {\n                    // default to text\n                    data = yield response.text();\n                }\n                return { data, error: null, response };\n            }\n            catch (error) {\n                return {\n                    data: null,\n                    error,\n                    response: error instanceof FunctionsHttpError || error instanceof FunctionsRelayError\n                        ? error.context\n                        : undefined,\n                };\n            }\n            finally {\n                // Clear the timeout if it was set\n                if (timeoutId) {\n                    clearTimeout(timeoutId);\n                }\n                // Remove the cross-signal listener to prevent memory leaks when the caller\n                // reuses the same AbortSignal across multiple invocations.\n                if (onAbort) {\n                    (_b = options.signal) === null || _b === void 0 ? void 0 : _b.removeEventListener('abort', onAbort);\n                }\n            }\n        });\n    }\n}\n//# sourceMappingURL=FunctionsClient.js.map","//#region src/PostgrestError.ts\n/**\n* Error format\n*\n* Returned by every PostgREST request that fails. When something fails, the\n* single most useful field is usually `hint` — Postgres often returns the\n* actionable fix there, not in `message`. Always log the full object (e.g.\n* `console.error(error)`); logging only `error.message` hides the hint.\n*\n* Read the fields in roughly this order of usefulness:\n*\n* - `hint` — actionable guidance from the database when available. For\n*   permission-denied errors (`42501`), this is the literal SQL to fix the\n*   problem, e.g.\n*   `\"Grant the required privileges to the current role with: GRANT SELECT ON public.users TO anon;\"`.\n*   Missing column? `hint` suggests the column you probably meant. Whenever\n*   Postgres knows the fix, it puts it in `hint`.\n* - `code` — stable error code from PostgREST (e.g. `PGRST301`) or Postgres\n*   (e.g. `42501`). Branch on this rather than on `message` text.\n* - `details` — extra context, often the offending value, key, or row.\n* - `message` — human-readable summary. Useful in UI strings; less useful\n*   for debugging.\n*\n* {@link https://postgrest.org/en/stable/api.html?highlight=options#errors-and-http-status-codes}\n*/\nvar PostgrestError = class extends Error {\n\t/**\n\t* @example\n\t* ```ts\n\t* import PostgrestError from '@supabase/postgrest-js'\n\t*\n\t* throw new PostgrestError({\n\t*   message: 'Row level security prevented the request',\n\t*   details: 'RLS denied the insert',\n\t*   hint: 'Check your policies',\n\t*   code: 'PGRST301',\n\t* })\n\t* ```\n\t*/\n\tconstructor(context) {\n\t\tsuper(context.message);\n\t\tthis.name = \"PostgrestError\";\n\t\tthis.details = context.details;\n\t\tthis.hint = context.hint;\n\t\tthis.code = context.code;\n\t}\n\ttoJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tmessage: this.message,\n\t\t\tdetails: this.details,\n\t\t\thint: this.hint,\n\t\t\tcode: this.code\n\t\t};\n\t}\n};\n\n//#endregion\n//#region src/types/common/common.ts\n/**\n* Default number of retry attempts.\n*/\nconst DEFAULT_MAX_RETRIES = 3;\n/**\n* Default exponential backoff delay function.\n* Delays: 1s, 2s, 4s, 8s, ... (max 30s)\n*\n* @param attemptIndex - Zero-based index of the retry attempt\n* @returns Delay in milliseconds before the next retry\n*/\nconst getRetryDelay = (attemptIndex) => Math.min(1e3 * 2 ** attemptIndex, 3e4);\n/**\n* Status codes that are safe to retry.\n* 520 = Cloudflare timeout/connection errors (transient)\n* 503 = PostgREST schema cache not yet loaded (transient, signals retry via Retry-After header)\n*/\nconst RETRYABLE_STATUS_CODES = [520, 503];\n/**\n* HTTP methods that are safe to retry (idempotent operations).\n*/\nconst RETRYABLE_METHODS = [\n\t\"GET\",\n\t\"HEAD\",\n\t\"OPTIONS\"\n];\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.103.0/helpers/typeof.js\nfunction _typeof(o) {\n\t\"@babel/helpers - typeof\";\n\treturn _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function(o$1) {\n\t\treturn typeof o$1;\n\t} : function(o$1) {\n\t\treturn o$1 && \"function\" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? \"symbol\" : typeof o$1;\n\t}, _typeof(o);\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.103.0/helpers/toPrimitive.js\nfunction toPrimitive(t, r) {\n\tif (\"object\" != _typeof(t) || !t) return t;\n\tvar e = t[Symbol.toPrimitive];\n\tif (void 0 !== e) {\n\t\tvar i = e.call(t, r || \"default\");\n\t\tif (\"object\" != _typeof(i)) return i;\n\t\tthrow new TypeError(\"@@toPrimitive must return a primitive value.\");\n\t}\n\treturn (\"string\" === r ? String : Number)(t);\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.103.0/helpers/toPropertyKey.js\nfunction toPropertyKey(t) {\n\tvar i = toPrimitive(t, \"string\");\n\treturn \"symbol\" == _typeof(i) ? i : i + \"\";\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.103.0/helpers/defineProperty.js\nfunction _defineProperty(e, r, t) {\n\treturn (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n\t\tvalue: t,\n\t\tenumerable: !0,\n\t\tconfigurable: !0,\n\t\twritable: !0\n\t}) : e[r] = t, e;\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.103.0/helpers/objectSpread2.js\nfunction ownKeys(e, r) {\n\tvar t = Object.keys(e);\n\tif (Object.getOwnPropertySymbols) {\n\t\tvar o = Object.getOwnPropertySymbols(e);\n\t\tr && (o = o.filter(function(r$1) {\n\t\t\treturn Object.getOwnPropertyDescriptor(e, r$1).enumerable;\n\t\t})), t.push.apply(t, o);\n\t}\n\treturn t;\n}\nfunction _objectSpread2(e) {\n\tfor (var r = 1; r < arguments.length; r++) {\n\t\tvar t = null != arguments[r] ? arguments[r] : {};\n\t\tr % 2 ? ownKeys(Object(t), !0).forEach(function(r$1) {\n\t\t\t_defineProperty(e, r$1, t[r$1]);\n\t\t}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) {\n\t\t\tObject.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1));\n\t\t});\n\t}\n\treturn e;\n}\n\n//#endregion\n//#region src/fetchWithRetry.ts\n/**\n* Sleep for a given number of milliseconds.\n* If an AbortSignal is provided, the sleep resolves early when the signal is aborted.\n*/\nfunction sleep(ms, signal) {\n\treturn new Promise((resolve) => {\n\t\tif (signal === null || signal === void 0 ? void 0 : signal.aborted) {\n\t\t\tresolve();\n\t\t\treturn;\n\t\t}\n\t\tconst id = setTimeout(() => {\n\t\t\tsignal === null || signal === void 0 || signal.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tfunction onAbort() {\n\t\t\tclearTimeout(id);\n\t\t\tresolve();\n\t\t}\n\t\tsignal === null || signal === void 0 || signal.addEventListener(\"abort\", onAbort);\n\t});\n}\n/**\n* Check if a request should be retried based on method and status code.\n*/\nfunction shouldRetry(method, status, attemptCount, retryEnabled) {\n\tif (!retryEnabled || attemptCount >= DEFAULT_MAX_RETRIES) return false;\n\tif (!RETRYABLE_METHODS.includes(method)) return false;\n\tif (!RETRYABLE_STATUS_CODES.includes(status)) return false;\n\treturn true;\n}\n/**\n* Perform a request with the retry policy shared by every PostgREST call.\n*\n* Idempotent methods (GET, HEAD, OPTIONS) are retried up to\n* `DEFAULT_MAX_RETRIES` times when the fetch rejects or the server answers\n* with a retryable status (503, 520). The wait honours the `Retry-After`\n* header when present and backs off exponentially otherwise. Retried\n* attempts carry an `X-Retry-Count` header. Aborted requests and\n* non-idempotent methods are never retried: their rejection propagates\n* unchanged. A response body is drained before its request is retried.\n*/\nasync function fetchWithRetry(fetchImpl, url, request, retryEnabled) {\n\tlet attemptCount = 0;\n\twhile (true) {\n\t\tconst headers = _objectSpread2({}, request.headers);\n\t\tif (attemptCount > 0) headers[\"X-Retry-Count\"] = String(attemptCount);\n\t\tlet res;\n\t\ttry {\n\t\t\tres = await fetchImpl(url, {\n\t\t\t\tmethod: request.method,\n\t\t\t\theaders,\n\t\t\t\tbody: request.body,\n\t\t\t\tsignal: request.signal\n\t\t\t});\n\t\t} catch (fetchError) {\n\t\t\tif ((fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) === \"AbortError\" || (fetchError === null || fetchError === void 0 ? void 0 : fetchError.code) === \"ABORT_ERR\") throw fetchError;\n\t\t\tif (!RETRYABLE_METHODS.includes(request.method)) throw fetchError;\n\t\t\tif (retryEnabled && attemptCount < DEFAULT_MAX_RETRIES) {\n\t\t\t\tconst delay = getRetryDelay(attemptCount);\n\t\t\t\tattemptCount++;\n\t\t\t\tawait sleep(delay, request.signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow fetchError;\n\t\t}\n\t\tif (shouldRetry(request.method, res.status, attemptCount, retryEnabled)) {\n\t\t\tvar _res$headers$get, _res$headers;\n\t\t\tconst retryAfterHeader = (_res$headers$get = (_res$headers = res.headers) === null || _res$headers === void 0 ? void 0 : _res$headers.get(\"Retry-After\")) !== null && _res$headers$get !== void 0 ? _res$headers$get : null;\n\t\t\tconst delay = retryAfterHeader !== null ? Math.max(0, parseInt(retryAfterHeader, 10) || 0) * 1e3 : getRetryDelay(attemptCount);\n\t\t\tawait res.text();\n\t\t\tattemptCount++;\n\t\t\tawait sleep(delay, request.signal);\n\t\t\tcontinue;\n\t\t}\n\t\treturn res;\n\t}\n}\n\n//#endregion\n//#region src/PostgrestBuilder.ts\nvar PostgrestBuilder = class {\n\t/**\n\t* Creates a builder configured for a specific PostgREST request.\n\t*\n\t* @example Using supabase-js (recommended)\n\t* ```ts\n\t* import { createClient } from '@supabase/supabase-js'\n\t*\n\t* const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n\t* const { data, error } = await supabase.from('users').select('*')\n\t* ```\n\t*\n\t* @category Database\n\t*\n\t* @example Standalone import for bundle-sensitive environments\n\t* ```ts\n\t* import { PostgrestQueryBuilder } from '@supabase/postgrest-js'\n\t*\n\t* const builder = new PostgrestQueryBuilder(\n\t*   new URL('https://xyzcompany.supabase.co/rest/v1/users'),\n\t*   { headers: new Headers({ apikey: 'your-publishable-key' }) }\n\t* )\n\t* ```\n\t*/\n\tconstructor(builder) {\n\t\tvar _builder$shouldThrowO, _builder$isMaybeSingl, _builder$shouldStripN, _builder$urlLengthLim, _builder$retry;\n\t\tthis.shouldThrowOnError = false;\n\t\tthis.retryEnabled = true;\n\t\tthis.method = builder.method;\n\t\tthis.url = builder.url;\n\t\tthis.headers = new Headers(builder.headers);\n\t\tthis.schema = builder.schema;\n\t\tthis.body = builder.body;\n\t\tthis.shouldThrowOnError = (_builder$shouldThrowO = builder.shouldThrowOnError) !== null && _builder$shouldThrowO !== void 0 ? _builder$shouldThrowO : false;\n\t\tthis.signal = builder.signal;\n\t\tthis.isMaybeSingle = (_builder$isMaybeSingl = builder.isMaybeSingle) !== null && _builder$isMaybeSingl !== void 0 ? _builder$isMaybeSingl : false;\n\t\tthis.shouldStripNulls = (_builder$shouldStripN = builder.shouldStripNulls) !== null && _builder$shouldStripN !== void 0 ? _builder$shouldStripN : false;\n\t\tthis.urlLengthLimit = (_builder$urlLengthLim = builder.urlLengthLimit) !== null && _builder$urlLengthLim !== void 0 ? _builder$urlLengthLim : 8e3;\n\t\tthis.retryEnabled = (_builder$retry = builder.retry) !== null && _builder$retry !== void 0 ? _builder$retry : true;\n\t\tif (builder.fetch) this.fetch = builder.fetch;\n\t\telse this.fetch = fetch;\n\t}\n\t/**\n\t* If there's an error with the query, throwOnError will reject the promise by\n\t* throwing the error instead of returning it as part of a successful response.\n\t*\n\t* {@link https://github.com/supabase/supabase-js/issues/92}\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*/\n\tthrowOnError() {\n\t\tthis.shouldThrowOnError = true;\n\t\treturn this;\n\t}\n\t/**\n\t* Strip null values from the response data. Properties with `null` values\n\t* will be omitted from the returned JSON objects.\n\t*\n\t* Requires PostgREST 11.2.0+.\n\t*\n\t* {@link https://docs.postgrest.org/en/stable/references/api/resource_representation.html#stripped-nulls}\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*\n\t* @example With `select()`\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select()\n\t*   .stripNulls()\n\t* ```\n\t*\n\t* @exampleSql With `select()`\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text, bio text);\n\t*\n\t* insert into\n\t*   characters (id, name, bio)\n\t* values\n\t*   (1, 'Luke', null),\n\t*   (2, 'Leia', 'Princess of Alderaan');\n\t* ```\n\t*\n\t* @exampleResponse With `select()`\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"id\": 1,\n\t*       \"name\": \"Luke\"\n\t*     },\n\t*     {\n\t*       \"id\": 2,\n\t*       \"name\": \"Leia\",\n\t*       \"bio\": \"Princess of Alderaan\"\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*/\n\tstripNulls() {\n\t\tif (this.headers.get(\"Accept\") === \"text/csv\") throw new Error(\"stripNulls() cannot be used with csv()\");\n\t\tthis.shouldStripNulls = true;\n\t\treturn this;\n\t}\n\t/**\n\t* Set an HTTP header on this single PostgREST request, overriding any header\n\t* with the same name set on the client.\n\t*\n\t* This is an advanced escape hatch for one-off needs (passing a custom\n\t* `Authorization` for a single query, attaching a tracing header, etc.).\n\t* Most callers do not need it: configure client-wide headers via the\n\t* `headers` option when constructing the client, and authentication via\n\t* Supabase Auth.\n\t*\n\t* @param name - HTTP header name\n\t* @param value - HTTP header value\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*/\n\tsetHeader(name, value) {\n\t\tthis.headers = new Headers(this.headers);\n\t\tthis.headers.set(name, value);\n\t\treturn this;\n\t}\n\t/**\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*\n\t* Configure retry behavior for this request.\n\t*\n\t* By default, retries are enabled for idempotent requests (GET, HEAD, OPTIONS)\n\t* that fail with network errors or specific HTTP status codes (503, 520).\n\t* Retries use exponential backoff (1s, 2s, 4s) with a maximum of 3 attempts.\n\t*\n\t* @param enabled - Whether to enable retries for this request\n\t*\n\t* @example\n\t* ```ts\n\t* // Disable retries for a specific query\n\t* const { data, error } = await supabase\n\t*   .from('users')\n\t*   .select()\n\t*   .retry(false)\n\t* ```\n\t*/\n\tretry(enabled) {\n\t\tthis.retryEnabled = enabled;\n\t\treturn this;\n\t}\n\tthen(onfulfilled, onrejected) {\n\t\tvar _this = this;\n\t\tif (this.schema === void 0) {} else if ([\"GET\", \"HEAD\"].includes(this.method)) this.headers.set(\"Accept-Profile\", this.schema);\n\t\telse this.headers.set(\"Content-Profile\", this.schema);\n\t\tif (this.method !== \"GET\" && this.method !== \"HEAD\") this.headers.set(\"Content-Type\", \"application/json\");\n\t\tif (this.shouldStripNulls) {\n\t\t\tconst currentAccept = this.headers.get(\"Accept\");\n\t\t\tif (currentAccept === \"application/vnd.pgrst.object+json\") this.headers.set(\"Accept\", \"application/vnd.pgrst.object+json;nulls=stripped\");\n\t\t\telse if (!currentAccept || currentAccept === \"application/json\") this.headers.set(\"Accept\", \"application/vnd.pgrst.array+json;nulls=stripped\");\n\t\t}\n\t\tconst _fetch = this.fetch;\n\t\tconst executeWithRetry = async () => {\n\t\t\tconst headers = {};\n\t\t\t_this.headers.forEach((value, key) => {\n\t\t\t\theaders[key] = value;\n\t\t\t});\n\t\t\tconst res$1 = await fetchWithRetry(_fetch, _this.url.toString(), {\n\t\t\t\tmethod: _this.method,\n\t\t\t\theaders,\n\t\t\t\tbody: JSON.stringify(_this.body, (_, value) => typeof value === \"bigint\" ? value.toString() : value),\n\t\t\t\tsignal: _this.signal\n\t\t\t}, _this.retryEnabled);\n\t\t\treturn await _this.processResponse(res$1);\n\t\t};\n\t\tlet res = executeWithRetry();\n\t\tif (!this.shouldThrowOnError) res = res.catch((fetchError) => {\n\t\t\tvar _fetchError$name2;\n\t\t\tlet errorDetails = \"\";\n\t\t\tlet hint = \"\";\n\t\t\tlet code = \"\";\n\t\t\tconst cause = fetchError === null || fetchError === void 0 ? void 0 : fetchError.cause;\n\t\t\tif (cause) {\n\t\t\t\tvar _cause$message, _cause$code, _fetchError$name, _cause$name;\n\t\t\t\tconst causeMessage = (_cause$message = cause === null || cause === void 0 ? void 0 : cause.message) !== null && _cause$message !== void 0 ? _cause$message : \"\";\n\t\t\t\tconst causeCode = (_cause$code = cause === null || cause === void 0 ? void 0 : cause.code) !== null && _cause$code !== void 0 ? _cause$code : \"\";\n\t\t\t\terrorDetails = `${(_fetchError$name = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _fetchError$name !== void 0 ? _fetchError$name : \"FetchError\"}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`;\n\t\t\t\terrorDetails += `\\n\\nCaused by: ${(_cause$name = cause === null || cause === void 0 ? void 0 : cause.name) !== null && _cause$name !== void 0 ? _cause$name : \"Error\"}: ${causeMessage}`;\n\t\t\t\tif (causeCode) errorDetails += ` (${causeCode})`;\n\t\t\t\tif (cause === null || cause === void 0 ? void 0 : cause.stack) errorDetails += `\\n${cause.stack}`;\n\t\t\t} else {\n\t\t\t\tvar _fetchError$stack;\n\t\t\t\terrorDetails = (_fetchError$stack = fetchError === null || fetchError === void 0 ? void 0 : fetchError.stack) !== null && _fetchError$stack !== void 0 ? _fetchError$stack : \"\";\n\t\t\t}\n\t\t\tconst urlLength = this.url.toString().length;\n\t\t\tif ((fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) === \"AbortError\" || (fetchError === null || fetchError === void 0 ? void 0 : fetchError.code) === \"ABORT_ERR\") {\n\t\t\t\tcode = \"\";\n\t\t\t\thint = \"Request was aborted (timeout or manual cancellation)\";\n\t\t\t\tif (urlLength > this.urlLengthLimit) hint += `. Note: Your request URL is ${urlLength} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`;\n\t\t\t} else if ((cause === null || cause === void 0 ? void 0 : cause.name) === \"HeadersOverflowError\" || (cause === null || cause === void 0 ? void 0 : cause.code) === \"UND_ERR_HEADERS_OVERFLOW\") {\n\t\t\t\tcode = \"\";\n\t\t\t\thint = \"HTTP headers exceeded server limits (typically 16KB)\";\n\t\t\t\tif (urlLength > this.urlLengthLimit) hint += `. Your request URL is ${urlLength} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tmessage: `${(_fetchError$name2 = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _fetchError$name2 !== void 0 ? _fetchError$name2 : \"FetchError\"}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`,\n\t\t\t\t\tdetails: errorDetails,\n\t\t\t\t\thint,\n\t\t\t\t\tcode\n\t\t\t\t},\n\t\t\t\tdata: null,\n\t\t\t\tcount: null,\n\t\t\t\tstatus: 0,\n\t\t\t\tstatusText: \"\"\n\t\t\t};\n\t\t});\n\t\treturn res.then(onfulfilled, onrejected);\n\t}\n\t/**\n\t* Process a fetch response and return the standardized postgrest response.\n\t*/\n\tasync processResponse(res) {\n\t\tvar _this2 = this;\n\t\tlet error = null;\n\t\tlet data = null;\n\t\tlet count = null;\n\t\tlet status = res.status;\n\t\tlet statusText = res.statusText;\n\t\tif (res.ok) {\n\t\t\tvar _this$headers$get2, _res$headers$get;\n\t\t\tif (_this2.method !== \"HEAD\") {\n\t\t\t\tvar _this$headers$get;\n\t\t\t\tconst body = await res.text();\n\t\t\t\tif (body === \"\") {} else if (_this2.headers.get(\"Accept\") === \"text/csv\") data = body;\n\t\t\t\telse if (_this2.headers.get(\"Accept\") && ((_this$headers$get = _this2.headers.get(\"Accept\")) === null || _this$headers$get === void 0 ? void 0 : _this$headers$get.includes(\"application/vnd.pgrst.plan+text\"))) data = body;\n\t\t\t\telse try {\n\t\t\t\t\tdata = JSON.parse(body);\n\t\t\t\t} catch (_unused) {\n\t\t\t\t\terror = { message: body };\n\t\t\t\t\tdata = null;\n\t\t\t\t\tif (_this2.shouldThrowOnError) throw new PostgrestError({\n\t\t\t\t\t\tmessage: body,\n\t\t\t\t\t\tdetails: \"\",\n\t\t\t\t\t\thint: \"\",\n\t\t\t\t\t\tcode: \"\"\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst countHeader = (_this$headers$get2 = _this2.headers.get(\"Prefer\")) === null || _this$headers$get2 === void 0 ? void 0 : _this$headers$get2.match(/count=(exact|planned|estimated)/);\n\t\t\tconst contentRange = (_res$headers$get = res.headers.get(\"content-range\")) === null || _res$headers$get === void 0 ? void 0 : _res$headers$get.split(\"/\");\n\t\t\tif (countHeader && contentRange && contentRange.length > 1) count = parseInt(contentRange[1]);\n\t\t\tif (_this2.isMaybeSingle && Array.isArray(data)) if (data.length > 1) {\n\t\t\t\terror = {\n\t\t\t\t\tcode: \"PGRST116\",\n\t\t\t\t\tdetails: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`,\n\t\t\t\t\thint: null,\n\t\t\t\t\tmessage: \"JSON object requested, multiple (or no) rows returned\"\n\t\t\t\t};\n\t\t\t\tdata = null;\n\t\t\t\tcount = null;\n\t\t\t\tstatus = 406;\n\t\t\t\tstatusText = \"Not Acceptable\";\n\t\t\t\tif (_this2.shouldThrowOnError) {\n\t\t\t\t\tvar _error$hint;\n\t\t\t\t\tthrow new PostgrestError(_objectSpread2(_objectSpread2({}, error), {}, { hint: (_error$hint = error.hint) !== null && _error$hint !== void 0 ? _error$hint : \"\" }));\n\t\t\t\t}\n\t\t\t} else if (data.length === 1) data = data[0];\n\t\t\telse data = null;\n\t\t} else {\n\t\t\tconst body = await res.text();\n\t\t\ttry {\n\t\t\t\terror = JSON.parse(body);\n\t\t\t\tif (Array.isArray(error) && res.status === 404) {\n\t\t\t\t\tdata = [];\n\t\t\t\t\terror = null;\n\t\t\t\t\tstatus = 200;\n\t\t\t\t\tstatusText = \"OK\";\n\t\t\t\t}\n\t\t\t} catch (_unused2) {\n\t\t\t\tif (res.status === 404 && body === \"\") {\n\t\t\t\t\tstatus = 204;\n\t\t\t\t\tstatusText = \"No Content\";\n\t\t\t\t} else error = { message: body };\n\t\t\t}\n\t\t\tif (error && _this2.shouldThrowOnError) throw new PostgrestError(error);\n\t\t}\n\t\treturn {\n\t\t\tsuccess: error === null,\n\t\t\terror,\n\t\t\tdata,\n\t\t\tcount,\n\t\t\tstatus,\n\t\t\tstatusText\n\t\t};\n\t}\n\t/**\n\t* Override the type of the returned `data`.\n\t*\n\t* @typeParam NewResult - The new result type to override with\n\t* @deprecated Use overrideTypes<yourType, { merge: false }>() method at the end of your call chain instead\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*/\n\treturns() {\n\t\t/* istanbul ignore next */\n\t\treturn this;\n\t}\n\t/**\n\t* Override the type of the returned `data` field in the response.\n\t*\n\t* @typeParam NewResult - The new type to cast the response data to\n\t* @typeParam Options - Optional type configuration (defaults to { merge: true })\n\t* @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true)\n\t* @example\n\t* ```typescript\n\t* // Merge with existing types (default behavior)\n\t* const query = supabase\n\t*   .from('users')\n\t*   .select()\n\t*   .overrideTypes<{ custom_field: string }>()\n\t*\n\t* // Replace existing types completely\n\t* const replaceQuery = supabase\n\t*   .from('users')\n\t*   .select()\n\t*   .overrideTypes<{ id: number; name: string }, { merge: false }>()\n\t* ```\n\t* @returns A PostgrestBuilder instance with the new type\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*\n\t* @example Complete Override type of successful response\n\t* ```ts\n\t* const { data } = await supabase\n\t*   .from('countries')\n\t*   .select()\n\t*   .overrideTypes<Array<MyType>, { merge: false }>()\n\t* ```\n\t*\n\t* @exampleResponse Complete Override type of successful response\n\t* ```ts\n\t* let x: typeof data // MyType[]\n\t* ```\n\t*\n\t* @example Complete Override type of object response\n\t* ```ts\n\t* const { data } = await supabase\n\t*   .from('countries')\n\t*   .select()\n\t*   .maybeSingle()\n\t*   .overrideTypes<MyType, { merge: false }>()\n\t* ```\n\t*\n\t* @exampleResponse Complete Override type of object response\n\t* ```ts\n\t* let x: typeof data // MyType | null\n\t* ```\n\t*\n\t* @example Partial Override type of successful response\n\t* ```ts\n\t* const { data } = await supabase\n\t*   .from('countries')\n\t*   .select()\n\t*   .overrideTypes<Array<{ status: \"A\" | \"B\" }>>()\n\t* ```\n\t*\n\t* @exampleResponse Partial Override type of successful response\n\t* ```ts\n\t* let x: typeof data // Array<CountryRowProperties & { status: \"A\" | \"B\" }>\n\t* ```\n\t*\n\t* @example Partial Override type of object response\n\t* ```ts\n\t* const { data } = await supabase\n\t*   .from('countries')\n\t*   .select()\n\t*   .maybeSingle()\n\t*   .overrideTypes<{ status: \"A\" | \"B\" }>()\n\t* ```\n\t*\n\t* @exampleResponse Partial Override type of object response\n\t* ```ts\n\t* let x: typeof data // CountryRowProperties & { status: \"A\" | \"B\" } | null\n\t* ```\n\t*\n\t* @example Merge vs replace existing types\n\t* ```typescript\n\t* // Merge with existing types (default behavior)\n\t* const query = supabase\n\t*   .from('users')\n\t*   .select()\n\t*   .overrideTypes<{ custom_field: string }>()\n\t*\n\t* // Replace existing types completely\n\t* const replaceQuery = supabase\n\t*   .from('users')\n\t*   .select()\n\t*   .overrideTypes<{ id: number; name: string }, { merge: false }>()\n\t* ```\n\t*/\n\toverrideTypes() {\n\t\treturn this;\n\t}\n};\n\n//#endregion\n//#region src/PostgrestTransformBuilder.ts\nvar PostgrestTransformBuilder = class extends PostgrestBuilder {\n\tthrowOnError() {\n\t\treturn super.throwOnError();\n\t}\n\t/**\n\t* Perform a SELECT on the query result.\n\t*\n\t* By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not\n\t* return modified rows. By calling this method, modified rows are returned in\n\t* `data`.\n\t*\n\t* @param columns - The columns to retrieve, separated by commas\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*\n\t* @example With `upsert()`\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .upsert({ id: 1, name: 'Han Solo' })\n\t*   .select()\n\t* ```\n\t*\n\t* @exampleSql With `upsert()`\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Han');\n\t* ```\n\t*\n\t* @exampleResponse With `upsert()`\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"id\": 1,\n\t*       \"name\": \"Han Solo\"\n\t*     }\n\t*   ],\n\t*   \"status\": 201,\n\t*   \"statusText\": \"\"\n\t* }\n\t* ```\n\t*/\n\tselect(columns) {\n\t\tlet quoted = false;\n\t\tconst cleanedColumns = (columns !== null && columns !== void 0 ? columns : \"*\").split(\"\").map((c) => {\n\t\t\tif (/\\s/.test(c) && !quoted) return \"\";\n\t\t\tif (c === \"\\\"\") quoted = !quoted;\n\t\t\treturn c;\n\t\t}).join(\"\");\n\t\tthis.url.searchParams.set(\"select\", cleanedColumns);\n\t\tthis.headers.append(\"Prefer\", \"return=representation\");\n\t\treturn this;\n\t}\n\t/**\n\t* Order the query result by `column`.\n\t*\n\t* You can call this method multiple times to order by multiple columns.\n\t*\n\t* You can order referenced tables, but it only affects the ordering of the\n\t* parent table if you use `!inner` in the query.\n\t*\n\t* @param column - The column to order by\n\t* @param options - Named parameters\n\t* @param options.ascending - If `true`, the result will be in ascending order\n\t* @param options.nullsFirst - If `true`, `null`s appear first. If `false`,\n\t* `null`s appear last.\n\t* @param options.referencedTable - Set this to order a referenced table by\n\t* its columns\n\t* @param options.foreignTable - Deprecated, use `options.referencedTable`\n\t* instead\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*\n\t* @example With `select()`\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select('id, name')\n\t*   .order('id', { ascending: false })\n\t* ```\n\t*\n\t* @exampleSql With `select()`\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Luke'),\n\t*   (2, 'Leia'),\n\t*   (3, 'Han');\n\t* ```\n\t*\n\t* @exampleResponse With `select()`\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"id\": 3,\n\t*       \"name\": \"Han\"\n\t*     },\n\t*     {\n\t*       \"id\": 2,\n\t*       \"name\": \"Leia\"\n\t*     },\n\t*     {\n\t*       \"id\": 1,\n\t*       \"name\": \"Luke\"\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription On a referenced table\n\t* Ordering with `referencedTable` doesn't affect the ordering of the\n\t* parent table.\n\t*\n\t* @example On a referenced table\n\t* ```ts\n\t*   const { data, error } = await supabase\n\t*     .from('orchestral_sections')\n\t*     .select(`\n\t*       name,\n\t*       instruments (\n\t*         name\n\t*       )\n\t*     `)\n\t*     .order('name', { referencedTable: 'instruments', ascending: false })\n\t*\n\t* ```\n\t*\n\t* @exampleSql On a referenced table\n\t* ```sql\n\t* create table\n\t*   orchestral_sections (id int8 primary key, name text);\n\t* create table\n\t*   instruments (\n\t*     id int8 primary key,\n\t*     section_id int8 not null references orchestral_sections,\n\t*     name text\n\t*   );\n\t*\n\t* insert into\n\t*   orchestral_sections (id, name)\n\t* values\n\t*   (1, 'strings'),\n\t*   (2, 'woodwinds');\n\t* insert into\n\t*   instruments (id, section_id, name)\n\t* values\n\t*   (1, 1, 'harp'),\n\t*   (2, 1, 'violin');\n\t* ```\n\t*\n\t* @exampleResponse On a referenced table\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"name\": \"strings\",\n\t*       \"instruments\": [\n\t*         {\n\t*           \"name\": \"violin\"\n\t*         },\n\t*         {\n\t*           \"name\": \"harp\"\n\t*         }\n\t*       ]\n\t*     },\n\t*     {\n\t*       \"name\": \"woodwinds\",\n\t*       \"instruments\": []\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Order parent table by a referenced table\n\t* Ordering with `referenced_table(col)` affects the ordering of the\n\t* parent table.\n\t*\n\t* @example Order parent table by a referenced table\n\t* ```ts\n\t*   const { data, error } = await supabase\n\t*     .from('instruments')\n\t*     .select(`\n\t*       name,\n\t*       section:orchestral_sections (\n\t*         name\n\t*       )\n\t*     `)\n\t*     .order('section(name)', { ascending: true })\n\t*\n\t* ```\n\t*\n\t* @exampleSql Order parent table by a referenced table\n\t* ```sql\n\t* create table\n\t*   orchestral_sections (id int8 primary key, name text);\n\t* create table\n\t*   instruments (\n\t*     id int8 primary key,\n\t*     section_id int8 not null references orchestral_sections,\n\t*     name text\n\t*   );\n\t*\n\t* insert into\n\t*   orchestral_sections (id, name)\n\t* values\n\t*   (1, 'strings'),\n\t*   (2, 'woodwinds');\n\t* insert into\n\t*   instruments (id, section_id, name)\n\t* values\n\t*   (1, 2, 'flute'),\n\t*   (2, 1, 'violin');\n\t* ```\n\t*\n\t* @exampleResponse Order parent table by a referenced table\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"name\": \"violin\",\n\t*       \"orchestral_sections\": {\"name\": \"strings\"}\n\t*     },\n\t*     {\n\t*       \"name\": \"flute\",\n\t*       \"orchestral_sections\": {\"name\": \"woodwinds\"}\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*/\n\torder(column, { ascending = true, nullsFirst, foreignTable, referencedTable = foreignTable } = {}) {\n\t\tconst key = referencedTable ? `${referencedTable}.order` : \"order\";\n\t\tconst existingOrder = this.url.searchParams.get(key);\n\t\tthis.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : \"\"}${column}.${ascending ? \"asc\" : \"desc\"}${nullsFirst === void 0 ? \"\" : nullsFirst ? \".nullsfirst\" : \".nullslast\"}`);\n\t\treturn this;\n\t}\n\t/**\n\t* Limit the query result by `rows`.\n\t*\n\t* @param rows - The maximum number of rows to return\n\t* @param options - Named parameters\n\t* @param options.referencedTable - Set this to limit rows of referenced\n\t* tables instead of the parent table\n\t* @param options.foreignTable - Deprecated, use `options.referencedTable`\n\t* instead\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*\n\t* @example With `select()`\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select('name')\n\t*   .limit(1)\n\t* ```\n\t*\n\t* @exampleSql With `select()`\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Luke'),\n\t*   (2, 'Leia'),\n\t*   (3, 'Han');\n\t* ```\n\t*\n\t* @exampleResponse With `select()`\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"name\": \"Luke\"\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @example On a referenced table\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('orchestral_sections')\n\t*   .select(`\n\t*     name,\n\t*     instruments (\n\t*       name\n\t*     )\n\t*   `)\n\t*   .limit(1, { referencedTable: 'instruments' })\n\t* ```\n\t*\n\t* @exampleSql On a referenced table\n\t* ```sql\n\t* create table\n\t*   orchestral_sections (id int8 primary key, name text);\n\t* create table\n\t*   instruments (\n\t*     id int8 primary key,\n\t*     section_id int8 not null references orchestral_sections,\n\t*     name text\n\t*   );\n\t*\n\t* insert into\n\t*   orchestral_sections (id, name)\n\t* values\n\t*   (1, 'strings');\n\t* insert into\n\t*   instruments (id, section_id, name)\n\t* values\n\t*   (1, 1, 'harp'),\n\t*   (2, 1, 'violin');\n\t* ```\n\t*\n\t* @exampleResponse On a referenced table\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"name\": \"strings\",\n\t*       \"instruments\": [\n\t*         {\n\t*           \"name\": \"violin\"\n\t*         }\n\t*       ]\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*/\n\tlimit(rows, { foreignTable, referencedTable = foreignTable } = {}) {\n\t\tconst key = typeof referencedTable === \"undefined\" ? \"limit\" : `${referencedTable}.limit`;\n\t\tthis.url.searchParams.set(key, `${rows}`);\n\t\treturn this;\n\t}\n\t/**\n\t* Limit the query result by starting at an offset `from` and ending at the offset `to`.\n\t* Only records within this range are returned.\n\t* This respects the query order and if there is no order clause the range could behave unexpectedly.\n\t* The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third\n\t* and fourth rows of the query.\n\t*\n\t* @param from - The starting index from which to limit the result\n\t* @param to - The last index to which to limit the result\n\t* @param options - Named parameters\n\t* @param options.referencedTable - Set this to limit rows of referenced\n\t* tables instead of the parent table\n\t* @param options.foreignTable - Deprecated, use `options.referencedTable`\n\t* instead\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*\n\t* @example With `select()`\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select('name')\n\t*   .range(0, 1)\n\t* ```\n\t*\n\t* @exampleSql With `select()`\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Luke'),\n\t*   (2, 'Leia'),\n\t*   (3, 'Han');\n\t* ```\n\t*\n\t* @exampleResponse With `select()`\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"name\": \"Luke\"\n\t*     },\n\t*     {\n\t*       \"name\": \"Leia\"\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*/\n\trange(from, to, { foreignTable, referencedTable = foreignTable } = {}) {\n\t\tconst keyOffset = typeof referencedTable === \"undefined\" ? \"offset\" : `${referencedTable}.offset`;\n\t\tconst keyLimit = typeof referencedTable === \"undefined\" ? \"limit\" : `${referencedTable}.limit`;\n\t\tthis.url.searchParams.set(keyOffset, `${from}`);\n\t\tthis.url.searchParams.set(keyLimit, `${to - from + 1}`);\n\t\treturn this;\n\t}\n\t/**\n\t* Set the AbortSignal for the fetch request.\n\t*\n\t* @param signal - The AbortSignal to use for the fetch request\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*\n\t* @remarks\n\t* You can use this to set a timeout for the request.\n\t*\n\t* @exampleDescription Aborting requests in-flight\n\t* You can use an [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) to abort requests.\n\t* Note that `status` and `statusText` don't mean anything for aborted requests as the request wasn't fulfilled.\n\t*\n\t* @example Aborting requests in-flight\n\t* ```ts\n\t* const ac = new AbortController()\n\t*\n\t* const { data, error } = await supabase\n\t*   .from('very_big_table')\n\t*   .select()\n\t*   .abortSignal(ac.signal)\n\t*\n\t* // Abort the request after 100 ms\n\t* setTimeout(() => ac.abort(), 100)\n\t* ```\n\t*\n\t* @exampleResponse Aborting requests in-flight\n\t* ```json\n\t*   {\n\t*     \"error\": {\n\t*       \"message\": \"AbortError: The user aborted a request.\",\n\t*       \"details\": \"\",\n\t*       \"hint\": \"The request was aborted locally via the provided AbortSignal.\",\n\t*       \"code\": \"\"\n\t*     },\n\t*     \"status\": 0,\n\t*     \"statusText\": \"\"\n\t*   }\n\t*\n\t* ```\n\t*\n\t* @example Set a timeout\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('very_big_table')\n\t*   .select()\n\t*   .abortSignal(AbortSignal.timeout(1000 /* ms *\\/))\n\t* ```\n\t*\n\t* @exampleResponse Set a timeout\n\t* ```json\n\t*   {\n\t*     \"error\": {\n\t*       \"message\": \"FetchError: The user aborted a request.\",\n\t*       \"details\": \"\",\n\t*       \"hint\": \"\",\n\t*       \"code\": \"\"\n\t*     },\n\t*     \"status\": 0,\n\t*     \"statusText\": \"\"\n\t*   }\n\t*\n\t* ```\n\t*/\n\tabortSignal(signal) {\n\t\tthis.signal = signal;\n\t\treturn this;\n\t}\n\t/**\n\t* Return `data` as a single object instead of an array of objects.\n\t*\n\t* Query result must be one row (e.g. using `.limit(1)`), otherwise this\n\t* returns an error.\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*\n\t* @example With `select()`\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select('name')\n\t*   .limit(1)\n\t*   .single()\n\t* ```\n\t*\n\t* @exampleSql With `select()`\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Luke'),\n\t*   (2, 'Leia'),\n\t*   (3, 'Han');\n\t* ```\n\t*\n\t* @exampleResponse With `select()`\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"name\": \"Luke\"\n\t*   },\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*/\n\tsingle() {\n\t\tthis.headers.set(\"Accept\", \"application/vnd.pgrst.object+json\");\n\t\treturn this;\n\t}\n\t/**\n\t* Return `data` as a single object instead of an array of objects.\n\t*\n\t* Query result must be zero or one row (e.g. using `.limit(1)`), otherwise\n\t* this returns an error.\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*\n\t* @example With `select()`\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select()\n\t*   .eq('name', 'Katniss')\n\t*   .maybeSingle()\n\t* ```\n\t*\n\t* @exampleSql With `select()`\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Luke'),\n\t*   (2, 'Leia'),\n\t*   (3, 'Han');\n\t* ```\n\t*\n\t* @exampleResponse With `select()`\n\t* ```json\n\t* {\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*/\n\tmaybeSingle() {\n\t\tthis.isMaybeSingle = true;\n\t\treturn this;\n\t}\n\t/**\n\t* Return `data` as a string in CSV format.\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*\n\t* @exampleDescription Return data as CSV\n\t* By default, the data is returned in JSON format, but can also be returned as Comma Separated Values.\n\t*\n\t* @example Return data as CSV\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select()\n\t*   .csv()\n\t* ```\n\t*\n\t* @exampleSql Return data as CSV\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Luke'),\n\t*   (2, 'Leia'),\n\t*   (3, 'Han');\n\t* ```\n\t*\n\t* @exampleResponse Return data as CSV\n\t* ```json\n\t* {\n\t*   \"data\": \"id,name\\n1,Luke\\n2,Leia\\n3,Han\",\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*/\n\tcsv() {\n\t\tthis.headers.set(\"Accept\", \"text/csv\");\n\t\treturn this;\n\t}\n\t/**\n\t* Return `data` as an object in [GeoJSON](https://geojson.org) format.\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*/\n\tgeojson() {\n\t\tthis.headers.set(\"Accept\", \"application/geo+json\");\n\t\treturn this;\n\t}\n\t/**\n\t* Return `data` as the EXPLAIN plan for the query.\n\t*\n\t* You need to enable the\n\t* [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain)\n\t* setting before using this method.\n\t*\n\t* @param options - Named parameters\n\t*\n\t* @param options.analyze - If `true`, the query will be executed and the\n\t* actual run time will be returned\n\t*\n\t* @param options.verbose - If `true`, the query identifier will be returned\n\t* and `data` will include the output columns of the query\n\t*\n\t* @param options.settings - If `true`, include information on configuration\n\t* parameters that affect query planning\n\t*\n\t* @param options.buffers - If `true`, include information on buffer usage\n\t*\n\t* @param options.wal - If `true`, include information on WAL record generation\n\t*\n\t* @param options.format - The format of the output, can be `\"text\"` (default)\n\t* or `\"json\"`\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*\n\t* @exampleDescription Get the execution plan\n\t* By default, the data is returned in TEXT format, but can also be returned as JSON by using the `format` parameter.\n\t*\n\t* @example Get the execution plan\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select()\n\t*   .explain()\n\t* ```\n\t*\n\t* @exampleSql Get the execution plan\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Luke'),\n\t*   (2, 'Leia'),\n\t*   (3, 'Han');\n\t* ```\n\t*\n\t* @exampleResponse Get the execution plan\n\t* ```js\n\t* Aggregate  (cost=33.34..33.36 rows=1 width=112)\n\t*   ->  Limit  (cost=0.00..18.33 rows=1000 width=40)\n\t*         ->  Seq Scan on characters  (cost=0.00..22.00 rows=1200 width=40)\n\t* ```\n\t*\n\t* @exampleDescription Get the execution plan with analyze and verbose\n\t* By default, the data is returned in TEXT format, but can also be returned as JSON by using the `format` parameter.\n\t*\n\t* @example Get the execution plan with analyze and verbose\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select()\n\t*   .explain({analyze:true,verbose:true})\n\t* ```\n\t*\n\t* @exampleSql Get the execution plan with analyze and verbose\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Luke'),\n\t*   (2, 'Leia'),\n\t*   (3, 'Han');\n\t* ```\n\t*\n\t* @exampleResponse Get the execution plan with analyze and verbose\n\t* ```js\n\t* Aggregate  (cost=33.34..33.36 rows=1 width=112) (actual time=0.041..0.041 rows=1 loops=1)\n\t*   Output: NULL::bigint, count(ROW(characters.id, characters.name)), COALESCE(json_agg(ROW(characters.id, characters.name)), '[]'::json), NULLIF(current_setting('response.headers'::text, true), ''::text), NULLIF(current_setting('response.status'::text, true), ''::text)\n\t*   ->  Limit  (cost=0.00..18.33 rows=1000 width=40) (actual time=0.005..0.006 rows=3 loops=1)\n\t*         Output: characters.id, characters.name\n\t*         ->  Seq Scan on public.characters  (cost=0.00..22.00 rows=1200 width=40) (actual time=0.004..0.005 rows=3 loops=1)\n\t*               Output: characters.id, characters.name\n\t* Query Identifier: -4730654291623321173\n\t* Planning Time: 0.407 ms\n\t* Execution Time: 0.119 ms\n\t* ```\n\t*/\n\texplain({ analyze = false, verbose = false, settings = false, buffers = false, wal = false, format = \"text\" } = {}) {\n\t\tvar _this$headers$get;\n\t\tconst options = [\n\t\t\tanalyze ? \"analyze\" : null,\n\t\t\tverbose ? \"verbose\" : null,\n\t\t\tsettings ? \"settings\" : null,\n\t\t\tbuffers ? \"buffers\" : null,\n\t\t\twal ? \"wal\" : null\n\t\t].filter(Boolean).join(\"|\");\n\t\tconst forMediatype = (_this$headers$get = this.headers.get(\"Accept\")) !== null && _this$headers$get !== void 0 ? _this$headers$get : \"application/json\";\n\t\tthis.headers.set(\"Accept\", `application/vnd.pgrst.plan+${format}; for=\"${forMediatype}\"; options=${options};`);\n\t\tif (format === \"json\") return this;\n\t\telse return this;\n\t}\n\t/**\n\t* Dry-run this request: execute the query but discard the changes.\n\t*\n\t* Server-side, PostgREST runs the query inside a transaction and rolls it back\n\t* instead of committing. The response still contains the data that *would* have\n\t* been returned — `RETURNING` clauses execute and RLS, triggers, and constraints\n\t* are all evaluated — but no row is actually inserted, updated, or deleted.\n\t*\n\t* This affects only the single request it is chained to. The JS caller has no\n\t* handle on the transaction: supabase-js does not group multiple queries into\n\t* one transaction. For multi-statement transactional logic, use a database\n\t* function (`supabase.rpc(...)`).\n\t*\n\t* Sets the `Prefer: tx=rollback` header. See PostgREST's docs on transaction\n\t* preferences for the underlying mechanism.\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*\n\t* @example Validate an insert without persisting\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('countries')\n\t*   .insert({ name: 'France' })\n\t*   .select()\n\t*   .rollback()\n\t* // `data` shows what would have been inserted; nothing is saved.\n\t* ```\n\t*/\n\trollback() {\n\t\tthis.headers.append(\"Prefer\", \"tx=rollback\");\n\t\treturn this;\n\t}\n\t/**\n\t* Override the type of the returned `data`.\n\t*\n\t* @typeParam NewResult - The new result type to override with\n\t* @deprecated Use overrideTypes<yourType, { merge: false }>() method at the end of your call chain instead\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*\n\t* @remarks\n\t* - Deprecated: use overrideTypes method instead\n\t*\n\t* @example Override type of successful response\n\t* ```ts\n\t* const { data } = await supabase\n\t*   .from('countries')\n\t*   .select()\n\t*   .returns<Array<MyType>>()\n\t* ```\n\t*\n\t* @exampleResponse Override type of successful response\n\t* ```js\n\t* let x: typeof data // MyType[]\n\t* ```\n\t*\n\t* @example Override type of object response\n\t* ```ts\n\t* const { data } = await supabase\n\t*   .from('countries')\n\t*   .select()\n\t*   .maybeSingle()\n\t*   .returns<MyType>()\n\t* ```\n\t*\n\t* @exampleResponse Override type of object response\n\t* ```js\n\t* let x: typeof data // MyType | null\n\t* ```\n\t*/\n\treturns() {\n\t\treturn this;\n\t}\n\t/**\n\t* Set the maximum number of rows that can be affected by the query.\n\t* Only available in PostgREST v13+ and only works with PATCH and DELETE methods.\n\t*\n\t* @param rows - The maximum number of rows that can be affected\n\t*\n\t* @category Database\n\t* @subcategory Using modifiers\n\t*/\n\tmaxAffected(rows) {\n\t\tthis.headers.append(\"Prefer\", \"handling=strict\");\n\t\tthis.headers.append(\"Prefer\", `max-affected=${rows}`);\n\t\treturn this;\n\t}\n};\n\n//#endregion\n//#region src/PostgrestFilterBuilder.ts\nconst PostgrestReservedCharsRegexp = /* @__PURE__ */ new RegExp(\"[,()]\");\nvar PostgrestFilterBuilder = class extends PostgrestTransformBuilder {\n\tthrowOnError() {\n\t\treturn super.throwOnError();\n\t}\n\t/**\n\t* Match only rows where `column` is equal to `value`.\n\t*\n\t* To check if the value of `column` is NULL, you should use `.is()` instead.\n\t*\n\t* @param column - The column to filter on\n\t* @param value - The value to filter with\n\t*\n\t* @category Database\n\t* @subcategory Using filters\n\t*\n\t* @example With `select()`\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select()\n\t*   .eq('name', 'Leia')\n\t* ```\n\t*\n\t* @exampleSql With `select()`\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Luke'),\n\t*   (2, 'Leia'),\n\t*   (3, 'Han');\n\t* ```\n\t*\n\t* @exampleResponse With `select()`\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"id\": 2,\n\t*       \"name\": \"Leia\"\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*/\n\teq(column, value) {\n\t\tthis.url.searchParams.append(column, `eq.${value}`);\n\t\treturn this;\n\t}\n\t/**\n\t* Match only rows where `column` is not equal to `value`.\n\t*\n\t* This filter does not include rows where `column` is `NULL`. To match null\n\t* values, use `.is(column, null)` instead.\n\t*\n\t* @param column - The column to filter on\n\t* @param value - The value to filter with\n\t*\n\t* @category Database\n\t* @subcategory Using filters\n\t*\n\t* @example With `select()`\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select()\n\t*   .neq('name', 'Leia')\n\t* ```\n\t*\n\t* @exampleSql With `select()`\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Luke'),\n\t*   (2, 'Leia'),\n\t*   (3, 'Han');\n\t* ```\n\t*\n\t* @exampleResponse With `select()`\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"id\": 1,\n\t*       \"name\": \"Luke\"\n\t*     },\n\t*     {\n\t*       \"id\": 3,\n\t*       \"name\": \"Han\"\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*/\n\tneq(column, value) {\n\t\tthis.url.searchParams.append(column, `neq.${value}`);\n\t\treturn this;\n\t}\n\tgt(column, value) {\n\t\tthis.url.searchParams.append(column, `gt.${value}`);\n\t\treturn this;\n\t}\n\tgte(column, value) {\n\t\tthis.url.searchParams.append(column, `gte.${value}`);\n\t\treturn this;\n\t}\n\tlt(column, value) {\n\t\tthis.url.searchParams.append(column, `lt.${value}`);\n\t\treturn this;\n\t}\n\tlte(column, value) {\n\t\tthis.url.searchParams.append(column, `lte.${value}`);\n\t\treturn this;\n\t}\n\tlike(column, pattern) {\n\t\tthis.url.searchParams.append(column, `like.${pattern}`);\n\t\treturn this;\n\t}\n\tlikeAllOf(column, patterns) {\n\t\tthis.url.searchParams.append(column, `like(all).{${patterns.join(\",\")}}`);\n\t\treturn this;\n\t}\n\tlikeAnyOf(column, patterns) {\n\t\tthis.url.searchParams.append(column, `like(any).{${patterns.join(\",\")}}`);\n\t\treturn this;\n\t}\n\tilike(column, pattern) {\n\t\tthis.url.searchParams.append(column, `ilike.${pattern}`);\n\t\treturn this;\n\t}\n\tilikeAllOf(column, patterns) {\n\t\tthis.url.searchParams.append(column, `ilike(all).{${patterns.join(\",\")}}`);\n\t\treturn this;\n\t}\n\tilikeAnyOf(column, patterns) {\n\t\tthis.url.searchParams.append(column, `ilike(any).{${patterns.join(\",\")}}`);\n\t\treturn this;\n\t}\n\tregexMatch(column, pattern) {\n\t\tthis.url.searchParams.append(column, `match.${pattern}`);\n\t\treturn this;\n\t}\n\tregexIMatch(column, pattern) {\n\t\tthis.url.searchParams.append(column, `imatch.${pattern}`);\n\t\treturn this;\n\t}\n\tis(column, value) {\n\t\tthis.url.searchParams.append(column, `is.${value}`);\n\t\treturn this;\n\t}\n\t/**\n\t* Match only rows where `column` IS DISTINCT FROM `value`.\n\t*\n\t* Unlike `.neq()`, this treats `NULL` as a comparable value. Two `NULL` values\n\t* are considered equal (not distinct), and comparing `NULL` with any non-NULL\n\t* value returns true (distinct).\n\t*\n\t* @param column - The column to filter on\n\t* @param value - The value to filter with\n\t*/\n\tisDistinct(column, value) {\n\t\tthis.url.searchParams.append(column, `isdistinct.${value}`);\n\t\treturn this;\n\t}\n\t/**\n\t* Match only rows where `column` is included in the `values` array.\n\t*\n\t* @param column - The column to filter on\n\t* @param values - The values array to filter with\n\t*\n\t* @category Database\n\t* @subcategory Using filters\n\t*\n\t* @example With `select()`\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select()\n\t*   .in('name', ['Leia', 'Han'])\n\t* ```\n\t*\n\t* @exampleSql With `select()`\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Luke'),\n\t*   (2, 'Leia'),\n\t*   (3, 'Han');\n\t* ```\n\t*\n\t* @exampleResponse With `select()`\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"id\": 2,\n\t*       \"name\": \"Leia\"\n\t*     },\n\t*     {\n\t*       \"id\": 3,\n\t*       \"name\": \"Han\"\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*/\n\tin(column, values) {\n\t\tconst cleanedValues = Array.from(new Set(values)).map((s) => {\n\t\t\tif (typeof s === \"string\" && PostgrestReservedCharsRegexp.test(s)) return `\"${s}\"`;\n\t\t\telse return `${s}`;\n\t\t}).join(\",\");\n\t\tthis.url.searchParams.append(column, `in.(${cleanedValues})`);\n\t\treturn this;\n\t}\n\t/**\n\t* Match only rows where `column` is NOT included in the `values` array.\n\t*\n\t* @param column - The column to filter on\n\t* @param values - The values array to filter with\n\t*/\n\tnotIn(column, values) {\n\t\tconst cleanedValues = Array.from(new Set(values)).map((s) => {\n\t\t\tif (typeof s === \"string\" && PostgrestReservedCharsRegexp.test(s)) return `\"${s}\"`;\n\t\t\telse return `${s}`;\n\t\t}).join(\",\");\n\t\tthis.url.searchParams.append(column, `not.in.(${cleanedValues})`);\n\t\treturn this;\n\t}\n\tcontains(column, value) {\n\t\tif (typeof value === \"string\") this.url.searchParams.append(column, `cs.${value}`);\n\t\telse if (Array.isArray(value)) this.url.searchParams.append(column, `cs.{${value.join(\",\")}}`);\n\t\telse this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`);\n\t\treturn this;\n\t}\n\tcontainedBy(column, value) {\n\t\tif (typeof value === \"string\") this.url.searchParams.append(column, `cd.${value}`);\n\t\telse if (Array.isArray(value)) this.url.searchParams.append(column, `cd.{${value.join(\",\")}}`);\n\t\telse this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`);\n\t\treturn this;\n\t}\n\trangeGt(column, range) {\n\t\tthis.url.searchParams.append(column, `sr.${range}`);\n\t\treturn this;\n\t}\n\trangeGte(column, range) {\n\t\tthis.url.searchParams.append(column, `nxl.${range}`);\n\t\treturn this;\n\t}\n\trangeLt(column, range) {\n\t\tthis.url.searchParams.append(column, `sl.${range}`);\n\t\treturn this;\n\t}\n\trangeLte(column, range) {\n\t\tthis.url.searchParams.append(column, `nxr.${range}`);\n\t\treturn this;\n\t}\n\trangeAdjacent(column, range) {\n\t\tthis.url.searchParams.append(column, `adj.${range}`);\n\t\treturn this;\n\t}\n\toverlaps(column, value) {\n\t\tif (typeof value === \"string\") this.url.searchParams.append(column, `ov.${value}`);\n\t\telse this.url.searchParams.append(column, `ov.{${value.join(\",\")}}`);\n\t\treturn this;\n\t}\n\ttextSearch(column, query, { config, type } = {}) {\n\t\tlet typePart = \"\";\n\t\tif (type === \"plain\") typePart = \"pl\";\n\t\telse if (type === \"phrase\") typePart = \"ph\";\n\t\telse if (type === \"websearch\") typePart = \"w\";\n\t\tconst configPart = config === void 0 ? \"\" : `(${config})`;\n\t\tthis.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`);\n\t\treturn this;\n\t}\n\tmatch(query) {\n\t\tObject.entries(query).filter(([_, value]) => value !== void 0).forEach(([column, value]) => {\n\t\t\tthis.url.searchParams.append(column, `eq.${value}`);\n\t\t});\n\t\treturn this;\n\t}\n\t/**\n\t* Match only rows which doesn't satisfy the filter.\n\t*\n\t* Unlike most filters, `opearator` and `value` are used as-is and need to\n\t* follow [PostgREST\n\t* syntax](https://postgrest.org/en/stable/api.html#operators). You also need\n\t* to make sure they are properly sanitized.\n\t*\n\t* @param column - The column to filter on\n\t* @param operator - The operator to be negated to filter with, following\n\t* PostgREST syntax\n\t* @param value - The value to filter with, following PostgREST syntax\n\t*\n\t* @category Database\n\t* @subcategory Using filters\n\t*\n\t* @remarks\n\t* not() expects you to use the raw PostgREST syntax for the filter values.\n\t*\n\t* ```ts\n\t* .not('id', 'in', '(5,6,7)')  // Use `()` for `in` filter\n\t* .not('arraycol', 'cs', '{\"a\",\"b\"}')  // Use `cs` for `contains()`, `{}` for array values\n\t* ```\n\t*\n\t* @example With `select()`\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('countries')\n\t*   .select()\n\t*   .not('name', 'is', null)\n\t* ```\n\t*\n\t* @exampleSql With `select()`\n\t* ```sql\n\t* create table\n\t*   countries (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   countries (id, name)\n\t* values\n\t*   (1, 'null'),\n\t*   (2, null);\n\t* ```\n\t*\n\t* @exampleResponse With `select()`\n\t* ```json\n\t*   {\n\t*     \"data\": [\n\t*       {\n\t*         \"id\": 1,\n\t*         \"name\": \"null\"\n\t*       }\n\t*     ],\n\t*     \"status\": 200,\n\t*     \"statusText\": \"OK\"\n\t*   }\n\t*\n\t* ```\n\t*/\n\tnot(column, operator, value) {\n\t\tthis.url.searchParams.append(column, `not.${operator}.${value}`);\n\t\treturn this;\n\t}\n\t/**\n\t* Match only rows which satisfy at least one of the filters.\n\t*\n\t* Unlike most filters, `filters` is used as-is and needs to follow [PostgREST\n\t* syntax](https://postgrest.org/en/stable/api.html#operators). You also need\n\t* to make sure it's properly sanitized.\n\t*\n\t* It's currently not possible to do an `.or()` filter across multiple tables.\n\t*\n\t* @param filters - The filters to use, following PostgREST syntax\n\t* @param options - Named parameters\n\t* @param options.referencedTable - Set this to filter on referenced tables\n\t* instead of the parent table\n\t* @param options.foreignTable - Deprecated, use `referencedTable` instead\n\t*\n\t* @category Database\n\t* @subcategory Using filters\n\t*\n\t* @remarks\n\t* or() expects you to use the raw PostgREST syntax for the filter names and values.\n\t*\n\t* ```ts\n\t* .or('id.in.(5,6,7), arraycol.cs.{\"a\",\"b\"}')  // Use `()` for `in` filter, `{}` for array values and `cs` for `contains()`.\n\t* .or('id.in.(5,6,7), arraycol.cd.{\"a\",\"b\"}')  // Use `cd` for `containedBy()`\n\t* ```\n\t*\n\t* @example With `select()`\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select('name')\n\t*   .or('id.eq.2,name.eq.Han')\n\t* ```\n\t*\n\t* @exampleSql With `select()`\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Luke'),\n\t*   (2, 'Leia'),\n\t*   (3, 'Han');\n\t* ```\n\t*\n\t* @exampleResponse With `select()`\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"name\": \"Leia\"\n\t*     },\n\t*     {\n\t*       \"name\": \"Han\"\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @example Use `or` with `and`\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select('name')\n\t*   .or('id.gt.3,and(id.eq.1,name.eq.Luke)')\n\t* ```\n\t*\n\t* @exampleSql Use `or` with `and`\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Luke'),\n\t*   (2, 'Leia'),\n\t*   (3, 'Han');\n\t* ```\n\t*\n\t* @exampleResponse Use `or` with `and`\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"name\": \"Luke\"\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @example Use `or` on referenced tables\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('orchestral_sections')\n\t*   .select(`\n\t*     name,\n\t*     instruments!inner (\n\t*       name\n\t*     )\n\t*   `)\n\t*   .or('section_id.eq.1,name.eq.guzheng', { referencedTable: 'instruments' })\n\t* ```\n\t*\n\t* @exampleSql Use `or` on referenced tables\n\t* ```sql\n\t* create table\n\t*   orchestral_sections (id int8 primary key, name text);\n\t* create table\n\t*   instruments (\n\t*     id int8 primary key,\n\t*     section_id int8 not null references orchestral_sections,\n\t*     name text\n\t*   );\n\t*\n\t* insert into\n\t*   orchestral_sections (id, name)\n\t* values\n\t*   (1, 'strings'),\n\t*   (2, 'woodwinds');\n\t* insert into\n\t*   instruments (id, section_id, name)\n\t* values\n\t*   (1, 2, 'flute'),\n\t*   (2, 1, 'violin');\n\t* ```\n\t*\n\t* @exampleResponse Use `or` on referenced tables\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"name\": \"strings\",\n\t*       \"instruments\": [\n\t*         {\n\t*           \"name\": \"violin\"\n\t*         }\n\t*       ]\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*/\n\tor(filters, { foreignTable, referencedTable = foreignTable } = {}) {\n\t\tconst key = referencedTable ? `${referencedTable}.or` : \"or\";\n\t\tthis.url.searchParams.append(key, `(${filters})`);\n\t\treturn this;\n\t}\n\tfilter(column, operator, value) {\n\t\tthis.url.searchParams.append(column, `${operator}.${value}`);\n\t\treturn this;\n\t}\n};\n\n//#endregion\n//#region src/PostgrestQueryBuilder.ts\nvar PostgrestQueryBuilder = class {\n\t/**\n\t* Creates a query builder scoped to a Postgres table or view.\n\t*\n\t* @category Database\n\t*\n\t* @param url - The URL for the query\n\t* @param options - Named parameters\n\t* @param options.headers - Custom headers\n\t* @param options.schema - Postgres schema to use\n\t* @param options.fetch - Custom fetch implementation\n\t* @param options.urlLengthLimit - Maximum URL length before warning\n\t* @param options.retry - Enable automatic retries for transient errors (default: true)\n\t*\n\t* @example Using supabase-js (recommended)\n\t* ```ts\n\t* import { createClient } from '@supabase/supabase-js'\n\t*\n\t* const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n\t* const { data, error } = await supabase.from('users').select('*')\n\t* ```\n\t*\n\t* @example Standalone import for bundle-sensitive environments\n\t* ```ts\n\t* import { PostgrestQueryBuilder } from '@supabase/postgrest-js'\n\t*\n\t* const query = new PostgrestQueryBuilder(\n\t*   new URL('https://xyzcompany.supabase.co/rest/v1/users'),\n\t*   { headers: { apikey: 'your-publishable-key' }, retry: true }\n\t* )\n\t* ```\n\t*/\n\tconstructor(url, { headers = {}, schema, fetch: fetch$1, urlLengthLimit = 8e3, retry }) {\n\t\tthis.url = url;\n\t\tthis.headers = new Headers(headers);\n\t\tthis.schema = schema;\n\t\tthis.fetch = fetch$1;\n\t\tthis.urlLengthLimit = urlLengthLimit;\n\t\tthis.retry = retry;\n\t}\n\t/**\n\t* Clone URL and headers to prevent shared state between operations.\n\t*/\n\tcloneRequestState() {\n\t\treturn {\n\t\t\turl: new URL(this.url.toString()),\n\t\t\theaders: new Headers(this.headers)\n\t\t};\n\t}\n\t/**\n\t* Perform a SELECT query on the table or view.\n\t*\n\t* @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName`\n\t*\n\t* @param options - Named parameters\n\t*\n\t* @param options.head - When set to `true`, `data` will not be returned.\n\t* Useful if you only need the count.\n\t*\n\t* @param options.count - Count algorithm to use to count rows in the table or view.\n\t*\n\t* `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n\t* hood.\n\t*\n\t* `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n\t* statistics under the hood.\n\t*\n\t* `\"estimated\"`: Uses exact count for low numbers and planned count for high\n\t* numbers.\n\t*\n\t* @remarks\n\t* When using `count` with `.range()` or `.limit()`, the returned `count` is the total number of rows\n\t* that match your filters, not the number of rows in the current page. Use this to build pagination UI.\n\t\n\t* - By default, Supabase projects return a maximum of 1,000 rows. This setting can be changed in your project's [API settings](/dashboard/project/_/settings/api). It's recommended that you keep it low to limit the payload size of accidental or malicious requests. You can use `range()` queries to paginate through your data.\n\t* - `select()` can be combined with [Filters](/docs/reference/javascript/using-filters)\n\t* - `select()` can be combined with [Modifiers](/docs/reference/javascript/using-modifiers)\n\t* - `apikey` is a reserved keyword if you're using the [Supabase Platform](/docs/guides/platform) and [should be avoided as a column name](https://github.com/supabase/supabase/issues/5465). *\n\t* @category Database\n\t*\n\t* @example Getting your data\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select()\n\t* ```\n\t*\n\t* @exampleSql Getting your data\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Harry'),\n\t*   (2, 'Frodo'),\n\t*   (3, 'Katniss');\n\t* ```\n\t*\n\t* @exampleResponse Getting your data\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"id\": 1,\n\t*       \"name\": \"Harry\"\n\t*     },\n\t*     {\n\t*       \"id\": 2,\n\t*       \"name\": \"Frodo\"\n\t*     },\n\t*     {\n\t*       \"id\": 3,\n\t*       \"name\": \"Katniss\"\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Handling errors\n\t* The most useful field on a Postgres error is usually `hint` — when the database knows the fix, it puts the literal SQL there. For example, a permission-denied error (`code: '42501'`) arrives with a `hint` like `\"Grant the required privileges to the current role with: GRANT SELECT ON public.characters TO anon;\"`. Log the full `error` object so the hint isn't hidden behind `error.message`.\n\t*\n\t* @example Handling errors\n\t* ```js\n\t* const { data, error } = await supabase.from('characters').select()\n\t* if (error) {\n\t*   // Logs the full error: message, code, details, and hint.\n\t*   console.error(error)\n\t*   return\n\t* }\n\t* ```\n\t*\n\t* @exampleResponse Handling errors\n\t* ```json\n\t* {\n\t*   \"error\": {\n\t*     \"code\": \"42501\",\n\t*     \"details\": null,\n\t*     \"hint\": \"Grant the required privileges to the current role with: GRANT SELECT ON public.characters TO anon;\",\n\t*     \"message\": \"permission denied for table characters\"\n\t*   },\n\t*   \"status\": 401,\n\t*   \"statusText\": \"\"\n\t* }\n\t* ```\n\t*\n\t* @example Selecting specific columns\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .from('characters')\n\t*   .select('name')\n\t* ```\n\t*\n\t* @exampleSql Selecting specific columns\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Frodo'),\n\t*   (2, 'Harry'),\n\t*   (3, 'Katniss');\n\t* ```\n\t*\n\t* @exampleResponse Selecting specific columns\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"name\": \"Frodo\"\n\t*     },\n\t*     {\n\t*       \"name\": \"Harry\"\n\t*     },\n\t*     {\n\t*       \"name\": \"Katniss\"\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Query referenced tables\n\t* If your database has foreign key relationships, you can query related tables too.\n\t*\n\t* @example Query referenced tables\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .from('orchestral_sections')\n\t*   .select(`\n\t*     name,\n\t*     instruments (\n\t*       name\n\t*     )\n\t*   `)\n\t* ```\n\t*\n\t* @exampleSql Query referenced tables\n\t* ```sql\n\t* create table\n\t*   orchestral_sections (id int8 primary key, name text);\n\t* create table\n\t*   instruments (\n\t*     id int8 primary key,\n\t*     section_id int8 not null references orchestral_sections,\n\t*     name text\n\t*   );\n\t*\n\t* insert into\n\t*   orchestral_sections (id, name)\n\t* values\n\t*   (1, 'strings'),\n\t*   (2, 'woodwinds');\n\t* insert into\n\t*   instruments (id, section_id, name)\n\t* values\n\t*   (1, 2, 'flute'),\n\t*   (2, 1, 'violin');\n\t* ```\n\t*\n\t* @exampleResponse Query referenced tables\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"name\": \"strings\",\n\t*       \"instruments\": [\n\t*         {\n\t*           \"name\": \"violin\"\n\t*         }\n\t*       ]\n\t*     },\n\t*     {\n\t*       \"name\": \"woodwinds\",\n\t*       \"instruments\": [\n\t*         {\n\t*           \"name\": \"flute\"\n\t*         }\n\t*       ]\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Query referenced tables with spaces in their names\n\t* If your table name contains spaces, you must use double quotes in the `select` statement to reference the table.\n\t*\n\t* @example Query referenced tables with spaces in their names\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .from('orchestral sections')\n\t*   .select(`\n\t*     name,\n\t*     \"musical instruments\" (\n\t*       name\n\t*     )\n\t*   `)\n\t* ```\n\t*\n\t* @exampleSql Query referenced tables with spaces in their names\n\t* ```sql\n\t* create table\n\t*   \"orchestral sections\" (id int8 primary key, name text);\n\t* create table\n\t*   \"musical instruments\" (\n\t*     id int8 primary key,\n\t*     section_id int8 not null references \"orchestral sections\",\n\t*     name text\n\t*   );\n\t*\n\t* insert into\n\t*   \"orchestral sections\" (id, name)\n\t* values\n\t*   (1, 'strings'),\n\t*   (2, 'woodwinds');\n\t* insert into\n\t*   \"musical instruments\" (id, section_id, name)\n\t* values\n\t*   (1, 2, 'flute'),\n\t*   (2, 1, 'violin');\n\t* ```\n\t*\n\t* @exampleResponse Query referenced tables with spaces in their names\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"name\": \"strings\",\n\t*       \"musical instruments\": [\n\t*         {\n\t*           \"name\": \"violin\"\n\t*         }\n\t*       ]\n\t*     },\n\t*     {\n\t*       \"name\": \"woodwinds\",\n\t*       \"musical instruments\": [\n\t*         {\n\t*           \"name\": \"flute\"\n\t*         }\n\t*       ]\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Query referenced tables through a join table\n\t* If you're in a situation where your tables are **NOT** directly\n\t* related, but instead are joined by a _join table_, you can still use\n\t* the `select()` method to query the related data. The join table needs\n\t* to have the foreign keys as part of its composite primary key.\n\t*\n\t* @example Query referenced tables through a join table\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('users')\n\t*   .select(`\n\t*     name,\n\t*     teams (\n\t*       name\n\t*     )\n\t*   `)\n\t*   \n\t* ```\n\t*\n\t* @exampleSql Query referenced tables through a join table\n\t* ```sql\n\t* create table\n\t*   users (\n\t*     id int8 primary key,\n\t*     name text\n\t*   );\n\t* create table\n\t*   teams (\n\t*     id int8 primary key,\n\t*     name text\n\t*   );\n\t* -- join table\n\t* create table\n\t*   users_teams (\n\t*     user_id int8 not null references users,\n\t*     team_id int8 not null references teams,\n\t*     -- both foreign keys must be part of a composite primary key\n\t*     primary key (user_id, team_id)\n\t*   );\n\t*\n\t* insert into\n\t*   users (id, name)\n\t* values\n\t*   (1, 'Kiran'),\n\t*   (2, 'Evan');\n\t* insert into\n\t*   teams (id, name)\n\t* values\n\t*   (1, 'Green'),\n\t*   (2, 'Blue');\n\t* insert into\n\t*   users_teams (user_id, team_id)\n\t* values\n\t*   (1, 1),\n\t*   (1, 2),\n\t*   (2, 2);\n\t* ```\n\t*\n\t* @exampleResponse Query referenced tables through a join table\n\t* ```json\n\t*   {\n\t*     \"data\": [\n\t*       {\n\t*         \"name\": \"Kiran\",\n\t*         \"teams\": [\n\t*           {\n\t*             \"name\": \"Green\"\n\t*           },\n\t*           {\n\t*             \"name\": \"Blue\"\n\t*           }\n\t*         ]\n\t*       },\n\t*       {\n\t*         \"name\": \"Evan\",\n\t*         \"teams\": [\n\t*           {\n\t*             \"name\": \"Blue\"\n\t*           }\n\t*         ]\n\t*       }\n\t*     ],\n\t*     \"status\": 200,\n\t*     \"statusText\": \"OK\"\n\t*   }\n\t*   \n\t* ```\n\t*\n\t* @exampleDescription Query the same referenced table multiple times\n\t* If you need to query the same referenced table twice, use the name of the\n\t* joined column to identify which join to use. You can also give each\n\t* column an alias.\n\t*\n\t* @example Query the same referenced table multiple times\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('messages')\n\t*   .select(`\n\t*     content,\n\t*     from:sender_id(name),\n\t*     to:receiver_id(name)\n\t*   `)\n\t*\n\t* // To infer types, use the name of the table (in this case `users`) and\n\t* // the name of the foreign key constraint.\n\t* const { data, error } = await supabase\n\t*   .from('messages')\n\t*   .select(`\n\t*     content,\n\t*     from:users!messages_sender_id_fkey(name),\n\t*     to:users!messages_receiver_id_fkey(name)\n\t*   `)\n\t* ```\n\t*\n\t* @exampleSql Query the same referenced table multiple times\n\t* ```sql\n\t*  create table\n\t*  users (id int8 primary key, name text);\n\t*\n\t*  create table\n\t*    messages (\n\t*      sender_id int8 not null references users,\n\t*      receiver_id int8 not null references users,\n\t*      content text\n\t*    );\n\t*\n\t*  insert into\n\t*    users (id, name)\n\t*  values\n\t*    (1, 'Kiran'),\n\t*    (2, 'Evan');\n\t*\n\t*  insert into\n\t*    messages (sender_id, receiver_id, content)\n\t*  values\n\t*    (1, 2, '👋');\n\t*  ```\n\t* ```\n\t*\n\t* @exampleResponse Query the same referenced table multiple times\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"content\": \"👋\",\n\t*       \"from\": {\n\t*         \"name\": \"Kiran\"\n\t*       },\n\t*       \"to\": {\n\t*         \"name\": \"Evan\"\n\t*       }\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Query nested foreign tables through a join table\n\t* You can use the result of a joined table to gather data in\n\t* another foreign table. With multiple references to the same foreign\n\t* table you must specify the column on which to conduct the join.\n\t*\n\t* @example Query nested foreign tables through a join table\n\t* ```ts\n\t*   const { data, error } = await supabase\n\t*     .from('games')\n\t*     .select(`\n\t*       game_id:id,\n\t*       away_team:teams!games_away_team_fkey (\n\t*         users (\n\t*           id,\n\t*           name\n\t*         )\n\t*       )\n\t*     `)\n\t*   \n\t* ```\n\t*\n\t* @exampleSql Query nested foreign tables through a join table\n\t* ```sql\n\t* ```sql\n\t* create table\n\t*   users (\n\t*     id int8 primary key,\n\t*     name text\n\t*   );\n\t* create table\n\t*   teams (\n\t*     id int8 primary key,\n\t*     name text\n\t*   );\n\t* -- join table\n\t* create table\n\t*   users_teams (\n\t*     user_id int8 not null references users,\n\t*     team_id int8 not null references teams,\n\t*\n\t*     primary key (user_id, team_id)\n\t*   );\n\t* create table\n\t*   games (\n\t*     id int8 primary key,\n\t*     home_team int8 not null references teams,\n\t*     away_team int8 not null references teams,\n\t*     name text\n\t*   );\n\t*\n\t* insert into users (id, name)\n\t* values\n\t*   (1, 'Kiran'),\n\t*   (2, 'Evan');\n\t* insert into\n\t*   teams (id, name)\n\t* values\n\t*   (1, 'Green'),\n\t*   (2, 'Blue');\n\t* insert into\n\t*   users_teams (user_id, team_id)\n\t* values\n\t*   (1, 1),\n\t*   (1, 2),\n\t*   (2, 2);\n\t* insert into\n\t*   games (id, home_team, away_team, name)\n\t* values\n\t*   (1, 1, 2, 'Green vs Blue'),\n\t*   (2, 2, 1, 'Blue vs Green');\n\t* ```\n\t*\n\t* @exampleResponse Query nested foreign tables through a join table\n\t* ```json\n\t*   {\n\t*     \"data\": [\n\t*       {\n\t*         \"game_id\": 1,\n\t*         \"away_team\": {\n\t*           \"users\": [\n\t*             {\n\t*               \"id\": 1,\n\t*               \"name\": \"Kiran\"\n\t*             },\n\t*             {\n\t*               \"id\": 2,\n\t*               \"name\": \"Evan\"\n\t*             }\n\t*           ]\n\t*         }\n\t*       },\n\t*       {\n\t*         \"game_id\": 2,\n\t*         \"away_team\": {\n\t*           \"users\": [\n\t*             {\n\t*               \"id\": 1,\n\t*               \"name\": \"Kiran\"\n\t*             }\n\t*           ]\n\t*         }\n\t*       }\n\t*     ],\n\t*     \"status\": 200,\n\t*     \"statusText\": \"OK\"\n\t*   }\n\t*   \n\t* ```\n\t*\n\t* @exampleDescription Filtering through referenced tables\n\t* If the filter on a referenced table's column is not satisfied, the referenced\n\t* table returns `[]` or `null` but the parent table is not filtered out.\n\t* If you want to filter out the parent table rows, use the `!inner` hint\n\t*\n\t* @example Filtering through referenced tables\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('instruments')\n\t*   .select('name, orchestral_sections(*)')\n\t*   .eq('orchestral_sections.name', 'percussion')\n\t* ```\n\t*\n\t* @exampleSql Filtering through referenced tables\n\t* ```sql\n\t* create table\n\t*   orchestral_sections (id int8 primary key, name text);\n\t* create table\n\t*   instruments (\n\t*     id int8 primary key,\n\t*     section_id int8 not null references orchestral_sections,\n\t*     name text\n\t*   );\n\t*\n\t* insert into\n\t*   orchestral_sections (id, name)\n\t* values\n\t*   (1, 'strings'),\n\t*   (2, 'woodwinds');\n\t* insert into\n\t*   instruments (id, section_id, name)\n\t* values\n\t*   (1, 2, 'flute'),\n\t*   (2, 1, 'violin');\n\t* ```\n\t*\n\t* @exampleResponse Filtering through referenced tables\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"name\": \"flute\",\n\t*       \"orchestral_sections\": null\n\t*     },\n\t*     {\n\t*       \"name\": \"violin\",\n\t*       \"orchestral_sections\": null\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Querying referenced table with count\n\t* You can get the number of rows in a related table by using the\n\t* **count** property.\n\t*\n\t* @example Querying referenced table with count\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('orchestral_sections')\n\t*   .select(`*, instruments(count)`)\n\t* ```\n\t*\n\t* @exampleSql Querying referenced table with count\n\t* ```sql\n\t* create table orchestral_sections (\n\t*   \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n\t*   \"name\" text\n\t* );\n\t*\n\t* create table characters (\n\t*   \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n\t*   \"name\" text,\n\t*   \"section_id\" \"uuid\" references public.orchestral_sections on delete cascade\n\t* );\n\t*\n\t* with section as (\n\t*   insert into orchestral_sections (name)\n\t*   values ('strings') returning id\n\t* )\n\t* insert into instruments (name, section_id) values\n\t* ('violin', (select id from section)),\n\t* ('viola', (select id from section)),\n\t* ('cello', (select id from section)),\n\t* ('double bass', (select id from section));\n\t* ```\n\t*\n\t* @exampleResponse Querying referenced table with count\n\t* ```json\n\t* [\n\t*   {\n\t*     \"id\": \"693694e7-d993-4360-a6d7-6294e325d9b6\",\n\t*     \"name\": \"strings\",\n\t*     \"instruments\": [\n\t*       {\n\t*         \"count\": 4\n\t*       }\n\t*     ]\n\t*   }\n\t* ]\n\t* ```\n\t*\n\t* @exampleDescription Querying with count option\n\t* You can get the number of rows by using the\n\t* [count](/docs/reference/javascript/select#parameters) option.\n\t*\n\t* @example Querying with count option\n\t* ```ts\n\t* const { count, error } = await supabase\n\t*   .from('characters')\n\t*   .select('*', { count: 'exact', head: true })\n\t* ```\n\t*\n\t* @exampleSql Querying with count option\n\t* ```sql\n\t* create table\n\t*   characters (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   characters (id, name)\n\t* values\n\t*   (1, 'Luke'),\n\t*   (2, 'Leia'),\n\t*   (3, 'Han');\n\t* ```\n\t*\n\t* @exampleResponse Querying with count option\n\t* ```json\n\t* {\n\t*   \"count\": 3,\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Querying JSON data\n\t* You can select and filter data inside of\n\t* [JSON](/docs/guides/database/json) columns. Postgres offers some\n\t* [operators](/docs/guides/database/json#query-the-jsonb-data) for\n\t* querying JSON data.\n\t*\n\t* @example Querying JSON data\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('users')\n\t*   .select(`\n\t*     id, name,\n\t*     address->city\n\t*   `)\n\t* ```\n\t*\n\t* @exampleSql Querying JSON data\n\t* ```sql\n\t* create table\n\t*   users (\n\t*     id int8 primary key,\n\t*     name text,\n\t*     address jsonb\n\t*   );\n\t*\n\t* insert into\n\t*   users (id, name, address)\n\t* values\n\t*   (1, 'Frodo', '{\"city\":\"Hobbiton\"}');\n\t* ```\n\t*\n\t* @exampleResponse Querying JSON data\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"id\": 1,\n\t*       \"name\": \"Frodo\",\n\t*       \"city\": \"Hobbiton\"\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Querying referenced table with inner join\n\t* If you don't want to return the referenced table contents, you can leave the parenthesis empty.\n\t* Like `.select('name, orchestral_sections!inner()')`.\n\t*\n\t* @example Querying referenced table with inner join\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('instruments')\n\t*   .select('name, orchestral_sections!inner(name)')\n\t*   .eq('orchestral_sections.name', 'woodwinds')\n\t*   .limit(1)\n\t* ```\n\t*\n\t* @exampleSql Querying referenced table with inner join\n\t* ```sql\n\t* create table orchestral_sections (\n\t*   \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n\t*   \"name\" text\n\t* );\n\t*\n\t* create table instruments (\n\t*   \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n\t*   \"name\" text,\n\t*   \"section_id\" \"uuid\" references public.orchestral_sections on delete cascade\n\t* );\n\t*\n\t* with section as (\n\t*   insert into orchestral_sections (name)\n\t*   values ('woodwinds') returning id\n\t* )\n\t* insert into instruments (name, section_id) values\n\t* ('flute', (select id from section)),\n\t* ('clarinet', (select id from section)),\n\t* ('bassoon', (select id from section)),\n\t* ('piccolo', (select id from section));\n\t* ```\n\t*\n\t* @exampleResponse Querying referenced table with inner join\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"name\": \"flute\",\n\t*       \"orchestral_sections\": {\"name\": \"woodwinds\"}\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Switching schemas per query\n\t* In addition to setting the schema during initialization, you can also switch schemas on a per-query basis.\n\t* Make sure you've set up your [database privileges and API settings](/docs/guides/api/using-custom-schemas).\n\t*\n\t* @example Switching schemas per query\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .schema('myschema')\n\t*   .from('mytable')\n\t*   .select()\n\t* ```\n\t*\n\t* @exampleSql Switching schemas per query\n\t* ```sql\n\t* create schema myschema;\n\t*\n\t* create table myschema.mytable (\n\t*   id uuid primary key default gen_random_uuid(),\n\t*   data text\n\t* );\n\t*\n\t* insert into myschema.mytable (data) values ('mydata');\n\t* ```\n\t*\n\t* @exampleResponse Switching schemas per query\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"id\": \"4162e008-27b0-4c0f-82dc-ccaeee9a624d\",\n\t*       \"data\": \"mydata\"\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*/\n\tselect(columns, options) {\n\t\tconst { head = false, count } = options !== null && options !== void 0 ? options : {};\n\t\tconst method = head ? \"HEAD\" : \"GET\";\n\t\tlet quoted = false;\n\t\tconst cleanedColumns = (columns !== null && columns !== void 0 ? columns : \"*\").split(\"\").map((c) => {\n\t\t\tif (/\\s/.test(c) && !quoted) return \"\";\n\t\t\tif (c === \"\\\"\") quoted = !quoted;\n\t\t\treturn c;\n\t\t}).join(\"\");\n\t\tconst { url, headers } = this.cloneRequestState();\n\t\turl.searchParams.set(\"select\", cleanedColumns);\n\t\tif (count) headers.append(\"Prefer\", `count=${count}`);\n\t\treturn new PostgrestFilterBuilder({\n\t\t\tmethod,\n\t\t\turl,\n\t\t\theaders,\n\t\t\tschema: this.schema,\n\t\t\tfetch: this.fetch,\n\t\t\turlLengthLimit: this.urlLengthLimit,\n\t\t\tretry: this.retry\n\t\t});\n\t}\n\t/**\n\t* Perform an INSERT into the table or view.\n\t*\n\t* By default, inserted rows are not returned. To return it, chain the call\n\t* with `.select()`.\n\t*\n\t* @param values - The values to insert. Pass an object to insert a single row\n\t* or an array to insert multiple rows.\n\t*\n\t* @param options - Named parameters\n\t*\n\t* @param options.count - Count algorithm to use to count inserted rows.\n\t*\n\t* `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n\t* hood.\n\t*\n\t* `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n\t* statistics under the hood.\n\t*\n\t* `\"estimated\"`: Uses exact count for low numbers and planned count for high\n\t* numbers.\n\t*\n\t* @param options.defaultToNull - Make missing fields default to `null`.\n\t* Otherwise, use the default value for the column. Only applies for bulk\n\t* inserts.\n\t*\n\t* @category Database\n\t*\n\t* @example Create a record\n\t* ```ts\n\t* const { error } = await supabase\n\t*   .from('countries')\n\t*   .insert({ id: 1, name: 'Mordor' })\n\t* ```\n\t*\n\t* @exampleSql Create a record\n\t* ```sql\n\t* create table\n\t*   countries (id int8 primary key, name text);\n\t* ```\n\t*\n\t* @exampleResponse Create a record\n\t* ```json\n\t* {\n\t*   \"status\": 201,\n\t*   \"statusText\": \"\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Handling errors\n\t* `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT INSERT ON public.countries TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n\t*\n\t* @example Handling errors\n\t* ```js\n\t* const { error } = await supabase.from('countries').insert({ id: 1, name: 'Mordor' })\n\t* if (error) console.error(error)\n\t* ```\n\t*\n\t* @example Create a record and return it\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('countries')\n\t*   .insert({ id: 1, name: 'Mordor' })\n\t*   .select()\n\t* ```\n\t*\n\t* @exampleSql Create a record and return it\n\t* ```sql\n\t* create table\n\t*   countries (id int8 primary key, name text);\n\t* ```\n\t*\n\t* @exampleResponse Create a record and return it\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"id\": 1,\n\t*       \"name\": \"Mordor\"\n\t*     }\n\t*   ],\n\t*   \"status\": 201,\n\t*   \"statusText\": \"\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Bulk create\n\t* A bulk create operation is handled in a single transaction.\n\t* If any of the inserts fail, none of the rows are inserted.\n\t*\n\t* @example Bulk create\n\t* ```ts\n\t* const { error } = await supabase\n\t*   .from('countries')\n\t*   .insert([\n\t*     { id: 1, name: 'Mordor' },\n\t*     { id: 1, name: 'The Shire' },\n\t*   ])\n\t* ```\n\t*\n\t* @exampleSql Bulk create\n\t* ```sql\n\t* create table\n\t*   countries (id int8 primary key, name text);\n\t* ```\n\t*\n\t* @exampleResponse Bulk create\n\t* ```json\n\t* {\n\t*   \"error\": {\n\t*     \"code\": \"23505\",\n\t*     \"details\": \"Key (id)=(1) already exists.\",\n\t*     \"hint\": null,\n\t*     \"message\": \"duplicate key value violates unique constraint \\\"countries_pkey\\\"\"\n\t*   },\n\t*   \"status\": 409,\n\t*   \"statusText\": \"\"\n\t* }\n\t* ```\n\t*/\n\tinsert(values, { count, defaultToNull = true } = {}) {\n\t\tvar _this$fetch;\n\t\tconst method = \"POST\";\n\t\tconst { url, headers } = this.cloneRequestState();\n\t\tif (count) headers.append(\"Prefer\", `count=${count}`);\n\t\tif (!defaultToNull) headers.append(\"Prefer\", `missing=default`);\n\t\tif (Array.isArray(values)) {\n\t\t\tconst columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []);\n\t\t\tif (columns.length > 0) {\n\t\t\t\tconst uniqueColumns = [...new Set(columns)].map((column) => `\"${column}\"`);\n\t\t\t\turl.searchParams.set(\"columns\", uniqueColumns.join(\",\"));\n\t\t\t}\n\t\t}\n\t\treturn new PostgrestFilterBuilder({\n\t\t\tmethod,\n\t\t\turl,\n\t\t\theaders,\n\t\t\tschema: this.schema,\n\t\t\tbody: values,\n\t\t\tfetch: (_this$fetch = this.fetch) !== null && _this$fetch !== void 0 ? _this$fetch : fetch,\n\t\t\turlLengthLimit: this.urlLengthLimit,\n\t\t\tretry: this.retry\n\t\t});\n\t}\n\t/**\n\t* Perform an UPSERT on the table or view. Depending on the column(s) passed\n\t* to `onConflict`, `.upsert()` allows you to perform the equivalent of\n\t* `.insert()` if a row with the corresponding `onConflict` columns doesn't\n\t* exist, or if it does exist, perform an alternative action depending on\n\t* `ignoreDuplicates`.\n\t*\n\t* By default, upserted rows are not returned. To return it, chain the call\n\t* with `.select()`.\n\t*\n\t* @param values - The values to upsert with. Pass an object to upsert a\n\t* single row or an array to upsert multiple rows.\n\t*\n\t* @param options - Named parameters\n\t*\n\t* @param options.onConflict - Comma-separated UNIQUE column(s) to specify how\n\t* duplicate rows are determined. Two rows are duplicates if all the\n\t* `onConflict` columns are equal.\n\t*\n\t* @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If\n\t* `false`, duplicate rows are merged with existing rows.\n\t*\n\t* @param options.count - Count algorithm to use to count upserted rows.\n\t*\n\t* `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n\t* hood.\n\t*\n\t* `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n\t* statistics under the hood.\n\t*\n\t* `\"estimated\"`: Uses exact count for low numbers and planned count for high\n\t* numbers.\n\t*\n\t* @param options.defaultToNull - Make missing fields default to `null`.\n\t* Otherwise, use the default value for the column. This only applies when\n\t* inserting new rows, not when merging with existing rows under\n\t* `ignoreDuplicates: false`. This also only applies when doing bulk upserts.\n\t*\n\t* @example Upsert a single row using a unique key\n\t* ```ts\n\t* // Upserting a single row, overwriting based on the 'username' unique column\n\t* const { data, error } = await supabase\n\t*   .from('users')\n\t*   .upsert({ username: 'supabot' }, { onConflict: 'username' })\n\t*\n\t* // Example response:\n\t* // {\n\t* //   data: [\n\t* //     { id: 4, message: 'bar', username: 'supabot' }\n\t* //   ],\n\t* //   error: null\n\t* // }\n\t* ```\n\t*\n\t* @example Upsert with conflict resolution and exact row counting\n\t* ```ts\n\t* // Upserting and returning exact count\n\t* const { data, error, count } = await supabase\n\t*   .from('users')\n\t*   .upsert(\n\t*     {\n\t*       id: 3,\n\t*       message: 'foo',\n\t*       username: 'supabot'\n\t*     },\n\t*     {\n\t*       onConflict: 'username',\n\t*       count: 'exact'\n\t*     }\n\t*   )\n\t*\n\t* // Example response:\n\t* // {\n\t* //   data: [\n\t* //     {\n\t* //       id: 42,\n\t* //       handle: \"saoirse\",\n\t* //       display_name: \"Saoirse\"\n\t* //     }\n\t* //   ],\n\t* //   count: 1,\n\t* //   error: null\n\t* // }\n\t* ```\n\t*\n\t* @category Database\n\t*\n\t* @remarks\n\t* - Primary keys must be included in `values` to use upsert.\n\t*\n\t* @example Upsert your data\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('instruments')\n\t*   .upsert({ id: 1, name: 'piano' })\n\t*   .select()\n\t* ```\n\t*\n\t* @exampleSql Upsert your data\n\t* ```sql\n\t* create table\n\t*   instruments (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   instruments (id, name)\n\t* values\n\t*   (1, 'harpsichord');\n\t* ```\n\t*\n\t* @exampleResponse Upsert your data\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"id\": 1,\n\t*       \"name\": \"piano\"\n\t*     }\n\t*   ],\n\t*   \"status\": 201,\n\t*   \"statusText\": \"\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Handling errors\n\t* `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT INSERT, UPDATE ON public.instruments TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n\t*\n\t* @example Handling errors\n\t* ```js\n\t* const { data, error } = await supabase.from('instruments').upsert({ id: 1, name: 'piano' }).select()\n\t* if (error) console.error(error)\n\t* ```\n\t*\n\t* @example Bulk Upsert your data\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('instruments')\n\t*   .upsert([\n\t*     { id: 1, name: 'piano' },\n\t*     { id: 2, name: 'harp' },\n\t*   ])\n\t*   .select()\n\t* ```\n\t*\n\t* @exampleSql Bulk Upsert your data\n\t* ```sql\n\t* create table\n\t*   instruments (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   instruments (id, name)\n\t* values\n\t*   (1, 'harpsichord');\n\t* ```\n\t*\n\t* @exampleResponse Bulk Upsert your data\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"id\": 1,\n\t*       \"name\": \"piano\"\n\t*     },\n\t*     {\n\t*       \"id\": 2,\n\t*       \"name\": \"harp\"\n\t*     }\n\t*   ],\n\t*   \"status\": 201,\n\t*   \"statusText\": \"\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Upserting into tables with constraints\n\t* In the following query, `upsert()` implicitly uses the `id`\n\t* (primary key) column to determine conflicts. If there is no existing\n\t* row with the same `id`, `upsert()` inserts a new row, which\n\t* will fail in this case as there is already a row with `handle` `\"saoirse\"`.\n\t* Using the `onConflict` option, you can instruct `upsert()` to use\n\t* another column with a unique constraint to determine conflicts.\n\t*\n\t* @example Upserting into tables with constraints\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('users')\n\t*   .upsert({ id: 42, handle: 'saoirse', display_name: 'Saoirse' })\n\t*   .select()\n\t* ```\n\t*\n\t* @exampleSql Upserting into tables with constraints\n\t* ```sql\n\t* create table\n\t*   users (\n\t*     id int8 generated by default as identity primary key,\n\t*     handle text not null unique,\n\t*     display_name text\n\t*   );\n\t*\n\t* insert into\n\t*   users (id, handle, display_name)\n\t* values\n\t*   (1, 'saoirse', null);\n\t* ```\n\t*\n\t* @exampleResponse Upserting into tables with constraints\n\t* ```json\n\t* {\n\t*   \"error\": {\n\t*     \"code\": \"23505\",\n\t*     \"details\": \"Key (handle)=(saoirse) already exists.\",\n\t*     \"hint\": null,\n\t*     \"message\": \"duplicate key value violates unique constraint \\\"users_handle_key\\\"\"\n\t*   },\n\t*   \"status\": 409,\n\t*   \"statusText\": \"\"\n\t* }\n\t* ```\n\t*/\n\tupsert(values, { onConflict, ignoreDuplicates = false, count, defaultToNull = true } = {}) {\n\t\tvar _this$fetch2;\n\t\tconst method = \"POST\";\n\t\tconst { url, headers } = this.cloneRequestState();\n\t\theaders.append(\"Prefer\", `resolution=${ignoreDuplicates ? \"ignore\" : \"merge\"}-duplicates`);\n\t\tif (onConflict !== void 0) url.searchParams.set(\"on_conflict\", onConflict);\n\t\tif (count) headers.append(\"Prefer\", `count=${count}`);\n\t\tif (!defaultToNull) headers.append(\"Prefer\", \"missing=default\");\n\t\tif (Array.isArray(values)) {\n\t\t\tconst columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []);\n\t\t\tif (columns.length > 0) {\n\t\t\t\tconst uniqueColumns = [...new Set(columns)].map((column) => `\"${column}\"`);\n\t\t\t\turl.searchParams.set(\"columns\", uniqueColumns.join(\",\"));\n\t\t\t}\n\t\t}\n\t\treturn new PostgrestFilterBuilder({\n\t\t\tmethod,\n\t\t\turl,\n\t\t\theaders,\n\t\t\tschema: this.schema,\n\t\t\tbody: values,\n\t\t\tfetch: (_this$fetch2 = this.fetch) !== null && _this$fetch2 !== void 0 ? _this$fetch2 : fetch,\n\t\t\turlLengthLimit: this.urlLengthLimit,\n\t\t\tretry: this.retry\n\t\t});\n\t}\n\t/**\n\t* Perform an UPDATE on the table or view.\n\t*\n\t* By default, updated rows are not returned. To return it, chain the call\n\t* with `.select()` after filters.\n\t*\n\t* @param values - The values to update with\n\t*\n\t* @param options - Named parameters\n\t*\n\t* @param options.count - Count algorithm to use to count updated rows.\n\t*\n\t* `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n\t* hood.\n\t*\n\t* `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n\t* statistics under the hood.\n\t*\n\t* `\"estimated\"`: Uses exact count for low numbers and planned count for high\n\t* numbers.\n\t*\n\t* @category Database\n\t*\n\t* @remarks\n\t* - `update()` should always be combined with [Filters](/docs/reference/javascript/using-filters) to target the item(s) you wish to update.\n\t*\n\t* @example Updating your data\n\t* ```ts\n\t* const { error } = await supabase\n\t*   .from('instruments')\n\t*   .update({ name: 'piano' })\n\t*   .eq('id', 1)\n\t* ```\n\t*\n\t* @exampleSql Updating your data\n\t* ```sql\n\t* create table\n\t*   instruments (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   instruments (id, name)\n\t* values\n\t*   (1, 'harpsichord');\n\t* ```\n\t*\n\t* @exampleResponse Updating your data\n\t* ```json\n\t* {\n\t*   \"status\": 204,\n\t*   \"statusText\": \"\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Handling errors\n\t* `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT UPDATE ON public.instruments TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n\t*\n\t* @example Handling errors\n\t* ```js\n\t* const { error } = await supabase.from('instruments').update({ name: 'piano' }).eq('id', 1)\n\t* if (error) console.error(error)\n\t* ```\n\t*\n\t* @example Update a record and return it\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('instruments')\n\t*   .update({ name: 'piano' })\n\t*   .eq('id', 1)\n\t*   .select()\n\t* ```\n\t*\n\t* @exampleSql Update a record and return it\n\t* ```sql\n\t* create table\n\t*   instruments (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   instruments (id, name)\n\t* values\n\t*   (1, 'harpsichord');\n\t* ```\n\t*\n\t* @exampleResponse Update a record and return it\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"id\": 1,\n\t*       \"name\": \"piano\"\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Updating JSON data\n\t* Postgres offers some\n\t* [operators](/docs/guides/database/json#query-the-jsonb-data) for\n\t* working with JSON data. Currently, it is only possible to update the entire JSON document.\n\t*\n\t* @example Updating JSON data\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('users')\n\t*   .update({\n\t*     address: {\n\t*       street: 'Melrose Place',\n\t*       postcode: 90210\n\t*     }\n\t*   })\n\t*   .eq('address->postcode', 90210)\n\t*   .select()\n\t* ```\n\t*\n\t* @exampleSql Updating JSON data\n\t* ```sql\n\t* create table\n\t*   users (\n\t*     id int8 primary key,\n\t*     name text,\n\t*     address jsonb\n\t*   );\n\t*\n\t* insert into\n\t*   users (id, name, address)\n\t* values\n\t*   (1, 'Michael', '{ \"postcode\": 90210 }');\n\t* ```\n\t*\n\t* @exampleResponse Updating JSON data\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"id\": 1,\n\t*       \"name\": \"Michael\",\n\t*       \"address\": {\n\t*         \"street\": \"Melrose Place\",\n\t*         \"postcode\": 90210\n\t*       }\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*/\n\tupdate(values, { count } = {}) {\n\t\tvar _this$fetch3;\n\t\tconst method = \"PATCH\";\n\t\tconst { url, headers } = this.cloneRequestState();\n\t\tif (count) headers.append(\"Prefer\", `count=${count}`);\n\t\treturn new PostgrestFilterBuilder({\n\t\t\tmethod,\n\t\t\turl,\n\t\t\theaders,\n\t\t\tschema: this.schema,\n\t\t\tbody: values,\n\t\t\tfetch: (_this$fetch3 = this.fetch) !== null && _this$fetch3 !== void 0 ? _this$fetch3 : fetch,\n\t\t\turlLengthLimit: this.urlLengthLimit,\n\t\t\tretry: this.retry\n\t\t});\n\t}\n\t/**\n\t* Perform a DELETE on the table or view.\n\t*\n\t* By default, deleted rows are not returned. To return it, chain the call\n\t* with `.select()` after filters.\n\t*\n\t* @param options - Named parameters\n\t*\n\t* @param options.count - Count algorithm to use to count deleted rows.\n\t*\n\t* `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n\t* hood.\n\t*\n\t* `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n\t* statistics under the hood.\n\t*\n\t* `\"estimated\"`: Uses exact count for low numbers and planned count for high\n\t* numbers.\n\t*\n\t* @category Database\n\t*\n\t* @remarks\n\t* - `delete()` should always be combined with [filters](/docs/reference/javascript/using-filters) to target the item(s) you wish to delete.\n\t* - If you use `delete()` with filters and you have\n\t*   [RLS](/docs/learn/auth-deep-dive/auth-row-level-security) enabled, only\n\t*   rows visible through `SELECT` policies are deleted. Note that by default\n\t*   no rows are visible, so you need at least one `SELECT`/`ALL` policy that\n\t*   makes the rows visible.\n\t* - When using `delete().in()`, specify an array of values to target multiple rows with a single query. This is particularly useful for batch deleting entries that share common criteria, such as deleting users by their IDs. Ensure that the array you provide accurately represents all records you intend to delete to avoid unintended data removal.\n\t*\n\t* @example Delete a single record\n\t* ```ts\n\t* const response = await supabase\n\t*   .from('countries')\n\t*   .delete()\n\t*   .eq('id', 1)\n\t* ```\n\t*\n\t* @exampleSql Delete a single record\n\t* ```sql\n\t* create table\n\t*   countries (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   countries (id, name)\n\t* values\n\t*   (1, 'Mordor');\n\t* ```\n\t*\n\t* @exampleResponse Delete a single record\n\t* ```json\n\t* {\n\t*   \"status\": 204,\n\t*   \"statusText\": \"\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Handling errors\n\t* `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT DELETE ON public.countries TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n\t*\n\t* @example Handling errors\n\t* ```js\n\t* const { error } = await supabase.from('countries').delete().eq('id', 1)\n\t* if (error) console.error(error)\n\t* ```\n\t*\n\t* @example Delete a record and return it\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .from('countries')\n\t*   .delete()\n\t*   .eq('id', 1)\n\t*   .select()\n\t* ```\n\t*\n\t* @exampleSql Delete a record and return it\n\t* ```sql\n\t* create table\n\t*   countries (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   countries (id, name)\n\t* values\n\t*   (1, 'Mordor');\n\t* ```\n\t*\n\t* @exampleResponse Delete a record and return it\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"id\": 1,\n\t*       \"name\": \"Mordor\"\n\t*     }\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @example Delete multiple records\n\t* ```ts\n\t* const response = await supabase\n\t*   .from('countries')\n\t*   .delete()\n\t*   .in('id', [1, 2, 3])\n\t* ```\n\t*\n\t* @exampleSql Delete multiple records\n\t* ```sql\n\t* create table\n\t*   countries (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   countries (id, name)\n\t* values\n\t*   (1, 'Rohan'), (2, 'The Shire'), (3, 'Mordor');\n\t* ```\n\t*\n\t* @exampleResponse Delete multiple records\n\t* ```json\n\t* {\n\t*   \"status\": 204,\n\t*   \"statusText\": \"\"\n\t* }\n\t* ```\n\t*/\n\tdelete({ count } = {}) {\n\t\tvar _this$fetch4;\n\t\tconst method = \"DELETE\";\n\t\tconst { url, headers } = this.cloneRequestState();\n\t\tif (count) headers.append(\"Prefer\", `count=${count}`);\n\t\treturn new PostgrestFilterBuilder({\n\t\t\tmethod,\n\t\t\turl,\n\t\t\theaders,\n\t\t\tschema: this.schema,\n\t\t\tfetch: (_this$fetch4 = this.fetch) !== null && _this$fetch4 !== void 0 ? _this$fetch4 : fetch,\n\t\t\turlLengthLimit: this.urlLengthLimit,\n\t\t\tretry: this.retry\n\t\t});\n\t}\n};\n\n//#endregion\n//#region src/PostgrestClient.ts\n/**\n* Build the error for a failed OpenAPI request. PostgREST answers with a JSON\n* error object when it produced the failure itself; proxies and disabled\n* OpenAPI output answer with plain text or an empty body, in which case the\n* body (or, failing that, the status text) becomes the message.\n*/\nfunction toOpenApiError(body, statusText) {\n\ttry {\n\t\tconst parsed = JSON.parse(body);\n\t\tif (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n\t\t\tvar _parsed$message, _parsed$details, _parsed$hint, _parsed$code;\n\t\t\treturn new PostgrestError({\n\t\t\t\tmessage: String((_parsed$message = parsed.message) !== null && _parsed$message !== void 0 ? _parsed$message : body),\n\t\t\t\tdetails: (_parsed$details = parsed.details) !== null && _parsed$details !== void 0 ? _parsed$details : \"\",\n\t\t\t\thint: (_parsed$hint = parsed.hint) !== null && _parsed$hint !== void 0 ? _parsed$hint : \"\",\n\t\t\t\tcode: (_parsed$code = parsed.code) !== null && _parsed$code !== void 0 ? _parsed$code : \"\"\n\t\t\t});\n\t\t}\n\t} catch (_unused) {}\n\treturn new PostgrestError({\n\t\tmessage: body || statusText,\n\t\tdetails: \"\",\n\t\thint: \"\",\n\t\tcode: \"\"\n\t});\n}\n/**\n* Build the response for a request that yielded no readable body: the fetch\n* itself rejected (no status is known, so it is 0), or the body stream failed\n* while being read (the response status is preserved).\n*/\nfunction toTransportFailure(cause, status, statusText) {\n\tvar _err$name;\n\tconst err = cause;\n\treturn {\n\t\tsuccess: false,\n\t\terror: new PostgrestError({\n\t\t\tmessage: `${(_err$name = err === null || err === void 0 ? void 0 : err.name) !== null && _err$name !== void 0 ? _err$name : \"FetchError\"}: ${err === null || err === void 0 ? void 0 : err.message}`,\n\t\t\tdetails: \"\",\n\t\t\thint: \"\",\n\t\t\tcode: \"\"\n\t\t}),\n\t\tdata: null,\n\t\tcount: null,\n\t\tstatus,\n\t\tstatusText\n\t};\n}\n/**\n* PostgREST client.\n*\n* @typeParam Database - Types for the schema from the [type\n* generator](https://supabase.com/docs/reference/javascript/next/typescript-support)\n*\n* @typeParam SchemaName - Postgres schema to switch to. Must be a string\n* literal, the same one passed to the constructor. If the schema is not\n* `\"public\"`, this must be supplied manually.\n*/\nvar PostgrestClient = class PostgrestClient {\n\t/**\n\t* Creates a PostgREST client.\n\t*\n\t* @param url - URL of the PostgREST endpoint\n\t* @param options - Named parameters\n\t* @param options.headers - Custom headers\n\t* @param options.schema - Postgres schema to switch to\n\t* @param options.fetch - Custom fetch\n\t* @param options.timeout - Optional timeout in milliseconds for all requests. When set, requests will automatically abort after this duration to prevent indefinite hangs.\n\t* @param options.urlLengthLimit - Maximum URL length in characters before warnings/errors are triggered. Defaults to 8000.\n\t* @param options.retry - Enable or disable automatic retries for transient errors.\n\t*   When enabled, idempotent requests (GET, HEAD, OPTIONS) that fail with network\n\t*   errors or HTTP 503/520 responses will be automatically retried up to 3 times\n\t*   with exponential backoff (1s, 2s, 4s). Defaults to `true`.\n\t* @example Using supabase-js (recommended)\n\t* ```ts\n\t* import { createClient } from '@supabase/supabase-js'\n\t*\n\t* const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n\t* const { data, error } = await supabase.from('profiles').select('*')\n\t* ```\n\t*\n\t* @category Database\n\t*\n\t* @remarks\n\t* - A `timeout` option (in milliseconds) can be set to automatically abort requests that take too long.\n\t* - A `urlLengthLimit` option (default: 8000) can be set to control when URL length warnings are included in error messages for aborted requests.\n\t*\n\t* @example Standalone import for bundle-sensitive environments\n\t* ```ts\n\t* import { PostgrestClient } from '@supabase/postgrest-js'\n\t*\n\t* const postgrest = new PostgrestClient('https://xyzcompany.supabase.co/rest/v1', {\n\t*   headers: { apikey: 'your-publishable-key' },\n\t*   schema: 'public',\n\t*   timeout: 30000, // 30 second timeout\n\t* })\n\t* ```\n\t*/\n\tconstructor(url, { headers = {}, schema, fetch: fetch$1, timeout, urlLengthLimit = 8e3, retry } = {}) {\n\t\tthis.url = url;\n\t\tthis.headers = new Headers(headers);\n\t\tthis.schemaName = schema;\n\t\tthis.urlLengthLimit = urlLengthLimit;\n\t\tconst originalFetch = fetch$1 !== null && fetch$1 !== void 0 ? fetch$1 : globalThis.fetch;\n\t\tif (timeout !== void 0 && timeout > 0) this.fetch = (input, init) => {\n\t\t\tconst controller = new AbortController();\n\t\t\tconst timeoutId = setTimeout(() => controller.abort(), timeout);\n\t\t\tconst existingSignal = init === null || init === void 0 ? void 0 : init.signal;\n\t\t\tif (existingSignal) {\n\t\t\t\tif (existingSignal.aborted) {\n\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t\treturn originalFetch(input, init);\n\t\t\t\t}\n\t\t\t\tconst abortHandler = () => {\n\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t\tcontroller.abort();\n\t\t\t\t};\n\t\t\t\texistingSignal.addEventListener(\"abort\", abortHandler, { once: true });\n\t\t\t\treturn originalFetch(input, _objectSpread2(_objectSpread2({}, init), {}, { signal: controller.signal })).finally(() => {\n\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t\texistingSignal.removeEventListener(\"abort\", abortHandler);\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn originalFetch(input, _objectSpread2(_objectSpread2({}, init), {}, { signal: controller.signal })).finally(() => clearTimeout(timeoutId));\n\t\t};\n\t\telse this.fetch = originalFetch;\n\t\tthis.retry = retry;\n\t}\n\tfrom(relation) {\n\t\tif (!relation || typeof relation !== \"string\" || relation.trim() === \"\") throw new Error(\"Invalid relation name: relation must be a non-empty string.\");\n\t\treturn new PostgrestQueryBuilder(new URL(`${this.url}/${relation}`), {\n\t\t\theaders: new Headers(this.headers),\n\t\t\tschema: this.schemaName,\n\t\t\tfetch: this.fetch,\n\t\t\turlLengthLimit: this.urlLengthLimit,\n\t\t\tretry: this.retry\n\t\t});\n\t}\n\t/**\n\t* Select a schema to query or perform an function (rpc) call.\n\t*\n\t* The schema needs to be on the list of exposed schemas inside Supabase.\n\t*\n\t* @param schema - The schema to query\n\t*\n\t* @category Database\n\t*/\n\tschema(schema) {\n\t\treturn new PostgrestClient(this.url, {\n\t\t\theaders: this.headers,\n\t\t\tschema,\n\t\t\tfetch: this.fetch,\n\t\t\turlLengthLimit: this.urlLengthLimit,\n\t\t\tretry: this.retry\n\t\t});\n\t}\n\t/**\n\t* Fetch the OpenAPI description PostgREST publishes for this client's schema.\n\t*\n\t* The document lists only the tables, views and functions the caller's role\n\t* holds privileges on; PostgREST applies that filtering server-side. The\n\t* schema is the one this client was created with, so call `.schema()` first\n\t* to describe a different one. Transient failures are retried according to\n\t* the client's `retry` option, like any other idempotent request.\n\t*\n\t* @example\n\t* ```ts\n\t* const { data, error } = await supabase.getOpenApiSpec()\n\t* ```\n\t*\n\t* @example Describe a schema other than the client default\n\t* ```ts\n\t* const { data, error } = await supabase.schema('billing').getOpenApiSpec()\n\t* ```\n\t*\n\t* @category Database\n\t*/\n\tasync getOpenApiSpec() {\n\t\tvar _this = this;\n\t\tvar _this$fetch;\n\t\tconst headers = new Headers(_this.headers);\n\t\theaders.set(\"Accept\", \"application/openapi+json\");\n\t\tif (_this.schemaName) headers.set(\"Accept-Profile\", _this.schemaName);\n\t\tconst requestHeaders = {};\n\t\theaders.forEach((value, key) => {\n\t\t\trequestHeaders[key] = value;\n\t\t});\n\t\tconst fetchImpl = (_this$fetch = _this.fetch) !== null && _this$fetch !== void 0 ? _this$fetch : globalThis.fetch;\n\t\tlet res;\n\t\ttry {\n\t\t\tvar _this$retry;\n\t\t\tres = await fetchWithRetry(fetchImpl, `${_this.url}/`, {\n\t\t\t\tmethod: \"GET\",\n\t\t\t\theaders: requestHeaders\n\t\t\t}, (_this$retry = _this.retry) !== null && _this$retry !== void 0 ? _this$retry : true);\n\t\t} catch (fetchError) {\n\t\t\treturn toTransportFailure(fetchError, 0, \"\");\n\t\t}\n\t\tlet body;\n\t\ttry {\n\t\t\tbody = await res.text();\n\t\t} catch (readError) {\n\t\t\treturn toTransportFailure(readError, res.status, res.statusText);\n\t\t}\n\t\tif (res.ok) try {\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\terror: null,\n\t\t\t\tdata: JSON.parse(body),\n\t\t\t\tcount: null,\n\t\t\t\tstatus: res.status,\n\t\t\t\tstatusText: res.statusText\n\t\t\t};\n\t\t} catch (_unused2) {}\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: toOpenApiError(body, res.statusText),\n\t\t\tdata: null,\n\t\t\tcount: null,\n\t\t\tstatus: res.status,\n\t\t\tstatusText: res.statusText\n\t\t};\n\t}\n\t/**\n\t* Perform a function call.\n\t*\n\t* @param fn - The function name to call\n\t* @param args - The arguments to pass to the function call\n\t* @param options - Named parameters\n\t* @param options.head - When set to `true`, `data` will not be returned.\n\t* Useful if you only need the count.\n\t* @param options.get - When set to `true`, the function will be called with\n\t* read-only access mode.\n\t* @param options.count - Count algorithm to use to count rows returned by the\n\t* function. Only applicable for [set-returning\n\t* functions](https://www.postgresql.org/docs/current/functions-srf.html).\n\t*\n\t* `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n\t* hood.\n\t*\n\t* `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n\t* statistics under the hood.\n\t*\n\t* `\"estimated\"`: Uses exact count for low numbers and planned count for high\n\t* numbers.\n\t*\n\t* @example\n\t* ```ts\n\t* // For cross-schema functions where type inference fails, use overrideTypes:\n\t* const { data } = await supabase\n\t*   .schema('schema_b')\n\t*   .rpc('function_a', {})\n\t*   .overrideTypes<{ id: string; user_id: string }[]>()\n\t* ```\n\t*\n\t* @category Database\n\t*\n\t* @example Call a Postgres function without arguments\n\t* ```ts\n\t* const { data, error } = await supabase.rpc('hello_world')\n\t* ```\n\t*\n\t* @exampleSql Call a Postgres function without arguments\n\t* ```sql\n\t* create function hello_world() returns text as $$\n\t*   select 'Hello world';\n\t* $$ language sql;\n\t* ```\n\t*\n\t* @exampleResponse Call a Postgres function without arguments\n\t* ```json\n\t* {\n\t*   \"data\": \"Hello world\",\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @example Call a Postgres function with arguments\n\t* ```ts\n\t* const { data, error } = await supabase.rpc('echo', { say: '👋' })\n\t* ```\n\t*\n\t* @exampleSql Call a Postgres function with arguments\n\t* ```sql\n\t* create function echo(say text) returns text as $$\n\t*   select say;\n\t* $$ language sql;\n\t* ```\n\t*\n\t* @exampleResponse Call a Postgres function with arguments\n\t* ```json\n\t*   {\n\t*     \"data\": \"👋\",\n\t*     \"status\": 200,\n\t*     \"statusText\": \"OK\"\n\t*   }\n\t*\n\t* ```\n\t*\n\t* @exampleDescription Bulk processing\n\t* You can process large payloads by passing in an array as an argument.\n\t*\n\t* @example Bulk processing\n\t* ```ts\n\t* const { data, error } = await supabase.rpc('add_one_each', { arr: [1, 2, 3] })\n\t* ```\n\t*\n\t* @exampleSql Bulk processing\n\t* ```sql\n\t* create function add_one_each(arr int[]) returns int[] as $$\n\t*   select array_agg(n + 1) from unnest(arr) as n;\n\t* $$ language sql;\n\t* ```\n\t*\n\t* @exampleResponse Bulk processing\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     2,\n\t*     3,\n\t*     4\n\t*   ],\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @exampleDescription Call a Postgres function with filters\n\t* Postgres functions that return tables can also be combined with [Filters](/docs/reference/javascript/using-filters) and [Modifiers](/docs/reference/javascript/using-modifiers).\n\t*\n\t* @example Call a Postgres function with filters\n\t* ```ts\n\t* const { data, error } = await supabase\n\t*   .rpc('list_stored_countries')\n\t*   .eq('id', 1)\n\t*   .single()\n\t* ```\n\t*\n\t* @exampleSql Call a Postgres function with filters\n\t* ```sql\n\t* create table\n\t*   countries (id int8 primary key, name text);\n\t*\n\t* insert into\n\t*   countries (id, name)\n\t* values\n\t*   (1, 'Rohan'),\n\t*   (2, 'The Shire');\n\t*\n\t* create function list_stored_countries() returns setof countries as $$\n\t*   select * from countries;\n\t* $$ language sql;\n\t* ```\n\t*\n\t* @exampleResponse Call a Postgres function with filters\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"id\": 1,\n\t*     \"name\": \"Rohan\"\n\t*   },\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*\n\t* @example Call a read-only Postgres function\n\t* ```ts\n\t* const { data, error } = await supabase.rpc('hello_world', undefined, { get: true })\n\t* ```\n\t*\n\t* @exampleSql Call a read-only Postgres function\n\t* ```sql\n\t* create function hello_world() returns text as $$\n\t*   select 'Hello world';\n\t* $$ language sql;\n\t* ```\n\t*\n\t* @exampleResponse Call a read-only Postgres function\n\t* ```json\n\t* {\n\t*   \"data\": \"Hello world\",\n\t*   \"status\": 200,\n\t*   \"statusText\": \"OK\"\n\t* }\n\t* ```\n\t*/\n\trpc(fn, args = {}, { head = false, get = false, count } = {}) {\n\t\tvar _this$fetch2;\n\t\tlet method;\n\t\tconst url = new URL(`${this.url}/rpc/${fn}`);\n\t\tlet body;\n\t\tconst _isObject = (v) => v !== null && typeof v === \"object\" && (!Array.isArray(v) || v.some(_isObject));\n\t\tconst _hasObjectArg = head && Object.values(args).some(_isObject);\n\t\tif (_hasObjectArg) {\n\t\t\tmethod = \"POST\";\n\t\t\tbody = args;\n\t\t} else if (head || get) {\n\t\t\tmethod = head ? \"HEAD\" : \"GET\";\n\t\t\tObject.entries(args).filter(([_, value]) => value !== void 0).map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(\",\")}}` : `${value}`]).forEach(([name, value]) => {\n\t\t\t\turl.searchParams.append(name, value);\n\t\t\t});\n\t\t} else {\n\t\t\tmethod = \"POST\";\n\t\t\tbody = args;\n\t\t}\n\t\tconst headers = new Headers(this.headers);\n\t\tif (_hasObjectArg) headers.set(\"Prefer\", count ? `count=${count},return=minimal` : \"return=minimal\");\n\t\telse if (count) headers.set(\"Prefer\", `count=${count}`);\n\t\treturn new PostgrestFilterBuilder({\n\t\t\tmethod,\n\t\t\turl,\n\t\t\theaders,\n\t\t\tschema: this.schemaName,\n\t\t\tbody,\n\t\t\tfetch: (_this$fetch2 = this.fetch) !== null && _this$fetch2 !== void 0 ? _this$fetch2 : fetch,\n\t\t\turlLengthLimit: this.urlLengthLimit,\n\t\t\tretry: this.retry\n\t\t});\n\t}\n};\n\n//#endregion\n//#region src/index.ts\nvar src_default = {\n\tPostgrestClient,\n\tPostgrestQueryBuilder,\n\tPostgrestFilterBuilder,\n\tPostgrestTransformBuilder,\n\tPostgrestBuilder,\n\tPostgrestError\n};\n\n//#endregion\nexport { PostgrestBuilder, PostgrestClient, PostgrestError, PostgrestFilterBuilder, PostgrestQueryBuilder, PostgrestTransformBuilder, src_default as default };\n//# sourceMappingURL=index.mjs.map","/**\n * Utilities for creating WebSocket instances across runtimes.\n */\nexport class WebSocketFactory {\n    /**\n     * Static-only utility – prevent instantiation.\n     */\n    constructor() { }\n    static detectEnvironment() {\n        var _a;\n        if (typeof WebSocket !== 'undefined') {\n            return { type: 'native', wsConstructor: WebSocket };\n        }\n        const gt = globalThis;\n        if (typeof globalThis !== 'undefined' && typeof gt.WebSocket !== 'undefined') {\n            return { type: 'native', wsConstructor: gt.WebSocket };\n        }\n        const gl = typeof global !== 'undefined' ? global : undefined;\n        if (gl && typeof gl.WebSocket !== 'undefined') {\n            return { type: 'native', wsConstructor: gl.WebSocket };\n        }\n        if (typeof globalThis !== 'undefined' &&\n            typeof gt.WebSocketPair !== 'undefined' &&\n            typeof globalThis.WebSocket === 'undefined') {\n            return {\n                type: 'cloudflare',\n                error: 'Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.',\n                workaround: 'Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime.',\n            };\n        }\n        if ((typeof globalThis !== 'undefined' && gt.EdgeRuntime) ||\n            (typeof navigator !== 'undefined' && ((_a = navigator.userAgent) === null || _a === void 0 ? void 0 : _a.includes('Vercel-Edge')))) {\n            return {\n                type: 'unsupported',\n                error: 'Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.',\n                workaround: 'Use serverless functions or a different deployment target for WebSocket functionality.',\n            };\n        }\n        // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings\n        const _process = globalThis['process'];\n        if (_process) {\n            const processVersions = _process['versions'];\n            if (processVersions && processVersions['node']) {\n                // Reaching here means an earlier check did not find a native WebSocket,\n                // so this Node.js process is missing the global WebSocket (Node.js 22+).\n                return {\n                    type: 'unsupported',\n                    error: 'Node.js detected but native WebSocket not found.',\n                    workaround: 'Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option.',\n                };\n            }\n        }\n        return {\n            type: 'unsupported',\n            error: 'Unknown JavaScript runtime without WebSocket support.',\n            workaround: \"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation.\",\n        };\n    }\n    /**\n     * Returns the best available WebSocket constructor for the current runtime.\n     *\n     * @category Realtime\n     *\n     * @example Example with error handling\n     * ```ts\n     * try {\n     *   const WS = WebSocketFactory.getWebSocketConstructor()\n     *   const socket = new WS('wss://example.com/socket')\n     * } catch (error) {\n     *   console.error('WebSocket not available in this environment.', error)\n     * }\n     * ```\n     */\n    static getWebSocketConstructor() {\n        const env = this.detectEnvironment();\n        if (env.wsConstructor) {\n            return env.wsConstructor;\n        }\n        let errorMessage = env.error || 'WebSocket not supported in this environment.';\n        if (env.workaround) {\n            errorMessage += `\\n\\nSuggested solution: ${env.workaround}`;\n        }\n        throw new Error(errorMessage);\n    }\n    /**\n     * Detects whether the runtime can establish WebSocket connections.\n     *\n     * @category Realtime\n     *\n     * @example Example in a Node.js script\n     * ```ts\n     * if (!WebSocketFactory.isWebSocketSupported()) {\n     *   console.error('WebSockets are required for this script.')\n     *   process.exitCode = 1\n     * }\n     * ```\n     */\n    static isWebSocketSupported() {\n        try {\n            const env = this.detectEnvironment();\n            return env.type === 'native';\n        }\n        catch (_a) {\n            return false;\n        }\n    }\n}\nexport default WebSocketFactory;\n//# sourceMappingURL=websocket-factory.js.map","import { version } from './version';\nexport const DEFAULT_VERSION = `realtime-js/${version}`;\nexport const VSN_1_0_0 = '1.0.0';\nexport const VSN_2_0_0 = '2.0.0';\nexport const DEFAULT_VSN = VSN_2_0_0;\nexport const VERSION = version;\nexport const DEFAULT_TIMEOUT = 10000;\n/** Mirrors the Realtime server's own default for `postgres_changes_options.timeout`. */\nexport const DEFAULT_POSTGRES_CHANGES_WAIT_TIMEOUT = 15000;\n/**\n * Headroom added to the join timeout when waiting on postgres_changes, covering the\n * CHANNEL_ERROR_BACKOFF_MS sleep (5s by default) the server takes before rejecting a join.\n */\nexport const POSTGRES_CHANGES_WAIT_ERROR_GRACE = 10000;\nexport const WS_CLOSE_NORMAL = 1000;\nexport const MAX_PUSH_BUFFER_SIZE = 100;\nexport const SOCKET_STATES = {\n    connecting: 0,\n    open: 1,\n    closing: 2,\n    closed: 3,\n};\nexport const CHANNEL_STATES = {\n    closed: 'closed',\n    errored: 'errored',\n    joined: 'joined',\n    joining: 'joining',\n    leaving: 'leaving',\n};\nexport const CHANNEL_EVENTS = {\n    close: 'phx_close',\n    error: 'phx_error',\n    join: 'phx_join',\n    reply: 'phx_reply',\n    leave: 'phx_leave',\n    access_token: 'access_token',\n};\nexport const TRANSPORTS = {\n    websocket: 'websocket',\n};\nexport const CONNECTION_STATE = {\n    connecting: 'connecting',\n    open: 'open',\n    closing: 'closing',\n    closed: 'closed',\n};\n//# sourceMappingURL=constants.js.map","export default class Serializer {\n    constructor(allowedMetadataKeys) {\n        this.HEADER_LENGTH = 1;\n        this.USER_BROADCAST_PUSH_META_LENGTH = 6;\n        this.KINDS = { userBroadcastPush: 3, userBroadcast: 4 };\n        this.BINARY_ENCODING = 0;\n        this.JSON_ENCODING = 1;\n        this.BROADCAST_EVENT = 'broadcast';\n        this.allowedMetadataKeys = [];\n        this.allowedMetadataKeys = allowedMetadataKeys !== null && allowedMetadataKeys !== void 0 ? allowedMetadataKeys : [];\n    }\n    encode(msg, callback) {\n        if (msg.event === this.BROADCAST_EVENT &&\n            !(msg.payload instanceof ArrayBuffer) &&\n            typeof msg.payload.event === 'string') {\n            return callback(this._binaryEncodeUserBroadcastPush(msg));\n        }\n        let payload = [msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload];\n        return callback(JSON.stringify(payload));\n    }\n    _binaryEncodeUserBroadcastPush(message) {\n        var _a;\n        if (this._isArrayBuffer((_a = message.payload) === null || _a === void 0 ? void 0 : _a.payload)) {\n            return this._encodeBinaryUserBroadcastPush(message);\n        }\n        else {\n            return this._encodeJsonUserBroadcastPush(message);\n        }\n    }\n    _encodeBinaryUserBroadcastPush(message) {\n        var _a, _b;\n        const userPayload = (_b = (_a = message.payload) === null || _a === void 0 ? void 0 : _a.payload) !== null && _b !== void 0 ? _b : new ArrayBuffer(0);\n        return this._encodeUserBroadcastPush(message, this.BINARY_ENCODING, userPayload);\n    }\n    _encodeJsonUserBroadcastPush(message) {\n        var _a, _b;\n        const userPayload = (_b = (_a = message.payload) === null || _a === void 0 ? void 0 : _a.payload) !== null && _b !== void 0 ? _b : {};\n        const encoder = new TextEncoder();\n        const encodedUserPayload = encoder.encode(JSON.stringify(userPayload)).buffer;\n        return this._encodeUserBroadcastPush(message, this.JSON_ENCODING, encodedUserPayload);\n    }\n    _encodeUserBroadcastPush(message, encodingType, encodedPayload) {\n        var _a, _b;\n        // Encode each header field as UTF-8. The length prefixes are byte counts and\n        // the decode side uses TextDecoder (UTF-8), so measuring with String.length\n        // and writing with charCodeAt would corrupt any multi-byte character (e.g.\n        // accents or emoji) and desynchronize the buffer.\n        const encoder = new TextEncoder();\n        const topic = encoder.encode(message.topic);\n        const ref = encoder.encode((_a = message.ref) !== null && _a !== void 0 ? _a : '');\n        const joinRef = encoder.encode((_b = message.join_ref) !== null && _b !== void 0 ? _b : '');\n        const userEvent = encoder.encode(message.payload.event);\n        // Filter metadata based on allowed keys\n        const rest = this.allowedMetadataKeys\n            ? this._pick(message.payload, this.allowedMetadataKeys)\n            : {};\n        const metadata = encoder.encode(Object.keys(rest).length === 0 ? '' : JSON.stringify(rest));\n        // Validate byte lengths don't exceed uint8 max value (255)\n        if (joinRef.length > 255) {\n            throw new Error(`joinRef length ${joinRef.length} exceeds maximum of 255`);\n        }\n        if (ref.length > 255) {\n            throw new Error(`ref length ${ref.length} exceeds maximum of 255`);\n        }\n        if (topic.length > 255) {\n            throw new Error(`topic length ${topic.length} exceeds maximum of 255`);\n        }\n        if (userEvent.length > 255) {\n            throw new Error(`userEvent length ${userEvent.length} exceeds maximum of 255`);\n        }\n        if (metadata.length > 255) {\n            throw new Error(`metadata length ${metadata.length} exceeds maximum of 255`);\n        }\n        const metaLength = this.USER_BROADCAST_PUSH_META_LENGTH +\n            joinRef.length +\n            ref.length +\n            topic.length +\n            userEvent.length +\n            metadata.length;\n        const header = new ArrayBuffer(this.HEADER_LENGTH + metaLength);\n        const view = new DataView(header);\n        const bytes = new Uint8Array(header);\n        let offset = 0;\n        view.setUint8(offset++, this.KINDS.userBroadcastPush); // kind\n        view.setUint8(offset++, joinRef.length);\n        view.setUint8(offset++, ref.length);\n        view.setUint8(offset++, topic.length);\n        view.setUint8(offset++, userEvent.length);\n        view.setUint8(offset++, metadata.length);\n        view.setUint8(offset++, encodingType);\n        bytes.set(joinRef, offset);\n        offset += joinRef.length;\n        bytes.set(ref, offset);\n        offset += ref.length;\n        bytes.set(topic, offset);\n        offset += topic.length;\n        bytes.set(userEvent, offset);\n        offset += userEvent.length;\n        bytes.set(metadata, offset);\n        offset += metadata.length;\n        var combined = new Uint8Array(header.byteLength + encodedPayload.byteLength);\n        combined.set(new Uint8Array(header), 0);\n        combined.set(new Uint8Array(encodedPayload), header.byteLength);\n        return combined.buffer;\n    }\n    decode(rawPayload, callback) {\n        if (this._isArrayBuffer(rawPayload)) {\n            let result = this._binaryDecode(rawPayload);\n            return callback(result);\n        }\n        if (typeof rawPayload === 'string') {\n            const jsonPayload = JSON.parse(rawPayload);\n            const [join_ref, ref, topic, event, payload] = jsonPayload;\n            return callback({ join_ref, ref, topic, event, payload });\n        }\n        return callback({});\n    }\n    _binaryDecode(buffer) {\n        const view = new DataView(buffer);\n        const kind = view.getUint8(0);\n        const decoder = new TextDecoder();\n        switch (kind) {\n            case this.KINDS.userBroadcast:\n                return this._decodeUserBroadcast(buffer, view, decoder);\n        }\n    }\n    _decodeUserBroadcast(buffer, view, decoder) {\n        const topicSize = view.getUint8(1);\n        const userEventSize = view.getUint8(2);\n        const metadataSize = view.getUint8(3);\n        const payloadEncoding = view.getUint8(4);\n        let offset = this.HEADER_LENGTH + 4;\n        const topic = decoder.decode(buffer.slice(offset, offset + topicSize));\n        offset = offset + topicSize;\n        const userEvent = decoder.decode(buffer.slice(offset, offset + userEventSize));\n        offset = offset + userEventSize;\n        const metadata = decoder.decode(buffer.slice(offset, offset + metadataSize));\n        offset = offset + metadataSize;\n        const payload = buffer.slice(offset, buffer.byteLength);\n        const parsedPayload = payloadEncoding === this.JSON_ENCODING ? JSON.parse(decoder.decode(payload)) : payload;\n        const data = {\n            type: this.BROADCAST_EVENT,\n            event: userEvent,\n            payload: parsedPayload,\n        };\n        // Metadata is optional and always JSON encoded\n        if (metadataSize > 0) {\n            data['meta'] = JSON.parse(metadata);\n        }\n        return { join_ref: null, ref: null, topic: topic, event: this.BROADCAST_EVENT, payload: data };\n    }\n    _isArrayBuffer(buffer) {\n        var _a;\n        return buffer instanceof ArrayBuffer || ((_a = buffer === null || buffer === void 0 ? void 0 : buffer.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'ArrayBuffer';\n    }\n    _pick(obj, keys) {\n        if (!obj || typeof obj !== 'object') {\n            return {};\n        }\n        return Object.fromEntries(Object.entries(obj).filter(([key]) => keys.includes(key)));\n    }\n}\n//# sourceMappingURL=serializer.js.map","/**\n * Helpers to convert the change Payload into native JS types.\n */\n// Adapted from epgsql (src/epgsql_binary.erl), this module licensed under\n// 3-clause BSD found here: https://raw.githubusercontent.com/epgsql/epgsql/devel/LICENSE\nexport var PostgresTypes;\n(function (PostgresTypes) {\n    PostgresTypes[\"abstime\"] = \"abstime\";\n    PostgresTypes[\"bool\"] = \"bool\";\n    PostgresTypes[\"date\"] = \"date\";\n    PostgresTypes[\"daterange\"] = \"daterange\";\n    PostgresTypes[\"float4\"] = \"float4\";\n    PostgresTypes[\"float8\"] = \"float8\";\n    PostgresTypes[\"int2\"] = \"int2\";\n    PostgresTypes[\"int4\"] = \"int4\";\n    PostgresTypes[\"int4range\"] = \"int4range\";\n    PostgresTypes[\"int8\"] = \"int8\";\n    PostgresTypes[\"int8range\"] = \"int8range\";\n    PostgresTypes[\"json\"] = \"json\";\n    PostgresTypes[\"jsonb\"] = \"jsonb\";\n    PostgresTypes[\"money\"] = \"money\";\n    PostgresTypes[\"numeric\"] = \"numeric\";\n    PostgresTypes[\"oid\"] = \"oid\";\n    PostgresTypes[\"reltime\"] = \"reltime\";\n    PostgresTypes[\"text\"] = \"text\";\n    PostgresTypes[\"time\"] = \"time\";\n    PostgresTypes[\"timestamp\"] = \"timestamp\";\n    PostgresTypes[\"timestamptz\"] = \"timestamptz\";\n    PostgresTypes[\"timetz\"] = \"timetz\";\n    PostgresTypes[\"tsrange\"] = \"tsrange\";\n    PostgresTypes[\"tstzrange\"] = \"tstzrange\";\n})(PostgresTypes || (PostgresTypes = {}));\n/**\n * Takes an array of columns and an object of string values then converts each string value\n * to its mapped type.\n *\n * @param {{name: String, type: String}[]} columns\n * @param {Object} record\n * @param {Object} options The map of various options that can be applied to the mapper\n * @param {Array} options.skipTypes The array of types that should not be converted\n *\n * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {})\n * //=>{ first_name: 'Paul', age: 33 }\n */\nexport const convertChangeData = (columns, record, options = {}) => {\n    var _a;\n    const skipTypes = (_a = options.skipTypes) !== null && _a !== void 0 ? _a : [];\n    if (!record) {\n        return {};\n    }\n    return Object.keys(record).reduce((acc, rec_key) => {\n        acc[rec_key] = convertColumn(rec_key, columns, record, skipTypes);\n        return acc;\n    }, {});\n};\n/**\n * Converts the value of an individual column.\n *\n * @param {String} columnName The column that you want to convert\n * @param {{name: String, type: String}[]} columns All of the columns\n * @param {Object} record The map of string values\n * @param {Array} skipTypes An array of types that should not be converted\n * @return {object} Useless information\n *\n * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, [])\n * //=> 33\n * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4'])\n * //=> \"33\"\n */\nexport const convertColumn = (columnName, columns, record, skipTypes) => {\n    const column = columns.find((x) => x.name === columnName);\n    const colType = column === null || column === void 0 ? void 0 : column.type;\n    const value = record[columnName];\n    if (colType && !skipTypes.includes(colType)) {\n        return convertCell(colType, value);\n    }\n    return noop(value);\n};\n/**\n * If the value of the cell is `null`, returns null.\n * Otherwise converts the string value to the correct type.\n * @param {String} type A postgres column type\n * @param {String} value The cell value\n *\n * @example convertCell('bool', 't')\n * //=> true\n * @example convertCell('int8', '10')\n * //=> 10\n * @example convertCell('_int4', '{1,2,3,4}')\n * //=> [1,2,3,4]\n */\nexport const convertCell = (type, value) => {\n    // if data type is an array\n    if (type.charAt(0) === '_') {\n        const dataType = type.slice(1, type.length);\n        return toArray(value, dataType);\n    }\n    // If not null, convert to correct type.\n    switch (type) {\n        case PostgresTypes.bool:\n            return toBoolean(value);\n        case PostgresTypes.float4:\n        case PostgresTypes.float8:\n        case PostgresTypes.int2:\n        case PostgresTypes.int4:\n        case PostgresTypes.int8:\n        case PostgresTypes.numeric:\n        case PostgresTypes.oid:\n            return toNumber(value);\n        case PostgresTypes.json:\n        case PostgresTypes.jsonb:\n            return toJson(value);\n        case PostgresTypes.timestamp:\n            return toTimestampString(value); // Format to be consistent with PostgREST\n        case PostgresTypes.abstime: // To allow users to cast it based on Timezone\n        case PostgresTypes.date: // To allow users to cast it based on Timezone\n        case PostgresTypes.daterange:\n        case PostgresTypes.int4range:\n        case PostgresTypes.int8range:\n        case PostgresTypes.money:\n        case PostgresTypes.reltime: // To allow users to cast it based on Timezone\n        case PostgresTypes.text:\n        case PostgresTypes.time: // To allow users to cast it based on Timezone\n        case PostgresTypes.timestamptz: // To allow users to cast it based on Timezone\n        case PostgresTypes.timetz: // To allow users to cast it based on Timezone\n        case PostgresTypes.tsrange:\n        case PostgresTypes.tstzrange:\n            return noop(value);\n        default:\n            // Return the value for remaining types\n            return noop(value);\n    }\n};\nconst noop = (value) => {\n    return value;\n};\nexport const toBoolean = (value) => {\n    switch (value) {\n        case 't':\n            return true;\n        case 'f':\n            return false;\n        default:\n            return value;\n    }\n};\nexport const toNumber = (value) => {\n    if (typeof value === 'string') {\n        const parsedValue = parseFloat(value);\n        if (!Number.isNaN(parsedValue)) {\n            return parsedValue;\n        }\n    }\n    return value;\n};\nexport const toJson = (value) => {\n    if (typeof value === 'string') {\n        try {\n            return JSON.parse(value);\n        }\n        catch (_a) {\n            return value;\n        }\n    }\n    return value;\n};\n/**\n * Converts a Postgres Array into a native JS array\n *\n * @example toArray('{}', 'int4')\n * //=> []\n * @example toArray('{\"[2021-01-01,2021-12-31)\",\"(2021-01-01,2021-12-32]\"}', 'daterange')\n * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]']\n * @example toArray([1,2,3,4], 'int4')\n * //=> [1,2,3,4]\n */\nexport const toArray = (value, type) => {\n    if (typeof value !== 'string') {\n        return value;\n    }\n    const lastIdx = value.length - 1;\n    const closeBrace = value[lastIdx];\n    const openBrace = value[0];\n    // Confirm value is a Postgres array by checking curly brackets\n    if (openBrace === '{' && closeBrace === '}') {\n        let arr;\n        const valTrim = value.slice(1, lastIdx);\n        // TODO: find a better solution to separate Postgres array data\n        try {\n            arr = JSON.parse('[' + valTrim + ']');\n        }\n        catch (_) {\n            // WARNING: splitting on comma does not cover all edge cases\n            arr = valTrim ? valTrim.split(',') : [];\n        }\n        return arr.map((val) => convertCell(type, val));\n    }\n    return value;\n};\n/**\n * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T'\n * See https://github.com/supabase/supabase/issues/18\n *\n * @example toTimestampString('2019-09-10 00:00:00')\n * //=> '2019-09-10T00:00:00'\n */\nexport const toTimestampString = (value) => {\n    if (typeof value === 'string') {\n        return value.replace(' ', 'T');\n    }\n    return value;\n};\nexport const httpEndpointURL = (socketUrl) => {\n    const wsUrl = new URL(socketUrl);\n    wsUrl.protocol = wsUrl.protocol.replace(/^ws/i, 'http');\n    wsUrl.pathname = wsUrl.pathname\n        .replace(/\\/+$/, '') // remove all trailing slashes\n        .replace(/\\/socket\\/websocket$/i, '') // remove the socket/websocket path\n        .replace(/\\/socket$/i, '') // remove the socket path\n        .replace(/\\/websocket$/i, ''); // remove the websocket path\n    if (wsUrl.pathname === '' || wsUrl.pathname === '/') {\n        wsUrl.pathname = '/api/broadcast';\n    }\n    else {\n        wsUrl.pathname = wsUrl.pathname + '/api/broadcast';\n    }\n    return wsUrl.href;\n};\n//# sourceMappingURL=transformers.js.map","// js/phoenix/utils.js\nvar closure = (value) => {\n  if (typeof value === \"function\") {\n    return (\n      /** @type {() => T} */\n      value\n    );\n  } else {\n    let closure2 = function() {\n      return value;\n    };\n    return closure2;\n  }\n};\n\n// js/phoenix/constants.js\nvar globalSelf = typeof self !== \"undefined\" ? self : null;\nvar phxWindow = typeof window !== \"undefined\" ? window : null;\nvar global = globalSelf || phxWindow || globalThis;\nvar DEFAULT_VSN = \"2.0.0\";\nvar DEFAULT_TIMEOUT = 1e4;\nvar WS_CLOSE_NORMAL = 1e3;\nvar MAX_LONGPOLL_BATCH_SIZE = 100;\nvar SOCKET_STATES = (\n  /** @type {const} */\n  { connecting: 0, open: 1, closing: 2, closed: 3 }\n);\nvar CHANNEL_STATES = (\n  /** @type {const} */\n  {\n    closed: \"closed\",\n    errored: \"errored\",\n    joined: \"joined\",\n    joining: \"joining\",\n    leaving: \"leaving\"\n  }\n);\nvar CHANNEL_EVENTS = (\n  /** @type {const} */\n  {\n    close: \"phx_close\",\n    error: \"phx_error\",\n    join: \"phx_join\",\n    reply: \"phx_reply\",\n    leave: \"phx_leave\"\n  }\n);\nvar TRANSPORTS = (\n  /** @type {const} */\n  {\n    longpoll: \"longpoll\",\n    websocket: \"websocket\"\n  }\n);\nvar XHR_STATES = (\n  /** @type {const} */\n  {\n    complete: 4\n  }\n);\nvar AUTH_TOKEN_PREFIX = \"base64url.bearer.phx.\";\n\n// js/phoenix/push.js\nvar Push = class {\n  /**\n   * Initializes the Push\n   * @param {Channel} channel - The Channel\n   * @param {ChannelEvent} event - The event, for example `\"phx_join\"`\n   * @param {() => Record<string, unknown>} payload - The payload, for example `{user_id: 123}`\n   * @param {number} timeout - The push timeout in milliseconds\n   */\n  constructor(channel, event, payload, timeout) {\n    this.channel = channel;\n    this.event = event;\n    this.payload = payload || function() {\n      return {};\n    };\n    this.receivedResp = null;\n    this.timeout = timeout;\n    this.timeoutTimer = null;\n    this.recHooks = [];\n    this.sent = false;\n    this.ref = void 0;\n  }\n  /**\n   *\n   * @param {number} timeout\n   */\n  resend(timeout) {\n    this.timeout = timeout;\n    this.reset();\n    this.send();\n  }\n  /**\n   *\n   */\n  send() {\n    if (this.hasReceived(\"timeout\")) {\n      return;\n    }\n    this.startTimeout();\n    this.sent = true;\n    this.channel.socket.push({\n      topic: this.channel.topic,\n      event: this.event,\n      payload: this.payload(),\n      ref: this.ref,\n      join_ref: this.channel.joinRef()\n    });\n  }\n  /**\n   *\n   * @param {string} status\n   * @param {(response: any) => void} callback\n   */\n  receive(status, callback) {\n    if (this.hasReceived(status)) {\n      callback(this.receivedResp.response);\n    }\n    this.recHooks.push({ status, callback });\n    return this;\n  }\n  reset() {\n    this.cancelRefEvent();\n    this.ref = null;\n    this.refEvent = null;\n    this.receivedResp = null;\n    this.sent = false;\n  }\n  destroy() {\n    this.cancelRefEvent();\n    this.cancelTimeout();\n  }\n  /**\n   * @private\n   */\n  matchReceive({ status, response, _ref }) {\n    this.recHooks.filter((h) => h.status === status).forEach((h) => h.callback(response));\n  }\n  /**\n   * @private\n   */\n  cancelRefEvent() {\n    if (!this.refEvent) {\n      return;\n    }\n    this.channel.off(this.refEvent);\n  }\n  cancelTimeout() {\n    clearTimeout(this.timeoutTimer);\n    this.timeoutTimer = null;\n  }\n  startTimeout() {\n    if (this.timeoutTimer) {\n      this.cancelTimeout();\n    }\n    this.ref = this.channel.socket.makeRef();\n    this.refEvent = this.channel.replyEventName(this.ref);\n    this.channel.on(this.refEvent, (payload) => {\n      this.cancelRefEvent();\n      this.cancelTimeout();\n      this.receivedResp = payload;\n      this.matchReceive(payload);\n    });\n    this.timeoutTimer = setTimeout(() => {\n      this.trigger(\"timeout\", {});\n    }, this.timeout);\n  }\n  /**\n   * @private\n   */\n  hasReceived(status) {\n    return this.receivedResp && this.receivedResp.status === status;\n  }\n  trigger(status, response) {\n    this.channel.trigger(this.refEvent, { status, response });\n  }\n};\n\n// js/phoenix/timer.js\nvar Timer = class {\n  /**\n  * @param {() => void} callback\n  * @param {(tries: number) => number} timerCalc\n  */\n  constructor(callback, timerCalc) {\n    this.callback = callback;\n    this.timerCalc = timerCalc;\n    this.timer = void 0;\n    this.tries = 0;\n  }\n  reset() {\n    this.tries = 0;\n    clearTimeout(this.timer);\n  }\n  /**\n   * Cancels any previous scheduleTimeout and schedules callback\n   */\n  scheduleTimeout() {\n    clearTimeout(this.timer);\n    this.timer = setTimeout(() => {\n      this.tries = this.tries + 1;\n      this.callback();\n    }, this.timerCalc(this.tries + 1));\n  }\n};\n\n// js/phoenix/channel.js\nvar Channel = class {\n  /**\n   * @param {string} topic\n   * @param {Params | (() => Params)} params\n   * @param {Socket} socket\n   */\n  constructor(topic, params, socket) {\n    this.state = CHANNEL_STATES.closed;\n    this.topic = topic;\n    this.params = closure(params || {});\n    this.socket = socket;\n    this.bindings = [];\n    this.bindingRef = 0;\n    this.timeout = this.socket.timeout;\n    this.joinedOnce = false;\n    this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout);\n    this.pushBuffer = [];\n    this.stateChangeRefs = [];\n    this.rejoinTimer = new Timer(() => {\n      if (this.socket.isConnected()) {\n        this.rejoin();\n      }\n    }, this.socket.rejoinAfterMs);\n    this.stateChangeRefs.push(this.socket.onError(() => this.rejoinTimer.reset()));\n    this.stateChangeRefs.push(\n      this.socket.onOpen(() => {\n        this.rejoinTimer.reset();\n        if (this.isErrored()) {\n          this.rejoin();\n        }\n      })\n    );\n    this.joinPush.receive(\"ok\", () => {\n      this.state = CHANNEL_STATES.joined;\n      this.rejoinTimer.reset();\n      this.pushBuffer.forEach((pushEvent) => pushEvent.send());\n      this.pushBuffer = [];\n    });\n    this.joinPush.receive(\"error\", (reason) => {\n      this.state = CHANNEL_STATES.errored;\n      if (this.socket.hasLogger()) this.socket.log(\"channel\", `error ${this.topic}`, reason);\n      if (this.socket.isConnected()) {\n        this.rejoinTimer.scheduleTimeout();\n      }\n    });\n    this.onClose(() => {\n      this.rejoinTimer.reset();\n      if (this.socket.hasLogger()) this.socket.log(\"channel\", `close ${this.topic}`);\n      this.state = CHANNEL_STATES.closed;\n      this.socket.remove(this);\n    });\n    this.onError((reason) => {\n      if (this.socket.hasLogger()) this.socket.log(\"channel\", `error ${this.topic}`, reason);\n      if (this.isJoining()) {\n        this.joinPush.reset();\n      }\n      this.state = CHANNEL_STATES.errored;\n      if (this.socket.isConnected()) {\n        this.rejoinTimer.scheduleTimeout();\n      }\n    });\n    this.joinPush.receive(\"timeout\", () => {\n      if (this.socket.hasLogger()) this.socket.log(\"channel\", `timeout ${this.topic}`, this.joinPush.timeout);\n      let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), this.timeout);\n      leavePush.send();\n      this.state = CHANNEL_STATES.errored;\n      this.joinPush.reset();\n      if (this.socket.isConnected()) {\n        this.rejoinTimer.scheduleTimeout();\n      }\n    });\n    this.on(CHANNEL_EVENTS.reply, (payload, ref) => {\n      this.trigger(this.replyEventName(ref), payload);\n    });\n  }\n  /**\n   * Join the channel\n   * @param {number} timeout\n   * @returns {Push}\n   */\n  join(timeout = this.timeout) {\n    if (this.joinedOnce) {\n      throw new Error(\"tried to join multiple times. 'join' can only be called a single time per channel instance\");\n    } else {\n      this.timeout = timeout;\n      this.joinedOnce = true;\n      this.rejoin();\n      return this.joinPush;\n    }\n  }\n  /**\n   * Teardown the channel.\n   *\n   * Destroys and stops related timers.\n   */\n  teardown() {\n    this.pushBuffer.forEach((push) => push.destroy());\n    this.pushBuffer = [];\n    this.rejoinTimer.reset();\n    this.joinPush.destroy();\n    this.state = CHANNEL_STATES.closed;\n    this.bindings = [];\n  }\n  /**\n   * Hook into channel close\n   * @param {ChannelBindingCallback} callback\n   */\n  onClose(callback) {\n    this.on(CHANNEL_EVENTS.close, callback);\n  }\n  /**\n   * Hook into channel errors\n   * @param {ChannelOnErrorCallback} callback\n   * @return {number}\n   */\n  onError(callback) {\n    return this.on(CHANNEL_EVENTS.error, (reason) => callback(reason));\n  }\n  /**\n   * Subscribes on channel events\n   *\n   * Subscription returns a ref counter, which can be used later to\n   * unsubscribe the exact event listener\n   *\n   * @example\n   * const ref1 = channel.on(\"event\", do_stuff)\n   * const ref2 = channel.on(\"event\", do_other_stuff)\n   * channel.off(\"event\", ref1)\n   * // Since unsubscription, do_stuff won't fire,\n   * // while do_other_stuff will keep firing on the \"event\"\n   *\n   * @param {string} event\n   * @param {ChannelBindingCallback} callback\n   * @returns {number} ref\n   */\n  on(event, callback) {\n    let ref = this.bindingRef++;\n    this.bindings.push({ event, ref, callback });\n    return ref;\n  }\n  /**\n   * Unsubscribes off of channel events\n   *\n   * Use the ref returned from a channel.on() to unsubscribe one\n   * handler, or pass nothing for the ref to unsubscribe all\n   * handlers for the given event.\n   *\n   * @example\n   * // Unsubscribe the do_stuff handler\n   * const ref1 = channel.on(\"event\", do_stuff)\n   * channel.off(\"event\", ref1)\n   *\n   * // Unsubscribe all handlers from event\n   * channel.off(\"event\")\n   *\n   * @param {string} event\n   * @param {number} [ref]\n   */\n  off(event, ref) {\n    this.bindings = this.bindings.filter((bind) => {\n      return !(bind.event === event && (typeof ref === \"undefined\" || ref === bind.ref));\n    });\n  }\n  /**\n   * @private\n   */\n  canPush() {\n    return this.socket.isConnected() && this.isJoined();\n  }\n  /**\n   * Sends a message `event` to phoenix with the payload `payload`.\n   * Phoenix receives this in the `handle_in(event, payload, socket)`\n   * function. if phoenix replies or it times out (default 10000ms),\n   * then optionally the reply can be received.\n   *\n   * @example\n   * channel.push(\"event\")\n   *   .receive(\"ok\", payload => console.log(\"phoenix replied:\", payload))\n   *   .receive(\"error\", err => console.log(\"phoenix errored\", err))\n   *   .receive(\"timeout\", () => console.log(\"timed out pushing\"))\n   * @param {string} event\n   * @param {Object} payload\n   * @param {number} [timeout]\n   * @returns {Push}\n   */\n  push(event, payload, timeout = this.timeout) {\n    payload = payload || {};\n    if (!this.joinedOnce) {\n      throw new Error(`tried to push '${event}' to '${this.topic}' before joining. Use channel.join() before pushing events`);\n    }\n    let pushEvent = new Push(this, event, function() {\n      return payload;\n    }, timeout);\n    if (this.canPush()) {\n      pushEvent.send();\n    } else {\n      pushEvent.startTimeout();\n      this.pushBuffer.push(pushEvent);\n    }\n    return pushEvent;\n  }\n  /** Leaves the channel\n   *\n   * Unsubscribes from server events, and\n   * instructs channel to terminate on server\n   *\n   * Triggers onClose() hooks\n   *\n   * To receive leave acknowledgements, use the `receive`\n   * hook to bind to the server ack, ie:\n   *\n   * @example\n   * channel.leave().receive(\"ok\", () => alert(\"left!\") )\n   *\n   * @param {number} timeout\n   * @returns {Push}\n   */\n  leave(timeout = this.timeout) {\n    this.rejoinTimer.reset();\n    this.joinPush.cancelTimeout();\n    this.state = CHANNEL_STATES.leaving;\n    let onClose = () => {\n      if (this.socket.hasLogger()) this.socket.log(\"channel\", `leave ${this.topic}`);\n      this.trigger(CHANNEL_EVENTS.close, \"leave\");\n    };\n    let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), timeout);\n    leavePush.receive(\"ok\", () => onClose()).receive(\"timeout\", () => onClose());\n    leavePush.send();\n    if (!this.canPush()) {\n      leavePush.trigger(\"ok\", {});\n    }\n    return leavePush;\n  }\n  /**\n   * Overridable message hook\n   *\n   * Receives all events for specialized message handling\n   * before dispatching to the channel callbacks.\n   *\n   * Must return the payload, modified or unmodified\n   * @type{ChannelOnMessage}\n   */\n  onMessage(_event, payload, _ref) {\n    return payload;\n  }\n  /**\n   * Overridable filter hook\n   *\n   * If this function returns `true`, `binding`'s callback will be called.\n   *\n   * @type{ChannelFilterBindings}\n   */\n  filterBindings(_binding, _payload, _ref) {\n    return true;\n  }\n  isMember(topic, event, payload, joinRef) {\n    if (this.topic !== topic) {\n      return false;\n    }\n    if (joinRef && joinRef !== this.joinRef()) {\n      if (this.socket.hasLogger()) this.socket.log(\"channel\", \"dropping outdated message\", { topic, event, payload, joinRef });\n      return false;\n    } else {\n      return true;\n    }\n  }\n  joinRef() {\n    return this.joinPush.ref;\n  }\n  /**\n   * @private\n   */\n  rejoin(timeout = this.timeout) {\n    if (this.isLeaving()) {\n      return;\n    }\n    this.socket.leaveOpenTopic(this.topic);\n    this.state = CHANNEL_STATES.joining;\n    this.joinPush.resend(timeout);\n  }\n  /**\n   * @param {string} event\n   * @param {unknown} [payload]\n   * @param {?string} [ref]\n   * @param {?string} [joinRef]\n   */\n  trigger(event, payload, ref, joinRef) {\n    let handledPayload = this.onMessage(event, payload, ref, joinRef);\n    if (payload && !handledPayload) {\n      throw new Error(\"channel onMessage callbacks must return the payload, modified or unmodified\");\n    }\n    let eventBindings = this.bindings.filter((bind) => bind.event === event && this.filterBindings(bind, payload, ref));\n    for (let i = 0; i < eventBindings.length; i++) {\n      let bind = eventBindings[i];\n      bind.callback(handledPayload, ref, joinRef || this.joinRef());\n    }\n  }\n  /**\n  * @param {string} ref\n  */\n  replyEventName(ref) {\n    return `chan_reply_${ref}`;\n  }\n  isClosed() {\n    return this.state === CHANNEL_STATES.closed;\n  }\n  isErrored() {\n    return this.state === CHANNEL_STATES.errored;\n  }\n  isJoined() {\n    return this.state === CHANNEL_STATES.joined;\n  }\n  isJoining() {\n    return this.state === CHANNEL_STATES.joining;\n  }\n  isLeaving() {\n    return this.state === CHANNEL_STATES.leaving;\n  }\n};\n\n// js/phoenix/ajax.js\nvar Ajax = class {\n  static request(method, endPoint, headers, body, timeout, ontimeout, callback) {\n    if (global.XDomainRequest) {\n      let req = new global.XDomainRequest();\n      return this.xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback);\n    } else if (global.XMLHttpRequest) {\n      let req = new global.XMLHttpRequest();\n      return this.xhrRequest(req, method, endPoint, headers, body, timeout, ontimeout, callback);\n    } else if (global.fetch && global.AbortController) {\n      return this.fetchRequest(method, endPoint, headers, body, timeout, ontimeout, callback);\n    } else {\n      throw new Error(\"No suitable XMLHttpRequest implementation found\");\n    }\n  }\n  static fetchRequest(method, endPoint, headers, body, timeout, ontimeout, callback) {\n    let options = {\n      method,\n      headers,\n      body\n    };\n    let controller = null;\n    if (timeout) {\n      controller = new AbortController();\n      const _timeoutId = setTimeout(() => controller.abort(), timeout);\n      options.signal = controller.signal;\n    }\n    global.fetch(endPoint, options).then((response) => response.text()).then((data) => this.parseJSON(data)).then((data) => callback && callback(data)).catch((err) => {\n      if (err.name === \"AbortError\" && ontimeout) {\n        ontimeout();\n      } else {\n        callback && callback(null);\n      }\n    });\n    return controller;\n  }\n  static xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback) {\n    req.timeout = timeout;\n    req.open(method, endPoint);\n    req.onload = () => {\n      let response = this.parseJSON(req.responseText);\n      callback && callback(response);\n    };\n    if (ontimeout) {\n      req.ontimeout = ontimeout;\n    }\n    req.onprogress = () => {\n    };\n    req.send(body);\n    return req;\n  }\n  static xhrRequest(req, method, endPoint, headers, body, timeout, ontimeout, callback) {\n    req.open(method, endPoint, true);\n    req.timeout = timeout;\n    for (let [key, value] of Object.entries(headers)) {\n      req.setRequestHeader(key, value);\n    }\n    req.onerror = () => callback && callback(null);\n    req.onreadystatechange = () => {\n      if (req.readyState === XHR_STATES.complete && callback) {\n        let response = this.parseJSON(req.responseText);\n        callback(response);\n      }\n    };\n    if (ontimeout) {\n      req.ontimeout = ontimeout;\n    }\n    req.send(body);\n    return req;\n  }\n  static parseJSON(resp) {\n    if (!resp || resp === \"\") {\n      return null;\n    }\n    try {\n      return JSON.parse(resp);\n    } catch {\n      console && console.log(\"failed to parse JSON response\", resp);\n      return null;\n    }\n  }\n  static serialize(obj, parentKey) {\n    let queryStr = [];\n    for (var key in obj) {\n      if (!Object.prototype.hasOwnProperty.call(obj, key)) {\n        continue;\n      }\n      let paramKey = parentKey ? `${parentKey}[${key}]` : key;\n      let paramVal = obj[key];\n      if (typeof paramVal === \"object\") {\n        queryStr.push(this.serialize(paramVal, paramKey));\n      } else {\n        queryStr.push(encodeURIComponent(paramKey) + \"=\" + encodeURIComponent(paramVal));\n      }\n    }\n    return queryStr.join(\"&\");\n  }\n  static appendParams(url, params) {\n    if (Object.keys(params).length === 0) {\n      return url;\n    }\n    let prefix = url.match(/\\?/) ? \"&\" : \"?\";\n    return `${url}${prefix}${this.serialize(params)}`;\n  }\n};\n\n// js/phoenix/longpoll.js\nvar arrayBufferToBase64 = (buffer) => {\n  let binary = \"\";\n  let bytes = new Uint8Array(buffer);\n  let len = bytes.byteLength;\n  for (let i = 0; i < len; i++) {\n    binary += String.fromCharCode(bytes[i]);\n  }\n  return btoa(binary);\n};\nvar LongPoll = class {\n  constructor(endPoint, protocols) {\n    if (protocols && protocols.length === 2 && protocols[1].startsWith(AUTH_TOKEN_PREFIX)) {\n      this.authToken = atob(protocols[1].slice(AUTH_TOKEN_PREFIX.length));\n    }\n    this.endPoint = null;\n    this.token = null;\n    this.skipHeartbeat = true;\n    this.reqs = /* @__PURE__ */ new Set();\n    this.awaitingBatchAck = false;\n    this.currentBatch = null;\n    this.currentBatchTimer = null;\n    this.batchBuffer = [];\n    this.onopen = function() {\n    };\n    this.onerror = function() {\n    };\n    this.onmessage = function() {\n    };\n    this.onclose = function() {\n    };\n    this.pollEndpoint = this.normalizeEndpoint(endPoint);\n    this.readyState = SOCKET_STATES.connecting;\n    setTimeout(() => this.poll(), 0);\n  }\n  normalizeEndpoint(endPoint) {\n    return endPoint.replace(\"ws://\", \"http://\").replace(\"wss://\", \"https://\").replace(new RegExp(\"(.*)/\" + TRANSPORTS.websocket), \"$1/\" + TRANSPORTS.longpoll);\n  }\n  endpointURL() {\n    return Ajax.appendParams(this.pollEndpoint, { token: this.token });\n  }\n  closeAndRetry(code, reason, wasClean) {\n    this.close(code, reason, wasClean);\n    this.readyState = SOCKET_STATES.connecting;\n  }\n  ontimeout() {\n    this.onerror(\"timeout\");\n    this.closeAndRetry(1005, \"timeout\", false);\n  }\n  isActive() {\n    return this.readyState === SOCKET_STATES.open || this.readyState === SOCKET_STATES.connecting;\n  }\n  poll() {\n    const headers = { \"Accept\": \"application/json\" };\n    if (this.authToken) {\n      headers[\"X-Phoenix-AuthToken\"] = this.authToken;\n    }\n    this.ajax(\"GET\", headers, null, () => this.ontimeout(), (resp) => {\n      if (resp) {\n        var { status, token, messages } = resp;\n        if (status === 410 && this.token !== null) {\n          this.onerror(410);\n          this.closeAndRetry(3410, \"session_gone\", false);\n          return;\n        }\n        this.token = token;\n      } else {\n        status = 0;\n      }\n      switch (status) {\n        case 200:\n          messages.forEach((msg) => {\n            setTimeout(() => this.onmessage({ data: msg }), 0);\n          });\n          this.poll();\n          break;\n        case 204:\n          this.poll();\n          break;\n        case 410:\n          this.readyState = SOCKET_STATES.open;\n          this.onopen({});\n          this.poll();\n          break;\n        case 403:\n          this.onerror(403);\n          this.close(1008, \"forbidden\", false);\n          break;\n        case 0:\n        case 500:\n          this.onerror(500);\n          this.closeAndRetry(1011, \"internal server error\", 500);\n          break;\n        default:\n          throw new Error(`unhandled poll status ${status}`);\n      }\n    });\n  }\n  // we collect all pushes within the current event loop by\n  // setTimeout 0, which optimizes back-to-back procedural\n  // pushes against an empty buffer\n  send(body) {\n    if (typeof body !== \"string\") {\n      body = arrayBufferToBase64(body);\n    }\n    if (this.currentBatch) {\n      this.currentBatch.push(body);\n    } else if (this.awaitingBatchAck) {\n      this.batchBuffer.push(body);\n    } else {\n      this.currentBatch = [body];\n      this.currentBatchTimer = setTimeout(() => {\n        this.batchSend(this.currentBatch);\n        this.currentBatch = null;\n      }, 0);\n    }\n  }\n  batchSend(messages, offset = 0) {\n    this.awaitingBatchAck = true;\n    const next = offset + MAX_LONGPOLL_BATCH_SIZE;\n    const batch = messages.slice(offset, next);\n    this.ajax(\"POST\", { \"Content-Type\": \"application/x-ndjson\" }, batch.join(\"\\n\"), () => this.onerror(\"timeout\"), (resp) => {\n      if (!resp || resp.status !== 200) {\n        this.awaitingBatchAck = false;\n        this.onerror(resp && resp.status);\n        this.closeAndRetry(1011, \"internal server error\", false);\n      } else if (next < messages.length) {\n        this.batchSend(messages, next);\n      } else if (this.batchBuffer.length > 0) {\n        this.batchSend(this.batchBuffer);\n        this.batchBuffer = [];\n      } else {\n        this.awaitingBatchAck = false;\n      }\n    });\n  }\n  close(code, reason, wasClean) {\n    for (let req of this.reqs) {\n      req.abort();\n    }\n    this.readyState = SOCKET_STATES.closed;\n    let opts = Object.assign({ code: 1e3, reason: void 0, wasClean: true }, { code, reason, wasClean });\n    this.batchBuffer = [];\n    clearTimeout(this.currentBatchTimer);\n    this.currentBatchTimer = null;\n    if (typeof CloseEvent !== \"undefined\") {\n      this.onclose(new CloseEvent(\"close\", opts));\n    } else {\n      this.onclose(opts);\n    }\n  }\n  ajax(method, headers, body, onCallerTimeout, callback) {\n    let req;\n    let ontimeout = () => {\n      this.reqs.delete(req);\n      onCallerTimeout();\n    };\n    req = Ajax.request(method, this.endpointURL(), headers, body, this.timeout, ontimeout, (resp) => {\n      this.reqs.delete(req);\n      if (this.isActive()) {\n        callback(resp);\n      }\n    });\n    this.reqs.add(req);\n  }\n};\n\n// js/phoenix/presence.js\nvar Presence = class _Presence {\n  /**\n   * Initializes the Presence\n   * @param {Channel} channel - The Channel\n   * @param {PresenceOptions} [opts] - The options, for example `{events: {state: \"state\", diff: \"diff\"}}`\n   */\n  constructor(channel, opts = {}) {\n    let events = opts.events || /** @type {PresenceEvents} */\n    { state: \"presence_state\", diff: \"presence_diff\" };\n    this.state = /* @__PURE__ */ Object.create(null);\n    this.pendingDiffs = [];\n    this.channel = channel;\n    this.joinRef = null;\n    this.caller = {\n      onJoin: function() {\n      },\n      onLeave: function() {\n      },\n      onSync: function() {\n      }\n    };\n    this.channel.on(events.state, (newState) => {\n      let { onJoin, onLeave, onSync } = this.caller;\n      this.joinRef = this.channel.joinRef();\n      this.state = _Presence.syncState(this.state, newState, onJoin, onLeave);\n      this.pendingDiffs.forEach((diff) => {\n        this.state = _Presence.syncDiff(this.state, diff, onJoin, onLeave);\n      });\n      this.pendingDiffs = [];\n      onSync();\n    });\n    this.channel.on(events.diff, (diff) => {\n      let { onJoin, onLeave, onSync } = this.caller;\n      if (this.inPendingSyncState()) {\n        this.pendingDiffs.push(diff);\n      } else {\n        this.state = _Presence.syncDiff(this.state, diff, onJoin, onLeave);\n        onSync();\n      }\n    });\n  }\n  /**\n   * @param {PresenceOnJoin} callback\n   */\n  onJoin(callback) {\n    this.caller.onJoin = callback;\n  }\n  /**\n   * @param {PresenceOnLeave} callback\n   */\n  onLeave(callback) {\n    this.caller.onLeave = callback;\n  }\n  /**\n   * @param {PresenceOnSync} callback\n   */\n  onSync(callback) {\n    this.caller.onSync = callback;\n  }\n  /**\n   * Returns the array of presences, with selected metadata.\n   *\n   * @template [T=PresenceState]\n   * @param {((key: string, obj: PresenceState) => T)} [by]\n   *\n   * @returns {T[]}\n   */\n  list(by) {\n    return _Presence.list(this.state, by);\n  }\n  inPendingSyncState() {\n    return !this.joinRef || this.joinRef !== this.channel.joinRef();\n  }\n  // lower-level public static API\n  /**\n   * Used to sync the list of presences on the server\n   * with the client's state. An optional `onJoin` and `onLeave` callback can\n   * be provided to react to changes in the client's local presences across\n   * disconnects and reconnects with the server.\n   *\n   * @param {Record<string, PresenceState>} currentState\n   * @param {Record<string, PresenceState>} newState\n   * @param {PresenceOnJoin} onJoin\n   * @param {PresenceOnLeave} onLeave\n   *\n   * @returns {Record<string, PresenceState>}\n   */\n  static syncState(currentState, newState, onJoin, onLeave) {\n    let state = this.toNullProtoObj(this.clone(currentState));\n    newState = this.toNullProtoObj(newState);\n    let joins = /* @__PURE__ */ Object.create(null);\n    let leaves = /* @__PURE__ */ Object.create(null);\n    this.map(state, (key, presence) => {\n      if (!newState[key]) {\n        leaves[key] = presence;\n      }\n    });\n    this.map(newState, (key, newPresence) => {\n      let currentPresence = state[key];\n      if (currentPresence) {\n        let newRefs = newPresence.metas.map((m) => m.phx_ref);\n        let curRefs = currentPresence.metas.map((m) => m.phx_ref);\n        let joinedMetas = newPresence.metas.filter((m) => curRefs.indexOf(m.phx_ref) < 0);\n        let leftMetas = currentPresence.metas.filter((m) => newRefs.indexOf(m.phx_ref) < 0);\n        if (joinedMetas.length > 0) {\n          joins[key] = newPresence;\n          joins[key].metas = joinedMetas;\n        }\n        if (leftMetas.length > 0) {\n          leaves[key] = this.clone(currentPresence);\n          leaves[key].metas = leftMetas;\n        }\n      } else {\n        joins[key] = newPresence;\n      }\n    });\n    return this.syncDiff(state, { joins, leaves }, onJoin, onLeave);\n  }\n  /**\n   *\n   * Used to sync a diff of presence join and leave\n   * events from the server, as they happen. Like `syncState`, `syncDiff`\n   * accepts optional `onJoin` and `onLeave` callbacks to react to a user\n   * joining or leaving from a device.\n   *\n   * @param {Record<string, PresenceState>} state\n   * @param {PresenceDiff} diff\n   * @param {PresenceOnJoin} onJoin\n   * @param {PresenceOnLeave} onLeave\n   *\n   * @returns {Record<string, PresenceState>}\n   */\n  static syncDiff(state, diff, onJoin, onLeave) {\n    state = this.toNullProtoObj(state);\n    let { joins, leaves } = this.clone(diff);\n    if (!onJoin) {\n      onJoin = function() {\n      };\n    }\n    if (!onLeave) {\n      onLeave = function() {\n      };\n    }\n    this.map(joins, (key, newPresence) => {\n      let currentPresence = state[key];\n      state[key] = this.clone(newPresence);\n      if (currentPresence) {\n        let joinedRefs = state[key].metas.map((m) => m.phx_ref);\n        let curMetas = currentPresence.metas.filter((m) => joinedRefs.indexOf(m.phx_ref) < 0);\n        state[key].metas.unshift(...curMetas);\n      }\n      onJoin(key, currentPresence, newPresence);\n    });\n    this.map(leaves, (key, leftPresence) => {\n      let currentPresence = state[key];\n      if (!currentPresence) {\n        return;\n      }\n      let refsToRemove = leftPresence.metas.map((m) => m.phx_ref);\n      currentPresence.metas = currentPresence.metas.filter((p) => {\n        return refsToRemove.indexOf(p.phx_ref) < 0;\n      });\n      onLeave(key, currentPresence, leftPresence);\n      if (currentPresence.metas.length === 0) {\n        delete state[key];\n      }\n    });\n    return state;\n  }\n  /**\n   * Returns the array of presences, with selected metadata.\n   *\n   * @template [T=PresenceState]\n   * @param {Record<string, PresenceState>} presences\n   * @param {((key: string, obj: PresenceState) => T)} [chooser]\n   *\n   * @returns {T[]}\n   */\n  static list(presences, chooser) {\n    if (!chooser) {\n      chooser = function(key, pres) {\n        return pres;\n      };\n    }\n    return this.map(presences, (key, presence) => {\n      return chooser(key, presence);\n    });\n  }\n  // private\n  /**\n  * @template T\n  * @param {Record<string, PresenceState>} obj\n  * @param {(key: string, obj: PresenceState) => T} func\n  */\n  static map(obj, func) {\n    return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key]));\n  }\n  // Presence keys are chosen on the server and may collide with\n  // Object.prototype properties (\"__proto__\", \"constructor\", ...), so any\n  // object indexed by presence key must not have a prototype chain\n  //\n  // TODO: replace the null-prototype objects with Maps in Phoenix 2.0\n  // (breaking change for the lower-level static API)\n  static toNullProtoObj(obj) {\n    if (Object.getPrototypeOf(obj) === null) {\n      return obj;\n    }\n    let cleaned = /* @__PURE__ */ Object.create(null);\n    Object.getOwnPropertyNames(obj).forEach((key) => {\n      cleaned[key] = obj[key];\n    });\n    return cleaned;\n  }\n  /**\n  * @template T\n  * @param {T} obj\n  * @returns {T}\n  */\n  static clone(obj) {\n    return JSON.parse(JSON.stringify(obj));\n  }\n};\n\n// js/phoenix/serializer.js\nvar serializer_default = {\n  HEADER_LENGTH: 1,\n  META_LENGTH: 4,\n  KINDS: { push: 0, reply: 1, broadcast: 2 },\n  /**\n  * @template T\n  * @param {Message<Record<string, any>>} msg\n  * @param {(msg: ArrayBuffer | string) => T} callback\n  * @returns {T}\n  */\n  encode(msg, callback) {\n    if (msg.payload.constructor === ArrayBuffer) {\n      return callback(this.binaryEncode(msg));\n    } else {\n      let payload = [msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload];\n      return callback(JSON.stringify(payload));\n    }\n  },\n  /**\n  * @template T\n  * @param {ArrayBuffer | string} rawPayload\n  * @param {(msg: Message<unknown>) => T} callback\n  * @returns {T}\n  */\n  decode(rawPayload, callback) {\n    if (rawPayload.constructor === ArrayBuffer) {\n      return callback(this.binaryDecode(rawPayload));\n    } else {\n      let [join_ref, ref, topic, event, payload] = JSON.parse(rawPayload);\n      return callback({ join_ref, ref, topic, event, payload });\n    }\n  },\n  /** @private */\n  binaryEncode(message) {\n    let { join_ref, ref, event, topic, payload } = message;\n    let encoder = new TextEncoder();\n    let joinRefBytes = encoder.encode(join_ref);\n    let refBytes = encoder.encode(ref);\n    let topicBytes = encoder.encode(topic);\n    let eventBytes = encoder.encode(event);\n    this.assertFieldSize(joinRefBytes.byteLength, \"join_ref\");\n    this.assertFieldSize(refBytes.byteLength, \"ref\");\n    this.assertFieldSize(topicBytes.byteLength, \"topic\");\n    this.assertFieldSize(eventBytes.byteLength, \"event\");\n    let metaLength = this.META_LENGTH + joinRefBytes.byteLength + refBytes.byteLength + topicBytes.byteLength + eventBytes.byteLength;\n    let header = new ArrayBuffer(this.HEADER_LENGTH + metaLength);\n    let headerBytes = new Uint8Array(header);\n    let view = new DataView(header);\n    let offset = 0;\n    view.setUint8(offset++, this.KINDS.push);\n    view.setUint8(offset++, joinRefBytes.byteLength);\n    view.setUint8(offset++, refBytes.byteLength);\n    view.setUint8(offset++, topicBytes.byteLength);\n    view.setUint8(offset++, eventBytes.byteLength);\n    headerBytes.set(joinRefBytes, offset);\n    offset += joinRefBytes.byteLength;\n    headerBytes.set(refBytes, offset);\n    offset += refBytes.byteLength;\n    headerBytes.set(topicBytes, offset);\n    offset += topicBytes.byteLength;\n    headerBytes.set(eventBytes, offset);\n    offset += eventBytes.byteLength;\n    var combined = new Uint8Array(header.byteLength + payload.byteLength);\n    combined.set(headerBytes, 0);\n    combined.set(new Uint8Array(payload), header.byteLength);\n    return combined.buffer;\n  },\n  assertFieldSize(size, name) {\n    if (size > 255) {\n      throw new Error(`unable to convert ${name} to binary: must be less than or equal to 255 bytes, but is ${size} bytes`);\n    }\n  },\n  /**\n  * @private\n  */\n  binaryDecode(buffer) {\n    let view = new DataView(buffer);\n    let kind = view.getUint8(0);\n    let decoder = new TextDecoder();\n    switch (kind) {\n      case this.KINDS.push:\n        return this.decodePush(buffer, view, decoder);\n      case this.KINDS.reply:\n        return this.decodeReply(buffer, view, decoder);\n      case this.KINDS.broadcast:\n        return this.decodeBroadcast(buffer, view, decoder);\n    }\n  },\n  /** @private */\n  decodePush(buffer, view, decoder) {\n    let joinRefSize = view.getUint8(1);\n    let topicSize = view.getUint8(2);\n    let eventSize = view.getUint8(3);\n    let offset = this.HEADER_LENGTH + this.META_LENGTH - 1;\n    let joinRef = decoder.decode(buffer.slice(offset, offset + joinRefSize));\n    offset = offset + joinRefSize;\n    let topic = decoder.decode(buffer.slice(offset, offset + topicSize));\n    offset = offset + topicSize;\n    let event = decoder.decode(buffer.slice(offset, offset + eventSize));\n    offset = offset + eventSize;\n    let data = buffer.slice(offset, buffer.byteLength);\n    return { join_ref: joinRef, ref: null, topic, event, payload: data };\n  },\n  /** @private */\n  decodeReply(buffer, view, decoder) {\n    let joinRefSize = view.getUint8(1);\n    let refSize = view.getUint8(2);\n    let topicSize = view.getUint8(3);\n    let eventSize = view.getUint8(4);\n    let offset = this.HEADER_LENGTH + this.META_LENGTH;\n    let joinRef = decoder.decode(buffer.slice(offset, offset + joinRefSize));\n    offset = offset + joinRefSize;\n    let ref = decoder.decode(buffer.slice(offset, offset + refSize));\n    offset = offset + refSize;\n    let topic = decoder.decode(buffer.slice(offset, offset + topicSize));\n    offset = offset + topicSize;\n    let event = decoder.decode(buffer.slice(offset, offset + eventSize));\n    offset = offset + eventSize;\n    let data = buffer.slice(offset, buffer.byteLength);\n    let payload = { status: event, response: data };\n    return { join_ref: joinRef, ref, topic, event: CHANNEL_EVENTS.reply, payload };\n  },\n  /** @private */\n  decodeBroadcast(buffer, view, decoder) {\n    let topicSize = view.getUint8(1);\n    let eventSize = view.getUint8(2);\n    let offset = this.HEADER_LENGTH + 2;\n    let topic = decoder.decode(buffer.slice(offset, offset + topicSize));\n    offset = offset + topicSize;\n    let event = decoder.decode(buffer.slice(offset, offset + eventSize));\n    offset = offset + eventSize;\n    let data = buffer.slice(offset, buffer.byteLength);\n    return { join_ref: null, ref: null, topic, event, payload: data };\n  }\n};\n\n// js/phoenix/socket.js\nvar Socket = class {\n  /** Initializes the Socket *\n   *\n   * For IE8 support use an ES5-shim (https://github.com/es-shims/es5-shim)\n   *\n   * @constructor\n   * @param {string} endPoint - The string WebSocket endpoint, ie, `\"ws://example.com/socket\"`,\n   *                                               `\"wss://example.com\"`\n   *                                               `\"/socket\"` (inherited host & protocol)\n   * @param {SocketOptions} [opts] - Optional configuration\n   */\n  constructor(endPoint, opts = {}) {\n    this.stateChangeCallbacks = { open: [], close: [], error: [], message: [] };\n    this.channels = [];\n    this.sendBuffer = [];\n    this.ref = 0;\n    this.fallbackRef = null;\n    this.timeout = opts.timeout || DEFAULT_TIMEOUT;\n    this.transport = opts.transport || global.WebSocket || LongPoll;\n    this.conn = void 0;\n    this.primaryPassedHealthCheck = false;\n    this.longPollFallbackMs = opts.longPollFallbackMs;\n    this.fallbackTimer = null;\n    let envSessionStorage = null;\n    try {\n      envSessionStorage = global && global.sessionStorage;\n    } catch {\n    }\n    this.sessionStore = opts.sessionStorage || envSessionStorage;\n    this.establishedConnections = 0;\n    this.defaultEncoder = serializer_default.encode.bind(serializer_default);\n    this.defaultDecoder = serializer_default.decode.bind(serializer_default);\n    this.closeWasClean = true;\n    this.disconnecting = false;\n    this.binaryType = opts.binaryType || \"arraybuffer\";\n    this.connectClock = 1;\n    this.pageHidden = false;\n    this.encode = void 0;\n    this.decode = void 0;\n    if (this.transport !== LongPoll) {\n      this.encode = opts.encode || this.defaultEncoder;\n      this.decode = opts.decode || this.defaultDecoder;\n    } else {\n      this.encode = this.defaultEncoder;\n      this.decode = this.defaultDecoder;\n    }\n    let awaitingConnectionOnPageShow = null;\n    if (phxWindow && phxWindow.addEventListener) {\n      phxWindow.addEventListener(\"pagehide\", (_e) => {\n        if (this.conn) {\n          this.disconnect();\n          awaitingConnectionOnPageShow = this.connectClock;\n        }\n      });\n      phxWindow.addEventListener(\"pageshow\", (_e) => {\n        if (awaitingConnectionOnPageShow === this.connectClock) {\n          awaitingConnectionOnPageShow = null;\n          this.connect();\n        }\n      });\n      phxWindow.addEventListener(\"visibilitychange\", () => {\n        if (document.visibilityState === \"hidden\") {\n          this.pageHidden = true;\n        } else {\n          this.pageHidden = false;\n          if (!this.isConnected() && !this.closeWasClean) {\n            this.teardown(() => this.connect());\n          }\n        }\n      });\n    }\n    this.heartbeatIntervalMs = opts.heartbeatIntervalMs || 3e4;\n    this.autoSendHeartbeat = opts.autoSendHeartbeat ?? true;\n    this.heartbeatCallback = opts.heartbeatCallback ?? (() => {\n    });\n    this.rejoinAfterMs = (tries) => {\n      if (opts.rejoinAfterMs) {\n        return opts.rejoinAfterMs(tries);\n      } else {\n        return [1e3, 2e3, 5e3][tries - 1] || 1e4;\n      }\n    };\n    this.reconnectAfterMs = (tries) => {\n      if (opts.reconnectAfterMs) {\n        return opts.reconnectAfterMs(tries);\n      } else {\n        return [10, 50, 100, 150, 200, 250, 500, 1e3, 2e3][tries - 1] || 5e3;\n      }\n    };\n    this.logger = opts.logger || null;\n    if (!this.logger && opts.debug) {\n      this.logger = (kind, msg, data) => {\n        console.log(`${kind}: ${msg}`, data);\n      };\n    }\n    this.longpollerTimeout = opts.longpollerTimeout || 2e4;\n    this.params = closure(opts.params || {});\n    this.endPoint = `${endPoint}/${TRANSPORTS.websocket}`;\n    this.vsn = opts.vsn || DEFAULT_VSN;\n    this.heartbeatTimeoutTimer = null;\n    this.heartbeatTimer = null;\n    this.heartbeatSentAt = null;\n    this.pendingHeartbeatRef = null;\n    this.reconnectTimer = new Timer(() => {\n      if (this.pageHidden) {\n        this.log(\"Not reconnecting as page is hidden!\");\n        this.teardown();\n        return;\n      }\n      this.teardown(async () => {\n        if (opts.beforeReconnect) await opts.beforeReconnect();\n        this.connect();\n      });\n    }, this.reconnectAfterMs);\n    this.authToken = opts.authToken && closure(opts.authToken);\n  }\n  /**\n   * Returns the LongPoll transport reference\n   */\n  getLongPollTransport() {\n    return LongPoll;\n  }\n  /**\n   * Disconnects and replaces the active transport\n   *\n   * @param {SocketTransport} newTransport - The new transport class to instantiate\n   *\n   */\n  replaceTransport(newTransport) {\n    this.connectClock++;\n    this.closeWasClean = true;\n    clearTimeout(this.fallbackTimer);\n    this.reconnectTimer.reset();\n    if (this.conn) {\n      this.conn.close();\n      this.conn = null;\n    }\n    this.transport = newTransport;\n  }\n  /**\n   * Returns the socket protocol\n   *\n   * @returns {\"wss\" | \"ws\"}\n   */\n  protocol() {\n    return location.protocol.match(/^https/) ? \"wss\" : \"ws\";\n  }\n  /**\n   * The fully qualified socket url\n   *\n   * @returns {string}\n   */\n  endPointURL() {\n    let uri = Ajax.appendParams(\n      Ajax.appendParams(this.endPoint, this.params()),\n      { vsn: this.vsn }\n    );\n    if (uri.charAt(0) !== \"/\") {\n      return uri;\n    }\n    if (uri.charAt(1) === \"/\") {\n      return `${this.protocol()}:${uri}`;\n    }\n    return `${this.protocol()}://${location.host}${uri}`;\n  }\n  /**\n   * Disconnects the socket\n   *\n   * See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes for valid status codes.\n   *\n   * @param {() => void} [callback] - Optional callback which is called after socket is disconnected.\n   * @param {number} [code] - A status code for disconnection (Optional).\n   * @param {string} [reason] - A textual description of the reason to disconnect. (Optional)\n   */\n  disconnect(callback, code, reason) {\n    this.connectClock++;\n    this.disconnecting = true;\n    this.closeWasClean = true;\n    clearTimeout(this.fallbackTimer);\n    this.reconnectTimer.reset();\n    this.teardown(() => {\n      this.disconnecting = false;\n      callback && callback();\n    }, code, reason);\n  }\n  /**\n   * @param {Params} [params] - [DEPRECATED] The params to send when connecting, for example `{user_id: userToken}`\n   *\n   * Passing params to connect is deprecated; pass them in the Socket constructor instead:\n   * `new Socket(\"/socket\", {params: {user_id: userToken}})`.\n   */\n  connect(params) {\n    if (params) {\n      console && console.log(\"passing params to connect is deprecated. Instead pass :params to the Socket constructor\");\n      this.params = closure(params);\n    }\n    if (this.conn && !this.disconnecting) {\n      return;\n    }\n    if (this.longPollFallbackMs && this.transport !== LongPoll) {\n      this.connectWithFallback(LongPoll, this.longPollFallbackMs);\n    } else {\n      this.transportConnect();\n    }\n  }\n  /**\n   * Logs the message. Override `this.logger` for specialized logging. noops by default\n   * @param {string} kind\n   * @param {string} msg\n   * @param {Object} data\n   */\n  log(kind, msg, data) {\n    this.logger && this.logger(kind, msg, data);\n  }\n  /**\n   * Returns true if a logger has been set on this socket.\n   */\n  hasLogger() {\n    return this.logger !== null;\n  }\n  /**\n   * Registers callbacks for connection open events\n   *\n   * @example socket.onOpen(function(){ console.info(\"the socket was opened\") })\n   *\n   * @param {SocketOnOpen} callback\n   */\n  onOpen(callback) {\n    let ref = this.makeRef();\n    this.stateChangeCallbacks.open.push([ref, callback]);\n    return ref;\n  }\n  /**\n   * Registers callbacks for connection close events\n   * @param {SocketOnClose} callback\n   * @returns {string}\n   */\n  onClose(callback) {\n    let ref = this.makeRef();\n    this.stateChangeCallbacks.close.push([ref, callback]);\n    return ref;\n  }\n  /**\n   * Registers callbacks for connection error events\n   *\n   * @example socket.onError(function(error){ alert(\"An error occurred\") })\n   *\n   * @param {SocketOnError} callback\n   * @returns {string}\n   */\n  onError(callback) {\n    let ref = this.makeRef();\n    this.stateChangeCallbacks.error.push([ref, callback]);\n    return ref;\n  }\n  /**\n   * Registers callbacks for connection message events\n   * @param {SocketOnMessage} callback\n   * @returns {string}\n   */\n  onMessage(callback) {\n    let ref = this.makeRef();\n    this.stateChangeCallbacks.message.push([ref, callback]);\n    return ref;\n  }\n  /**\n   * Sets a callback that receives lifecycle events for internal heartbeat messages.\n   * Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected).\n   * @param {HeartbeatCallback} callback\n   */\n  onHeartbeat(callback) {\n    this.heartbeatCallback = callback;\n  }\n  /**\n   * Pings the server and invokes the callback with the RTT in milliseconds\n   * @param {(timeDelta: number) => void} callback\n   *\n   * Returns true if the ping was pushed or false if unable to be pushed.\n   */\n  ping(callback) {\n    if (!this.isConnected()) {\n      return false;\n    }\n    let ref = this.makeRef();\n    let startTime = Date.now();\n    this.push({ topic: \"phoenix\", event: \"heartbeat\", payload: {}, ref });\n    let onMsgRef = this.onMessage((msg) => {\n      if (msg.ref === ref) {\n        this.off([onMsgRef]);\n        callback(Date.now() - startTime);\n      }\n    });\n    return true;\n  }\n  /**\n   * @private\n   *\n   * @param {Function}\n   */\n  transportName(transport) {\n    switch (transport) {\n      case LongPoll:\n        return \"LongPoll\";\n      default:\n        return transport.name;\n    }\n  }\n  /**\n   * @private\n   */\n  transportConnect() {\n    this.connectClock++;\n    this.closeWasClean = false;\n    let protocols = void 0;\n    if (this.authToken) {\n      protocols = [\"phoenix\", `${AUTH_TOKEN_PREFIX}${btoa(this.authToken()).replace(/=/g, \"\")}`];\n    }\n    this.conn = new this.transport(this.endPointURL(), protocols);\n    this.conn.binaryType = this.binaryType;\n    this.conn.timeout = this.longpollerTimeout;\n    this.conn.onopen = () => this.onConnOpen();\n    this.conn.onerror = (error) => this.onConnError(error);\n    this.conn.onmessage = (event) => this.onConnMessage(event);\n    this.conn.onclose = (event) => this.onConnClose(event);\n  }\n  getSession(key) {\n    return this.sessionStore && this.sessionStore.getItem(key);\n  }\n  storeSession(key, val) {\n    this.sessionStore && this.sessionStore.setItem(key, val);\n  }\n  connectWithFallback(fallbackTransport, fallbackThreshold = 2500) {\n    clearTimeout(this.fallbackTimer);\n    let established = false;\n    let primaryTransport = true;\n    let openRef, errorRef;\n    let fallbackTransportName = this.transportName(fallbackTransport);\n    let fallback = (reason) => {\n      this.log(\"transport\", `falling back to ${fallbackTransportName}...`, reason);\n      this.off([openRef, errorRef]);\n      primaryTransport = false;\n      this.replaceTransport(fallbackTransport);\n      this.transportConnect();\n    };\n    if (this.getSession(`phx:fallback:${fallbackTransportName}`)) {\n      return fallback(\"memorized\");\n    }\n    this.fallbackTimer = setTimeout(fallback, fallbackThreshold);\n    errorRef = this.onError((reason) => {\n      this.log(\"transport\", \"error\", reason);\n      if (primaryTransport && !established) {\n        clearTimeout(this.fallbackTimer);\n        fallback(reason);\n      }\n    });\n    if (this.fallbackRef) {\n      this.off([this.fallbackRef]);\n    }\n    this.fallbackRef = this.onOpen(() => {\n      established = true;\n      if (!primaryTransport) {\n        let fallbackTransportName2 = this.transportName(fallbackTransport);\n        if (!this.primaryPassedHealthCheck) {\n          this.storeSession(`phx:fallback:${fallbackTransportName2}`, \"true\");\n        }\n        return this.log(\"transport\", `established ${fallbackTransportName2} fallback`);\n      }\n      clearTimeout(this.fallbackTimer);\n      this.fallbackTimer = setTimeout(fallback, fallbackThreshold);\n      this.ping((rtt) => {\n        this.log(\"transport\", \"connected to primary after\", rtt);\n        this.primaryPassedHealthCheck = true;\n        clearTimeout(this.fallbackTimer);\n      });\n    });\n    this.transportConnect();\n  }\n  clearHeartbeats() {\n    clearTimeout(this.heartbeatTimer);\n    clearTimeout(this.heartbeatTimeoutTimer);\n  }\n  onConnOpen() {\n    if (this.hasLogger()) this.log(\"transport\", `connected to ${this.endPointURL()}`);\n    this.closeWasClean = false;\n    this.disconnecting = false;\n    this.establishedConnections++;\n    this.flushSendBuffer();\n    this.reconnectTimer.reset();\n    if (this.autoSendHeartbeat) {\n      this.resetHeartbeat();\n    }\n    this.triggerStateCallbacks(\"open\");\n  }\n  /**\n   * @private\n   */\n  heartbeatTimeout() {\n    if (this.pendingHeartbeatRef) {\n      this.pendingHeartbeatRef = null;\n      this.heartbeatSentAt = null;\n      if (this.hasLogger()) {\n        this.log(\"transport\", \"heartbeat timeout. Attempting to re-establish connection\");\n      }\n      try {\n        this.heartbeatCallback(\"timeout\");\n      } catch (e) {\n        this.log(\"error\", \"error in heartbeat callback\", e);\n      }\n      this.triggerChanError(new Error(\"heartbeat timeout\"));\n      this.closeWasClean = false;\n      this.teardown(() => this.reconnectTimer.scheduleTimeout(), WS_CLOSE_NORMAL, \"heartbeat timeout\");\n    }\n  }\n  resetHeartbeat() {\n    if (this.conn && this.conn.skipHeartbeat) {\n      return;\n    }\n    this.pendingHeartbeatRef = null;\n    this.clearHeartbeats();\n    this.heartbeatTimer = setTimeout(() => this.sendHeartbeat(), this.heartbeatIntervalMs);\n  }\n  teardown(callback, code, reason) {\n    if (!this.conn) {\n      return callback && callback();\n    }\n    const connToClose = this.conn;\n    this.waitForBufferDone(connToClose, () => {\n      if (code) {\n        connToClose.close(code, reason || \"\");\n      } else {\n        connToClose.close();\n      }\n      this.waitForSocketClosed(connToClose, () => {\n        if (this.conn === connToClose) {\n          this.conn.onopen = function() {\n          };\n          this.conn.onerror = function() {\n          };\n          this.conn.onmessage = function() {\n          };\n          this.conn.onclose = function() {\n          };\n          this.conn = null;\n        }\n        callback && callback();\n      });\n    });\n  }\n  waitForBufferDone(conn, callback, tries = 1) {\n    if (tries === 5 || !conn.bufferedAmount) {\n      callback();\n      return;\n    }\n    setTimeout(() => {\n      this.waitForBufferDone(conn, callback, tries + 1);\n    }, 150 * tries);\n  }\n  waitForSocketClosed(conn, callback, tries = 1) {\n    if (tries === 5 || conn.readyState === SOCKET_STATES.closed) {\n      callback();\n      return;\n    }\n    setTimeout(() => {\n      this.waitForSocketClosed(conn, callback, tries + 1);\n    }, 150 * tries);\n  }\n  /**\n  * @param {CloseEvent} event\n  */\n  onConnClose(event) {\n    if (this.conn) this.conn.onclose = () => {\n    };\n    if (this.hasLogger()) this.log(\"transport\", \"close\", event);\n    this.triggerChanError(event);\n    this.clearHeartbeats();\n    if (!this.closeWasClean) {\n      this.reconnectTimer.scheduleTimeout();\n    }\n    this.triggerStateCallbacks(\"close\", event);\n  }\n  /**\n   * @private\n   * @param {Event} error\n   */\n  onConnError(error) {\n    if (this.hasLogger()) this.log(\"transport\", \"error\", error);\n    let transportBefore = this.transport;\n    let establishedBefore = this.establishedConnections;\n    this.triggerStateCallbacks(\"error\", error, transportBefore, establishedBefore);\n    if (transportBefore === this.transport || establishedBefore > 0) {\n      this.triggerChanError(error);\n    }\n  }\n  /**\n   * @private\n   * @param {unknown} [reason] underlying close/error event forwarded to channel error listeners\n   */\n  triggerChanError(reason) {\n    this.channels.forEach((channel) => {\n      if (!(channel.isErrored() || channel.isLeaving() || channel.isClosed())) {\n        channel.trigger(CHANNEL_EVENTS.error, reason);\n      }\n    });\n  }\n  /**\n   * @returns {string}\n   */\n  connectionState() {\n    switch (this.conn && this.conn.readyState) {\n      case SOCKET_STATES.connecting:\n        return \"connecting\";\n      case SOCKET_STATES.open:\n        return \"open\";\n      case SOCKET_STATES.closing:\n        return \"closing\";\n      default:\n        return \"closed\";\n    }\n  }\n  /**\n   * @returns {boolean}\n   */\n  isConnected() {\n    return this.connectionState() === \"open\";\n  }\n  /**\n   *\n   * @param {Channel} channel\n   */\n  remove(channel) {\n    this.off(channel.stateChangeRefs);\n    this.channels = this.channels.filter((c) => c !== channel);\n  }\n  /**\n   * Removes `onOpen`, `onClose`, `onError,` and `onMessage` registrations.\n   *\n   * @param {string[]} refs - list of refs returned by calls to\n   *                 `onOpen`, `onClose`, `onError,` and `onMessage`\n   */\n  off(refs) {\n    for (let key in this.stateChangeCallbacks) {\n      this.stateChangeCallbacks[key] = this.stateChangeCallbacks[key].filter(([ref]) => {\n        return refs.indexOf(ref) === -1;\n      });\n    }\n  }\n  /**\n   * Initiates a new channel for the given topic\n   *\n   * @param {string} topic\n   * @param {Params | (() => Params)} [chanParams]- Parameters for the channel\n   * @returns {Channel}\n   */\n  channel(topic, chanParams = {}) {\n    let chan = new Channel(topic, chanParams, this);\n    this.channels.push(chan);\n    return chan;\n  }\n  /**\n   * @param {Message<Record<string, any>>} data\n   */\n  push(data) {\n    if (this.hasLogger()) {\n      let { topic, event, payload, ref, join_ref } = data;\n      this.log(\"push\", `${topic} ${event} (${join_ref}, ${ref})`, payload);\n    }\n    if (this.isConnected()) {\n      this.encode(data, (result) => this.conn.send(result));\n    } else {\n      this.sendBuffer.push(() => this.encode(data, (result) => this.conn.send(result)));\n    }\n  }\n  /**\n   * Return the next message ref, accounting for overflows\n   * @returns {string}\n   */\n  makeRef() {\n    let newRef = this.ref + 1;\n    if (newRef === this.ref) {\n      this.ref = 0;\n    } else {\n      this.ref = newRef;\n    }\n    return this.ref.toString();\n  }\n  sendHeartbeat() {\n    if (!this.isConnected()) {\n      try {\n        this.heartbeatCallback(\"disconnected\");\n      } catch (e) {\n        this.log(\"error\", \"error in heartbeat callback\", e);\n      }\n      return;\n    }\n    if (this.pendingHeartbeatRef) {\n      this.heartbeatTimeout();\n      return;\n    }\n    this.pendingHeartbeatRef = this.makeRef();\n    this.heartbeatSentAt = Date.now();\n    this.push({ topic: \"phoenix\", event: \"heartbeat\", payload: {}, ref: this.pendingHeartbeatRef });\n    try {\n      this.heartbeatCallback(\"sent\");\n    } catch (e) {\n      this.log(\"error\", \"error in heartbeat callback\", e);\n    }\n    this.heartbeatTimeoutTimer = setTimeout(() => this.heartbeatTimeout(), this.heartbeatIntervalMs);\n  }\n  flushSendBuffer() {\n    if (this.isConnected() && this.sendBuffer.length > 0) {\n      this.sendBuffer.forEach((callback) => callback());\n      this.sendBuffer = [];\n    }\n  }\n  /**\n  * @param {MessageEvent<any>} rawMessage\n  */\n  onConnMessage(rawMessage) {\n    this.decode(rawMessage.data, (msg) => {\n      let { topic, event, payload, ref, join_ref } = msg;\n      if (ref && ref === this.pendingHeartbeatRef) {\n        const latency = this.heartbeatSentAt ? Date.now() - this.heartbeatSentAt : void 0;\n        this.clearHeartbeats();\n        try {\n          this.heartbeatCallback(payload.status === \"ok\" ? \"ok\" : \"error\", latency);\n        } catch (e) {\n          this.log(\"error\", \"error in heartbeat callback\", e);\n        }\n        this.pendingHeartbeatRef = null;\n        this.heartbeatSentAt = null;\n        if (this.autoSendHeartbeat) {\n          this.heartbeatTimer = setTimeout(() => this.sendHeartbeat(), this.heartbeatIntervalMs);\n        }\n      }\n      if (this.hasLogger()) this.log(\"receive\", `${payload.status || \"\"} ${topic} ${event} ${ref && \"(\" + ref + \")\" || \"\"}`.trim(), payload);\n      for (let i = 0; i < this.channels.length; i++) {\n        const channel = this.channels[i];\n        if (!channel.isMember(topic, event, payload, join_ref)) {\n          continue;\n        }\n        channel.trigger(event, payload, ref, join_ref);\n      }\n      this.triggerStateCallbacks(\"message\", msg);\n    });\n  }\n  /**\n   * @private\n   * @template {keyof SocketStateChangeCallbacks} K\n   * @param {K} event\n   * @param {...Parameters<SocketStateChangeCallbacks[K][number][1]>} args\n   * @returns {void}\n   */\n  triggerStateCallbacks(event, ...args) {\n    try {\n      this.stateChangeCallbacks[event].forEach(([_, callback]) => {\n        try {\n          callback(...args);\n        } catch (e) {\n          this.log(\"error\", `error in ${event} callback`, e);\n        }\n      });\n    } catch (e) {\n      this.log(\"error\", `error triggering ${event} callbacks`, e);\n    }\n  }\n  leaveOpenTopic(topic) {\n    let dupChannel = this.channels.find((c) => c.topic === topic && (c.isJoined() || c.isJoining()));\n    if (dupChannel) {\n      if (this.hasLogger()) this.log(\"transport\", `leaving duplicate topic \"${topic}\"`);\n      dupChannel.leave();\n    }\n  }\n};\nexport {\n  Channel,\n  LongPoll,\n  Presence,\n  Push,\n  serializer_default as Serializer,\n  Socket,\n  Timer\n};\n//# sourceMappingURL=phoenix.mjs.map\n","import { Presence } from '@supabase/phoenix';\nexport default class PresenceAdapter {\n    constructor(channel, opts) {\n        const phoenixOptions = phoenixPresenceOptions(opts);\n        this.presence = new Presence(channel.getChannel(), phoenixOptions);\n        this.presence.onJoin((key, currentPresence, newPresence) => {\n            const onJoinPayload = PresenceAdapter.onJoinPayload(key, currentPresence, newPresence);\n            channel.getChannel().trigger('presence', onJoinPayload);\n        });\n        this.presence.onLeave((key, currentPresence, leftPresence) => {\n            const onLeavePayload = PresenceAdapter.onLeavePayload(key, currentPresence, leftPresence);\n            channel.getChannel().trigger('presence', onLeavePayload);\n        });\n        this.presence.onSync(() => {\n            channel.getChannel().trigger('presence', { event: 'sync' });\n        });\n    }\n    get state() {\n        return PresenceAdapter.transformState(this.presence.state);\n    }\n    /**\n     * @private\n     * Remove 'metas' key\n     * Change 'phx_ref' to 'presence_ref'\n     * Remove 'phx_ref' and 'phx_ref_prev'\n     *\n     * @example Transform state\n     * // returns {\n     *  abc123: [\n     *    { presence_ref: '2', user_id: 1 },\n     *    { presence_ref: '3', user_id: 2 }\n     *  ]\n     * }\n     * RealtimePresence.transformState({\n     *  abc123: {\n     *    metas: [\n     *      { phx_ref: '2', phx_ref_prev: '1' user_id: 1 },\n     *      { phx_ref: '3', user_id: 2 }\n     *    ]\n     *  }\n     * })\n     *\n     */\n    static transformState(state) {\n        state = cloneState(state);\n        return Object.getOwnPropertyNames(state).reduce((newState, key) => {\n            const presences = state[key];\n            newState[key] = transformState(presences);\n            return newState;\n        }, {});\n    }\n    static onJoinPayload(key, currentPresence, newPresence) {\n        const currentPresences = parseCurrentPresences(currentPresence);\n        const newPresences = transformState(newPresence);\n        return {\n            event: 'join',\n            key,\n            currentPresences,\n            newPresences,\n        };\n    }\n    static onLeavePayload(key, currentPresence, leftPresence) {\n        const currentPresences = parseCurrentPresences(currentPresence);\n        const leftPresences = transformState(leftPresence);\n        return {\n            event: 'leave',\n            key,\n            currentPresences,\n            leftPresences,\n        };\n    }\n}\nfunction transformState(presences) {\n    return presences.metas.map((presence) => {\n        // Object spread compiles to Object.assign for ES2017, which treats __proto__ as a setter.\n        const descriptors = Object.getOwnPropertyDescriptors(presence);\n        const transformedPresence = Object.defineProperties({}, descriptors);\n        transformedPresence['presence_ref'] = transformedPresence['phx_ref'];\n        delete transformedPresence['phx_ref'];\n        delete transformedPresence['phx_ref_prev'];\n        return transformedPresence;\n    });\n}\nfunction cloneState(state) {\n    return JSON.parse(JSON.stringify(state));\n}\nfunction phoenixPresenceOptions(opts) {\n    return (opts === null || opts === void 0 ? void 0 : opts.events) && { events: opts.events };\n}\nfunction parseCurrentPresences(currentPresences) {\n    return (currentPresences === null || currentPresences === void 0 ? void 0 : currentPresences.metas) ? transformState(currentPresences) : [];\n}\n//# sourceMappingURL=presenceAdapter.js.map","/*\n  This file draws heavily from https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/assets/js/phoenix/presence.js\n  License: https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/LICENSE.md\n*/\nimport PresenceAdapter from './phoenix/presenceAdapter';\nexport var REALTIME_PRESENCE_LISTEN_EVENTS;\n(function (REALTIME_PRESENCE_LISTEN_EVENTS) {\n    REALTIME_PRESENCE_LISTEN_EVENTS[\"SYNC\"] = \"sync\";\n    REALTIME_PRESENCE_LISTEN_EVENTS[\"JOIN\"] = \"join\";\n    REALTIME_PRESENCE_LISTEN_EVENTS[\"LEAVE\"] = \"leave\";\n})(REALTIME_PRESENCE_LISTEN_EVENTS || (REALTIME_PRESENCE_LISTEN_EVENTS = {}));\nexport default class RealtimePresence {\n    get state() {\n        return this.presenceAdapter.state;\n    }\n    /**\n     * Creates a Presence helper that keeps the local presence state in sync with the server.\n     *\n     * @param channel - The realtime channel to bind to.\n     * @param opts - Optional custom event names, e.g. `{ events: { state: 'state', diff: 'diff' } }`.\n     *\n     * @category Realtime\n     *\n     * @example Example for a presence channel\n     * ```ts\n     * const presence = new RealtimePresence(channel)\n     *\n     * channel.on('presence', ({ event, key }) => {\n     *   console.log(`Presence ${event} on ${key}`)\n     * })\n     * ```\n     */\n    constructor(channel, opts) {\n        this.channel = channel;\n        this.presenceAdapter = new PresenceAdapter(this.channel.channelAdapter, opts);\n    }\n}\n//# sourceMappingURL=RealtimePresence.js.map","/**\n * Normalize the various shapes a channel error reason can take into a real `Error`.\n *\n * Transport-level channel errors arrive as a `CloseEvent`, a transport `Event`, an `Error`,\n * a string, or `undefined` depending on which path in the underlying socket fired. Server-reply\n * errors arrive as a payload object. This helper produces a consistent `Error` for every case\n * and preserves the original via `cause` so callers can still inspect the raw event.\n */\nexport function normalizeChannelError(reason) {\n    if (reason instanceof Error) {\n        return reason;\n    }\n    if (typeof reason === 'string') {\n        return new Error(reason);\n    }\n    if (reason && typeof reason === 'object') {\n        const obj = reason;\n        if (typeof obj.code === 'number') {\n            const detail = typeof obj.reason === 'string' && obj.reason ? ` (${obj.reason})` : '';\n            return new Error(`socket closed: ${obj.code}${detail}`, { cause: reason });\n        }\n        return new Error('channel error: transport failure', { cause: reason });\n    }\n    return new Error('channel error: connection lost');\n}\n//# sourceMappingURL=normalizeChannelError.js.map","import { CHANNEL_STATES, MAX_PUSH_BUFFER_SIZE } from '../lib/constants';\nexport default class ChannelAdapter {\n    constructor(socket, topic, params) {\n        const phoenixParams = phoenixChannelParams(params);\n        this.channel = socket.getSocket().channel(topic, phoenixParams);\n        this.socket = socket;\n    }\n    get state() {\n        return this.channel.state;\n    }\n    set state(state) {\n        this.channel.state = state;\n    }\n    get joinedOnce() {\n        return this.channel.joinedOnce;\n    }\n    get joinPush() {\n        return this.channel.joinPush;\n    }\n    get rejoinTimer() {\n        return this.channel.rejoinTimer;\n    }\n    on(event, callback) {\n        return this.channel.on(event, callback);\n    }\n    off(event, refNumber) {\n        this.channel.off(event, refNumber);\n    }\n    subscribe(timeout) {\n        return this.channel.join(timeout);\n    }\n    unsubscribe(timeout) {\n        return this.channel.leave(timeout);\n    }\n    teardown() {\n        this.channel.teardown();\n    }\n    onClose(callback) {\n        this.channel.onClose(callback);\n    }\n    onError(callback) {\n        return this.channel.onError(callback);\n    }\n    push(event, payload, timeout) {\n        let push;\n        try {\n            push = this.channel.push(event, payload, timeout);\n        }\n        catch (error) {\n            throw new Error(`tried to push '${event}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`);\n        }\n        if (this.channel.pushBuffer.length > MAX_PUSH_BUFFER_SIZE) {\n            const removedPush = this.channel.pushBuffer.shift();\n            removedPush.cancelTimeout();\n            this.socket.log('channel', `discarded push due to buffer overflow: ${removedPush.event}`, removedPush.payload());\n        }\n        return push;\n    }\n    updateJoinPayload(payload) {\n        const oldPayload = this.channel.joinPush.payload();\n        this.channel.joinPush.payload = () => (Object.assign(Object.assign({}, oldPayload), payload));\n    }\n    canPush() {\n        return this.socket.isConnected() && this.state === CHANNEL_STATES.joined;\n    }\n    isJoined() {\n        return this.state === CHANNEL_STATES.joined;\n    }\n    isJoining() {\n        return this.state === CHANNEL_STATES.joining;\n    }\n    isClosed() {\n        return this.state === CHANNEL_STATES.closed;\n    }\n    isLeaving() {\n        return this.state === CHANNEL_STATES.leaving;\n    }\n    updateFilterBindings(filterBindings) {\n        this.channel.filterBindings = filterBindings;\n    }\n    updatePayloadTransform(callback) {\n        this.channel.onMessage = callback;\n    }\n    /**\n     * @internal\n     */\n    getChannel() {\n        return this.channel;\n    }\n}\nfunction phoenixChannelParams(options) {\n    return {\n        config: Object.assign({\n            broadcast: { ack: false, self: false },\n            presence: { key: '', enabled: false },\n            private: false,\n        }, options.config),\n    };\n}\n//# sourceMappingURL=channelAdapter.js.map","// Reserved characters that force PostgREST-style quoting: `[,()]` (which the\n// server reads as condition/list delimiters) plus `\"`/`\\` (escaped inside quotes).\nconst PostgrestReservedCharsRegexp = /[,()\"\\\\]/;\nconst needsQuoting = (value) => PostgrestReservedCharsRegexp.test(value) || value !== value.trim();\nconst quote = (value) => `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\nconst serializeScalar = (value) => {\n    const serialized = value === null ? 'null' : String(value);\n    return needsQuoting(serialized) ? quote(serialized) : serialized;\n};\nconst serializeIsValue = (value) => value === null ? 'null' : String(value);\n// Builds the `operator.value` portion of a filter (everything after `column=`).\nconst serialize = (operator, value) => {\n    if (operator === 'in') {\n        const values = Array.isArray(value) ? value : [value];\n        if (values.length === 0) {\n            throw new Error('Realtime `in` filter requires at least one value.');\n        }\n        const items = Array.from(new Set(values))\n            .map((v) => serializeScalar(v))\n            .join(',');\n        return `in.(${items})`;\n    }\n    if (operator === 'is') {\n        return `is.${serializeIsValue(value)}`;\n    }\n    return `${operator}.${serializeScalar(value)}`;\n};\n/**\n * Fluent builder for Postgres Changes `filter` strings.\n *\n * Each method appends a single `column=operator.value` condition. Multiple\n * conditions are combined with commas, which the Realtime server applies as an\n * `AND`. Pass an instance straight to `channel.on('postgres_changes', …)` — the\n * SDK serializes it to a string automatically — or call {@link build} to obtain\n * the string yourself.\n *\n * The builder mirrors the `postgrest-js` filter API (`eq`, `neq`, `in`, `like`,\n * `not`, …) for the operators that Realtime supports. Values containing reserved\n * characters (`,`, `(`, `)`, `\"`, `\\`) — or surrounding whitespace — are\n * automatically double-quoted and escaped the same way PostgREST does, so they\n * survive the server's filter parser; all other values are sent verbatim.\n *\n * The filter is snapshotted when passed to `channel.on(...)`; mutating the\n * builder afterwards does not affect an existing subscription. An empty builder\n * serializes to `''`, which the server treats as \"no filter\".\n *\n * @example\n * channel.on('postgres_changes', {\n *   event: '*',\n *   schema: 'public',\n *   table: 'users',\n *   filter: postgresChangesFilter().eq('id', 1).lt('age', 30), // → 'id=eq.1,age=lt.30'\n * }, (payload) => { ... })\n */\nexport class RealtimePostgresFilterBuilder {\n    constructor() {\n        this.filters = [];\n    }\n    add(column, operator, value, negate = false) {\n        const prefix = negate ? 'not.' : '';\n        this.filters.push(`${column}=${prefix}${serialize(operator, value)}`);\n        return this;\n    }\n    /** Match rows where `column` equals `value` (`column=eq.value`). */\n    eq(column, value) {\n        return this.add(column, 'eq', value);\n    }\n    /** Match rows where `column` does not equal `value` (`column=neq.value`). */\n    neq(column, value) {\n        return this.add(column, 'neq', value);\n    }\n    /** Match rows where `column` is greater than `value` (`column=gt.value`). */\n    gt(column, value) {\n        return this.add(column, 'gt', value);\n    }\n    /** Match rows where `column` is greater than or equal to `value` (`column=gte.value`). */\n    gte(column, value) {\n        return this.add(column, 'gte', value);\n    }\n    /** Match rows where `column` is less than `value` (`column=lt.value`). */\n    lt(column, value) {\n        return this.add(column, 'lt', value);\n    }\n    /** Match rows where `column` is less than or equal to `value` (`column=lte.value`). */\n    lte(column, value) {\n        return this.add(column, 'lte', value);\n    }\n    /**\n     * Match rows where `column` is one of `values` (`column=in.(a,b,c)`).\n     * Requires at least one value; duplicates are removed. An element containing a\n     * reserved character is double-quoted (`in.(\"a,b\",c)`), so commas inside an\n     * element are preserved. `null` is intentionally not accepted (`IN (null)`\n     * never matches in SQL) — use `is`/`not('col','is',null)` for null checks.\n     */\n    in(column, values) {\n        return this.add(column, 'in', values);\n    }\n    /** Match rows where `column` matches the case-sensitive `pattern` (`column=like.pattern`). */\n    like(column, pattern) {\n        return this.add(column, 'like', pattern);\n    }\n    /** Match rows where `column` matches the case-insensitive `pattern` (`column=ilike.pattern`). */\n    ilike(column, pattern) {\n        return this.add(column, 'ilike', pattern);\n    }\n    /** Match rows where `column` matches the POSIX regex `pattern` (`column=match.pattern`). */\n    match(column, pattern) {\n        return this.add(column, 'match', pattern);\n    }\n    /** Match rows where `column` matches the case-insensitive POSIX regex `pattern` (`column=imatch.pattern`). */\n    imatch(column, pattern) {\n        return this.add(column, 'imatch', pattern);\n    }\n    /**\n     * Match rows where `column` `IS` the given value (`column=is.null`).\n     * Accepts `null`, a boolean, or the keywords `'null' | 'true' | 'false' | 'unknown'`.\n     */\n    is(column, value) {\n        return this.add(column, 'is', value);\n    }\n    /** Match rows where `column` is distinct from `value` (`column=isdistinct.value`). NULL-safe inequality. */\n    isDistinct(column, value) {\n        return this.add(column, 'isdistinct', value);\n    }\n    not(column, operator, value) {\n        return this.add(column, operator, value, true);\n    }\n    /**\n     * Serialize all conditions into the comma-separated (AND) filter string.\n     *\n     * Conditions are joined by commas, which the server applies as `AND`. A scalar\n     * value (or single `in` element) that contains a reserved character — `,`,\n     * `(`, `)`, `\"`, `\\` — or surrounding whitespace is double-quoted and escaped\n     * the way PostgREST does, so commas inside a value are preserved rather than\n     * read as a condition boundary.\n     */\n    build() {\n        return this.filters.join(',');\n    }\n    /** Alias for {@link build}; lets the builder be used wherever a string is expected. */\n    toString() {\n        return this.build();\n    }\n}\n/**\n * Create a {@link RealtimePostgresFilterBuilder} for composing a Postgres\n * Changes `filter`. Conditions are combined with `AND`.\n *\n * @example\n * import { postgresChangesFilter } from '@supabase/realtime-js'\n *\n * channel.on('postgres_changes', {\n *   event: 'UPDATE',\n *   schema: 'public',\n *   table: 'orders',\n *   filter: postgresChangesFilter().gt('amount', 100).eq('status', 'open'),\n * }, (payload) => { ... })\n */\nexport const postgresChangesFilter = () => new RealtimePostgresFilterBuilder();\n//# sourceMappingURL=RealtimePostgresFilterBuilder.js.map","import { CHANNEL_EVENTS, CHANNEL_STATES, DEFAULT_POSTGRES_CHANGES_WAIT_TIMEOUT, POSTGRES_CHANGES_WAIT_ERROR_GRACE, } from './lib/constants';\nimport RealtimePresence from './RealtimePresence';\nimport * as Transformers from './lib/transformers';\nimport { httpEndpointURL } from './lib/transformers';\nimport { normalizeChannelError } from './lib/normalizeChannelError';\nimport ChannelAdapter from './phoenix/channelAdapter';\nimport { RealtimePostgresFilterBuilder } from './RealtimePostgresFilterBuilder';\nexport { RealtimePostgresFilterBuilder, postgresChangesFilter, } from './RealtimePostgresFilterBuilder';\nexport var REALTIME_POSTGRES_CHANGES_LISTEN_EVENT;\n(function (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT) {\n    REALTIME_POSTGRES_CHANGES_LISTEN_EVENT[\"ALL\"] = \"*\";\n    REALTIME_POSTGRES_CHANGES_LISTEN_EVENT[\"INSERT\"] = \"INSERT\";\n    REALTIME_POSTGRES_CHANGES_LISTEN_EVENT[\"UPDATE\"] = \"UPDATE\";\n    REALTIME_POSTGRES_CHANGES_LISTEN_EVENT[\"DELETE\"] = \"DELETE\";\n})(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT || (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = {}));\nexport var REALTIME_LISTEN_TYPES;\n(function (REALTIME_LISTEN_TYPES) {\n    REALTIME_LISTEN_TYPES[\"BROADCAST\"] = \"broadcast\";\n    REALTIME_LISTEN_TYPES[\"PRESENCE\"] = \"presence\";\n    REALTIME_LISTEN_TYPES[\"POSTGRES_CHANGES\"] = \"postgres_changes\";\n    REALTIME_LISTEN_TYPES[\"SYSTEM\"] = \"system\";\n})(REALTIME_LISTEN_TYPES || (REALTIME_LISTEN_TYPES = {}));\nexport var REALTIME_SUBSCRIBE_STATES;\n(function (REALTIME_SUBSCRIBE_STATES) {\n    REALTIME_SUBSCRIBE_STATES[\"SUBSCRIBED\"] = \"SUBSCRIBED\";\n    REALTIME_SUBSCRIBE_STATES[\"TIMED_OUT\"] = \"TIMED_OUT\";\n    REALTIME_SUBSCRIBE_STATES[\"CLOSED\"] = \"CLOSED\";\n    REALTIME_SUBSCRIBE_STATES[\"CHANNEL_ERROR\"] = \"CHANNEL_ERROR\";\n})(REALTIME_SUBSCRIBE_STATES || (REALTIME_SUBSCRIBE_STATES = {}));\nexport const REALTIME_CHANNEL_STATES = CHANNEL_STATES;\n/** A channel is the basic building block of Realtime\n * and narrows the scope of data flow to subscribed clients.\n * You can think of a channel as a chatroom where participants are able to see who's online\n * and send and receive messages.\n */\nexport default class RealtimeChannel {\n    get state() {\n        return this.channelAdapter.state;\n    }\n    set state(state) {\n        this.channelAdapter.state = state;\n    }\n    get joinedOnce() {\n        return this.channelAdapter.joinedOnce;\n    }\n    get timeout() {\n        return this.socket.timeout;\n    }\n    get joinPush() {\n        return this.channelAdapter.joinPush;\n    }\n    get rejoinTimer() {\n        return this.channelAdapter.rejoinTimer;\n    }\n    /**\n     * Creates a channel that can broadcast messages, sync presence, and listen to Postgres changes.\n     *\n     * The topic determines which realtime stream you are subscribing to. Config options let you\n     * enable acknowledgement for broadcasts, presence tracking, or private channels.\n     *\n     * @category Realtime\n     *\n     * @example Using supabase-js (recommended)\n     * ```ts\n     * import { createClient } from '@supabase/supabase-js'\n     *\n     * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n     * const channel = supabase.channel('room1')\n     * channel\n     *   .on('broadcast', { event: 'cursor-pos' }, (payload) => console.log(payload))\n     *   .subscribe()\n     * ```\n     *\n     * @example Standalone import for bundle-sensitive environments\n     * ```ts\n     * import RealtimeClient from '@supabase/realtime-js'\n     *\n     * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', {\n     *   params: { apikey: 'your-publishable-key' },\n     * })\n     * const channel = new RealtimeChannel('realtime:public:messages', { config: {} }, client)\n     * ```\n     */\n    constructor(\n    /** Topic name can be any string. */\n    topic, params = { config: {} }, socket) {\n        var _a, _b;\n        this.topic = topic;\n        this.params = params;\n        this.socket = socket;\n        this.bindings = {};\n        this.subTopic = topic.replace(/^realtime:/i, '');\n        this.params.config = Object.assign({\n            broadcast: { ack: false, self: false },\n            presence: { key: '', enabled: false },\n            private: false,\n        }, params.config);\n        this.channelAdapter = new ChannelAdapter(this.socket.socketAdapter, topic, this.params);\n        this.presence = new RealtimePresence(this);\n        this._onClose(() => {\n            this.socket._remove(this);\n        });\n        this._updateFilterTransform();\n        this.broadcastEndpointURL = httpEndpointURL(this.socket.socketAdapter.endPointURL());\n        this.private = this.params.config.private || false;\n        if (!this.private && ((_b = (_a = this.params.config) === null || _a === void 0 ? void 0 : _a.broadcast) === null || _b === void 0 ? void 0 : _b.replay)) {\n            throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`);\n        }\n    }\n    /**\n     * Subscribe registers your client with the server.\n     *\n     * The optional `callback` receives a `status` and, on failure, an `err` argument.\n     * Log the full `err` so its `cause`, `name`, and any structured fields aren't hidden\n     * behind `err.message`.\n     *\n     * @category Realtime\n     *\n     * @example Handling errors\n     * ```js\n     * supabase.channel('room1').subscribe((status, err) => {\n     *   if (status === 'CHANNEL_ERROR' || status === 'TIMED_OUT') {\n     *     // Log the full error: its `cause` often holds the underlying reason.\n     *     console.error(status, err)\n     *   }\n     * })\n     * ```\n     */\n    subscribe(callback, timeout = this.timeout) {\n        var _a, _b, _c, _d;\n        if (!this.socket.isConnected()) {\n            this.socket.connect();\n        }\n        if (this.channelAdapter.isClosed()) {\n            const { config: { broadcast, presence, private: isPrivate, postgres_changes_options }, } = this.params;\n            const postgres_changes = (_b = (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.map((r) => r.filter)) !== null && _b !== void 0 ? _b : [];\n            const presence_enabled = (!!this.bindings[REALTIME_LISTEN_TYPES.PRESENCE] &&\n                this.bindings[REALTIME_LISTEN_TYPES.PRESENCE].length > 0) ||\n                ((_c = this.params.config.presence) === null || _c === void 0 ? void 0 : _c.enabled) === true;\n            const accessTokenPayload = {};\n            const config = Object.assign({ broadcast, presence: Object.assign(Object.assign({}, presence), { enabled: presence_enabled }), postgres_changes, private: isPrivate }, (postgres_changes_options ? { postgres_changes_options } : {}));\n            if (this.socket.accessTokenValue) {\n                accessTokenPayload.access_token = this.socket.accessTokenValue;\n            }\n            this._onError((reason) => {\n                callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, normalizeChannelError(reason));\n            });\n            this._onClose(() => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CLOSED));\n            this.updateJoinPayload(Object.assign({ config }, accessTokenPayload));\n            this._updateFilterMessage();\n            const joinTimeout = (postgres_changes_options === null || postgres_changes_options === void 0 ? void 0 : postgres_changes_options.wait) && postgres_changes.length > 0\n                ? Math.max(timeout, ((_d = postgres_changes_options.timeout) !== null && _d !== void 0 ? _d : DEFAULT_POSTGRES_CHANGES_WAIT_TIMEOUT) +\n                    POSTGRES_CHANGES_WAIT_ERROR_GRACE)\n                : timeout;\n            this.channelAdapter\n                .subscribe(joinTimeout)\n                .receive('ok', async ({ postgres_changes }) => {\n                // Only refresh auth if using callback-based tokens\n                if (!this.socket._isManualToken()) {\n                    this.socket.setAuth();\n                }\n                if (postgres_changes === undefined) {\n                    callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED);\n                    return;\n                }\n                this._updatePostgresBindings(postgres_changes, callback);\n            })\n                .receive('error', (error) => {\n                this.state = CHANNEL_STATES.errored;\n                const message = Object.values(error).join(', ') || 'error';\n                callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error(message, { cause: error }));\n            })\n                .receive('timeout', () => {\n                callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.TIMED_OUT);\n            });\n        }\n        return this;\n    }\n    _updatePostgresBindings(postgres_changes, callback) {\n        var _a;\n        const clientPostgresBindings = this.bindings.postgres_changes;\n        const bindingsLen = (_a = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a !== void 0 ? _a : 0;\n        const newPostgresBindings = [];\n        for (let i = 0; i < bindingsLen; i++) {\n            const clientPostgresBinding = clientPostgresBindings[i];\n            const { filter: { event, schema, table, filter }, } = clientPostgresBinding;\n            const serverPostgresFilter = postgres_changes && postgres_changes[i];\n            if (serverPostgresFilter &&\n                serverPostgresFilter.event === event &&\n                RealtimeChannel.isFilterValueEqual(serverPostgresFilter.schema, schema) &&\n                RealtimeChannel.isFilterValueEqual(serverPostgresFilter.table, table) &&\n                RealtimeChannel.isFilterValueEqual(serverPostgresFilter.filter, filter)) {\n                newPostgresBindings.push(Object.assign(Object.assign({}, clientPostgresBinding), { id: serverPostgresFilter.id }));\n            }\n            else {\n                this.unsubscribe();\n                this.state = CHANNEL_STATES.errored;\n                callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error('mismatch between server and client bindings for postgres changes'));\n                return;\n            }\n        }\n        this.bindings.postgres_changes = newPostgresBindings;\n        if (this.state != CHANNEL_STATES.errored && callback) {\n            callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED);\n        }\n    }\n    /**\n     * Returns the current presence state for this channel.\n     *\n     * The shape is a map keyed by presence key (for example a user id) where each entry contains the\n     * tracked metadata for that user.\n     *\n     * @category Realtime\n     */\n    presenceState() {\n        return this.presence.state;\n    }\n    /**\n     * Sends the supplied payload to the presence tracker so other subscribers can see that this\n     * client is online. Use `untrack` to stop broadcasting presence for the same key.\n     *\n     * Tracking makes this client visible to other subscribers immediately, regardless of this\n     * channel's `config.presence.enabled` setting or whether it has a `presence` listener — that\n     * flag only affects whether *this* client receives presence updates from others (and, on\n     * RLS-protected channels, whether it's authorized to do so).\n     *\n     * @category Realtime\n     */\n    async track(payload, opts = {}) {\n        return await this.send({\n            type: 'presence',\n            event: 'track',\n            payload,\n        }, opts);\n    }\n    /**\n     * Removes the current presence state for this client.\n     *\n     * @category Realtime\n     */\n    async untrack(opts = {}) {\n        return await this.send({\n            type: 'presence',\n            event: 'untrack',\n        }, opts);\n    }\n    /**\n     * Listen to realtime events on this channel.\n     * @category Realtime\n     *\n     * @remarks\n     * - By default, Broadcast and Presence are enabled for all projects.\n     * - By default, listening to database changes is disabled for new projects due to database performance and security concerns. You can turn it on by managing Realtime's [replication](/docs/guides/api#realtime-api-overview).\n     * - You can receive the \"previous\" data for updates and deletes by setting the table's `REPLICA IDENTITY` to `FULL` (e.g., `ALTER TABLE your_table REPLICA IDENTITY FULL;`).\n     * - Row level security is not applied to delete statements. When RLS is enabled and replica identity is set to full, only the primary key is sent to clients.\n     *\n     * @example Listen to broadcast messages\n     * ```js\n     * const channel = supabase.channel(\"room1\")\n     *\n     * channel.on(\"broadcast\", { event: \"cursor-pos\" }, (payload) => {\n     *   console.log(\"Cursor position received!\", payload);\n     * }).subscribe((status) => {\n     *   if (status === \"SUBSCRIBED\") {\n     *     channel.send({\n     *       type: \"broadcast\",\n     *       event: \"cursor-pos\",\n     *       payload: { x: Math.random(), y: Math.random() },\n     *     });\n     *   }\n     * });\n     * ```\n     *\n     * @example Listen to presence sync\n     * ```js\n     * const channel = supabase.channel('room1')\n     * channel\n     *   .on('presence', { event: 'sync' }, () => {\n     *     console.log('Synced presence state: ', channel.presenceState())\n     *   })\n     *   .subscribe(async (status) => {\n     *     if (status === 'SUBSCRIBED') {\n     *       await channel.track({ online_at: new Date().toISOString() })\n     *     }\n     *   })\n     * ```\n     *\n     * @example Listen to presence join\n     * ```js\n     * const channel = supabase.channel('room1')\n     * channel\n     *   .on('presence', { event: 'join' }, ({ newPresences }) => {\n     *     console.log('Newly joined presences: ', newPresences)\n     *   })\n     *   .subscribe(async (status) => {\n     *     if (status === 'SUBSCRIBED') {\n     *       await channel.track({ online_at: new Date().toISOString() })\n     *     }\n     *   })\n     * ```\n     *\n     * @example Listen to presence leave\n     * ```js\n     * const channel = supabase.channel('room1')\n     * channel\n     *   .on('presence', { event: 'leave' }, ({ leftPresences }) => {\n     *     console.log('Newly left presences: ', leftPresences)\n     *   })\n     *   .subscribe(async (status) => {\n     *     if (status === 'SUBSCRIBED') {\n     *       await channel.track({ online_at: new Date().toISOString() })\n     *       await channel.untrack()\n     *     }\n     *   })\n     * ```\n     *\n     * Registering the same `postgres_changes` filter more than once on a channel is a no-op: the\n     * duplicate is ignored and an error is logged, since the server only ever creates one\n     * subscription per distinct filter.\n     *\n     * @example Listen to all database changes\n     * ```js\n     * supabase\n     *   .channel('room1')\n     *   .on('postgres_changes', { event: '*', schema: '*' }, payload => {\n     *     console.log('Change received!', payload)\n     *   })\n     *   .subscribe()\n     * ```\n     *\n     * @example Listen to a specific table\n     * ```js\n     * supabase\n     *   .channel('room1')\n     *   .on('postgres_changes', { event: '*', schema: 'public', table: 'countries' }, payload => {\n     *     console.log('Change received!', payload)\n     *   })\n     *   .subscribe()\n     * ```\n     *\n     * @example Listen to inserts\n     * ```js\n     * supabase\n     *   .channel('room1')\n     *   .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'countries' }, payload => {\n     *     console.log('Change received!', payload)\n     *   })\n     *   .subscribe()\n     * ```\n     *\n     * @exampleDescription Listen to updates\n     * By default, Supabase will send only the updated record. If you want to receive the previous values as well you can\n     * enable full replication for the table you are listening to:\n     *\n     * ```sql\n     * alter table \"your_table\" replica identity full;\n     * ```\n     *\n     * @example Listen to updates\n     * ```js\n     * supabase\n     *   .channel('room1')\n     *   .on('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'countries' }, payload => {\n     *     console.log('Change received!', payload)\n     *   })\n     *   .subscribe()\n     * ```\n     *\n     * @exampleDescription Listen to deletes\n     * By default, Supabase does not send deleted records. If you want to receive the deleted record you can\n     * enable full replication for the table you are listening to:\n     *\n     * ```sql\n     * alter table \"your_table\" replica identity full;\n     * ```\n     *\n     * @example Listen to deletes\n     * ```js\n     * supabase\n     *   .channel('room1')\n     *   .on('postgres_changes', { event: 'DELETE', schema: 'public', table: 'countries' }, payload => {\n     *     console.log('Change received!', payload)\n     *   })\n     *   .subscribe()\n     * ```\n     *\n     * @exampleDescription Listen to multiple events\n     * You can chain listeners if you want to listen to multiple events for each table.\n     *\n     * @example Listen to multiple events\n     * ```js\n     * supabase\n     *   .channel('room1')\n     *   .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'countries' }, handleRecordInserted)\n     *   .on('postgres_changes', { event: 'DELETE', schema: 'public', table: 'countries' }, handleRecordDeleted)\n     *   .subscribe()\n     * ```\n     *\n     * @exampleDescription Listen to row level changes\n     * You can listen to individual rows using the format `{table}:{col}=eq.{val}` - where `{col}` is the column name, and `{val}` is the value which you want to match.\n     *\n     * @example Listen to row level changes\n     * ```js\n     * supabase\n     *   .channel('room1')\n     *   .on('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'countries', filter: 'id=eq.200' }, handleRecordUpdated)\n     *   .subscribe()\n     * ```\n     */\n    on(type, filter, callback) {\n        const stateCheck = this.channelAdapter.isJoined() || this.channelAdapter.isJoining();\n        const typeCheck = type === REALTIME_LISTEN_TYPES.PRESENCE || type === REALTIME_LISTEN_TYPES.POSTGRES_CHANGES;\n        if (stateCheck && typeCheck) {\n            this.socket.log('channel', `cannot add \\`${type}\\` callbacks for ${this.topic} after \\`subscribe()\\`.`);\n            throw new Error(`cannot add \\`${type}\\` callbacks for ${this.topic} after \\`subscribe()\\`.`);\n        }\n        return this._on(type, filter, callback);\n    }\n    /**\n     * Sends a broadcast message explicitly via REST API.\n     *\n     * This method always uses the REST API endpoint regardless of WebSocket connection state.\n     * Useful when you want to guarantee REST delivery or when gradually migrating from implicit REST fallback.\n     *\n     * Payloads that are `ArrayBuffer` or `ArrayBufferView` (e.g. `Uint8Array`) are sent as\n     * `application/octet-stream`; all other payloads are JSON-encoded.\n     *\n     * @param event The name of the broadcast event\n     * @param payload Payload to be sent (required)\n     * @param opts Options including timeout\n     * @returns Promise resolving to object with success status, and error details if failed\n     *\n     * @category Realtime\n     */\n    async httpSend(event, payload, opts = {}) {\n        var _a;\n        if (payload === undefined || payload === null) {\n            return Promise.reject(new Error('Payload is required for httpSend()'));\n        }\n        const isBinary = payload instanceof ArrayBuffer || ArrayBuffer.isView(payload);\n        const headers = {\n            apikey: this.socket.apiKey ? this.socket.apiKey : '',\n            'Content-Type': isBinary ? 'application/octet-stream' : 'application/json',\n        };\n        if (this.socket.accessTokenValue) {\n            headers['Authorization'] = `Bearer ${this.socket.accessTokenValue}`;\n        }\n        const url = new URL(this.broadcastEndpointURL);\n        url.pathname += `/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(event)}`;\n        if (this.private) {\n            url.searchParams.set('private', 'true');\n        }\n        const options = {\n            method: 'POST',\n            headers,\n            body: isBinary ? payload : JSON.stringify(payload),\n        };\n        const response = await this._fetchWithTimeout(url.toString(), options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout);\n        if (response.status === 202) {\n            return { success: true };\n        }\n        if (response.status === 404) {\n            return Promise.reject(new Error('httpSend() requires Realtime server v2.97.0 or newer; the endpoint returned 404. ' +\n                'Update your Supabase CLI to a recent version, or upgrade the Realtime server in your self-hosted setup. ' +\n                'See https://github.com/supabase/supabase-js/blob/master/packages/core/realtime-js/migrations/httpsend-server-version.md'));\n        }\n        let errorMessage = response.statusText;\n        try {\n            const errorBody = await response.json();\n            errorMessage = errorBody.error || errorBody.message || errorMessage;\n        }\n        catch (_b) { }\n        return Promise.reject(new Error(errorMessage));\n    }\n    /**\n     * Sends a message into the channel.\n     *\n     * @param args Arguments to send to channel\n     * @param args.type The type of event to send\n     * @param args.event The name of the event being sent\n     * @param args.payload Payload to be sent\n     * @param opts Options to be used during the send process\n     *\n     * @category Realtime\n     *\n     * @remarks\n     * - When using REST you don't need to subscribe to the channel\n     * - REST calls are only available from 2.37.0 onwards\n     * - If you create a channel only to send a REST broadcast, remove it from\n     *   the client when the send completes\n     *\n     * @example Send a message via websocket\n     * ```js\n     * const channel = supabase.channel('room1')\n     *\n     * channel.subscribe((status) => {\n     *   if (status === 'SUBSCRIBED') {\n     *     channel.send({\n     *       type: 'broadcast',\n     *       event: 'cursor-pos',\n     *       payload: { x: Math.random(), y: Math.random() },\n     *     })\n     *   }\n     * })\n     * ```\n     *\n     * @exampleResponse Send a message via websocket\n     * ```js\n     * ok | timed out | error\n     * ```\n     *\n     * @example Send a message via REST\n     * ```js\n     * const channel = supabase.channel('room1')\n     *\n     * try {\n     *   await channel.httpSend('cursor-pos', { x: Math.random(), y: Math.random() })\n     * } finally {\n     *   await supabase.removeChannel(channel)\n     * }\n     * ```\n     */\n    async send(args, opts = {}) {\n        var _a, _b;\n        if (!this.channelAdapter.canPush() && args.type === 'broadcast') {\n            const fallbackWarning = 'Realtime send() is automatically falling back to REST API. ' +\n                'This behavior will be deprecated in the future. ' +\n                'Please use httpSend() explicitly for REST delivery.';\n            if (this.socket.hasLogger()) {\n                this.socket.log('channel', fallbackWarning);\n            }\n            else {\n                console.warn(fallbackWarning);\n            }\n            const { event, payload: endpoint_payload } = args;\n            const headers = {\n                apikey: this.socket.apiKey ? this.socket.apiKey : '',\n                'Content-Type': 'application/json',\n            };\n            if (this.socket.accessTokenValue) {\n                headers['Authorization'] = `Bearer ${this.socket.accessTokenValue}`;\n            }\n            const options = {\n                method: 'POST',\n                headers,\n                body: JSON.stringify({\n                    messages: [\n                        {\n                            topic: this.subTopic,\n                            event,\n                            payload: endpoint_payload,\n                            private: this.private,\n                        },\n                    ],\n                }),\n            };\n            try {\n                const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout);\n                await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel());\n                return response.ok ? 'ok' : 'error';\n            }\n            catch (error) {\n                if (error instanceof Error && error.name === 'AbortError') {\n                    return 'timed out';\n                }\n                else {\n                    return 'error';\n                }\n            }\n        }\n        else {\n            return new Promise((resolve) => {\n                var _a, _b, _c;\n                const push = this.channelAdapter.push(args.type, args, opts.timeout || this.timeout);\n                if (args.type === 'broadcast' && !((_c = (_b = (_a = this.params) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) {\n                    resolve('ok');\n                }\n                push.receive('ok', () => resolve('ok'));\n                push.receive('error', () => resolve('error'));\n                push.receive('timeout', () => resolve('timed out'));\n            });\n        }\n    }\n    /**\n     * Updates the payload that will be sent the next time the channel joins (reconnects).\n     * Useful for rotating access tokens or updating config without re-creating the channel.\n     *\n     * @category Realtime\n     */\n    updateJoinPayload(payload) {\n        this.channelAdapter.updateJoinPayload(payload);\n    }\n    /**\n     * Leaves the channel.\n     *\n     * Unsubscribes from server events, and instructs channel to terminate on server.\n     * Triggers onClose() hooks.\n     *\n     * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie:\n     * channel.unsubscribe().receive(\"ok\", () => alert(\"left!\") )\n     *\n     * @category Realtime\n     */\n    async unsubscribe(timeout = this.timeout) {\n        return new Promise((resolve) => {\n            this.channelAdapter\n                .unsubscribe(timeout)\n                .receive('ok', () => resolve('ok'))\n                .receive('timeout', () => resolve('timed out'))\n                .receive('error', () => resolve('error'));\n        });\n    }\n    /**\n     * Destroys and stops related timers.\n     *\n     * @category Realtime\n     */\n    teardown() {\n        this.channelAdapter.teardown();\n    }\n    /** @internal */\n    async _fetchWithTimeout(url, options, timeout) {\n        const controller = new AbortController();\n        const id = setTimeout(() => controller.abort(), timeout);\n        const response = await this.socket.fetch(url, Object.assign(Object.assign({}, options), { signal: controller.signal }));\n        clearTimeout(id);\n        return response;\n    }\n    /** @internal */\n    _on(type, filter, callback) {\n        var _a;\n        const typeLower = type.toLocaleLowerCase();\n        // Serialize a postgres_changes filter builder into its string form so the\n        // rest of the pipeline (join payload, server binding match) sees a string.\n        // Duck-type `build()` in addition to `instanceof` so a builder constructed\n        // against a duplicate copy of the package (separate module realm) still works.\n        const filterValue = filter === null || filter === void 0 ? void 0 : filter.filter;\n        if (filterValue instanceof RealtimePostgresFilterBuilder ||\n            (typeof filterValue === 'object' &&\n                filterValue !== null &&\n                typeof filterValue.build === 'function')) {\n            filter = Object.assign(Object.assign({}, filter), { filter: filterValue.build() });\n        }\n        // The server collapses identical postgres_changes filters, so keeping a duplicate here would\n        // desync the client and server binding lists and make `subscribe()` fail with a mismatch.\n        if (typeLower === REALTIME_LISTEN_TYPES.POSTGRES_CHANGES) {\n            const duplicate = (_a = this.bindings[typeLower]) === null || _a === void 0 ? void 0 : _a.find((bind) => RealtimeChannel.isSamePostgresFilter(bind.filter, filter));\n            if (duplicate) {\n                this.socket.log('error', `duplicate \\`postgres_changes\\` binding for ${this.topic} ignored`, filter);\n                return this;\n            }\n        }\n        const ref = this.channelAdapter.on(type, callback);\n        const binding = {\n            type: typeLower,\n            filter: filter,\n            callback: callback,\n            ref: ref,\n        };\n        if (this.bindings[typeLower]) {\n            this.bindings[typeLower].push(binding);\n        }\n        else {\n            this.bindings[typeLower] = [binding];\n        }\n        this._updateFilterMessage();\n        return this;\n    }\n    /**\n     * Registers a callback that will be executed when the channel closes.\n     *\n     * @internal\n     */\n    _onClose(callback) {\n        this.channelAdapter.onClose(callback);\n    }\n    /**\n     * Registers a callback that will be executed when the channel encounteres an error.\n     *\n     * @internal\n     */\n    _onError(callback) {\n        this.channelAdapter.onError(callback);\n    }\n    /** @internal */\n    _updateFilterMessage() {\n        this.channelAdapter.updateFilterBindings((binding, payload, ref) => {\n            var _a, _b, _c, _d, _e, _f, _g;\n            const typeLower = binding.event.toLocaleLowerCase();\n            if (this._notThisChannelEvent(typeLower, ref)) {\n                return false;\n            }\n            const bind = (_a = this.bindings[typeLower]) === null || _a === void 0 ? void 0 : _a.find((bind) => bind.ref === binding.ref);\n            if (!bind) {\n                return true;\n            }\n            if (['broadcast', 'presence', 'postgres_changes'].includes(typeLower)) {\n                if ('id' in bind) {\n                    const bindId = bind.id;\n                    const bindEvent = (_b = bind.filter) === null || _b === void 0 ? void 0 : _b.event;\n                    return (bindId &&\n                        ((_c = payload.ids) === null || _c === void 0 ? void 0 : _c.includes(bindId)) &&\n                        (bindEvent === '*' ||\n                            (bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) === ((_d = payload.data) === null || _d === void 0 ? void 0 : _d.type.toLocaleLowerCase())));\n                }\n                else {\n                    const bindEvent = (_f = (_e = bind === null || bind === void 0 ? void 0 : bind.filter) === null || _e === void 0 ? void 0 : _e.event) === null || _f === void 0 ? void 0 : _f.toLocaleLowerCase();\n                    return bindEvent === '*' || bindEvent === ((_g = payload === null || payload === void 0 ? void 0 : payload.event) === null || _g === void 0 ? void 0 : _g.toLocaleLowerCase());\n                }\n            }\n            else {\n                return bind.type.toLocaleLowerCase() === typeLower;\n            }\n        });\n    }\n    /** @internal */\n    _notThisChannelEvent(event, ref) {\n        const { close, error, leave, join } = CHANNEL_EVENTS;\n        const events = [close, error, leave, join];\n        return ref && events.includes(event) && ref !== this.joinPush.ref;\n    }\n    /** @internal */\n    _updateFilterTransform() {\n        this.channelAdapter.updatePayloadTransform((event, payload, ref) => {\n            if (typeof payload === 'object' && 'ids' in payload) {\n                const postgresChanges = payload.data;\n                const { schema, table, commit_timestamp, type, errors } = postgresChanges;\n                const enrichedPayload = {\n                    schema: schema,\n                    table: table,\n                    commit_timestamp: commit_timestamp,\n                    eventType: type,\n                    new: {},\n                    old: {},\n                    errors: errors,\n                };\n                return Object.assign(Object.assign({}, enrichedPayload), this._getPayloadRecords(postgresChanges));\n            }\n            return payload;\n        });\n    }\n    copyBindings(other) {\n        if (this.joinedOnce) {\n            throw new Error('cannot copy bindings into joined channel');\n        }\n        for (const kind in other.bindings) {\n            for (const binding of other.bindings[kind]) {\n                this._on(binding.type, binding.filter, binding.callback);\n            }\n        }\n    }\n    /**\n     * Compares two optional filter values for equality.\n     * Treats undefined, null, and empty string as equivalent empty values.\n     * @internal\n     */\n    static isFilterValueEqual(serverValue, clientValue) {\n        const normalizedServer = serverValue !== null && serverValue !== void 0 ? serverValue : undefined;\n        const normalizedClient = clientValue !== null && clientValue !== void 0 ? clientValue : undefined;\n        return normalizedServer === normalizedClient;\n    }\n    /**\n     * Two `postgres_changes` filters are the same when the server would collapse them into a single\n     * subscription.\n     * @internal\n     */\n    static isSamePostgresFilter(a, b) {\n        var _a, _b, _c, _d;\n        const selectA = (_b = (_a = a === null || a === void 0 ? void 0 : a.select) === null || _a === void 0 ? void 0 : _a.join()) !== null && _b !== void 0 ? _b : undefined;\n        const selectB = (_d = (_c = b === null || b === void 0 ? void 0 : b.select) === null || _c === void 0 ? void 0 : _c.join()) !== null && _d !== void 0 ? _d : undefined;\n        return ((a === null || a === void 0 ? void 0 : a.event) === (b === null || b === void 0 ? void 0 : b.event) &&\n            RealtimeChannel.isFilterValueEqual(a === null || a === void 0 ? void 0 : a.schema, b === null || b === void 0 ? void 0 : b.schema) &&\n            RealtimeChannel.isFilterValueEqual(a === null || a === void 0 ? void 0 : a.table, b === null || b === void 0 ? void 0 : b.table) &&\n            RealtimeChannel.isFilterValueEqual(a === null || a === void 0 ? void 0 : a.filter, b === null || b === void 0 ? void 0 : b.filter) &&\n            selectA === selectB);\n    }\n    /** @internal */\n    _getPayloadRecords(payload) {\n        const records = {\n            new: {},\n            old: {},\n        };\n        if (payload.type === 'INSERT' || payload.type === 'UPDATE') {\n            records.new = Transformers.convertChangeData(payload.columns, payload.record);\n        }\n        if (payload.type === 'UPDATE' || payload.type === 'DELETE') {\n            records.old = Transformers.convertChangeData(payload.columns, payload.old_record);\n        }\n        return records;\n    }\n}\n//# sourceMappingURL=RealtimeChannel.js.map","import { Socket } from '@supabase/phoenix';\nimport { CONNECTION_STATE } from '../lib/constants';\nexport default class SocketAdapter {\n    constructor(endPoint, options) {\n        this.socket = new Socket(endPoint, options);\n    }\n    get timeout() {\n        return this.socket.timeout;\n    }\n    get endPoint() {\n        return this.socket.endPoint;\n    }\n    get transport() {\n        return this.socket.transport;\n    }\n    get heartbeatIntervalMs() {\n        return this.socket.heartbeatIntervalMs;\n    }\n    get heartbeatCallback() {\n        return this.socket.heartbeatCallback;\n    }\n    set heartbeatCallback(callback) {\n        this.socket.heartbeatCallback = callback;\n    }\n    get heartbeatTimer() {\n        return this.socket.heartbeatTimer;\n    }\n    get pendingHeartbeatRef() {\n        return this.socket.pendingHeartbeatRef;\n    }\n    get reconnectTimer() {\n        return this.socket.reconnectTimer;\n    }\n    get vsn() {\n        return this.socket.vsn;\n    }\n    get encode() {\n        return this.socket.encode;\n    }\n    get decode() {\n        return this.socket.decode;\n    }\n    get reconnectAfterMs() {\n        return this.socket.reconnectAfterMs;\n    }\n    get sendBuffer() {\n        return this.socket.sendBuffer;\n    }\n    get stateChangeCallbacks() {\n        return this.socket.stateChangeCallbacks;\n    }\n    connect() {\n        this.socket.connect();\n    }\n    disconnect(callback, code, reason, timeout = 10000) {\n        return new Promise((resolve) => {\n            setTimeout(() => resolve('timeout'), timeout);\n            this.socket.disconnect(() => {\n                callback();\n                resolve('ok');\n            }, code, reason);\n        });\n    }\n    push(data) {\n        this.socket.push(data);\n    }\n    log(kind, msg, data) {\n        this.socket.log(kind, msg, data);\n    }\n    hasLogger() {\n        return this.socket.hasLogger();\n    }\n    makeRef() {\n        return this.socket.makeRef();\n    }\n    onOpen(callback) {\n        this.socket.onOpen(callback);\n    }\n    onClose(callback) {\n        this.socket.onClose(callback);\n    }\n    onError(callback) {\n        this.socket.onError(callback);\n    }\n    onMessage(callback) {\n        this.socket.onMessage(callback);\n    }\n    isConnected() {\n        return this.socket.isConnected();\n    }\n    isConnecting() {\n        return this.socket.connectionState() == CONNECTION_STATE.connecting;\n    }\n    isDisconnecting() {\n        return this.socket.connectionState() == CONNECTION_STATE.closing;\n    }\n    connectionState() {\n        // @ts-ignore - requires better typing and exposing type in phoenix\n        return this.socket.connectionState();\n    }\n    endPointURL() {\n        return this.socket.endPointURL();\n    }\n    sendHeartbeat() {\n        this.socket.sendHeartbeat();\n    }\n    /**\n     * @internal\n     */\n    getSocket() {\n        return this.socket;\n    }\n}\n//# sourceMappingURL=socketAdapter.js.map","import WebSocketFactory from './lib/websocket-factory';\nimport { CHANNEL_EVENTS, CONNECTION_STATE, DEFAULT_VERSION, DEFAULT_TIMEOUT, DEFAULT_VSN, VSN_1_0_0, VSN_2_0_0, } from './lib/constants';\nimport Serializer from './lib/serializer';\nimport { httpEndpointURL } from './lib/transformers';\nimport RealtimeChannel from './RealtimeChannel';\nimport SocketAdapter from './phoenix/socketAdapter';\n// Connection-related constants\nconst CONNECTION_TIMEOUTS = {\n    HEARTBEAT_INTERVAL: 25000,\n    RECONNECT_DELAY: 10,\n    HEARTBEAT_TIMEOUT_FALLBACK: 100,\n};\nconst RECONNECT_INTERVALS = [1000, 2000, 5000, 10000];\nconst DEFAULT_RECONNECT_FALLBACK = 10000;\nfunction createMemorySessionStorage() {\n    const store = new Map();\n    return {\n        get length() {\n            return store.size;\n        },\n        clear() {\n            store.clear();\n        },\n        getItem(key) {\n            return store.has(key) ? store.get(key) : null;\n        },\n        key(index) {\n            var _a;\n            return (_a = Array.from(store.keys())[index]) !== null && _a !== void 0 ? _a : null;\n        },\n        removeItem(key) {\n            store.delete(key);\n        },\n        setItem(key, value) {\n            store.set(key, String(value));\n        },\n    };\n}\nfunction resolveSessionStorage() {\n    try {\n        if (typeof globalThis !== 'undefined' && globalThis.sessionStorage) {\n            return globalThis.sessionStorage;\n        }\n    }\n    catch (_a) {\n        // Property access on `sessionStorage` itself throws in restricted-storage browsers.\n    }\n    return createMemorySessionStorage();\n}\nconst WORKER_SCRIPT = `\n  addEventListener(\"message\", (e) => {\n    if (e.data.event === \"start\") {\n      setInterval(() => postMessage({ event: \"keepAlive\" }), e.data.interval);\n    }\n  });`;\nexport default class RealtimeClient {\n    get endPoint() {\n        return this.socketAdapter.endPoint;\n    }\n    get timeout() {\n        return this.socketAdapter.timeout;\n    }\n    get transport() {\n        return this.socketAdapter.transport;\n    }\n    get heartbeatCallback() {\n        return this.socketAdapter.heartbeatCallback;\n    }\n    get heartbeatIntervalMs() {\n        return this.socketAdapter.heartbeatIntervalMs;\n    }\n    get heartbeatTimer() {\n        if (this.worker) {\n            return this._workerHeartbeatTimer;\n        }\n        return this.socketAdapter.heartbeatTimer;\n    }\n    get pendingHeartbeatRef() {\n        if (this.worker) {\n            return this._pendingWorkerHeartbeatRef;\n        }\n        return this.socketAdapter.pendingHeartbeatRef;\n    }\n    get reconnectTimer() {\n        return this.socketAdapter.reconnectTimer;\n    }\n    get vsn() {\n        return this.socketAdapter.vsn;\n    }\n    get encode() {\n        return this.socketAdapter.encode;\n    }\n    get decode() {\n        return this.socketAdapter.decode;\n    }\n    get reconnectAfterMs() {\n        return this.socketAdapter.reconnectAfterMs;\n    }\n    get sendBuffer() {\n        return this.socketAdapter.sendBuffer;\n    }\n    get stateChangeCallbacks() {\n        return this.socketAdapter.stateChangeCallbacks;\n    }\n    /**\n     * Initializes the Socket.\n     *\n     * @param endPoint The string WebSocket endpoint, ie, \"ws://example.com/socket\", \"wss://example.com\", \"/socket\" (inherited host & protocol)\n     * @param options.transport The Websocket Transport, for example WebSocket. This can be a custom implementation\n     * @param options.timeout The default timeout in milliseconds to trigger push timeouts.\n     * @param options.params The optional params to pass when connecting.\n     * @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future.\n     * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message.\n     * @param options.heartbeatCallback The optional function to handle heartbeat status and latency.\n     * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) }\n     * @param options.logLevel Sets the log level for Realtime\n     * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload))\n     * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode.\n     * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off.\n     * @param options.worker Use Web Worker to set a side flow. Defaults to false.\n     * @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive.\n     * @param options.vsn The protocol version to use when connecting. Supported versions are \"1.0.0\" and \"2.0.0\". Defaults to \"2.0.0\".\n     *\n     * @category Realtime\n     *\n     * @example Using supabase-js (recommended)\n     * ```ts\n     * import { createClient } from '@supabase/supabase-js'\n     *\n     * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n     * const channel = supabase.channel('room1')\n     * channel\n     *   .on('broadcast', { event: 'cursor-pos' }, (payload) => console.log(payload))\n     *   .subscribe()\n     * ```\n     *\n     * @example Standalone import for bundle-sensitive environments\n     * ```ts\n     * import RealtimeClient from '@supabase/realtime-js'\n     *\n     * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', {\n     *   params: { apikey: 'your-publishable-key' },\n     * })\n     * client.connect()\n     * ```\n     */\n    constructor(endPoint, options) {\n        var _a;\n        this.channels = new Array();\n        this.accessTokenValue = null;\n        this.accessToken = null;\n        this.apiKey = null;\n        this.httpEndpoint = '';\n        /** @deprecated headers cannot be set on websocket connections */\n        this.headers = {};\n        this.params = {};\n        this.ref = 0;\n        this.serializer = new Serializer();\n        this._manuallySetToken = false;\n        this._authPromise = null;\n        this._authGeneration = 0;\n        this._workerHeartbeatTimer = undefined;\n        this._pendingWorkerHeartbeatRef = null;\n        this._pendingDisconnectTimer = null;\n        this._disconnectOnEmptyChannelsAfterMs = 0;\n        /**\n         * Use either custom fetch, if provided, or default fetch to make HTTP requests\n         *\n         * @internal\n         */\n        this._resolveFetch = (customFetch) => {\n            if (customFetch) {\n                return (...args) => customFetch(...args);\n            }\n            return (...args) => fetch(...args);\n        };\n        // Validate required parameters\n        if (!((_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.apikey)) {\n            throw new Error('API key is required to connect to Realtime');\n        }\n        this.apiKey = options.params.apikey;\n        const socketAdapterOptions = this._initializeOptions(options);\n        this.socketAdapter = new SocketAdapter(endPoint, socketAdapterOptions);\n        this.httpEndpoint = httpEndpointURL(endPoint);\n        this.fetch = this._resolveFetch(options === null || options === void 0 ? void 0 : options.fetch);\n    }\n    /**\n     * Connects the socket, unless already connected.\n     *\n     * @category Realtime\n     */\n    connect() {\n        // Skip if already connecting, disconnecting, or connected\n        if (this.isConnecting() || this.isDisconnecting() || this.isConnected()) {\n            return;\n        }\n        // Trigger auth if needed and not already in progress\n        // This ensures auth is called for standalone RealtimeClient usage\n        // while avoiding race conditions with SupabaseClient's immediate setAuth call\n        if (this.accessToken && !this._authPromise) {\n            this._setAuthSafely('connect');\n        }\n        this._setupConnectionHandlers();\n        try {\n            this.socketAdapter.connect();\n        }\n        catch (error) {\n            const errorMessage = error.message;\n            throw new Error(`WebSocket not available: ${errorMessage}`);\n        }\n        this._handleNodeJsRaceCondition();\n    }\n    /**\n     * Returns the URL of the websocket.\n     * @returns string The URL of the websocket.\n     *\n     * @category Realtime\n     */\n    endpointURL() {\n        return this.socketAdapter.endPointURL();\n    }\n    /**\n     * Disconnects the socket.\n     *\n     * @param code A numeric status code to send on disconnect.\n     * @param reason A custom reason for the disconnect.\n     *\n     * @category Realtime\n     */\n    async disconnect(code, reason) {\n        this._cancelPendingDisconnect();\n        if (this.isDisconnecting()) {\n            return 'ok';\n        }\n        return await this.socketAdapter.disconnect(() => {\n            clearInterval(this._workerHeartbeatTimer);\n            this._terminateWorker();\n        }, code, reason);\n    }\n    /**\n     * Returns all created channels\n     *\n     * @category Realtime\n     */\n    getChannels() {\n        return this.channels;\n    }\n    /**\n     * Unsubscribes, removes and tears down a single channel\n     * @param channel A RealtimeChannel instance\n     *\n     * @category Realtime\n     */\n    async removeChannel(channel) {\n        const status = await channel.unsubscribe();\n        if (status === 'ok') {\n            channel.teardown();\n        }\n        return status;\n    }\n    /**\n     * Unsubscribes, removes and tears down all channels\n     *\n     * @category Realtime\n     */\n    async removeAllChannels() {\n        const promises = this.channels.map(async (channel) => {\n            const result = await channel.unsubscribe();\n            channel.teardown();\n            return result;\n        });\n        const result = await Promise.all(promises);\n        await this.disconnect();\n        return result;\n    }\n    /**\n     * Logs the message.\n     *\n     * For customized logging, `this.logger` can be overridden in Client constructor.\n     *\n     * @category Realtime\n     */\n    log(kind, msg, data) {\n        this.socketAdapter.log(kind, msg, data);\n    }\n    /**\n     * Returns true if a custom `logger` has been configured on this client.\n     *\n     * @category Realtime\n     */\n    hasLogger() {\n        return this.socketAdapter.hasLogger();\n    }\n    /**\n     * Returns the current state of the socket.\n     *\n     * @category Realtime\n     */\n    connectionState() {\n        return this.socketAdapter.connectionState() || CONNECTION_STATE.closed;\n    }\n    /**\n     * Returns `true` is the connection is open.\n     *\n     * @category Realtime\n     */\n    isConnected() {\n        return this.socketAdapter.isConnected();\n    }\n    /**\n     * Returns `true` if the connection is currently connecting.\n     *\n     * @category Realtime\n     */\n    isConnecting() {\n        return this.socketAdapter.isConnecting();\n    }\n    /**\n     * Returns `true` if the connection is currently disconnecting.\n     *\n     * @category Realtime\n     */\n    isDisconnecting() {\n        return this.socketAdapter.isDisconnecting();\n    }\n    /**\n     * Creates (or reuses) a {@link RealtimeChannel} for the provided topic.\n     *\n     * Topics are automatically prefixed with `realtime:` to match the Realtime service.\n     * If a channel with the same topic already exists it will be returned instead of creating\n     * a duplicate connection.\n     *\n     * @category Realtime\n     */\n    channel(topic, params = { config: {} }) {\n        const realtimeTopic = `realtime:${topic}`;\n        const exists = this.getChannels().find((c) => c.topic === realtimeTopic);\n        if (!exists) {\n            const chan = new RealtimeChannel(`realtime:${topic}`, params, this);\n            this._cancelPendingDisconnect();\n            this.channels.push(chan);\n            return chan;\n        }\n        else {\n            return exists;\n        }\n    }\n    /**\n     * Push out a message if the socket is connected.\n     *\n     * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established.\n     *\n     * @category Realtime\n     */\n    push(data) {\n        this.socketAdapter.push(data);\n    }\n    /**\n     * Sets the JWT access token used for channel subscription authorization and Realtime RLS.\n     *\n     * If param is null it will use the `accessToken` callback function or the token set on the client.\n     *\n     * On callback used, it will set the value of the token internal to the client.\n     *\n     * When a token is explicitly provided AND no `accessToken` callback is configured,\n     * it will be preserved across channel operations (including removeChannel and\n     * resubscribe) and the client stays in manual-token mode.\n     *\n     * When an `accessToken` callback IS configured, the callback is the source of truth:\n     * the client remains in callback mode and continues to refresh from it on heartbeat,\n     * even after a bootstrap/override `setAuth(token)` call.\n     *\n     * @param token A JWT string to override the token set on the client.\n     *\n     * @example Setting the authorization header\n     * // Use a manual token (preserved across resubscribes when no accessToken callback is set)\n     * client.realtime.setAuth('my-custom-jwt')\n     *\n     * // Switch back to using the accessToken callback\n     * client.realtime.setAuth()\n     *\n     * @category Realtime\n     */\n    async setAuth(token = null) {\n        const authGeneration = ++this._authGeneration;\n        const authPromise = this._performAuth(token, authGeneration);\n        if (authGeneration === this._authGeneration) {\n            this._authPromise = authPromise;\n        }\n        try {\n            await authPromise;\n        }\n        finally {\n            if (this._authPromise === authPromise) {\n                this._authPromise = null;\n            }\n        }\n    }\n    /**\n     * Returns true if the current access token was explicitly set via setAuth(token),\n     * false if it was obtained via the accessToken callback.\n     * @internal\n     */\n    _isManualToken() {\n        return this._manuallySetToken;\n    }\n    /**\n     * Sends a heartbeat message if the socket is connected.\n     *\n     * @category Realtime\n     */\n    async sendHeartbeat() {\n        this.socketAdapter.sendHeartbeat();\n    }\n    /**\n     * Sets a callback that receives lifecycle events for internal heartbeat messages.\n     * Useful for instrumenting connection health (e.g. sent/ok/timeout).\n     *\n     * @category Realtime\n     */\n    onHeartbeat(callback) {\n        this.socketAdapter.heartbeatCallback = this._wrapHeartbeatCallback(callback);\n    }\n    /**\n     * Return the next message ref, accounting for overflows\n     *\n     * @internal\n     */\n    _makeRef() {\n        return this.socketAdapter.makeRef();\n    }\n    /**\n     * Removes a channel from RealtimeClient\n     *\n     * @param channel An open subscription.\n     *\n     * @internal\n     */\n    _remove(channel) {\n        this.channels = this.channels.filter((c) => c.topic !== channel.topic);\n        if (this.channels.length === 0) {\n            this.log('transport', 'no channels remaining, scheduling disconnect');\n            this._schedulePendingDisconnect();\n        }\n    }\n    /** @internal */\n    _schedulePendingDisconnect() {\n        this._cancelPendingDisconnect();\n        if (this._disconnectOnEmptyChannelsAfterMs === 0) {\n            this.log('transport', 'disconnecting immediately - no channels');\n            this.disconnect();\n            return;\n        }\n        this._pendingDisconnectTimer = setTimeout(() => {\n            this._pendingDisconnectTimer = null;\n            if (this.channels.length === 0) {\n                this.log('transport', 'deferred disconnect fired - no channels, disconnecting');\n                this.disconnect();\n            }\n        }, this._disconnectOnEmptyChannelsAfterMs);\n        this.log('transport', `deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`);\n    }\n    /** @internal */\n    _cancelPendingDisconnect() {\n        if (this._pendingDisconnectTimer !== null) {\n            this.log('transport', 'pending disconnect cancelled - channel activity detected');\n            clearTimeout(this._pendingDisconnectTimer);\n            this._pendingDisconnectTimer = null;\n        }\n    }\n    /**\n     * Perform the actual auth operation\n     * @internal\n     */\n    async _performAuth(token, authGeneration) {\n        let tokenToSend;\n        let isManualToken = false;\n        if (token) {\n            tokenToSend = token;\n            // Track if this is a manually-provided token\n            isManualToken = true;\n        }\n        else if (this.accessToken) {\n            // Call the accessToken callback to get fresh token\n            try {\n                tokenToSend = await this.accessToken();\n            }\n            catch (e) {\n                this.log('error', 'Error fetching access token from callback', e);\n                // Fall back to cached value if callback fails\n                tokenToSend = this.accessTokenValue;\n            }\n        }\n        else {\n            tokenToSend = this.accessTokenValue;\n        }\n        if (authGeneration !== this._authGeneration) {\n            return;\n        }\n        // Track whether this token was manually set or fetched via callback.\n        // The callback is the source of truth for token refresh\n        if (this.accessToken) {\n            this._manuallySetToken = false;\n        }\n        else if (isManualToken) {\n            this._manuallySetToken = true;\n        }\n        if (this.accessTokenValue != tokenToSend) {\n            this.accessTokenValue = tokenToSend;\n            this.channels.forEach((channel) => {\n                const payload = {\n                    access_token: tokenToSend,\n                    version: DEFAULT_VERSION,\n                };\n                channel.updateJoinPayload(payload);\n                if (channel.joinedOnce && channel.channelAdapter.isJoined()) {\n                    channel.channelAdapter.push(CHANNEL_EVENTS.access_token, {\n                        access_token: tokenToSend,\n                    });\n                }\n            });\n        }\n    }\n    /**\n     * Wait for any in-flight auth operations to complete\n     * @internal\n     */\n    async _waitForAuthIfNeeded() {\n        if (this._authPromise) {\n            await this._authPromise;\n        }\n    }\n    /**\n     * Safely call setAuth with standardized error handling\n     * @internal\n     */\n    _setAuthSafely(context = 'general') {\n        // Only refresh auth if using callback-based tokens\n        if (!this._isManualToken()) {\n            this.setAuth().catch((e) => {\n                this.log('error', `Error setting auth in ${context}`, e);\n            });\n        }\n    }\n    /** @internal */\n    _setupConnectionHandlers() {\n        this.socketAdapter.onOpen(() => {\n            const authPromise = this._authPromise ||\n                (this.accessToken && !this.accessTokenValue ? this.setAuth() : Promise.resolve());\n            authPromise.catch((e) => {\n                this.log('error', 'error waiting for auth on connect', e);\n            });\n            if (this.worker && !this.workerRef) {\n                this._startWorkerHeartbeat();\n            }\n        });\n        this.socketAdapter.onClose(() => {\n            if (this.worker && this.workerRef) {\n                this._terminateWorker();\n            }\n        });\n        this.socketAdapter.onMessage((message) => {\n            if (message.ref && message.ref === this._pendingWorkerHeartbeatRef) {\n                this._pendingWorkerHeartbeatRef = null;\n            }\n        });\n    }\n    /** @internal */\n    _handleNodeJsRaceCondition() {\n        if (this.socketAdapter.isConnected()) {\n            // hack: ensure onConnOpen is called\n            this.socketAdapter.getSocket().onConnOpen();\n        }\n    }\n    /** @internal */\n    _wrapHeartbeatCallback(heartbeatCallback) {\n        return (status, latency) => {\n            if (status === 'disconnected')\n                return;\n            if (status == 'sent')\n                this._setAuthSafely();\n            if (heartbeatCallback)\n                heartbeatCallback(status, latency);\n        };\n    }\n    /** @internal */\n    _startWorkerHeartbeat() {\n        if (this.workerUrl) {\n            this.log('worker', `starting worker for from ${this.workerUrl}`);\n        }\n        else {\n            this.log('worker', `starting default worker`);\n        }\n        const objectUrl = this._workerObjectUrl(this.workerUrl);\n        this.workerRef = new Worker(objectUrl);\n        this.workerRef.onerror = (error) => {\n            this.log('worker', 'worker error', error.message);\n            this._terminateWorker();\n            this.disconnect();\n        };\n        this.workerRef.onmessage = (event) => {\n            if (event.data.event === 'keepAlive') {\n                this.sendHeartbeat();\n            }\n        };\n        this.workerRef.postMessage({\n            event: 'start',\n            interval: this.heartbeatIntervalMs,\n        });\n    }\n    /**\n     * Terminate the Web Worker and clear the reference\n     * @internal\n     */\n    _terminateWorker() {\n        if (this.workerRef) {\n            this.log('worker', 'terminating worker');\n            this.workerRef.terminate();\n            this.workerRef = undefined;\n        }\n    }\n    /** @internal */\n    _workerObjectUrl(url) {\n        let result_url;\n        if (url) {\n            result_url = url;\n        }\n        else {\n            const blob = new Blob([WORKER_SCRIPT], { type: 'application/javascript' });\n            result_url = URL.createObjectURL(blob);\n        }\n        return result_url;\n    }\n    /**\n     * Initialize socket options with defaults\n     * @internal\n     */\n    _initializeOptions(options) {\n        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;\n        this.worker = (_a = options === null || options === void 0 ? void 0 : options.worker) !== null && _a !== void 0 ? _a : false;\n        this.accessToken = (_b = options === null || options === void 0 ? void 0 : options.accessToken) !== null && _b !== void 0 ? _b : null;\n        const result = {};\n        result.timeout = (_c = options === null || options === void 0 ? void 0 : options.timeout) !== null && _c !== void 0 ? _c : DEFAULT_TIMEOUT;\n        result.heartbeatIntervalMs =\n            (_d = options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) !== null && _d !== void 0 ? _d : CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL;\n        this._disconnectOnEmptyChannelsAfterMs =\n            (_e = options === null || options === void 0 ? void 0 : options.disconnectOnEmptyChannelsAfterMs) !== null && _e !== void 0 ? _e : 2 * ((_f = options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) !== null && _f !== void 0 ? _f : CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL);\n        // @ts-ignore - mismatch between phoenix and supabase\n        result.transport = (_g = options === null || options === void 0 ? void 0 : options.transport) !== null && _g !== void 0 ? _g : WebSocketFactory.getWebSocketConstructor();\n        result.params = options === null || options === void 0 ? void 0 : options.params;\n        result.logger = options === null || options === void 0 ? void 0 : options.logger;\n        result.heartbeatCallback = this._wrapHeartbeatCallback(options === null || options === void 0 ? void 0 : options.heartbeatCallback);\n        result.sessionStorage = (_h = options === null || options === void 0 ? void 0 : options.sessionStorage) !== null && _h !== void 0 ? _h : resolveSessionStorage();\n        result.reconnectAfterMs =\n            (_j = options === null || options === void 0 ? void 0 : options.reconnectAfterMs) !== null && _j !== void 0 ? _j : ((tries) => {\n                return RECONNECT_INTERVALS[tries - 1] || DEFAULT_RECONNECT_FALLBACK;\n            });\n        let defaultEncode;\n        let defaultDecode;\n        const vsn = (_k = options === null || options === void 0 ? void 0 : options.vsn) !== null && _k !== void 0 ? _k : DEFAULT_VSN;\n        switch (vsn) {\n            case VSN_1_0_0:\n                defaultEncode = (payload, callback) => {\n                    return callback(JSON.stringify(payload));\n                };\n                defaultDecode = (payload, callback) => {\n                    return callback(JSON.parse(payload));\n                };\n                break;\n            case VSN_2_0_0:\n                defaultEncode = this.serializer.encode.bind(this.serializer);\n                defaultDecode = this.serializer.decode.bind(this.serializer);\n                break;\n            default:\n                throw new Error(`Unsupported serializer version: ${result.vsn}`);\n        }\n        result.vsn = vsn;\n        result.encode = (_l = options === null || options === void 0 ? void 0 : options.encode) !== null && _l !== void 0 ? _l : defaultEncode;\n        result.decode = (_m = options === null || options === void 0 ? void 0 : options.decode) !== null && _m !== void 0 ? _m : defaultDecode;\n        result.beforeReconnect = this._reconnectAuth.bind(this);\n        if ((options === null || options === void 0 ? void 0 : options.logLevel) || (options === null || options === void 0 ? void 0 : options.log_level)) {\n            this.logLevel = options.logLevel || options.log_level;\n            result.params = Object.assign(Object.assign({}, result.params), { log_level: this.logLevel });\n        }\n        // Handle worker setup\n        if (this.worker) {\n            if (typeof window !== 'undefined' && !window.Worker) {\n                throw new Error('Web Worker is not supported');\n            }\n            this.workerUrl = options === null || options === void 0 ? void 0 : options.workerUrl;\n            result.autoSendHeartbeat = !this.worker;\n        }\n        return result;\n    }\n    /** @internal */\n    async _reconnectAuth() {\n        await this._waitForAuthIfNeeded();\n        if (!this.isConnected()) {\n            this.connect();\n        }\n    }\n}\n//# sourceMappingURL=RealtimeClient.js.map","// src/errors/IcebergError.ts\nvar IcebergError = class extends Error {\n  constructor(message, opts) {\n    super(message);\n    this.name = \"IcebergError\";\n    this.status = opts.status;\n    this.icebergType = opts.icebergType;\n    this.icebergCode = opts.icebergCode;\n    this.details = opts.details;\n    this.isCommitStateUnknown = opts.icebergType === \"CommitStateUnknownException\" || [500, 502, 504].includes(opts.status) && opts.icebergType?.includes(\"CommitState\") === true;\n  }\n  /**\n   * Returns true if the error is a 404 Not Found error.\n   */\n  isNotFound() {\n    return this.status === 404;\n  }\n  /**\n   * Returns true if the error is a 409 Conflict error.\n   */\n  isConflict() {\n    return this.status === 409;\n  }\n  /**\n   * Returns true if the error is a 419 Authentication Timeout error.\n   */\n  isAuthenticationTimeout() {\n    return this.status === 419;\n  }\n};\n\n// src/utils/url.ts\nfunction buildUrl(baseUrl, path, query) {\n  const url = new URL(path, baseUrl);\n  if (query) {\n    for (const [key, value] of Object.entries(query)) {\n      if (value !== void 0) {\n        url.searchParams.set(key, value);\n      }\n    }\n  }\n  return url.toString();\n}\n\n// src/http/createFetchClient.ts\nasync function buildAuthHeaders(auth) {\n  if (!auth || auth.type === \"none\") {\n    return {};\n  }\n  if (auth.type === \"bearer\") {\n    return { Authorization: `Bearer ${auth.token}` };\n  }\n  if (auth.type === \"header\") {\n    return { [auth.name]: auth.value };\n  }\n  if (auth.type === \"custom\") {\n    return await auth.getHeaders();\n  }\n  return {};\n}\nfunction createFetchClient(options) {\n  const fetchFn = options.fetchImpl ?? globalThis.fetch;\n  return {\n    async request({\n      method,\n      path,\n      query,\n      body,\n      headers\n    }) {\n      const url = buildUrl(options.baseUrl, path, query);\n      const authHeaders = await buildAuthHeaders(options.auth);\n      const res = await fetchFn(url, {\n        method,\n        headers: {\n          ...body ? { \"Content-Type\": \"application/json\" } : {},\n          ...authHeaders,\n          ...headers\n        },\n        body: body ? JSON.stringify(body) : void 0\n      });\n      const text = await res.text();\n      const isJson = (res.headers.get(\"content-type\") || \"\").includes(\"application/json\");\n      const data = isJson && text ? JSON.parse(text) : text;\n      if (!res.ok) {\n        const errBody = isJson ? data : void 0;\n        const errorDetail = errBody?.error;\n        throw new IcebergError(\n          errorDetail?.message ?? `Request failed with status ${res.status}`,\n          {\n            status: res.status,\n            icebergType: errorDetail?.type,\n            icebergCode: errorDetail?.code,\n            details: errBody\n          }\n        );\n      }\n      return { status: res.status, headers: res.headers, data };\n    }\n  };\n}\n\n// src/catalog/namespaces.ts\nfunction namespaceToPath(namespace) {\n  return namespace.join(\"\u001f\");\n}\nvar NamespaceOperations = class {\n  constructor(client, prefix = \"\") {\n    this.client = client;\n    this.prefix = prefix;\n  }\n  async listNamespaces(parent) {\n    const query = parent ? { parent: namespaceToPath(parent.namespace) } : void 0;\n    const response = await this.client.request({\n      method: \"GET\",\n      path: `${this.prefix}/namespaces`,\n      query\n    });\n    return response.data.namespaces.map((ns) => ({ namespace: ns }));\n  }\n  async createNamespace(id, metadata) {\n    const request = {\n      namespace: id.namespace,\n      properties: metadata?.properties\n    };\n    const response = await this.client.request({\n      method: \"POST\",\n      path: `${this.prefix}/namespaces`,\n      body: request\n    });\n    return response.data;\n  }\n  async dropNamespace(id) {\n    await this.client.request({\n      method: \"DELETE\",\n      path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}`\n    });\n  }\n  async loadNamespaceMetadata(id) {\n    const response = await this.client.request({\n      method: \"GET\",\n      path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}`\n    });\n    return {\n      properties: response.data.properties\n    };\n  }\n  async namespaceExists(id) {\n    try {\n      await this.client.request({\n        method: \"HEAD\",\n        path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}`\n      });\n      return true;\n    } catch (error) {\n      if (error instanceof IcebergError && error.status === 404) {\n        return false;\n      }\n      throw error;\n    }\n  }\n  async createNamespaceIfNotExists(id, metadata) {\n    try {\n      return await this.createNamespace(id, metadata);\n    } catch (error) {\n      if (error instanceof IcebergError && error.status === 409) {\n        return;\n      }\n      throw error;\n    }\n  }\n};\n\n// src/catalog/tables.ts\nfunction namespaceToPath2(namespace) {\n  return namespace.join(\"\u001f\");\n}\nvar TableOperations = class {\n  constructor(client, prefix = \"\", accessDelegation) {\n    this.client = client;\n    this.prefix = prefix;\n    this.accessDelegation = accessDelegation;\n  }\n  async listTables(namespace) {\n    const response = await this.client.request({\n      method: \"GET\",\n      path: `${this.prefix}/namespaces/${namespaceToPath2(namespace.namespace)}/tables`\n    });\n    return response.data.identifiers;\n  }\n  async createTable(namespace, request) {\n    const headers = {};\n    if (this.accessDelegation) {\n      headers[\"X-Iceberg-Access-Delegation\"] = this.accessDelegation;\n    }\n    const response = await this.client.request({\n      method: \"POST\",\n      path: `${this.prefix}/namespaces/${namespaceToPath2(namespace.namespace)}/tables`,\n      body: request,\n      headers\n    });\n    return response.data.metadata;\n  }\n  async updateTable(id, request) {\n    const response = await this.client.request({\n      method: \"POST\",\n      path: `${this.prefix}/namespaces/${namespaceToPath2(id.namespace)}/tables/${id.name}`,\n      body: request\n    });\n    return {\n      \"metadata-location\": response.data[\"metadata-location\"],\n      metadata: response.data.metadata\n    };\n  }\n  async dropTable(id, options) {\n    await this.client.request({\n      method: \"DELETE\",\n      path: `${this.prefix}/namespaces/${namespaceToPath2(id.namespace)}/tables/${id.name}`,\n      query: { purgeRequested: String(options?.purge ?? false) }\n    });\n  }\n  async loadTable(id) {\n    const headers = {};\n    if (this.accessDelegation) {\n      headers[\"X-Iceberg-Access-Delegation\"] = this.accessDelegation;\n    }\n    const response = await this.client.request({\n      method: \"GET\",\n      path: `${this.prefix}/namespaces/${namespaceToPath2(id.namespace)}/tables/${id.name}`,\n      headers\n    });\n    return response.data.metadata;\n  }\n  async tableExists(id) {\n    const headers = {};\n    if (this.accessDelegation) {\n      headers[\"X-Iceberg-Access-Delegation\"] = this.accessDelegation;\n    }\n    try {\n      await this.client.request({\n        method: \"HEAD\",\n        path: `${this.prefix}/namespaces/${namespaceToPath2(id.namespace)}/tables/${id.name}`,\n        headers\n      });\n      return true;\n    } catch (error) {\n      if (error instanceof IcebergError && error.status === 404) {\n        return false;\n      }\n      throw error;\n    }\n  }\n  async createTableIfNotExists(namespace, request) {\n    try {\n      return await this.createTable(namespace, request);\n    } catch (error) {\n      if (error instanceof IcebergError && error.status === 409) {\n        return await this.loadTable({ namespace: namespace.namespace, name: request.name });\n      }\n      throw error;\n    }\n  }\n};\n\n// src/catalog/IcebergRestCatalog.ts\nvar IcebergRestCatalog = class {\n  /**\n   * Creates a new Iceberg REST Catalog client.\n   *\n   * @param options - Configuration options for the catalog client\n   */\n  constructor(options) {\n    let prefix = \"v1\";\n    if (options.catalogName) {\n      prefix += `/${options.catalogName}`;\n    }\n    const baseUrl = options.baseUrl.endsWith(\"/\") ? options.baseUrl : `${options.baseUrl}/`;\n    this.client = createFetchClient({\n      baseUrl,\n      auth: options.auth,\n      fetchImpl: options.fetch\n    });\n    this.accessDelegation = options.accessDelegation?.join(\",\");\n    this.namespaceOps = new NamespaceOperations(this.client, prefix);\n    this.tableOps = new TableOperations(this.client, prefix, this.accessDelegation);\n  }\n  /**\n   * Lists all namespaces in the catalog.\n   *\n   * @param parent - Optional parent namespace to list children under\n   * @returns Array of namespace identifiers\n   *\n   * @example\n   * ```typescript\n   * // List all top-level namespaces\n   * const namespaces = await catalog.listNamespaces();\n   *\n   * // List namespaces under a parent\n   * const children = await catalog.listNamespaces({ namespace: ['analytics'] });\n   * ```\n   */\n  async listNamespaces(parent) {\n    return this.namespaceOps.listNamespaces(parent);\n  }\n  /**\n   * Creates a new namespace in the catalog.\n   *\n   * @param id - Namespace identifier to create\n   * @param metadata - Optional metadata properties for the namespace\n   * @returns Response containing the created namespace and its properties\n   *\n   * @example\n   * ```typescript\n   * const response = await catalog.createNamespace(\n   *   { namespace: ['analytics'] },\n   *   { properties: { owner: 'data-team' } }\n   * );\n   * console.log(response.namespace); // ['analytics']\n   * console.log(response.properties); // { owner: 'data-team', ... }\n   * ```\n   */\n  async createNamespace(id, metadata) {\n    return this.namespaceOps.createNamespace(id, metadata);\n  }\n  /**\n   * Drops a namespace from the catalog.\n   *\n   * The namespace must be empty (contain no tables) before it can be dropped.\n   *\n   * @param id - Namespace identifier to drop\n   *\n   * @example\n   * ```typescript\n   * await catalog.dropNamespace({ namespace: ['analytics'] });\n   * ```\n   */\n  async dropNamespace(id) {\n    await this.namespaceOps.dropNamespace(id);\n  }\n  /**\n   * Loads metadata for a namespace.\n   *\n   * @param id - Namespace identifier to load\n   * @returns Namespace metadata including properties\n   *\n   * @example\n   * ```typescript\n   * const metadata = await catalog.loadNamespaceMetadata({ namespace: ['analytics'] });\n   * console.log(metadata.properties);\n   * ```\n   */\n  async loadNamespaceMetadata(id) {\n    return this.namespaceOps.loadNamespaceMetadata(id);\n  }\n  /**\n   * Lists all tables in a namespace.\n   *\n   * @param namespace - Namespace identifier to list tables from\n   * @returns Array of table identifiers\n   *\n   * @example\n   * ```typescript\n   * const tables = await catalog.listTables({ namespace: ['analytics'] });\n   * console.log(tables); // [{ namespace: ['analytics'], name: 'events' }, ...]\n   * ```\n   */\n  async listTables(namespace) {\n    return this.tableOps.listTables(namespace);\n  }\n  /**\n   * Creates a new table in the catalog.\n   *\n   * @param namespace - Namespace to create the table in\n   * @param request - Table creation request including name, schema, partition spec, etc.\n   * @returns Table metadata for the created table\n   *\n   * @example\n   * ```typescript\n   * const metadata = await catalog.createTable(\n   *   { namespace: ['analytics'] },\n   *   {\n   *     name: 'events',\n   *     schema: {\n   *       type: 'struct',\n   *       fields: [\n   *         { id: 1, name: 'id', type: 'long', required: true },\n   *         { id: 2, name: 'timestamp', type: 'timestamp', required: true }\n   *       ],\n   *       'schema-id': 0\n   *     },\n   *     'partition-spec': {\n   *       'spec-id': 0,\n   *       fields: [\n   *         { source_id: 2, field_id: 1000, name: 'ts_day', transform: 'day' }\n   *       ]\n   *     }\n   *   }\n   * );\n   * ```\n   */\n  async createTable(namespace, request) {\n    return this.tableOps.createTable(namespace, request);\n  }\n  /**\n   * Updates an existing table's metadata.\n   *\n   * Can update the schema, partition spec, or properties of a table.\n   *\n   * @param id - Table identifier to update\n   * @param request - Update request with fields to modify\n   * @returns Response containing the metadata location and updated table metadata\n   *\n   * @example\n   * ```typescript\n   * const response = await catalog.updateTable(\n   *   { namespace: ['analytics'], name: 'events' },\n   *   {\n   *     properties: { 'read.split.target-size': '134217728' }\n   *   }\n   * );\n   * console.log(response['metadata-location']); // s3://...\n   * console.log(response.metadata); // TableMetadata object\n   * ```\n   */\n  async updateTable(id, request) {\n    return this.tableOps.updateTable(id, request);\n  }\n  /**\n   * Drops a table from the catalog.\n   *\n   * @param id - Table identifier to drop\n   *\n   * @example\n   * ```typescript\n   * await catalog.dropTable({ namespace: ['analytics'], name: 'events' });\n   * ```\n   */\n  async dropTable(id, options) {\n    await this.tableOps.dropTable(id, options);\n  }\n  /**\n   * Loads metadata for a table.\n   *\n   * @param id - Table identifier to load\n   * @returns Table metadata including schema, partition spec, location, etc.\n   *\n   * @example\n   * ```typescript\n   * const metadata = await catalog.loadTable({ namespace: ['analytics'], name: 'events' });\n   * console.log(metadata.schema);\n   * console.log(metadata.location);\n   * ```\n   */\n  async loadTable(id) {\n    return this.tableOps.loadTable(id);\n  }\n  /**\n   * Checks if a namespace exists in the catalog.\n   *\n   * @param id - Namespace identifier to check\n   * @returns True if the namespace exists, false otherwise\n   *\n   * @example\n   * ```typescript\n   * const exists = await catalog.namespaceExists({ namespace: ['analytics'] });\n   * console.log(exists); // true or false\n   * ```\n   */\n  async namespaceExists(id) {\n    return this.namespaceOps.namespaceExists(id);\n  }\n  /**\n   * Checks if a table exists in the catalog.\n   *\n   * @param id - Table identifier to check\n   * @returns True if the table exists, false otherwise\n   *\n   * @example\n   * ```typescript\n   * const exists = await catalog.tableExists({ namespace: ['analytics'], name: 'events' });\n   * console.log(exists); // true or false\n   * ```\n   */\n  async tableExists(id) {\n    return this.tableOps.tableExists(id);\n  }\n  /**\n   * Creates a namespace if it does not exist.\n   *\n   * If the namespace already exists, returns void. If created, returns the response.\n   *\n   * @param id - Namespace identifier to create\n   * @param metadata - Optional metadata properties for the namespace\n   * @returns Response containing the created namespace and its properties, or void if it already exists\n   *\n   * @example\n   * ```typescript\n   * const response = await catalog.createNamespaceIfNotExists(\n   *   { namespace: ['analytics'] },\n   *   { properties: { owner: 'data-team' } }\n   * );\n   * if (response) {\n   *   console.log('Created:', response.namespace);\n   * } else {\n   *   console.log('Already exists');\n   * }\n   * ```\n   */\n  async createNamespaceIfNotExists(id, metadata) {\n    return this.namespaceOps.createNamespaceIfNotExists(id, metadata);\n  }\n  /**\n   * Creates a table if it does not exist.\n   *\n   * If the table already exists, returns its metadata instead.\n   *\n   * @param namespace - Namespace to create the table in\n   * @param request - Table creation request including name, schema, partition spec, etc.\n   * @returns Table metadata for the created or existing table\n   *\n   * @example\n   * ```typescript\n   * const metadata = await catalog.createTableIfNotExists(\n   *   { namespace: ['analytics'] },\n   *   {\n   *     name: 'events',\n   *     schema: {\n   *       type: 'struct',\n   *       fields: [\n   *         { id: 1, name: 'id', type: 'long', required: true },\n   *         { id: 2, name: 'timestamp', type: 'timestamp', required: true }\n   *       ],\n   *       'schema-id': 0\n   *     }\n   *   }\n   * );\n   * ```\n   */\n  async createTableIfNotExists(namespace, request) {\n    return this.tableOps.createTableIfNotExists(namespace, request);\n  }\n};\n\n// src/catalog/types.ts\nvar DECIMAL_REGEX = /^decimal\\s*\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)$/;\nvar FIXED_REGEX = /^fixed\\s*\\[\\s*(\\d+)\\s*\\]$/;\nfunction parseDecimalType(type) {\n  const match = type.match(DECIMAL_REGEX);\n  if (!match) return null;\n  return {\n    precision: parseInt(match[1], 10),\n    scale: parseInt(match[2], 10)\n  };\n}\nfunction parseFixedType(type) {\n  const match = type.match(FIXED_REGEX);\n  if (!match) return null;\n  return {\n    length: parseInt(match[1], 10)\n  };\n}\nfunction isDecimalType(type) {\n  return DECIMAL_REGEX.test(type);\n}\nfunction isFixedType(type) {\n  return FIXED_REGEX.test(type);\n}\nfunction typesEqual(a, b) {\n  const decimalA = parseDecimalType(a);\n  const decimalB = parseDecimalType(b);\n  if (decimalA && decimalB) {\n    return decimalA.precision === decimalB.precision && decimalA.scale === decimalB.scale;\n  }\n  const fixedA = parseFixedType(a);\n  const fixedB = parseFixedType(b);\n  if (fixedA && fixedB) {\n    return fixedA.length === fixedB.length;\n  }\n  return a === b;\n}\nfunction getCurrentSchema(metadata) {\n  return metadata.schemas.find((s) => s[\"schema-id\"] === metadata[\"current-schema-id\"]);\n}\n\nexport { IcebergError, IcebergRestCatalog, getCurrentSchema, isDecimalType, isFixedType, parseDecimalType, parseFixedType, typesEqual };\n//# sourceMappingURL=index.mjs.map\n//# sourceMappingURL=index.mjs.map","import { IcebergRestCatalog } from \"iceberg-js\";\n\n//#region \\0@oxc-project+runtime@0.103.0/helpers/typeof.js\nfunction _typeof(o) {\n\t\"@babel/helpers - typeof\";\n\treturn _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function(o$1) {\n\t\treturn typeof o$1;\n\t} : function(o$1) {\n\t\treturn o$1 && \"function\" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? \"symbol\" : typeof o$1;\n\t}, _typeof(o);\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.103.0/helpers/toPrimitive.js\nfunction toPrimitive(t, r) {\n\tif (\"object\" != _typeof(t) || !t) return t;\n\tvar e = t[Symbol.toPrimitive];\n\tif (void 0 !== e) {\n\t\tvar i = e.call(t, r || \"default\");\n\t\tif (\"object\" != _typeof(i)) return i;\n\t\tthrow new TypeError(\"@@toPrimitive must return a primitive value.\");\n\t}\n\treturn (\"string\" === r ? String : Number)(t);\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.103.0/helpers/toPropertyKey.js\nfunction toPropertyKey(t) {\n\tvar i = toPrimitive(t, \"string\");\n\treturn \"symbol\" == _typeof(i) ? i : i + \"\";\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.103.0/helpers/defineProperty.js\nfunction _defineProperty(e, r, t) {\n\treturn (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n\t\tvalue: t,\n\t\tenumerable: !0,\n\t\tconfigurable: !0,\n\t\twritable: !0\n\t}) : e[r] = t, e;\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.103.0/helpers/objectSpread2.js\nfunction ownKeys(e, r) {\n\tvar t = Object.keys(e);\n\tif (Object.getOwnPropertySymbols) {\n\t\tvar o = Object.getOwnPropertySymbols(e);\n\t\tr && (o = o.filter(function(r$1) {\n\t\t\treturn Object.getOwnPropertyDescriptor(e, r$1).enumerable;\n\t\t})), t.push.apply(t, o);\n\t}\n\treturn t;\n}\nfunction _objectSpread2(e) {\n\tfor (var r = 1; r < arguments.length; r++) {\n\t\tvar t = null != arguments[r] ? arguments[r] : {};\n\t\tr % 2 ? ownKeys(Object(t), !0).forEach(function(r$1) {\n\t\t\t_defineProperty(e, r$1, t[r$1]);\n\t\t}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) {\n\t\t\tObject.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1));\n\t\t});\n\t}\n\treturn e;\n}\n\n//#endregion\n//#region src/lib/common/errors.ts\n/**\n* Base error class for all Storage errors\n* Supports both 'storage' and 'vectors' namespaces\n*/\nvar StorageError = class extends Error {\n\tconstructor(message, namespace = \"storage\", status, statusCode) {\n\t\tsuper(message);\n\t\tthis.__isStorageError = true;\n\t\tthis.namespace = namespace;\n\t\tthis.name = namespace === \"vectors\" ? \"StorageVectorsError\" : \"StorageError\";\n\t\tthis.status = status;\n\t\tthis.statusCode = statusCode;\n\t}\n\ttoJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tmessage: this.message,\n\t\t\tstatus: this.status,\n\t\t\tstatusCode: this.statusCode\n\t\t};\n\t}\n};\n/**\n* Type guard to check if an error is a StorageError\n* @param error - The error to check\n* @returns True if the error is a StorageError\n*/\nfunction isStorageError(error) {\n\treturn typeof error === \"object\" && error !== null && \"__isStorageError\" in error;\n}\n/**\n* API error returned from Storage service\n* Includes HTTP status code and service-specific error code\n*/\nvar StorageApiError = class extends StorageError {\n\tconstructor(message, status, statusCode, namespace = \"storage\", code) {\n\t\tsuper(message, namespace, status, statusCode);\n\t\tthis.name = namespace === \"vectors\" ? \"StorageVectorsApiError\" : \"StorageApiError\";\n\t\tthis.status = status;\n\t\tthis.statusCode = statusCode;\n\t\tthis.code = code;\n\t}\n\ttoJSON() {\n\t\treturn _objectSpread2(_objectSpread2({}, super.toJSON()), {}, { code: this.code });\n\t}\n};\n/**\n* Unknown error that doesn't match expected error patterns\n* Wraps the original error for debugging\n*/\nvar StorageUnknownError = class extends StorageError {\n\tconstructor(message, originalError, namespace = \"storage\") {\n\t\tsuper(message, namespace);\n\t\tthis.name = namespace === \"vectors\" ? \"StorageVectorsUnknownError\" : \"StorageUnknownError\";\n\t\tthis.originalError = originalError;\n\t}\n};\n/**\n* @deprecated Use StorageError with namespace='vectors' instead\n* Alias for backward compatibility with existing vector storage code\n*/\nvar StorageVectorsError = class extends StorageError {\n\tconstructor(message) {\n\t\tsuper(message, \"vectors\");\n\t}\n};\n/**\n* Type guard to check if an error is a StorageVectorsError\n* @param error - The error to check\n* @returns True if the error is a StorageVectorsError\n*/\nfunction isStorageVectorsError(error) {\n\treturn isStorageError(error) && error[\"namespace\"] === \"vectors\";\n}\n/**\n* @deprecated Use StorageApiError with namespace='vectors' instead\n* Alias for backward compatibility with existing vector storage code\n*/\nvar StorageVectorsApiError = class extends StorageApiError {\n\tconstructor(message, status, statusCode) {\n\t\tsuper(message, status, statusCode, \"vectors\");\n\t}\n};\n/**\n* @deprecated Use StorageUnknownError with namespace='vectors' instead\n* Alias for backward compatibility with existing vector storage code\n*/\nvar StorageVectorsUnknownError = class extends StorageUnknownError {\n\tconstructor(message, originalError) {\n\t\tsuper(message, originalError, \"vectors\");\n\t}\n};\n/**\n* Error codes specific to S3 Vectors API\n* Maps AWS service errors to application-friendly error codes\n*/\nlet StorageVectorsErrorCode = /* @__PURE__ */ function(StorageVectorsErrorCode$1) {\n\t/** Internal server fault (HTTP 500) */\n\tStorageVectorsErrorCode$1[\"InternalError\"] = \"InternalError\";\n\t/** Resource already exists / conflict (HTTP 409) */\n\tStorageVectorsErrorCode$1[\"S3VectorConflictException\"] = \"S3VectorConflictException\";\n\t/** Resource not found (HTTP 404) */\n\tStorageVectorsErrorCode$1[\"S3VectorNotFoundException\"] = \"S3VectorNotFoundException\";\n\t/** Delete bucket while not empty (HTTP 400) */\n\tStorageVectorsErrorCode$1[\"S3VectorBucketNotEmpty\"] = \"S3VectorBucketNotEmpty\";\n\t/** Exceeds bucket quota/limit (HTTP 400) */\n\tStorageVectorsErrorCode$1[\"S3VectorMaxBucketsExceeded\"] = \"S3VectorMaxBucketsExceeded\";\n\t/** Exceeds index quota/limit (HTTP 400) */\n\tStorageVectorsErrorCode$1[\"S3VectorMaxIndexesExceeded\"] = \"S3VectorMaxIndexesExceeded\";\n\treturn StorageVectorsErrorCode$1;\n}({});\n\n//#endregion\n//#region src/lib/common/headers.ts\n/**\n* Sets a header with case-insensitive deduplication.\n* Removes any existing headers whose name matches (case-insensitive),\n* then sets the value under the lowercase key. Does not mutate the input object.\n*\n* @param headers - Existing headers object\n* @param name - Header name to set (stored as lowercase)\n* @param value - Header value\n* @returns New headers object with the header set\n*/\nfunction setHeader(headers, name, value) {\n\tconst result = _objectSpread2({}, headers);\n\tconst nameLower = name.toLowerCase();\n\tfor (const key of Object.keys(result)) if (key.toLowerCase() === nameLower) delete result[key];\n\tresult[nameLower] = value;\n\treturn result;\n}\n/**\n* Normalizes all header keys to lowercase with case-insensitive deduplication.\n* When duplicate keys exist (differing only in case), the last value wins.\n* Does not mutate the input object.\n*\n* @param headers - Headers object to normalize\n* @returns New headers object with all keys lowercased\n*/\nfunction normalizeHeaders(headers) {\n\tconst result = {};\n\tfor (const [key, value] of Object.entries(headers)) result[key.toLowerCase()] = value;\n\treturn result;\n}\n\n//#endregion\n//#region src/lib/common/helpers.ts\n/**\n* Resolves the fetch implementation to use\n* Uses custom fetch if provided, otherwise uses native fetch\n*\n* @param customFetch - Optional custom fetch implementation\n* @returns Resolved fetch function\n*/\nconst resolveFetch = (customFetch) => {\n\tif (customFetch) return (...args) => customFetch(...args);\n\treturn (...args) => fetch(...args);\n};\n/**\n* Determine if input is a plain object\n* An object is plain if it's created by either {}, new Object(), or Object.create(null)\n*\n* @param value - Value to check\n* @returns True if value is a plain object\n* @source https://github.com/sindresorhus/is-plain-obj\n*/\nconst isPlainObject = (value) => {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);\n};\n/**\n* Recursively converts object keys from snake_case to camelCase\n* Used for normalizing API responses\n*\n* @param item - Object to convert\n* @returns Converted object with camelCase keys\n*/\nconst recursiveToCamel = (item) => {\n\tif (Array.isArray(item)) return item.map((el) => recursiveToCamel(el));\n\telse if (typeof item === \"function\" || item !== Object(item)) return item;\n\tconst result = {};\n\tObject.entries(item).forEach(([key, value]) => {\n\t\tconst newKey = key.replace(/([-_][a-z])/gi, (c) => c.toUpperCase().replace(/[-_]/g, \"\"));\n\t\tresult[newKey] = recursiveToCamel(value);\n\t});\n\treturn result;\n};\n/**\n* Validates if a given bucket name is valid according to Supabase Storage API rules\n* Mirrors backend validation from: storage/src/storage/limits.ts:isValidBucketName()\n*\n* Rules:\n* - Length: 1-100 characters\n* - Allowed characters: alphanumeric (a-z, A-Z, 0-9), underscore (_), and safe special characters\n* - Safe special characters: ! - . * ' ( ) space & $ @ = ; : + , ?\n* - Forbidden: path separators (/, \\), path traversal (..), leading/trailing whitespace\n*\n* AWS S3 Reference: https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html\n*\n* @param bucketName - The bucket name to validate\n* @returns true if valid, false otherwise\n*/\nconst isValidBucketName = (bucketName) => {\n\tif (!bucketName || typeof bucketName !== \"string\") return false;\n\tif (bucketName.length === 0 || bucketName.length > 100) return false;\n\tif (bucketName.trim() !== bucketName) return false;\n\tif (bucketName.includes(\"/\") || bucketName.includes(\"\\\\\")) return false;\n\treturn /^[\\w!.\\*'() &$@=;:+,?-]+$/.test(bucketName);\n};\n/**\n* Percent-encodes each segment of a storage path so URL delimiters within a\n* key (e.g. `?`, `#`) can't be interpreted as a querystring/fragment start.\n*\n* Splits on `/` so real path separators stay literal — the storage server\n* routes on them and decodes each segment back to the original key.\n*\n* @param path - A bucket id or `bucketId/objectKey` path\n* @returns The path with each `/`-delimited segment percent-encoded\n*/\nconst encodeStoragePath = (path) => path.split(\"/\").map(encodeURIComponent).join(\"/\");\n\n//#endregion\n//#region src/lib/common/fetch.ts\n/**\n* Extracts error message from various error response formats\n* @param err - Error object from API\n* @returns Human-readable error message\n*/\nconst _getErrorMessage = (err) => {\n\tif (typeof err === \"object\" && err !== null) {\n\t\tconst e = err;\n\t\tif (typeof e.msg === \"string\") return e.msg;\n\t\tif (typeof e.message === \"string\") return e.message;\n\t\tif (typeof e.error_description === \"string\") return e.error_description;\n\t\tif (typeof e.error === \"string\") return e.error;\n\t\tif (typeof e.error === \"object\" && e.error !== null) {\n\t\t\tconst nested = e.error;\n\t\t\tif (typeof nested.message === \"string\") return nested.message;\n\t\t}\n\t}\n\treturn JSON.stringify(err);\n};\n/**\n* Handles fetch errors and converts them to Storage error types\n* @param error - The error caught from fetch\n* @param reject - Promise rejection function\n* @param options - Fetch options that may affect error handling\n* @param namespace - Error namespace ('storage' or 'vectors')\n*/\nconst handleError = async (error, reject, options, namespace) => {\n\tif (error !== null && typeof error === \"object\" && \"json\" in error && typeof error.json === \"function\") {\n\t\tconst responseError = error;\n\t\tlet status = parseInt(String(responseError.status), 10);\n\t\tif (!Number.isFinite(status)) status = 500;\n\t\tresponseError.json().then((err) => {\n\t\t\tconst statusCode = (err === null || err === void 0 ? void 0 : err.statusCode) || (err === null || err === void 0 ? void 0 : err.code) || status + \"\";\n\t\t\treject(new StorageApiError(_getErrorMessage(err), status, statusCode, namespace, err === null || err === void 0 ? void 0 : err.code));\n\t\t}).catch(() => {\n\t\t\tconst statusCode = status + \"\";\n\t\t\treject(new StorageApiError(responseError.statusText || `HTTP ${status} error`, status, statusCode, namespace));\n\t\t});\n\t} else reject(new StorageUnknownError(_getErrorMessage(error), error, namespace));\n};\n/**\n* Builds request parameters for fetch calls\n* @param method - HTTP method\n* @param options - Custom fetch options\n* @param parameters - Additional fetch parameters like AbortSignal\n* @param body - Request body (will be JSON stringified if plain object)\n* @returns Complete fetch request parameters\n*/\nconst _getRequestParams = (method, options, parameters, body) => {\n\tconst params = {\n\t\tmethod,\n\t\theaders: (options === null || options === void 0 ? void 0 : options.headers) || {}\n\t};\n\tif (method === \"GET\" || method === \"HEAD\" || !body) return _objectSpread2(_objectSpread2({}, params), parameters);\n\tif (isPlainObject(body)) {\n\t\tvar _contentType;\n\t\tconst headers = (options === null || options === void 0 ? void 0 : options.headers) || {};\n\t\tlet contentType;\n\t\tfor (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === \"content-type\") contentType = value;\n\t\tparams.headers = setHeader(headers, \"Content-Type\", (_contentType = contentType) !== null && _contentType !== void 0 ? _contentType : \"application/json\");\n\t\tparams.body = JSON.stringify(body);\n\t} else params.body = body;\n\tif (options === null || options === void 0 ? void 0 : options.duplex) params.duplex = options.duplex;\n\treturn _objectSpread2(_objectSpread2({}, params), parameters);\n};\n/**\n* Internal request handler that wraps fetch with error handling\n* @param fetcher - Fetch function to use\n* @param method - HTTP method\n* @param url - Request URL\n* @param options - Custom fetch options\n* @param parameters - Additional fetch parameters\n* @param body - Request body\n* @param namespace - Error namespace ('storage' or 'vectors')\n* @returns Promise with parsed response or error\n*/\nasync function _handleRequest(fetcher, method, url, options, parameters, body, namespace) {\n\treturn new Promise((resolve, reject) => {\n\t\tfetcher(url, _getRequestParams(method, options, parameters, body)).then((result) => {\n\t\t\tif (!result.ok) throw result;\n\t\t\tif (options === null || options === void 0 ? void 0 : options.noResolveJson) return result;\n\t\t\tif (namespace === \"vectors\") {\n\t\t\t\tconst contentType = result.headers.get(\"content-type\");\n\t\t\t\tif (result.headers.get(\"content-length\") === \"0\" || result.status === 204) return {};\n\t\t\t\tif (!contentType || !contentType.includes(\"application/json\")) return {};\n\t\t\t}\n\t\t\treturn result.json();\n\t\t}).then((data) => resolve(data)).catch((error) => handleError(error, reject, options, namespace));\n\t});\n}\n/**\n* Creates a fetch API with the specified namespace\n* @param namespace - Error namespace ('storage' or 'vectors')\n* @returns Object with HTTP method functions\n*/\nfunction createFetchApi(namespace = \"storage\") {\n\treturn {\n\t\tget: async (fetcher, url, options, parameters) => {\n\t\t\treturn _handleRequest(fetcher, \"GET\", url, options, parameters, void 0, namespace);\n\t\t},\n\t\tpost: async (fetcher, url, body, options, parameters) => {\n\t\t\treturn _handleRequest(fetcher, \"POST\", url, options, parameters, body, namespace);\n\t\t},\n\t\tput: async (fetcher, url, body, options, parameters) => {\n\t\t\treturn _handleRequest(fetcher, \"PUT\", url, options, parameters, body, namespace);\n\t\t},\n\t\thead: async (fetcher, url, options, parameters) => {\n\t\t\treturn _handleRequest(fetcher, \"HEAD\", url, _objectSpread2(_objectSpread2({}, options), {}, { noResolveJson: true }), parameters, void 0, namespace);\n\t\t},\n\t\tremove: async (fetcher, url, body, options, parameters) => {\n\t\t\treturn _handleRequest(fetcher, \"DELETE\", url, options, parameters, body, namespace);\n\t\t}\n\t};\n}\nconst defaultApi = createFetchApi(\"storage\");\nconst { get, post, put, head, remove } = defaultApi;\nconst vectorsApi = createFetchApi(\"vectors\");\n\n//#endregion\n//#region src/lib/common/BaseApiClient.ts\n/**\n* @ignore\n* Base API client class for all Storage API classes\n* Provides common infrastructure for error handling and configuration\n*\n* @typeParam TError - The error type (StorageError or subclass)\n*/\nvar BaseApiClient = class {\n\t/**\n\t* Creates a new BaseApiClient instance\n\t* @param url - Base URL for API requests\n\t* @param headers - Default headers for API requests\n\t* @param fetch - Optional custom fetch implementation\n\t* @param namespace - Error namespace ('storage' or 'vectors')\n\t*/\n\tconstructor(url, headers = {}, fetch$1, namespace = \"storage\") {\n\t\tthis.shouldThrowOnError = false;\n\t\tthis.url = url;\n\t\tthis.headers = normalizeHeaders(headers);\n\t\tthis.fetch = resolveFetch(fetch$1);\n\t\tthis.namespace = namespace;\n\t}\n\t/**\n\t* Enable throwing errors instead of returning them.\n\t* When enabled, errors are thrown instead of returned in { data, error } format.\n\t*\n\t* @returns this - For method chaining\n\t*/\n\tthrowOnError() {\n\t\tthis.shouldThrowOnError = true;\n\t\treturn this;\n\t}\n\t/**\n\t* Set an HTTP header for the request.\n\t* Creates a shallow copy of headers to avoid mutating shared state.\n\t*\n\t* @param name - Header name\n\t* @param value - Header value\n\t* @returns this - For method chaining\n\t*/\n\tsetHeader(name, value) {\n\t\tthis.headers = setHeader(this.headers, name, value);\n\t\treturn this;\n\t}\n\t/**\n\t* Handles API operation with standardized error handling\n\t* Eliminates repetitive try-catch blocks across all API methods\n\t*\n\t* This wrapper:\n\t* 1. Executes the operation\n\t* 2. Returns { data, error: null } on success\n\t* 3. Returns { data: null, error } on failure (if shouldThrowOnError is false)\n\t* 4. Throws error on failure (if shouldThrowOnError is true)\n\t*\n\t* @typeParam T - The expected data type from the operation\n\t* @param operation - Async function that performs the API call\n\t* @returns Promise with { data, error } tuple\n\t*\n\t* @example Handling an operation\n\t* ```typescript\n\t* async listBuckets() {\n\t*   return this.handleOperation(async () => {\n\t*     return await get(this.fetch, `${this.url}/bucket`, {\n\t*       headers: this.headers,\n\t*     })\n\t*   })\n\t* }\n\t* ```\n\t*/\n\tasync handleOperation(operation) {\n\t\tvar _this = this;\n\t\ttry {\n\t\t\treturn {\n\t\t\t\tdata: await operation(),\n\t\t\t\terror: null\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (_this.shouldThrowOnError) throw error;\n\t\t\tif (isStorageError(error)) return {\n\t\t\t\tdata: null,\n\t\t\t\terror\n\t\t\t};\n\t\t\tthrow error;\n\t\t}\n\t}\n};\n\n//#endregion\n//#region src/packages/StreamDownloadBuilder.ts\nlet _Symbol$toStringTag$1;\n_Symbol$toStringTag$1 = Symbol.toStringTag;\nvar StreamDownloadBuilder = class {\n\tconstructor(downloadFn, shouldThrowOnError) {\n\t\tthis.downloadFn = downloadFn;\n\t\tthis.shouldThrowOnError = shouldThrowOnError;\n\t\tthis[_Symbol$toStringTag$1] = \"StreamDownloadBuilder\";\n\t\tthis.promise = null;\n\t}\n\tthen(onfulfilled, onrejected) {\n\t\treturn this.getPromise().then(onfulfilled, onrejected);\n\t}\n\tcatch(onrejected) {\n\t\treturn this.getPromise().catch(onrejected);\n\t}\n\tfinally(onfinally) {\n\t\treturn this.getPromise().finally(onfinally);\n\t}\n\tgetPromise() {\n\t\tif (!this.promise) this.promise = this.execute();\n\t\treturn this.promise;\n\t}\n\tasync execute() {\n\t\tvar _this = this;\n\t\ttry {\n\t\t\treturn {\n\t\t\t\tdata: (await _this.downloadFn()).body,\n\t\t\t\terror: null\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (_this.shouldThrowOnError) throw error;\n\t\t\tif (isStorageError(error)) return {\n\t\t\t\tdata: null,\n\t\t\t\terror\n\t\t\t};\n\t\t\tthrow error;\n\t\t}\n\t}\n};\n\n//#endregion\n//#region src/packages/BlobDownloadBuilder.ts\nlet _Symbol$toStringTag;\n_Symbol$toStringTag = Symbol.toStringTag;\nvar BlobDownloadBuilder = class {\n\tconstructor(downloadFn, shouldThrowOnError) {\n\t\tthis.downloadFn = downloadFn;\n\t\tthis.shouldThrowOnError = shouldThrowOnError;\n\t\tthis[_Symbol$toStringTag] = \"BlobDownloadBuilder\";\n\t\tthis.promise = null;\n\t}\n\tasStream() {\n\t\treturn new StreamDownloadBuilder(this.downloadFn, this.shouldThrowOnError);\n\t}\n\tthen(onfulfilled, onrejected) {\n\t\treturn this.getPromise().then(onfulfilled, onrejected);\n\t}\n\tcatch(onrejected) {\n\t\treturn this.getPromise().catch(onrejected);\n\t}\n\tfinally(onfinally) {\n\t\treturn this.getPromise().finally(onfinally);\n\t}\n\tgetPromise() {\n\t\tif (!this.promise) this.promise = this.execute();\n\t\treturn this.promise;\n\t}\n\tasync execute() {\n\t\tvar _this = this;\n\t\ttry {\n\t\t\treturn {\n\t\t\t\tdata: await (await _this.downloadFn()).blob(),\n\t\t\t\terror: null\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (_this.shouldThrowOnError) throw error;\n\t\t\tif (isStorageError(error)) return {\n\t\t\t\tdata: null,\n\t\t\t\terror\n\t\t\t};\n\t\t\tthrow error;\n\t\t}\n\t}\n};\n\n//#endregion\n//#region src/packages/StorageFileApi.ts\nconst DEFAULT_SEARCH_OPTIONS = {\n\tlimit: 100,\n\toffset: 0,\n\tsortBy: {\n\t\tcolumn: \"name\",\n\t\torder: \"asc\"\n\t}\n};\nconst DEFAULT_FILE_OPTIONS = {\n\tcacheControl: \"3600\",\n\tcontentType: \"text/plain;charset=UTF-8\",\n\tupsert: false\n};\nvar StorageFileApi = class extends BaseApiClient {\n\tconstructor(url, headers = {}, bucketId, fetch$1) {\n\t\tsuper(url, headers, fetch$1, \"storage\");\n\t\tthis.bucketId = bucketId;\n\t}\n\t/**\n\t* Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one.\n\t*\n\t* @param method HTTP method.\n\t* @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.\n\t* @param fileBody The body of the file to be stored in the bucket.\n\t*/\n\tasync uploadOrUpdate(method, path, fileBody, fileOptions) {\n\t\tvar _this = this;\n\t\treturn _this.handleOperation(async () => {\n\t\t\tlet body;\n\t\t\tconst options = _objectSpread2(_objectSpread2({}, DEFAULT_FILE_OPTIONS), fileOptions);\n\t\t\tlet headers = _objectSpread2(_objectSpread2({}, _this.headers), method === \"POST\" && { \"x-upsert\": String(options.upsert) });\n\t\t\tconst metadata = options.metadata;\n\t\t\tif (typeof Blob !== \"undefined\" && fileBody instanceof Blob) {\n\t\t\t\tbody = new FormData();\n\t\t\t\tbody.append(\"cacheControl\", options.cacheControl);\n\t\t\t\tif (metadata) body.append(\"metadata\", _this.encodeMetadata(metadata));\n\t\t\t\tbody.append(\"\", fileBody);\n\t\t\t} else if (typeof FormData !== \"undefined\" && fileBody instanceof FormData) {\n\t\t\t\tbody = fileBody;\n\t\t\t\tif (!body.has(\"cacheControl\")) body.append(\"cacheControl\", options.cacheControl);\n\t\t\t\tif (metadata && !body.has(\"metadata\")) body.append(\"metadata\", _this.encodeMetadata(metadata));\n\t\t\t} else {\n\t\t\t\tbody = fileBody;\n\t\t\t\theaders[\"cache-control\"] = `max-age=${options.cacheControl}`;\n\t\t\t\theaders[\"content-type\"] = options.contentType;\n\t\t\t\tif (metadata) headers[\"x-metadata\"] = _this.toBase64(_this.encodeMetadata(metadata));\n\t\t\t\tif ((typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream || body && typeof body === \"object\" && \"pipe\" in body && typeof body.pipe === \"function\") && !options.duplex) options.duplex = \"half\";\n\t\t\t}\n\t\t\tif (fileOptions === null || fileOptions === void 0 ? void 0 : fileOptions.headers) for (const [key, value] of Object.entries(fileOptions.headers)) headers = setHeader(headers, key, value);\n\t\t\tconst cleanPath = _this._removeEmptyFolders(path);\n\t\t\tconst _path = _this._getFinalPath(cleanPath);\n\t\t\tconst data = await (method == \"PUT\" ? put : post)(_this.fetch, `${_this.url}/object/${_path}`, body, _objectSpread2({ headers }, (options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {}));\n\t\t\treturn {\n\t\t\t\tpath: cleanPath,\n\t\t\t\tid: data.Id,\n\t\t\t\tfullPath: data.Key\n\t\t\t};\n\t\t});\n\t}\n\t/**\n\t* Uploads a file to an existing bucket.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.\n\t* @param fileBody The body of the file to be stored in the bucket.\n\t* @param fileOptions Optional file upload options including cacheControl, contentType, upsert, and metadata.\n\t* @returns Promise with response containing file path, id, and fullPath or error\n\t*\n\t* @example Upload file\n\t* ```js\n\t* const avatarFile = event.target.files[0]\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .upload('public/avatar1.png', avatarFile, {\n\t*     cacheControl: '3600',\n\t*     upsert: false\n\t*   })\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"path\": \"public/avatar1.png\",\n\t*     \"fullPath\": \"avatars/public/avatar1.png\"\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @example Upload file using `ArrayBuffer` from base64 file data\n\t* ```js\n\t* import { decode } from 'base64-arraybuffer'\n\t*\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .upload('public/avatar1.png', decode('base64FileData'), {\n\t*     contentType: 'image/png'\n\t*   })\n\t* ```\n\t*\n\t* @example Handling errors\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .upload('public/avatar1.png', avatarFile)\n\t*\n\t* if (error) {\n\t*   // Log the full error so fields like `statusCode` and `error` (the\n\t*   // Storage error name, e.g. \"Duplicate\") aren't hidden behind `error.message`.\n\t*   console.error(error)\n\t*   return\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: none\n\t*   - `objects` table permissions: only `insert` when you are uploading new files and `select`, `insert` and `update` when you are upserting files\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t* - For React Native, using either `Blob`, `File` or `FormData` does not work as intended. Upload file using `ArrayBuffer` from base64 file data instead, see example below.\n\t*/\n\tasync upload(path, fileBody, fileOptions) {\n\t\treturn this.uploadOrUpdate(\"POST\", path, fileBody, fileOptions);\n\t}\n\t/**\n\t* Upload a file with a token generated from `createSignedUploadUrl`.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.\n\t* @param token The token generated from `createSignedUploadUrl`\n\t* @param fileBody The body of the file to be stored in the bucket.\n\t* @param fileOptions HTTP headers (cacheControl, contentType, etc.).\n\t* **Note:** The `upsert` option has no effect here. To enable upsert behavior,\n\t* pass `{ upsert: true }` when calling `createSignedUploadUrl()` instead.\n\t* @returns Promise with response containing file path and fullPath or error\n\t*\n\t* @example Upload to a signed URL\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .uploadToSignedUrl('folder/cat.jpg', 'token-from-createSignedUploadUrl', file)\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"path\": \"folder/cat.jpg\",\n\t*     \"fullPath\": \"avatars/folder/cat.jpg\"\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: none\n\t*   - `objects` table permissions: none\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync uploadToSignedUrl(path, token, fileBody, fileOptions) {\n\t\tvar _this3 = this;\n\t\tconst cleanPath = _this3._removeEmptyFolders(path);\n\t\tconst _path = _this3._getFinalPath(cleanPath);\n\t\tconst url = new URL(_this3.url + `/object/upload/sign/${_path}`);\n\t\turl.searchParams.set(\"token\", token);\n\t\treturn _this3.handleOperation(async () => {\n\t\t\tlet body;\n\t\t\tconst options = _objectSpread2(_objectSpread2({}, DEFAULT_FILE_OPTIONS), fileOptions);\n\t\t\tlet headers = _objectSpread2(_objectSpread2({}, _this3.headers), { \"x-upsert\": String(options.upsert) });\n\t\t\tconst metadata = options.metadata;\n\t\t\tif (typeof Blob !== \"undefined\" && fileBody instanceof Blob) {\n\t\t\t\tbody = new FormData();\n\t\t\t\tbody.append(\"cacheControl\", options.cacheControl);\n\t\t\t\tif (metadata) body.append(\"metadata\", _this3.encodeMetadata(metadata));\n\t\t\t\tbody.append(\"\", fileBody);\n\t\t\t} else if (typeof FormData !== \"undefined\" && fileBody instanceof FormData) {\n\t\t\t\tbody = fileBody;\n\t\t\t\tif (!body.has(\"cacheControl\")) body.append(\"cacheControl\", options.cacheControl);\n\t\t\t\tif (metadata && !body.has(\"metadata\")) body.append(\"metadata\", _this3.encodeMetadata(metadata));\n\t\t\t} else {\n\t\t\t\tbody = fileBody;\n\t\t\t\theaders[\"cache-control\"] = `max-age=${options.cacheControl}`;\n\t\t\t\theaders[\"content-type\"] = options.contentType;\n\t\t\t\tif (metadata) headers[\"x-metadata\"] = _this3.toBase64(_this3.encodeMetadata(metadata));\n\t\t\t\tif ((typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream || body && typeof body === \"object\" && \"pipe\" in body && typeof body.pipe === \"function\") && !options.duplex) options.duplex = \"half\";\n\t\t\t}\n\t\t\tif (fileOptions === null || fileOptions === void 0 ? void 0 : fileOptions.headers) for (const [key, value] of Object.entries(fileOptions.headers)) headers = setHeader(headers, key, value);\n\t\t\treturn {\n\t\t\t\tpath: cleanPath,\n\t\t\t\tfullPath: (await put(_this3.fetch, url.toString(), body, _objectSpread2({ headers }, (options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {}))).Key\n\t\t\t};\n\t\t});\n\t}\n\t/**\n\t* Creates a signed upload URL.\n\t* Signed upload URLs can be used to upload files to the bucket without further authentication.\n\t* They are valid for 2 hours.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param path The file path, including the current file name. For example `folder/image.png`.\n\t* @param options.upsert If set to true, allows the file to be overwritten if it already exists.\n\t* @returns Promise with response containing signed upload URL, token, and path or error\n\t*\n\t* @example Create Signed Upload URL\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .createSignedUploadUrl('folder/cat.jpg')\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"signedUrl\": \"https://example.supabase.co/storage/v1/object/upload/sign/avatars/folder/cat.jpg?token=<TOKEN>\",\n\t*     \"path\": \"folder/cat.jpg\",\n\t*     \"token\": \"<TOKEN>\"\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: none\n\t*   - `objects` table permissions: `insert`\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync createSignedUploadUrl(path, options) {\n\t\tvar _this4 = this;\n\t\treturn _this4.handleOperation(async () => {\n\t\t\tlet _path = _this4._getFinalPath(path);\n\t\t\tconst headers = _objectSpread2({}, _this4.headers);\n\t\t\tif (options === null || options === void 0 ? void 0 : options.upsert) headers[\"x-upsert\"] = \"true\";\n\t\t\tconst data = await post(_this4.fetch, `${_this4.url}/object/upload/sign/${_path}`, {}, { headers });\n\t\t\tconst url = new URL(_this4.url + data.url);\n\t\t\tconst token = url.searchParams.get(\"token\");\n\t\t\tif (!token) throw new StorageError(\"No token returned by API\");\n\t\t\treturn {\n\t\t\t\tsignedUrl: url.toString(),\n\t\t\t\tpath,\n\t\t\t\ttoken\n\t\t\t};\n\t\t});\n\t}\n\t/**\n\t* Replaces an existing file at the specified path with a new one.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update.\n\t* @param fileBody The body of the file to be stored in the bucket.\n\t* @param fileOptions Optional file upload options including cacheControl, contentType, and metadata.\n\t* **Note:** The `upsert` option has no effect here. `update()` always replaces the\n\t* file at the given path, so the `x-upsert` header is not sent. To control upsert\n\t* behavior, use `upload()` instead.\n\t* @returns Promise with response containing file path, id, and fullPath or error\n\t*\n\t* @example Update file\n\t* ```js\n\t* const avatarFile = event.target.files[0]\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .update('public/avatar1.png', avatarFile, {\n\t*     cacheControl: '3600'\n\t*   })\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"path\": \"public/avatar1.png\",\n\t*     \"fullPath\": \"avatars/public/avatar1.png\"\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @example Update file using `ArrayBuffer` from base64 file data\n\t* ```js\n\t* import {decode} from 'base64-arraybuffer'\n\t*\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .update('public/avatar1.png', decode('base64FileData'), {\n\t*     contentType: 'image/png'\n\t*   })\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: none\n\t*   - `objects` table permissions: `update` and `select`\n\t* - `update()` always replaces the file at the given path regardless of the `upsert` option.\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t* - For React Native, using either `Blob`, `File` or `FormData` does not work as intended. Update file using `ArrayBuffer` from base64 file data instead, see example below.\n\t*/\n\tasync update(path, fileBody, fileOptions) {\n\t\treturn this.uploadOrUpdate(\"PUT\", path, fileBody, fileOptions);\n\t}\n\t/**\n\t* Moves an existing file to a new path in the same bucket.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param fromPath The original file path, including the current file name. For example `folder/image.png`.\n\t* @param toPath The new file path, including the new file name. For example `folder/image-new.png`.\n\t* @param options The destination options.\n\t* @param options.sourceVersionId The version id of the source object to move.\n\t* @returns Promise with response containing success message or error\n\t*\n\t* @example Move file\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .move('public/avatar1.png', 'private/avatar2.png')\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"message\": \"Successfully moved\"\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: none\n\t*   - `objects` table permissions: `update` and `select`\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync move(fromPath, toPath, options) {\n\t\tvar _this6 = this;\n\t\treturn _this6.handleOperation(async () => {\n\t\t\treturn await post(_this6.fetch, `${_this6.url}/object/move`, {\n\t\t\t\tbucketId: _this6.bucketId,\n\t\t\t\tsourceKey: fromPath,\n\t\t\t\tdestinationKey: toPath,\n\t\t\t\tdestinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket,\n\t\t\t\tsourceVersionId: options === null || options === void 0 ? void 0 : options.sourceVersionId\n\t\t\t}, { headers: _this6.headers });\n\t\t});\n\t}\n\t/**\n\t* Copies an existing file to a new path in the same bucket.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param fromPath The original file path, including the current file name. For example `folder/image.png`.\n\t* @param toPath The new file path, including the new file name. For example `folder/image-copy.png`.\n\t* @param options The destination options.\n\t* @param options.sourceVersionId The version id of the source object to copy.\n\t* @returns Promise with response containing copied file path or error\n\t*\n\t* @example Copy file\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .copy('public/avatar1.png', 'private/avatar2.png')\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"path\": \"avatars/private/avatar2.png\"\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: none\n\t*   - `objects` table permissions: `insert` and `select`\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync copy(fromPath, toPath, options) {\n\t\tvar _this7 = this;\n\t\treturn _this7.handleOperation(async () => {\n\t\t\treturn { path: (await post(_this7.fetch, `${_this7.url}/object/copy`, {\n\t\t\t\tbucketId: _this7.bucketId,\n\t\t\t\tsourceKey: fromPath,\n\t\t\t\tdestinationKey: toPath,\n\t\t\t\tdestinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket,\n\t\t\t\tsourceVersionId: options === null || options === void 0 ? void 0 : options.sourceVersionId\n\t\t\t}, { headers: _this7.headers })).Key };\n\t\t});\n\t}\n\t/**\n\t* Creates a signed URL. Use a signed URL to share a file for a fixed amount of time.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param path The file path, including the current file name. For example `folder/image.png`.\n\t* @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute.\n\t* @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.\n\t* @param options.transform Transform the asset before serving it to the client.\n\t* @param options.cacheNonce Append a cache nonce parameter to the URL to invalidate the cache.\n\t* @param options.versionId Create a signed URL for a specific object version rather than the current one.\n\t* @returns Promise with response containing signed URL or error\n\t*\n\t* @example Create Signed URL\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .createSignedUrl('folder/avatar1.png', 60)\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"signedUrl\": \"https://example.supabase.co/storage/v1/object/sign/avatars/folder/avatar1.png?token=<TOKEN>\"\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @example Create a signed URL for an asset with transformations\n\t* ```js\n\t* const { data } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .createSignedUrl('folder/avatar1.png', 60, {\n\t*     transform: {\n\t*       width: 100,\n\t*       height: 100,\n\t*     }\n\t*   })\n\t* ```\n\t*\n\t* @example Create a signed URL which triggers the download of the asset\n\t* ```js\n\t* const { data } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .createSignedUrl('folder/avatar1.png', 60, {\n\t*     download: true,\n\t*   })\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: none\n\t*   - `objects` table permissions: `select`\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync createSignedUrl(path, expiresIn, options) {\n\t\tvar _this8 = this;\n\t\treturn _this8.handleOperation(async () => {\n\t\t\tlet _path = _this8._getFinalPath(path);\n\t\t\tconst hasTransform = typeof (options === null || options === void 0 ? void 0 : options.transform) === \"object\" && options.transform !== null && Object.keys(options.transform).length > 0;\n\t\t\tlet data = await post(_this8.fetch, `${_this8.url}/object/sign/${_path}`, _objectSpread2(_objectSpread2({ expiresIn }, hasTransform ? { transform: options.transform } : {}), (options === null || options === void 0 ? void 0 : options.versionId) != null ? { versionId: options.versionId } : {}), { headers: _this8.headers });\n\t\t\tconst query = new URLSearchParams();\n\t\t\tif (options === null || options === void 0 ? void 0 : options.download) query.set(\"download\", options.download === true ? \"\" : options.download);\n\t\t\tif ((options === null || options === void 0 ? void 0 : options.cacheNonce) != null) query.set(\"cacheNonce\", String(options.cacheNonce));\n\t\t\tconst queryString = query.toString();\n\t\t\treturn { signedUrl: encodeURI(`${_this8.url}${data.signedURL}${queryString ? `&${queryString}` : \"\"}`) };\n\t\t});\n\t}\n\t/**\n\t* Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`.\n\t* @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute.\n\t* @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.\n\t* @param options.cacheNonce Append a cache nonce parameter to the URL to invalidate the cache.\n\t* @returns Promise with response containing array of objects with signedUrl, path, and error or error\n\t*\n\t* @example Create Signed URLs\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .createSignedUrls(['folder/avatar1.png', 'folder/avatar2.png'], 60)\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"error\": null,\n\t*       \"path\": \"folder/avatar1.png\",\n\t*       \"signedURL\": \"/object/sign/avatars/folder/avatar1.png?token=<TOKEN>\",\n\t*       \"signedUrl\": \"https://example.supabase.co/storage/v1/object/sign/avatars/folder/avatar1.png?token=<TOKEN>\"\n\t*     },\n\t*     {\n\t*       \"error\": null,\n\t*       \"path\": \"folder/avatar2.png\",\n\t*       \"signedURL\": \"/object/sign/avatars/folder/avatar2.png?token=<TOKEN>\",\n\t*       \"signedUrl\": \"https://example.supabase.co/storage/v1/object/sign/avatars/folder/avatar2.png?token=<TOKEN>\"\n\t*     }\n\t*   ],\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: none\n\t*   - `objects` table permissions: `select`\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync createSignedUrls(paths, expiresIn, options) {\n\t\tvar _this9 = this;\n\t\treturn _this9.handleOperation(async () => {\n\t\t\tconst data = await post(_this9.fetch, `${_this9.url}/object/sign/${_this9.bucketId}`, {\n\t\t\t\texpiresIn,\n\t\t\t\tpaths\n\t\t\t}, { headers: _this9.headers });\n\t\t\tconst query = new URLSearchParams();\n\t\t\tif (options === null || options === void 0 ? void 0 : options.download) query.set(\"download\", options.download === true ? \"\" : options.download);\n\t\t\tif ((options === null || options === void 0 ? void 0 : options.cacheNonce) != null) query.set(\"cacheNonce\", String(options.cacheNonce));\n\t\t\tconst queryString = query.toString();\n\t\t\treturn data.map((datum) => _objectSpread2(_objectSpread2({}, datum), {}, { signedUrl: datum.signedURL ? encodeURI(`${_this9.url}${datum.signedURL}${queryString ? `&${queryString}` : \"\"}`) : null }));\n\t\t});\n\t}\n\t/**\n\t* Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param path The full path and file name of the file to be downloaded. For example `folder/image.png`.\n\t* @param options Optional settings: `transform` to transform the asset before serving it to the client, `cacheNonce` to append a cache nonce parameter to the URL to invalidate the cache, and `versionId` to download a specific object version.\n\t* @param parameters Additional fetch parameters like signal for cancellation. Supports standard fetch options including cache control.\n\t* @returns BlobDownloadBuilder instance for downloading the file\n\t*\n\t* @example Download file\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .download('folder/avatar1.png')\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": <BLOB>,\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @example Download file with transformations\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .download('folder/avatar1.png', {\n\t*     transform: {\n\t*       width: 100,\n\t*       height: 100,\n\t*       quality: 80\n\t*     }\n\t*   })\n\t* ```\n\t*\n\t* @example Download with cache control (useful in Edge Functions)\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .download('folder/avatar1.png', {}, { cache: 'no-store' })\n\t* ```\n\t*\n\t* @example Download with abort signal\n\t* ```js\n\t* const controller = new AbortController()\n\t* setTimeout(() => controller.abort(), 5000)\n\t*\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .download('folder/avatar1.png', {}, { signal: controller.signal })\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: none\n\t*   - `objects` table permissions: `select`\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tdownload(path, options, parameters) {\n\t\tconst renderPath = typeof (options === null || options === void 0 ? void 0 : options.transform) === \"object\" && options.transform !== null && Object.keys(options.transform).length > 0 ? \"render/image/authenticated\" : \"object\";\n\t\tconst query = new URLSearchParams();\n\t\tif (options === null || options === void 0 ? void 0 : options.transform) this.applyTransformOptsToQuery(query, options.transform);\n\t\tif ((options === null || options === void 0 ? void 0 : options.cacheNonce) != null) query.set(\"cacheNonce\", String(options.cacheNonce));\n\t\tif ((options === null || options === void 0 ? void 0 : options.versionId) != null) query.set(\"versionId\", String(options.versionId));\n\t\tconst queryString = query.toString();\n\t\tconst _path = this._getFinalPath(path);\n\t\tconst downloadFn = () => get(this.fetch, `${this.url}/${renderPath}/${_path}${queryString ? `?${queryString}` : \"\"}`, {\n\t\t\theaders: this.headers,\n\t\t\tnoResolveJson: true\n\t\t}, parameters);\n\t\treturn new BlobDownloadBuilder(downloadFn, this.shouldThrowOnError);\n\t}\n\t/**\n\t* Retrieves the details of an existing file.\n\t*\n\t* Returns detailed file metadata including size, content type, and timestamps.\n\t* Note: The API returns `last_modified` field, not `updated_at`.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param path The file path, including the file name. For example `folder/image.png`.\n\t* @param options Optional settings, including `versionId` to retrieve a specific object version.\n\t* @returns Promise with response containing file metadata or error\n\t*\n\t* @example Get file info\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .info('folder/avatar1.png')\n\t*\n\t* if (data) {\n\t*   console.log('Last modified:', data.lastModified)\n\t*   console.log('Size:', data.size)\n\t* }\n\t* ```\n\t*/\n\tasync info(path, options) {\n\t\tvar _this10 = this;\n\t\tconst _path = _this10._getFinalPath(path);\n\t\tconst query = new URLSearchParams();\n\t\tif ((options === null || options === void 0 ? void 0 : options.versionId) != null) query.set(\"versionId\", String(options.versionId));\n\t\tconst queryString = query.toString();\n\t\treturn _this10.handleOperation(async () => {\n\t\t\treturn recursiveToCamel(await get(_this10.fetch, `${_this10.url}/object/info/${_path}${queryString ? `?${queryString}` : \"\"}`, { headers: _this10.headers }));\n\t\t});\n\t}\n\t/**\n\t* Checks the existence of a file.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param path The file path, including the file name. For example `folder/image.png`.\n\t* @returns Promise with response containing boolean indicating file existence or error\n\t*\n\t* @example Check file existence\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .exists('folder/avatar1.png')\n\t* ```\n\t*/\n\tasync exists(path) {\n\t\tvar _this11 = this;\n\t\tconst _path = _this11._getFinalPath(path);\n\t\ttry {\n\t\t\tawait head(_this11.fetch, `${_this11.url}/object/${_path}`, { headers: _this11.headers });\n\t\t\treturn {\n\t\t\t\tdata: true,\n\t\t\t\terror: null\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (_this11.shouldThrowOnError) throw error;\n\t\t\tif (isStorageError(error)) {\n\t\t\t\tvar _error$originalError;\n\t\t\t\tconst status = error instanceof StorageApiError ? error.status : error instanceof StorageUnknownError ? (_error$originalError = error.originalError) === null || _error$originalError === void 0 ? void 0 : _error$originalError.status : void 0;\n\t\t\t\tif (status !== void 0 && [400, 404].includes(status)) return {\n\t\t\t\t\tdata: false,\n\t\t\t\t\terror\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/**\n\t* A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset.\n\t* This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param path The path and name of the file to generate the public URL for. For example `folder/image.png`.\n\t* @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.\n\t* @param options.transform Transform the asset before serving it to the client.\n\t* @param options.cacheNonce Append a cache nonce parameter to the URL to invalidate the cache.\n\t* @param options.versionId Return the URL for a specific object version rather than the current one.\n\t* @returns Object with public URL\n\t*\n\t* @example Returns the URL for an asset in a public bucket\n\t* ```js\n\t* const { data } = supabase\n\t*   .storage\n\t*   .from('public-bucket')\n\t*   .getPublicUrl('folder/avatar1.png')\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"publicUrl\": \"https://example.supabase.co/storage/v1/object/public/public-bucket/folder/avatar1.png\"\n\t*   }\n\t* }\n\t* ```\n\t*\n\t* @example Returns the URL for an asset in a public bucket with transformations\n\t* ```js\n\t* const { data } = supabase\n\t*   .storage\n\t*   .from('public-bucket')\n\t*   .getPublicUrl('folder/avatar1.png', {\n\t*     transform: {\n\t*       width: 100,\n\t*       height: 100,\n\t*     }\n\t*   })\n\t* ```\n\t*\n\t* @example Returns the URL which triggers the download of an asset in a public bucket\n\t* ```js\n\t* const { data } = supabase\n\t*   .storage\n\t*   .from('public-bucket')\n\t*   .getPublicUrl('folder/avatar1.png', {\n\t*     download: true,\n\t*   })\n\t* ```\n\t*\n\t* @remarks\n\t* - The bucket needs to be set to public, either via [updateBucket()](/docs/reference/javascript/storage-updatebucket) or by going to Storage on [supabase.com/dashboard](https://supabase.com/dashboard), clicking the overflow menu on a bucket and choosing \"Make public\"\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: none\n\t*   - `objects` table permissions: none\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tgetPublicUrl(path, options) {\n\t\tconst _path = this._getFinalPath(path);\n\t\tconst query = new URLSearchParams();\n\t\tif (options === null || options === void 0 ? void 0 : options.download) query.set(\"download\", options.download === true ? \"\" : options.download);\n\t\tif (options === null || options === void 0 ? void 0 : options.transform) this.applyTransformOptsToQuery(query, options.transform);\n\t\tif ((options === null || options === void 0 ? void 0 : options.cacheNonce) != null) query.set(\"cacheNonce\", String(options.cacheNonce));\n\t\tif ((options === null || options === void 0 ? void 0 : options.versionId) != null) query.set(\"versionId\", String(options.versionId));\n\t\tconst queryString = query.toString();\n\t\tconst renderPath = typeof (options === null || options === void 0 ? void 0 : options.transform) === \"object\" && options.transform !== null && Object.keys(options.transform).length > 0 ? \"render/image\" : \"object\";\n\t\treturn { data: { publicUrl: encodeURI(`${this.url}/${renderPath}/public/${_path}`) + (queryString ? `?${queryString}` : \"\") } };\n\t}\n\t/**\n\t* Deletes files within the same bucket\n\t*\n\t* Returns an array of FileObject entries for the deleted files. Note that deprecated\n\t* fields like `bucket_id` may or may not be present in the response - do not rely on them.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param paths An array of files to delete. Each entry is either a path (deletes whichever\n\t* version is currently at that path, e.g. `'folder/image.png'`), or `{ path, versionId }` to\n\t* delete an exact version current or archived (e.g. `{ path: 'folder/image.png', versionId: '...' }`).\n\t* @returns Promise with response containing array of deleted file objects or error\n\t*\n\t* @example Delete file\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .remove(['folder/avatar1.png'])\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": [],\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @example Delete a specific object version\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .remove([{ path: 'folder/avatar1.png', versionId: 'noncurrent-version-id' }])\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: none\n\t*   - `objects` table permissions: `delete` and `select`\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync remove(paths) {\n\t\tvar _this12 = this;\n\t\treturn _this12.handleOperation(async () => {\n\t\t\treturn await remove(_this12.fetch, `${_this12.url}/object/${_this12.bucketId}`, { prefixes: paths }, { headers: _this12.headers });\n\t\t});\n\t}\n\t/**\n\t* Purges the CDN cache for a single object in this bucket.\n\t*\n\t* Maps to `DELETE /cdn/{bucket}/{path}` on the Storage API. The server\n\t* issues a CDN invalidation for the object and returns `{ message: 'success' }`.\n\t*\n\t* **Requires the `service_role` key.** The underlying endpoint enforces\n\t* `service_role` JWT — calls made with the anon key or a user JWT will be\n\t* rejected by the server.\n\t*\n\t* **Hosted CDN feature.** On self-hosted Supabase, the Storage service must\n\t* have `CDN_PURGE_ENDPOINT_URL` configured and the `purgeCache` tenant\n\t* feature enabled, otherwise the server returns an error.\n\t*\n\t* Operates on a single object path. There is no wildcard or recursion: pass\n\t* the exact path of the object you want invalidated.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param path The path (relative to the bucket) of the object to purge, e.g. `folder/avatar.png`.\n\t* @param options Optional purge cache options.\n\t* @param options.transformations If true, purges only transformations (resized/formatted variants), leaving the original cached file intact.\n\t* @param parameters Optional fetch parameters such as an `AbortController` signal.\n\t* @returns Promise with `{ data: { message }, error: null }` on success or `{ data: null, error }` on failure.\n\t*\n\t* @example Purge a single cached object\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .purgeCache('folder/avatar1.png')\n\t* ```\n\t*\n\t* @example Purge only transformations for a single object\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .purgeCache('folder/avatar1.png', { transformations: true })\n\t* ```\n\t*/\n\tasync purgeCache(path, options, parameters) {\n\t\tvar _this13 = this;\n\t\treturn _this13.handleOperation(async () => {\n\t\t\tconst _path = encodeStoragePath(_this13._getFinalPath(path));\n\t\t\tconst query = new URLSearchParams();\n\t\t\tif (options === null || options === void 0 ? void 0 : options.transformations) query.set(\"transformations\", \"true\");\n\t\t\tconst queryString = query.toString();\n\t\t\treturn await remove(_this13.fetch, `${_this13.url}/cdn/${_path}${queryString ? `?${queryString}` : \"\"}`, {}, { headers: _this13.headers }, parameters);\n\t\t});\n\t}\n\t/**\n\t* Get file metadata\n\t* @param id the file id to retrieve metadata\n\t*/\n\t/**\n\t* Update file metadata\n\t* @param id the file id to update metadata\n\t* @param meta the new file metadata\n\t*/\n\t/**\n\t* Lists all the files and folders within a path of the bucket.\n\t*\n\t* **Important:** For folder entries, fields like `id`, `updated_at`, `created_at`,\n\t* `last_accessed_at`, and `metadata` will be `null`. Only files have these fields populated.\n\t* Additionally, deprecated fields like `bucket_id`, `owner`, and `buckets` are NOT returned\n\t* by this method.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param path The folder path.\n\t* @param options Search options including limit (defaults to 100), offset, sortBy, and search\n\t* @param parameters Optional fetch parameters including signal for cancellation\n\t* @returns Promise with response containing array of files/folders or error\n\t*\n\t* @example List files in a bucket\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .list('folder', {\n\t*     limit: 100,\n\t*     offset: 0,\n\t*     sortBy: { column: 'name', order: 'asc' },\n\t*   })\n\t*\n\t* // Handle files vs folders\n\t* data?.forEach(item => {\n\t*   if (item.id !== null) {\n\t*     // It's a file\n\t*     console.log('File:', item.name, 'Size:', item.metadata?.size)\n\t*   } else {\n\t*     // It's a folder\n\t*     console.log('Folder:', item.name)\n\t*   }\n\t* })\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"name\": \"avatar1.png\",\n\t*       \"id\": \"e668cf7f-821b-4a2f-9dce-7dfa5dd1cfd2\",\n\t*       \"updated_at\": \"2024-05-22T23:06:05.580Z\",\n\t*       \"created_at\": \"2024-05-22T23:04:34.443Z\",\n\t*       \"last_accessed_at\": \"2024-05-22T23:04:34.443Z\",\n\t*       \"metadata\": {\n\t*         \"eTag\": \"\\\"c5e8c553235d9af30ef4f6e280790b92\\\"\",\n\t*         \"size\": 32175,\n\t*         \"mimetype\": \"image/png\",\n\t*         \"cacheControl\": \"max-age=3600\",\n\t*         \"lastModified\": \"2024-05-22T23:06:05.574Z\",\n\t*         \"contentLength\": 32175,\n\t*         \"httpStatusCode\": 200\n\t*       }\n\t*     }\n\t*   ],\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @example Search files in a bucket\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .list('folder', {\n\t*     limit: 100,\n\t*     offset: 0,\n\t*     sortBy: { column: 'name', order: 'asc' },\n\t*     search: 'jon'\n\t*   })\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: none\n\t*   - `objects` table permissions: `select`\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync list(path, options, parameters) {\n\t\tvar _this14 = this;\n\t\treturn _this14.handleOperation(async () => {\n\t\t\tconst sortBy = (options === null || options === void 0 ? void 0 : options.sortBy) ? _objectSpread2(_objectSpread2({}, DEFAULT_SEARCH_OPTIONS.sortBy), options.sortBy) : DEFAULT_SEARCH_OPTIONS.sortBy;\n\t\t\tconst body = _objectSpread2(_objectSpread2(_objectSpread2({}, DEFAULT_SEARCH_OPTIONS), options), {}, {\n\t\t\t\tsortBy,\n\t\t\t\tprefix: path || \"\"\n\t\t\t});\n\t\t\treturn await post(_this14.fetch, `${_this14.url}/object/list/${_this14.bucketId}`, body, { headers: _this14.headers }, parameters);\n\t\t});\n\t}\n\t/**\n\t* Lists all the files and folders within a bucket using the V2 API with pagination support.\n\t*\n\t* **Important:** Folder entries in the `folders` array only contain `name` and optionally `key` —\n\t* they have no `id`, timestamps, or `metadata` fields. Full file metadata is only available\n\t* on entries in the `objects` array.\n\t*\n\t* @experimental this method signature might change in the future\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param options Search options including prefix, cursor for pagination, limit, with_delimiter\n\t* @param parameters Optional fetch parameters including signal for cancellation\n\t* @returns Promise with response containing folders/objects arrays with pagination info or error\n\t*\n\t* @example List files with pagination\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .from('avatars')\n\t*   .listV2({\n\t*     prefix: 'folder/',\n\t*     limit: 100,\n\t*   })\n\t*\n\t* // Handle pagination\n\t* if (data?.hasNext) {\n\t*   const nextPage = await supabase\n\t*     .storage\n\t*     .from('avatars')\n\t*     .listV2({\n\t*       prefix: 'folder/',\n\t*       cursor: data.nextCursor,\n\t*     })\n\t* }\n\t*\n\t* // Handle files vs folders\n\t* data?.objects.forEach(file => {\n\t*   if (file.id !== null) {\n\t*     console.log('File:', file.name, 'Size:', file.metadata?.size)\n\t*   }\n\t* })\n\t* data?.folders.forEach(folder => {\n\t*   console.log('Folder:', folder.name)\n\t* })\n\t* ```\n\t*/\n\tasync listV2(options, parameters) {\n\t\tvar _this15 = this;\n\t\treturn _this15.handleOperation(async () => {\n\t\t\tconst body = _objectSpread2({}, options);\n\t\t\treturn await post(_this15.fetch, `${_this15.url}/object/list-v2/${_this15.bucketId}`, body, { headers: _this15.headers }, parameters);\n\t\t});\n\t}\n\tencodeMetadata(metadata) {\n\t\treturn JSON.stringify(metadata);\n\t}\n\ttoBase64(data) {\n\t\tif (typeof Buffer !== \"undefined\") return Buffer.from(data).toString(\"base64\");\n\t\treturn btoa(data);\n\t}\n\t_getFinalPath(path) {\n\t\treturn `${this.bucketId}/${path.replace(/^\\/+/, \"\")}`;\n\t}\n\t_removeEmptyFolders(path) {\n\t\treturn path.replace(/^\\/|\\/$/g, \"\").replace(/\\/+/g, \"/\");\n\t}\n\t/** Modifies the `query`, appending values the from `transform` */\n\tapplyTransformOptsToQuery(query, transform) {\n\t\tif (transform.width) query.set(\"width\", transform.width.toString());\n\t\tif (transform.height) query.set(\"height\", transform.height.toString());\n\t\tif (transform.resize) query.set(\"resize\", transform.resize);\n\t\tif (transform.format) query.set(\"format\", transform.format);\n\t\tif (transform.quality) query.set(\"quality\", transform.quality.toString());\n\t\treturn query;\n\t}\n};\n\n//#endregion\n//#region src/lib/version.ts\nconst version = \"2.116.0\";\n\n//#endregion\n//#region src/lib/constants.ts\nconst DEFAULT_HEADERS = { \"X-Client-Info\": `storage-js/${version}` };\n\n//#endregion\n//#region src/packages/StorageBucketApi.ts\nvar StorageBucketApi = class extends BaseApiClient {\n\tconstructor(url, headers = {}, fetch$1, opts) {\n\t\tconst baseUrl = new URL(url);\n\t\tif (opts === null || opts === void 0 ? void 0 : opts.useNewHostname) {\n\t\t\tif (/supabase\\.(co|in|red)$/.test(baseUrl.hostname) && !baseUrl.hostname.includes(\"storage.supabase.\")) baseUrl.hostname = baseUrl.hostname.replace(\"supabase.\", \"storage.supabase.\");\n\t\t}\n\t\tconst finalUrl = baseUrl.href.replace(/\\/$/, \"\");\n\t\tconst finalHeaders = _objectSpread2(_objectSpread2({}, DEFAULT_HEADERS), headers);\n\t\tsuper(finalUrl, finalHeaders, fetch$1, \"storage\");\n\t}\n\t/**\n\t* Retrieves the details of all Storage buckets within an existing project.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param options Query parameters for listing buckets\n\t* @param options.limit Maximum number of buckets to return\n\t* @param options.offset Number of buckets to skip\n\t* @param options.sortColumn Column to sort by ('id', 'name', 'created_at', 'updated_at')\n\t* @param options.sortOrder Sort order ('asc' or 'desc')\n\t* @param options.search Search term to filter bucket names\n\t* @returns Promise with response containing array of buckets or error\n\t*\n\t* @example List buckets\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .listBuckets()\n\t* ```\n\t*\n\t* @example List buckets with options\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .listBuckets({\n\t*     limit: 10,\n\t*     offset: 0,\n\t*     sortColumn: 'created_at',\n\t*     sortOrder: 'desc',\n\t*     search: 'prod'\n\t*   })\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: `select`\n\t*   - `objects` table permissions: none\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync listBuckets(options) {\n\t\tvar _this = this;\n\t\treturn _this.handleOperation(async () => {\n\t\t\tconst queryString = _this.listBucketOptionsToQueryString(options);\n\t\t\treturn await get(_this.fetch, `${_this.url}/bucket${queryString}`, { headers: _this.headers });\n\t\t});\n\t}\n\t/**\n\t* Retrieves the details of an existing Storage bucket.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param id The unique identifier of the bucket you would like to retrieve.\n\t* @returns Promise with response containing bucket details or error\n\t*\n\t* @example Get bucket\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .getBucket('avatars')\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"id\": \"avatars\",\n\t*     \"name\": \"avatars\",\n\t*     \"owner\": \"\",\n\t*     \"public\": false,\n\t*     \"file_size_limit\": 1024,\n\t*     \"allowed_mime_types\": [\n\t*       \"image/png\"\n\t*     ],\n\t*     \"created_at\": \"2024-05-22T22:26:05.100Z\",\n\t*     \"updated_at\": \"2024-05-22T22:26:05.100Z\"\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: `select`\n\t*   - `objects` table permissions: none\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync getBucket(id) {\n\t\tvar _this2 = this;\n\t\treturn _this2.handleOperation(async () => {\n\t\t\treturn await get(_this2.fetch, `${_this2.url}/bucket/${id}`, { headers: _this2.headers });\n\t\t});\n\t}\n\t/**\n\t* Creates a new Storage bucket\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param id A unique identifier for the bucket you are creating.\n\t* @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private.\n\t* @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket.\n\t* The global file size limit takes precedence over this value.\n\t* The default value is null, which doesn't set a per bucket file size limit.\n\t* @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload.\n\t* The default value is null, which allows files with all mime types to be uploaded.\n\t* Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.\n\t* @param options.type (private-beta) specifies the bucket type. see `BucketType` for more details.\n\t*   - default bucket type is `STANDARD`\n\t* @param options.versioningStatus the bucket's initial object versioning status.\n\t* The default value is `DISABLED`\n\t* @returns Promise with response containing newly created bucket name or error\n\t*\n\t* @example Create bucket\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .createBucket('avatars', {\n\t*     public: false,\n\t*     allowedMimeTypes: ['image/png'],\n\t*     fileSizeLimit: 1024\n\t*   })\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"name\": \"avatars\"\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: `insert`\n\t*   - `objects` table permissions: none\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync createBucket(id, options = { public: false }) {\n\t\tvar _this3 = this;\n\t\treturn _this3.handleOperation(async () => {\n\t\t\treturn await post(_this3.fetch, `${_this3.url}/bucket`, {\n\t\t\t\tid,\n\t\t\t\tname: id,\n\t\t\t\ttype: options.type,\n\t\t\t\tpublic: options.public,\n\t\t\t\tfile_size_limit: options.fileSizeLimit,\n\t\t\t\tallowed_mime_types: options.allowedMimeTypes,\n\t\t\t\tversioning_status: options.versioningStatus\n\t\t\t}, { headers: _this3.headers });\n\t\t});\n\t}\n\t/**\n\t* Updates a Storage bucket\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param id A unique identifier for the bucket you are updating.\n\t* @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations.\n\t* @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket.\n\t* The global file size limit takes precedence over this value.\n\t* The default value is null, which doesn't set a per bucket file size limit.\n\t* @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload.\n\t* The default value is null, which allows files with all mime types to be uploaded.\n\t* Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.\n\t* @param options.versioningStatus the bucket's new object versioning status. `DISABLED` is not\n\t* valid here, there's no transition back to it once versioning has been touched.\n\t* @returns Promise with response containing success message or error\n\t*\n\t* @example Update bucket\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .updateBucket('avatars', {\n\t*     public: false,\n\t*     allowedMimeTypes: ['image/png'],\n\t*     fileSizeLimit: 1024\n\t*   })\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"message\": \"Successfully updated\"\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: `select` and `update`\n\t*   - `objects` table permissions: none\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync updateBucket(id, options) {\n\t\tvar _this4 = this;\n\t\treturn _this4.handleOperation(async () => {\n\t\t\treturn await put(_this4.fetch, `${_this4.url}/bucket/${id}`, {\n\t\t\t\tid,\n\t\t\t\tname: id,\n\t\t\t\tpublic: options.public,\n\t\t\t\tfile_size_limit: options.fileSizeLimit,\n\t\t\t\tallowed_mime_types: options.allowedMimeTypes,\n\t\t\t\tversioning_status: options.versioningStatus\n\t\t\t}, { headers: _this4.headers });\n\t\t});\n\t}\n\t/**\n\t* Removes all objects inside a single bucket.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param id The unique identifier of the bucket you would like to empty.\n\t* @returns Promise with success message or error\n\t*\n\t* @example Empty bucket\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .emptyBucket('avatars')\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"message\": \"Successfully emptied\"\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: `select`\n\t*   - `objects` table permissions: `select` and `delete`\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync emptyBucket(id) {\n\t\tvar _this5 = this;\n\t\treturn _this5.handleOperation(async () => {\n\t\t\treturn await post(_this5.fetch, `${_this5.url}/bucket/${id}/empty`, {}, { headers: _this5.headers });\n\t\t});\n\t}\n\t/**\n\t* Deletes an existing bucket. A bucket can't be deleted with existing objects inside it.\n\t* You must first `empty()` the bucket.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param id The unique identifier of the bucket you would like to delete.\n\t* @returns Promise with success message or error\n\t*\n\t* @example Delete bucket\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .deleteBucket('avatars')\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"message\": \"Successfully deleted\"\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: `select` and `delete`\n\t*   - `objects` table permissions: none\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync deleteBucket(id) {\n\t\tvar _this6 = this;\n\t\treturn _this6.handleOperation(async () => {\n\t\t\treturn await remove(_this6.fetch, `${_this6.url}/bucket/${id}`, {}, { headers: _this6.headers });\n\t\t});\n\t}\n\t/**\n\t* Returns the lifecycle policy stored on a bucket.\n\t*\n\t* Fails with `NoSuchLifecycleConfiguration` when the bucket has no policy.\n\t*\n\t* These rules expire previous versions of objects, not the current one.\n\t* Turn versioning on or there is nothing for the policy to act on.\n\t* Standard buckets only. Returns `FeatureNotEnabled` if lifecycle is off\n\t* for the project.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param id The unique identifier of the bucket.\n\t* @returns Promise with the lifecycle configuration or error\n\t*\n\t* @example Get lifecycle configuration\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .getBucketLifecycle('avatars')\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"rules\": [\n\t*       {\n\t*         \"id\": \"expire-history\",\n\t*         \"status\": \"Enabled\",\n\t*         \"filter\": {},\n\t*         \"noncurrentVersionExpiration\": {\n\t*           \"noncurrentDays\": 30,\n\t*           \"newerNoncurrentVersions\": 2\n\t*         }\n\t*       }\n\t*     ]\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: `select`\n\t*   - `objects` table permissions: none\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync getBucketLifecycle(id) {\n\t\tvar _this7 = this;\n\t\treturn _this7.handleOperation(async () => {\n\t\t\treturn await get(_this7.fetch, _this7.bucketLifecycleUrl(id), { headers: _this7.headers });\n\t\t});\n\t}\n\t/**\n\t* Replaces the lifecycle policy on a bucket.\n\t*\n\t* The `rules` array you send is the whole policy. Anything previously stored\n\t* is overwritten. Send at least one rule. Call {@link deleteBucketLifecycle}\n\t* to remove the policy.\n\t*\n\t* Each rule currently supports only `noncurrentVersionExpiration`. `filter`\n\t* is required and must be `{}`. Prefix filters, tag filters, and current-object\n\t* expiration are rejected. Rule IDs must be unique. Omit `id` and the\n\t* server generates one.\n\t*\n\t* Standard buckets only. Returns `FeatureNotEnabled` if lifecycle is off\n\t* for the project.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param id The unique identifier of the bucket.\n\t* @param configuration The full lifecycle configuration to store.\n\t* @returns Promise with the stored configuration or error\n\t*\n\t* @example Replace lifecycle configuration\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .updateBucketLifecycle('avatars', {\n\t*     rules: [\n\t*       {\n\t*         id: 'expire-history',\n\t*         status: 'Enabled',\n\t*         filter: {},\n\t*         noncurrentVersionExpiration: {\n\t*           noncurrentDays: 30,\n\t*           newerNoncurrentVersions: 2,\n\t*         },\n\t*       },\n\t*     ],\n\t*   })\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: `select` and `update`\n\t*   - `objects` table permissions: none\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync updateBucketLifecycle(id, configuration) {\n\t\tvar _this8 = this;\n\t\treturn _this8.handleOperation(async () => {\n\t\t\treturn await put(_this8.fetch, _this8.bucketLifecycleUrl(id), configuration, { headers: _this8.headers });\n\t\t});\n\t}\n\t/**\n\t* Removes the lifecycle policy from a bucket.\n\t*\n\t* Safe to call when no policy is stored. The response is still success.\n\t* Standard buckets only. Returns `FeatureNotEnabled` if lifecycle is off\n\t* for the project.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param id The unique identifier of the bucket.\n\t* @returns Promise with success message or error\n\t*\n\t* @example Delete lifecycle configuration\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .deleteBucketLifecycle('avatars')\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"message\": \"Successfully deleted\"\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - RLS policy permissions required:\n\t*   - `buckets` table permissions: `select` and `update`\n\t*   - `objects` table permissions: none\n\t* - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works\n\t*/\n\tasync deleteBucketLifecycle(id) {\n\t\tvar _this9 = this;\n\t\treturn _this9.handleOperation(async () => {\n\t\t\treturn await remove(_this9.fetch, _this9.bucketLifecycleUrl(id), {}, { headers: _this9.headers });\n\t\t});\n\t}\n\t/**\n\t* Purges the CDN cache for an entire bucket.\n\t*\n\t* Maps to `DELETE /cdn/{bucket}` on the Storage API. The server\n\t* issues a CDN invalidation for the bucket and returns `{ message: 'success' }`.\n\t*\n\t* **Requires the `service_role` key.** The underlying endpoint enforces\n\t* `service_role` JWT — calls made with the anon key or a user JWT will be\n\t* rejected by the server.\n\t*\n\t* **Hosted CDN feature.** On self-hosted Supabase, the Storage service must\n\t* have `CDN_PURGE_ENDPOINT_URL` configured and the `purgeCache` tenant\n\t* feature enabled, otherwise the server returns an error.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t* @param id The unique identifier of the bucket you would like to purge from cache.\n\t* @param options Optional purge cache options.\n\t* @param options.transformations If true, purges only transformations (resized/formatted variants), leaving original cached files intact.\n\t* @param parameters Optional fetch parameters such as an `AbortController` signal.\n\t* @returns Promise with `{ data: { message }, error: null }` on success or `{ data: null, error }` on failure.\n\t*\n\t* @example Purge cache for an entire bucket\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .purgeBucketCache('avatars')\n\t* ```\n\t*\n\t* @example Purge only transformations for an entire bucket\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .purgeBucketCache('avatars', { transformations: true })\n\t* ```\n\t*/\n\tasync purgeBucketCache(id, options, parameters) {\n\t\tvar _this10 = this;\n\t\treturn _this10.handleOperation(async () => {\n\t\t\tconst query = new URLSearchParams();\n\t\t\tif (options === null || options === void 0 ? void 0 : options.transformations) query.set(\"transformations\", \"true\");\n\t\t\tconst queryString = query.toString();\n\t\t\treturn await remove(_this10.fetch, `${_this10.url}/cdn/${encodeStoragePath(id)}${queryString ? `?${queryString}` : \"\"}`, {}, { headers: _this10.headers }, parameters);\n\t\t});\n\t}\n\tbucketLifecycleUrl(id) {\n\t\treturn `${this.url}/bucket/${encodeStoragePath(id)}/lifecycle`;\n\t}\n\tlistBucketOptionsToQueryString(options) {\n\t\tconst params = {};\n\t\tif (options) {\n\t\t\tif (\"limit\" in options) params.limit = String(options.limit);\n\t\t\tif (\"offset\" in options) params.offset = String(options.offset);\n\t\t\tif (options.search) params.search = options.search;\n\t\t\tif (options.sortColumn) params.sortColumn = options.sortColumn;\n\t\t\tif (options.sortOrder) params.sortOrder = options.sortOrder;\n\t\t}\n\t\treturn Object.keys(params).length > 0 ? \"?\" + new URLSearchParams(params).toString() : \"\";\n\t}\n};\n\n//#endregion\n//#region src/packages/StorageAnalyticsClient.ts\n/**\n* Client class for managing Analytics Buckets using Iceberg tables\n* Provides methods for creating, listing, and deleting analytics buckets\n*/\nvar StorageAnalyticsClient = class extends BaseApiClient {\n\t/**\n\t* @alpha\n\t*\n\t* Creates a new StorageAnalyticsClient instance\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Analytics Buckets\n\t* @param url - The base URL for the storage API\n\t* @param headers - HTTP headers to include in requests\n\t* @param fetch - Optional custom fetch implementation\n\t*\n\t* @example Using supabase-js (recommended)\n\t* ```typescript\n\t* import { createClient } from '@supabase/supabase-js'\n\t*\n\t* const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n\t* const { data, error } = await supabase.storage.analytics.listBuckets()\n\t* ```\n\t*\n\t* @example Standalone import for bundle-sensitive environments\n\t* ```typescript\n\t* import { StorageAnalyticsClient } from '@supabase/storage-js'\n\t*\n\t* const client = new StorageAnalyticsClient(url, headers)\n\t* ```\n\t*/\n\tconstructor(url, headers = {}, fetch$1) {\n\t\tconst finalUrl = url.replace(/\\/$/, \"\");\n\t\tconst finalHeaders = _objectSpread2(_objectSpread2({}, DEFAULT_HEADERS), headers);\n\t\tsuper(finalUrl, finalHeaders, fetch$1, \"storage\");\n\t}\n\t/**\n\t* @alpha\n\t*\n\t* Creates a new analytics bucket using Iceberg tables\n\t* Analytics buckets are optimized for analytical queries and data processing\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Analytics Buckets\n\t* @param name A unique name for the bucket you are creating\n\t* @returns Promise with response containing newly created analytics bucket or error\n\t*\n\t* @example Create analytics bucket\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .analytics\n\t*   .createBucket('analytics-data')\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"name\": \"analytics-data\",\n\t*     \"type\": \"ANALYTICS\",\n\t*     \"format\": \"iceberg\",\n\t*     \"created_at\": \"2024-05-22T22:26:05.100Z\",\n\t*     \"updated_at\": \"2024-05-22T22:26:05.100Z\"\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - Creates a new analytics bucket using Iceberg tables\n\t* - Analytics buckets are optimized for analytical queries and data processing\n\t*/\n\tasync createBucket(name) {\n\t\tvar _this = this;\n\t\treturn _this.handleOperation(async () => {\n\t\t\treturn await post(_this.fetch, `${_this.url}/bucket`, { name }, { headers: _this.headers });\n\t\t});\n\t}\n\t/**\n\t* @alpha\n\t*\n\t* Retrieves the details of all Analytics Storage buckets within an existing project\n\t* Only returns buckets of type 'ANALYTICS'\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Analytics Buckets\n\t* @param options Query parameters for listing buckets\n\t* @param options.limit Maximum number of buckets to return\n\t* @param options.offset Number of buckets to skip\n\t* @param options.sortColumn Column to sort by ('name', 'created_at', 'updated_at')\n\t* @param options.sortOrder Sort order ('asc' or 'desc')\n\t* @param options.search Search term to filter bucket names\n\t* @returns Promise with response containing array of analytics buckets or error\n\t*\n\t* @example List analytics buckets\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .analytics\n\t*   .listBuckets({\n\t*     limit: 10,\n\t*     offset: 0,\n\t*     sortColumn: 'created_at',\n\t*     sortOrder: 'desc'\n\t*   })\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": [\n\t*     {\n\t*       \"name\": \"analytics-data\",\n\t*       \"type\": \"ANALYTICS\",\n\t*       \"format\": \"iceberg\",\n\t*       \"created_at\": \"2024-05-22T22:26:05.100Z\",\n\t*       \"updated_at\": \"2024-05-22T22:26:05.100Z\"\n\t*     }\n\t*   ],\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - Retrieves the details of all Analytics Storage buckets within an existing project\n\t* - Only returns buckets of type 'ANALYTICS'\n\t*/\n\tasync listBuckets(options) {\n\t\tvar _this2 = this;\n\t\treturn _this2.handleOperation(async () => {\n\t\t\tconst queryParams = new URLSearchParams();\n\t\t\tif ((options === null || options === void 0 ? void 0 : options.limit) !== void 0) queryParams.set(\"limit\", options.limit.toString());\n\t\t\tif ((options === null || options === void 0 ? void 0 : options.offset) !== void 0) queryParams.set(\"offset\", options.offset.toString());\n\t\t\tif (options === null || options === void 0 ? void 0 : options.sortColumn) queryParams.set(\"sortColumn\", options.sortColumn);\n\t\t\tif (options === null || options === void 0 ? void 0 : options.sortOrder) queryParams.set(\"sortOrder\", options.sortOrder);\n\t\t\tif (options === null || options === void 0 ? void 0 : options.search) queryParams.set(\"search\", options.search);\n\t\t\tconst queryString = queryParams.toString();\n\t\t\tconst url = queryString ? `${_this2.url}/bucket?${queryString}` : `${_this2.url}/bucket`;\n\t\t\treturn await get(_this2.fetch, url, { headers: _this2.headers });\n\t\t});\n\t}\n\t/**\n\t* @alpha\n\t*\n\t* Deletes an existing analytics bucket\n\t* A bucket can't be deleted with existing objects inside it\n\t* You must first empty the bucket before deletion\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Analytics Buckets\n\t* @param bucketName The unique identifier of the bucket you would like to delete\n\t* @returns Promise with response containing success message or error\n\t*\n\t* @example Delete analytics bucket\n\t* ```js\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .analytics\n\t*   .deleteBucket('analytics-data')\n\t* ```\n\t*\n\t* Response:\n\t* ```json\n\t* {\n\t*   \"data\": {\n\t*     \"message\": \"Successfully deleted\"\n\t*   },\n\t*   \"error\": null\n\t* }\n\t* ```\n\t*\n\t* @remarks\n\t* - Deletes an analytics bucket\n\t*/\n\tasync deleteBucket(bucketName) {\n\t\tvar _this3 = this;\n\t\treturn _this3.handleOperation(async () => {\n\t\t\treturn await remove(_this3.fetch, `${_this3.url}/bucket/${bucketName}`, {}, { headers: _this3.headers });\n\t\t});\n\t}\n\t/**\n\t* @alpha\n\t*\n\t* Get an Iceberg REST Catalog client configured for a specific analytics bucket\n\t* Use this to perform advanced table and namespace operations within the bucket\n\t* The returned client provides full access to the Apache Iceberg REST Catalog API\n\t* with the Supabase `{ data, error }` pattern for consistent error handling on all operations.\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Analytics Buckets\n\t* @param bucketName - The name of the analytics bucket (warehouse) to connect to\n\t* @returns The wrapped Iceberg catalog client\n\t* @throws {StorageError} If the bucket name is invalid\n\t*\n\t* @example Get catalog and create table\n\t* ```js\n\t* // First, create an analytics bucket\n\t* const { data: bucket, error: bucketError } = await supabase\n\t*   .storage\n\t*   .analytics\n\t*   .createBucket('analytics-data')\n\t*\n\t* // Get the Iceberg catalog for that bucket\n\t* const catalog = supabase.storage.analytics.from('analytics-data')\n\t*\n\t* // Create a namespace\n\t* const { error: nsError } = await catalog.createNamespace({ namespace: ['default'] })\n\t*\n\t* // Create a table with schema\n\t* const { data: tableMetadata, error: tableError } = await catalog.createTable(\n\t*   { namespace: ['default'] },\n\t*   {\n\t*     name: 'events',\n\t*     schema: {\n\t*       type: 'struct',\n\t*       fields: [\n\t*         { id: 1, name: 'id', type: 'long', required: true },\n\t*         { id: 2, name: 'timestamp', type: 'timestamp', required: true },\n\t*         { id: 3, name: 'user_id', type: 'string', required: false }\n\t*       ],\n\t*       'schema-id': 0,\n\t*       'identifier-field-ids': [1]\n\t*     },\n\t*     'partition-spec': {\n\t*       'spec-id': 0,\n\t*       fields: []\n\t*     },\n\t*     'write-order': {\n\t*       'order-id': 0,\n\t*       fields: []\n\t*     },\n\t*     properties: {\n\t*       'write.format.default': 'parquet'\n\t*     }\n\t*   }\n\t* )\n\t* ```\n\t*\n\t* @example List tables in namespace\n\t* ```js\n\t* const catalog = supabase.storage.analytics.from('analytics-data')\n\t*\n\t* // List all tables in the default namespace\n\t* const { data: tables, error: listError } = await catalog.listTables({ namespace: ['default'] })\n\t* if (listError) {\n\t*   if (listError.isNotFound()) {\n\t*     console.log('Namespace not found')\n\t*   }\n\t*   return\n\t* }\n\t* console.log(tables) // [{ namespace: ['default'], name: 'events' }]\n\t* ```\n\t*\n\t* @example Working with namespaces\n\t* ```js\n\t* const catalog = supabase.storage.analytics.from('analytics-data')\n\t*\n\t* // List all namespaces\n\t* const { data: namespaces } = await catalog.listNamespaces()\n\t*\n\t* // Create namespace with properties\n\t* await catalog.createNamespace(\n\t*   { namespace: ['production'] },\n\t*   { properties: { owner: 'data-team', env: 'prod' } }\n\t* )\n\t* ```\n\t*\n\t* @example Cleanup operations\n\t* ```js\n\t* const catalog = supabase.storage.analytics.from('analytics-data')\n\t*\n\t* // Drop table with purge option (removes all data)\n\t* const { error: dropError } = await catalog.dropTable(\n\t*   { namespace: ['default'], name: 'events' },\n\t*   { purge: true }\n\t* )\n\t*\n\t* if (dropError?.isNotFound()) {\n\t*   console.log('Table does not exist')\n\t* }\n\t*\n\t* // Drop namespace (must be empty)\n\t* await catalog.dropNamespace({ namespace: ['default'] })\n\t* ```\n\t*\n\t* @remarks\n\t* This method provides a bridge between Supabase's bucket management and the standard\n\t* Apache Iceberg REST Catalog API. The bucket name maps to the Iceberg warehouse parameter.\n\t* All authentication and configuration is handled automatically using your Supabase credentials.\n\t*\n\t* **Error Handling**: Invalid bucket names throw immediately. All catalog\n\t* operations return `{ data, error }` where errors are `IcebergError` instances from iceberg-js.\n\t* Use helper methods like `error.isNotFound()` or check `error.status` for specific error handling.\n\t* Use `.throwOnError()` on the analytics client if you prefer exceptions for catalog operations.\n\t*\n\t* **Cleanup Operations**: When using `dropTable`, the `purge: true` option permanently\n\t* deletes all table data. Without it, the table is marked as deleted but data remains.\n\t*\n\t* **Library Dependency**: The returned catalog wraps `IcebergRestCatalog` from iceberg-js.\n\t* For complete API documentation and advanced usage, refer to the\n\t* [iceberg-js documentation](https://supabase.github.io/iceberg-js/).\n\t*/\n\tfrom(bucketName) {\n\t\tvar _this4 = this;\n\t\tif (!isValidBucketName(bucketName)) throw new StorageError(\"Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.\");\n\t\tconst catalog = new IcebergRestCatalog({\n\t\t\tbaseUrl: this.url,\n\t\t\tcatalogName: bucketName,\n\t\t\tauth: {\n\t\t\t\ttype: \"custom\",\n\t\t\t\tgetHeaders: async () => _this4.headers\n\t\t\t},\n\t\t\tfetch: this.fetch\n\t\t});\n\t\tconst shouldThrowOnError = this.shouldThrowOnError;\n\t\treturn new Proxy(catalog, { get(target, prop) {\n\t\t\tconst value = target[prop];\n\t\t\tif (typeof value !== \"function\") return value;\n\t\t\treturn async (...args) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdata: await value.apply(target, args),\n\t\t\t\t\t\terror: null\n\t\t\t\t\t};\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (shouldThrowOnError) throw error;\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\terror\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t};\n\t\t} });\n\t}\n};\n\n//#endregion\n//#region src/packages/VectorIndexApi.ts\n/**\n* @hidden\n* Base implementation for vector index operations.\n* Use {@link VectorBucketScope} via `supabase.storage.vectors.from('bucket')` instead.\n*/\nvar VectorIndexApi = class extends BaseApiClient {\n\t/** Creates a new VectorIndexApi instance */\n\tconstructor(url, headers = {}, fetch$1) {\n\t\tconst finalUrl = url.replace(/\\/$/, \"\");\n\t\tconst finalHeaders = _objectSpread2(_objectSpread2({}, DEFAULT_HEADERS), {}, { \"Content-Type\": \"application/json\" }, headers);\n\t\tsuper(finalUrl, finalHeaders, fetch$1, \"vectors\");\n\t}\n\t/** Creates a new vector index within a bucket */\n\tasync createIndex(options) {\n\t\tvar _this = this;\n\t\treturn _this.handleOperation(async () => {\n\t\t\treturn await vectorsApi.post(_this.fetch, `${_this.url}/CreateIndex`, options, { headers: _this.headers }) || {};\n\t\t});\n\t}\n\t/** Retrieves metadata for a specific vector index */\n\tasync getIndex(vectorBucketName, indexName) {\n\t\tvar _this2 = this;\n\t\treturn _this2.handleOperation(async () => {\n\t\t\treturn await vectorsApi.post(_this2.fetch, `${_this2.url}/GetIndex`, {\n\t\t\t\tvectorBucketName,\n\t\t\t\tindexName\n\t\t\t}, { headers: _this2.headers });\n\t\t});\n\t}\n\t/** Lists vector indexes within a bucket with optional filtering and pagination */\n\tasync listIndexes(options) {\n\t\tvar _this3 = this;\n\t\treturn _this3.handleOperation(async () => {\n\t\t\treturn await vectorsApi.post(_this3.fetch, `${_this3.url}/ListIndexes`, options, { headers: _this3.headers });\n\t\t});\n\t}\n\t/** Deletes a vector index and all its data */\n\tasync deleteIndex(vectorBucketName, indexName) {\n\t\tvar _this4 = this;\n\t\treturn _this4.handleOperation(async () => {\n\t\t\treturn await vectorsApi.post(_this4.fetch, `${_this4.url}/DeleteIndex`, {\n\t\t\t\tvectorBucketName,\n\t\t\t\tindexName\n\t\t\t}, { headers: _this4.headers }) || {};\n\t\t});\n\t}\n};\n\n//#endregion\n//#region src/packages/VectorDataApi.ts\n/**\n* @hidden\n* Base implementation for vector data operations.\n* Use {@link VectorIndexScope} via `supabase.storage.vectors.from('bucket').index('idx')` instead.\n*/\nvar VectorDataApi = class extends BaseApiClient {\n\t/** Creates a new VectorDataApi instance */\n\tconstructor(url, headers = {}, fetch$1) {\n\t\tconst finalUrl = url.replace(/\\/$/, \"\");\n\t\tconst finalHeaders = _objectSpread2(_objectSpread2({}, DEFAULT_HEADERS), {}, { \"Content-Type\": \"application/json\" }, headers);\n\t\tsuper(finalUrl, finalHeaders, fetch$1, \"vectors\");\n\t}\n\t/** Inserts or updates vectors in batch (1-500 per request) */\n\tasync putVectors(options) {\n\t\tvar _this = this;\n\t\tif (options.vectors.length < 1 || options.vectors.length > 500) throw new Error(\"Vector batch size must be between 1 and 500 items\");\n\t\treturn _this.handleOperation(async () => {\n\t\t\treturn await vectorsApi.post(_this.fetch, `${_this.url}/PutVectors`, options, { headers: _this.headers }) || {};\n\t\t});\n\t}\n\t/** Retrieves vectors by their keys in batch */\n\tasync getVectors(options) {\n\t\tvar _this2 = this;\n\t\treturn _this2.handleOperation(async () => {\n\t\t\treturn await vectorsApi.post(_this2.fetch, `${_this2.url}/GetVectors`, options, { headers: _this2.headers });\n\t\t});\n\t}\n\t/** Lists vectors in an index with pagination */\n\tasync listVectors(options) {\n\t\tvar _this3 = this;\n\t\tif (options.segmentCount !== void 0) {\n\t\t\tif (options.segmentCount < 1 || options.segmentCount > 16) throw new Error(\"segmentCount must be between 1 and 16\");\n\t\t\tif (options.segmentIndex !== void 0) {\n\t\t\t\tif (options.segmentIndex < 0 || options.segmentIndex >= options.segmentCount) throw new Error(`segmentIndex must be between 0 and ${options.segmentCount - 1}`);\n\t\t\t}\n\t\t}\n\t\treturn _this3.handleOperation(async () => {\n\t\t\treturn await vectorsApi.post(_this3.fetch, `${_this3.url}/ListVectors`, options, { headers: _this3.headers });\n\t\t});\n\t}\n\t/** Queries for similar vectors using approximate nearest neighbor search */\n\tasync queryVectors(options) {\n\t\tvar _this4 = this;\n\t\treturn _this4.handleOperation(async () => {\n\t\t\treturn await vectorsApi.post(_this4.fetch, `${_this4.url}/QueryVectors`, options, { headers: _this4.headers });\n\t\t});\n\t}\n\t/** Deletes vectors by their keys in batch (1-500 per request) */\n\tasync deleteVectors(options) {\n\t\tvar _this5 = this;\n\t\tif (options.keys.length < 1 || options.keys.length > 500) throw new Error(\"Keys batch size must be between 1 and 500 items\");\n\t\treturn _this5.handleOperation(async () => {\n\t\t\treturn await vectorsApi.post(_this5.fetch, `${_this5.url}/DeleteVectors`, options, { headers: _this5.headers }) || {};\n\t\t});\n\t}\n};\n\n//#endregion\n//#region src/packages/VectorBucketApi.ts\n/**\n* @hidden\n* Base implementation for vector bucket operations.\n* Use {@link StorageVectorsClient} via `supabase.storage.vectors` instead.\n*/\nvar VectorBucketApi = class extends BaseApiClient {\n\t/** Creates a new VectorBucketApi instance */\n\tconstructor(url, headers = {}, fetch$1) {\n\t\tconst finalUrl = url.replace(/\\/$/, \"\");\n\t\tconst finalHeaders = _objectSpread2(_objectSpread2({}, DEFAULT_HEADERS), {}, { \"Content-Type\": \"application/json\" }, headers);\n\t\tsuper(finalUrl, finalHeaders, fetch$1, \"vectors\");\n\t}\n\t/** Creates a new vector bucket */\n\tasync createBucket(vectorBucketName) {\n\t\tvar _this = this;\n\t\treturn _this.handleOperation(async () => {\n\t\t\treturn await vectorsApi.post(_this.fetch, `${_this.url}/CreateVectorBucket`, { vectorBucketName }, { headers: _this.headers }) || {};\n\t\t});\n\t}\n\t/** Retrieves metadata for a specific vector bucket */\n\tasync getBucket(vectorBucketName) {\n\t\tvar _this2 = this;\n\t\treturn _this2.handleOperation(async () => {\n\t\t\treturn await vectorsApi.post(_this2.fetch, `${_this2.url}/GetVectorBucket`, { vectorBucketName }, { headers: _this2.headers });\n\t\t});\n\t}\n\t/** Lists vector buckets with optional filtering and pagination */\n\tasync listBuckets(options = {}) {\n\t\tvar _this3 = this;\n\t\treturn _this3.handleOperation(async () => {\n\t\t\treturn await vectorsApi.post(_this3.fetch, `${_this3.url}/ListVectorBuckets`, options, { headers: _this3.headers });\n\t\t});\n\t}\n\t/** Deletes a vector bucket (must be empty first) */\n\tasync deleteBucket(vectorBucketName) {\n\t\tvar _this4 = this;\n\t\treturn _this4.handleOperation(async () => {\n\t\t\treturn await vectorsApi.post(_this4.fetch, `${_this4.url}/DeleteVectorBucket`, { vectorBucketName }, { headers: _this4.headers }) || {};\n\t\t});\n\t}\n};\n\n//#endregion\n//#region src/packages/StorageVectorsClient.ts\n/**\n*\n* @alpha\n*\n* Main client for interacting with S3 Vectors API\n* Provides access to bucket, index, and vector data operations\n*\n* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n*\n* **Usage Patterns:**\n*\n* ```typescript\n* const { data, error } = await supabase\n*  .storage\n*  .vectors\n*  .createBucket('embeddings-prod')\n*\n* // Access index operations via buckets\n* const bucket = supabase.storage.vectors.from('embeddings-prod')\n* await bucket.createIndex({\n*   indexName: 'documents',\n*   dataType: 'float32',\n*   dimension: 1536,\n*   distanceMetric: 'cosine'\n* })\n*\n* // Access vector operations via index\n* const index = bucket.index('documents')\n* await index.putVectors({\n*   vectors: [\n*     { key: 'doc-1', data: { float32: [...] }, metadata: { title: 'Intro' } }\n*   ]\n* })\n*\n* // Query similar vectors\n* const { data } = await index.queryVectors({\n*   queryVector: { float32: [...] },\n*   topK: 5,\n*   returnDistance: true\n* })\n* ```\n*/\nvar StorageVectorsClient = class extends VectorBucketApi {\n\t/**\n\t* @alpha\n\t*\n\t* Creates a StorageVectorsClient that can manage buckets, indexes, and vectors.\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param url - Base URL of the Storage Vectors REST API.\n\t* @param options.headers - Optional headers (for example `Authorization`) applied to every request.\n\t* @param options.fetch - Optional custom `fetch` implementation for non-browser runtimes.\n\t*\n\t* @example Using supabase-js (recommended)\n\t* ```typescript\n\t* import { createClient } from '@supabase/supabase-js'\n\t*\n\t* const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n\t* const bucket = supabase.storage.vectors.from('embeddings-prod')\n\t* ```\n\t*\n\t* @example Standalone import for bundle-sensitive environments\n\t* ```typescript\n\t* import { StorageVectorsClient } from '@supabase/storage-js'\n\t*\n\t* const client = new StorageVectorsClient(url, options)\n\t* ```\n\t*/\n\tconstructor(url, options = {}) {\n\t\tsuper(url, options.headers || {}, options.fetch);\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Access operations for a specific vector bucket\n\t* Returns a scoped client for index and vector operations within the bucket\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param vectorBucketName - Name of the vector bucket\n\t* @returns Bucket-scoped client with index and vector operations\n\t*\n\t* @example Accessing a vector bucket\n\t* ```typescript\n\t* const bucket = supabase.storage.vectors.from('embeddings-prod')\n\t* ```\n\t*/\n\tfrom(vectorBucketName) {\n\t\treturn new VectorBucketScope(this.url, this.headers, vectorBucketName, this.fetch);\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Creates a new vector bucket\n\t* Vector buckets are containers for vector indexes and their data\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param vectorBucketName - Unique name for the vector bucket\n\t* @returns Promise with empty response on success or error\n\t*\n\t* @example Creating a vector bucket\n\t* ```typescript\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .vectors\n\t*   .createBucket('embeddings-prod')\n\t* ```\n\t*/\n\tasync createBucket(vectorBucketName) {\n\t\tvar _superprop_getCreateBucket = () => super.createBucket, _this = this;\n\t\treturn _superprop_getCreateBucket().call(_this, vectorBucketName);\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Retrieves metadata for a specific vector bucket\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param vectorBucketName - Name of the vector bucket\n\t* @returns Promise with bucket metadata or error\n\t*\n\t* @example Get bucket metadata\n\t* ```typescript\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .vectors\n\t*   .getBucket('embeddings-prod')\n\t*\n\t* console.log('Bucket created:', data?.vectorBucket.creationTime)\n\t* ```\n\t*/\n\tasync getBucket(vectorBucketName) {\n\t\tvar _superprop_getGetBucket = () => super.getBucket, _this2 = this;\n\t\treturn _superprop_getGetBucket().call(_this2, vectorBucketName);\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Lists all vector buckets with optional filtering and pagination\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param options - Optional filters (prefix, maxResults, nextToken)\n\t* @returns Promise with list of buckets or error\n\t*\n\t* @example List vector buckets\n\t* ```typescript\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .vectors\n\t*   .listBuckets({ prefix: 'embeddings-' })\n\t*\n\t* data?.vectorBuckets.forEach(bucket => {\n\t*   console.log(bucket.vectorBucketName)\n\t* })\n\t* ```\n\t*/\n\tasync listBuckets(options = {}) {\n\t\tvar _superprop_getListBuckets = () => super.listBuckets, _this3 = this;\n\t\treturn _superprop_getListBuckets().call(_this3, options);\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Deletes a vector bucket (bucket must be empty)\n\t* All indexes must be deleted before deleting the bucket\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param vectorBucketName - Name of the vector bucket to delete\n\t* @returns Promise with empty response on success or error\n\t*\n\t* @example Delete a vector bucket\n\t* ```typescript\n\t* const { data, error } = await supabase\n\t*   .storage\n\t*   .vectors\n\t*   .deleteBucket('embeddings-old')\n\t* ```\n\t*/\n\tasync deleteBucket(vectorBucketName) {\n\t\tvar _superprop_getDeleteBucket = () => super.deleteBucket, _this4 = this;\n\t\treturn _superprop_getDeleteBucket().call(_this4, vectorBucketName);\n\t}\n};\n/**\n*\n* @alpha\n*\n* Scoped client for operations within a specific vector bucket\n* Provides index management and access to vector operations\n*\n* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n*/\nvar VectorBucketScope = class extends VectorIndexApi {\n\t/**\n\t* @alpha\n\t*\n\t* Creates a helper that automatically scopes all index operations to the provided bucket.\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @example Creating a vector bucket scope\n\t* ```typescript\n\t* const bucket = supabase.storage.vectors.from('embeddings-prod')\n\t* ```\n\t*/\n\tconstructor(url, headers, vectorBucketName, fetch$1) {\n\t\tsuper(url, headers, fetch$1);\n\t\tthis.vectorBucketName = vectorBucketName;\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Creates a new vector index in this bucket\n\t* Convenience method that automatically includes the bucket name\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param options - Index configuration (vectorBucketName is automatically set)\n\t* @returns Promise with empty response on success or error\n\t*\n\t* @example Creating a vector index\n\t* ```typescript\n\t* const bucket = supabase.storage.vectors.from('embeddings-prod')\n\t* await bucket.createIndex({\n\t*   indexName: 'documents-openai',\n\t*   dataType: 'float32',\n\t*   dimension: 1536,\n\t*   distanceMetric: 'cosine',\n\t*   metadataConfiguration: {\n\t*     nonFilterableMetadataKeys: ['raw_text']\n\t*   }\n\t* })\n\t* ```\n\t*/\n\tasync createIndex(options) {\n\t\tvar _superprop_getCreateIndex = () => super.createIndex, _this5 = this;\n\t\treturn _superprop_getCreateIndex().call(_this5, _objectSpread2(_objectSpread2({}, options), {}, { vectorBucketName: _this5.vectorBucketName }));\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Lists indexes in this bucket\n\t* Convenience method that automatically includes the bucket name\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param options - Listing options (vectorBucketName is automatically set)\n\t* @returns Promise with response containing indexes array and pagination token or error\n\t*\n\t* @example List indexes\n\t* ```typescript\n\t* const bucket = supabase.storage.vectors.from('embeddings-prod')\n\t* const { data } = await bucket.listIndexes({ prefix: 'documents-' })\n\t* ```\n\t*/\n\tasync listIndexes(options = {}) {\n\t\tvar _superprop_getListIndexes = () => super.listIndexes, _this6 = this;\n\t\treturn _superprop_getListIndexes().call(_this6, _objectSpread2(_objectSpread2({}, options), {}, { vectorBucketName: _this6.vectorBucketName }));\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Retrieves metadata for a specific index in this bucket\n\t* Convenience method that automatically includes the bucket name\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param indexName - Name of the index to retrieve\n\t* @returns Promise with index metadata or error\n\t*\n\t* @example Get index metadata\n\t* ```typescript\n\t* const bucket = supabase.storage.vectors.from('embeddings-prod')\n\t* const { data } = await bucket.getIndex('documents-openai')\n\t* console.log('Dimension:', data?.index.dimension)\n\t* ```\n\t*/\n\tasync getIndex(indexName) {\n\t\tvar _superprop_getGetIndex = () => super.getIndex, _this7 = this;\n\t\treturn _superprop_getGetIndex().call(_this7, _this7.vectorBucketName, indexName);\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Deletes an index from this bucket\n\t* Convenience method that automatically includes the bucket name\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param indexName - Name of the index to delete\n\t* @returns Promise with empty response on success or error\n\t*\n\t* @example Delete an index\n\t* ```typescript\n\t* const bucket = supabase.storage.vectors.from('embeddings-prod')\n\t* await bucket.deleteIndex('old-index')\n\t* ```\n\t*/\n\tasync deleteIndex(indexName) {\n\t\tvar _superprop_getDeleteIndex = () => super.deleteIndex, _this8 = this;\n\t\treturn _superprop_getDeleteIndex().call(_this8, _this8.vectorBucketName, indexName);\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Access operations for a specific index within this bucket\n\t* Returns a scoped client for vector data operations\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param indexName - Name of the index\n\t* @returns Index-scoped client with vector data operations\n\t*\n\t* @example Accessing an index\n\t* ```typescript\n\t* const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai')\n\t*\n\t* // Insert vectors\n\t* await index.putVectors({\n\t*   vectors: [\n\t*     { key: 'doc-1', data: { float32: [...] }, metadata: { title: 'Intro' } }\n\t*   ]\n\t* })\n\t*\n\t* // Query similar vectors\n\t* const { data } = await index.queryVectors({\n\t*   queryVector: { float32: [...] },\n\t*   topK: 5\n\t* })\n\t* ```\n\t*/\n\tindex(indexName) {\n\t\treturn new VectorIndexScope(this.url, this.headers, this.vectorBucketName, indexName, this.fetch);\n\t}\n};\n/**\n*\n* @alpha\n*\n* Scoped client for operations within a specific vector index\n* Provides vector data operations (put, get, list, query, delete)\n*\n* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n*/\nvar VectorIndexScope = class extends VectorDataApi {\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Creates a helper that automatically scopes all vector operations to the provided bucket/index names.\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @example Creating a vector index scope\n\t* ```typescript\n\t* const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai')\n\t* ```\n\t*/\n\tconstructor(url, headers, vectorBucketName, indexName, fetch$1) {\n\t\tsuper(url, headers, fetch$1);\n\t\tthis.vectorBucketName = vectorBucketName;\n\t\tthis.indexName = indexName;\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Inserts or updates vectors in this index\n\t* Convenience method that automatically includes bucket and index names\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param options - Vector insertion options (bucket and index names automatically set)\n\t* @returns Promise with empty response on success or error\n\t*\n\t* @example Insert vectors into an index\n\t* ```typescript\n\t* const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai')\n\t* await index.putVectors({\n\t*   vectors: [\n\t*     {\n\t*       key: 'doc-1',\n\t*       data: { float32: [0.1, 0.2, ...] },\n\t*       metadata: { title: 'Introduction', page: 1 }\n\t*     }\n\t*   ]\n\t* })\n\t* ```\n\t*/\n\tasync putVectors(options) {\n\t\tvar _superprop_getPutVectors = () => super.putVectors, _this9 = this;\n\t\treturn _superprop_getPutVectors().call(_this9, _objectSpread2(_objectSpread2({}, options), {}, {\n\t\t\tvectorBucketName: _this9.vectorBucketName,\n\t\t\tindexName: _this9.indexName\n\t\t}));\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Retrieves vectors by keys from this index\n\t* Convenience method that automatically includes bucket and index names\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param options - Vector retrieval options (bucket and index names automatically set)\n\t* @returns Promise with response containing vectors array or error\n\t*\n\t* @example Get vectors by keys\n\t* ```typescript\n\t* const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai')\n\t* const { data } = await index.getVectors({\n\t*   keys: ['doc-1', 'doc-2'],\n\t*   returnMetadata: true\n\t* })\n\t* ```\n\t*/\n\tasync getVectors(options) {\n\t\tvar _superprop_getGetVectors = () => super.getVectors, _this10 = this;\n\t\treturn _superprop_getGetVectors().call(_this10, _objectSpread2(_objectSpread2({}, options), {}, {\n\t\t\tvectorBucketName: _this10.vectorBucketName,\n\t\t\tindexName: _this10.indexName\n\t\t}));\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Lists vectors in this index with pagination\n\t* Convenience method that automatically includes bucket and index names\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param options - Listing options (bucket and index names automatically set)\n\t* @returns Promise with response containing vectors array and pagination token or error\n\t*\n\t* @example List vectors with pagination\n\t* ```typescript\n\t* const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai')\n\t* const { data } = await index.listVectors({\n\t*   maxResults: 500,\n\t*   returnMetadata: true\n\t* })\n\t* ```\n\t*/\n\tasync listVectors(options = {}) {\n\t\tvar _superprop_getListVectors = () => super.listVectors, _this11 = this;\n\t\treturn _superprop_getListVectors().call(_this11, _objectSpread2(_objectSpread2({}, options), {}, {\n\t\t\tvectorBucketName: _this11.vectorBucketName,\n\t\t\tindexName: _this11.indexName\n\t\t}));\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Queries for similar vectors in this index\n\t* Convenience method that automatically includes bucket and index names\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param options - Query options (bucket and index names automatically set)\n\t* @returns Promise with response containing vectors ordered by distance, an optional pagination token, or an error\n\t*\n\t* @example Query similar vectors\n\t* ```typescript\n\t* const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai')\n\t* const { data } = await index.queryVectors({\n\t*   queryVector: { float32: [0.1, 0.2, ...] },\n\t*   topK: 5,\n\t*   filter: { category: 'technical' },\n\t*   returnDistance: true,\n\t*   returnMetadata: true\n\t* })\n\t* ```\n\t*/\n\tasync queryVectors(options) {\n\t\tvar _superprop_getQueryVectors = () => super.queryVectors, _this12 = this;\n\t\treturn _superprop_getQueryVectors().call(_this12, _objectSpread2(_objectSpread2({}, options), {}, {\n\t\t\tvectorBucketName: _this12.vectorBucketName,\n\t\t\tindexName: _this12.indexName\n\t\t}));\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Deletes vectors by keys from this index\n\t* Convenience method that automatically includes bucket and index names\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t* @param options - Deletion options (bucket and index names automatically set)\n\t* @returns Promise with empty response on success or error\n\t*\n\t* @example Delete vectors by keys\n\t* ```typescript\n\t* const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai')\n\t* await index.deleteVectors({\n\t*   keys: ['doc-1', 'doc-2', 'doc-3']\n\t* })\n\t* ```\n\t*/\n\tasync deleteVectors(options) {\n\t\tvar _superprop_getDeleteVectors = () => super.deleteVectors, _this13 = this;\n\t\treturn _superprop_getDeleteVectors().call(_this13, _objectSpread2(_objectSpread2({}, options), {}, {\n\t\t\tvectorBucketName: _this13.vectorBucketName,\n\t\t\tindexName: _this13.indexName\n\t\t}));\n\t}\n};\n\n//#endregion\n//#region src/StorageClient.ts\nvar StorageClient = class extends StorageBucketApi {\n\t/**\n\t* Creates a client for Storage buckets, files, analytics, and vectors.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t*\n\t* @example Using supabase-js (recommended)\n\t* ```ts\n\t* import { createClient } from '@supabase/supabase-js'\n\t*\n\t* const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n\t* const avatars = supabase.storage.from('avatars')\n\t* ```\n\t*\n\t* @example Standalone import for bundle-sensitive environments\n\t* ```ts\n\t* import { StorageClient } from '@supabase/storage-js'\n\t*\n\t* const storage = new StorageClient('https://xyzcompany.supabase.co/storage/v1', {\n\t*   apikey: 'your-publishable-key',\n\t* })\n\t* const avatars = storage.from('avatars')\n\t* ```\n\t*/\n\tconstructor(url, headers = {}, fetch$1, opts) {\n\t\tsuper(url, headers, fetch$1, opts);\n\t}\n\t/**\n\t* Perform file operation in a bucket.\n\t*\n\t* @category Storage\n\t* @subcategory File Buckets\n\t*\n\t* @param id The bucket id to operate on.\n\t*\n\t* @example Accessing a bucket\n\t* ```typescript\n\t* const avatars = supabase.storage.from('avatars')\n\t* ```\n\t*/\n\tfrom(id) {\n\t\treturn new StorageFileApi(this.url, this.headers, id, this.fetch);\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Access vector storage operations.\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Vector Buckets\n\t*\n\t* @returns A StorageVectorsClient instance configured with the current storage settings.\n\t*/\n\tget vectors() {\n\t\treturn new StorageVectorsClient(this.url + \"/vector\", {\n\t\t\theaders: this.headers,\n\t\t\tfetch: this.fetch\n\t\t});\n\t}\n\t/**\n\t*\n\t* @alpha\n\t*\n\t* Access analytics storage operations using Iceberg tables.\n\t*\n\t* **Public alpha:** This API is part of a public alpha release and may not be available to your account type.\n\t*\n\t* @category Storage\n\t* @subcategory Analytics Buckets\n\t*\n\t* @returns A StorageAnalyticsClient instance configured with the current storage settings.\n\t*/\n\tget analytics() {\n\t\treturn new StorageAnalyticsClient(this.url + \"/iceberg\", this.headers, this.fetch);\n\t}\n};\n\n//#endregion\nexport { StorageAnalyticsClient, StorageApiError, StorageClient, StorageError, StorageUnknownError, StorageVectorsApiError, StorageVectorsClient, StorageVectorsError, StorageVectorsErrorCode, StorageVectorsUnknownError, VectorBucketApi, VectorBucketScope, VectorDataApi, VectorIndexApi, VectorIndexScope, isStorageError, isStorageVectorsError };\n//# sourceMappingURL=index.mjs.map","// Generated automatically during releases by scripts/update-version-files.ts\n// This file provides runtime access to the package version for:\n// - HTTP request headers (e.g., X-Client-Info header for API requests)\n// - Debugging and support (identifying which version is running)\n// - Telemetry and logging (version reporting in errors/analytics)\n// - Ensuring build artifacts match the published package version\nexport const version = '2.116.0';\n//# sourceMappingURL=version.js.map","import { version } from './version';\n/** Current session will be checked for refresh at this interval. */\nexport const AUTO_REFRESH_TICK_DURATION_MS = 30 * 1000;\n/**\n * A token refresh will be attempted this many ticks before the current session expires. */\nexport const AUTO_REFRESH_TICK_THRESHOLD = 3;\n/*\n * Earliest time before an access token expires that the session should be refreshed.\n */\nexport const EXPIRY_MARGIN_MS = AUTO_REFRESH_TICK_THRESHOLD * AUTO_REFRESH_TICK_DURATION_MS;\n/**\n * After a refresh fails, serial callers (including the next auto-refresh\n * tick) within this window receive the cached failure instead of firing\n * another /token request. Two ticks: each outage burns at most one /token\n * call per cooldown window. Cleared on any successful refresh (locally or\n * via BroadcastChannel from another tab) and on `_removeSession`.\n */\nexport const REFRESH_FAILURE_COOLDOWN_MS = 2 * AUTO_REFRESH_TICK_DURATION_MS;\nexport const GOTRUE_URL = 'http://localhost:9999';\nexport const STORAGE_KEY = 'supabase.auth.token';\nexport const AUDIENCE = '';\nexport const DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version}` };\nexport const NETWORK_FAILURE = {\n    MAX_RETRIES: 10,\n    RETRY_INTERVAL: 2, // in deciseconds\n};\nexport const API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version';\nexport const API_VERSIONS = {\n    '2024-01-01': {\n        timestamp: Date.parse('2024-01-01T00:00:00.0Z'),\n        name: '2024-01-01',\n    },\n};\nexport const BASE64URL_REGEX = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;\n/**\n * Reserved query parameter appended to `redirectTo` URLs (behind\n * `experimental.appendPkceFlowIdToRedirects`) that correlates a PKCE callback\n * with the code verifier stored when its flow started. It round-trips through\n * the auth server untouched and identifies a verifier slot in storage — the\n * verifier itself never appears in a URL.\n */\nexport const PKCE_FLOW_ID_PARAM = 'sb_flow_id';\n/**\n * Maximum number of PKCE code verifiers kept in storage at once. Starting a\n * new flow beyond this evicts the oldest pending verifier.\n */\nexport const PKCE_MAX_CONCURRENT_FLOWS = 5;\nexport const JWKS_TTL = 10 * 60 * 1000; // 10 minutes\n//# sourceMappingURL=constants.js.map","/**\n * Base error thrown by Supabase Auth helpers.\n *\n * @example\n * ```ts\n * import { AuthError } from '@supabase/auth-js'\n *\n * throw new AuthError('Unexpected auth error', 500, 'unexpected')\n * ```\n */\nexport class AuthError extends Error {\n    constructor(message, status, code) {\n        super(message);\n        this.__isAuthError = true;\n        this.name = 'AuthError';\n        this.status = status;\n        this.code = code;\n    }\n    toJSON() {\n        return {\n            name: this.name,\n            message: this.message,\n            status: this.status,\n            code: this.code,\n        };\n    }\n}\nexport function isAuthError(error) {\n    return typeof error === 'object' && error !== null && '__isAuthError' in error;\n}\n/**\n * Error returned directly from the GoTrue REST API.\n *\n * @example\n * ```ts\n * import { AuthApiError } from '@supabase/auth-js'\n *\n * throw new AuthApiError('Invalid credentials', 400, 'invalid_credentials')\n * ```\n */\nexport class AuthApiError extends AuthError {\n    constructor(message, status, code) {\n        super(message, status, code);\n        this.name = 'AuthApiError';\n        this.status = status;\n        this.code = code;\n    }\n}\nexport function isAuthApiError(error) {\n    return isAuthError(error) && error.name === 'AuthApiError';\n}\n/**\n * Wraps non-standard errors so callers can inspect the root cause.\n *\n * @example\n * ```ts\n * import { AuthUnknownError } from '@supabase/auth-js'\n *\n * try {\n *   await someAuthCall()\n * } catch (err) {\n *   throw new AuthUnknownError('Auth failed', err)\n * }\n * ```\n */\nexport class AuthUnknownError extends AuthError {\n    constructor(message, originalError) {\n        super(message);\n        this.name = 'AuthUnknownError';\n        this.originalError = originalError;\n    }\n}\n/**\n * Flexible error class used to create named auth errors at runtime.\n *\n * @example\n * ```ts\n * import { CustomAuthError } from '@supabase/auth-js'\n *\n * throw new CustomAuthError('My custom auth error', 'MyAuthError', 400, 'custom_code')\n * ```\n */\nexport class CustomAuthError extends AuthError {\n    constructor(message, name, status, code) {\n        super(message, status, code);\n        this.name = name;\n        this.status = status;\n    }\n}\n/**\n * Error thrown when an operation requires a session but none is present.\n *\n * @example\n * ```ts\n * import { AuthSessionMissingError } from '@supabase/auth-js'\n *\n * throw new AuthSessionMissingError()\n * ```\n */\nexport class AuthSessionMissingError extends CustomAuthError {\n    constructor() {\n        super('Auth session missing!', 'AuthSessionMissingError', 400, undefined);\n    }\n}\nexport function isAuthSessionMissingError(error) {\n    return isAuthError(error) && error.name === 'AuthSessionMissingError';\n}\n/**\n * Error thrown when the token response is malformed.\n *\n * @example\n * ```ts\n * import { AuthInvalidTokenResponseError } from '@supabase/auth-js'\n *\n * throw new AuthInvalidTokenResponseError()\n * ```\n */\nexport class AuthInvalidTokenResponseError extends CustomAuthError {\n    constructor() {\n        super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined);\n    }\n}\n/**\n * Error thrown when email/password credentials are invalid.\n *\n * @example\n * ```ts\n * import { AuthInvalidCredentialsError } from '@supabase/auth-js'\n *\n * throw new AuthInvalidCredentialsError('Email or password is incorrect')\n * ```\n */\nexport class AuthInvalidCredentialsError extends CustomAuthError {\n    constructor(message) {\n        super(message, 'AuthInvalidCredentialsError', 400, undefined);\n    }\n}\n/**\n * Error thrown when implicit grant redirects contain an error.\n *\n * @example\n * ```ts\n * import { AuthImplicitGrantRedirectError } from '@supabase/auth-js'\n *\n * throw new AuthImplicitGrantRedirectError('OAuth redirect failed', {\n *   error: 'access_denied',\n *   code: 'oauth_error',\n * })\n * ```\n */\nexport class AuthImplicitGrantRedirectError extends CustomAuthError {\n    constructor(message, details = null) {\n        super(message, 'AuthImplicitGrantRedirectError', 500, undefined);\n        this.details = null;\n        this.details = details;\n    }\n    toJSON() {\n        return Object.assign(Object.assign({}, super.toJSON()), { details: this.details });\n    }\n}\nexport function isAuthImplicitGrantRedirectError(error) {\n    return isAuthError(error) && error.name === 'AuthImplicitGrantRedirectError';\n}\n/**\n * Error thrown during PKCE code exchanges.\n *\n * @example\n * ```ts\n * import { AuthPKCEGrantCodeExchangeError } from '@supabase/auth-js'\n *\n * throw new AuthPKCEGrantCodeExchangeError('PKCE exchange failed')\n * ```\n */\nexport class AuthPKCEGrantCodeExchangeError extends CustomAuthError {\n    constructor(message, details = null) {\n        super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined);\n        this.details = null;\n        this.details = details;\n    }\n    toJSON() {\n        return Object.assign(Object.assign({}, super.toJSON()), { details: this.details });\n    }\n}\n/**\n * Error thrown when the PKCE code verifier is not found in storage.\n * This typically happens when the auth flow was initiated in a different\n * browser, device, or the storage was cleared.\n *\n * @example\n * ```ts\n * import { AuthPKCECodeVerifierMissingError } from '@supabase/auth-js'\n *\n * throw new AuthPKCECodeVerifierMissingError()\n * ```\n */\nexport class AuthPKCECodeVerifierMissingError extends CustomAuthError {\n    constructor() {\n        super('PKCE code verifier not found in storage. ' +\n            'This can happen if the auth flow was initiated in a different browser or device, ' +\n            'or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), ' +\n            'use @supabase/ssr on both the server and client to store the code verifier in cookies.', 'AuthPKCECodeVerifierMissingError', 400, 'pkce_code_verifier_not_found');\n    }\n}\nexport function isAuthPKCECodeVerifierMissingError(error) {\n    return isAuthError(error) && error.name === 'AuthPKCECodeVerifierMissingError';\n}\n/**\n * Error thrown when a transient fetch issue occurs.\n *\n * @example\n * ```ts\n * import { AuthRetryableFetchError } from '@supabase/auth-js'\n *\n * throw new AuthRetryableFetchError('Service temporarily unavailable', 503)\n * ```\n */\nexport class AuthRetryableFetchError extends CustomAuthError {\n    constructor(message, status) {\n        super(message, 'AuthRetryableFetchError', status, undefined);\n    }\n}\nexport function isAuthRetryableFetchError(error) {\n    return isAuthError(error) && error.name === 'AuthRetryableFetchError';\n}\n/**\n * Returned when the server rotated a refresh token successfully but the\n * client chose not to persist the rotated tokens because the local session\n * changed mid-flight. Usually means a concurrent `signOut` cleared storage\n * between when the refresh started and when it came back.\n *\n * Set on the `error` field of the refresh result so callers can tell \"we\n * got rotated tokens but threw them away\" apart from \"the refresh failed.\"\n * The rotated session on the server will be picked up on the next refresh\n * via GoTrue's parent-of-active path.\n *\n * @example\n * ```ts\n * import { isAuthRefreshDiscardedError } from '@supabase/auth-js'\n *\n * if (isAuthRefreshDiscardedError(error)) {\n *   // Concurrent signOut/sign-in raced our refresh. Treat as a no-op.\n * }\n * ```\n */\nexport class AuthRefreshDiscardedError extends CustomAuthError {\n    constructor(message = 'Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)') {\n        super(message, 'AuthRefreshDiscardedError', 409, undefined);\n    }\n}\nexport function isAuthRefreshDiscardedError(error) {\n    return isAuthError(error) && error.name === 'AuthRefreshDiscardedError';\n}\n/**\n * This error is thrown on certain methods when the password used is deemed\n * weak. Inspect the reasons to identify what password strength rules are\n * inadequate.\n */\n/**\n * Error thrown when a supplied password is considered weak.\n *\n * @example\n * ```ts\n * import { AuthWeakPasswordError } from '@supabase/auth-js'\n *\n * throw new AuthWeakPasswordError('Password too short', 400, ['min_length'])\n * ```\n */\nexport class AuthWeakPasswordError extends CustomAuthError {\n    constructor(message, status, reasons) {\n        super(message, 'AuthWeakPasswordError', status, 'weak_password');\n        this.reasons = reasons;\n    }\n    toJSON() {\n        return Object.assign(Object.assign({}, super.toJSON()), { reasons: this.reasons });\n    }\n}\nexport function isAuthWeakPasswordError(error) {\n    return isAuthError(error) && error.name === 'AuthWeakPasswordError';\n}\n/**\n * Error thrown when a JWT cannot be verified or parsed.\n *\n * @example\n * ```ts\n * import { AuthInvalidJwtError } from '@supabase/auth-js'\n *\n * throw new AuthInvalidJwtError('Token signature is invalid')\n * ```\n */\nexport class AuthInvalidJwtError extends CustomAuthError {\n    constructor(message) {\n        super(message, 'AuthInvalidJwtError', 400, 'invalid_jwt');\n    }\n}\n//# sourceMappingURL=errors.js.map","/**\n * Avoid modifying this file. It's part of\n * https://github.com/supabase-community/base64url-js.  Submit all fixes on\n * that repo!\n */\n/**\n * An array of characters that encode 6 bits into a Base64-URL alphabet\n * character.\n */\nconst TO_BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.split('');\n/**\n * An array of characters that can appear in a Base64-URL encoded string but\n * should be ignored.\n */\nconst IGNORE_BASE64URL = ' \\t\\n\\r='.split('');\n/**\n * An array of 128 numbers that map a Base64-URL character to 6 bits, or if -2\n * used to skip the character, or if -1 used to error out.\n */\nconst FROM_BASE64URL = (() => {\n    const charMap = new Array(128);\n    for (let i = 0; i < charMap.length; i += 1) {\n        charMap[i] = -1;\n    }\n    for (let i = 0; i < IGNORE_BASE64URL.length; i += 1) {\n        charMap[IGNORE_BASE64URL[i].charCodeAt(0)] = -2;\n    }\n    for (let i = 0; i < TO_BASE64URL.length; i += 1) {\n        charMap[TO_BASE64URL[i].charCodeAt(0)] = i;\n    }\n    return charMap;\n})();\n/**\n * Converts a byte to a Base64-URL string.\n *\n * @param byte The byte to convert, or null to flush at the end of the byte sequence.\n * @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.\n * @param emit A function called with the next Base64 character when ready.\n */\nexport function byteToBase64URL(byte, state, emit) {\n    if (byte !== null) {\n        state.queue = (state.queue << 8) | byte;\n        state.queuedBits += 8;\n        while (state.queuedBits >= 6) {\n            const pos = (state.queue >> (state.queuedBits - 6)) & 63;\n            emit(TO_BASE64URL[pos]);\n            state.queuedBits -= 6;\n        }\n    }\n    else if (state.queuedBits > 0) {\n        state.queue = state.queue << (6 - state.queuedBits);\n        state.queuedBits = 6;\n        while (state.queuedBits >= 6) {\n            const pos = (state.queue >> (state.queuedBits - 6)) & 63;\n            emit(TO_BASE64URL[pos]);\n            state.queuedBits -= 6;\n        }\n    }\n}\n/**\n * Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters.\n *\n * @param charCode The char code of the JavaScript string.\n * @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`.\n * @param emit A function called with the next byte.\n */\nexport function byteFromBase64URL(charCode, state, emit) {\n    const bits = FROM_BASE64URL[charCode];\n    if (bits > -1) {\n        // valid Base64-URL character\n        state.queue = (state.queue << 6) | bits;\n        state.queuedBits += 6;\n        while (state.queuedBits >= 8) {\n            emit((state.queue >> (state.queuedBits - 8)) & 0xff);\n            state.queuedBits -= 8;\n        }\n    }\n    else if (bits === -2) {\n        // ignore spaces, tabs, newlines, =\n        return;\n    }\n    else {\n        throw new Error(`Invalid Base64-URL character \"${String.fromCharCode(charCode)}\"`);\n    }\n}\n/**\n * Converts a JavaScript string (which may include any valid character) into a\n * Base64-URL encoded string. The string is first encoded in UTF-8 which is\n * then encoded as Base64-URL.\n *\n * @param str The string to convert.\n */\nexport function stringToBase64URL(str) {\n    const base64 = [];\n    const emitter = (char) => {\n        base64.push(char);\n    };\n    const state = { queue: 0, queuedBits: 0 };\n    stringToUTF8(str, (byte) => {\n        byteToBase64URL(byte, state, emitter);\n    });\n    byteToBase64URL(null, state, emitter);\n    return base64.join('');\n}\n/**\n * Converts a Base64-URL encoded string into a JavaScript string. It is assumed\n * that the underlying string has been encoded as UTF-8.\n *\n * @param str The Base64-URL encoded string.\n */\nexport function stringFromBase64URL(str) {\n    const conv = [];\n    const utf8Emit = (codepoint) => {\n        conv.push(String.fromCodePoint(codepoint));\n    };\n    const utf8State = {\n        utf8seq: 0,\n        codepoint: 0,\n    };\n    const b64State = { queue: 0, queuedBits: 0 };\n    const byteEmit = (byte) => {\n        stringFromUTF8(byte, utf8State, utf8Emit);\n    };\n    for (let i = 0; i < str.length; i += 1) {\n        byteFromBase64URL(str.charCodeAt(i), b64State, byteEmit);\n    }\n    return conv.join('');\n}\n/**\n * Converts a Unicode codepoint to a multi-byte UTF-8 sequence.\n *\n * @param codepoint The Unicode codepoint.\n * @param emit      Function which will be called for each UTF-8 byte that represents the codepoint.\n */\nexport function codepointToUTF8(codepoint, emit) {\n    if (codepoint <= 0x7f) {\n        emit(codepoint);\n        return;\n    }\n    else if (codepoint <= 0x7ff) {\n        emit(0xc0 | (codepoint >> 6));\n        emit(0x80 | (codepoint & 0x3f));\n        return;\n    }\n    else if (codepoint <= 0xffff) {\n        emit(0xe0 | (codepoint >> 12));\n        emit(0x80 | ((codepoint >> 6) & 0x3f));\n        emit(0x80 | (codepoint & 0x3f));\n        return;\n    }\n    else if (codepoint <= 0x10ffff) {\n        emit(0xf0 | (codepoint >> 18));\n        emit(0x80 | ((codepoint >> 12) & 0x3f));\n        emit(0x80 | ((codepoint >> 6) & 0x3f));\n        emit(0x80 | (codepoint & 0x3f));\n        return;\n    }\n    throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`);\n}\n/**\n * Converts a JavaScript string to a sequence of UTF-8 bytes.\n *\n * @param str  The string to convert to UTF-8.\n * @param emit Function which will be called for each UTF-8 byte of the string.\n */\nexport function stringToUTF8(str, emit) {\n    for (let i = 0; i < str.length; i += 1) {\n        let codepoint = str.charCodeAt(i);\n        if (codepoint > 0xd7ff && codepoint <= 0xdbff) {\n            // most UTF-16 codepoints are Unicode codepoints, except values in this\n            // range where the next UTF-16 codepoint needs to be combined with the\n            // current one to get the Unicode codepoint\n            const highSurrogate = ((codepoint - 0xd800) * 0x400) & 0xffff;\n            const lowSurrogate = (str.charCodeAt(i + 1) - 0xdc00) & 0xffff;\n            codepoint = (lowSurrogate | highSurrogate) + 0x10000;\n            i += 1;\n        }\n        codepointToUTF8(codepoint, emit);\n    }\n}\n/**\n * Converts a UTF-8 byte to a Unicode codepoint.\n *\n * @param byte  The UTF-8 byte next in the sequence.\n * @param state The shared state between consecutive UTF-8 bytes in the\n *              sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`.\n * @param emit  Function which will be called for each codepoint.\n */\nexport function stringFromUTF8(byte, state, emit) {\n    if (state.utf8seq === 0) {\n        if (byte <= 0x7f) {\n            emit(byte);\n            return;\n        }\n        // count the number of 1 leading bits until you reach 0\n        for (let leadingBit = 1; leadingBit < 6; leadingBit += 1) {\n            if (((byte >> (7 - leadingBit)) & 1) === 0) {\n                state.utf8seq = leadingBit;\n                break;\n            }\n        }\n        if (state.utf8seq === 2) {\n            state.codepoint = byte & 31;\n        }\n        else if (state.utf8seq === 3) {\n            state.codepoint = byte & 15;\n        }\n        else if (state.utf8seq === 4) {\n            state.codepoint = byte & 7;\n        }\n        else {\n            throw new Error('Invalid UTF-8 sequence');\n        }\n        state.utf8seq -= 1;\n    }\n    else if (state.utf8seq > 0) {\n        if (byte <= 0x7f) {\n            throw new Error('Invalid UTF-8 sequence');\n        }\n        state.codepoint = (state.codepoint << 6) | (byte & 63);\n        state.utf8seq -= 1;\n        if (state.utf8seq === 0) {\n            emit(state.codepoint);\n        }\n    }\n}\n/**\n * Helper functions to convert different types of strings to Uint8Array\n */\nexport function base64UrlToUint8Array(str) {\n    const result = [];\n    const state = { queue: 0, queuedBits: 0 };\n    const onByte = (byte) => {\n        result.push(byte);\n    };\n    for (let i = 0; i < str.length; i += 1) {\n        byteFromBase64URL(str.charCodeAt(i), state, onByte);\n    }\n    return new Uint8Array(result);\n}\nexport function stringToUint8Array(str) {\n    const result = [];\n    stringToUTF8(str, (byte) => result.push(byte));\n    return new Uint8Array(result);\n}\nexport function bytesToBase64URL(bytes) {\n    const result = [];\n    const state = { queue: 0, queuedBits: 0 };\n    const onChar = (char) => {\n        result.push(char);\n    };\n    bytes.forEach((byte) => byteToBase64URL(byte, state, onChar));\n    // always call with `null` after processing all bytes\n    byteToBase64URL(null, state, onChar);\n    return result.join('');\n}\n//# sourceMappingURL=base64url.js.map","import { API_VERSION_HEADER_NAME, BASE64URL_REGEX, PKCE_FLOW_ID_PARAM, PKCE_MAX_CONCURRENT_FLOWS, } from './constants';\nimport { AuthInvalidJwtError } from './errors';\nimport { base64UrlToUint8Array, stringFromBase64URL } from './base64url';\nexport function expiresAt(expiresIn) {\n    const timeNow = Math.round(Date.now() / 1000);\n    return timeNow + expiresIn;\n}\n/**\n * Generates a unique identifier for internal callback subscriptions.\n *\n * This function uses JavaScript Symbols to create guaranteed-unique identifiers\n * for auth state change callbacks. Symbols are ideal for this use case because:\n * - They are guaranteed unique by the JavaScript runtime\n * - They work in all environments (browser, SSR, Node.js)\n * - They avoid issues with Next.js 16 deterministic rendering requirements\n * - They are perfect for internal, non-serializable identifiers\n *\n * Note: This function is only used for internal subscription management,\n * not for security-critical operations like session tokens.\n */\nexport function generateCallbackId() {\n    return Symbol('auth-callback');\n}\nexport const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined';\nconst localStorageWriteTests = {\n    tested: false,\n    writable: false,\n};\n/**\n * Checks whether localStorage is supported on this browser.\n */\nexport const supportsLocalStorage = () => {\n    if (!isBrowser()) {\n        return false;\n    }\n    try {\n        if (typeof globalThis.localStorage !== 'object') {\n            return false;\n        }\n    }\n    catch (e) {\n        // DOM exception when accessing `localStorage`\n        return false;\n    }\n    if (localStorageWriteTests.tested) {\n        return localStorageWriteTests.writable;\n    }\n    const randomKey = `lswt-${Math.random()}${Math.random()}`;\n    try {\n        globalThis.localStorage.setItem(randomKey, randomKey);\n        globalThis.localStorage.removeItem(randomKey);\n        localStorageWriteTests.tested = true;\n        localStorageWriteTests.writable = true;\n    }\n    catch (e) {\n        // localStorage can't be written to\n        // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document\n        localStorageWriteTests.tested = true;\n        localStorageWriteTests.writable = false;\n    }\n    return localStorageWriteTests.writable;\n};\n/**\n * Extracts parameters encoded in the URL both in the query and fragment.\n */\nexport function parseParametersFromURL(href) {\n    const result = {};\n    const url = new URL(href);\n    if (url.hash && url.hash[0] === '#') {\n        try {\n            const hashSearchParams = new URLSearchParams(url.hash.substring(1));\n            hashSearchParams.forEach((value, key) => {\n                result[key] = value;\n            });\n        }\n        catch (_e) {\n            // hash is not a query string\n        }\n    }\n    // search parameters take precedence over hash parameters\n    url.searchParams.forEach((value, key) => {\n        result[key] = value;\n    });\n    return result;\n}\nexport const resolveFetch = (customFetch) => {\n    if (customFetch) {\n        return (...args) => customFetch(...args);\n    }\n    return (...args) => fetch(...args);\n};\nexport const looksLikeFetchResponse = (maybeResponse) => {\n    return (typeof maybeResponse === 'object' &&\n        maybeResponse !== null &&\n        'status' in maybeResponse &&\n        'ok' in maybeResponse &&\n        'json' in maybeResponse &&\n        typeof maybeResponse.json === 'function');\n};\n// Storage helpers\nexport const setItemAsync = async (storage, key, data) => {\n    await storage.setItem(key, JSON.stringify(data));\n};\nexport const getItemAsync = async (storage, key) => {\n    const value = await storage.getItem(key);\n    if (!value) {\n        return null;\n    }\n    try {\n        return JSON.parse(value);\n    }\n    catch (_a) {\n        // Storage values are always written as JSON via setItemAsync. A non-JSON\n        // value means the entry is corrupted (e.g. mismatched chunked cookies in\n        // SSR contexts). Treat as absent so callers do not mutate or re-save the\n        // garbage, which would otherwise trigger a TypeError downstream and\n        // leak the raw value into error logs.\n        return null;\n    }\n};\nexport const removeItemAsync = async (storage, key) => {\n    await storage.removeItem(key);\n};\n/**\n * A deferred represents some asynchronous work that is not yet finished, which\n * may or may not culminate in a value.\n * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts\n */\nexport class Deferred {\n    constructor() {\n        // eslint-disable-next-line @typescript-eslint/no-extra-semi\n        ;\n        this.promise = new Deferred.promiseConstructor((res, rej) => {\n            // eslint-disable-next-line @typescript-eslint/no-extra-semi\n            ;\n            this.resolve = res;\n            this.reject = rej;\n        });\n    }\n}\nDeferred.promiseConstructor = Promise;\nexport function decodeJWT(token) {\n    const parts = token.split('.');\n    if (parts.length !== 3) {\n        throw new AuthInvalidJwtError('Invalid JWT structure');\n    }\n    // Regex checks for base64url format\n    for (let i = 0; i < parts.length; i++) {\n        if (!BASE64URL_REGEX.test(parts[i])) {\n            throw new AuthInvalidJwtError('JWT not in base64url format');\n        }\n    }\n    const data = {\n        // using base64url lib\n        header: JSON.parse(stringFromBase64URL(parts[0])),\n        payload: JSON.parse(stringFromBase64URL(parts[1])),\n        signature: base64UrlToUint8Array(parts[2]),\n        raw: {\n            header: parts[0],\n            payload: parts[1],\n        },\n    };\n    return data;\n}\n/**\n * Creates a promise that resolves to null after some time.\n */\nexport async function sleep(time) {\n    return await new Promise((accept) => {\n        setTimeout(() => accept(null), time);\n    });\n}\n/**\n * Converts the provided async function into a retryable function. Each result\n * or thrown error is sent to the isRetryable function which should return true\n * if the function should run again.\n */\nexport function retryable(fn, isRetryable) {\n    const promise = new Promise((accept, reject) => {\n        // eslint-disable-next-line @typescript-eslint/no-extra-semi\n        ;\n        (async () => {\n            for (let attempt = 0; attempt < Infinity; attempt++) {\n                try {\n                    const result = await fn(attempt);\n                    if (!isRetryable(attempt, null, result)) {\n                        accept(result);\n                        return;\n                    }\n                }\n                catch (e) {\n                    if (!isRetryable(attempt, e)) {\n                        reject(e);\n                        return;\n                    }\n                }\n            }\n        })();\n    });\n    return promise;\n}\nfunction dec2hex(dec) {\n    return ('0' + dec.toString(16)).substr(-2);\n}\n// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs\nexport function generatePKCEVerifier() {\n    const verifierLength = 56;\n    const array = new Uint32Array(verifierLength);\n    if (typeof crypto === 'undefined') {\n        const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';\n        const charSetLen = charSet.length;\n        let verifier = '';\n        for (let i = 0; i < verifierLength; i++) {\n            verifier += charSet.charAt(Math.floor(Math.random() * charSetLen));\n        }\n        return verifier;\n    }\n    crypto.getRandomValues(array);\n    return Array.from(array, dec2hex).join('');\n}\nasync function sha256(randomString) {\n    const encoder = new TextEncoder();\n    const encodedData = encoder.encode(randomString);\n    const hash = await crypto.subtle.digest('SHA-256', encodedData);\n    const bytes = new Uint8Array(hash);\n    return Array.from(bytes)\n        .map((c) => String.fromCharCode(c))\n        .join('');\n}\nexport async function generatePKCEChallenge(verifier) {\n    const hasCryptoSupport = typeof crypto !== 'undefined' &&\n        typeof crypto.subtle !== 'undefined' &&\n        typeof TextEncoder !== 'undefined';\n    if (!hasCryptoSupport) {\n        console.warn('WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.');\n        return verifier;\n    }\n    const hashed = await sha256(verifier);\n    return btoa(hashed).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\nconst PKCE_FLOW_ID_PATTERN = /^[a-zA-Z0-9_-]{8,64}$/;\n/**\n * Returns the flow id if it is a plausible flow id, `null` otherwise. Flow\n * ids can arrive via URL parameters, so anything outside the expected shape\n * is discarded before it is used to build a storage key.\n */\nexport function validatePKCEFlowId(flowId) {\n    return typeof flowId === 'string' && PKCE_FLOW_ID_PATTERN.test(flowId) ? flowId : null;\n}\nexport function generatePKCEFlowId() {\n    if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n        const bytes = new Uint8Array(16);\n        crypto.getRandomValues(bytes);\n        return Array.from(bytes, dec2hex).join('');\n    }\n    let flowId = '';\n    for (let i = 0; i < 32; i++) {\n        flowId += Math.floor(Math.random() * 16).toString(16);\n    }\n    return flowId;\n}\n// Slot keys deliberately end in `-code-verifier`: @supabase/ssr's server\n// cookie adapter only persists writes immediately for keys with that suffix\n// (no auth event fires when a verifier is stored). They also contain no dot,\n// because @supabase/ssr chunks oversized cookies as `<key>.<number>` and a\n// dot-delimited key could be mistaken for a chunk of the fixed\n// `-code-verifier` cookie and clobbered by its chunk management.\nexport const pkceVerifierSlotKey = (storageKey, flowId) => `${storageKey}-flow-${flowId}-code-verifier`;\nconst pkceFlowIndexKey = (storageKey) => `${storageKey}-flows-code-verifier`;\n/**\n * Storage adapters cannot enumerate keys, so the ids of pending verifier\n * slots are tracked in an index entry, oldest first. Index entries pass\n * through the same validation as URL-provided flow ids: with cookie-based\n * storage the index contents are no more trustworthy than a URL parameter.\n */\nasync function getPKCEFlowIndex(storage, storageKey) {\n    const index = await getItemAsync(storage, pkceFlowIndexKey(storageKey));\n    return Array.isArray(index)\n        ? index.filter((id) => validatePKCEFlowId(id) !== null)\n        : [];\n}\n/**\n * The index is read-modify-write without a lock: two concurrent starts (e.g.\n * two tabs) can lose one index update. The losing flow still works — its slot\n * is addressed directly by key — but its entry is missing from the index, so\n * it escapes both ring eviction and removeAllPKCEVerifiers: the orphaned slot\n * persists for the storage medium's lifetime (up to the cookie max age in\n * cookie storage) and repeated races accumulate one orphan each. Accepted\n * trade-off: locking every flow start is far more intrusive than the leak.\n */\nexport async function storePKCEVerifier(storage, storageKey, flowId, verifier, onEvictFlow) {\n    await setItemAsync(storage, pkceVerifierSlotKey(storageKey, flowId), verifier);\n    const index = (await getPKCEFlowIndex(storage, storageKey)).filter((id) => id !== flowId);\n    index.push(flowId);\n    while (index.length > PKCE_MAX_CONCURRENT_FLOWS) {\n        const evicted = index.shift();\n        await removeItemAsync(storage, pkceVerifierSlotKey(storageKey, evicted));\n        onEvictFlow === null || onEvictFlow === void 0 ? void 0 : onEvictFlow(evicted);\n    }\n    await setItemAsync(storage, pkceFlowIndexKey(storageKey), index);\n    // Deprecation-window dual write: exchanges that cannot identify their flow\n    // (older SDK versions, redirects without the flow id parameter) read the\n    // fixed key, which mirrors the most recently started flow.\n    await setItemAsync(storage, `${storageKey}-code-verifier`, verifier);\n}\n/**\n * Looks up the verifier for `flowId`. When a flow id is given, only that slot\n * is consulted — deliberately no fallback to the fixed legacy key: submitting\n * another flow's verifier would burn the single-use auth code, and the\n * subsequent cleanup would delete a pending flow's only fallback. The legacy\n * key is read only when no flow id is available at all.\n */\nexport async function retrievePKCEVerifier(storage, storageKey, flowId) {\n    if (flowId) {\n        const verifier = await getItemAsync(storage, pkceVerifierSlotKey(storageKey, flowId));\n        return { verifier: typeof verifier === 'string' ? verifier : null, flowId };\n    }\n    const verifier = await getItemAsync(storage, `${storageKey}-code-verifier`);\n    return { verifier: typeof verifier === 'string' ? verifier : null, flowId: null };\n}\n/**\n * Removes a single flow's verifier. Never clears other flows' slots: with a\n * `flowId` only that slot is deleted (plus the legacy fixed key when it holds\n * the same verifier); without one, only the legacy fixed key is deleted.\n */\nexport async function removePKCEVerifier(storage, storageKey, flowId) {\n    const legacyKey = `${storageKey}-code-verifier`;\n    if (!flowId) {\n        await removeItemAsync(storage, legacyKey);\n        return;\n    }\n    const slotKey = pkceVerifierSlotKey(storageKey, flowId);\n    const slotValue = await getItemAsync(storage, slotKey);\n    await removeItemAsync(storage, slotKey);\n    // Skip the index rewrite when the flow was never indexed (e.g. a failed\n    // exchange for an absent slot): on cookie storage every write is a full\n    // Set-Cookie cycle.\n    const index = await getPKCEFlowIndex(storage, storageKey);\n    const remaining = index.filter((id) => id !== flowId);\n    if (remaining.length !== index.length) {\n        if (remaining.length > 0) {\n            await setItemAsync(storage, pkceFlowIndexKey(storageKey), remaining);\n        }\n        else {\n            await removeItemAsync(storage, pkceFlowIndexKey(storageKey));\n        }\n    }\n    if (slotValue != null && slotValue === (await getItemAsync(storage, legacyKey))) {\n        await removeItemAsync(storage, legacyKey);\n    }\n}\n/**\n * Removes every pending verifier: all slots in the index, the index itself\n * and the fixed legacy key. Used on session teardown (sign-out, invalid\n * session) — matches the pre-slot behavior where tearing down the session\n * deleted the only verifier, and prevents long-lived stale verifier cookies.\n */\nexport async function removeAllPKCEVerifiers(storage, storageKey) {\n    const index = await getPKCEFlowIndex(storage, storageKey);\n    for (const flowId of index) {\n        await removeItemAsync(storage, pkceVerifierSlotKey(storageKey, flowId));\n    }\n    await removeItemAsync(storage, pkceFlowIndexKey(storageKey));\n    await removeItemAsync(storage, `${storageKey}-code-verifier`);\n}\n/**\n * Appends the reserved flow id parameter to a `redirectTo` URL, replacing any\n * existing occurrence. String-based (no URL round-trip) so custom schemes\n * (native deep links) and the exact encoding of the app's own parameters\n * survive untouched; an existing fragment stays at the end of the URL.\n */\nexport function appendFlowIdToRedirectTo(redirectTo, flowId) {\n    const hashIndex = redirectTo.indexOf('#');\n    let base = hashIndex === -1 ? redirectTo : redirectTo.slice(0, hashIndex);\n    const fragment = hashIndex === -1 ? '' : redirectTo.slice(hashIndex);\n    const queryIndex = base.indexOf('?');\n    if (queryIndex !== -1) {\n        const path = base.slice(0, queryIndex);\n        const remaining = base\n            .slice(queryIndex + 1)\n            .split('&')\n            .filter((pair) => pair !== '' && pair !== PKCE_FLOW_ID_PARAM && !pair.startsWith(`${PKCE_FLOW_ID_PARAM}=`));\n        base = remaining.length > 0 ? `${path}?${remaining.join('&')}` : path;\n    }\n    const separator = base.includes('?') ? '&' : '?';\n    return `${base}${separator}${PKCE_FLOW_ID_PARAM}=${encodeURIComponent(flowId)}${fragment}`;\n}\nexport async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false, onEvictFlow) {\n    const codeVerifier = generatePKCEVerifier();\n    let storedCodeVerifier = codeVerifier;\n    if (isPasswordRecovery) {\n        storedCodeVerifier += '/recovery';\n    }\n    const flowId = generatePKCEFlowId();\n    await storePKCEVerifier(storage, storageKey, flowId, storedCodeVerifier, onEvictFlow);\n    const codeChallenge = await generatePKCEChallenge(codeVerifier);\n    const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256';\n    return [codeChallenge, codeChallengeMethod, flowId];\n}\n/** Parses the API version which is 2YYY-MM-DD. */\nconst API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;\nexport function parseResponseAPIVersion(response) {\n    const apiVersion = response.headers.get(API_VERSION_HEADER_NAME);\n    if (!apiVersion) {\n        return null;\n    }\n    if (!apiVersion.match(API_VERSION_REGEX)) {\n        return null;\n    }\n    try {\n        const date = new Date(`${apiVersion}T00:00:00.0Z`);\n        return date;\n    }\n    catch (_e) {\n        return null;\n    }\n}\nexport function validateExp(exp) {\n    if (!exp) {\n        throw new Error('Missing exp claim');\n    }\n    const timeNow = Math.floor(Date.now() / 1000);\n    if (exp <= timeNow) {\n        throw new Error('JWT has expired');\n    }\n}\nexport function getAlgorithm(alg) {\n    switch (alg) {\n        case 'RS256':\n            return {\n                name: 'RSASSA-PKCS1-v1_5',\n                hash: { name: 'SHA-256' },\n            };\n        case 'ES256':\n            return {\n                name: 'ECDSA',\n                namedCurve: 'P-256',\n                hash: { name: 'SHA-256' },\n            };\n        default:\n            throw new Error('Invalid alg claim');\n    }\n}\nconst UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nexport function validateUUID(str) {\n    if (!UUID_REGEX.test(str)) {\n        throw new Error('@supabase/auth-js: Expected parameter to be UUID but is not');\n    }\n}\nexport function assertPasskeyExperimentalEnabled(experimental) {\n    if (!experimental.passkey) {\n        throw new Error('@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).');\n    }\n}\nexport function assertRecoveryCodesExperimentalEnabled(experimental) {\n    if (!experimental.recoveryCodes) {\n        throw new Error('@supabase/auth-js: the MFA recovery codes API is experimental and disabled by default. Enable it by passing `auth: { experimental: { recoveryCodes: true } }` to createClient (or to the GoTrueClient constructor).');\n    }\n}\nexport function userNotAvailableProxy() {\n    const proxyTarget = {};\n    return new Proxy(proxyTarget, {\n        get: (target, prop) => {\n            if (prop === '__isUserNotAvailableProxy') {\n                return true;\n            }\n            // Preventative check for common problematic symbols during cloning/inspection\n            // These symbols might be accessed by structuredClone or other internal mechanisms.\n            if (typeof prop === 'symbol') {\n                const sProp = prop.toString();\n                if (sProp === 'Symbol(Symbol.toPrimitive)' ||\n                    sProp === 'Symbol(Symbol.toStringTag)' ||\n                    sProp === 'Symbol(util.inspect.custom)') {\n                    // Node.js util.inspect\n                    return undefined;\n                }\n            }\n            throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the \"${prop}\" property of the session object is not supported. Please use getUser() instead.`);\n        },\n        set: (_target, prop) => {\n            throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the \"${prop}\" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`);\n        },\n        deleteProperty: (_target, prop) => {\n            throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the \"${prop}\" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`);\n        },\n    });\n}\n/**\n * Creates a proxy around a user object that warns when properties are accessed on the server.\n * This is used to alert developers that using user data from getSession() on the server is insecure.\n *\n * @param user The actual user object to wrap\n * @param suppressWarningRef An object with a 'value' property that controls warning suppression\n * @returns A proxied user object that warns on property access\n */\nexport function insecureUserWarningProxy(user, suppressWarningRef) {\n    return new Proxy(user, {\n        get: (target, prop, receiver) => {\n            // Allow internal checks without warning\n            if (prop === '__isInsecureUserWarningProxy') {\n                return true;\n            }\n            // Preventative check for common problematic symbols during cloning/inspection\n            // These symbols might be accessed by structuredClone or other internal mechanisms\n            if (typeof prop === 'symbol') {\n                const sProp = prop.toString();\n                if (sProp === 'Symbol(Symbol.toPrimitive)' ||\n                    sProp === 'Symbol(Symbol.toStringTag)' ||\n                    sProp === 'Symbol(util.inspect.custom)' ||\n                    sProp === 'Symbol(nodejs.util.inspect.custom)') {\n                    // Return the actual value for these symbols to allow proper inspection\n                    return Reflect.get(target, prop, receiver);\n                }\n            }\n            // Emit warning on first property access\n            if (!suppressWarningRef.value && typeof prop === 'string') {\n                console.warn('Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.');\n                suppressWarningRef.value = true;\n            }\n            return Reflect.get(target, prop, receiver);\n        },\n    });\n}\n/**\n * Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)).\n * Note: Only works for JSON-safe data.\n */\nexport function deepClone(obj) {\n    return JSON.parse(JSON.stringify(obj));\n}\n//# sourceMappingURL=helpers.js.map","import { __rest } from \"tslib\";\nimport { API_VERSIONS, API_VERSION_HEADER_NAME } from './constants';\nimport { expiresAt, looksLikeFetchResponse, parseResponseAPIVersion } from './helpers';\nimport { AuthApiError, AuthRetryableFetchError, AuthWeakPasswordError, AuthUnknownError, AuthSessionMissingError, } from './errors';\nconst _getErrorMessage = (err) => {\n    if (typeof err === 'object' && err !== null) {\n        const e = err;\n        if (typeof e.msg === 'string')\n            return e.msg;\n        if (typeof e.message === 'string')\n            return e.message;\n        if (typeof e.error_description === 'string')\n            return e.error_description;\n        if (typeof e.error === 'string')\n            return e.error;\n    }\n    return JSON.stringify(err);\n};\n// 500, 501, 502, 503, 504: Standard server/gateway errors\n// 520-529, 530: Cloudflare-specific error codes (web server down, connection timed out, etc.)\n// These are infrastructure errors and should not cause session invalidation.\nconst NETWORK_ERROR_CODES = [\n    500, 501, 502, 503, 504, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530,\n];\nexport async function handleError(error) {\n    var _a;\n    if (!looksLikeFetchResponse(error)) {\n        throw new AuthRetryableFetchError(_getErrorMessage(error), 0);\n    }\n    let data;\n    try {\n        data = await error.json();\n    }\n    catch (e) {\n        if (NETWORK_ERROR_CODES.includes(error.status)) {\n            // statusText can be empty — HTTP/2 has no reason phrase\n            throw new AuthRetryableFetchError(error.statusText || `HTTP ${error.status}`, error.status);\n        }\n        throw new AuthUnknownError(_getErrorMessage(e), e);\n    }\n    if (NETWORK_ERROR_CODES.includes(error.status)) {\n        // status in 500...599 range - server had an error, request might be retryed.\n        throw new AuthRetryableFetchError(_getErrorMessage(data), error.status);\n    }\n    let errorCode = undefined;\n    const responseAPIVersion = parseResponseAPIVersion(error);\n    if (responseAPIVersion &&\n        responseAPIVersion.getTime() >= API_VERSIONS['2024-01-01'].timestamp &&\n        typeof data === 'object' &&\n        data &&\n        typeof data.code === 'string') {\n        errorCode = data.code;\n    }\n    else if (typeof data === 'object' && data && typeof data.error_code === 'string') {\n        errorCode = data.error_code;\n    }\n    if (!errorCode) {\n        // Legacy support for weak password errors, when there were no error codes\n        if (typeof data === 'object' &&\n            data &&\n            typeof data.weak_password === 'object' &&\n            data.weak_password &&\n            Array.isArray(data.weak_password.reasons) &&\n            data.weak_password.reasons.length &&\n            data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) {\n            throw new AuthWeakPasswordError(_getErrorMessage(data), error.status, data.weak_password.reasons);\n        }\n    }\n    else if (errorCode === 'weak_password') {\n        throw new AuthWeakPasswordError(_getErrorMessage(data), error.status, ((_a = data.weak_password) === null || _a === void 0 ? void 0 : _a.reasons) || []);\n    }\n    else if (errorCode === 'session_not_found') {\n        // The `session_id` inside the JWT does not correspond to a row in the\n        // `sessions` table. This usually means the user has signed out, has been\n        // deleted, or their session has somehow been terminated.\n        throw new AuthSessionMissingError();\n    }\n    throw new AuthApiError(_getErrorMessage(data), error.status || 500, errorCode);\n}\nconst _getRequestParams = (method, options, parameters, body) => {\n    const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} };\n    if (method === 'GET') {\n        return params;\n    }\n    params.headers = Object.assign({ 'Content-Type': 'application/json;charset=UTF-8' }, options === null || options === void 0 ? void 0 : options.headers);\n    params.body = JSON.stringify(body);\n    return Object.assign(Object.assign({}, params), parameters);\n};\nexport async function _request(fetcher, method, url, options) {\n    var _a;\n    const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers);\n    if (!headers[API_VERSION_HEADER_NAME]) {\n        headers[API_VERSION_HEADER_NAME] = API_VERSIONS['2024-01-01'].name;\n    }\n    if (options === null || options === void 0 ? void 0 : options.jwt) {\n        headers['Authorization'] = `Bearer ${options.jwt}`;\n    }\n    const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {};\n    if (options === null || options === void 0 ? void 0 : options.redirectTo) {\n        qs['redirect_to'] = options.redirectTo;\n    }\n    const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : '';\n    const data = await _handleRequest(fetcher, method, url + queryString, {\n        headers,\n        noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson,\n    }, {}, options === null || options === void 0 ? void 0 : options.body);\n    return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null };\n}\nasync function _handleRequest(fetcher, method, url, options, parameters, body) {\n    const requestParams = _getRequestParams(method, options, parameters, body);\n    let result;\n    try {\n        result = await fetcher(url, Object.assign({}, requestParams));\n    }\n    catch (e) {\n        // fetch failed (network / CORS / aborted request) — surfaced to the\n        // caller as a retryable error below. Deliberately not logged here: an\n        // aborted in-flight request (e.g. a superseded page navigation) is a\n        // transient condition, and logging the raw error pollutes the console.\n        throw new AuthRetryableFetchError(_getErrorMessage(e), 0);\n    }\n    if (!result.ok) {\n        await handleError(result);\n    }\n    if (options === null || options === void 0 ? void 0 : options.noResolveJson) {\n        return result;\n    }\n    try {\n        return await result.json();\n    }\n    catch (e) {\n        await handleError(e);\n    }\n}\nexport function _sessionResponse(data) {\n    var _a;\n    let session = null;\n    if (hasSession(data)) {\n        session = Object.assign({}, data);\n        if (!data.expires_at) {\n            session.expires_at = expiresAt(data.expires_in);\n        }\n    }\n    // Some /verify responses (e.g. secure email_change first-confirmation) return\n    // only `{ msg, code }` with no user and no session. Treat those as null user.\n    const user = (_a = data.user) !== null && _a !== void 0 ? _a : (typeof (data === null || data === void 0 ? void 0 : data.id) === 'string' ? data : null);\n    return { data: { session, user }, error: null };\n}\nexport function _sessionResponsePassword(data) {\n    const response = _sessionResponse(data);\n    if (!response.error &&\n        data.weak_password &&\n        typeof data.weak_password === 'object' &&\n        Array.isArray(data.weak_password.reasons) &&\n        data.weak_password.reasons.length &&\n        data.weak_password.message &&\n        typeof data.weak_password.message === 'string' &&\n        data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) {\n        response.data.weak_password = data.weak_password;\n    }\n    return response;\n}\nexport function _userResponse(data) {\n    var _a;\n    const user = (_a = data.user) !== null && _a !== void 0 ? _a : data;\n    return { data: { user }, error: null };\n}\nexport function _ssoResponse(data) {\n    return { data, error: null };\n}\nexport function _generateLinkResponse(data) {\n    const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = __rest(data, [\"action_link\", \"email_otp\", \"hashed_token\", \"redirect_to\", \"verification_type\"]);\n    const properties = {\n        action_link,\n        email_otp,\n        hashed_token,\n        redirect_to,\n        verification_type,\n    };\n    const user = Object.assign({}, rest);\n    return {\n        data: {\n            properties,\n            user,\n        },\n        error: null,\n    };\n}\nexport function _noResolveJsonResponse(data) {\n    return data;\n}\n/**\n * hasSession checks if the response object contains a valid session\n * @param data A response object\n * @returns true if a session is in the response\n */\nfunction hasSession(data) {\n    return !!data.access_token && !!data.refresh_token && !!data.expires_in;\n}\n//# sourceMappingURL=fetch.js.map","const WeakPasswordReasons = ['length', 'characters', 'pwned'];\nconst AMRMethods = [\n    'password',\n    'otp',\n    'oauth',\n    'totp',\n    'mfa/totp',\n    'mfa/phone',\n    'mfa/webauthn',\n    'mfa/recovery_code',\n    'anonymous',\n    'sso/saml',\n    'magiclink',\n    'web3',\n    'oauth_provider/authorization_code',\n];\nconst FactorTypes = ['totp', 'phone', 'webauthn', 'recovery_code'];\nconst FactorVerificationStatuses = ['verified', 'unverified'];\nconst MFATOTPChannels = ['sms', 'whatsapp'];\nexport const SIGN_OUT_SCOPES = ['global', 'local', 'others'];\n//# sourceMappingURL=types.js.map","import { __rest } from \"tslib\";\nimport { _generateLinkResponse, _noResolveJsonResponse, _request, _userResponse, } from './lib/fetch';\nimport { assertPasskeyExperimentalEnabled, resolveFetch, validateUUID } from './lib/helpers';\nimport { SIGN_OUT_SCOPES, } from './lib/types';\nimport { isAuthError } from './lib/errors';\nexport default class GoTrueAdminApi {\n    /**\n     * Creates an admin API client that can be used to manage users and OAuth clients.\n     *\n     * @example Using supabase-js (recommended)\n     * ```ts\n     * import { createClient } from '@supabase/supabase-js'\n     *\n     * const supabase = createClient('https://xyzcompany.supabase.co', 'your-secret-key')\n     * const { data, error } = await supabase.auth.admin.listUsers()\n     * ```\n     *\n     * @example Standalone import for bundle-sensitive environments\n     * ```ts\n     * import { GoTrueAdminApi } from '@supabase/auth-js'\n     *\n     * const admin = new GoTrueAdminApi({\n     *   url: 'https://xyzcompany.supabase.co/auth/v1',\n     *   headers: { Authorization: `Bearer ${process.env.SUPABASE_SECRET_KEY}` },\n     * })\n     * ```\n     */\n    constructor({ url = '', headers = {}, fetch, experimental, }) {\n        this.url = url;\n        this.headers = headers;\n        this.fetch = resolveFetch(fetch);\n        this.experimental = experimental !== null && experimental !== void 0 ? experimental : {};\n        this.mfa = {\n            listFactors: this._listFactors.bind(this),\n            deleteFactor: this._deleteFactor.bind(this),\n        };\n        this.oauth = {\n            listClients: this._listOAuthClients.bind(this),\n            createClient: this._createOAuthClient.bind(this),\n            getClient: this._getOAuthClient.bind(this),\n            updateClient: this._updateOAuthClient.bind(this),\n            deleteClient: this._deleteOAuthClient.bind(this),\n            regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this),\n        };\n        this.customProviders = {\n            listProviders: this._listCustomProviders.bind(this),\n            createProvider: this._createCustomProvider.bind(this),\n            getProvider: this._getCustomProvider.bind(this),\n            updateProvider: this._updateCustomProvider.bind(this),\n            deleteProvider: this._deleteCustomProvider.bind(this),\n        };\n        this.passkey = {\n            listPasskeys: this._adminListPasskeys.bind(this),\n            deletePasskey: this._adminDeletePasskey.bind(this),\n        };\n    }\n    /**\n     * Removes a logged-in session.\n     * @param jwt A valid, logged-in JWT.\n     * @param scope The logout sope.\n     *\n     * @category Auth\n     * @subcategory Auth Admin\n     */\n    async signOut(jwt, scope = SIGN_OUT_SCOPES[0]) {\n        if (SIGN_OUT_SCOPES.indexOf(scope) < 0) {\n            throw new Error(`@supabase/auth-js: Parameter scope must be one of ${SIGN_OUT_SCOPES.join(', ')}`);\n        }\n        try {\n            await _request(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, {\n                headers: this.headers,\n                jwt,\n                noResolveJson: true,\n            });\n            return { data: null, error: null };\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Sends an invite link to an email address.\n     * @param email The email address of the user.\n     * @param options Additional options to be included when inviting.\n     *\n     * @category Auth\n     * @subcategory Auth Admin\n     *\n     * @remarks\n     * - Sends an invite link to the user's email address.\n     * - The `inviteUserByEmail()` method is typically used by administrators to invite users to join the application.\n     * - Note that PKCE is not supported when using `inviteUserByEmail`. This is because the browser initiating the invite is often different from the browser accepting the invite which makes it difficult to provide the security guarantees required of the PKCE flow.\n     *\n     * @example Invite a user\n     * ```js\n     * const { data, error } = await supabase.auth.admin.inviteUserByEmail('email@example.com')\n     * ```\n     *\n     * @exampleResponse Invite a user\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"user\": {\n     *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *       \"aud\": \"authenticated\",\n     *       \"role\": \"authenticated\",\n     *       \"email\": \"example@email.com\",\n     *       \"invited_at\": \"2024-01-01T00:00:00Z\",\n     *       \"phone\": \"\",\n     *       \"confirmation_sent_at\": \"2024-01-01T00:00:00Z\",\n     *       \"app_metadata\": {\n     *         \"provider\": \"email\",\n     *         \"providers\": [\n     *           \"email\"\n     *         ]\n     *       },\n     *       \"user_metadata\": {},\n     *       \"identities\": [\n     *         {\n     *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"identity_data\": {\n     *             \"email\": \"example@email.com\",\n     *             \"email_verified\": false,\n     *             \"phone_verified\": false,\n     *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *           },\n     *           \"provider\": \"email\",\n     *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *           \"created_at\": \"2024-01-01T00:00:00Z\",\n     *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *           \"email\": \"example@email.com\"\n     *         }\n     *       ],\n     *       \"created_at\": \"2024-01-01T00:00:00Z\",\n     *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *       \"is_anonymous\": false\n     *     }\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     */\n    async inviteUserByEmail(email, options = {}) {\n        try {\n            return await _request(this.fetch, 'POST', `${this.url}/invite`, {\n                body: { email, data: options.data },\n                headers: this.headers,\n                redirectTo: options.redirectTo,\n                xform: _userResponse,\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: { user: null }, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Generates email links and OTPs to be sent via a custom email provider.\n     * @param params The parameters for generating the link, including the link `type`, the user's `email`, and type-specific options such as `password`, `data`, and `redirectTo`.\n     *\n     * @category Auth\n     * @subcategory Auth Admin\n     *\n     * @remarks\n     * - The following types can be passed into `generateLink()`: `signup`, `magiclink`, `invite`, `recovery`, `email_change_current`, `email_change_new`, `phone_change`.\n     * - `generateLink()` only generates the email link for `email_change_email` if the **Secure email change** is enabled in your project's [email auth provider settings](/dashboard/project/_/auth/providers).\n     * - `generateLink()` handles the creation of the user for `signup`, `invite` and `magiclink`.\n     *\n     * @example Generate a signup link\n     * ```js\n     * const { data, error } = await supabase.auth.admin.generateLink({\n     *   type: 'signup',\n     *   email: 'email@example.com',\n     *   password: 'secret'\n     * })\n     * ```\n     *\n     * @exampleResponse Generate a signup link\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"properties\": {\n     *       \"action_link\": \"<LINK_TO_SEND_TO_USER>\",\n     *       \"email_otp\": \"999999\",\n     *       \"hashed_token\": \"<HASHED_TOKEN\",\n     *       \"redirect_to\": \"<REDIRECT_URL>\",\n     *       \"verification_type\": \"signup\"\n     *     },\n     *     \"user\": {\n     *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *       \"aud\": \"authenticated\",\n     *       \"role\": \"authenticated\",\n     *       \"email\": \"email@example.com\",\n     *       \"phone\": \"\",\n     *       \"confirmation_sent_at\": \"2024-01-01T00:00:00Z\",\n     *       \"app_metadata\": {\n     *         \"provider\": \"email\",\n     *         \"providers\": [\n     *           \"email\"\n     *         ]\n     *       },\n     *       \"user_metadata\": {},\n     *       \"identities\": [\n     *         {\n     *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"identity_data\": {\n     *             \"email\": \"email@example.com\",\n     *             \"email_verified\": false,\n     *             \"phone_verified\": false,\n     *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *           },\n     *           \"provider\": \"email\",\n     *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *           \"created_at\": \"2024-01-01T00:00:00Z\",\n     *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *           \"email\": \"email@example.com\"\n     *         }\n     *       ],\n     *       \"created_at\": \"2024-01-01T00:00:00Z\",\n     *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *       \"is_anonymous\": false\n     *     }\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     *\n     * @example Generate an invite link\n     * ```js\n     * const { data, error } = await supabase.auth.admin.generateLink({\n     *   type: 'invite',\n     *   email: 'email@example.com'\n     * })\n     * ```\n     *\n     * @example Generate a magic link\n     * ```js\n     * const { data, error } = await supabase.auth.admin.generateLink({\n     *   type: 'magiclink',\n     *   email: 'email@example.com'\n     * })\n     * ```\n     *\n     * @example Generate a recovery link\n     * ```js\n     * const { data, error } = await supabase.auth.admin.generateLink({\n     *   type: 'recovery',\n     *   email: 'email@example.com'\n     * })\n     * ```\n     *\n     * @example Generate links to change current email address\n     * ```js\n     * // generate an email change link to be sent to the current email address\n     * const { data, error } = await supabase.auth.admin.generateLink({\n     *   type: 'email_change_current',\n     *   email: 'current.email@example.com',\n     *   newEmail: 'new.email@example.com'\n     * })\n     *\n     * // generate an email change link to be sent to the new email address\n     * const { data, error } = await supabase.auth.admin.generateLink({\n     *   type: 'email_change_new',\n     *   email: 'current.email@example.com',\n     *   newEmail: 'new.email@example.com'\n     * })\n     * ```\n     */\n    async generateLink(params) {\n        try {\n            const { options } = params, rest = __rest(params, [\"options\"]);\n            const body = Object.assign(Object.assign({}, rest), options);\n            if ('newEmail' in rest) {\n                // replace newEmail with new_email in request body\n                body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail;\n                delete body['newEmail'];\n            }\n            return await _request(this.fetch, 'POST', `${this.url}/admin/generate_link`, {\n                body: body,\n                headers: this.headers,\n                xform: _generateLinkResponse,\n                redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo,\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return {\n                    data: {\n                        properties: null,\n                        user: null,\n                    },\n                    error,\n                };\n            }\n            throw error;\n        }\n    }\n    // User Admin API\n    /**\n     * Creates a new user.\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     *\n     * @category Auth\n     * @subcategory Auth Admin\n     *\n     * @remarks\n     * - To confirm the user's email address or phone number, set `email_confirm` or `phone_confirm` to true. Both arguments default to false.\n     * - `createUser()` will not send a confirmation email to the user. You can use [`inviteUserByEmail()`](/docs/reference/javascript/auth-admin-inviteuserbyemail) if you want to send them an email invite instead.\n     * - If you are sure that the created user's email or phone number is legitimate and verified, you can set the `email_confirm` or `phone_confirm` param to `true`.\n     *\n     * @example With custom user metadata\n     * ```js\n     * const { data, error } = await supabase.auth.admin.createUser({\n     *   email: 'user@email.com',\n     *   password: 'password',\n     *   user_metadata: { name: 'Yoda' }\n     * })\n     * ```\n     *\n     * @exampleResponse With custom user metadata\n     * ```json\n     * {\n     *   data: {\n     *     user: {\n     *       id: '1',\n     *       aud: 'authenticated',\n     *       role: 'authenticated',\n     *       email: 'example@email.com',\n     *       email_confirmed_at: '2024-01-01T00:00:00Z',\n     *       phone: '',\n     *       confirmation_sent_at: '2024-01-01T00:00:00Z',\n     *       confirmed_at: '2024-01-01T00:00:00Z',\n     *       last_sign_in_at: '2024-01-01T00:00:00Z',\n     *       app_metadata: {},\n     *       user_metadata: {},\n     *       identities: [\n     *         {\n     *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *           \"id\": \"1\",\n     *           \"user_id\": \"1\",\n     *           \"identity_data\": {\n     *             \"email\": \"example@email.com\",\n     *             \"email_verified\": true,\n     *             \"phone_verified\": false,\n     *             \"sub\": \"1\"\n     *           },\n     *           \"provider\": \"email\",\n     *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *           \"created_at\": \"2024-01-01T00:00:00Z\",\n     *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *           \"email\": \"email@example.com\"\n     *         },\n     *       ],\n     *       created_at: '2024-01-01T00:00:00Z',\n     *       updated_at: '2024-01-01T00:00:00Z',\n     *       is_anonymous: false,\n     *     }\n     *   }\n     *   error: null\n     * }\n     * ```\n     *\n     * @example Auto-confirm the user's email\n     * ```js\n     * const { data, error } = await supabase.auth.admin.createUser({\n     *   email: 'user@email.com',\n     *   email_confirm: true\n     * })\n     * ```\n     *\n     * @example Auto-confirm the user's phone number\n     * ```js\n     * const { data, error } = await supabase.auth.admin.createUser({\n     *   phone: '1234567890',\n     *   phone_confirm: true\n     * })\n     * ```\n     */\n    async createUser(attributes) {\n        try {\n            return await _request(this.fetch, 'POST', `${this.url}/admin/users`, {\n                body: attributes,\n                headers: this.headers,\n                xform: _userResponse,\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: { user: null }, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Get a list of users.\n     *\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results.\n     *\n     * @category Auth\n     * @subcategory Auth Admin\n     *\n     * @remarks\n     * - Defaults to return 50 users per page.\n     *\n     * @example Get a page of users\n     * ```js\n     * const { data: { users }, error } = await supabase.auth.admin.listUsers()\n     * ```\n     *\n     * @example Paginated list of users\n     * ```js\n     * const { data: { users }, error } = await supabase.auth.admin.listUsers({\n     *   page: 1,\n     *   perPage: 1000\n     * })\n     * ```\n     */\n    async listUsers(params) {\n        var _a, _b, _c, _d, _e, _f, _g;\n        try {\n            const pagination = { nextPage: null, lastPage: 0, total: 0 };\n            const response = await _request(this.fetch, 'GET', `${this.url}/admin/users`, {\n                headers: this.headers,\n                noResolveJson: true,\n                query: {\n                    page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '',\n                    per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '',\n                },\n                xform: _noResolveJsonResponse,\n            });\n            if (response.error)\n                throw response.error;\n            const users = await response.json();\n            const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0;\n            const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : [];\n            if (links.length > 0) {\n                links.forEach((link) => {\n                    const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1));\n                    const rel = JSON.parse(link.split(';')[1].split('=')[1]);\n                    pagination[`${rel}Page`] = page;\n                });\n                pagination.total = parseInt(total);\n            }\n            return { data: Object.assign(Object.assign({}, users), pagination), error: null };\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: { users: [] }, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Get user by id.\n     *\n     * @param uid The user's unique identifier\n     *\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     *\n     * @category Auth\n     * @subcategory Auth Admin\n     *\n     * @remarks\n     * - Fetches the user object from the database based on the user's id.\n     * - The `getUserById()` method requires the user's id which maps to the `auth.users.id` column.\n     *\n     * @example Fetch the user object using the access_token jwt\n     * ```js\n     * const { data, error } = await supabase.auth.admin.getUserById(1)\n     * ```\n     *\n     * @exampleResponse Fetch the user object using the access_token jwt\n     * ```json\n     * {\n     *   data: {\n     *     user: {\n     *       id: '1',\n     *       aud: 'authenticated',\n     *       role: 'authenticated',\n     *       email: 'example@email.com',\n     *       email_confirmed_at: '2024-01-01T00:00:00Z',\n     *       phone: '',\n     *       confirmation_sent_at: '2024-01-01T00:00:00Z',\n     *       confirmed_at: '2024-01-01T00:00:00Z',\n     *       last_sign_in_at: '2024-01-01T00:00:00Z',\n     *       app_metadata: {},\n     *       user_metadata: {},\n     *       identities: [\n     *         {\n     *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *           \"id\": \"1\",\n     *           \"user_id\": \"1\",\n     *           \"identity_data\": {\n     *             \"email\": \"example@email.com\",\n     *             \"email_verified\": true,\n     *             \"phone_verified\": false,\n     *             \"sub\": \"1\"\n     *           },\n     *           \"provider\": \"email\",\n     *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *           \"created_at\": \"2024-01-01T00:00:00Z\",\n     *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *           \"email\": \"email@example.com\"\n     *         },\n     *       ],\n     *       created_at: '2024-01-01T00:00:00Z',\n     *       updated_at: '2024-01-01T00:00:00Z',\n     *       is_anonymous: false,\n     *     }\n     *   }\n     *   error: null\n     * }\n     * ```\n     */\n    async getUserById(uid) {\n        validateUUID(uid);\n        try {\n            return await _request(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, {\n                headers: this.headers,\n                xform: _userResponse,\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: { user: null }, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Updates the user data. Changes are applied directly without confirmation flows.\n     *\n     * @param uid The user's unique identifier\n     * @param attributes The data you want to update.\n     *\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     *\n     * @remarks\n     * **Important:** This is a server-side operation and does **not** trigger client-side\n     * `onAuthStateChange` listeners. The admin API has no connection to client state.\n     *\n     * To sync changes to the client after calling this method:\n     * 1. On the client, call `supabase.auth.refreshSession()` to fetch the updated user data\n     * 2. This will trigger the `TOKEN_REFRESHED` event and notify all listeners\n     *\n     * @example\n     * ```typescript\n     * // Server-side (Edge Function)\n     * const { data, error } = await supabase.auth.admin.updateUserById(\n     *   userId,\n     *   { user_metadata: { preferences: { theme: 'dark' } } }\n     * )\n     *\n     * // Client-side (to sync the changes)\n     * const { data, error } = await supabase.auth.refreshSession()\n     * // onAuthStateChange listeners will now be notified with updated user\n     * ```\n     *\n     * @see {@link GoTrueClient.refreshSession} for syncing admin changes to the client\n     * @see {@link GoTrueClient.updateUser} for client-side user updates (triggers listeners automatically)\n     *\n     * @category Auth\n     * @subcategory Auth Admin\n     *\n     * @example Updates a user's email\n     * ```js\n     * const { data: user, error } = await supabase.auth.admin.updateUserById(\n     *   '11111111-1111-1111-1111-111111111111',\n     *   { email: 'new@email.com' }\n     * )\n     * ```\n     *\n     * @exampleResponse Updates a user's email\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"user\": {\n     *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *       \"aud\": \"authenticated\",\n     *       \"role\": \"authenticated\",\n     *       \"email\": \"new@email.com\",\n     *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *       \"phone\": \"\",\n     *       \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *       \"recovery_sent_at\": \"2024-01-01T00:00:00Z\",\n     *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *       \"app_metadata\": {\n     *         \"provider\": \"email\",\n     *         \"providers\": [\n     *           \"email\"\n     *         ]\n     *       },\n     *       \"user_metadata\": {\n     *         \"email\": \"example@email.com\",\n     *         \"email_verified\": false,\n     *         \"phone_verified\": false,\n     *         \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *       },\n     *       \"identities\": [\n     *         {\n     *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"identity_data\": {\n     *             \"email\": \"example@email.com\",\n     *             \"email_verified\": false,\n     *             \"phone_verified\": false,\n     *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *           },\n     *           \"provider\": \"email\",\n     *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *           \"created_at\": \"2024-01-01T00:00:00Z\",\n     *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *           \"email\": \"example@email.com\"\n     *         }\n     *       ],\n     *       \"created_at\": \"2024-01-01T00:00:00Z\",\n     *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *       \"is_anonymous\": false\n     *     }\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     *\n     * @example Updates a user's password\n     * ```js\n     * const { data: user, error } = await supabase.auth.admin.updateUserById(\n     *   '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',\n     *   { password: 'new_password' }\n     * )\n     * ```\n     *\n     * @example Updates a user's metadata\n     * ```js\n     * const { data: user, error } = await supabase.auth.admin.updateUserById(\n     *   '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',\n     *   { user_metadata: { hello: 'world' } }\n     * )\n     * ```\n     *\n     * @example Updates a user's app_metadata\n     * ```js\n     * const { data: user, error } = await supabase.auth.admin.updateUserById(\n     *   '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',\n     *   { app_metadata: { plan: 'trial' } }\n     * )\n     * ```\n     *\n     * @example Confirms a user's email address\n     * ```js\n     * const { data: user, error } = await supabase.auth.admin.updateUserById(\n     *   '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',\n     *   { email_confirm: true }\n     * )\n     * ```\n     *\n     * @example Confirms a user's phone number\n     * ```js\n     * const { data: user, error } = await supabase.auth.admin.updateUserById(\n     *   '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',\n     *   { phone_confirm: true }\n     * )\n     * ```\n     *\n     * @example Ban a user for 100 years\n     * ```js\n     * const { data: user, error } = await supabase.auth.admin.updateUserById(\n     *   '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',\n     *   { ban_duration: '876000h' }\n     * )\n     * ```\n     */\n    async updateUserById(uid, attributes) {\n        validateUUID(uid);\n        try {\n            return await _request(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, {\n                body: attributes,\n                headers: this.headers,\n                xform: _userResponse,\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: { user: null }, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Delete a user. Requires a `service_role` key.\n     *\n     * @param id The user id you want to remove.\n     * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible.\n     * Defaults to false for backward compatibility.\n     *\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     *\n     * @category Auth\n     * @subcategory Auth Admin\n     *\n     * @remarks\n     * - The `deleteUser()` method requires the user's ID, which maps to the `auth.users.id` column.\n     *\n     * @example Removes a user\n     * ```js\n     * const { data, error } = await supabase.auth.admin.deleteUser(\n     *   '715ed5db-f090-4b8c-a067-640ecee36aa0'\n     * )\n     * ```\n     *\n     * @exampleResponse Removes a user\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"user\": {}\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     */\n    async deleteUser(id, shouldSoftDelete = false) {\n        validateUUID(id);\n        try {\n            return await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, {\n                headers: this.headers,\n                body: {\n                    should_soft_delete: shouldSoftDelete,\n                },\n                xform: _userResponse,\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: { user: null }, error };\n            }\n            throw error;\n        }\n    }\n    async _listFactors(params) {\n        validateUUID(params.userId);\n        try {\n            const { data, error } = await _request(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, {\n                headers: this.headers,\n                xform: (factors) => {\n                    return { data: { factors }, error: null };\n                },\n            });\n            return { data, error };\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            throw error;\n        }\n    }\n    async _deleteFactor(params) {\n        validateUUID(params.userId);\n        validateUUID(params.id);\n        try {\n            const data = await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, {\n                headers: this.headers,\n            });\n            return { data, error: null };\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Lists all OAuth clients with optional pagination.\n     * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n     *\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     */\n    async _listOAuthClients(params) {\n        var _a, _b, _c, _d, _e, _f, _g;\n        try {\n            const pagination = { nextPage: null, lastPage: 0, total: 0 };\n            const response = await _request(this.fetch, 'GET', `${this.url}/admin/oauth/clients`, {\n                headers: this.headers,\n                noResolveJson: true,\n                query: {\n                    page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '',\n                    per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '',\n                },\n                xform: _noResolveJsonResponse,\n            });\n            if (response.error)\n                throw response.error;\n            const clients = await response.json();\n            const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0;\n            const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : [];\n            if (links.length > 0) {\n                links.forEach((link) => {\n                    const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1));\n                    const rel = JSON.parse(link.split(';')[1].split('=')[1]);\n                    pagination[`${rel}Page`] = page;\n                });\n                pagination.total = parseInt(total);\n            }\n            return { data: Object.assign(Object.assign({}, clients), pagination), error: null };\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: { clients: [] }, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Creates a new OAuth client.\n     * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n     *\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     */\n    async _createOAuthClient(params) {\n        try {\n            return await _request(this.fetch, 'POST', `${this.url}/admin/oauth/clients`, {\n                body: params,\n                headers: this.headers,\n                xform: (client) => {\n                    return { data: client, error: null };\n                },\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Gets details of a specific OAuth client.\n     * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n     *\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     */\n    async _getOAuthClient(clientId) {\n        try {\n            return await _request(this.fetch, 'GET', `${this.url}/admin/oauth/clients/${clientId}`, {\n                headers: this.headers,\n                xform: (client) => {\n                    return { data: client, error: null };\n                },\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Updates an existing OAuth client.\n     * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n     *\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     */\n    async _updateOAuthClient(clientId, params) {\n        try {\n            return await _request(this.fetch, 'PUT', `${this.url}/admin/oauth/clients/${clientId}`, {\n                body: params,\n                headers: this.headers,\n                xform: (client) => {\n                    return { data: client, error: null };\n                },\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Deletes an OAuth client.\n     * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n     *\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     */\n    async _deleteOAuthClient(clientId) {\n        try {\n            await _request(this.fetch, 'DELETE', `${this.url}/admin/oauth/clients/${clientId}`, {\n                headers: this.headers,\n                noResolveJson: true,\n            });\n            return { data: null, error: null };\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Regenerates the secret for an OAuth client.\n     * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n     *\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     */\n    async _regenerateOAuthClientSecret(clientId) {\n        try {\n            return await _request(this.fetch, 'POST', `${this.url}/admin/oauth/clients/${clientId}/regenerate_secret`, {\n                headers: this.headers,\n                xform: (client) => {\n                    return { data: client, error: null };\n                },\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Lists all custom providers with optional type filter.\n     *\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     */\n    async _listCustomProviders(params) {\n        try {\n            const query = {};\n            if (params === null || params === void 0 ? void 0 : params.type) {\n                query.type = params.type;\n            }\n            return await _request(this.fetch, 'GET', `${this.url}/admin/custom-providers`, {\n                headers: this.headers,\n                query,\n                xform: (data) => {\n                    var _a;\n                    return { data: { providers: (_a = data === null || data === void 0 ? void 0 : data.providers) !== null && _a !== void 0 ? _a : [] }, error: null };\n                },\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: { providers: [] }, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Creates a new custom OIDC/OAuth provider.\n     *\n     * For OIDC providers, the server fetches and validates the OpenID Connect discovery document\n     * from the issuer's well-known endpoint (or the provided `discovery_url`) at creation time.\n     * This may return a validation error (`error_code: \"validation_failed\"`) if the discovery\n     * document is unreachable, not valid JSON, missing required fields, or if the issuer\n     * in the document does not match the expected issuer.\n     *\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     */\n    async _createCustomProvider(params) {\n        try {\n            return await _request(this.fetch, 'POST', `${this.url}/admin/custom-providers`, {\n                body: params,\n                headers: this.headers,\n                xform: (provider) => {\n                    return { data: provider, error: null };\n                },\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Gets details of a specific custom provider by identifier.\n     *\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     */\n    async _getCustomProvider(identifier) {\n        try {\n            return await _request(this.fetch, 'GET', `${this.url}/admin/custom-providers/${identifier}`, {\n                headers: this.headers,\n                xform: (provider) => {\n                    return { data: provider, error: null };\n                },\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Updates an existing custom provider.\n     *\n     * When `issuer` or `discovery_url` is changed on an OIDC provider, the server re-fetches and\n     * validates the discovery document before persisting. This may return a validation error\n     * (`error_code: \"validation_failed\"`) if the discovery document is unreachable, invalid, or\n     * the issuer does not match.\n     *\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     */\n    async _updateCustomProvider(identifier, params) {\n        try {\n            return await _request(this.fetch, 'PUT', `${this.url}/admin/custom-providers/${identifier}`, {\n                body: params,\n                headers: this.headers,\n                xform: (provider) => {\n                    return { data: provider, error: null };\n                },\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Deletes a custom provider.\n     *\n     * This function should only be called on a server. Never expose your `service_role` key in the browser.\n     */\n    async _deleteCustomProvider(identifier) {\n        try {\n            await _request(this.fetch, 'DELETE', `${this.url}/admin/custom-providers/${identifier}`, {\n                headers: this.headers,\n                noResolveJson: true,\n            });\n            return { data: null, error: null };\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Lists all passkeys for a user.\n     *\n     * This function should only be called on a server. Never expose your secret key in the browser.\n     *\n     * Requires `auth.experimental.passkey: true`.\n     */\n    async _adminListPasskeys(params) {\n        assertPasskeyExperimentalEnabled(this.experimental);\n        validateUUID(params.userId);\n        try {\n            return await _request(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/passkeys`, { headers: this.headers, xform: (data) => ({ data, error: null }) });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            throw error;\n        }\n    }\n    /**\n     * Deletes a user's passkey.\n     *\n     * This function should only be called on a server. Never expose your secret key in the browser.\n     *\n     * Requires `auth.experimental.passkey: true`.\n     */\n    async _adminDeletePasskey(params) {\n        assertPasskeyExperimentalEnabled(this.experimental);\n        validateUUID(params.userId);\n        validateUUID(params.passkeyId);\n        try {\n            await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/passkeys/${params.passkeyId}`, { headers: this.headers, noResolveJson: true });\n            return { data: null, error: null };\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            throw error;\n        }\n    }\n}\n//# sourceMappingURL=GoTrueAdminApi.js.map","/**\n * Returns a localStorage-like object that stores the key-value pairs in\n * memory.\n */\nexport function memoryLocalStorageAdapter(store = {}) {\n    return {\n        getItem: (key) => {\n            return store[key] || null;\n        },\n        setItem: (key, value) => {\n            store[key] = value;\n        },\n        removeItem: (key) => {\n            delete store[key];\n        },\n    };\n}\n//# sourceMappingURL=local-storage.js.map","/**\n * Lock primitives retained for backwards-compatible imports. The auth client\n * coordinates refreshes itself (deduping in-instance callers onto a shared\n * in-flight promise) and lets the GoTrue server resolve cross-instance races,\n * so it does not invoke any primitive from this module. The functions still\n * work for direct callers that need a navigator.locks-backed or in-process\n * exclusive lock of their own.\n */\nimport { supportsLocalStorage } from './helpers';\n/**\n * @deprecated Debug flag for `navigatorLock` / `processLock`. The auth\n * client ignores both, so this has no client-side effect.\n * @experimental\n */\nexport const internals = {\n    /**\n     * @experimental\n     */\n    debug: !!(globalThis &&\n        supportsLocalStorage() &&\n        globalThis.localStorage &&\n        globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'),\n};\n/**\n * An error thrown when a lock cannot be acquired after some amount of time.\n *\n * @deprecated The auth client doesn't acquire locks around auth operations,\n * so this error never originates from `supabase.auth.*` calls. Direct callers\n * of `navigatorLock` / `processLock` still receive it on acquire timeout.\n */\nexport class LockAcquireTimeoutError extends Error {\n    constructor(message) {\n        super(message);\n        this.isAcquireTimeout = true;\n    }\n}\n/**\n * @deprecated The auth client doesn't call `navigator.locks`, so this error\n * never originates from `supabase.auth.*` calls. Direct callers of\n * `navigatorLock` still receive it on acquire timeout.\n */\nexport class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {\n}\n/**\n * @deprecated The auth client doesn't run `processLock`, so this error\n * never originates from `supabase.auth.*` calls. Direct callers of\n * `processLock` still receive it on acquire timeout.\n */\nexport class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError {\n}\n/**\n * Implements a global exclusive lock using the Navigator LockManager API. It\n * is available on all browsers released after 2022-03-15 with Safari being the\n * last one to release support. If the API is not available, this function will\n * throw. Make sure you check availablility before configuring {@link\n * GoTrueClient}.\n *\n * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug`\n * local storage item to `true`.\n *\n * Internals:\n *\n * Since the LockManager API does not preserve stack traces for the async\n * function passed in the `request` method, a trick is used where acquiring the\n * lock releases a previously started promise to run the operation in the `fn`\n * function. The lock waits for that promise to finish (with or without error),\n * while the function will finally wait for the result anyway.\n *\n * @param name Name of the lock to be acquired.\n * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if\n *                       the lock can't be acquired without waiting. If positive, the lock acquire\n *                       will time out after so many milliseconds. An error is\n *                       a timeout if it has `isAcquireTimeout` set to true.\n * @param fn The operation to run once the lock is acquired.\n *\n * @deprecated The auth client coordinates refreshes itself and the server\n * resolves concurrent refresh races, so passing `{ lock: navigatorLock }`\n * to it has no effect. You can safely drop the import from your client setup.\n */\nexport async function navigatorLock(name, acquireTimeout, fn) {\n    if (internals.debug) {\n        console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout);\n    }\n    const abortController = new globalThis.AbortController();\n    let acquireTimeoutTimer;\n    if (acquireTimeout > 0) {\n        acquireTimeoutTimer = setTimeout(() => {\n            abortController.abort();\n            if (internals.debug) {\n                console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name);\n            }\n        }, acquireTimeout);\n    }\n    // MDN article: https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request\n    // Wrapping navigator.locks.request() with a plain Promise is done as some\n    // libraries like zone.js patch the Promise object to track the execution\n    // context. However, it appears that most browsers use an internal promise\n    // implementation when using the navigator.locks.request() API causing them\n    // to lose context and emit confusing log messages or break certain features.\n    // This wrapping is believed to help zone.js track the execution context\n    // better.\n    await Promise.resolve();\n    try {\n        return await globalThis.navigator.locks.request(name, acquireTimeout === 0\n            ? {\n                mode: 'exclusive',\n                ifAvailable: true,\n            }\n            : {\n                mode: 'exclusive',\n                signal: abortController.signal,\n            }, async (lock) => {\n            if (lock) {\n                // Lock acquired — cancel the acquire-timeout timer so it cannot fire\n                // while fn() is running. Without this, a delayed timeout abort would\n                // set signal.aborted = true even though we already hold the lock,\n                // causing a subsequent steal to be misclassified as \"our timeout\n                // fired\" and triggering a spurious steal-back cascade.\n                clearTimeout(acquireTimeoutTimer);\n                if (internals.debug) {\n                    console.log('@supabase/gotrue-js: navigatorLock: acquired', name, lock.name);\n                }\n                try {\n                    return await fn();\n                }\n                finally {\n                    if (internals.debug) {\n                        console.log('@supabase/gotrue-js: navigatorLock: released', name, lock.name);\n                    }\n                }\n            }\n            else {\n                if (acquireTimeout === 0) {\n                    if (internals.debug) {\n                        console.log('@supabase/gotrue-js: navigatorLock: not immediately available', name);\n                    }\n                    throw new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock \"${name}\" immediately failed`);\n                }\n                else {\n                    if (internals.debug) {\n                        try {\n                            const result = await globalThis.navigator.locks.query();\n                            console.log('@supabase/gotrue-js: Navigator LockManager state', JSON.stringify(result, null, '  '));\n                        }\n                        catch (e) {\n                            console.warn('@supabase/gotrue-js: Error when querying Navigator LockManager state', e);\n                        }\n                    }\n                    // Browser is not following the Navigator LockManager spec, it\n                    // returned a null lock when we didn't use ifAvailable. So we can\n                    // pretend the lock is acquired in the name of backward compatibility\n                    // and user experience and just run the function.\n                    console.warn('@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request');\n                    clearTimeout(acquireTimeoutTimer);\n                    return await fn();\n                }\n            }\n        });\n    }\n    catch (e) {\n        // Always clear the acquire timeout once the request settles, so it cannot\n        // fire later and incorrectly abort/log after a rejection.\n        clearTimeout(acquireTimeoutTimer);\n        // DOMException does not extend Error in Node.js, so use structural check\n        if (e !== null && typeof e === 'object' && 'name' in e && e.name === 'AbortError') {\n            if (abortController.signal.aborted) {\n                // OUR timeout fired — the lock is genuinely orphaned. Steal it.\n                //\n                // The lock acquisition was aborted because the timeout fired while the\n                // request was still pending. This typically means another lock holder is\n                // not releasing the lock, possibly due to React Strict Mode's\n                // double-mount/unmount behavior or a component unmounting mid-operation,\n                // leaving an orphaned lock.\n                //\n                // Recovery: use { steal: true } to forcefully acquire the lock. Per the\n                // Web Locks API spec, this releases any currently held lock with the same\n                // name and grants the request immediately, preempting any queued requests.\n                // The previous holder's callback continues running to completion but no\n                // longer holds the lock for exclusion purposes.\n                //\n                // See: https://github.com/supabase/supabase/issues/42505\n                if (internals.debug) {\n                    console.log('@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock', name);\n                }\n                console.warn(`@supabase/gotrue-js: Lock \"${name}\" was not released within ${acquireTimeout}ms. ` +\n                    'This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). ' +\n                    'Forcefully acquiring the lock to recover.');\n                return await Promise.resolve().then(() => globalThis.navigator.locks.request(name, {\n                    mode: 'exclusive',\n                    steal: true,\n                }, async (lock) => {\n                    if (lock) {\n                        if (internals.debug) {\n                            console.log('@supabase/gotrue-js: navigatorLock: recovered (stolen)', name, lock.name);\n                        }\n                        try {\n                            return await fn();\n                        }\n                        finally {\n                            if (internals.debug) {\n                                console.log('@supabase/gotrue-js: navigatorLock: released (stolen)', name, lock.name);\n                            }\n                        }\n                    }\n                    else {\n                        // This should not happen with steal: true, but handle gracefully.\n                        console.warn('@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true');\n                        return await fn();\n                    }\n                }));\n            }\n            else {\n                // We HELD the lock but another request stole it from us.\n                // Per the Web Locks spec, our fn() callback is still running as an\n                // orphaned background task — do NOT steal back. Stealing back would\n                // cause a cascade (A steals B, B steals A, ...) and run fn() a second\n                // time concurrently, corrupting auth state.\n                // Convert to a typed error so callers (e.g. _autoRefreshTokenTick)\n                // can handle/filter it without it leaking to Sentry as a raw AbortError.\n                if (internals.debug) {\n                    console.log('@supabase/gotrue-js: navigatorLock: lock was stolen by another request', name);\n                }\n                throw new NavigatorLockAcquireTimeoutError(`Lock \"${name}\" was released because another request stole it`);\n            }\n        }\n        throw e;\n    }\n}\nconst PROCESS_LOCKS = {};\n/**\n * Implements a global exclusive lock that works only in the current process.\n * Useful for environments like React Native or other non-browser\n * single-process (i.e. no concept of \"tabs\") environments.\n *\n * Use {@link navigatorLock} in browser environments.\n *\n * @param name Name of the lock to be acquired.\n * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if\n *                       the lock can't be acquired without waiting. If positive, the lock acquire\n *                       will time out after so many milliseconds. An error is\n *                       a timeout if it has `isAcquireTimeout` set to true.\n * @param fn The operation to run once the lock is acquired.\n *\n * @deprecated The auth client coordinates refreshes itself and the server\n * resolves concurrent refresh races, so passing `{ lock: processLock }`\n * to it has no effect. You can safely drop the import from your client setup.\n *\n * @example\n * ```ts\n * await processLock('migrate', 5000, async () => {\n *   await runMigration()\n * })\n * ```\n */\nexport async function processLock(name, acquireTimeout, fn) {\n    var _a;\n    const previousOperation = (_a = PROCESS_LOCKS[name]) !== null && _a !== void 0 ? _a : Promise.resolve();\n    // Wrap previousOperation to handle errors without using .catch()\n    // This avoids Firefox content script security errors\n    const previousOperationHandled = (async () => {\n        try {\n            await previousOperation;\n            return null;\n        }\n        catch (e) {\n            // ignore error of previous operation that we're waiting to finish\n            return null;\n        }\n    })();\n    const currentOperation = (async () => {\n        let timeoutId = null;\n        try {\n            // Wait for either previous operation or timeout\n            const timeoutPromise = acquireTimeout >= 0\n                ? new Promise((_, reject) => {\n                    timeoutId = setTimeout(() => {\n                        console.warn(`@supabase/gotrue-js: Lock \"${name}\" acquisition timed out after ${acquireTimeout}ms. ` +\n                            'This may be caused by another operation holding the lock. ' +\n                            'Consider increasing lockAcquireTimeout or checking for stuck operations.');\n                        reject(new ProcessLockAcquireTimeoutError(`Acquiring process lock with name \"${name}\" timed out`));\n                    }, acquireTimeout);\n                })\n                : null;\n            await Promise.race([previousOperationHandled, timeoutPromise].filter((x) => x));\n            // If we reach here, previousOperationHandled won the race\n            // Clear the timeout to prevent false warnings\n            if (timeoutId !== null) {\n                clearTimeout(timeoutId);\n            }\n        }\n        catch (e) {\n            // Clear the timeout on error path as well\n            if (timeoutId !== null) {\n                clearTimeout(timeoutId);\n            }\n            // Re-throw timeout errors, ignore others\n            if (e instanceof LockAcquireTimeoutError) {\n                throw e;\n            }\n            // Fall through to run fn() - previous operation finished with error\n        }\n        // Previous operations finished and we didn't get a race on the acquire\n        // timeout, so the current operation can finally start\n        return await fn();\n    })();\n    PROCESS_LOCKS[name] = (async () => {\n        try {\n            return await currentOperation;\n        }\n        catch (e) {\n            if (e instanceof LockAcquireTimeoutError) {\n                // if the current operation timed out, it doesn't mean that the previous\n                // operation finished, so we need continue waiting for it to finish\n                try {\n                    await previousOperation;\n                }\n                catch (prevError) {\n                    // Ignore previous operation errors\n                }\n                return null;\n            }\n            throw e;\n        }\n    })();\n    // finally wait for the current operation to finish successfully, with an\n    // error or with an acquire timeout error\n    return await currentOperation;\n}\n//# sourceMappingURL=locks.js.map","/**\n * https://mathiasbynens.be/notes/globalthis\n */\nexport function polyfillGlobalThis() {\n    if (typeof globalThis === 'object')\n        return;\n    try {\n        Object.defineProperty(Object.prototype, '__magic__', {\n            get: function () {\n                return this;\n            },\n            configurable: true,\n        });\n        // @ts-expect-error 'Allow access to magic'\n        __magic__.globalThis = __magic__;\n        // @ts-expect-error 'Allow access to magic'\n        delete Object.prototype.__magic__;\n    }\n    catch (e) {\n        if (typeof self !== 'undefined') {\n            // @ts-expect-error 'Allow access to globals'\n            self.globalThis = self;\n        }\n    }\n}\n//# sourceMappingURL=polyfills.js.map","// types and functions copied over from viem so this library doesn't depend on it\nexport function getAddress(address) {\n    if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {\n        throw new Error(`@supabase/auth-js: Address \"${address}\" is invalid.`);\n    }\n    return address.toLowerCase();\n}\nexport function fromHex(hex) {\n    return parseInt(hex, 16);\n}\nexport function toHex(value) {\n    const bytes = new TextEncoder().encode(value);\n    const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n    return ('0x' + hex);\n}\n/**\n * Creates EIP-4361 formatted message.\n */\nexport function createSiweMessage(parameters) {\n    var _a;\n    const { chainId, domain, expirationTime, issuedAt = new Date(), nonce, notBefore, requestId, resources, scheme, uri, version, } = parameters;\n    // Validate fields\n    {\n        if (!Number.isInteger(chainId))\n            throw new Error(`@supabase/auth-js: Invalid SIWE message field \"chainId\". Chain ID must be a EIP-155 chain ID. Provided value: ${chainId}`);\n        if (!domain)\n            throw new Error(`@supabase/auth-js: Invalid SIWE message field \"domain\". Domain must be provided.`);\n        if (nonce && nonce.length < 8)\n            throw new Error(`@supabase/auth-js: Invalid SIWE message field \"nonce\". Nonce must be at least 8 characters. Provided value: ${nonce}`);\n        if (!uri)\n            throw new Error(`@supabase/auth-js: Invalid SIWE message field \"uri\". URI must be provided.`);\n        if (version !== '1')\n            throw new Error(`@supabase/auth-js: Invalid SIWE message field \"version\". Version must be '1'. Provided value: ${version}`);\n        if ((_a = parameters.statement) === null || _a === void 0 ? void 0 : _a.includes('\\n'))\n            throw new Error(`@supabase/auth-js: Invalid SIWE message field \"statement\". Statement must not include '\\\\n'. Provided value: ${parameters.statement}`);\n    }\n    // Construct message\n    const address = getAddress(parameters.address);\n    const origin = scheme ? `${scheme}://${domain}` : domain;\n    const statement = parameters.statement ? `${parameters.statement}\\n` : '';\n    const prefix = `${origin} wants you to sign in with your Ethereum account:\\n${address}\\n\\n${statement}`;\n    let suffix = `URI: ${uri}\\nVersion: ${version}\\nChain ID: ${chainId}${nonce ? `\\nNonce: ${nonce}` : ''}\\nIssued At: ${issuedAt.toISOString()}`;\n    if (expirationTime)\n        suffix += `\\nExpiration Time: ${expirationTime.toISOString()}`;\n    if (notBefore)\n        suffix += `\\nNot Before: ${notBefore.toISOString()}`;\n    if (requestId)\n        suffix += `\\nRequest ID: ${requestId}`;\n    if (resources) {\n        let content = '\\nResources:';\n        for (const resource of resources) {\n            if (!resource || typeof resource !== 'string')\n                throw new Error(`@supabase/auth-js: Invalid SIWE message field \"resources\". Every resource must be a valid string. Provided value: ${resource}`);\n            content += `\\n- ${resource}`;\n        }\n        suffix += content;\n    }\n    return `${prefix}\\n${suffix}`;\n}\n//# sourceMappingURL=ethereum.js.map","/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport { isValidDomain } from './webauthn';\n/**\n * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented\n * errors in the spec was raised after calling `navigator.credentials.create()` or\n * `navigator.credentials.get()`:\n *\n * - `AbortError`\n * - `ConstraintError`\n * - `InvalidStateError`\n * - `NotAllowedError`\n * - `NotSupportedError`\n * - `SecurityError`\n * - `TypeError`\n * - `UnknownError`\n *\n * Error messages were determined through investigation of the spec to determine under which\n * scenarios a given error would be raised.\n */\nexport class WebAuthnError extends Error {\n    constructor({ message, code, cause, name, }) {\n        var _a;\n        // @ts-ignore: help Rollup understand that `cause` is okay to set\n        super(message, { cause });\n        this.__isWebAuthnError = true;\n        this.name = (_a = name !== null && name !== void 0 ? name : (cause instanceof Error ? cause.name : undefined)) !== null && _a !== void 0 ? _a : 'Unknown Error';\n        this.code = code;\n    }\n    toJSON() {\n        return {\n            name: this.name,\n            message: this.message,\n            code: this.code,\n        };\n    }\n}\n/**\n * Error class for unknown WebAuthn errors.\n * Wraps unexpected errors that don't match known WebAuthn error conditions.\n */\nexport class WebAuthnUnknownError extends WebAuthnError {\n    constructor(message, originalError) {\n        super({\n            code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n            cause: originalError,\n            message,\n        });\n        this.name = 'WebAuthnUnknownError';\n        this.originalError = originalError;\n    }\n}\n/**\n * Type guard to check if an error is a WebAuthnError.\n * @param {unknown} error - The error to check\n * @returns {boolean} True if the error is a WebAuthnError\n */\nexport function isWebAuthnError(error) {\n    return typeof error === 'object' && error !== null && '__isWebAuthnError' in error;\n}\n/**\n * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`.\n * Maps browser errors to specific WebAuthn error codes for better debugging.\n * @param {Object} params - Error identification parameters\n * @param {Error} params.error - The error thrown by the browser\n * @param {CredentialCreationOptions} params.options - The options passed to credentials.create()\n * @returns {WebAuthnError} A WebAuthnError with a specific error code\n * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential}\n */\nexport function identifyRegistrationError({ error, options, }) {\n    var _a, _b, _c;\n    const { publicKey } = options;\n    if (!publicKey) {\n        throw Error('options was missing required publicKey property');\n    }\n    if (error.name === 'AbortError') {\n        if (options.signal instanceof AbortSignal) {\n            // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)\n            return new WebAuthnError({\n                message: 'Registration ceremony was sent an abort signal',\n                code: 'ERROR_CEREMONY_ABORTED',\n                cause: error,\n            });\n        }\n    }\n    else if (error.name === 'ConstraintError') {\n        if (((_a = publicKey.authenticatorSelection) === null || _a === void 0 ? void 0 : _a.requireResidentKey) === true) {\n            // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4)\n            return new WebAuthnError({\n                message: 'Discoverable credentials were required but no available authenticator supported it',\n                code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT',\n                cause: error,\n            });\n        }\n        else if (\n        // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024\n        options.mediation === 'conditional' &&\n            ((_b = publicKey.authenticatorSelection) === null || _b === void 0 ? void 0 : _b.userVerification) === 'required') {\n            // https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4)\n            return new WebAuthnError({\n                message: 'User verification was required during automatic registration but it could not be performed',\n                code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE',\n                cause: error,\n            });\n        }\n        else if (((_c = publicKey.authenticatorSelection) === null || _c === void 0 ? void 0 : _c.userVerification) === 'required') {\n            // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5)\n            return new WebAuthnError({\n                message: 'User verification was required but no available authenticator supported it',\n                code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT',\n                cause: error,\n            });\n        }\n    }\n    else if (error.name === 'InvalidStateError') {\n        // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20)\n        // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3)\n        return new WebAuthnError({\n            message: 'The authenticator was previously registered',\n            code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED',\n            cause: error,\n        });\n    }\n    else if (error.name === 'NotAllowedError') {\n        /**\n         * Pass the error directly through. Platforms are overloading this error beyond what the spec\n         * defines and we don't want to overwrite potentially useful error messages.\n         */\n        return new WebAuthnError({\n            message: error.message,\n            code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n            cause: error,\n        });\n    }\n    else if (error.name === 'NotSupportedError') {\n        const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key');\n        if (validPubKeyCredParams.length === 0) {\n            // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10)\n            return new WebAuthnError({\n                message: 'No entry in pubKeyCredParams was of type \"public-key\"',\n                code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS',\n                cause: error,\n            });\n        }\n        // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2)\n        return new WebAuthnError({\n            message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms',\n            code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG',\n            cause: error,\n        });\n    }\n    else if (error.name === 'SecurityError') {\n        const effectiveDomain = window.location.hostname;\n        if (!isValidDomain(effectiveDomain)) {\n            // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7)\n            return new WebAuthnError({\n                message: `${window.location.hostname} is an invalid domain`,\n                code: 'ERROR_INVALID_DOMAIN',\n                cause: error,\n            });\n        }\n        else if (publicKey.rp.id !== effectiveDomain) {\n            // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8)\n            return new WebAuthnError({\n                message: `The RP ID \"${publicKey.rp.id}\" is invalid for this domain`,\n                code: 'ERROR_INVALID_RP_ID',\n                cause: error,\n            });\n        }\n    }\n    else if (error.name === 'TypeError') {\n        if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) {\n            // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5)\n            return new WebAuthnError({\n                message: 'User ID was not between 1 and 64 characters',\n                code: 'ERROR_INVALID_USER_ID_LENGTH',\n                cause: error,\n            });\n        }\n    }\n    else if (error.name === 'UnknownError') {\n        // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1)\n        // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8)\n        return new WebAuthnError({\n            message: 'The authenticator was unable to process the specified options, or could not create a new credential',\n            code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',\n            cause: error,\n        });\n    }\n    return new WebAuthnError({\n        message: 'a Non-Webauthn related error has occurred',\n        code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n        cause: error,\n    });\n}\n/**\n * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`.\n * Maps browser errors to specific WebAuthn error codes for better debugging.\n * @param {Object} params - Error identification parameters\n * @param {Error} params.error - The error thrown by the browser\n * @param {CredentialRequestOptions} params.options - The options passed to credentials.get()\n * @returns {WebAuthnError} A WebAuthnError with a specific error code\n * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion}\n */\nexport function identifyAuthenticationError({ error, options, }) {\n    const { publicKey } = options;\n    if (!publicKey) {\n        throw Error('options was missing required publicKey property');\n    }\n    if (error.name === 'AbortError') {\n        if (options.signal instanceof AbortSignal) {\n            // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)\n            return new WebAuthnError({\n                message: 'Authentication ceremony was sent an abort signal',\n                code: 'ERROR_CEREMONY_ABORTED',\n                cause: error,\n            });\n        }\n    }\n    else if (error.name === 'NotAllowedError') {\n        /**\n         * Pass the error directly through. Platforms are overloading this error beyond what the spec\n         * defines and we don't want to overwrite potentially useful error messages.\n         */\n        return new WebAuthnError({\n            message: error.message,\n            code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n            cause: error,\n        });\n    }\n    else if (error.name === 'SecurityError') {\n        const effectiveDomain = window.location.hostname;\n        if (!isValidDomain(effectiveDomain)) {\n            // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5)\n            return new WebAuthnError({\n                message: `${window.location.hostname} is an invalid domain`,\n                code: 'ERROR_INVALID_DOMAIN',\n                cause: error,\n            });\n        }\n        else if (publicKey.rpId !== effectiveDomain) {\n            // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6)\n            return new WebAuthnError({\n                message: `The RP ID \"${publicKey.rpId}\" is invalid for this domain`,\n                code: 'ERROR_INVALID_RP_ID',\n                cause: error,\n            });\n        }\n    }\n    else if (error.name === 'UnknownError') {\n        // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1)\n        // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12)\n        return new WebAuthnError({\n            message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature',\n            code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',\n            cause: error,\n        });\n    }\n    return new WebAuthnError({\n        message: 'a Non-Webauthn related error has occurred',\n        code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n        cause: error,\n    });\n}\n//# sourceMappingURL=webauthn.errors.js.map","import { __rest } from \"tslib\";\nimport { base64UrlToUint8Array, bytesToBase64URL } from './base64url';\nimport { AuthError, AuthUnknownError, isAuthError } from './errors';\nimport { isBrowser } from './helpers';\nimport { identifyAuthenticationError, identifyRegistrationError, isWebAuthnError, WebAuthnError, WebAuthnUnknownError, } from './webauthn.errors';\nexport { WebAuthnError, isWebAuthnError, identifyRegistrationError, identifyAuthenticationError };\n/**\n * WebAuthn abort service to manage ceremony cancellation.\n * Ensures only one WebAuthn ceremony is active at a time to prevent \"operation already in progress\" errors.\n *\n * @experimental This class is experimental and may change in future releases\n * @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies}\n */\nexport class WebAuthnAbortService {\n    /**\n     * Create an abort signal for a new WebAuthn operation.\n     * Automatically cancels any existing operation.\n     *\n     * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get()\n     * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal}\n     */\n    createNewAbortSignal() {\n        // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get()\n        if (this.controller) {\n            const abortError = new Error('Cancelling existing WebAuthn API call for new one');\n            abortError.name = 'AbortError';\n            this.controller.abort(abortError);\n        }\n        const newController = new AbortController();\n        this.controller = newController;\n        return newController.signal;\n    }\n    /**\n     * Manually cancel the current WebAuthn operation.\n     * Useful for cleaning up when user cancels or navigates away.\n     *\n     * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort}\n     */\n    cancelCeremony() {\n        if (this.controller) {\n            const abortError = new Error('Manually cancelling existing WebAuthn API call');\n            abortError.name = 'AbortError';\n            this.controller.abort(abortError);\n            this.controller = undefined;\n        }\n    }\n}\n/**\n * Singleton instance to ensure only one WebAuthn ceremony is active at a time.\n * This prevents \"operation already in progress\" errors when retrying WebAuthn operations.\n *\n * @experimental This instance is experimental and may change in future releases\n */\nexport const webAuthnAbortService = new WebAuthnAbortService();\n/**\n * Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers\n * as required by the WebAuthn browser API.\n * Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback.\n *\n * @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields\n * @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create()\n * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON}\n */\nexport function deserializeCredentialCreationOptions(options) {\n    if (!options) {\n        throw new Error('Credential creation options are required');\n    }\n    // Check if the native parseCreationOptionsFromJSON method is available\n    if (typeof PublicKeyCredential !== 'undefined' &&\n        'parseCreationOptionsFromJSON' in PublicKeyCredential &&\n        typeof PublicKeyCredential\n            .parseCreationOptionsFromJSON === 'function') {\n        // Use the native WebAuthn Level 3 method\n        return PublicKeyCredential.parseCreationOptionsFromJSON(\n        /** we assert the options here as typescript still doesn't know about future webauthn types */\n        options);\n    }\n    // Fallback to manual parsing for browsers that don't support the native method\n    // Destructure to separate fields that need transformation\n    const { challenge: challengeStr, user: userOpts, excludeCredentials } = options, restOptions = __rest(options\n    // Convert challenge from base64url to ArrayBuffer\n    , [\"challenge\", \"user\", \"excludeCredentials\"]);\n    // Convert challenge from base64url to ArrayBuffer\n    const challenge = base64UrlToUint8Array(challengeStr).buffer;\n    // Convert user.id from base64url to ArrayBuffer\n    const user = Object.assign(Object.assign({}, userOpts), { id: base64UrlToUint8Array(userOpts.id).buffer });\n    // Build the result object\n    const result = Object.assign(Object.assign({}, restOptions), { challenge,\n        user });\n    // Only add excludeCredentials if it exists\n    if (excludeCredentials && excludeCredentials.length > 0) {\n        result.excludeCredentials = new Array(excludeCredentials.length);\n        for (let i = 0; i < excludeCredentials.length; i++) {\n            const cred = excludeCredentials[i];\n            result.excludeCredentials[i] = Object.assign(Object.assign({}, cred), { id: base64UrlToUint8Array(cred.id).buffer, type: cred.type || 'public-key', \n                // Cast transports to handle future transport types like \"cable\"\n                transports: cred.transports });\n        }\n    }\n    return result;\n}\n/**\n * Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers\n * as required by the WebAuthn browser API.\n * Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback.\n *\n * @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields\n * @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get()\n * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON}\n */\nexport function deserializeCredentialRequestOptions(options) {\n    if (!options) {\n        throw new Error('Credential request options are required');\n    }\n    // Check if the native parseRequestOptionsFromJSON method is available\n    if (typeof PublicKeyCredential !== 'undefined' &&\n        'parseRequestOptionsFromJSON' in PublicKeyCredential &&\n        typeof PublicKeyCredential\n            .parseRequestOptionsFromJSON === 'function') {\n        // Use the native WebAuthn Level 3 method\n        return PublicKeyCredential.parseRequestOptionsFromJSON(options);\n    }\n    // Fallback to manual parsing for browsers that don't support the native method\n    // Destructure to separate fields that need transformation\n    const { challenge: challengeStr, allowCredentials } = options, restOptions = __rest(options\n    // Convert challenge from base64url to ArrayBuffer\n    , [\"challenge\", \"allowCredentials\"]);\n    // Convert challenge from base64url to ArrayBuffer\n    const challenge = base64UrlToUint8Array(challengeStr).buffer;\n    // Build the result object\n    const result = Object.assign(Object.assign({}, restOptions), { challenge });\n    // Only add allowCredentials if it exists\n    if (allowCredentials && allowCredentials.length > 0) {\n        result.allowCredentials = new Array(allowCredentials.length);\n        for (let i = 0; i < allowCredentials.length; i++) {\n            const cred = allowCredentials[i];\n            result.allowCredentials[i] = Object.assign(Object.assign({}, cred), { id: base64UrlToUint8Array(cred.id).buffer, type: cred.type || 'public-key', \n                // Cast transports to handle future transport types like \"cable\"\n                transports: cred.transports });\n        }\n    }\n    return result;\n}\n/**\n * Convert a registration/enrollment credential response to server format.\n * Serializes binary fields to base64url for JSON transmission.\n * Supports both native WebAuthn Level 3 toJSON and manual fallback.\n *\n * @param {RegistrationCredential} credential - Credential from navigator.credentials.create()\n * @returns {RegistrationResponseJSON} JSON-serializable credential for server\n * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON}\n */\nexport function serializeCredentialCreationResponse(credential) {\n    var _a;\n    // Check if the credential instance has the toJSON method\n    if ('toJSON' in credential && typeof credential.toJSON === 'function') {\n        // Use the native WebAuthn Level 3 method\n        return credential.toJSON();\n    }\n    const credentialWithAttachment = credential;\n    return {\n        id: credential.id,\n        rawId: credential.id,\n        response: {\n            attestationObject: bytesToBase64URL(new Uint8Array(credential.response.attestationObject)),\n            clientDataJSON: bytesToBase64URL(new Uint8Array(credential.response.clientDataJSON)),\n        },\n        type: 'public-key',\n        clientExtensionResults: credential.getClientExtensionResults(),\n        // Convert null to undefined and cast to AuthenticatorAttachment type\n        authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined),\n    };\n}\n/**\n * Convert an authentication/verification credential response to server format.\n * Serializes binary fields to base64url for JSON transmission.\n * Supports both native WebAuthn Level 3 toJSON and manual fallback.\n *\n * @param {AuthenticationCredential} credential - Credential from navigator.credentials.get()\n * @returns {AuthenticationResponseJSON} JSON-serializable credential for server\n * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON}\n */\nexport function serializeCredentialRequestResponse(credential) {\n    var _a;\n    // Check if the credential instance has the toJSON method\n    if ('toJSON' in credential && typeof credential.toJSON === 'function') {\n        // Use the native WebAuthn Level 3 method\n        return credential.toJSON();\n    }\n    // Fallback to manual conversion for browsers that don't support toJSON\n    // Access authenticatorAttachment via type assertion to handle TypeScript version differences\n    // @simplewebauthn/types includes this property but base TypeScript 4.7.4 doesn't\n    const credentialWithAttachment = credential;\n    const clientExtensionResults = credential.getClientExtensionResults();\n    const assertionResponse = credential.response;\n    return {\n        id: credential.id,\n        rawId: credential.id, // W3C spec expects rawId to match id for JSON format\n        response: {\n            authenticatorData: bytesToBase64URL(new Uint8Array(assertionResponse.authenticatorData)),\n            clientDataJSON: bytesToBase64URL(new Uint8Array(assertionResponse.clientDataJSON)),\n            signature: bytesToBase64URL(new Uint8Array(assertionResponse.signature)),\n            userHandle: assertionResponse.userHandle\n                ? bytesToBase64URL(new Uint8Array(assertionResponse.userHandle))\n                : undefined,\n        },\n        type: 'public-key',\n        clientExtensionResults,\n        // Convert null to undefined and cast to AuthenticatorAttachment type\n        authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined),\n    };\n}\n/**\n * A simple test to determine if a hostname is a properly-formatted domain name.\n * Considers localhost valid for development environments.\n *\n * A \"valid domain\" is defined here: https://url.spec.whatwg.org/#valid-domain\n *\n * Regex sourced from here:\n * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html\n *\n * @param {string} hostname - The hostname to validate\n * @returns {boolean} True if valid domain or localhost\n * @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain}\n */\nexport function isValidDomain(hostname) {\n    return (\n    // Consider localhost valid as well since it's okay wrt Secure Contexts\n    hostname === 'localhost' || /^([a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,}$/i.test(hostname));\n}\n/**\n * Determine if the browser is capable of WebAuthn.\n * Checks for necessary Web APIs: PublicKeyCredential and Credential Management.\n *\n * @returns {boolean} True if browser supports WebAuthn\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential#browser_compatibility MDN - PublicKeyCredential Browser Compatibility}\n */\nexport function browserSupportsWebAuthn() {\n    var _a, _b;\n    return !!(isBrowser() &&\n        'PublicKeyCredential' in window &&\n        window.PublicKeyCredential &&\n        'credentials' in navigator &&\n        typeof ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a === void 0 ? void 0 : _a.create) === 'function' &&\n        typeof ((_b = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _b === void 0 ? void 0 : _b.get) === 'function');\n}\n/**\n * Create a WebAuthn credential using the browser's credentials API.\n * Wraps navigator.credentials.create() with error handling.\n *\n * @param {CredentialCreationOptions} options - Options including publicKey parameters\n * @returns {Promise<RequestResult<RegistrationCredential, WebAuthnError>>} Created credential or error\n * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential}\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create}\n */\nexport async function createCredential(options) {\n    try {\n        const response = await navigator.credentials.create(\n        /** we assert the type here until typescript types are updated */\n        options);\n        if (!response) {\n            return {\n                data: null,\n                error: new WebAuthnUnknownError('Empty credential response', response),\n            };\n        }\n        if (!(response instanceof PublicKeyCredential)) {\n            return {\n                data: null,\n                error: new WebAuthnUnknownError('Browser returned unexpected credential type', response),\n            };\n        }\n        return { data: response, error: null };\n    }\n    catch (err) {\n        return {\n            data: null,\n            error: identifyRegistrationError({\n                error: err,\n                options,\n            }),\n        };\n    }\n}\n/**\n * Get a WebAuthn credential using the browser's credentials API.\n * Wraps navigator.credentials.get() with error handling.\n *\n * @param {CredentialRequestOptions} options - Options including publicKey parameters\n * @returns {Promise<RequestResult<AuthenticationCredential, WebAuthnError>>} Retrieved credential or error\n * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion}\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get}\n */\nexport async function getCredential(options) {\n    try {\n        const response = await navigator.credentials.get(\n        /** we assert the type here until typescript types are updated */\n        options);\n        if (!response) {\n            return {\n                data: null,\n                error: new WebAuthnUnknownError('Empty credential response', response),\n            };\n        }\n        if (!(response instanceof PublicKeyCredential)) {\n            return {\n                data: null,\n                error: new WebAuthnUnknownError('Browser returned unexpected credential type', response),\n            };\n        }\n        return { data: response, error: null };\n    }\n    catch (err) {\n        return {\n            data: null,\n            error: identifyAuthenticationError({\n                error: err,\n                options,\n            }),\n        };\n    }\n}\nexport const DEFAULT_CREATION_OPTIONS = {\n    hints: ['security-key'],\n    authenticatorSelection: {\n        authenticatorAttachment: 'cross-platform',\n        requireResidentKey: false,\n        /** set to preferred because older yubikeys don't have PIN/Biometric */\n        userVerification: 'preferred',\n        residentKey: 'discouraged',\n    },\n    attestation: 'direct',\n};\nexport const DEFAULT_REQUEST_OPTIONS = {\n    /** set to preferred because older yubikeys don't have PIN/Biometric */\n    userVerification: 'preferred',\n    hints: ['security-key'],\n    attestation: 'direct',\n};\nfunction deepMerge(...sources) {\n    const isObject = (val) => val !== null && typeof val === 'object' && !Array.isArray(val);\n    const isArrayBufferLike = (val) => val instanceof ArrayBuffer || ArrayBuffer.isView(val);\n    const result = {};\n    for (const source of sources) {\n        if (!source)\n            continue;\n        for (const key in source) {\n            const value = source[key];\n            if (value === undefined)\n                continue;\n            if (Array.isArray(value)) {\n                // preserve array reference, including unions like AuthenticatorTransport[]\n                result[key] = value;\n            }\n            else if (isArrayBufferLike(value)) {\n                result[key] = value;\n            }\n            else if (isObject(value)) {\n                const existing = result[key];\n                if (isObject(existing)) {\n                    result[key] = deepMerge(existing, value);\n                }\n                else {\n                    result[key] = deepMerge(value);\n                }\n            }\n            else {\n                result[key] = value;\n            }\n        }\n    }\n    return result;\n}\n/**\n * Merges WebAuthn credential creation options with overrides.\n * Sets sensible defaults for authenticator selection and extensions.\n *\n * @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server\n * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply\n * @param {string} friendlyName - Optional friendly name for the credential\n * @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options\n * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria}\n */\nexport function mergeCredentialCreationOptions(baseOptions, overrides) {\n    return deepMerge(DEFAULT_CREATION_OPTIONS, baseOptions, overrides || {});\n}\n/**\n * Merges WebAuthn credential request options with overrides.\n * Sets sensible defaults for user verification and hints.\n *\n * @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server\n * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply\n * @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options\n * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions}\n */\nexport function mergeCredentialRequestOptions(baseOptions, overrides) {\n    return deepMerge(DEFAULT_REQUEST_OPTIONS, baseOptions, overrides || {});\n}\n/**\n * WebAuthn API wrapper for Supabase Auth.\n * Provides methods for enrolling, challenging, verifying, authenticating, and registering WebAuthn credentials.\n *\n * @experimental This API is experimental and may change in future releases\n * @see {@link https://w3c.github.io/webauthn/ W3C WebAuthn Specification}\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API MDN - Web Authentication API}\n */\nexport class WebAuthnApi {\n    constructor(client) {\n        this.client = client;\n        // Bind all methods so they can be destructured\n        this.enroll = this._enroll.bind(this);\n        this.challenge = this._challenge.bind(this);\n        this.verify = this._verify.bind(this);\n        this.authenticate = this._authenticate.bind(this);\n        this.register = this._register.bind(this);\n    }\n    /**\n     * Enroll a new WebAuthn factor.\n     * Creates an unverified WebAuthn factor that must be verified with a credential.\n     *\n     * @experimental This method is experimental and may change in future releases\n     * @param {Omit<MFAEnrollWebauthnParams, 'factorType'>} params - Enrollment parameters (friendlyName required)\n     * @returns {Promise<AuthMFAEnrollWebauthnResponse>} Enrolled factor details or error\n     * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential}\n     */\n    async _enroll(params) {\n        return this.client.mfa.enroll(Object.assign(Object.assign({}, params), { factorType: 'webauthn' }));\n    }\n    /**\n     * Challenge for WebAuthn credential creation or authentication.\n     * Combines server challenge with browser credential operations.\n     * Handles both registration (create) and authentication (request) flows.\n     *\n     * @experimental This method is experimental and may change in future releases\n     * @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId\n     * @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials\n     * @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation\n     * @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request\n     * @returns {Promise<RequestResult>} Challenge response with credential or error\n     * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation}\n     * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion}\n     */\n    async _challenge({ factorId, webauthn, friendlyName, signal, }, overrides) {\n        var _a;\n        try {\n            // Get challenge from server using the client's MFA methods\n            const { data: challengeResponse, error: challengeError } = await this.client.mfa.challenge({\n                factorId,\n                webauthn,\n            });\n            if (!challengeResponse) {\n                return { data: null, error: challengeError };\n            }\n            const abortSignal = signal !== null && signal !== void 0 ? signal : webAuthnAbortService.createNewAbortSignal();\n            /** webauthn will fail if either of the name/displayname are blank */\n            if (challengeResponse.webauthn.type === 'create') {\n                const { user } = challengeResponse.webauthn.credential_options.publicKey;\n                if (!user.name) {\n                    // Preserve original format: use friendlyName if provided, otherwise fetch fallback\n                    // This maintains backward compatibility with the ${user.id}:${name} format\n                    const nameToUse = friendlyName;\n                    if (!nameToUse) {\n                        // Only fetch user data if friendlyName is not provided (bug fix for null friendlyName)\n                        const currentUser = await this.client.getUser();\n                        const userData = currentUser.data.user;\n                        const fallbackName = ((_a = userData === null || userData === void 0 ? void 0 : userData.user_metadata) === null || _a === void 0 ? void 0 : _a.name) || (userData === null || userData === void 0 ? void 0 : userData.email) || (userData === null || userData === void 0 ? void 0 : userData.id) || 'User';\n                        user.name = `${user.id}:${fallbackName}`;\n                    }\n                    else {\n                        user.name = `${user.id}:${nameToUse}`;\n                    }\n                }\n                if (!user.displayName) {\n                    user.displayName = user.name;\n                }\n            }\n            switch (challengeResponse.webauthn.type) {\n                case 'create': {\n                    const options = mergeCredentialCreationOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.create);\n                    const { data, error } = await createCredential({\n                        publicKey: options,\n                        signal: abortSignal,\n                    });\n                    if (data) {\n                        return {\n                            data: {\n                                factorId,\n                                challengeId: challengeResponse.id,\n                                webauthn: {\n                                    type: challengeResponse.webauthn.type,\n                                    credential_response: data,\n                                },\n                            },\n                            error: null,\n                        };\n                    }\n                    return { data: null, error };\n                }\n                case 'request': {\n                    const options = mergeCredentialRequestOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.request);\n                    const { data, error } = await getCredential(Object.assign(Object.assign({}, challengeResponse.webauthn.credential_options), { publicKey: options, signal: abortSignal }));\n                    if (data) {\n                        return {\n                            data: {\n                                factorId,\n                                challengeId: challengeResponse.id,\n                                webauthn: {\n                                    type: challengeResponse.webauthn.type,\n                                    credential_response: data,\n                                },\n                            },\n                            error: null,\n                        };\n                    }\n                    return { data: null, error };\n                }\n            }\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            return {\n                data: null,\n                error: new AuthUnknownError('Unexpected error in challenge', error),\n            };\n        }\n    }\n    /**\n     * Verify a WebAuthn credential with the server.\n     * Completes the WebAuthn ceremony by sending the credential to the server for verification.\n     *\n     * @experimental This method is experimental and may change in future releases\n     * @param {Object} params - Verification parameters\n     * @param {string} params.challengeId - ID of the challenge being verified\n     * @param {string} params.factorId - ID of the WebAuthn factor\n     * @param {MFAVerifyWebauthnParams<T>['webauthn']} params.webauthn - WebAuthn credential response\n     * @returns {Promise<AuthMFAVerifyResponse>} Verification result with session or error\n     * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion}\n     * */\n    async _verify({ challengeId, factorId, webauthn, }) {\n        return this.client.mfa.verify({\n            factorId,\n            challengeId,\n            webauthn: webauthn,\n        });\n    }\n    /**\n     * Complete WebAuthn authentication flow.\n     * Performs challenge and verification in a single operation for existing credentials.\n     *\n     * @experimental This method is experimental and may change in future releases\n     * @param {Object} params - Authentication parameters\n     * @param {string} params.factorId - ID of the WebAuthn factor to authenticate with\n     * @param {Object} params.webauthn - WebAuthn configuration\n     * @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname)\n     * @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin)\n     * @param {AbortSignal} params.webauthn.signal - Optional abort signal\n     * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get\n     * @returns {Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>} Authentication result\n     * @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony}\n     * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions}\n     */\n    async _authenticate({ factorId, webauthn: { rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, } = {}, }, overrides) {\n        if (!rpId) {\n            return {\n                data: null,\n                error: new AuthError('rpId is required for WebAuthn authentication'),\n            };\n        }\n        try {\n            if (!browserSupportsWebAuthn()) {\n                return {\n                    data: null,\n                    error: new AuthUnknownError('Browser does not support WebAuthn', null),\n                };\n            }\n            // Get challenge and credential\n            const { data: challengeResponse, error: challengeError } = await this.challenge({\n                factorId,\n                webauthn: { rpId, rpOrigins },\n                signal,\n            }, { request: overrides });\n            if (!challengeResponse) {\n                return { data: null, error: challengeError };\n            }\n            const { webauthn } = challengeResponse;\n            // Verify credential\n            return this._verify({\n                factorId,\n                challengeId: challengeResponse.challengeId,\n                webauthn: {\n                    type: webauthn.type,\n                    rpId,\n                    rpOrigins,\n                    credential_response: webauthn.credential_response,\n                },\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            return {\n                data: null,\n                error: new AuthUnknownError('Unexpected error in authenticate', error),\n            };\n        }\n    }\n    /**\n     * Complete WebAuthn registration flow.\n     * Performs enrollment, challenge, and verification in a single operation for new credentials.\n     *\n     * @experimental This method is experimental and may change in future releases\n     * @param {Object} params - Registration parameters\n     * @param {string} params.friendlyName - User-friendly name for the credential\n     * @param {string} params.rpId - Relying Party ID (defaults to current hostname)\n     * @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin)\n     * @param {AbortSignal} params.signal - Optional abort signal\n     * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create\n     * @returns {Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>} Registration result\n     * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony}\n     * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions}\n     */\n    async _register({ friendlyName, webauthn: { rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, } = {}, }, overrides) {\n        if (!rpId) {\n            return {\n                data: null,\n                error: new AuthError('rpId is required for WebAuthn registration'),\n            };\n        }\n        try {\n            if (!browserSupportsWebAuthn()) {\n                return {\n                    data: null,\n                    error: new AuthUnknownError('Browser does not support WebAuthn', null),\n                };\n            }\n            // Enroll factor\n            const { data: factor, error: enrollError } = await this._enroll({\n                friendlyName,\n            });\n            if (!factor) {\n                await this.client.mfa\n                    .listFactors()\n                    .then((factors) => {\n                    var _a;\n                    // Only an unverified factor is leftover from the enrollment that just\n                    // failed, and removing it is what lets a retry with the same name\n                    // succeed. A verified factor of that name is a passkey the user is\n                    // already using, so it must never be selected here.\n                    return (_a = factors.data) === null || _a === void 0 ? void 0 : _a.all.find((v) => v.factor_type === 'webauthn' &&\n                        v.friendly_name === friendlyName &&\n                        v.status === 'unverified');\n                })\n                    .then((factor) => (factor ? this.client.mfa.unenroll({ factorId: factor === null || factor === void 0 ? void 0 : factor.id }) : void 0));\n                return { data: null, error: enrollError };\n            }\n            // Get challenge and create credential\n            const { data: challengeResponse, error: challengeError } = await this._challenge({\n                factorId: factor.id,\n                friendlyName: factor.friendly_name,\n                webauthn: { rpId, rpOrigins },\n                signal,\n            }, {\n                create: overrides,\n            });\n            if (!challengeResponse) {\n                return { data: null, error: challengeError };\n            }\n            return this._verify({\n                factorId: factor.id,\n                challengeId: challengeResponse.challengeId,\n                webauthn: {\n                    rpId,\n                    rpOrigins,\n                    type: challengeResponse.webauthn.type,\n                    credential_response: challengeResponse.webauthn.credential_response,\n                },\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return { data: null, error };\n            }\n            return {\n                data: null,\n                error: new AuthUnknownError('Unexpected error in register', error),\n            };\n        }\n    }\n}\n//# sourceMappingURL=webauthn.js.map","import GoTrueAdminApi from './GoTrueAdminApi';\nimport { AUTO_REFRESH_TICK_DURATION_MS, AUTO_REFRESH_TICK_THRESHOLD, DEFAULT_HEADERS, EXPIRY_MARGIN_MS, GOTRUE_URL, JWKS_TTL, PKCE_FLOW_ID_PARAM, REFRESH_FAILURE_COOLDOWN_MS, STORAGE_KEY, } from './lib/constants';\nimport { AuthImplicitGrantRedirectError, AuthInvalidCredentialsError, AuthInvalidJwtError, AuthInvalidTokenResponseError, AuthPKCECodeVerifierMissingError, AuthPKCEGrantCodeExchangeError, AuthRefreshDiscardedError, AuthSessionMissingError, AuthUnknownError, isAuthApiError, isAuthError, isAuthImplicitGrantRedirectError, isAuthRefreshDiscardedError, isAuthRetryableFetchError, isAuthSessionMissingError, } from './lib/errors';\nimport { _request, _sessionResponse, _sessionResponsePassword, _ssoResponse, _userResponse, } from './lib/fetch';\nimport { appendFlowIdToRedirectTo, assertPasskeyExperimentalEnabled, assertRecoveryCodesExperimentalEnabled, decodeJWT, deepClone, Deferred, expiresAt, generateCallbackId, getAlgorithm, getCodeChallengeAndMethod, getItemAsync, insecureUserWarningProxy, isBrowser, parseParametersFromURL, pkceVerifierSlotKey, removeAllPKCEVerifiers, removeItemAsync, removePKCEVerifier, resolveFetch, retrievePKCEVerifier, retryable, setItemAsync, sleep, supportsLocalStorage, userNotAvailableProxy, validateExp, validatePKCEFlowId, } from './lib/helpers';\nimport { memoryLocalStorageAdapter } from './lib/local-storage';\nimport { LockAcquireTimeoutError } from './lib/locks';\nimport { polyfillGlobalThis } from './lib/polyfills';\nimport { version } from './lib/version';\nimport { bytesToBase64URL, stringToUint8Array } from './lib/base64url';\nimport { createSiweMessage, fromHex, getAddress, toHex, } from './lib/web3/ethereum';\nimport { createCredential, deserializeCredentialCreationOptions, deserializeCredentialRequestOptions, getCredential, serializeCredentialCreationResponse, serializeCredentialRequestResponse, browserSupportsWebAuthn, webAuthnAbortService, WebAuthnApi, } from './lib/webauthn';\npolyfillGlobalThis(); // Make \"globalThis\" available\nconst DEFAULT_OPTIONS = {\n    url: GOTRUE_URL,\n    storageKey: STORAGE_KEY,\n    autoRefreshToken: true,\n    persistSession: true,\n    detectSessionInUrl: true,\n    headers: DEFAULT_HEADERS,\n    flowType: 'implicit',\n    debug: false,\n    hasCustomAuthorizationHeader: false,\n    throwOnError: false,\n    lockAcquireTimeout: 5000, // 5 seconds. Only used when a custom `lock` is supplied. TODO(v3): remove.\n    skipAutoInitialize: false,\n    experimental: {},\n};\n/**\n * No-op lock used internally as a placeholder. Kept so older test setups that\n * inject this exact reference do not break; new code never sees it because\n * `this.lock` stays `null` when no custom lock is supplied (lockless path).\n * TODO(v3): remove with the legacy lock path.\n */\nasync function lockNoOp(name, acquireTimeout, fn) {\n    return await fn();\n}\n/**\n * Caches JWKS values for all clients created in the same environment. This is\n * especially useful for shared-memory execution environments such as Vercel's\n * Fluid Compute, AWS Lambda or Supabase's Edge Functions. Regardless of how\n * many clients are created, if they share the same storage key they will use\n * the same JWKS cache, significantly speeding up getClaims() with asymmetric\n * JWTs.\n */\nconst GLOBAL_JWKS = {};\n// Warn once per JS realm, not per client instance — server-side apps can\n// construct many clients per process and must not be spammed.\nlet deprecatedLockWarned = false;\nclass GoTrueClient {\n    /**\n     * The JWKS used for verifying asymmetric JWTs\n     */\n    get jwks() {\n        var _a, _b;\n        return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.jwks) !== null && _b !== void 0 ? _b : { keys: [] };\n    }\n    set jwks(value) {\n        GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { jwks: value });\n    }\n    get jwks_cached_at() {\n        var _a, _b;\n        return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.cachedAt) !== null && _b !== void 0 ? _b : Number.MIN_SAFE_INTEGER;\n    }\n    set jwks_cached_at(value) {\n        GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { cachedAt: value });\n    }\n    /**\n     * Create a new client for use in the browser.\n     *\n     * @example Using supabase-js (recommended)\n     * ```ts\n     * import { createClient } from '@supabase/supabase-js'\n     *\n     * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n     * const { data, error } = await supabase.auth.getUser()\n     * ```\n     *\n     * @example Standalone import for bundle-sensitive environments\n     * ```ts\n     * import { GoTrueClient } from '@supabase/auth-js'\n     *\n     * const auth = new GoTrueClient({\n     *   url: 'https://xyzcompany.supabase.co/auth/v1',\n     *   headers: { apikey: 'your-publishable-key' },\n     *   storageKey: 'supabase-auth',\n     * })\n     * ```\n     */\n    constructor(options) {\n        var _a, _b, _c;\n        /**\n         * @experimental\n         */\n        this.userStorage = null;\n        this.memoryStorage = null;\n        this.stateChangeEmitters = new Map();\n        this.autoRefreshTicker = null;\n        this.autoRefreshTickTimeout = null;\n        this.visibilityChangedCallback = null;\n        this.refreshingDeferred = null;\n        /**\n         * Cache of the most recent refresh failure, keyed by the refresh token\n         * that failed. Serial callers passing the *same* token within\n         * `REFRESH_FAILURE_COOLDOWN_MS` (including subsequent auto-refresh ticks)\n         * receive this cached result instead of firing another `/token` request.\n         * Callers passing a *different* token (token rotation pickup, explicit\n         * `setSession`/`refreshSession({ refresh_token })`, multi-account switch)\n         * bypass the cache and attempt a fresh refresh as they should.\n         * Cleared on any successful refresh (locally or via BroadcastChannel from\n         * another tab) and on `_removeSession`.\n         *\n         * Pairs with `refreshingDeferred`: concurrent callers share the in-flight\n         * promise, serial callers within the cooldown share the failure result.\n         */\n        this.lastRefreshFailure = null;\n        /**\n         * Monotonic counter incremented at the top of `_removeSession`, before any\n         * `await`. The commit guard inside `_callRefreshToken` captures this value\n         * before `_saveSession` and re-checks it after, so a `signOut` that\n         * interleaves inside `_saveSession`'s storage-write awaits is still caught\n         * (the post-fetch storage snapshot alone misses that window).\n         */\n        this._sessionRemovalEpoch = 0;\n        /**\n         * Keeps track of the async client initialization.\n         * When null or not yet resolved the auth state is `unknown`\n         * Once resolved the auth state is known and it's safe to call any further client methods.\n         * Keep extra care to never reject or throw uncaught errors\n         */\n        this.initializePromise = null;\n        /**\n         * Non-null only while `initialize()` is running. While open,\n         * `_notifyAllSubscribers` enqueues init-chain notifications (those fired with\n         * `broadcast = true`, i.e. from `_recoverAndRefresh`) into this array instead\n         * of firing directly, so that `initializePromise` is guaranteed to be\n         * resolved before any subscriber callback runs. Callbacks that call\n         * `getSession()` / `getUser()` etc. would otherwise deadlock because those\n         * methods await `initializePromise`. Notifications from the incoming\n         * BroadcastChannel handler (`broadcast = false`) are not enqueued — they fire\n         * immediately. Flushed (in order) by `initialize()` after `initializePromise`\n         * settles.\n         */\n        this._pendingInitNotifications = null;\n        this.detectSessionInUrl = true;\n        this.hasCustomAuthorizationHeader = false;\n        this.suppressGetSessionWarning = false;\n        /**\n         * Custom lock function passed via `settings.lock`. When non-null, every auth\n         * operation runs inside `_acquireLock`. When null (the default), the client\n         * uses its lockless coordination (refresh single-flight + commit guard).\n         * TODO(v3): remove along with the legacy lock path.\n         */\n        this.lock = null;\n        this.lockAcquired = false;\n        this.pendingInLock = [];\n        /**\n         * Used to broadcast state change events to other tabs listening.\n         */\n        this.broadcastChannel = null;\n        this.logger = console.log;\n        const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options);\n        this.storageKey = settings.storageKey;\n        this.instanceID = (_a = GoTrueClient.nextInstanceID[this.storageKey]) !== null && _a !== void 0 ? _a : 0;\n        GoTrueClient.nextInstanceID[this.storageKey] = this.instanceID + 1;\n        this.logDebugMessages = !!settings.debug;\n        if (typeof settings.debug === 'function') {\n            this.logger = settings.debug;\n        }\n        if (this.instanceID > 0 && isBrowser()) {\n            const message = `${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;\n            console.warn(message);\n            if (this.logDebugMessages) {\n                console.trace(message);\n            }\n        }\n        this.persistSession = settings.persistSession;\n        this.autoRefreshToken = settings.autoRefreshToken;\n        this.experimental = (_b = settings.experimental) !== null && _b !== void 0 ? _b : {};\n        this.admin = new GoTrueAdminApi({\n            url: settings.url,\n            headers: settings.headers,\n            fetch: settings.fetch,\n            experimental: this.experimental,\n        });\n        this.url = settings.url;\n        this.headers = settings.headers;\n        this.fetch = resolveFetch(settings.fetch);\n        this.detectSessionInUrl = settings.detectSessionInUrl;\n        this.flowType = settings.flowType;\n        this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader;\n        this.throwOnError = settings.throwOnError;\n        // Always wire `lockAcquireTimeout` even on the lockless path: consumers\n        // (including supabase-js tests) read it off the client to verify option\n        // flow-through.\n        this.lockAcquireTimeout = settings.lockAcquireTimeout;\n        // TODO(v3): remove. Legacy opt-in path preserved for backwards\n        // compatibility with callers passing a custom `lock` (typically React\n        // Native `processLock` or Node multi-process setups). When `settings.lock`\n        // is null the client uses its lockless coordination — no `navigator.locks`\n        // by default, no implicit `processLock`.\n        if (settings.lock != null) {\n            this.lock = settings.lock;\n            if (!deprecatedLockWarned) {\n                deprecatedLockWarned = true;\n                console.warn(`${this._logPrefix()} The \"lock\" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`);\n            }\n        }\n        if (!this.jwks) {\n            this.jwks = { keys: [] };\n            this.jwks_cached_at = Number.MIN_SAFE_INTEGER;\n        }\n        this.mfa = {\n            verify: this._verify.bind(this),\n            enroll: this._enroll.bind(this),\n            unenroll: this._unenroll.bind(this),\n            challenge: this._challenge.bind(this),\n            listFactors: this._listFactors.bind(this),\n            challengeAndVerify: this._challengeAndVerify.bind(this),\n            getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this),\n            webauthn: new WebAuthnApi(this),\n            recoveryCodes: {\n                getStatus: this._getRecoveryCodesStatus.bind(this),\n                generate: this._generateRecoveryCodes.bind(this),\n                verify: this._verifyRecoveryCode.bind(this),\n                regenerate: this._regenerateRecoveryCodes.bind(this),\n                unenroll: this._unenrollRecoveryCodes.bind(this),\n            },\n        };\n        this.oauth = {\n            getAuthorizationDetails: this._getAuthorizationDetails.bind(this),\n            approveAuthorization: this._approveAuthorization.bind(this),\n            denyAuthorization: this._denyAuthorization.bind(this),\n            listGrants: this._listOAuthGrants.bind(this),\n            revokeGrant: this._revokeOAuthGrant.bind(this),\n        };\n        this.passkey = {\n            startRegistration: this._startPasskeyRegistration.bind(this),\n            verifyRegistration: this._verifyPasskeyRegistration.bind(this),\n            startAuthentication: this._startPasskeyAuthentication.bind(this),\n            verifyAuthentication: this._verifyPasskeyAuthentication.bind(this),\n            list: this._listPasskeys.bind(this),\n            update: this._updatePasskey.bind(this),\n            delete: this._deletePasskey.bind(this),\n        };\n        if (this.persistSession) {\n            if (settings.storage) {\n                this.storage = settings.storage;\n            }\n            else {\n                if (supportsLocalStorage()) {\n                    this.storage = globalThis.localStorage;\n                }\n                else {\n                    this.memoryStorage = {};\n                    this.storage = memoryLocalStorageAdapter(this.memoryStorage);\n                }\n            }\n            if (settings.userStorage) {\n                this.userStorage = settings.userStorage;\n            }\n        }\n        else {\n            this.memoryStorage = {};\n            this.storage = memoryLocalStorageAdapter(this.memoryStorage);\n        }\n        if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) {\n            try {\n                this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey);\n            }\n            catch (e) {\n                console.error('Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e);\n            }\n            (_c = this.broadcastChannel) === null || _c === void 0 ? void 0 : _c.addEventListener('message', async (event) => {\n                this._debug('received broadcast notification from other tab or client', event);\n                // Another tab successfully refreshed or signed in — any cached\n                // failure in this tab is stale and should not block the next\n                // refresh attempt.\n                if (event.data.event === 'TOKEN_REFRESHED' || event.data.event === 'SIGNED_IN') {\n                    this.lastRefreshFailure = null;\n                }\n                try {\n                    await this._notifyAllSubscribers(event.data.event, event.data.session, false); // broadcast = false so we don't get an endless loop of messages\n                }\n                catch (error) {\n                    this._debug('#broadcastChannel', 'error', error);\n                }\n            });\n        }\n        // Only auto-initialize if not explicitly disabled. Skipped in SSR contexts\n        // where initialization timing must be controlled. All public methods have\n        // lazy initialization, so the client remains fully functional.\n        if (!settings.skipAutoInitialize) {\n            this.initialize().catch((error) => {\n                this._debug('#initialize()', 'error', error);\n            });\n        }\n    }\n    /**\n     * Returns whether error throwing mode is enabled for this client.\n     */\n    isThrowOnErrorEnabled() {\n        return this.throwOnError;\n    }\n    /**\n     * Centralizes return handling with optional error throwing. When `throwOnError` is enabled\n     * and the provided result contains a non-nullish error, the error is thrown instead of\n     * being returned. This ensures consistent behavior across all public API methods.\n     */\n    _returnResult(result) {\n        if (this.throwOnError && result && result.error) {\n            throw result.error;\n        }\n        return result;\n    }\n    _logPrefix() {\n        return ('GoTrueClient@' +\n            `${this.storageKey}:${this.instanceID} (${version}) ${new Date().toISOString()}`);\n    }\n    _debug(...args) {\n        if (this.logDebugMessages) {\n            this.logger(this._logPrefix(), ...args);\n        }\n        return this;\n    }\n    /**\n     * Initialize the auth client by loading the session from storage or\n     * detecting it from the URL after an OAuth, magic-link, or password-recovery\n     * redirect.\n     *\n     * **Most callers do not need to invoke this directly.** The client calls it\n     * automatically during construction, and to react to sign-in events (including\n     * post-redirect events) you should subscribe to `onAuthStateChange` rather\n     * than awaiting `initialize()`.\n     *\n     * You only need to call it manually when you have opted out of the automatic\n     * call by passing `skipAutoInitialize: true` — for example, in an SSR context\n     * where you need to control initialization timing. In that case, awaiting\n     * `initialize()` returns the resolved session result (or any error encountered\n     * while detecting it from the URL).\n     *\n     * @category Auth\n     */\n    async initialize() {\n        var _a;\n        if (this.initializePromise) {\n            return await this.initializePromise;\n        }\n        // Open the notification queue before _initialize() runs so that every\n        // _notifyAllSubscribers call inside the init chain enqueues instead of\n        // firing. Without this, a callback receiving SIGNED_IN (or TOKEN_REFRESHED\n        // / SIGNED_OUT) during _recoverAndRefresh would deadlock if it called\n        // getSession() / getUser() — those methods await initializePromise, which\n        // can only resolve after the callback returns, which can only return after\n        // getSession() resolves. The queue is flushed below after initializePromise\n        // has settled, so callbacks run with a fully resolved initializePromise.\n        this._pendingInitNotifications = [];\n        this.initializePromise = (async () => {\n            if (this.lock != null) {\n                // TODO(v3): remove legacy lock path\n                return await this._acquireLock(this.lockAcquireTimeout, async () => {\n                    return await this._initialize();\n                });\n            }\n            return await this._initialize();\n        })();\n        const result = await this.initializePromise;\n        // initializePromise is now resolved — flush queued notifications in order.\n        // Callbacks can safely call getSession() / getUser() / signOut() etc.\n        const queue = (_a = this._pendingInitNotifications) !== null && _a !== void 0 ? _a : [];\n        this._pendingInitNotifications = null;\n        for (const n of queue) {\n            await this._notifyAllSubscribers(n.event, n.session, n.broadcast);\n        }\n        return result;\n    }\n    /**\n     * IMPORTANT:\n     * 1. Never throw in this method, as it is called from the constructor\n     * 2. Never return a session from this method as it would be cached over\n     *    the whole lifetime of the client\n     */\n    async _initialize() {\n        var _a;\n        try {\n            let params = {};\n            let callbackUrlType = 'none';\n            if (isBrowser()) {\n                params = parseParametersFromURL(window.location.href);\n                if (this._isImplicitGrantCallback(params)) {\n                    callbackUrlType = 'implicit';\n                }\n                else if (await this._isPKCECallback(params)) {\n                    callbackUrlType = 'pkce';\n                }\n            }\n            /**\n             * Attempt to get the session from the URL only if these conditions are fulfilled\n             *\n             * Note: If the URL isn't one of the callback url types (implicit or pkce),\n             * then there could be an existing session so we don't want to prematurely remove it\n             */\n            if (isBrowser() && this.detectSessionInUrl && callbackUrlType !== 'none') {\n                const { data, error } = await this._getSessionFromURL(params, callbackUrlType);\n                if (error) {\n                    this._debug('#_initialize()', 'error detecting session from URL', error);\n                    if (isAuthImplicitGrantRedirectError(error)) {\n                        const errorCode = (_a = error.details) === null || _a === void 0 ? void 0 : _a.code;\n                        if (errorCode === 'identity_already_exists' ||\n                            errorCode === 'identity_not_found' ||\n                            errorCode === 'single_identity_not_deletable') {\n                            return { error };\n                        }\n                    }\n                    // Don't remove existing session on URL login failure.\n                    // A failed attempt (e.g. reused magic link) shouldn't invalidate a valid session.\n                    return { error };\n                }\n                const { session, redirectType } = data;\n                this._debug('#_initialize()', 'detected session in URL', session, 'redirect type', redirectType);\n                await this._saveSession(session);\n                setTimeout(async () => {\n                    if (redirectType === 'recovery') {\n                        await this._notifyAllSubscribers('PASSWORD_RECOVERY', session);\n                    }\n                    else {\n                        await this._notifyAllSubscribers('SIGNED_IN', session);\n                    }\n                }, 0);\n                return { error: null };\n            }\n            // no login attempt via callback url try to recover session from storage\n            await this._recoverAndRefresh();\n            return { error: null };\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ error });\n            }\n            return this._returnResult({\n                error: new AuthUnknownError('Unexpected error during initialization', error),\n            });\n        }\n        finally {\n            await this._handleVisibilityChange();\n            this._debug('#_initialize()', 'end');\n        }\n    }\n    /**\n     * Creates a new anonymous user.\n     *\n     * @returns A session where the is_anonymous claim in the access token JWT set to true\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - Returns an anonymous user\n     * - It is recommended to set up captcha for anonymous sign-ins to prevent abuse. You can pass in the captcha token in the `options` param.\n     *\n     * @example Create an anonymous user\n     * ```js\n     * const { data, error } = await supabase.auth.signInAnonymously({\n     *   options: {\n     *     captchaToken\n     *   }\n     * });\n     * ```\n     *\n     * @exampleResponse Create an anonymous user\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"user\": {\n     *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *       \"aud\": \"authenticated\",\n     *       \"role\": \"authenticated\",\n     *       \"email\": \"\",\n     *       \"phone\": \"\",\n     *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *       \"app_metadata\": {},\n     *       \"user_metadata\": {},\n     *       \"identities\": [],\n     *       \"created_at\": \"2024-01-01T00:00:00Z\",\n     *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *       \"is_anonymous\": true\n     *     },\n     *     \"session\": {\n     *       \"access_token\": \"<ACCESS_TOKEN>\",\n     *       \"token_type\": \"bearer\",\n     *       \"expires_in\": 3600,\n     *       \"expires_at\": 1700000000,\n     *       \"refresh_token\": \"<REFRESH_TOKEN>\",\n     *       \"user\": {\n     *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *         \"aud\": \"authenticated\",\n     *         \"role\": \"authenticated\",\n     *         \"email\": \"\",\n     *         \"phone\": \"\",\n     *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *         \"app_metadata\": {},\n     *         \"user_metadata\": {},\n     *         \"identities\": [],\n     *         \"created_at\": \"2024-01-01T00:00:00Z\",\n     *         \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *         \"is_anonymous\": true\n     *       }\n     *     }\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     *\n     * @example Create an anonymous user with custom user metadata\n     * ```js\n     * const { data, error } = await supabase.auth.signInAnonymously({\n     *   options: {\n     *     data\n     *   }\n     * })\n     * ```\n     */\n    async signInAnonymously(credentials) {\n        var _a, _b, _c;\n        try {\n            const res = await _request(this.fetch, 'POST', `${this.url}/signup`, {\n                headers: this.headers,\n                body: {\n                    data: (_b = (_a = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {},\n                    gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken },\n                },\n                xform: _sessionResponse,\n            });\n            const { data, error } = res;\n            if (error || !data) {\n                return this._returnResult({ data: { user: null, session: null }, error: error });\n            }\n            const session = data.session;\n            const user = data.user;\n            if (data.session) {\n                await this._saveSession(data.session);\n                await this._notifyAllSubscribers('SIGNED_IN', session);\n            }\n            return this._returnResult({ data: { user, session }, error: null });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: { user: null, session: null }, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Creates a new user.\n     *\n     * Be aware that if a user account exists in the system you may get back an\n     * error message that attempts to hide this information from the user.\n     * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled.\n     *\n     * @returns A logged-in session if the server has \"autoconfirm\" ON\n     * @returns A user if the server has \"autoconfirm\" OFF\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - By default, the user needs to verify their email address before logging in. To turn this off, disable **Confirm email** in [your project](/dashboard/project/_/auth/providers).\n     * - **Confirm email** determines if users need to confirm their email address after signing up.\n     *   - If **Confirm email** is enabled, a `user` is returned but `session` is null.\n     *   - If **Confirm email** is disabled, both a `user` and a `session` are returned.\n     * - When the user confirms their email address, they are redirected to the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) by default. You can modify your `SITE_URL` or add additional redirect URLs in [your project](/dashboard/project/_/auth/url-configuration).\n     * - If signUp() is called for an existing confirmed user:\n     *   - When both **Confirm email** and **Confirm phone** (even when phone provider is disabled) are enabled in [your project](/dashboard/project/_/auth/providers), an obfuscated/fake user object is returned.\n     *   - When either **Confirm email** or **Confirm phone** (even when phone provider is disabled) is disabled, the error message, `User already registered` is returned.\n     * - To fetch the currently logged-in user, refer to [`getUser()`](/docs/reference/javascript/auth-getuser).\n     *\n     * @example Sign up with an email and password\n     * ```js\n     * const { data, error } = await supabase.auth.signUp({\n     *   email: 'example@email.com',\n     *   password: 'example-password',\n     * })\n     * ```\n     *\n     * @exampleResponse Sign up with an email and password\n     * ```json\n     * // Some fields may be null if \"confirm email\" is enabled.\n     * {\n     *   \"data\": {\n     *     \"user\": {\n     *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *       \"aud\": \"authenticated\",\n     *       \"role\": \"authenticated\",\n     *       \"email\": \"example@email.com\",\n     *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *       \"phone\": \"\",\n     *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *       \"app_metadata\": {\n     *         \"provider\": \"email\",\n     *         \"providers\": [\n     *           \"email\"\n     *         ]\n     *       },\n     *       \"user_metadata\": {},\n     *       \"identities\": [\n     *         {\n     *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"identity_data\": {\n     *             \"email\": \"example@email.com\",\n     *             \"email_verified\": false,\n     *             \"phone_verified\": false,\n     *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *           },\n     *           \"provider\": \"email\",\n     *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *           \"created_at\": \"2024-01-01T00:00:00Z\",\n     *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *           \"email\": \"example@email.com\"\n     *         }\n     *       ],\n     *       \"created_at\": \"2024-01-01T00:00:00Z\",\n     *       \"updated_at\": \"2024-01-01T00:00:00Z\"\n     *     },\n     *     \"session\": {\n     *       \"access_token\": \"<ACCESS_TOKEN>\",\n     *       \"token_type\": \"bearer\",\n     *       \"expires_in\": 3600,\n     *       \"expires_at\": 1700000000,\n     *       \"refresh_token\": \"<REFRESH_TOKEN>\",\n     *       \"user\": {\n     *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *         \"aud\": \"authenticated\",\n     *         \"role\": \"authenticated\",\n     *         \"email\": \"example@email.com\",\n     *         \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *         \"phone\": \"\",\n     *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *         \"app_metadata\": {\n     *           \"provider\": \"email\",\n     *           \"providers\": [\n     *             \"email\"\n     *           ]\n     *         },\n     *         \"user_metadata\": {},\n     *         \"identities\": [\n     *           {\n     *             \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *             \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *             \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *             \"identity_data\": {\n     *               \"email\": \"example@email.com\",\n     *               \"email_verified\": false,\n     *               \"phone_verified\": false,\n     *               \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *             },\n     *             \"provider\": \"email\",\n     *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *             \"created_at\": \"2024-01-01T00:00:00Z\",\n     *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *             \"email\": \"example@email.com\"\n     *           }\n     *         ],\n     *         \"created_at\": \"2024-01-01T00:00:00Z\",\n     *         \"updated_at\": \"2024-01-01T00:00:00Z\"\n     *       }\n     *     }\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     *\n     * @example Sign up with a phone number and password (SMS)\n     * ```js\n     * const { data, error } = await supabase.auth.signUp({\n     *   phone: '123456789',\n     *   password: 'example-password',\n     *   options: {\n     *     channel: 'sms'\n     *   }\n     * })\n     * ```\n     *\n     * @exampleDescription Sign up with a phone number and password (whatsapp)\n     * The user will be sent a WhatsApp message which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. Note that a user will need to have a valid WhatsApp account that is linked to Twilio in order to use this feature.\n     *\n     * @example Sign up with a phone number and password (whatsapp)\n     * ```js\n     * const { data, error } = await supabase.auth.signUp({\n     *   phone: '123456789',\n     *   password: 'example-password',\n     *   options: {\n     *     channel: 'whatsapp'\n     *   }\n     * })\n     * ```\n     *\n     * @example Sign up with additional user metadata\n     * ```js\n     * const { data, error } = await supabase.auth.signUp(\n     *   {\n     *     email: 'example@email.com',\n     *     password: 'example-password',\n     *     options: {\n     *       data: {\n     *         first_name: 'John',\n     *         age: 27,\n     *       }\n     *     }\n     *   }\n     * )\n     * ```\n     *\n     * @exampleDescription Sign up with a redirect URL\n     * - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project.\n     *\n     * @example Sign up with a redirect URL\n     * ```js\n     * const { data, error } = await supabase.auth.signUp(\n     *   {\n     *     email: 'example@email.com',\n     *     password: 'example-password',\n     *     options: {\n     *       emailRedirectTo: 'https://example.com/welcome'\n     *     }\n     *   }\n     * )\n     * ```\n     */\n    async signUp(credentials) {\n        var _a, _b, _c;\n        let flowId = null;\n        try {\n            let res;\n            if ('email' in credentials) {\n                const { email, password, options } = credentials;\n                let codeChallenge = null;\n                let codeChallengeMethod = null;\n                if (this.flowType === 'pkce') {\n                    ;\n                    [codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod();\n                }\n                res = await _request(this.fetch, 'POST', `${this.url}/signup`, {\n                    headers: this.headers,\n                    redirectTo: this._maybeAppendFlowIdToRedirect(options === null || options === void 0 ? void 0 : options.emailRedirectTo, flowId),\n                    body: {\n                        email,\n                        password,\n                        data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {},\n                        gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },\n                        code_challenge: codeChallenge,\n                        code_challenge_method: codeChallengeMethod,\n                    },\n                    xform: _sessionResponse,\n                });\n            }\n            else if ('phone' in credentials) {\n                const { phone, password, options } = credentials;\n                res = await _request(this.fetch, 'POST', `${this.url}/signup`, {\n                    headers: this.headers,\n                    body: {\n                        phone,\n                        password,\n                        data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {},\n                        channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms',\n                        gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },\n                    },\n                    xform: _sessionResponse,\n                });\n            }\n            else {\n                throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password');\n            }\n            const { data, error } = res;\n            if (error || !data) {\n                await removePKCEVerifier(this.storage, this.storageKey, flowId);\n                return this._returnResult({ data: { user: null, session: null }, error: error });\n            }\n            const session = data.session;\n            const user = data.user;\n            if (data.session) {\n                await this._saveSession(data.session);\n                await this._notifyAllSubscribers('SIGNED_IN', session);\n            }\n            return this._returnResult({ data: { user, session }, error: null });\n        }\n        catch (error) {\n            await removePKCEVerifier(this.storage, this.storageKey, flowId);\n            if (isAuthError(error)) {\n                return this._returnResult({ data: { user: null, session: null }, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Log in an existing user with an email and password or phone and password.\n     *\n     * Be aware that you may get back an error message that will not distinguish\n     * between the cases where the account does not exist or that the\n     * email/phone and password combination is wrong or that the account can only\n     * be accessed via social login.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - Requires either an email and password or a phone number and password.\n     *\n     * @example Sign in with email and password\n     * ```js\n     * const { data, error } = await supabase.auth.signInWithPassword({\n     *   email: 'example@email.com',\n     *   password: 'example-password',\n     * })\n     * ```\n     *\n     * @exampleResponse Sign in with email and password\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"user\": {\n     *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *       \"aud\": \"authenticated\",\n     *       \"role\": \"authenticated\",\n     *       \"email\": \"example@email.com\",\n     *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *       \"phone\": \"\",\n     *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *       \"app_metadata\": {\n     *         \"provider\": \"email\",\n     *         \"providers\": [\n     *           \"email\"\n     *         ]\n     *       },\n     *       \"user_metadata\": {},\n     *       \"identities\": [\n     *         {\n     *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"identity_data\": {\n     *             \"email\": \"example@email.com\",\n     *             \"email_verified\": false,\n     *             \"phone_verified\": false,\n     *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *           },\n     *           \"provider\": \"email\",\n     *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *           \"created_at\": \"2024-01-01T00:00:00Z\",\n     *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *           \"email\": \"example@email.com\"\n     *         }\n     *       ],\n     *       \"created_at\": \"2024-01-01T00:00:00Z\",\n     *       \"updated_at\": \"2024-01-01T00:00:00Z\"\n     *     },\n     *     \"session\": {\n     *       \"access_token\": \"<ACCESS_TOKEN>\",\n     *       \"token_type\": \"bearer\",\n     *       \"expires_in\": 3600,\n     *       \"expires_at\": 1700000000,\n     *       \"refresh_token\": \"<REFRESH_TOKEN>\",\n     *       \"user\": {\n     *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *         \"aud\": \"authenticated\",\n     *         \"role\": \"authenticated\",\n     *         \"email\": \"example@email.com\",\n     *         \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *         \"phone\": \"\",\n     *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *         \"app_metadata\": {\n     *           \"provider\": \"email\",\n     *           \"providers\": [\n     *             \"email\"\n     *           ]\n     *         },\n     *         \"user_metadata\": {},\n     *         \"identities\": [\n     *           {\n     *             \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *             \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *             \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *             \"identity_data\": {\n     *               \"email\": \"example@email.com\",\n     *               \"email_verified\": false,\n     *               \"phone_verified\": false,\n     *               \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *             },\n     *             \"provider\": \"email\",\n     *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *             \"created_at\": \"2024-01-01T00:00:00Z\",\n     *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *             \"email\": \"example@email.com\"\n     *           }\n     *         ],\n     *         \"created_at\": \"2024-01-01T00:00:00Z\",\n     *         \"updated_at\": \"2024-01-01T00:00:00Z\"\n     *       }\n     *     }\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     *\n     * @example Sign in with phone and password\n     * ```js\n     * const { data, error } = await supabase.auth.signInWithPassword({\n     *   phone: '+13334445555',\n     *   password: 'some-password',\n     * })\n     * ```\n     *\n     * @exampleDescription Handling errors\n     * Log the full `error` object so fields like `code`, `status`, and `name` aren't hidden. The `error.code` (e.g. `'invalid_credentials'`, `'email_not_confirmed'`) is often more useful for branching than `error.message`, and the full object surfaces both.\n     *\n     * @example Handling errors\n     * ```js\n     * const { data, error } = await supabase.auth.signInWithPassword({\n     *   email: 'example@email.com',\n     *   password: 'example-password',\n     * })\n     * if (error) {\n     *   console.error(error)\n     *   return\n     * }\n     * ```\n     */\n    async signInWithPassword(credentials) {\n        try {\n            let res;\n            if ('email' in credentials) {\n                const { email, password, options } = credentials;\n                res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {\n                    headers: this.headers,\n                    body: {\n                        email,\n                        password,\n                        gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },\n                    },\n                    xform: _sessionResponsePassword,\n                });\n            }\n            else if ('phone' in credentials) {\n                const { phone, password, options } = credentials;\n                res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {\n                    headers: this.headers,\n                    body: {\n                        phone,\n                        password,\n                        gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },\n                    },\n                    xform: _sessionResponsePassword,\n                });\n            }\n            else {\n                throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password');\n            }\n            const { data, error } = res;\n            if (error) {\n                return this._returnResult({ data: { user: null, session: null }, error });\n            }\n            else if (!data || !data.session || !data.user) {\n                const invalidTokenError = new AuthInvalidTokenResponseError();\n                return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError });\n            }\n            if (data.session) {\n                await this._saveSession(data.session);\n                await this._notifyAllSubscribers('SIGNED_IN', data.session);\n            }\n            return this._returnResult({\n                data: Object.assign({ user: data.user, session: data.session }, (data.weak_password ? { weakPassword: data.weak_password } : null)),\n                error,\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: { user: null, session: null }, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Log in an existing user via a third-party provider.\n     * This method supports the PKCE flow.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - This method is used for signing in using [Social Login (OAuth) providers](/docs/guides/auth#configure-third-party-providers).\n     * - It works by redirecting your application to the provider's authorization screen, before bringing back the user to your app.\n     *\n     * @example Sign in using a third-party provider\n     * ```js\n     * const { data, error } = await supabase.auth.signInWithOAuth({\n     *   provider: 'github'\n     * })\n     * ```\n     *\n     * @exampleResponse Sign in using a third-party provider\n     * ```json\n     * {\n     *   data: {\n     *     provider: 'github',\n     *     url: <PROVIDER_URL_TO_REDIRECT_TO>,\n     *     flowId: <PKCE_FLOW_ID_OR_NULL>\n     *   },\n     *   error: null\n     * }\n     * ```\n     *\n     * @exampleDescription Sign in using a third-party provider with redirect\n     * - When the OAuth provider successfully authenticates the user, they are redirected to the URL specified in the `redirectTo` parameter. This parameter defaults to the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls). It does not redirect the user immediately after invoking this method.\n     * - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project.\n     *\n     * @example Sign in using a third-party provider with redirect\n     * ```js\n     * const { data, error } = await supabase.auth.signInWithOAuth({\n     *   provider: 'github',\n     *   options: {\n     *     redirectTo: 'https://example.com/welcome'\n     *   }\n     * })\n     * ```\n     *\n     * @exampleDescription Sign in with scopes and access provider tokens\n     * If you need additional access from an OAuth provider, in order to access provider specific APIs in the name of the user, you can do this by passing in the scopes the user should authorize for your application. Note that the `scopes` option takes in **a space-separated list** of scopes.\n     *\n     * Because OAuth sign-in often includes redirects, you should register an `onAuthStateChange` callback immediately after you create the Supabase client. This callback will listen for the presence of `provider_token` and `provider_refresh_token` properties on the `session` object and store them in local storage. The client library will emit these values **only once** immediately after the user signs in. You can then access them by looking them up in local storage, or send them to your backend servers for further processing.\n     *\n     * Finally, make sure you remove them from local storage on the `SIGNED_OUT` event. If the OAuth provider supports token revocation, make sure you call those APIs either from the frontend or schedule them to be called on the backend.\n     *\n     * @example Sign in with scopes and access provider tokens\n     * ```js\n     * // Register this immediately after calling createClient!\n     * // Because signInWithOAuth causes a redirect, you need to fetch the\n     * // provider tokens from the callback.\n     * supabase.auth.onAuthStateChange((event, session) => {\n     *   if (session && session.provider_token) {\n     *     window.localStorage.setItem('oauth_provider_token', session.provider_token)\n     *   }\n     *\n     *   if (session && session.provider_refresh_token) {\n     *     window.localStorage.setItem('oauth_provider_refresh_token', session.provider_refresh_token)\n     *   }\n     *\n     *   if (event === 'SIGNED_OUT') {\n     *     window.localStorage.removeItem('oauth_provider_token')\n     *     window.localStorage.removeItem('oauth_provider_refresh_token')\n     *   }\n     * })\n     *\n     * // Call this on your Sign in with GitHub button to initiate OAuth\n     * // with GitHub with the requested elevated scopes.\n     * await supabase.auth.signInWithOAuth({\n     *   provider: 'github',\n     *   options: {\n     *     scopes: 'repo gist notifications'\n     *   }\n     * })\n     * ```\n     */\n    async signInWithOAuth(credentials) {\n        var _a, _b, _c, _d;\n        return await this._handleProviderSignIn(credentials.provider, {\n            redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo,\n            scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes,\n            queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams,\n            skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect,\n        });\n    }\n    /**\n     * Log in an existing user by exchanging an Auth Code issued during the PKCE flow.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - Used when `flowType` is set to `pkce` in client options.\n     * - When several PKCE flows are in flight at once, pass `options.flowId` so\n     *   the code is exchanged with the verifier created by that specific flow.\n     *   The flow id is returned by `signInWithOAuth`, and with\n     *   `experimental.appendPkceFlowIdToRedirects` enabled it also arrives on\n     *   your callback URL as the reserved `sb_flow_id` query parameter (read\n     *   automatically in a browser).\n     * - When a flow id is present but its stored verifier is gone (evicted,\n     *   already used, or from another device), the call fails with a verifier\n     *   missing error instead of trying another flow's verifier — a mismatched\n     *   verifier would consume the single-use code. Without any flow id the\n     *   most recently stored verifier is used, as before.\n     *\n     * @example Exchange Auth Code\n     * ```js\n     * supabase.auth.exchangeCodeForSession('34e770dd-9ff9-416c-87fa-43b31d7ef225')\n     * ```\n     *\n     * @example Exchange Auth Code for a specific flow (e.g. in a server-side callback handler)\n     * ```js\n     * const flowId = requestUrl.searchParams.get('sb_flow_id')\n     * supabase.auth.exchangeCodeForSession(code, flowId ? { flowId } : undefined)\n     * ```\n     *\n     * @exampleResponse Exchange Auth Code\n     * ```json\n     * {\n     *   \"data\": {\n     *     session: {\n     *       access_token: '<ACCESS_TOKEN>',\n     *       token_type: 'bearer',\n     *       expires_in: 3600,\n     *       expires_at: 1700000000,\n     *       refresh_token: '<REFRESH_TOKEN>',\n     *       user: {\n     *         id: '11111111-1111-1111-1111-111111111111',\n     *         aud: 'authenticated',\n     *         role: 'authenticated',\n     *         email: 'example@email.com'\n     *         email_confirmed_at: '2024-01-01T00:00:00Z',\n     *         phone: '',\n     *         confirmation_sent_at: '2024-01-01T00:00:00Z',\n     *         confirmed_at: '2024-01-01T00:00:00Z',\n     *         last_sign_in_at: '2024-01-01T00:00:00Z',\n     *         app_metadata: {\n     *           \"provider\": \"email\",\n     *           \"providers\": [\n     *             \"email\",\n     *             \"<OTHER_PROVIDER>\"\n     *           ]\n     *         },\n     *         user_metadata: {\n     *           email: 'email@email.com',\n     *           email_verified: true,\n     *           full_name: 'User Name',\n     *           iss: '<ISS>',\n     *           name: 'User Name',\n     *           phone_verified: false,\n     *           provider_id: '<PROVIDER_ID>',\n     *           sub: '<SUB>'\n     *         },\n     *         identities: [\n     *           {\n     *             \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *             \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *             \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *             \"identity_data\": {\n     *               \"email\": \"example@email.com\",\n     *               \"email_verified\": false,\n     *               \"phone_verified\": false,\n     *               \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *             },\n     *             \"provider\": \"email\",\n     *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *             \"created_at\": \"2024-01-01T00:00:00Z\",\n     *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *             \"email\": \"email@example.com\"\n     *           },\n     *           {\n     *             \"identity_id\": \"33333333-3333-3333-3333-333333333333\",\n     *             \"id\": \"<ID>\",\n     *             \"user_id\": \"<USER_ID>\",\n     *             \"identity_data\": {\n     *               \"email\": \"example@email.com\",\n     *               \"email_verified\": true,\n     *               \"full_name\": \"User Name\",\n     *               \"iss\": \"<ISS>\",\n     *               \"name\": \"User Name\",\n     *               \"phone_verified\": false,\n     *               \"provider_id\": \"<PROVIDER_ID>\",\n     *               \"sub\": \"<SUB>\"\n     *             },\n     *             \"provider\": \"<PROVIDER>\",\n     *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *             \"created_at\": \"2024-01-01T00:00:00Z\",\n     *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *             \"email\": \"example@email.com\"\n     *           }\n     *         ],\n     *         created_at: '2024-01-01T00:00:00Z',\n     *         updated_at: '2024-01-01T00:00:00Z',\n     *         is_anonymous: false\n     *       },\n     *       provider_token: '<PROVIDER_TOKEN>',\n     *       provider_refresh_token: '<PROVIDER_REFRESH_TOKEN>'\n     *     },\n     *     user: {\n     *       id: '11111111-1111-1111-1111-111111111111',\n     *       aud: 'authenticated',\n     *       role: 'authenticated',\n     *       email: 'example@email.com',\n     *       email_confirmed_at: '2024-01-01T00:00:00Z',\n     *       phone: '',\n     *       confirmation_sent_at: '2024-01-01T00:00:00Z',\n     *       confirmed_at: '2024-01-01T00:00:00Z',\n     *       last_sign_in_at: '2024-01-01T00:00:00Z',\n     *       app_metadata: {\n     *         provider: 'email',\n     *         providers: [\n     *           \"email\",\n     *           \"<OTHER_PROVIDER>\"\n     *         ]\n     *       },\n     *       user_metadata: {\n     *         email: 'email@email.com',\n     *         email_verified: true,\n     *         full_name: 'User Name',\n     *         iss: '<ISS>',\n     *         name: 'User Name',\n     *         phone_verified: false,\n     *         provider_id: '<PROVIDER_ID>',\n     *         sub: '<SUB>'\n     *       },\n     *       identities: [\n     *         {\n     *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"identity_data\": {\n     *             \"email\": \"example@email.com\",\n     *             \"email_verified\": false,\n     *             \"phone_verified\": false,\n     *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *           },\n     *           \"provider\": \"email\",\n     *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *           \"created_at\": \"2024-01-01T00:00:00Z\",\n     *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *           \"email\": \"email@example.com\"\n     *         },\n     *         {\n     *           \"identity_id\": \"33333333-3333-3333-3333-333333333333\",\n     *           \"id\": \"<ID>\",\n     *           \"user_id\": \"<USER_ID>\",\n     *           \"identity_data\": {\n     *             \"email\": \"example@email.com\",\n     *             \"email_verified\": true,\n     *             \"full_name\": \"User Name\",\n     *             \"iss\": \"<ISS>\",\n     *             \"name\": \"User Name\",\n     *             \"phone_verified\": false,\n     *             \"provider_id\": \"<PROVIDER_ID>\",\n     *             \"sub\": \"<SUB>\"\n     *           },\n     *           \"provider\": \"<PROVIDER>\",\n     *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *           \"created_at\": \"2024-01-01T00:00:00Z\",\n     *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *           \"email\": \"example@email.com\"\n     *         }\n     *       ],\n     *       created_at: '2024-01-01T00:00:00Z',\n     *       updated_at: '2024-01-01T00:00:00Z',\n     *       is_anonymous: false\n     *     },\n     *     redirectType: null\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     */\n    async exchangeCodeForSession(authCode, options) {\n        await this.initializePromise;\n        if (this.lock != null) {\n            // TODO(v3): remove legacy lock path\n            return this._acquireLock(this.lockAcquireTimeout, async () => {\n                return this._exchangeCodeForSession(authCode, options);\n            });\n        }\n        return this._exchangeCodeForSession(authCode, options);\n    }\n    /**\n     * Signs in a user by verifying a message signed by the user's private key.\n     * Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards,\n     * both of which derive from the EIP-4361 standard\n     * With slight variation on Solana's side.\n     * @reference https://eips.ethereum.org/EIPS/eip-4361\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - Uses a Web3 (Ethereum, Solana) wallet to sign a user in.\n     * - Read up on the [potential for abuse](/docs/guides/auth/auth-web3#potential-for-abuse) before using it.\n     *\n     * @example Sign in with Solana or Ethereum (Window API)\n     * ```js\n     *   // uses window.ethereum for the wallet\n     *   const { data, error } = await supabase.auth.signInWithWeb3({\n     *     chain: 'ethereum',\n     *     statement: 'I accept the Terms of Service at https://example.com/tos'\n     *   })\n     *\n     *   // uses window.solana for the wallet\n     *   const { data, error } = await supabase.auth.signInWithWeb3({\n     *     chain: 'solana',\n     *     statement: 'I accept the Terms of Service at https://example.com/tos'\n     *   })\n     * ```\n     *\n     * @example Sign in with Ethereum (Message and Signature)\n     * ```js\n     *   const { data, error } = await supabase.auth.signInWithWeb3({\n     *     chain: 'ethereum',\n     *     message: '<sign in with ethereum message>',\n     *     signature: '<hex of the ethereum signature over the message>',\n     *   })\n     * ```\n     *\n     * @example Sign in with Solana (Brave)\n     * ```js\n     *   const { data, error } = await supabase.auth.signInWithWeb3({\n     *     chain: 'solana',\n     *     statement: 'I accept the Terms of Service at https://example.com/tos',\n     *     wallet: window.braveSolana\n     *   })\n     * ```\n     *\n     * @example Sign in with Solana (Wallet Adapter)\n     * ```jsx\n     *   function SignInButton() {\n     *   const wallet = useWallet()\n     *\n     *   return (\n     *     <>\n     *       {wallet.connected ? (\n     *         <button\n     *           onClick={() => {\n     *             supabase.auth.signInWithWeb3({\n     *               chain: 'solana',\n     *               statement: 'I accept the Terms of Service at https://example.com/tos',\n     *               wallet,\n     *             })\n     *           }}\n     *         >\n     *           Sign in with Solana\n     *         </button>\n     *       ) : (\n     *         <WalletMultiButton />\n     *       )}\n     *     </>\n     *   )\n     * }\n     *\n     * function App() {\n     *   const endpoint = clusterApiUrl('devnet')\n     *   const wallets = useMemo(() => [], [])\n     *\n     *   return (\n     *     <ConnectionProvider endpoint={endpoint}>\n     *       <WalletProvider wallets={wallets}>\n     *         <WalletModalProvider>\n     *           <SignInButton />\n     *         </WalletModalProvider>\n     *       </WalletProvider>\n     *     </ConnectionProvider>\n     *   )\n     * }\n     * ```\n     */\n    async signInWithWeb3(credentials) {\n        const { chain } = credentials;\n        switch (chain) {\n            case 'ethereum':\n                return await this.signInWithEthereum(credentials);\n            case 'solana':\n                return await this.signInWithSolana(credentials);\n            default:\n                throw new Error(`@supabase/auth-js: Unsupported chain \"${chain}\"`);\n        }\n    }\n    async signInWithEthereum(credentials) {\n        var _a, _b, _c, _d, _f, _g, _h, _j, _k, _l, _m;\n        // TODO: flatten type\n        let message;\n        let signature;\n        if ('message' in credentials) {\n            message = credentials.message;\n            signature = credentials.signature;\n        }\n        else {\n            const { chain, wallet, statement, options } = credentials;\n            let resolvedWallet;\n            if (!isBrowser()) {\n                if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) {\n                    throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.');\n                }\n                resolvedWallet = wallet;\n            }\n            else if (typeof wallet === 'object') {\n                resolvedWallet = wallet;\n            }\n            else {\n                const windowAny = window;\n                if ('ethereum' in windowAny &&\n                    typeof windowAny.ethereum === 'object' &&\n                    'request' in windowAny.ethereum &&\n                    typeof windowAny.ethereum.request === 'function') {\n                    resolvedWallet = windowAny.ethereum;\n                }\n                else {\n                    throw new Error(`@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`);\n                }\n            }\n            const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href);\n            const accounts = await resolvedWallet\n                .request({\n                method: 'eth_requestAccounts',\n            })\n                .then((accs) => accs)\n                .catch(() => {\n                throw new Error(`@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`);\n            });\n            if (!accounts || accounts.length === 0) {\n                throw new Error(`@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`);\n            }\n            const address = getAddress(accounts[0]);\n            let chainId = (_b = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _b === void 0 ? void 0 : _b.chainId;\n            if (!chainId) {\n                const chainIdHex = await resolvedWallet.request({\n                    method: 'eth_chainId',\n                });\n                chainId = fromHex(chainIdHex);\n            }\n            const siweMessage = {\n                domain: url.host,\n                address: address,\n                statement: statement,\n                uri: url.href,\n                version: '1',\n                chainId: chainId,\n                nonce: (_c = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _c === void 0 ? void 0 : _c.nonce,\n                issuedAt: (_f = (_d = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _d === void 0 ? void 0 : _d.issuedAt) !== null && _f !== void 0 ? _f : new Date(),\n                expirationTime: (_g = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _g === void 0 ? void 0 : _g.expirationTime,\n                notBefore: (_h = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _h === void 0 ? void 0 : _h.notBefore,\n                requestId: (_j = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _j === void 0 ? void 0 : _j.requestId,\n                resources: (_k = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _k === void 0 ? void 0 : _k.resources,\n            };\n            message = createSiweMessage(siweMessage);\n            // Sign message\n            signature = (await resolvedWallet.request({\n                method: 'personal_sign',\n                params: [toHex(message), address],\n            }));\n        }\n        try {\n            const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, {\n                headers: this.headers,\n                body: Object.assign({ chain: 'ethereum', message,\n                    signature }, (((_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken)\n                    ? { gotrue_meta_security: { captcha_token: (_m = credentials.options) === null || _m === void 0 ? void 0 : _m.captchaToken } }\n                    : null)),\n                xform: _sessionResponse,\n            });\n            if (error) {\n                throw error;\n            }\n            if (!data || !data.session || !data.user) {\n                const invalidTokenError = new AuthInvalidTokenResponseError();\n                return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError });\n            }\n            if (data.session) {\n                await this._saveSession(data.session);\n                await this._notifyAllSubscribers('SIGNED_IN', data.session);\n            }\n            return this._returnResult({ data: Object.assign({}, data), error });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: { user: null, session: null }, error });\n            }\n            throw error;\n        }\n    }\n    async signInWithSolana(credentials) {\n        var _a, _b, _c, _d, _f, _g, _h, _j, _k, _l, _m, _o;\n        let message;\n        let signature;\n        if ('message' in credentials) {\n            message = credentials.message;\n            signature = credentials.signature;\n        }\n        else {\n            const { chain, wallet, statement, options } = credentials;\n            let resolvedWallet;\n            if (!isBrowser()) {\n                if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) {\n                    throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.');\n                }\n                resolvedWallet = wallet;\n            }\n            else if (typeof wallet === 'object') {\n                resolvedWallet = wallet;\n            }\n            else {\n                const windowAny = window;\n                if ('solana' in windowAny &&\n                    typeof windowAny.solana === 'object' &&\n                    (('signIn' in windowAny.solana && typeof windowAny.solana.signIn === 'function') ||\n                        ('signMessage' in windowAny.solana &&\n                            typeof windowAny.solana.signMessage === 'function'))) {\n                    resolvedWallet = windowAny.solana;\n                }\n                else {\n                    throw new Error(`@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`);\n                }\n            }\n            const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href);\n            if ('signIn' in resolvedWallet && resolvedWallet.signIn) {\n                const output = await resolvedWallet.signIn(Object.assign(Object.assign(Object.assign({ issuedAt: new Date().toISOString() }, options === null || options === void 0 ? void 0 : options.signInWithSolana), { \n                    // non-overridable properties\n                    version: '1', domain: url.host, uri: url.href }), (statement ? { statement } : null)));\n                let outputToProcess;\n                if (Array.isArray(output) && output[0] && typeof output[0] === 'object') {\n                    outputToProcess = output[0];\n                }\n                else if (output &&\n                    typeof output === 'object' &&\n                    'signedMessage' in output &&\n                    'signature' in output) {\n                    outputToProcess = output;\n                }\n                else {\n                    throw new Error('@supabase/auth-js: Wallet method signIn() returned unrecognized value');\n                }\n                if ('signedMessage' in outputToProcess &&\n                    'signature' in outputToProcess &&\n                    (typeof outputToProcess.signedMessage === 'string' ||\n                        outputToProcess.signedMessage instanceof Uint8Array) &&\n                    outputToProcess.signature instanceof Uint8Array) {\n                    message =\n                        typeof outputToProcess.signedMessage === 'string'\n                            ? outputToProcess.signedMessage\n                            : new TextDecoder().decode(outputToProcess.signedMessage);\n                    signature = outputToProcess.signature;\n                }\n                else {\n                    throw new Error('@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields');\n                }\n            }\n            else {\n                if (!('signMessage' in resolvedWallet) ||\n                    typeof resolvedWallet.signMessage !== 'function' ||\n                    !('publicKey' in resolvedWallet) ||\n                    typeof resolvedWallet !== 'object' ||\n                    !resolvedWallet.publicKey ||\n                    !('toBase58' in resolvedWallet.publicKey) ||\n                    typeof resolvedWallet.publicKey.toBase58 !== 'function') {\n                    throw new Error('@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API');\n                }\n                message = [\n                    `${url.host} wants you to sign in with your Solana account:`,\n                    resolvedWallet.publicKey.toBase58(),\n                    ...(statement ? ['', statement, ''] : ['']),\n                    'Version: 1',\n                    `URI: ${url.href}`,\n                    `Issued At: ${(_c = (_b = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _b === void 0 ? void 0 : _b.issuedAt) !== null && _c !== void 0 ? _c : new Date().toISOString()}`,\n                    ...(((_d = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _d === void 0 ? void 0 : _d.notBefore)\n                        ? [`Not Before: ${options.signInWithSolana.notBefore}`]\n                        : []),\n                    ...(((_f = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _f === void 0 ? void 0 : _f.expirationTime)\n                        ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`]\n                        : []),\n                    ...(((_g = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _g === void 0 ? void 0 : _g.chainId)\n                        ? [`Chain ID: ${options.signInWithSolana.chainId}`]\n                        : []),\n                    ...(((_h = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _h === void 0 ? void 0 : _h.nonce) ? [`Nonce: ${options.signInWithSolana.nonce}`] : []),\n                    ...(((_j = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _j === void 0 ? void 0 : _j.requestId)\n                        ? [`Request ID: ${options.signInWithSolana.requestId}`]\n                        : []),\n                    ...(((_l = (_k = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _k === void 0 ? void 0 : _k.resources) === null || _l === void 0 ? void 0 : _l.length)\n                        ? [\n                            'Resources',\n                            ...options.signInWithSolana.resources.map((resource) => `- ${resource}`),\n                        ]\n                        : []),\n                ].join('\\n');\n                const maybeSignature = await resolvedWallet.signMessage(new TextEncoder().encode(message), 'utf8');\n                if (!maybeSignature || !(maybeSignature instanceof Uint8Array)) {\n                    throw new Error('@supabase/auth-js: Wallet signMessage() API returned an recognized value');\n                }\n                signature = maybeSignature;\n            }\n        }\n        try {\n            const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, {\n                headers: this.headers,\n                body: Object.assign({ chain: 'solana', message, signature: bytesToBase64URL(signature) }, (((_m = credentials.options) === null || _m === void 0 ? void 0 : _m.captchaToken)\n                    ? { gotrue_meta_security: { captcha_token: (_o = credentials.options) === null || _o === void 0 ? void 0 : _o.captchaToken } }\n                    : null)),\n                xform: _sessionResponse,\n            });\n            if (error) {\n                throw error;\n            }\n            if (!data || !data.session || !data.user) {\n                const invalidTokenError = new AuthInvalidTokenResponseError();\n                return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError });\n            }\n            if (data.session) {\n                await this._saveSession(data.session);\n                await this._notifyAllSubscribers('SIGNED_IN', data.session);\n            }\n            return this._returnResult({ data: Object.assign({}, data), error });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: { user: null, session: null }, error });\n            }\n            throw error;\n        }\n    }\n    async _exchangeCodeForSession(authCode, options) {\n        const hasExplicitFlowId = (options === null || options === void 0 ? void 0 : options.flowId) != null;\n        const requestedFlowId = hasExplicitFlowId\n            ? validatePKCEFlowId(options === null || options === void 0 ? void 0 : options.flowId)\n            : isBrowser()\n                ? validatePKCEFlowId(parseParametersFromURL(window.location.href)[PKCE_FLOW_ID_PARAM])\n                : null;\n        if (hasExplicitFlowId && !requestedFlowId) {\n            this._debug('#_exchangeCodeForSession()', 'provided flowId is not a valid flow id', options === null || options === void 0 ? void 0 : options.flowId);\n        }\n        // With a flow id (explicit or from the callback URL) the lookup is\n        // slot-only and a miss fails fast — see retrievePKCEVerifier. An invalid\n        // explicit flow id also fails fast rather than borrowing another flow's\n        // verifier.\n        const { verifier: storageItem, flowId } = hasExplicitFlowId && !requestedFlowId\n            ? { verifier: null, flowId: null }\n            : await retrievePKCEVerifier(this.storage, this.storageKey, requestedFlowId);\n        const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : '').split('/');\n        try {\n            if (!codeVerifier && this.flowType === 'pkce') {\n                throw new AuthPKCECodeVerifierMissingError();\n            }\n            const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=pkce`, {\n                headers: this.headers,\n                body: {\n                    auth_code: authCode,\n                    code_verifier: codeVerifier,\n                },\n                xform: _sessionResponse,\n            });\n            await removePKCEVerifier(this.storage, this.storageKey, flowId);\n            if (error) {\n                throw error;\n            }\n            if (!data || !data.session || !data.user) {\n                const invalidTokenError = new AuthInvalidTokenResponseError();\n                return this._returnResult({\n                    data: { user: null, session: null, redirectType: null },\n                    error: invalidTokenError,\n                });\n            }\n            if (data.session) {\n                await this._saveSession(data.session);\n                await this._notifyAllSubscribers(redirectType === 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN', data.session);\n            }\n            return this._returnResult({ data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error });\n        }\n        catch (error) {\n            await removePKCEVerifier(this.storage, this.storageKey, flowId);\n            if (isAuthError(error)) {\n                return this._returnResult({\n                    data: { user: null, session: null, redirectType: null },\n                    error,\n                });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Allows signing in with an OIDC ID token. The authentication provider used\n     * should be enabled and configured.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - Use an ID token to sign in.\n     * - Especially useful when implementing sign in using native platform dialogs in mobile or desktop apps using Sign in with Apple or Sign in with Google on iOS and Android.\n     * - You can also use Google's [One Tap](https://developers.google.com/identity/gsi/web/guides/display-google-one-tap) and [Automatic sign-in](https://developers.google.com/identity/gsi/web/guides/automatic-sign-in-sign-out) via this API.\n     *\n     * @example Sign In using ID Token\n     * ```js\n     * const { data, error } = await supabase.auth.signInWithIdToken({\n     *   provider: 'google',\n     *   token: 'your-id-token'\n     * })\n     * ```\n     *\n     * @exampleResponse Sign In using ID Token\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"user\": {\n     *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *       \"aud\": \"authenticated\",\n     *       \"role\": \"authenticated\",\n     *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *       \"app_metadata\": {\n     *         ...\n     *       },\n     *       \"user_metadata\": {\n     *         ...\n     *       },\n     *       \"identities\": [\n     *         {\n     *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *           \"provider\": \"google\",\n     *         }\n     *       ],\n     *       \"created_at\": \"2024-01-01T00:00:00Z\",\n     *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *     },\n     *     \"session\": {\n     *       \"access_token\": \"<ACCESS_TOKEN>\",\n     *       \"token_type\": \"bearer\",\n     *       \"expires_in\": 3600,\n     *       \"expires_at\": 1700000000,\n     *       \"refresh_token\": \"<REFRESH_TOKEN>\",\n     *       \"user\": {\n     *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *         \"aud\": \"authenticated\",\n     *         \"role\": \"authenticated\",\n     *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *         \"app_metadata\": {\n     *           ...\n     *         },\n     *         \"user_metadata\": {\n     *           ...\n     *         },\n     *         \"identities\": [\n     *           {\n     *             \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *             \"provider\": \"google\",\n     *           }\n     *         ],\n     *         \"created_at\": \"2024-01-01T00:00:00Z\",\n     *         \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *       }\n     *     }\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     */\n    async signInWithIdToken(credentials) {\n        try {\n            const { options, provider, token, access_token, nonce } = credentials;\n            const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, {\n                headers: this.headers,\n                body: {\n                    provider,\n                    id_token: token,\n                    access_token,\n                    nonce,\n                    gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },\n                },\n                xform: _sessionResponse,\n            });\n            const { data, error } = res;\n            if (error) {\n                return this._returnResult({ data: { user: null, session: null }, error });\n            }\n            else if (!data || !data.session || !data.user) {\n                const invalidTokenError = new AuthInvalidTokenResponseError();\n                return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError });\n            }\n            if (data.session) {\n                await this._saveSession(data.session);\n                await this._notifyAllSubscribers('SIGNED_IN', data.session);\n            }\n            return this._returnResult({ data, error });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: { user: null, session: null }, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Log in a user using magiclink or a one-time password (OTP).\n     *\n     * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent.\n     * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent.\n     * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.\n     *\n     * Be aware that you may get back an error message that will not distinguish\n     * between the cases where the account does not exist or, that the account\n     * can only be accessed via social login.\n     *\n     * Do note that you will need to configure a Whatsapp sender on Twilio\n     * if you are using phone sign in with the 'whatsapp' channel. The whatsapp\n     * channel is not supported on other providers\n     * at this time.\n     * This method supports PKCE when an email is passed.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - Requires either an email or phone number.\n     * - This method is used for passwordless sign-ins where a OTP is sent to the user's email or phone number.\n     * - If the user doesn't exist, `signInWithOtp()` will signup the user instead. To restrict this behavior, you can set `shouldCreateUser` in `SignInWithPasswordlessCredentials.options` to `false`.\n     * - If you're using an email, you can configure whether you want the user to receive a magiclink or a OTP.\n     * - If you're using phone, you can configure whether you want the user to receive a OTP.\n     * - The magic link's destination URL is determined by the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls).\n     * - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project.\n     * - Magic links and OTPs share the same implementation. To send users a one-time code instead of a magic link, [modify the magic link email template](/dashboard/project/_/auth/templates) to include `{{ .Token }}` instead of `{{ .ConfirmationURL }}`.\n     * - See our [Twilio Phone Auth Guide](/docs/guides/auth/phone-login?showSMSProvider=Twilio) for details about configuring WhatsApp sign in.\n     *\n     * @exampleDescription Sign in with email\n     * The user will be sent an email which contains either a magiclink or a OTP or both. By default, a given user can only request a OTP once every 60 seconds.\n     *\n     * @example Sign in with email\n     * ```js\n     * const { data, error } = await supabase.auth.signInWithOtp({\n     *   email: 'example@email.com',\n     *   options: {\n     *     emailRedirectTo: 'https://example.com/welcome'\n     *   }\n     * })\n     * ```\n     *\n     * @exampleResponse Sign in with email\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"user\": null,\n     *     \"session\": null\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     *\n     * @exampleDescription Sign in with SMS OTP\n     * The user will be sent a SMS which contains a OTP. By default, a given user can only request a OTP once every 60 seconds.\n     *\n     * @example Sign in with SMS OTP\n     * ```js\n     * const { data, error } = await supabase.auth.signInWithOtp({\n     *   phone: '+13334445555',\n     * })\n     * ```\n     *\n     * @exampleDescription Sign in with WhatsApp OTP\n     * The user will be sent a WhatsApp message which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. Note that a user will need to have a valid WhatsApp account that is linked to Twilio in order to use this feature.\n     *\n     * @example Sign in with WhatsApp OTP\n     * ```js\n     * const { data, error } = await supabase.auth.signInWithOtp({\n     *   phone: '+13334445555',\n     *   options: {\n     *     channel:'whatsapp',\n     *   }\n     * })\n     * ```\n     */\n    async signInWithOtp(credentials) {\n        var _a, _b, _c, _d, _f;\n        let flowId = null;\n        try {\n            if ('email' in credentials) {\n                const { email, options } = credentials;\n                let codeChallenge = null;\n                let codeChallengeMethod = null;\n                if (this.flowType === 'pkce') {\n                    ;\n                    [codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod();\n                }\n                const { error } = await _request(this.fetch, 'POST', `${this.url}/otp`, {\n                    headers: this.headers,\n                    body: {\n                        email,\n                        data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {},\n                        create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true,\n                        gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },\n                        code_challenge: codeChallenge,\n                        code_challenge_method: codeChallengeMethod,\n                    },\n                    redirectTo: this._maybeAppendFlowIdToRedirect(options === null || options === void 0 ? void 0 : options.emailRedirectTo, flowId),\n                });\n                return this._returnResult({ data: { user: null, session: null }, error });\n            }\n            if ('phone' in credentials) {\n                const { phone, options } = credentials;\n                const { data, error } = await _request(this.fetch, 'POST', `${this.url}/otp`, {\n                    headers: this.headers,\n                    body: {\n                        phone,\n                        data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {},\n                        create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true,\n                        gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },\n                        channel: (_f = options === null || options === void 0 ? void 0 : options.channel) !== null && _f !== void 0 ? _f : 'sms',\n                    },\n                });\n                return this._returnResult({\n                    data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id },\n                    error,\n                });\n            }\n            throw new AuthInvalidCredentialsError('You must provide either an email or phone number.');\n        }\n        catch (error) {\n            await removePKCEVerifier(this.storage, this.storageKey, flowId);\n            if (isAuthError(error)) {\n                return this._returnResult({ data: { user: null, session: null }, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Log in a user given a User supplied OTP or TokenHash received through mobile or email.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - The `verifyOtp` method takes in different verification types.\n     * - If a phone number is used, the type can either be:\n     *   1. `sms` – Used when verifying a one-time password (OTP) sent via SMS during sign-up or sign-in.\n     *   2. `phone_change` – Used when verifying an OTP sent to a new phone number during a phone number update process.\n     * - If an email address is used, the type can be one of the following (note: `signup` and `magiclink` types are deprecated):\n     *   1. `email` – Used when verifying an OTP sent to the user's email during sign-up or sign-in.\n     *   2. `recovery` – Used when verifying an OTP sent for account recovery, typically after a password reset request.\n     *   3. `invite` – Used when verifying an OTP sent as part of an invitation to join a project or organization.\n     *   4. `email_change` – Used when verifying an OTP sent to a new email address during an email update process.\n     * - The verification type used should be determined based on the corresponding auth method called before `verifyOtp` to sign up / sign-in a user.\n     * - The `TokenHash` is contained in the [email templates](/docs/guides/auth/auth-email-templates) and can be used to sign in.  You may wish to use the hash for the PKCE flow for Server Side Auth. Read [the Password-based Auth guide](/docs/guides/auth/passwords) for more details.\n     *\n     * @example Verify Signup One-Time Password (OTP)\n     * ```js\n     * const { data, error } = await supabase.auth.verifyOtp({ email, token, type: 'email'})\n     * ```\n     *\n     * @exampleResponse Verify Signup One-Time Password (OTP)\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"user\": {\n     *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *       \"aud\": \"authenticated\",\n     *       \"role\": \"authenticated\",\n     *       \"email\": \"example@email.com\",\n     *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *       \"phone\": \"\",\n     *       \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *       \"recovery_sent_at\": \"2024-01-01T00:00:00Z\",\n     *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *       \"app_metadata\": {\n     *         \"provider\": \"email\",\n     *         \"providers\": [\n     *           \"email\"\n     *         ]\n     *       },\n     *       \"user_metadata\": {\n     *         \"email\": \"example@email.com\",\n     *         \"email_verified\": false,\n     *         \"phone_verified\": false,\n     *         \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *       },\n     *       \"identities\": [\n     *         {\n     *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"identity_data\": {\n     *             \"email\": \"example@email.com\",\n     *             \"email_verified\": false,\n     *             \"phone_verified\": false,\n     *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *           },\n     *           \"provider\": \"email\",\n     *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *           \"created_at\": \"2024-01-01T00:00:00Z\",\n     *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *           \"email\": \"example@email.com\"\n     *         }\n     *       ],\n     *       \"created_at\": \"2024-01-01T00:00:00Z\",\n     *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *       \"is_anonymous\": false\n     *     },\n     *     \"session\": {\n     *       \"access_token\": \"<ACCESS_TOKEN>\",\n     *       \"token_type\": \"bearer\",\n     *       \"expires_in\": 3600,\n     *       \"expires_at\": 1700000000,\n     *       \"refresh_token\": \"<REFRESH_TOKEN>\",\n     *       \"user\": {\n     *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *         \"aud\": \"authenticated\",\n     *         \"role\": \"authenticated\",\n     *         \"email\": \"example@email.com\",\n     *         \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *         \"phone\": \"\",\n     *         \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *         \"recovery_sent_at\": \"2024-01-01T00:00:00Z\",\n     *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *         \"app_metadata\": {\n     *           \"provider\": \"email\",\n     *           \"providers\": [\n     *             \"email\"\n     *           ]\n     *         },\n     *         \"user_metadata\": {\n     *           \"email\": \"example@email.com\",\n     *           \"email_verified\": false,\n     *           \"phone_verified\": false,\n     *           \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *         },\n     *         \"identities\": [\n     *           {\n     *             \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *             \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *             \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *             \"identity_data\": {\n     *               \"email\": \"example@email.com\",\n     *               \"email_verified\": false,\n     *               \"phone_verified\": false,\n     *               \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *             },\n     *             \"provider\": \"email\",\n     *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *             \"created_at\": \"2024-01-01T00:00:00Z\",\n     *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *             \"email\": \"example@email.com\"\n     *           }\n     *         ],\n     *         \"created_at\": \"2024-01-01T00:00:00Z\",\n     *         \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *         \"is_anonymous\": false\n     *       }\n     *     }\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     *\n     * @example Verify SMS One-Time Password (OTP)\n     * ```js\n     * const { data, error } = await supabase.auth.verifyOtp({ phone, token, type: 'sms'})\n     * ```\n     *\n     * @example Verify Email Auth (Token Hash)\n     * ```js\n     * const { data, error } = await supabase.auth.verifyOtp({ token_hash: tokenHash, type: 'email'})\n     * ```\n     */\n    async verifyOtp(params) {\n        var _a, _b;\n        try {\n            let redirectTo = undefined;\n            let captchaToken = undefined;\n            if ('options' in params) {\n                redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo;\n                captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken;\n            }\n            const { data, error } = await _request(this.fetch, 'POST', `${this.url}/verify`, {\n                headers: this.headers,\n                body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }),\n                redirectTo,\n                xform: _sessionResponse,\n            });\n            if (error) {\n                throw error;\n            }\n            if (!data) {\n                const tokenVerificationError = new Error('An error occurred on token verification.');\n                throw tokenVerificationError;\n            }\n            const session = data.session;\n            const user = data.user;\n            if (session === null || session === void 0 ? void 0 : session.access_token) {\n                await this._saveSession(session);\n                await this._notifyAllSubscribers(params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN', session);\n            }\n            return this._returnResult({ data: { user, session }, error: null });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: { user: null, session: null }, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Attempts a single-sign on using an enterprise Identity Provider. A\n     * successful SSO attempt will redirect the current page to the identity\n     * provider authorization page. The redirect URL is implementation and SSO\n     * protocol specific.\n     *\n     * You can use it by providing a SSO domain. Typically you can extract this\n     * domain by asking users for their email address. If this domain is\n     * registered on the Auth instance the redirect will use that organization's\n     * currently active SSO Identity Provider for the login.\n     *\n     * If you have built an organization-specific login page, you can use the\n     * organization's SSO Identity Provider UUID directly instead.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - Before you can call this method you need to [establish a connection](/docs/guides/auth/sso/auth-sso-saml#managing-saml-20-connections) to an identity provider. Use the [CLI commands](/docs/reference/cli/supabase-sso) to do this.\n     * - If you've associated an email domain to the identity provider, you can use the `domain` property to start a sign-in flow.\n     * - In case you need to use a different way to start the authentication flow with an identity provider, you can use the `providerId` property. For example:\n     *     - Mapping specific user email addresses with an identity provider.\n     *     - Using different hints to identity the identity provider to be used by the user, like a company-specific page, IP address or other tracking information.\n     *\n     * @example Sign in with email domain\n     * ```js\n     *   // You can extract the user's email domain and use it to trigger the\n     *   // authentication flow with the correct identity provider.\n     *\n     *   const { data, error } = await supabase.auth.signInWithSSO({\n     *     domain: 'company.com'\n     *   })\n     *\n     *   if (data?.url) {\n     *     // redirect the user to the identity provider's authentication flow\n     *     window.location.href = data.url\n     *   }\n     * ```\n     *\n     * @example Sign in with provider UUID\n     * ```js\n     *   // Useful when you need to map a user's sign in request according\n     *   // to different rules that can't use email domains.\n     *\n     *   const { data, error } = await supabase.auth.signInWithSSO({\n     *     providerId: '21648a9d-8d5a-4555-a9d1-d6375dc14e92'\n     *   })\n     *\n     *   if (data?.url) {\n     *     // redirect the user to the identity provider's authentication flow\n     *     window.location.href = data.url\n     *   }\n     * ```\n     */\n    async signInWithSSO(params) {\n        var _a, _b, _c, _d;\n        let flowId = null;\n        try {\n            let codeChallenge = null;\n            let codeChallengeMethod = null;\n            if (this.flowType === 'pkce') {\n                ;\n                [codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod();\n            }\n            const result = await _request(this.fetch, 'POST', `${this.url}/sso`, {\n                body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, ('providerId' in params ? { provider_id: params.providerId } : null)), ('domain' in params ? { domain: params.domain } : null)), { redirect_to: this._maybeAppendFlowIdToRedirect((_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo, flowId) }), (((_b = params === null || params === void 0 ? void 0 : params.options) === null || _b === void 0 ? void 0 : _b.captchaToken)\n                    ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } }\n                    : null)), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }),\n                headers: this.headers,\n                xform: _ssoResponse,\n            });\n            // Automatically redirect in browser unless skipBrowserRedirect is true\n            if (((_c = result.data) === null || _c === void 0 ? void 0 : _c.url) && isBrowser() && !((_d = params.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect)) {\n                window.location.assign(result.data.url);\n            }\n            return this._returnResult(result);\n        }\n        catch (error) {\n            await removePKCEVerifier(this.storage, this.storageKey, flowId);\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Sends a reauthentication OTP to the user's email or phone number.\n     * Requires the user to be signed-in.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - This method is used together with `updateUser()` when a user's password needs to be updated.\n     * - If you require your user to reauthenticate before updating their password, you need to enable the **Secure password change** option in your [project's email provider settings](/dashboard/project/_/auth/providers).\n     * - A user is only require to reauthenticate before updating their password if **Secure password change** is enabled and the user **hasn't recently signed in**. A user is deemed recently signed in if the session was created in the last 24 hours.\n     * - This method will send a nonce to the user's email. If the user doesn't have a confirmed email address, the method will send the nonce to the user's confirmed phone number instead.\n     * - After receiving the OTP, include it as the `nonce` in your `updateUser()` call to finalize the password change.\n     *\n     * @exampleDescription Send reauthentication nonce\n     * Sends a reauthentication nonce to the user's email or phone number.\n     *\n     * @example Send reauthentication nonce\n     * ```js\n     * const { error } = await supabase.auth.reauthenticate()\n     * ```\n     */\n    async reauthenticate() {\n        await this.initializePromise;\n        if (this.lock != null) {\n            // TODO(v3): remove legacy lock path\n            return await this._acquireLock(this.lockAcquireTimeout, async () => {\n                return await this._reauthenticate();\n            });\n        }\n        return await this._reauthenticate();\n    }\n    async _reauthenticate() {\n        try {\n            return await this._useSession(async (result) => {\n                const { data: { session }, error: sessionError, } = result;\n                if (sessionError)\n                    throw sessionError;\n                if (!session)\n                    throw new AuthSessionMissingError();\n                const { error } = await _request(this.fetch, 'GET', `${this.url}/reauthenticate`, {\n                    headers: this.headers,\n                    jwt: session.access_token,\n                });\n                return this._returnResult({ data: { user: null, session: null }, error });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: { user: null, session: null }, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - Resends a signup confirmation, email change or phone change email to the user.\n     * - Passwordless sign-ins can be resent by calling the `signInWithOtp()` method again.\n     * - Password recovery emails can be resent by calling the `resetPasswordForEmail()` method again.\n     * - This method will only resend an email or phone OTP to the user if there was an initial signup, email change or phone change request being made(note: For existing users signing in with OTP, you should use `signInWithOtp()` again to resend the OTP).\n     * - You can specify a redirect url when you resend an email link using the `emailRedirectTo` option.\n     *\n     * @exampleDescription Resend an email signup confirmation\n     * Resends the email signup confirmation to the user\n     *\n     * @example Resend an email signup confirmation\n     * ```js\n     * const { error } = await supabase.auth.resend({\n     *   type: 'signup',\n     *   email: 'email@example.com',\n     *   options: {\n     *     emailRedirectTo: 'https://example.com/welcome'\n     *   }\n     * })\n     * ```\n     *\n     * @exampleDescription Resend a phone signup confirmation\n     * Resends the phone signup confirmation email to the user\n     *\n     * @example Resend a phone signup confirmation\n     * ```js\n     * const { error } = await supabase.auth.resend({\n     *   type: 'sms',\n     *   phone: '1234567890'\n     * })\n     * ```\n     *\n     * @exampleDescription Resend email change email\n     * Resends the email change email to the user\n     *\n     * @example Resend email change email\n     * ```js\n     * const { error } = await supabase.auth.resend({\n     *   type: 'email_change',\n     *   email: 'email@example.com'\n     * })\n     * ```\n     *\n     * @exampleDescription Resend phone change OTP\n     * Resends the phone change OTP to the user\n     *\n     * @example Resend phone change OTP\n     * ```js\n     * const { error } = await supabase.auth.resend({\n     *   type: 'phone_change',\n     *   phone: '1234567890'\n     * })\n     * ```\n     */\n    async resend(credentials) {\n        let flowId = null;\n        try {\n            const endpoint = `${this.url}/resend`;\n            if ('email' in credentials) {\n                const { email, type, options } = credentials;\n                let codeChallenge = null;\n                let codeChallengeMethod = null;\n                if (this.flowType === 'pkce') {\n                    ;\n                    [codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod();\n                }\n                const { error } = await _request(this.fetch, 'POST', endpoint, {\n                    headers: this.headers,\n                    body: {\n                        email,\n                        type,\n                        gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },\n                        code_challenge: codeChallenge,\n                        code_challenge_method: codeChallengeMethod,\n                    },\n                    redirectTo: this._maybeAppendFlowIdToRedirect(options === null || options === void 0 ? void 0 : options.emailRedirectTo, flowId),\n                });\n                if (error) {\n                    await removePKCEVerifier(this.storage, this.storageKey, flowId);\n                }\n                return this._returnResult({ data: { user: null, session: null }, error });\n            }\n            else if ('phone' in credentials) {\n                const { phone, type, options } = credentials;\n                const { data, error } = await _request(this.fetch, 'POST', endpoint, {\n                    headers: this.headers,\n                    body: {\n                        phone,\n                        type,\n                        gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },\n                    },\n                });\n                return this._returnResult({\n                    data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id },\n                    error,\n                });\n            }\n            throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a type');\n        }\n        catch (error) {\n            await removePKCEVerifier(this.storage, this.storageKey, flowId);\n            if (isAuthError(error)) {\n                return this._returnResult({ data: { user: null, session: null }, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Returns the session, refreshing it if necessary.\n     *\n     * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.\n     *\n     * **IMPORTANT:** This method loads values directly from the storage attached\n     * to the client. If that storage is based on request cookies for example,\n     * the values in it may not be authentic and therefore it's strongly advised\n     * against using this method and its results in such circumstances. A warning\n     * will be emitted if this is detected. Use {@link GoTrueClient.getUser} instead.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - Since the introduction of [asymmetric JWT signing keys](/docs/guides/auth/signing-keys), this method is considered low-level and we encourage you to use `getClaims()` or `getUser()` instead.\n     * - Retrieves the current [user session](/docs/guides/auth/sessions) from the storage medium (local storage, cookies).\n     * - The session contains an access token (signed JWT), a refresh token and the user object.\n     * - If the session's access token is expired or is about to expire, this method will use the refresh token to refresh the session.\n     * - When using in a browser, or you've called `startAutoRefresh()` in your environment (React Native, etc.) this function always returns a valid access token without refreshing the session itself, as this is done in the background. This function returns very fast.\n     * - **IMPORTANT SECURITY NOTICE:** If using an insecure storage medium, such as cookies or request headers, the user object returned by this function **must not be trusted**. Always verify the JWT using `getClaims()` or your own JWT verification library to securely establish the user's identity and access. You can also use `getUser()` to fetch the user object directly from the Auth server for this purpose.\n     * - Cross-tab refresh races are handled by the GoTrue server (the rotated token from the first tab is returned to subsequent tabs via the parent-of-active mechanism), so no client-side serialization is needed.\n     *\n     * @example Get the session data\n     * ```js\n     * const { data, error } = await supabase.auth.getSession()\n     * ```\n     *\n     * @exampleResponse Get the session data\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"session\": {\n     *       \"access_token\": \"<ACCESS_TOKEN>\",\n     *       \"token_type\": \"bearer\",\n     *       \"expires_in\": 3600,\n     *       \"expires_at\": 1700000000,\n     *       \"refresh_token\": \"<REFRESH_TOKEN>\",\n     *       \"user\": {\n     *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *         \"aud\": \"authenticated\",\n     *         \"role\": \"authenticated\",\n     *         \"email\": \"example@email.com\",\n     *         \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *         \"phone\": \"\",\n     *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *         \"app_metadata\": {\n     *           \"provider\": \"email\",\n     *           \"providers\": [\n     *             \"email\"\n     *           ]\n     *         },\n     *         \"user_metadata\": {\n     *           \"email\": \"example@email.com\",\n     *           \"email_verified\": false,\n     *           \"phone_verified\": false,\n     *           \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *         },\n     *         \"identities\": [\n     *           {\n     *             \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *             \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *             \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *             \"identity_data\": {\n     *               \"email\": \"example@email.com\",\n     *               \"email_verified\": false,\n     *               \"phone_verified\": false,\n     *               \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *             },\n     *             \"provider\": \"email\",\n     *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *             \"created_at\": \"2024-01-01T00:00:00Z\",\n     *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *             \"email\": \"example@email.com\"\n     *           }\n     *         ],\n     *         \"created_at\": \"2024-01-01T00:00:00Z\",\n     *         \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *         \"is_anonymous\": false\n     *       }\n     *     }\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     */\n    async getSession() {\n        await this.initializePromise;\n        if (this.lock != null) {\n            // TODO(v3): remove legacy lock path\n            return await this._acquireLock(this.lockAcquireTimeout, async () => {\n                return this._useSession(async (result) => {\n                    return result;\n                });\n            });\n        }\n        return await this._useSession(async (result) => {\n            return result;\n        });\n    }\n    /**\n     * Acquires a global lock based on the storage key.\n     *\n     * TODO(v3): remove along with the legacy lock path. Only called when\n     * `this.lock` is non-null (custom lock supplied via constructor). The\n     * default lockless path bypasses this entirely.\n     */\n    async _acquireLock(acquireTimeout, fn) {\n        this._debug('#_acquireLock', 'begin', acquireTimeout);\n        try {\n            if (this.lockAcquired) {\n                const last = this.pendingInLock.length\n                    ? this.pendingInLock[this.pendingInLock.length - 1]\n                    : Promise.resolve();\n                const result = (async () => {\n                    await last;\n                    return await fn();\n                })();\n                this.pendingInLock.push((async () => {\n                    try {\n                        await result;\n                    }\n                    catch (_e) {\n                        // we just care if it finished\n                    }\n                })());\n                return result;\n            }\n            return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => {\n                this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey);\n                try {\n                    this.lockAcquired = true;\n                    const result = fn();\n                    this.pendingInLock.push((async () => {\n                        try {\n                            await result;\n                        }\n                        catch (e) {\n                            // we just care if it finished\n                        }\n                    })());\n                    await result;\n                    // keep draining the queue until there's nothing to wait on\n                    while (this.pendingInLock.length) {\n                        const waitOn = [...this.pendingInLock];\n                        await Promise.all(waitOn);\n                        this.pendingInLock.splice(0, waitOn.length);\n                    }\n                    return await result;\n                }\n                finally {\n                    this._debug('#_acquireLock', 'lock released for storage key', this.storageKey);\n                    this.lockAcquired = false;\n                }\n            });\n        }\n        finally {\n            this._debug('#_acquireLock', 'end');\n        }\n    }\n    /**\n     * Use instead of {@link GoTrueClient.getSession} inside the library. Loads the session\n     * via `__loadSession` (which may trigger a refresh if the access token is\n     * within the expiry margin) and runs `fn` with the result.\n     */\n    async _useSession(fn) {\n        this._debug('#_useSession', 'begin');\n        try {\n            // Concurrent callers may both reach __loadSession; storage reads are\n            // idempotent, and the only write path inside it (refresh) is\n            // single-flighted downstream by `refreshingDeferred` in\n            // `_callRefreshToken`. No serialization is needed at this layer.\n            const result = await this.__loadSession();\n            return await fn(result);\n        }\n        finally {\n            this._debug('#_useSession', 'end');\n        }\n    }\n    /**\n     * NEVER USE DIRECTLY!\n     *\n     * Always use `_useSession`.\n     */\n    async __loadSession() {\n        this._debug('#__loadSession()', 'begin');\n        if (this.lock != null && !this.lockAcquired) {\n            // TODO(v3): remove. Only meaningful on the legacy lock path.\n            this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack);\n        }\n        try {\n            let currentSession = null;\n            const maybeSession = await getItemAsync(this.storage, this.storageKey);\n            this._debug('#getSession()', 'session from storage', maybeSession);\n            if (maybeSession !== null) {\n                if (this._isValidSession(maybeSession)) {\n                    currentSession = maybeSession;\n                }\n                else {\n                    this._debug('#getSession()', 'session from storage is not valid');\n                    await this._removeSession();\n                }\n            }\n            if (!currentSession) {\n                return { data: { session: null }, error: null };\n            }\n            // A session is considered expired before the access token _actually_\n            // expires. When the autoRefreshToken option is off (or when the tab is\n            // in the background), very eager users of getSession() -- like\n            // realtime-js -- might send a valid JWT which will expire by the time it\n            // reaches the server.\n            const hasExpired = currentSession.expires_at\n                ? currentSession.expires_at * 1000 - Date.now() < EXPIRY_MARGIN_MS\n                : false;\n            this._debug('#__loadSession()', `session has${hasExpired ? '' : ' not'} expired`, 'expires_at', currentSession.expires_at);\n            if (!hasExpired) {\n                if (this.userStorage) {\n                    const maybeUser = (await getItemAsync(this.userStorage, this.storageKey + '-user'));\n                    if (maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) {\n                        currentSession.user = maybeUser.user;\n                    }\n                    else {\n                        currentSession.user = userNotAvailableProxy();\n                    }\n                }\n                // Wrap the user object with a warning proxy on the server\n                // This warns when properties of the user are accessed, not when session.user itself is accessed\n                if (this.storage.isServer &&\n                    currentSession.user &&\n                    !currentSession.user.__isUserNotAvailableProxy) {\n                    const suppressWarningRef = { value: this.suppressGetSessionWarning };\n                    currentSession.user = insecureUserWarningProxy(currentSession.user, suppressWarningRef);\n                    // Update the client-level suppression flag when the proxy suppresses the warning\n                    if (suppressWarningRef.value) {\n                        this.suppressGetSessionWarning = true;\n                    }\n                }\n                return { data: { session: currentSession }, error: null };\n            }\n            const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token);\n            if (error) {\n                // Proactive-preserve mirror: `_callRefreshToken` keeps the session\n                // in storage when refresh fails non-retryably but the access token\n                // is still inside its real expiry window. Hand the caller the\n                // still-valid session instead of translating the refresh error\n                // into `session: null`. If the access token has actually expired,\n                // the session is genuinely dead and the error stands. Explicit\n                // refresh entry points (`refreshSession`, `setSession`)\n                // intentionally bypass this fallback — they want to know the\n                // refresh failed.\n                const accessTokenStillValid = !!(currentSession.expires_at && currentSession.expires_at * 1000 > Date.now());\n                if (accessTokenStillValid) {\n                    // Race guard: a concurrent `signOut` may have cleared storage\n                    // during the refresh attempt. Don't hand back a session that no\n                    // longer exists on disk.\n                    const stillStored = (await getItemAsync(this.storage, this.storageKey));\n                    if (stillStored && stillStored.refresh_token === currentSession.refresh_token) {\n                        return this._returnResult({ data: { session: currentSession }, error: null });\n                    }\n                }\n                return this._returnResult({ data: { session: null }, error });\n            }\n            return this._returnResult({ data: { session }, error: null });\n        }\n        finally {\n            this._debug('#__loadSession()', 'end');\n        }\n    }\n    /**\n     * Gets the current user details if there is an existing session. This method\n     * performs a network request to the Supabase Auth server, so the returned\n     * value is authentic and can be used to base authorization rules on.\n     *\n     * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - This method fetches the user object from the database instead of local session.\n     * - This method is useful for checking if the user is authorized because it validates the user's access token JWT on the server.\n     * - Should always be used when checking for user authorization on the server. On the client, you can instead use `getSession().session.user` for faster results. `getSession` is insecure on the server.\n     *\n     * @example Get the logged in user with the current existing session\n     * ```js\n     * const { data: { user } } = await supabase.auth.getUser()\n     * ```\n     *\n     * @exampleResponse Get the logged in user with the current existing session\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"user\": {\n     *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *       \"aud\": \"authenticated\",\n     *       \"role\": \"authenticated\",\n     *       \"email\": \"example@email.com\",\n     *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *       \"phone\": \"\",\n     *       \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *       \"app_metadata\": {\n     *         \"provider\": \"email\",\n     *         \"providers\": [\n     *           \"email\"\n     *         ]\n     *       },\n     *       \"user_metadata\": {\n     *         \"email\": \"example@email.com\",\n     *         \"email_verified\": false,\n     *         \"phone_verified\": false,\n     *         \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *       },\n     *       \"identities\": [\n     *         {\n     *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"identity_data\": {\n     *             \"email\": \"example@email.com\",\n     *             \"email_verified\": false,\n     *             \"phone_verified\": false,\n     *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *           },\n     *           \"provider\": \"email\",\n     *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *           \"created_at\": \"2024-01-01T00:00:00Z\",\n     *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *           \"email\": \"example@email.com\"\n     *         }\n     *       ],\n     *       \"created_at\": \"2024-01-01T00:00:00Z\",\n     *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *       \"is_anonymous\": false\n     *     }\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     *\n     * @example Get the logged in user with a custom access token jwt\n     * ```js\n     * const { data: { user } } = await supabase.auth.getUser(jwt)\n     * ```\n     */\n    async getUser(jwt) {\n        if (jwt) {\n            return await this._getUser(jwt);\n        }\n        await this.initializePromise;\n        let result;\n        if (this.lock != null) {\n            // TODO(v3): remove legacy lock path\n            result = await this._acquireLock(this.lockAcquireTimeout, async () => {\n                return await this._getUser();\n            });\n        }\n        else {\n            result = await this._getUser();\n        }\n        if (result.data.user) {\n            this.suppressGetSessionWarning = true;\n        }\n        return result;\n    }\n    async _getUser(jwt) {\n        try {\n            if (jwt) {\n                return await _request(this.fetch, 'GET', `${this.url}/user`, {\n                    headers: this.headers,\n                    jwt: jwt,\n                    xform: _userResponse,\n                });\n            }\n            return await this._useSession(async (result) => {\n                var _a, _b, _c;\n                const { data, error } = result;\n                if (error) {\n                    throw error;\n                }\n                // returns an error if there is no access_token or custom authorization header\n                if (!((_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) && !this.hasCustomAuthorizationHeader) {\n                    return { data: { user: null }, error: new AuthSessionMissingError() };\n                }\n                return await _request(this.fetch, 'GET', `${this.url}/user`, {\n                    headers: this.headers,\n                    jwt: (_c = (_b = data.session) === null || _b === void 0 ? void 0 : _b.access_token) !== null && _c !== void 0 ? _c : undefined,\n                    xform: _userResponse,\n                });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                if (isAuthSessionMissingError(error)) {\n                    // JWT contains a `session_id` which does not correspond to an active\n                    // session in the database, indicating the user is signed out.\n                    await this._removeSession();\n                }\n                return this._returnResult({ data: { user: null }, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Updates user data for a logged in user.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - In order to use the `updateUser()` method, the user needs to be signed in first.\n     * - By default, email updates sends a confirmation link to both the user's current and new email.\n     * To only send a confirmation link to the user's new email, disable **Secure email change** in your project's [email auth provider settings](/dashboard/project/_/auth/providers).\n     *\n     * @exampleDescription Update the email for an authenticated user\n     * Sends a \"Confirm Email Change\" email to the new address. If **Secure Email Change** is enabled (default), confirmation is also required from the **old email** before the change is applied. To skip dual confirmation and apply the change after only the new email is verified, disable **Secure Email Change** in the [Email Auth Provider settings](/dashboard/project/_/auth/providers?provider=Email).\n     *\n     * @example Update the email for an authenticated user\n     * ```js\n     * const { data, error } = await supabase.auth.updateUser({\n     *   email: 'new@email.com'\n     * })\n     * ```\n     *\n     * @exampleResponse Update the email for an authenticated user\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"user\": {\n     *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *       \"aud\": \"authenticated\",\n     *       \"role\": \"authenticated\",\n     *       \"email\": \"example@email.com\",\n     *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *       \"phone\": \"\",\n     *       \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *       \"new_email\": \"new@email.com\",\n     *       \"email_change_sent_at\": \"2024-01-01T00:00:00Z\",\n     *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *       \"app_metadata\": {\n     *         \"provider\": \"email\",\n     *         \"providers\": [\n     *           \"email\"\n     *         ]\n     *       },\n     *       \"user_metadata\": {\n     *         \"email\": \"example@email.com\",\n     *         \"email_verified\": false,\n     *         \"phone_verified\": false,\n     *         \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *       },\n     *       \"identities\": [\n     *         {\n     *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"identity_data\": {\n     *             \"email\": \"example@email.com\",\n     *             \"email_verified\": false,\n     *             \"phone_verified\": false,\n     *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *           },\n     *           \"provider\": \"email\",\n     *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *           \"created_at\": \"2024-01-01T00:00:00Z\",\n     *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *           \"email\": \"example@email.com\"\n     *         }\n     *       ],\n     *       \"created_at\": \"2024-01-01T00:00:00Z\",\n     *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *       \"is_anonymous\": false\n     *     }\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     *\n     * @exampleDescription Update the phone number for an authenticated user\n     * Sends a one-time password (OTP) to the new phone number.\n     *\n     * @example Update the phone number for an authenticated user\n     * ```js\n     * const { data, error } = await supabase.auth.updateUser({\n     *   phone: '123456789'\n     * })\n     * ```\n     *\n     * @example Update the password for an authenticated user\n     * ```js\n     * const { data, error } = await supabase.auth.updateUser({\n     *   password: 'new password'\n     * })\n     * ```\n     *\n     * @exampleDescription Update the user's metadata\n     * Updates the user's custom metadata.\n     *\n     * **Note**: The `data` field maps to the `auth.users.raw_user_meta_data` column in your Supabase database. When calling `getUser()`, the data will be available as `user.user_metadata`.\n     *\n     * @example Update the user's metadata\n     * ```js\n     * const { data, error } = await supabase.auth.updateUser({\n     *   data: { hello: 'world' }\n     * })\n     * ```\n     *\n     * @exampleDescription Update the user's password with a nonce\n     * If **Secure password change** is enabled in your [project's email provider settings](/dashboard/project/_/auth/providers), updating the user's password would require a nonce if the user **hasn't recently signed in**. The nonce is sent to the user's email or phone number. A user is deemed recently signed in if the session was created in the last 24 hours.\n     *\n     * @example Update the user's password with a nonce\n     * ```js\n     * const { data, error } = await supabase.auth.updateUser({\n     *   password: 'new password',\n     *   nonce: '123456'\n     * })\n     * ```\n     */\n    async updateUser(attributes, options = {}) {\n        await this.initializePromise;\n        if (this.lock != null) {\n            // TODO(v3): remove legacy lock path\n            return await this._acquireLock(this.lockAcquireTimeout, async () => {\n                return await this._updateUser(attributes, options);\n            });\n        }\n        return await this._updateUser(attributes, options);\n    }\n    async _updateUser(attributes, options = {}) {\n        let flowId = null;\n        try {\n            return await this._useSession(async (result) => {\n                const { data: sessionData, error: sessionError } = result;\n                if (sessionError) {\n                    throw sessionError;\n                }\n                if (!sessionData.session) {\n                    throw new AuthSessionMissingError();\n                }\n                const session = sessionData.session;\n                let codeChallenge = null;\n                let codeChallengeMethod = null;\n                if (this.flowType === 'pkce' && attributes.email != null) {\n                    ;\n                    [codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod();\n                }\n                const { data, error: userError } = await _request(this.fetch, 'PUT', `${this.url}/user`, {\n                    headers: this.headers,\n                    redirectTo: this._maybeAppendFlowIdToRedirect(options === null || options === void 0 ? void 0 : options.emailRedirectTo, flowId),\n                    body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }),\n                    jwt: session.access_token,\n                    xform: _userResponse,\n                });\n                if (userError) {\n                    throw userError;\n                }\n                session.user = data.user;\n                await this._saveSession(session);\n                await this._notifyAllSubscribers('USER_UPDATED', session);\n                return this._returnResult({ data: { user: session.user }, error: null });\n            });\n        }\n        catch (error) {\n            await removePKCEVerifier(this.storage, this.storageKey, flowId);\n            if (isAuthError(error)) {\n                return this._returnResult({ data: { user: null }, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session.\n     * If the refresh token or access token in the current session is invalid, an error will be thrown.\n     * @param currentSession The current session that minimally contains an access token and refresh token.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - This method sets the session using an `access_token` and `refresh_token`.\n     * - If successful, a `SIGNED_IN` event is emitted.\n     *\n     * @exampleDescription Set the session\n     * Sets the session data from an access_token and refresh_token, then returns an auth response or error.\n     *\n     * @example Set the session\n     * ```js\n     *   const { data, error } = await supabase.auth.setSession({\n     *     access_token,\n     *     refresh_token\n     *   })\n     * ```\n     *\n     * @exampleResponse Set the session\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"user\": {\n     *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *       \"aud\": \"authenticated\",\n     *       \"role\": \"authenticated\",\n     *       \"email\": \"example@email.com\",\n     *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *       \"phone\": \"\",\n     *       \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *       \"app_metadata\": {\n     *         \"provider\": \"email\",\n     *         \"providers\": [\n     *           \"email\"\n     *         ]\n     *       },\n     *       \"user_metadata\": {\n     *         \"email\": \"example@email.com\",\n     *         \"email_verified\": false,\n     *         \"phone_verified\": false,\n     *         \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *       },\n     *       \"identities\": [\n     *         {\n     *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"identity_data\": {\n     *             \"email\": \"example@email.com\",\n     *             \"email_verified\": false,\n     *             \"phone_verified\": false,\n     *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *           },\n     *           \"provider\": \"email\",\n     *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *           \"created_at\": \"2024-01-01T00:00:00Z\",\n     *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *           \"email\": \"example@email.com\"\n     *         }\n     *       ],\n     *       \"created_at\": \"2024-01-01T00:00:00Z\",\n     *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *       \"is_anonymous\": false\n     *     },\n     *     \"session\": {\n     *       \"access_token\": \"<ACCESS_TOKEN>\",\n     *       \"refresh_token\": \"<REFRESH_TOKEN>\",\n     *       \"user\": {\n     *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *         \"aud\": \"authenticated\",\n     *         \"role\": \"authenticated\",\n     *         \"email\": \"example@email.com\",\n     *         \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *         \"phone\": \"\",\n     *         \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *         \"last_sign_in_at\": \"11111111-1111-1111-1111-111111111111\",\n     *         \"app_metadata\": {\n     *           \"provider\": \"email\",\n     *           \"providers\": [\n     *             \"email\"\n     *           ]\n     *         },\n     *         \"user_metadata\": {\n     *           \"email\": \"example@email.com\",\n     *           \"email_verified\": false,\n     *           \"phone_verified\": false,\n     *           \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *         },\n     *         \"identities\": [\n     *           {\n     *             \"identity_id\": \"2024-01-01T00:00:00Z\",\n     *             \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *             \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *             \"identity_data\": {\n     *               \"email\": \"example@email.com\",\n     *               \"email_verified\": false,\n     *               \"phone_verified\": false,\n     *               \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *             },\n     *             \"provider\": \"email\",\n     *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *             \"created_at\": \"2024-01-01T00:00:00Z\",\n     *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *             \"email\": \"example@email.com\"\n     *           }\n     *         ],\n     *         \"created_at\": \"2024-01-01T00:00:00Z\",\n     *         \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *         \"is_anonymous\": false\n     *       },\n     *       \"token_type\": \"bearer\",\n     *       \"expires_in\": 3500,\n     *       \"expires_at\": 1700000000\n     *     }\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     */\n    async setSession(currentSession) {\n        await this.initializePromise;\n        if (this.lock != null) {\n            // TODO(v3): remove legacy lock path\n            return await this._acquireLock(this.lockAcquireTimeout, async () => {\n                return await this._setSession(currentSession);\n            });\n        }\n        return await this._setSession(currentSession);\n    }\n    async _setSession(currentSession) {\n        try {\n            if (!currentSession.access_token || !currentSession.refresh_token) {\n                throw new AuthSessionMissingError();\n            }\n            const timeNow = Date.now() / 1000;\n            let expiresAt = timeNow;\n            let hasExpired = true;\n            let session = null;\n            const { payload } = decodeJWT(currentSession.access_token);\n            if (payload.exp) {\n                expiresAt = payload.exp;\n                hasExpired = expiresAt <= timeNow;\n            }\n            if (hasExpired) {\n                const { data: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token);\n                if (error) {\n                    return this._returnResult({ data: { user: null, session: null }, error: error });\n                }\n                if (!refreshedSession) {\n                    return { data: { user: null, session: null }, error: null };\n                }\n                session = refreshedSession;\n            }\n            else {\n                const { data, error } = await this._getUser(currentSession.access_token);\n                if (error) {\n                    return this._returnResult({ data: { user: null, session: null }, error });\n                }\n                session = {\n                    access_token: currentSession.access_token,\n                    refresh_token: currentSession.refresh_token,\n                    user: data.user,\n                    token_type: 'bearer',\n                    expires_in: expiresAt - timeNow,\n                    expires_at: expiresAt,\n                };\n                await this._saveSession(session);\n                await this._notifyAllSubscribers('SIGNED_IN', session);\n            }\n            return this._returnResult({ data: { user: session.user, session }, error: null });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: { session: null, user: null }, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Returns a new session, regardless of expiry status.\n     * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession().\n     * If the current session's refresh token is invalid, an error will be thrown.\n     * @param currentSession The current session. If passed in, it must contain a refresh token.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - This method will refresh and return a new session whether the current one is expired or not.\n     *\n     * @example Refresh session using the current session\n     * ```js\n     * const { data, error } = await supabase.auth.refreshSession()\n     * const { session, user } = data\n     * ```\n     *\n     * @exampleResponse Refresh session using the current session\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"user\": {\n     *       \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *       \"aud\": \"authenticated\",\n     *       \"role\": \"authenticated\",\n     *       \"email\": \"example@email.com\",\n     *       \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *       \"phone\": \"\",\n     *       \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *       \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *       \"app_metadata\": {\n     *         \"provider\": \"email\",\n     *         \"providers\": [\n     *           \"email\"\n     *         ]\n     *       },\n     *       \"user_metadata\": {\n     *         \"email\": \"example@email.com\",\n     *         \"email_verified\": false,\n     *         \"phone_verified\": false,\n     *         \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *       },\n     *       \"identities\": [\n     *         {\n     *           \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *           \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *           \"identity_data\": {\n     *             \"email\": \"example@email.com\",\n     *             \"email_verified\": false,\n     *             \"phone_verified\": false,\n     *             \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *           },\n     *           \"provider\": \"email\",\n     *           \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *           \"created_at\": \"2024-01-01T00:00:00Z\",\n     *           \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *           \"email\": \"example@email.com\"\n     *         }\n     *       ],\n     *       \"created_at\": \"2024-01-01T00:00:00Z\",\n     *       \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *       \"is_anonymous\": false\n     *     },\n     *     \"session\": {\n     *       \"access_token\": \"<ACCESS_TOKEN>\",\n     *       \"token_type\": \"bearer\",\n     *       \"expires_in\": 3600,\n     *       \"expires_at\": 1700000000,\n     *       \"refresh_token\": \"<REFRESH_TOKEN>\",\n     *       \"user\": {\n     *         \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *         \"aud\": \"authenticated\",\n     *         \"role\": \"authenticated\",\n     *         \"email\": \"example@email.com\",\n     *         \"email_confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *         \"phone\": \"\",\n     *         \"confirmed_at\": \"2024-01-01T00:00:00Z\",\n     *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *         \"app_metadata\": {\n     *           \"provider\": \"email\",\n     *           \"providers\": [\n     *             \"email\"\n     *           ]\n     *         },\n     *         \"user_metadata\": {\n     *           \"email\": \"example@email.com\",\n     *           \"email_verified\": false,\n     *           \"phone_verified\": false,\n     *           \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *         },\n     *         \"identities\": [\n     *           {\n     *             \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *             \"id\": \"11111111-1111-1111-1111-111111111111\",\n     *             \"user_id\": \"11111111-1111-1111-1111-111111111111\",\n     *             \"identity_data\": {\n     *               \"email\": \"example@email.com\",\n     *               \"email_verified\": false,\n     *               \"phone_verified\": false,\n     *               \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *             },\n     *             \"provider\": \"email\",\n     *             \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *             \"created_at\": \"2024-01-01T00:00:00Z\",\n     *             \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *             \"email\": \"example@email.com\"\n     *           }\n     *         ],\n     *         \"created_at\": \"2024-01-01T00:00:00Z\",\n     *         \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *         \"is_anonymous\": false\n     *       }\n     *     }\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     *\n     * @example Refresh session using a refresh token\n     * ```js\n     * const { data, error } = await supabase.auth.refreshSession({ refresh_token })\n     * const { session, user } = data\n     * ```\n     */\n    async refreshSession(currentSession) {\n        await this.initializePromise;\n        if (this.lock != null) {\n            // TODO(v3): remove legacy lock path\n            return await this._acquireLock(this.lockAcquireTimeout, async () => {\n                return await this._refreshSession(currentSession);\n            });\n        }\n        return await this._refreshSession(currentSession);\n    }\n    async _refreshSession(currentSession) {\n        try {\n            return await this._useSession(async (result) => {\n                var _a;\n                if (!currentSession) {\n                    const { data, error } = result;\n                    if (error) {\n                        throw error;\n                    }\n                    currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : undefined;\n                }\n                if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) {\n                    throw new AuthSessionMissingError();\n                }\n                const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token);\n                if (error) {\n                    return this._returnResult({ data: { user: null, session: null }, error: error });\n                }\n                if (!session) {\n                    return this._returnResult({ data: { user: null, session: null }, error: null });\n                }\n                return this._returnResult({ data: { user: session.user, session }, error: null });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: { user: null, session: null }, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Gets the session data from a URL string\n     */\n    async _getSessionFromURL(params, callbackUrlType) {\n        var _a;\n        try {\n            if (!isBrowser())\n                throw new AuthImplicitGrantRedirectError('No browser detected.');\n            // If there's an error in the URL, it doesn't matter what flow it is, we just return the error.\n            if (params.error || params.error_description || params.error_code) {\n                // The error class returned implies that the redirect is from an implicit grant flow\n                // but it could also be from a redirect error from a PKCE flow.\n                throw new AuthImplicitGrantRedirectError(params.error_description || 'Error in URL with unspecified error_description', {\n                    error: params.error || 'unspecified_error',\n                    code: params.error_code || 'unspecified_code',\n                });\n            }\n            // Checks for mismatches between the flowType initialised in the client and the URL parameters\n            switch (callbackUrlType) {\n                case 'implicit':\n                    if (this.flowType === 'pkce') {\n                        throw new AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.');\n                    }\n                    break;\n                case 'pkce':\n                    if (this.flowType === 'implicit') {\n                        throw new AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.');\n                    }\n                    break;\n                default:\n                // there's no mismatch so we continue\n            }\n            // Since this is a redirect for PKCE, we attempt to retrieve the code from the URL for the code exchange\n            if (callbackUrlType === 'pkce') {\n                this._debug('#_initialize()', 'begin', 'is PKCE flow', true);\n                if (!params.code)\n                    throw new AuthPKCEGrantCodeExchangeError('No code detected.');\n                const { data, error } = await this._exchangeCodeForSession(params.code, {\n                    flowId: params[PKCE_FLOW_ID_PARAM],\n                });\n                if (error)\n                    throw error;\n                const url = new URL(window.location.href);\n                url.searchParams.delete('code');\n                url.searchParams.delete(PKCE_FLOW_ID_PARAM);\n                window.history.replaceState(window.history.state, '', url.toString());\n                return {\n                    data: { session: data.session, redirectType: (_a = data.redirectType) !== null && _a !== void 0 ? _a : null },\n                    error: null,\n                };\n            }\n            const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type, } = params;\n            if (!access_token || !expires_in || !refresh_token || !token_type) {\n                throw new AuthImplicitGrantRedirectError('No session defined in URL');\n            }\n            const timeNow = Math.round(Date.now() / 1000);\n            const expiresIn = parseInt(expires_in);\n            let expiresAt = timeNow + expiresIn;\n            if (expires_at) {\n                expiresAt = parseInt(expires_at);\n            }\n            const actuallyExpiresIn = expiresAt - timeNow;\n            if (actuallyExpiresIn * 1000 <= AUTO_REFRESH_TICK_DURATION_MS) {\n                console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`);\n            }\n            const issuedAt = expiresAt - expiresIn;\n            if (timeNow - issuedAt >= 120) {\n                console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale', issuedAt, expiresAt, timeNow);\n            }\n            else if (timeNow - issuedAt < 0) {\n                console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew', issuedAt, expiresAt, timeNow);\n            }\n            const { data, error } = await this._getUser(access_token);\n            if (error)\n                throw error;\n            const session = {\n                provider_token,\n                provider_refresh_token,\n                access_token,\n                expires_in: expiresIn,\n                expires_at: expiresAt,\n                refresh_token,\n                token_type: token_type,\n                user: data.user,\n            };\n            // Remove tokens from URL\n            window.location.hash = '';\n            this._debug('#_getSessionFromURL()', 'clearing window.location.hash');\n            return this._returnResult({ data: { session, redirectType: params.type }, error: null });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: { session: null, redirectType: null }, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2)\n     *\n     * If `detectSessionInUrl` is a function, it will be called with the URL and params to determine\n     * if the URL should be processed as a Supabase auth callback. This allows users to exclude\n     * URLs from other OAuth providers (e.g., Facebook Login) that also return access_token in the fragment.\n     */\n    _isImplicitGrantCallback(params) {\n        if (typeof this.detectSessionInUrl === 'function') {\n            return this.detectSessionInUrl(new URL(window.location.href), params);\n        }\n        return Boolean(params.access_token || params.error || params.error_description || params.error_code);\n    }\n    /**\n     * Checks if the current URL and backing storage contain parameters given by a PKCE flow\n     */\n    async _isPKCECallback(params) {\n        if (!params.code) {\n            return false;\n        }\n        const flowId = validatePKCEFlowId(params[PKCE_FLOW_ID_PARAM]);\n        if (flowId &&\n            (await getItemAsync(this.storage, pkceVerifierSlotKey(this.storageKey, flowId)))) {\n            return true;\n        }\n        const currentStorageContent = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`);\n        return !!currentStorageContent;\n    }\n    /**\n     * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `\"SIGNED_OUT\"` event.\n     *\n     * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`.\n     * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason.\n     *\n     * If using `others` scope, no `SIGNED_OUT` event is fired!\n     *\n     * **Warning:** the default `scope` is `'global'`. This signs the user out of\n     * **every device they are currently signed in on**, not just the current\n     * tab/session. If you only want to sign the user out of the current session\n     * (the behavior most other auth libraries default to), pass\n     * `{ scope: 'local' }` explicitly.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - In order to use the `signOut()` method, the user needs to be signed in first.\n     * - By default, `signOut()` uses the **global** scope, which signs out the user\n     *   on every device they are signed in on (not just the current one). Pass\n     *   `{ scope: 'local' }` to only sign out the current session. This is\n     *   usually what apps want on a \"Sign out\" button, especially when users\n     *   sign in from multiple devices and do not expect signing out of one to\n     *   terminate the others.\n     * - Since Supabase Auth uses JWTs for authentication, the access token JWT will be valid until it's expired. When the user signs out, Supabase revokes the refresh token and deletes the JWT from the client-side. This does not revoke the JWT and it will still be valid until it expires.\n     *\n     * @example Sign out of every device (global – default)\n     * ```js\n     * const { error } = await supabase.auth.signOut()\n     * ```\n     *\n     * @example Sign out only the current session (recommended for most apps)\n     * ```js\n     * const { error } = await supabase.auth.signOut({ scope: 'local' })\n     * ```\n     *\n     * @example Sign out of all other sessions, keep the current one\n     * ```js\n     * const { error } = await supabase.auth.signOut({ scope: 'others' })\n     * ```\n     */\n    async signOut(options = { scope: 'global' }) {\n        await this.initializePromise;\n        if (this.lock != null) {\n            // TODO(v3): remove legacy lock path\n            return await this._acquireLock(this.lockAcquireTimeout, async () => {\n                return await this._signOut(options);\n            });\n        }\n        return await this._signOut(options);\n    }\n    async _signOut({ scope } = { scope: 'global' }) {\n        return await this._useSession(async (result) => {\n            var _a;\n            const removeCurrentSession = async () => {\n                await this._removeSession();\n            };\n            const { data, error: sessionError } = result;\n            if (sessionError && !isAuthSessionMissingError(sessionError)) {\n                return this._returnResult({ error: sessionError });\n            }\n            const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token;\n            if (accessToken) {\n                const { error } = await this.admin.signOut(accessToken, scope);\n                if (error) {\n                    // ignore 404s since user might not exist anymore\n                    // ignore 401s since an invalid or expired JWT should sign out the current session\n                    if (!((isAuthApiError(error) &&\n                        (error.status === 404 || error.status === 401 || error.status === 403)) ||\n                        isAuthSessionMissingError(error))) {\n                        if (scope !== 'others') {\n                            await removeCurrentSession();\n                        }\n                        return this._returnResult({ error });\n                    }\n                }\n            }\n            if (scope !== 'others') {\n                await removeCurrentSession();\n            }\n            return this._returnResult({ error: null });\n        });\n    }\n    /**  *\n     * @category Auth\n     *\n     * @remarks\n     * - Subscribes to important events occurring on the user's session.\n     * - Use on the frontend/client. It is less useful on the server.\n     * - Events are emitted across tabs to keep your application's UI up-to-date. Some events can fire very frequently, based on the number of tabs open. Use a quick and efficient callback function, and defer or debounce as many operations as you can to be performed outside of the callback.\n     * - Callbacks can be `async` and can safely call other Supabase auth methods (`getUser`, `setSession`, etc.) from inside the callback.\n     * - Keep callbacks quick. Events are awaited in order, so a slow callback delays subsequent events to subscribers in this tab.\n     * - Emitted events:\n     *   - `INITIAL_SESSION`\n     *     - Emitted right after the Supabase client is constructed and the initial session from storage is loaded.\n     *   - `SIGNED_IN`\n     *     - Emitted each time a user session is confirmed or re-established, including on user sign in and when refocusing a tab.\n     *     - Avoid making assumptions as to when this event is fired, this may occur even when the user is already signed in. Instead, check the user object attached to the event to see if a new user has signed in and update your application's UI.\n     *     - This event can fire very frequently depending on the number of tabs open in your application.\n     *   - `SIGNED_OUT`\n     *     - Emitted when the user signs out. This can be after:\n     *       - A call to `supabase.auth.signOut()`.\n     *       - After the user's session has expired for any reason:\n     *         - User has signed out on another device.\n     *         - The session has reached its timebox limit or inactivity timeout.\n     *         - User has signed in on another device with single session per user enabled.\n     *         - Check the [User Sessions](/docs/guides/auth/sessions) docs for more information.\n     *     - Use this to clean up any local storage your application has associated with the user.\n     *   - `TOKEN_REFRESHED`\n     *     - Emitted each time a new access and refresh token are fetched for the signed in user.\n     *     - It's best practice and highly recommended to extract the access token (JWT) and store it in memory for further use in your application.\n     *       - Avoid frequent calls to `supabase.auth.getSession()` for the same purpose.\n     *     - There is a background process that keeps track of when the session should be refreshed so you will always receive valid tokens by listening to this event.\n     *     - The frequency of this event is related to the JWT expiry limit configured on your project.\n     *   - `USER_UPDATED`\n     *     - Emitted each time the `supabase.auth.updateUser()` method finishes successfully. Listen to it to update your application's UI based on new profile information.\n     *   - `PASSWORD_RECOVERY`\n     *     - Emitted instead of the `SIGNED_IN` event when the user lands on a page that includes a password recovery link in the URL.\n     *     - Use it to show a UI to the user where they can [reset their password](/docs/guides/auth/passwords#resetting-a-users-password-forgot-password).\n     *\n     * @example Listen to auth changes\n     * ```js\n     * const { data } = supabase.auth.onAuthStateChange((event, session) => {\n     *   console.log(event, session)\n     *\n     *   if (event === 'INITIAL_SESSION') {\n     *     // handle initial session\n     *   } else if (event === 'SIGNED_IN') {\n     *     // handle sign in event\n     *   } else if (event === 'SIGNED_OUT') {\n     *     // handle sign out event\n     *   } else if (event === 'PASSWORD_RECOVERY') {\n     *     // handle password recovery event\n     *   } else if (event === 'TOKEN_REFRESHED') {\n     *     // handle token refreshed event\n     *   } else if (event === 'USER_UPDATED') {\n     *     // handle user updated event\n     *   }\n     * })\n     *\n     * // call unsubscribe to remove the callback\n     * data.subscription.unsubscribe()\n     * ```\n     *\n     * @exampleDescription Listen to sign out\n     * Make sure you clear out any local data, such as local and session storage, after the client library has detected the user's sign out.\n     *\n     * @example Listen to sign out\n     * ```js\n     * supabase.auth.onAuthStateChange((event, session) => {\n     *   if (event === 'SIGNED_OUT') {\n     *     console.log('SIGNED_OUT', session)\n     *\n     *     // clear local and session storage\n     *     [\n     *       window.localStorage,\n     *       window.sessionStorage,\n     *     ].forEach((storage) => {\n     *       Object.entries(storage)\n     *         .forEach(([key]) => {\n     *           storage.removeItem(key)\n     *         })\n     *     })\n     *   }\n     * })\n     * ```\n     *\n     * @exampleDescription Store OAuth provider tokens on sign in\n     * When using [OAuth (Social Login)](/docs/guides/auth/social-login) you sometimes wish to get access to the provider's access token and refresh token, in order to call provider APIs in the name of the user.\n     *\n     * For example, if you are using [Sign in with Google](/docs/guides/auth/social-login/auth-google) you may want to use the provider token to call Google APIs on behalf of the user. Supabase Auth does not keep track of the provider access and refresh token, but does return them for you once, immediately after sign in. You can use the `onAuthStateChange` method to listen for the presence of the provider tokens and store them in local storage. You can further send them to your server's APIs for use on the backend.\n     *\n     * Finally, make sure you remove them from local storage on the `SIGNED_OUT` event. If the OAuth provider supports token revocation, make sure you call those APIs either from the frontend or schedule them to be called on the backend.\n     *\n     * @example Store OAuth provider tokens on sign in\n     * ```js\n     * // Register this immediately after calling createClient!\n     * // Because signInWithOAuth causes a redirect, you need to fetch the\n     * // provider tokens from the callback.\n     * supabase.auth.onAuthStateChange((event, session) => {\n     *   if (session && session.provider_token) {\n     *     window.localStorage.setItem('oauth_provider_token', session.provider_token)\n     *   }\n     *\n     *   if (session && session.provider_refresh_token) {\n     *     window.localStorage.setItem('oauth_provider_refresh_token', session.provider_refresh_token)\n     *   }\n     *\n     *   if (event === 'SIGNED_OUT') {\n     *     window.localStorage.removeItem('oauth_provider_token')\n     *     window.localStorage.removeItem('oauth_provider_refresh_token')\n     *   }\n     * })\n     * ```\n     *\n     * @exampleDescription Use React Context for the User's session\n     * Instead of relying on `supabase.auth.getSession()` within your React components, you can use a [React Context](https://react.dev/reference/react/createContext) to store the latest session information from the `onAuthStateChange` callback and access it that way.\n     *\n     * @example Use React Context for the User's session\n     * ```js\n     * const SessionContext = React.createContext(null)\n     *\n     * function main() {\n     *   const [session, setSession] = React.useState(null)\n     *\n     *   React.useEffect(() => {\n     *     const {data: { subscription }} = supabase.auth.onAuthStateChange(\n     *       (event, session) => {\n     *         if (event === 'SIGNED_OUT') {\n     *           setSession(null)\n     *         } else if (session) {\n     *           setSession(session)\n     *         }\n     *       })\n     *\n     *     return () => {\n     *       subscription.unsubscribe()\n     *     }\n     *   }, [])\n     *\n     *   return (\n     *     <SessionContext.Provider value={session}>\n     *       <App />\n     *     </SessionContext.Provider>\n     *   )\n     * }\n     * ```\n     *\n     * @example Listen to password recovery events\n     * ```js\n     * supabase.auth.onAuthStateChange((event, session) => {\n     *   if (event === 'PASSWORD_RECOVERY') {\n     *     console.log('PASSWORD_RECOVERY', session)\n     *     // show screen to update user's password\n     *     showPasswordResetScreen(true)\n     *   }\n     * })\n     * ```\n     *\n     * @example Listen to sign in\n     * ```js\n     * supabase.auth.onAuthStateChange((event, session) => {\n     *   if (event === 'SIGNED_IN') console.log('SIGNED_IN', session)\n     * })\n     * ```\n     *\n     * @example Listen to token refresh\n     * ```js\n     * supabase.auth.onAuthStateChange((event, session) => {\n     *   if (event === 'TOKEN_REFRESHED') console.log('TOKEN_REFRESHED', session)\n     * })\n     * ```\n     *\n     * @example Listen to user updates\n     * ```js\n     * supabase.auth.onAuthStateChange((event, session) => {\n     *   if (event === 'USER_UPDATED') console.log('USER_UPDATED', session)\n     * })\n     * ```\n     */\n    onAuthStateChange(callback) {\n        const id = generateCallbackId();\n        const subscription = {\n            id,\n            callback,\n            unsubscribe: () => {\n                this._debug('#unsubscribe()', 'state change callback with id removed', id);\n                this.stateChangeEmitters.delete(id);\n            },\n        };\n        this._debug('#onAuthStateChange()', 'registered callback with id', id);\n        this.stateChangeEmitters.set(id, subscription);\n        (async () => {\n            await this.initializePromise;\n            if (this.lock != null) {\n                // TODO(v3): remove legacy lock path\n                await this._acquireLock(this.lockAcquireTimeout, async () => {\n                    this._emitInitialSession(id);\n                });\n            }\n            else {\n                await this._emitInitialSession(id);\n            }\n        })();\n        return { data: { subscription } };\n    }\n    async _emitInitialSession(id) {\n        return await this._useSession(async (result) => {\n            var _a, _b;\n            try {\n                const { data: { session }, error, } = result;\n                if (error)\n                    throw error;\n                await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback('INITIAL_SESSION', session));\n                this._debug('INITIAL_SESSION', 'callback id', id, 'session', session);\n            }\n            catch (err) {\n                await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback('INITIAL_SESSION', null));\n                this._debug('INITIAL_SESSION', 'callback id', id, 'error', err);\n                if (isAuthRefreshDiscardedError(err)) {\n                    // Same successful no-op _recoverAndRefresh treats as debug-only: the\n                    // commit guard discarded a refresh because a concurrent signOut\n                    // changed session state mid-flight.\n                    return;\n                }\n                if (isAuthSessionMissingError(err) ||\n                    isAuthRetryableFetchError(err) ||\n                    (isAuthApiError(err) &&\n                        (err.code === 'refresh_token_not_found' ||\n                            err.code === 'refresh_token_already_used' ||\n                            err.code === 'session_expired'))) {\n                    // A missing session, a transient/aborted network failure (e.g. a\n                    // superseded page navigation cancelling the in-flight request), or\n                    // a dead refresh token (e.g. stale SSR cookies) is not an\n                    // application error — warn rather than surface it raw.\n                    console.warn(err);\n                }\n                else {\n                    console.error(err);\n                }\n            }\n        });\n    }\n    /**\n     * Sends a password reset request to an email address. This method supports the PKCE flow.\n     *\n     * @param email The email address of the user.\n     * @param options.redirectTo The URL to send the user to after they click the password reset link.\n     * @param options.captchaToken Verification token received when the user completes the captcha on the site.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - The password reset flow consist of 2 broad steps: (i) Allow the user to login via the password reset link; (ii) Update the user's password.\n     * - The `resetPasswordForEmail()` only sends a password reset link to the user's email.\n     * To update the user's password, see [`updateUser()`](/docs/reference/javascript/auth-updateuser).\n     * - A `PASSWORD_RECOVERY` event will be emitted when the password recovery link is clicked.\n     * You can use [`onAuthStateChange()`](/docs/reference/javascript/auth-onauthstatechange) to listen and invoke a callback function on these events.\n     * - When the user clicks the reset link in the email they are redirected back to your application.\n     * You can configure the URL that the user is redirected to with the `redirectTo` parameter.\n     * See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project.\n     * - After the user has been redirected successfully, prompt them for a new password and call `updateUser()`:\n     * ```js\n     * const { data, error } = await supabase.auth.updateUser({\n     *   password: new_password\n     * })\n     * ```\n     *\n     * @example Reset password\n     * ```js\n     * const { data, error } = await supabase.auth.resetPasswordForEmail(email, {\n     *   redirectTo: 'https://example.com/update-password',\n     * })\n     * ```\n     *\n     * @exampleResponse Reset password\n     * ```json\n     * {\n     *   data: {}\n     *   error: null\n     * }\n     * ```\n     *\n     * @example Reset password (React)\n     * ```js\n     * /**\n     *  * Step 1: Send the user an email to get a password reset token.\n     *  * This email contains a link which sends the user back to your application.\n     *  *\\/\n     * const { data, error } = await supabase.auth\n     *   .resetPasswordForEmail('user@email.com')\n     *\n     * /**\n     *  * Step 2: Once the user is redirected back to your application,\n     *  * ask the user to reset their password.\n     *  *\\/\n     *  useEffect(() => {\n     *    supabase.auth.onAuthStateChange(async (event, session) => {\n     *      if (event == \"PASSWORD_RECOVERY\") {\n     *        const newPassword = prompt(\"What would you like your new password to be?\");\n     *        const { data, error } = await supabase.auth\n     *          .updateUser({ password: newPassword })\n     *\n     *        if (data) alert(\"Password updated successfully!\")\n     *        if (error) alert(\"There was an error updating your password.\")\n     *      }\n     *    })\n     *  }, [])\n     * ```\n     */\n    async resetPasswordForEmail(email, options = {}) {\n        let codeChallenge = null;\n        let codeChallengeMethod = null;\n        let flowId = null;\n        if (this.flowType === 'pkce') {\n            ;\n            [codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod(true // isPasswordRecovery\n            );\n        }\n        try {\n            return await _request(this.fetch, 'POST', `${this.url}/recover`, {\n                body: {\n                    email,\n                    code_challenge: codeChallenge,\n                    code_challenge_method: codeChallengeMethod,\n                    gotrue_meta_security: { captcha_token: options.captchaToken },\n                },\n                headers: this.headers,\n                redirectTo: this._maybeAppendFlowIdToRedirect(options.redirectTo, flowId),\n            });\n        }\n        catch (error) {\n            await removePKCEVerifier(this.storage, this.storageKey, flowId);\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Gets all the identities linked to a user.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - The user needs to be signed in to call `getUserIdentities()`.\n     *\n     * @example Returns a list of identities linked to the user\n     * ```js\n     * const { data, error } = await supabase.auth.getUserIdentities()\n     * ```\n     *\n     * @exampleResponse Returns a list of identities linked to the user\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"identities\": [\n     *       {\n     *         \"identity_id\": \"22222222-2222-2222-2222-222222222222\",\n     *         \"id\": \"2024-01-01T00:00:00Z\",\n     *         \"user_id\": \"2024-01-01T00:00:00Z\",\n     *         \"identity_data\": {\n     *           \"email\": \"example@email.com\",\n     *           \"email_verified\": false,\n     *           \"phone_verified\": false,\n     *           \"sub\": \"11111111-1111-1111-1111-111111111111\"\n     *         },\n     *         \"provider\": \"email\",\n     *         \"last_sign_in_at\": \"2024-01-01T00:00:00Z\",\n     *         \"created_at\": \"2024-01-01T00:00:00Z\",\n     *         \"updated_at\": \"2024-01-01T00:00:00Z\",\n     *         \"email\": \"example@email.com\"\n     *       }\n     *     ]\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     */\n    async getUserIdentities() {\n        var _a;\n        try {\n            const { data, error } = await this.getUser();\n            if (error)\n                throw error;\n            return this._returnResult({ data: { identities: (_a = data.user.identities) !== null && _a !== void 0 ? _a : [] }, error: null });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**  *\n     * @category Auth\n     *\n     * @remarks\n     * - The **Enable Manual Linking** option must be enabled from your [project's authentication settings](/dashboard/project/_/auth/providers).\n     * - The user needs to be signed in to call `linkIdentity()`.\n     * - If the candidate identity is already linked to the existing user or another user, `linkIdentity()` will fail.\n     * - If `linkIdentity` is run in the browser, the user is automatically redirected to the returned URL. On the server, you should handle the redirect.\n     *\n     * @example Link an identity to a user\n     * ```js\n     * const { data, error } = await supabase.auth.linkIdentity({\n     *   provider: 'github'\n     * })\n     * ```\n     *\n     * @exampleResponse Link an identity to a user\n     * ```json\n     * {\n     *   data: {\n     *     provider: 'github',\n     *     url: <PROVIDER_URL_TO_REDIRECT_TO>,\n     *     flowId: <PKCE_FLOW_ID_OR_NULL>\n     *   },\n     *   error: null\n     * }\n     * ```\n     */\n    async linkIdentity(credentials) {\n        if ('token' in credentials) {\n            return this.linkIdentityIdToken(credentials);\n        }\n        return this.linkIdentityOAuth(credentials);\n    }\n    async linkIdentityOAuth(credentials) {\n        var _a;\n        let flowId = null;\n        try {\n            const { data, error } = await this._useSession(async (result) => {\n                var _a, _b, _c, _d, _f;\n                const { data, error } = result;\n                if (error)\n                    throw error;\n                const { url, flowId: urlFlowId } = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, {\n                    redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo,\n                    scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes,\n                    queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams,\n                    skipBrowserRedirect: true,\n                });\n                flowId = urlFlowId;\n                return await _request(this.fetch, 'GET', url, {\n                    headers: this.headers,\n                    jwt: (_f = (_d = data.session) === null || _d === void 0 ? void 0 : _d.access_token) !== null && _f !== void 0 ? _f : undefined,\n                });\n            });\n            if (error)\n                throw error;\n            if (isBrowser() && !((_a = credentials.options) === null || _a === void 0 ? void 0 : _a.skipBrowserRedirect)) {\n                window.location.assign(data === null || data === void 0 ? void 0 : data.url);\n            }\n            return this._returnResult({\n                data: { provider: credentials.provider, url: data === null || data === void 0 ? void 0 : data.url, flowId },\n                error: null,\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({\n                    data: { provider: credentials.provider, url: null, flowId },\n                    error,\n                });\n            }\n            throw error;\n        }\n    }\n    async linkIdentityIdToken(credentials) {\n        return await this._useSession(async (result) => {\n            var _a;\n            try {\n                const { error: sessionError, data: { session }, } = result;\n                if (sessionError)\n                    throw sessionError;\n                const { options, provider, token, access_token, nonce } = credentials;\n                const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, {\n                    headers: this.headers,\n                    jwt: (_a = session === null || session === void 0 ? void 0 : session.access_token) !== null && _a !== void 0 ? _a : undefined,\n                    body: {\n                        provider,\n                        id_token: token,\n                        access_token,\n                        nonce,\n                        link_identity: true,\n                        gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },\n                    },\n                    xform: _sessionResponse,\n                });\n                const { data, error } = res;\n                if (error) {\n                    return this._returnResult({ data: { user: null, session: null }, error });\n                }\n                else if (!data || !data.session || !data.user) {\n                    return this._returnResult({\n                        data: { user: null, session: null },\n                        error: new AuthInvalidTokenResponseError(),\n                    });\n                }\n                if (data.session) {\n                    await this._saveSession(data.session);\n                    await this._notifyAllSubscribers('USER_UPDATED', data.session);\n                }\n                return this._returnResult({ data, error });\n            }\n            catch (error) {\n                await removePKCEVerifier(this.storage, this.storageKey, null);\n                if (isAuthError(error)) {\n                    return this._returnResult({ data: { user: null, session: null }, error });\n                }\n                throw error;\n            }\n        });\n    }\n    /**\n     * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - The **Enable Manual Linking** option must be enabled from your [project's authentication settings](/dashboard/project/_/auth/providers).\n     * - The user needs to be signed in to call `unlinkIdentity()`.\n     * - The user must have at least 2 identities in order to unlink an identity.\n     * - The identity to be unlinked must belong to the user.\n     *\n     * @example Unlink an identity\n     * ```js\n     * // retrieve all identities linked to a user\n     * const identities = await supabase.auth.getUserIdentities()\n     *\n     * // find the google identity\n     * const googleIdentity = identities.find(\n     *   identity => identity.provider === 'google'\n     * )\n     *\n     * // unlink the google identity\n     * const { error } = await supabase.auth.unlinkIdentity(googleIdentity)\n     * ```\n     */\n    async unlinkIdentity(identity) {\n        try {\n            return await this._useSession(async (result) => {\n                var _a, _b;\n                const { data, error } = result;\n                if (error) {\n                    throw error;\n                }\n                return await _request(this.fetch, 'DELETE', `${this.url}/user/identities/${identity.identity_id}`, {\n                    headers: this.headers,\n                    jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : undefined,\n                });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Generates a new JWT.\n     * @param refreshToken A valid refresh token that was returned on login.\n     */\n    async _refreshAccessToken(refreshToken) {\n        // Refresh tokens are long-lived bearer credentials; do NOT include any\n        // fragment of the token in the debug tag, even when `debug: true` is\n        // enabled (logs may be forwarded to third-party services).\n        const debugName = `#_refreshAccessToken()`;\n        this._debug(debugName, 'begin');\n        try {\n            const startedAt = Date.now();\n            // will attempt to refresh the token with exponential backoff\n            return await retryable(async (attempt) => {\n                if (attempt > 0) {\n                    await sleep(200 * Math.pow(2, attempt - 1)); // 200, 400, 800, ...\n                }\n                this._debug(debugName, 'refreshing attempt', attempt);\n                return await _request(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, {\n                    body: { refresh_token: refreshToken },\n                    headers: this.headers,\n                    xform: _sessionResponse,\n                });\n            }, (attempt, error) => {\n                const nextBackOffInterval = 200 * Math.pow(2, attempt);\n                return (error &&\n                    isAuthRetryableFetchError(error) &&\n                    // retryable only if the request can be sent before the backoff overflows the tick duration\n                    Date.now() + nextBackOffInterval - startedAt < AUTO_REFRESH_TICK_DURATION_MS);\n            });\n        }\n        catch (error) {\n            this._debug(debugName, 'error', error);\n            if (isAuthError(error)) {\n                return this._returnResult({ data: { session: null, user: null }, error });\n            }\n            throw error;\n        }\n        finally {\n            this._debug(debugName, 'end');\n        }\n    }\n    _isValidSession(maybeSession) {\n        const isValidSession = typeof maybeSession === 'object' &&\n            maybeSession !== null &&\n            'access_token' in maybeSession &&\n            'refresh_token' in maybeSession &&\n            'expires_at' in maybeSession;\n        return isValidSession;\n    }\n    async _handleProviderSignIn(provider, options) {\n        const { url, flowId } = await this._getUrlForProvider(`${this.url}/authorize`, provider, {\n            redirectTo: options.redirectTo,\n            scopes: options.scopes,\n            queryParams: options.queryParams,\n        });\n        this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url);\n        // try to open on the browser\n        if (isBrowser() && !options.skipBrowserRedirect) {\n            window.location.assign(url);\n        }\n        return { data: { provider, url, flowId }, error: null };\n    }\n    /**\n     * Recovers the session from LocalStorage and refreshes the token\n     * Note: this method is async to accommodate for AsyncStorage e.g. in React native.\n     */\n    async _recoverAndRefresh() {\n        var _a, _b;\n        const debugName = '#_recoverAndRefresh()';\n        this._debug(debugName, 'begin');\n        try {\n            const currentSession = (await getItemAsync(this.storage, this.storageKey));\n            if (currentSession && this.userStorage) {\n                let maybeUser = (await getItemAsync(this.userStorage, this.storageKey + '-user'));\n                if (!this.storage.isServer && Object.is(this.storage, this.userStorage) && !maybeUser) {\n                    // storage and userStorage are the same storage medium, for example\n                    // window.localStorage if userStorage does not have the user from\n                    // storage stored, store it first thereby migrating the user object\n                    // from storage -> userStorage\n                    maybeUser = { user: currentSession.user };\n                    await setItemAsync(this.userStorage, this.storageKey + '-user', maybeUser);\n                }\n                currentSession.user = (_a = maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) !== null && _a !== void 0 ? _a : userNotAvailableProxy();\n            }\n            else if (currentSession && !currentSession.user) {\n                // user storage is not set, let's check if it was previously enabled so\n                // we bring back the storage as it should be\n                if (!currentSession.user) {\n                    // test if userStorage was previously enabled and the storage medium was the same, to move the user back under the same key\n                    const separateUser = (await getItemAsync(this.storage, this.storageKey + '-user'));\n                    if (separateUser && (separateUser === null || separateUser === void 0 ? void 0 : separateUser.user)) {\n                        currentSession.user = separateUser.user;\n                        await removeItemAsync(this.storage, this.storageKey + '-user');\n                        await setItemAsync(this.storage, this.storageKey, currentSession);\n                    }\n                    else {\n                        currentSession.user = userNotAvailableProxy();\n                    }\n                }\n            }\n            this._debug(debugName, 'session from storage', currentSession);\n            if (!this._isValidSession(currentSession)) {\n                this._debug(debugName, 'session is not valid');\n                if (currentSession !== null) {\n                    await this._removeSession();\n                }\n                return;\n            }\n            const expiresWithMargin = ((_b = currentSession.expires_at) !== null && _b !== void 0 ? _b : Infinity) * 1000 - Date.now() < EXPIRY_MARGIN_MS;\n            this._debug(debugName, `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${EXPIRY_MARGIN_MS}s`);\n            if (expiresWithMargin) {\n                if (this.autoRefreshToken && currentSession.refresh_token) {\n                    const { error } = await this._callRefreshToken(currentSession.refresh_token);\n                    if (error) {\n                        // `_callRefreshToken` is the single source of truth for refresh\n                        // outcomes: it removes the session itself when the access token\n                        // is actually expired, and preserves it when the token is still\n                        // valid (proactive-preserve). Don't second-guess that here — a\n                        // local `_removeSession` would emit a duplicate `SIGNED_OUT` on\n                        // genuine failures and undo the proactive-preserve at init time.\n                        if (isAuthRefreshDiscardedError(error)) {\n                            this._debug(debugName, 'refresh discarded by commit guard', error);\n                        }\n                        else {\n                            this._debug(debugName, 'refresh failed', error);\n                        }\n                    }\n                }\n            }\n            else if (currentSession.user &&\n                currentSession.user.__isUserNotAvailableProxy === true) {\n                // If we have a proxy user, try to get the real user data\n                try {\n                    const { data, error: userError } = await this._getUser(currentSession.access_token);\n                    if (!userError && (data === null || data === void 0 ? void 0 : data.user)) {\n                        currentSession.user = data.user;\n                        await this._saveSession(currentSession);\n                        await this._notifyAllSubscribers('SIGNED_IN', currentSession);\n                    }\n                    else {\n                        this._debug(debugName, 'could not get user data, skipping SIGNED_IN notification');\n                    }\n                }\n                catch (getUserError) {\n                    console.error('Error getting user data:', getUserError);\n                    this._debug(debugName, 'error getting user data, skipping SIGNED_IN notification', getUserError);\n                }\n            }\n            else {\n                // no need to persist currentSession again, as we just loaded it from\n                // local storage; persisting it again may overwrite a value saved by\n                // another client with access to the same local storage\n                await this._notifyAllSubscribers('SIGNED_IN', currentSession);\n            }\n        }\n        catch (err) {\n            this._debug(debugName, 'error', err);\n            if (isAuthRetryableFetchError(err)) {\n                // Transient/aborted network failure during session recovery (e.g. a\n                // superseded page navigation cancelling the in-flight request). Warn\n                // rather than surface it raw; the session is untouched and recovery\n                // will run again on the next load.\n                console.warn(err);\n            }\n            else {\n                console.error(err);\n            }\n            return;\n        }\n        finally {\n            this._debug(debugName, 'end');\n        }\n    }\n    async _callRefreshToken(refreshToken) {\n        var _a, _b;\n        if (!refreshToken) {\n            throw new AuthSessionMissingError();\n        }\n        // refreshing is already in progress\n        if (this.refreshingDeferred) {\n            return this.refreshingDeferred.promise;\n        }\n        // Serial failure cooldown: callers passing the *same* refresh token\n        // after a recent failure receive the cached result instead of firing\n        // another `/token` request. This caps the proactive-refresh storm\n        // where every `getSession()` call inside the 90s EXPIRY_MARGIN_MS\n        // window kept re-firing against the same broken refresh token during\n        // outages. Concurrent callers already share `refreshingDeferred`; this\n        // cache covers serial callers spaced across cooldown windows.\n        //\n        // Token-keyed so callers with a fresh refresh token (rotation pickup\n        // from another tab, explicit `setSession`/`refreshSession({ refresh_token })`,\n        // multi-account switch) bypass the cache and attempt a real refresh.\n        if (this.lastRefreshFailure &&\n            this.lastRefreshFailure.refreshToken === refreshToken &&\n            Date.now() < this.lastRefreshFailure.expiresAt) {\n            this._debug('#_callRefreshToken()', 'returning cached failure (cooldown active)');\n            return this.lastRefreshFailure.result;\n        }\n        // Refresh tokens are long-lived bearer credentials; do NOT include any\n        // fragment of the token in the debug tag, even when `debug: true` is\n        // enabled (logs may be forwarded to third-party services).\n        const debugName = `#_callRefreshToken()`;\n        this._debug(debugName, 'begin');\n        try {\n            this.refreshingDeferred = new Deferred();\n            // Only callers that arrive while this refresh is in flight await the\n            // deferred; the original caller is served by the `throw` in the catch\n            // below. Pre-attach a no-op rejection handler so a failing refresh with\n            // no concurrent callers cannot surface as an unhandled rejection —\n            // concurrent callers attach their own handlers via `.promise` and still\n            // observe the rejection.\n            this.refreshingDeferred.promise.then(undefined, () => { });\n            // Snapshot storage before the fetch. The commit guard discards the\n            // rotated tokens only when a non-null pre-fetch snapshot changed under\n            // us — typical case: a concurrent `signOut` ran `_removeSession`, or\n            // another tab's refresh rewrote the slot. Callers passing\n            // externally-sourced tokens (SSR cookie handoff, multi-account\n            // switching, `setSession`/`refreshSession({ refresh_token })`) may\n            // start from a null snapshot OR from a non-null snapshot whose\n            // refresh_token differs from the one they're hydrating; in both\n            // cases the guard fires only when storage was *modified between\n            // snapshots*, not when the input token disagrees with what's stored.\n            const storedAtStart = (await getItemAsync(this.storage, this.storageKey));\n            const { data, error } = await this._refreshAccessToken(refreshToken);\n            if (error)\n                throw error;\n            if (!data.session)\n                throw new AuthSessionMissingError();\n            const storedAfter = (await getItemAsync(this.storage, this.storageKey));\n            const storageChangedUnderUs = storedAtStart !== null &&\n                (storedAfter === null || storedAfter.refresh_token !== storedAtStart.refresh_token);\n            if (storageChangedUnderUs) {\n                this._debug(debugName, 'commit guard: storage changed since refresh started, discarding rotated tokens', {\n                    // Presence indicators only — never log refresh token fragments,\n                    // even partial. Logs may be forwarded to third-party services.\n                    startedWith: 'present',\n                    nowHolds: storedAfter ? 'replaced' : 'cleared',\n                });\n                const discarded = {\n                    data: null,\n                    error: new AuthRefreshDiscardedError(),\n                };\n                this.refreshingDeferred.resolve(discarded);\n                return discarded;\n            }\n            // Second leg of the commit guard: close the TOCTOU window between the\n            // synchronous `storageChangedUnderUs` check and the actual storage\n            // writes inside `_saveSession`. A concurrent `signOut → _removeSession`\n            // can land inside `_saveSession`'s `await setItemAsync(...)` yields and\n            // clear storage just before we overwrite it. Capture the epoch BEFORE\n            // the save and re-check after; if it advanced, undo the write directly\n            // (do NOT call `_removeSession` — that would emit a duplicate\n            // SIGNED_OUT for the concurrent signOut that already fired one).\n            const epochBeforeSave = this._sessionRemovalEpoch;\n            await this._saveSession(data.session);\n            if (this._sessionRemovalEpoch !== epochBeforeSave) {\n                this._debug(debugName, 'commit guard (post-save): _removeSession ran during _saveSession, undoing write');\n                await removeItemAsync(this.storage, this.storageKey);\n                if (this.userStorage) {\n                    await removeItemAsync(this.userStorage, this.storageKey + '-user');\n                }\n                const discarded = {\n                    data: null,\n                    error: new AuthRefreshDiscardedError(),\n                };\n                this.refreshingDeferred.resolve(discarded);\n                return discarded;\n            }\n            await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session);\n            const result = { data: data.session, error: null };\n            // Refresh succeeded — clear any cached failure so the next caller\n            // (including the auto-refresh ticker) attempts a real refresh again.\n            this.lastRefreshFailure = null;\n            this.refreshingDeferred.resolve(result);\n            return result;\n        }\n        catch (error) {\n            this._debug(debugName, 'error', error);\n            if (isAuthError(error)) {\n                const result = { data: null, error };\n                if (!isAuthRetryableFetchError(error)) {\n                    // Proactive vs reactive distinction: a refresh fires whenever\n                    // the access token is within EXPIRY_MARGIN_MS of expiry. If the\n                    // access token is *still valid* at this moment, the refresh was\n                    // proactive and the existing session is still usable until its\n                    // real expiry — destroying it now would log out a user whose\n                    // access token works. If the access token has actually expired,\n                    // the refresh token is the only credential left and it just got\n                    // rejected — the session is genuinely dead. `__loadSession`\n                    // mirrors this distinction on the read path so callers see the\n                    // preserved session instead of `session: null`.\n                    const storedNow = (await getItemAsync(this.storage, this.storageKey));\n                    const accessTokenStillValid = !!((storedNow === null || storedNow === void 0 ? void 0 : storedNow.expires_at) && storedNow.expires_at * 1000 > Date.now());\n                    if (accessTokenStillValid) {\n                        this._debug(debugName, 'proactive refresh failed, access token still valid — preserving session');\n                    }\n                    else {\n                        await this._removeSession();\n                    }\n                }\n                // Cache the failure so serial callers (and the next auto-refresh\n                // tick) passing the same refresh token within the cooldown window\n                // receive it synchronously instead of firing another `/token`\n                // call. Set after the optional `_removeSession` above (which\n                // clears the cache as part of teardown) so the cache survives.\n                this.lastRefreshFailure = {\n                    refreshToken,\n                    result,\n                    expiresAt: Date.now() + REFRESH_FAILURE_COOLDOWN_MS,\n                };\n                (_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result);\n                return result;\n            }\n            (_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error);\n            throw error;\n        }\n        finally {\n            this.refreshingDeferred = null;\n            this._debug(debugName, 'end');\n        }\n    }\n    async _notifyAllSubscribers(event, session, broadcast = true) {\n        if (this._pendingInitNotifications !== null && broadcast) {\n            // We're inside initialize() before initializePromise has resolved, and\n            // this notification originates from the init chain (_recoverAndRefresh),\n            // which always fires with broadcast = true. Enqueue instead of firing so\n            // that callbacks can safely call getSession() / getUser() without\n            // deadlocking on initializePromise.\n            //\n            // Notifications with broadcast = false come from the incoming\n            // BroadcastChannel handler (a cross-tab event), not the init chain, so\n            // they are fired immediately to preserve multi-tab ordering.\n            this._pendingInitNotifications.push({ event, session, broadcast });\n            return;\n        }\n        const debugName = `#_notifyAllSubscribers(${event})`;\n        this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`);\n        try {\n            if (this.broadcastChannel && broadcast) {\n                this.broadcastChannel.postMessage({ event, session });\n            }\n            const errors = [];\n            const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => {\n                try {\n                    await x.callback(event, session);\n                }\n                catch (e) {\n                    errors.push(e);\n                }\n            });\n            await Promise.all(promises);\n            if (errors.length > 0) {\n                for (let i = 0; i < errors.length; i += 1) {\n                    console.error(errors[i]);\n                }\n                throw errors[0];\n            }\n        }\n        finally {\n            this._debug(debugName, 'end');\n        }\n    }\n    /**\n     * set currentSession and currentUser\n     * process to _startAutoRefreshToken if possible\n     */\n    async _saveSession(session) {\n        this._debug('#_saveSession()', session);\n        // _saveSession is always called whenever a new session has been acquired\n        // so we can safely suppress the warning returned by future getSession calls\n        this.suppressGetSessionWarning = true;\n        // Create a shallow copy to work with, to avoid mutating the original session object if it's used elsewhere\n        const sessionToProcess = Object.assign({}, session);\n        const userIsProxy = sessionToProcess.user && sessionToProcess.user.__isUserNotAvailableProxy === true;\n        if (this.userStorage) {\n            if (!userIsProxy && sessionToProcess.user) {\n                // If it's a real user object, save it to userStorage.\n                await setItemAsync(this.userStorage, this.storageKey + '-user', {\n                    user: sessionToProcess.user,\n                });\n            }\n            else if (userIsProxy) {\n                // If it's the proxy, it means user was not found in userStorage.\n                // We should ensure no stale user data for this key exists in userStorage if we were to save null,\n                // or simply not save the proxy. For now, we don't save the proxy here.\n                // If there's a need to clear userStorage if user becomes proxy, that logic would go here.\n            }\n            // Prepare the main session data for primary storage: remove the user property before cloning\n            // This is important because the original session.user might be the proxy\n            const mainSessionData = Object.assign({}, sessionToProcess);\n            delete mainSessionData.user; // Remove user (real or proxy) before cloning for main storage\n            const clonedMainSessionData = deepClone(mainSessionData);\n            await setItemAsync(this.storage, this.storageKey, clonedMainSessionData);\n        }\n        else {\n            // No userStorage is configured.\n            // In this case, session.user should ideally not be a proxy.\n            // If it were, structuredClone would fail. This implies an issue elsewhere if user is a proxy here\n            const clonedSession = deepClone(sessionToProcess); // sessionToProcess still has its original user property\n            await setItemAsync(this.storage, this.storageKey, clonedSession);\n        }\n    }\n    async _removeSession() {\n        // Bump synchronously, BEFORE any `await`, so that `_callRefreshToken`'s\n        // post-save check sees the increment whenever this method has started —\n        // even if it hasn't finished. Pairs with the epoch check in\n        // `_callRefreshToken`. See `_sessionRemovalEpoch` field doc.\n        this._sessionRemovalEpoch += 1;\n        this._debug('#_removeSession()');\n        // The session is gone — no point holding on to a cached refresh failure\n        // for a token that no longer exists. Synchronous, before any `await`.\n        this.lastRefreshFailure = null;\n        this.suppressGetSessionWarning = false;\n        await removeItemAsync(this.storage, this.storageKey);\n        await removeAllPKCEVerifiers(this.storage, this.storageKey);\n        await removeItemAsync(this.storage, this.storageKey + '-user');\n        if (this.userStorage) {\n            await removeItemAsync(this.userStorage, this.storageKey + '-user');\n        }\n        await this._notifyAllSubscribers('SIGNED_OUT', null);\n    }\n    /**\n     * Removes any registered visibilitychange callback.\n     *\n     * {@link GoTrueClient.startAutoRefresh}\n     * {@link GoTrueClient.stopAutoRefresh}\n     */\n    _removeVisibilityChangedCallback() {\n        this._debug('#_removeVisibilityChangedCallback()');\n        const callback = this.visibilityChangedCallback;\n        this.visibilityChangedCallback = null;\n        try {\n            if (callback && isBrowser() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) {\n                window.removeEventListener('visibilitychange', callback);\n            }\n        }\n        catch (e) {\n            console.error('removing visibilitychange callback failed', e);\n        }\n    }\n    /**\n     * This is the private implementation of {@link GoTrueClient.startAutoRefresh}. Use this\n     * within the library.\n     */\n    async _startAutoRefresh() {\n        await this._stopAutoRefresh();\n        this._debug('#_startAutoRefresh()');\n        const ticker = setInterval(() => this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION_MS);\n        this.autoRefreshTicker = ticker;\n        if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') {\n            // ticker is a NodeJS Timeout object that has an `unref` method\n            // https://nodejs.org/api/timers.html#timeoutunref\n            // When auto refresh is used in NodeJS (like for testing) the\n            // `setInterval` is preventing the process from being marked as\n            // finished and tests run endlessly. This can be prevented by calling\n            // `unref()` on the returned object.\n            ticker.unref();\n            // @ts-expect-error TS has no context of Deno\n        }\n        else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') {\n            // similar like for NodeJS, but with the Deno API\n            // https://deno.land/api@latest?unstable&s=Deno.unrefTimer\n            // @ts-expect-error TS has no context of Deno\n            Deno.unrefTimer(ticker);\n        }\n        // run the tick immediately, but in the next pass of the event loop so that\n        // #_initialize can be allowed to complete without recursively waiting on\n        // itself\n        const timeout = setTimeout(async () => {\n            await this.initializePromise;\n            await this._autoRefreshTokenTick();\n        }, 0);\n        this.autoRefreshTickTimeout = timeout;\n        if (timeout && typeof timeout === 'object' && typeof timeout.unref === 'function') {\n            timeout.unref();\n            // @ts-expect-error TS has no context of Deno\n        }\n        else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') {\n            // @ts-expect-error TS has no context of Deno\n            Deno.unrefTimer(timeout);\n        }\n    }\n    /**\n     * This is the private implementation of {@link GoTrueClient.stopAutoRefresh}. Use this\n     * within the library.\n     */\n    async _stopAutoRefresh() {\n        this._debug('#_stopAutoRefresh()');\n        const ticker = this.autoRefreshTicker;\n        this.autoRefreshTicker = null;\n        if (ticker) {\n            clearInterval(ticker);\n        }\n        const timeout = this.autoRefreshTickTimeout;\n        this.autoRefreshTickTimeout = null;\n        if (timeout) {\n            clearTimeout(timeout);\n        }\n    }\n    /**\n     * Starts an auto-refresh process in the background. The session is checked\n     * every few seconds. Close to the time of expiration a process is started to\n     * refresh the session. If refreshing fails it will be retried for as long as\n     * necessary.\n     *\n     * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need\n     * to call this function, it will be called for you.\n     *\n     * On browsers the refresh process works only when the tab/window is in the\n     * foreground to conserve resources as well as prevent race conditions and\n     * flooding auth with requests. If you call this method any managed\n     * visibility change callback will be removed and you must manage visibility\n     * changes on your own.\n     *\n     * On non-browser platforms the refresh process works *continuously* in the\n     * background, which may not be desirable. You should hook into your\n     * platform's foreground indication mechanism and call these methods\n     * appropriately to conserve resources.\n     *\n     * {@link GoTrueClient.stopAutoRefresh}\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - Only useful in non-browser environments such as React Native or Electron.\n     * - The Supabase Auth library automatically starts and stops proactively refreshing the session when a tab is focused or not.\n     * - On non-browser platforms, such as mobile or desktop apps built with web technologies, the library is not able to effectively determine whether the application is _focused_ or not.\n     * - To give this hint to the application, you should be calling this method when the app is in focus and calling `supabase.auth.stopAutoRefresh()` when it's out of focus.\n     *\n     * @example Start and stop auto refresh in React Native\n     * ```js\n     * import { AppState } from 'react-native'\n     *\n     * // make sure you register this only once!\n     * AppState.addEventListener('change', (state) => {\n     *   if (state === 'active') {\n     *     supabase.auth.startAutoRefresh()\n     *   } else {\n     *     supabase.auth.stopAutoRefresh()\n     *   }\n     * })\n     * ```\n     */\n    async startAutoRefresh() {\n        this._removeVisibilityChangedCallback();\n        await this._startAutoRefresh();\n    }\n    /**\n     * Stops an active auto refresh process running in the background (if any).\n     *\n     * If you call this method any managed visibility change callback will be\n     * removed and you must manage visibility changes on your own.\n     *\n     * See {@link GoTrueClient.startAutoRefresh} for more details.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - Only useful in non-browser environments such as React Native or Electron.\n     * - The Supabase Auth library automatically starts and stops proactively refreshing the session when a tab is focused or not.\n     * - On non-browser platforms, such as mobile or desktop apps built with web technologies, the library is not able to effectively determine whether the application is _focused_ or not.\n     * - When your application goes in the background or out of focus, call this method to stop the proactive refreshing of the session.\n     *\n     * @example Start and stop auto refresh in React Native\n     * ```js\n     * import { AppState } from 'react-native'\n     *\n     * // make sure you register this only once!\n     * AppState.addEventListener('change', (state) => {\n     *   if (state === 'active') {\n     *     supabase.auth.startAutoRefresh()\n     *   } else {\n     *     supabase.auth.stopAutoRefresh()\n     *   }\n     * })\n     * ```\n     */\n    async stopAutoRefresh() {\n        this._removeVisibilityChangedCallback();\n        await this._stopAutoRefresh();\n    }\n    /**\n     * Tears down the client's background work: stops the auto-refresh interval,\n     * removes the `visibilitychange` listener, closes the cross-tab\n     * `BroadcastChannel`, and clears registered `onAuthStateChange` subscribers.\n     *\n     * Call this from cleanup hooks when the client is being replaced before\n     * its JS realm is destroyed. React Strict Mode and HMR are the common\n     * cases. Any in-flight `fetch` calls continue to completion and may still\n     * write to storage; dispose doesn't abort them or erase storage.\n     *\n     * Lifecycle caveat: because in-flight refreshes are not aborted, a\n     * disposed instance can still persist a rotated session to storage after\n     * `dispose()` returns. A subsequent `createClient` against the same\n     * `storageKey` will pick up that session on its next read. If you need\n     * strict isolation between client lifecycles, await any pending auth\n     * operation before calling `dispose()` (or change the `storageKey` for\n     * the replacement client).\n     *\n     * Safe to call repeatedly.\n     *\n     * @category Auth\n     *\n     * @example Cleanup on React unmount\n     * ```ts\n     * useEffect(() => {\n     *   const client = createClient(...)\n     *   return () => { client.auth.dispose() }\n     * }, [])\n     * ```\n     */\n    async dispose() {\n        var _a;\n        this._removeVisibilityChangedCallback();\n        await this._stopAutoRefresh();\n        (_a = this.broadcastChannel) === null || _a === void 0 ? void 0 : _a.close();\n        this.broadcastChannel = null;\n        this.stateChangeEmitters.clear();\n    }\n    /**\n     * Runs the auto refresh token tick.\n     */\n    async _autoRefreshTokenTick() {\n        this._debug('#_autoRefreshTokenTick()', 'begin');\n        if (this.lock != null) {\n            // TODO(v3): remove legacy lock path. Uses `_acquireLock(0, ...)` which\n            // throws `LockAcquireTimeoutError` immediately if the lock is held —\n            // that's the fail-fast skip path that lets the tick bail out instead\n            // of queuing behind a long-running operation.\n            try {\n                await this._acquireLock(0, async () => {\n                    try {\n                        const now = Date.now();\n                        try {\n                            return await this._useSession(async (result) => {\n                                const { data: { session }, } = result;\n                                if (!session || !session.refresh_token || !session.expires_at) {\n                                    this._debug('#_autoRefreshTokenTick()', 'no session');\n                                    return;\n                                }\n                                const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION_MS);\n                                this._debug('#_autoRefreshTokenTick()', `access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`);\n                                if (expiresInTicks <= AUTO_REFRESH_TICK_THRESHOLD) {\n                                    await this._callRefreshToken(session.refresh_token);\n                                }\n                            });\n                        }\n                        catch (e) {\n                            console.error('Auto refresh tick failed with error. This is likely a transient error.', e);\n                        }\n                    }\n                    finally {\n                        this._debug('#_autoRefreshTokenTick()', 'end');\n                    }\n                });\n            }\n            catch (e) {\n                if (e instanceof LockAcquireTimeoutError) {\n                    this._debug('auto refresh token tick lock not available');\n                }\n                else {\n                    throw e;\n                }\n            }\n            return;\n        }\n        // Lockless default: skip if a refresh is already in flight.\n        // `_callRefreshToken` also dedupes via the same field; this is just a\n        // fast-path skip to avoid an unnecessary storage read.\n        if (this.refreshingDeferred !== null) {\n            this._debug('#_autoRefreshTokenTick()', 'refresh already in flight, skipping');\n            return;\n        }\n        try {\n            const now = Date.now();\n            try {\n                await this._useSession(async (result) => {\n                    const { data: { session }, } = result;\n                    if (!session || !session.refresh_token || !session.expires_at) {\n                        this._debug('#_autoRefreshTokenTick()', 'no session');\n                        return;\n                    }\n                    // session will expire in this many ticks (or has already expired if <= 0)\n                    const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION_MS);\n                    this._debug('#_autoRefreshTokenTick()', `access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`);\n                    if (expiresInTicks <= AUTO_REFRESH_TICK_THRESHOLD) {\n                        await this._callRefreshToken(session.refresh_token);\n                    }\n                });\n            }\n            catch (e) {\n                console.error('Auto refresh tick failed with error. This is likely a transient error.', e);\n            }\n        }\n        finally {\n            this._debug('#_autoRefreshTokenTick()', 'end');\n        }\n    }\n    /**\n     * Registers callbacks on the browser / platform, which in-turn run\n     * algorithms when the browser window/tab are in foreground. On non-browser\n     * platforms it assumes always foreground.\n     */\n    async _handleVisibilityChange() {\n        this._debug('#_handleVisibilityChange()');\n        if (!isBrowser() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) {\n            if (this.autoRefreshToken) {\n                // in non-browser environments the refresh token ticker runs always\n                this.startAutoRefresh();\n            }\n            return false;\n        }\n        try {\n            this.visibilityChangedCallback = async () => {\n                try {\n                    await this._onVisibilityChanged(false);\n                }\n                catch (error) {\n                    this._debug('#visibilityChangedCallback', 'error', error);\n                }\n            };\n            window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', this.visibilityChangedCallback);\n            // now immediately call the visbility changed callback to setup with the\n            // current visbility state\n            await this._onVisibilityChanged(true); // initial call\n        }\n        catch (error) {\n            console.error('_handleVisibilityChange', error);\n        }\n    }\n    /**\n     * Callback registered with `window.addEventListener('visibilitychange')`.\n     */\n    async _onVisibilityChanged(calledFromInitialize) {\n        const methodName = `#_onVisibilityChanged(${calledFromInitialize})`;\n        this._debug(methodName, 'visibilityState', document.visibilityState);\n        if (document.visibilityState === 'visible') {\n            if (this.autoRefreshToken) {\n                // in browser environments the refresh token ticker runs only on focused tabs\n                // which prevents race conditions\n                this._startAutoRefresh();\n            }\n            if (!calledFromInitialize) {\n                // called when the visibility has changed, i.e. the browser\n                // transitioned from hidden -> visible so we need to see if the session\n                // should be recovered\n                await this.initializePromise;\n                if (this.lock != null) {\n                    // TODO(v3): remove legacy lock path\n                    await this._acquireLock(this.lockAcquireTimeout, async () => {\n                        if (document.visibilityState !== 'visible') {\n                            this._debug(methodName, 'acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting');\n                            return;\n                        }\n                        await this._recoverAndRefresh();\n                    });\n                }\n                else {\n                    if (document.visibilityState !== 'visible') {\n                        this._debug(methodName, 'visibilityState is no longer visible, skipping recovery');\n                        return;\n                    }\n                    // recover the session\n                    await this._recoverAndRefresh();\n                }\n            }\n        }\n        else if (document.visibilityState === 'hidden') {\n            if (this.autoRefreshToken) {\n                this._stopAutoRefresh();\n            }\n        }\n    }\n    /**\n     * Generates the relevant login URL for a third-party provider.\n     * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed.\n     * @param options.scopes A space-separated list of scopes granted to the OAuth application.\n     * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application.\n     */\n    async _getUrlForProvider(url, provider, options) {\n        let redirectTo = options === null || options === void 0 ? void 0 : options.redirectTo;\n        let codeChallenge = null;\n        let codeChallengeMethod = null;\n        let flowId = null;\n        if (this.flowType === 'pkce') {\n            ;\n            [codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod();\n            redirectTo = this._maybeAppendFlowIdToRedirect(redirectTo, flowId);\n        }\n        const urlParams = [`provider=${encodeURIComponent(provider)}`];\n        if (redirectTo) {\n            urlParams.push(`redirect_to=${encodeURIComponent(redirectTo)}`);\n        }\n        if (options === null || options === void 0 ? void 0 : options.scopes) {\n            urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`);\n        }\n        if (codeChallenge != null && codeChallengeMethod != null) {\n            const flowParams = new URLSearchParams({\n                code_challenge: `${encodeURIComponent(codeChallenge)}`,\n                code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`,\n            });\n            urlParams.push(flowParams.toString());\n        }\n        if (options === null || options === void 0 ? void 0 : options.queryParams) {\n            const query = new URLSearchParams(options.queryParams);\n            urlParams.push(query.toString());\n        }\n        if (options === null || options === void 0 ? void 0 : options.skipBrowserRedirect) {\n            urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`);\n        }\n        return { url: `${url}?${urlParams.join('&')}`, flowId };\n    }\n    /**\n     * Appends the reserved flow id parameter to a redirect URL so the callback\n     * can be matched to the verifier stored for its flow. Opt-in via\n     * `experimental.appendPkceFlowIdToRedirects`: redirect URLs are validated\n     * against the project's allow list including the query string, so an extra\n     * parameter can stop exact (non-wildcard) entries from matching.\n     */\n    _maybeAppendFlowIdToRedirect(redirectTo, flowId) {\n        if (!redirectTo || !flowId || !this.experimental.appendPkceFlowIdToRedirects) {\n            return redirectTo !== null && redirectTo !== void 0 ? redirectTo : undefined;\n        }\n        return appendFlowIdToRedirectTo(redirectTo, flowId);\n    }\n    /**\n     * Generates and stores a PKCE challenge/verifier pair for a new flow,\n     * logging any pending verifier the bounded slot ring evicts.\n     */\n    async _getCodeChallengeAndMethod(isPasswordRecovery = false) {\n        return getCodeChallengeAndMethod(this.storage, this.storageKey, isPasswordRecovery, (evictedFlowId) => this._debug('#_getCodeChallengeAndMethod()', 'evicted oldest pending PKCE verifier slot', evictedFlowId));\n    }\n    async _unenroll(params) {\n        try {\n            return await this._useSession(async (result) => {\n                var _a;\n                const { data: sessionData, error: sessionError } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                return await _request(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, {\n                    headers: this.headers,\n                    jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,\n                });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    async _enroll(params) {\n        try {\n            return await this._useSession(async (result) => {\n                var _a, _b;\n                const { data: sessionData, error: sessionError } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                const body = Object.assign({ friendly_name: params.friendlyName, factor_type: params.factorType }, (params.factorType === 'phone'\n                    ? { phone: params.phone }\n                    : params.factorType === 'totp'\n                        ? { issuer: params.issuer }\n                        : {}));\n                const { data, error } = (await _request(this.fetch, 'POST', `${this.url}/factors`, {\n                    body,\n                    headers: this.headers,\n                    jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,\n                }));\n                if (error) {\n                    return this._returnResult({ data: null, error });\n                }\n                if (params.factorType === 'totp' && data.type === 'totp' && ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code)) {\n                    data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`;\n                }\n                return this._returnResult({ data, error: null });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    async _verify(params) {\n        const run = async () => {\n            try {\n                return await this._useSession(async (result) => {\n                    var _a;\n                    const { data: sessionData, error: sessionError } = result;\n                    if (sessionError) {\n                        return this._returnResult({ data: null, error: sessionError });\n                    }\n                    const body = Object.assign({ challenge_id: params.challengeId }, ('webauthn' in params\n                        ? {\n                            webauthn: Object.assign(Object.assign({}, params.webauthn), { credential_response: params.webauthn.type === 'create'\n                                    ? serializeCredentialCreationResponse(params.webauthn.credential_response)\n                                    : serializeCredentialRequestResponse(params.webauthn.credential_response) }),\n                        }\n                        : { code: params.code }));\n                    const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/verify`, {\n                        body,\n                        headers: this.headers,\n                        jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,\n                    });\n                    if (error) {\n                        return this._returnResult({ data: null, error });\n                    }\n                    await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1000) + data.expires_in }, data));\n                    await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data);\n                    return this._returnResult({ data, error });\n                });\n            }\n            catch (error) {\n                if (isAuthError(error)) {\n                    return this._returnResult({ data: null, error });\n                }\n                throw error;\n            }\n        };\n        if (this.lock != null) {\n            // TODO(v3): remove legacy lock path\n            return this._acquireLock(this.lockAcquireTimeout, run);\n        }\n        return run();\n    }\n    async _challenge(params) {\n        const run = async () => {\n            try {\n                return await this._useSession(async (result) => {\n                    var _a;\n                    const { data: sessionData, error: sessionError } = result;\n                    if (sessionError) {\n                        return this._returnResult({ data: null, error: sessionError });\n                    }\n                    const response = (await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/challenge`, {\n                        body: params,\n                        headers: this.headers,\n                        jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,\n                    }));\n                    if (response.error) {\n                        return response;\n                    }\n                    const { data } = response;\n                    if (data.type !== 'webauthn') {\n                        return { data, error: null };\n                    }\n                    switch (data.webauthn.type) {\n                        case 'create':\n                            return {\n                                data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: deserializeCredentialCreationOptions(data.webauthn.credential_options.publicKey) }) }) }),\n                                error: null,\n                            };\n                        case 'request':\n                            return {\n                                data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: deserializeCredentialRequestOptions(data.webauthn.credential_options.publicKey) }) }) }),\n                                error: null,\n                            };\n                    }\n                });\n            }\n            catch (error) {\n                if (isAuthError(error)) {\n                    return this._returnResult({ data: null, error });\n                }\n                throw error;\n            }\n        };\n        if (this.lock != null) {\n            // TODO(v3): remove legacy lock path\n            return this._acquireLock(this.lockAcquireTimeout, run);\n        }\n        return run();\n    }\n    /**\n     * {@link GoTrueMFAApi#challengeAndVerify}\n     */\n    async _challengeAndVerify(params) {\n        const { data: challengeData, error: challengeError } = await this._challenge({\n            factorId: params.factorId,\n        });\n        if (challengeError) {\n            return this._returnResult({ data: null, error: challengeError });\n        }\n        return await this._verify({\n            factorId: params.factorId,\n            challengeId: challengeData.id,\n            code: params.code,\n        });\n    }\n    /**\n     * {@link GoTrueMFAApi#listFactors}\n     */\n    async _listFactors() {\n        var _a;\n        const { data: { user }, error: userError, } = await this.getUser();\n        if (userError) {\n            return { data: null, error: userError };\n        }\n        const data = {\n            all: [],\n            phone: [],\n            totp: [],\n            webauthn: [],\n            recovery_code: [],\n        };\n        // loop over the factors ONCE\n        for (const factor of (_a = user === null || user === void 0 ? void 0 : user.factors) !== null && _a !== void 0 ? _a : []) {\n            data.all.push(factor);\n            // Types that are not recognized are pushed to `all` bucket.\n            if (factor.status === 'verified' &&\n                factor.factor_type in data &&\n                Array.isArray(data[factor.factor_type])) {\n                ;\n                data[factor.factor_type].push(factor);\n            }\n        }\n        return {\n            data,\n            error: null,\n        };\n    }\n    /**\n     * {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel}\n     */\n    async _getAuthenticatorAssuranceLevel(jwt) {\n        var _a, _b, _c, _d;\n        if (jwt) {\n            try {\n                const { payload } = decodeJWT(jwt);\n                let currentLevel = null;\n                if (payload.aal) {\n                    currentLevel = payload.aal;\n                }\n                let nextLevel = currentLevel;\n                const { data: { user }, error: userError, } = await this.getUser(jwt);\n                if (userError) {\n                    return this._returnResult({ data: null, error: userError });\n                }\n                const verifiedFactors = (_b = (_a = user === null || user === void 0 ? void 0 : user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === 'verified')) !== null && _b !== void 0 ? _b : [];\n                if (verifiedFactors.length > 0) {\n                    nextLevel = 'aal2';\n                }\n                const currentAuthenticationMethods = payload.amr || [];\n                return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null };\n            }\n            catch (error) {\n                if (isAuthError(error)) {\n                    return this._returnResult({ data: null, error });\n                }\n                throw error;\n            }\n        }\n        const { data: { session }, error: sessionError, } = await this.getSession();\n        if (sessionError) {\n            return this._returnResult({ data: null, error: sessionError });\n        }\n        if (!session) {\n            return {\n                data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] },\n                error: null,\n            };\n        }\n        const { payload } = decodeJWT(session.access_token);\n        let currentLevel = null;\n        if (payload.aal) {\n            currentLevel = payload.aal;\n        }\n        let nextLevel = currentLevel;\n        const verifiedFactors = (_d = (_c = session.user.factors) === null || _c === void 0 ? void 0 : _c.filter((factor) => factor.status === 'verified')) !== null && _d !== void 0 ? _d : [];\n        if (verifiedFactors.length > 0) {\n            nextLevel = 'aal2';\n        }\n        const currentAuthenticationMethods = payload.amr || [];\n        return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null };\n    }\n    /**\n     * {@link AuthMFARecoveryCodesApi#getStatus}\n     */\n    async _getRecoveryCodesStatus() {\n        assertRecoveryCodesExperimentalEnabled(this.experimental);\n        try {\n            return await this._useSession(async (result) => {\n                var _a;\n                const { data: sessionData, error: sessionError } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                const { data, error } = await _request(this.fetch, 'GET', `${this.url}/factors/recovery-codes`, {\n                    headers: this.headers,\n                    jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,\n                });\n                if (error) {\n                    return this._returnResult({ data: null, error });\n                }\n                return this._returnResult({ data, error: null });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * {@link AuthMFARecoveryCodesApi#generate}\n     */\n    async _generateRecoveryCodes(params) {\n        assertRecoveryCodesExperimentalEnabled(this.experimental);\n        try {\n            return await this._useSession(async (result) => {\n                var _a;\n                const { data: sessionData, error: sessionError } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors/recovery-codes`, {\n                    // The body is optional server-side; only send one when a name was given.\n                    body: (params === null || params === void 0 ? void 0 : params.friendlyName) ? { friendly_name: params.friendlyName } : undefined,\n                    headers: this.headers,\n                    jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,\n                });\n                if (error) {\n                    return this._returnResult({ data: null, error });\n                }\n                return this._returnResult({ data, error: null });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * {@link AuthMFARecoveryCodesApi#verify}\n     */\n    async _verifyRecoveryCode(params) {\n        assertRecoveryCodesExperimentalEnabled(this.experimental);\n        const run = async () => {\n            try {\n                return await this._useSession(async (result) => {\n                    var _a;\n                    const { data: sessionData, error: sessionError } = result;\n                    if (sessionError) {\n                        return this._returnResult({ data: null, error: sessionError });\n                    }\n                    const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors/recovery-codes/verify`, {\n                        body: { code: params.code },\n                        headers: this.headers,\n                        jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,\n                    });\n                    if (error) {\n                        return this._returnResult({ data: null, error });\n                    }\n                    // A server-provided expires_at takes precedence over the computed one.\n                    const session = Object.assign({ expires_at: expiresAt(data.expires_in) }, data);\n                    await this._saveSession(session);\n                    await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', session);\n                    return this._returnResult({ data, error: null });\n                });\n            }\n            catch (error) {\n                if (isAuthError(error)) {\n                    return this._returnResult({ data: null, error });\n                }\n                throw error;\n            }\n        };\n        if (this.lock != null) {\n            return this._acquireLock(this.lockAcquireTimeout, run);\n        }\n        return run();\n    }\n    /**\n     * {@link AuthMFARecoveryCodesApi#regenerate}\n     */\n    async _regenerateRecoveryCodes() {\n        assertRecoveryCodesExperimentalEnabled(this.experimental);\n        try {\n            return await this._useSession(async (result) => {\n                var _a;\n                const { data: sessionData, error: sessionError } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors/recovery-codes/regenerate`, {\n                    headers: this.headers,\n                    jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,\n                });\n                if (error) {\n                    return this._returnResult({ data: null, error });\n                }\n                return this._returnResult({ data, error: null });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * {@link AuthMFARecoveryCodesApi#unenroll}\n     */\n    async _unenrollRecoveryCodes() {\n        assertRecoveryCodesExperimentalEnabled(this.experimental);\n        try {\n            return await this._useSession(async (result) => {\n                var _a;\n                const { data: sessionData, error: sessionError } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                const { data, error } = await _request(this.fetch, 'DELETE', `${this.url}/factors/recovery-codes`, {\n                    headers: this.headers,\n                    jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,\n                });\n                if (error) {\n                    return this._returnResult({ data: null, error });\n                }\n                return this._returnResult({ data, error: null });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Retrieves details about an OAuth authorization request.\n     * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n     *\n     * Returns authorization details including client info, scopes, and user information.\n     * If the response includes only a redirect_url field, it means consent was already given - the caller\n     * should handle the redirect manually if needed.\n     */\n    async _getAuthorizationDetails(authorizationId) {\n        try {\n            return await this._useSession(async (result) => {\n                const { data: { session }, error: sessionError, } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                if (!session) {\n                    return this._returnResult({ data: null, error: new AuthSessionMissingError() });\n                }\n                return await _request(this.fetch, 'GET', `${this.url}/oauth/authorizations/${authorizationId}`, {\n                    headers: this.headers,\n                    jwt: session.access_token,\n                    xform: (data) => ({ data, error: null }),\n                });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Approves an OAuth authorization request.\n     * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n     */\n    async _approveAuthorization(authorizationId, options) {\n        try {\n            return await this._useSession(async (result) => {\n                const { data: { session }, error: sessionError, } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                if (!session) {\n                    return this._returnResult({ data: null, error: new AuthSessionMissingError() });\n                }\n                const response = await _request(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, {\n                    headers: this.headers,\n                    jwt: session.access_token,\n                    body: { action: 'approve' },\n                    xform: (data) => ({ data, error: null }),\n                });\n                if (response.data && response.data.redirect_url) {\n                    // Automatically redirect in browser unless skipBrowserRedirect is true\n                    if (isBrowser() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) {\n                        window.location.assign(response.data.redirect_url);\n                    }\n                }\n                return response;\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Denies an OAuth authorization request.\n     * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n     */\n    async _denyAuthorization(authorizationId, options) {\n        try {\n            return await this._useSession(async (result) => {\n                const { data: { session }, error: sessionError, } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                if (!session) {\n                    return this._returnResult({ data: null, error: new AuthSessionMissingError() });\n                }\n                const response = await _request(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, {\n                    headers: this.headers,\n                    jwt: session.access_token,\n                    body: { action: 'deny' },\n                    xform: (data) => ({ data, error: null }),\n                });\n                if (response.data && response.data.redirect_url) {\n                    // Automatically redirect in browser unless skipBrowserRedirect is true\n                    if (isBrowser() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) {\n                        window.location.assign(response.data.redirect_url);\n                    }\n                }\n                return response;\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Lists all OAuth grants that the authenticated user has authorized.\n     * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n     */\n    async _listOAuthGrants() {\n        try {\n            return await this._useSession(async (result) => {\n                const { data: { session }, error: sessionError, } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                if (!session) {\n                    return this._returnResult({ data: null, error: new AuthSessionMissingError() });\n                }\n                return await _request(this.fetch, 'GET', `${this.url}/user/oauth/grants`, {\n                    headers: this.headers,\n                    jwt: session.access_token,\n                    xform: (data) => ({ data, error: null }),\n                });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Revokes a user's OAuth grant for a specific client.\n     * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.\n     */\n    async _revokeOAuthGrant(options) {\n        try {\n            return await this._useSession(async (result) => {\n                const { data: { session }, error: sessionError, } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                if (!session) {\n                    return this._returnResult({ data: null, error: new AuthSessionMissingError() });\n                }\n                await _request(this.fetch, 'DELETE', `${this.url}/user/oauth/grants`, {\n                    headers: this.headers,\n                    jwt: session.access_token,\n                    query: { client_id: options.clientId },\n                    noResolveJson: true,\n                });\n                return { data: {}, error: null };\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    async fetchJwk(kid, jwks = { keys: [] }) {\n        // try fetching from the supplied jwks\n        let jwk = jwks.keys.find((key) => key.kid === kid);\n        if (jwk) {\n            return jwk;\n        }\n        const now = Date.now();\n        // try fetching from cache\n        jwk = this.jwks.keys.find((key) => key.kid === kid);\n        // jwk exists and jwks isn't stale\n        if (jwk && this.jwks_cached_at + JWKS_TTL > now) {\n            return jwk;\n        }\n        // jwk isn't cached in memory so we need to fetch it from the well-known endpoint\n        const { data, error } = await _request(this.fetch, 'GET', `${this.url}/.well-known/jwks.json`, {\n            headers: this.headers,\n        });\n        if (error) {\n            throw error;\n        }\n        if (!data.keys || data.keys.length === 0) {\n            return null;\n        }\n        this.jwks = data;\n        this.jwks_cached_at = now;\n        // Find the signing key\n        jwk = data.keys.find((key) => key.kid === kid);\n        if (!jwk) {\n            return null;\n        }\n        return jwk;\n    }\n    /**\n     * Extracts the JWT claims present in the access token by first verifying the\n     * JWT against the server's JSON Web Key Set endpoint\n     * `/.well-known/jwks.json` which is often cached, resulting in significantly\n     * faster responses. Prefer this method over {@link GoTrueClient.getUser} which always\n     * sends a request to the Auth server for each JWT.\n     *\n     * If the project is not using an asymmetric JWT signing key (like ECC or\n     * RSA) it always sends a request to the Auth server (similar to\n     * {@link GoTrueClient.getUser}) to verify the JWT.\n     *\n     * @param jwt An optional specific JWT you wish to verify, not the one you\n     *            can obtain from {@link GoTrueClient.getSession}.\n     * @param options Various additional options that allow you to customize the\n     *                behavior of this method.\n     *\n     * @category Auth\n     *\n     * @remarks\n     * - Parses the user's [access token](/docs/guides/auth/sessions#access-token-jwt-claims) as a [JSON Web Token (JWT)](/docs/guides/auth/jwts) and returns its components if valid and not expired.\n     * - If your project is using asymmetric JWT signing keys, then the verification is done locally usually without a network request using the [WebCrypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API).\n     * - A network request is sent to your project's JWT signing key discovery endpoint `https://project-id.supabase.co/auth/v1/.well-known/jwks.json`, which is cached locally. If your environment is ephemeral, such as a Lambda function that is destroyed after every request, a network request will be sent for each new invocation. Supabase provides a network-edge cache providing fast responses for these situations.\n     * - If the user's access token is about to expire when calling this function, the user's session will first be refreshed before validating the JWT.\n     * - If your project is using a symmetric secret to sign the JWT, it always sends a request similar to `getUser()` to validate the JWT at the server before returning the decoded token. This is also used if the WebCrypto API is not available in the environment. Make sure you polyfill it in such situations.\n     * - The returned claims can be customized per project using the [Custom Access Token Hook](/docs/guides/auth/auth-hooks/custom-access-token-hook).\n     *\n     * @example Get JWT claims, header and signature\n     * ```js\n     * const { data, error } = await supabase.auth.getClaims()\n     * ```\n     *\n     * @exampleResponse Get JWT claims, header and signature\n     * ```json\n     * {\n     *   \"data\": {\n     *     \"claims\": {\n     *       \"aal\": \"aal1\",\n     *       \"amr\": [{\n     *         \"method\": \"email\",\n     *         \"timestamp\": 1715766000\n     *       }],\n     *       \"app_metadata\": {},\n     *       \"aud\": \"authenticated\",\n     *       \"email\": \"example@email.com\",\n     *       \"exp\": 1715769600,\n     *       \"iat\": 1715766000,\n     *       \"is_anonymous\": false,\n     *       \"iss\": \"https://project-id.supabase.co/auth/v1\",\n     *       \"phone\": \"+13334445555\",\n     *       \"role\": \"authenticated\",\n     *       \"session_id\": \"11111111-1111-1111-1111-111111111111\",\n     *       \"sub\": \"11111111-1111-1111-1111-111111111111\",\n     *       \"user_metadata\": {}\n     *     },\n     *     \"header\": {\n     *       \"alg\": \"RS256\",\n     *       \"typ\": \"JWT\",\n     *       \"kid\": \"11111111-1111-1111-1111-111111111111\"\n     *     },\n     *     \"signature\": [/** Uint8Array *\\/],\n     *   },\n     *   \"error\": null\n     * }\n     * ```\n     */\n    async getClaims(jwt, options = {}) {\n        try {\n            let token = jwt;\n            if (!token) {\n                const { data, error } = await this.getSession();\n                if (error || !data.session) {\n                    return this._returnResult({ data: null, error });\n                }\n                token = data.session.access_token;\n            }\n            const { header, payload, signature, raw: { header: rawHeader, payload: rawPayload }, } = decodeJWT(token);\n            if (!(options === null || options === void 0 ? void 0 : options.allowExpired)) {\n                // Reject expired JWTs should only happen if jwt argument was passed.\n                // Rethrow as AuthInvalidJwtError so the outer catch converts it to { data, error }.\n                try {\n                    validateExp(payload.exp);\n                }\n                catch (e) {\n                    throw new AuthInvalidJwtError(e instanceof Error ? e.message : 'JWT validation failed');\n                }\n            }\n            const signingKey = !header.alg ||\n                header.alg.startsWith('HS') ||\n                !header.kid ||\n                !('crypto' in globalThis && 'subtle' in globalThis.crypto)\n                ? null\n                : await this.fetchJwk(header.kid, (options === null || options === void 0 ? void 0 : options.keys) ? { keys: options.keys } : options === null || options === void 0 ? void 0 : options.jwks);\n            // If symmetric algorithm or WebCrypto API is unavailable, fallback to getUser()\n            if (!signingKey) {\n                const { error } = await this.getUser(token);\n                if (error) {\n                    throw error;\n                }\n                // getUser succeeds so the claims in the JWT can be trusted\n                return {\n                    data: {\n                        claims: payload,\n                        header,\n                        signature,\n                    },\n                    error: null,\n                };\n            }\n            const algorithm = getAlgorithm(header.alg);\n            // Convert JWK to CryptoKey\n            const publicKey = await crypto.subtle.importKey('jwk', signingKey, algorithm, true, [\n                'verify',\n            ]);\n            // Verify the signature\n            const isValid = await crypto.subtle.verify(algorithm, publicKey, signature, stringToUint8Array(`${rawHeader}.${rawPayload}`));\n            if (!isValid) {\n                throw new AuthInvalidJwtError('Invalid JWT signature');\n            }\n            // If verification succeeds, decode and return claims\n            return {\n                data: {\n                    claims: payload,\n                    header,\n                    signature,\n                },\n                error: null,\n            };\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    // --- Passkey Methods ---\n    /**\n     * Sign in with a passkey. Handles the full WebAuthn ceremony:\n     * 1. Fetches authentication challenge from server\n     * 2. Prompts user via navigator.credentials.get()\n     * 3. Verifies credential with server and creates session\n     *\n     * Requires `auth.experimental.passkey: true`.\n     *\n     * @category Auth\n     */\n    async signInWithPasskey(credentials) {\n        var _a, _b, _c;\n        assertPasskeyExperimentalEnabled(this.experimental);\n        try {\n            if (!browserSupportsWebAuthn()) {\n                return this._returnResult({\n                    data: null,\n                    error: new AuthUnknownError('Browser does not support WebAuthn', null),\n                });\n            }\n            // 1. Get challenge options from server\n            const { data: options, error: optionsError } = await this._startPasskeyAuthentication({\n                options: { captchaToken: (_a = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a === void 0 ? void 0 : _a.captchaToken },\n            });\n            if (optionsError || !options) {\n                return this._returnResult({ data: null, error: optionsError });\n            }\n            // 2. Deserialize and prompt user via browser WebAuthn API\n            const publicKeyOptions = deserializeCredentialRequestOptions(options.options);\n            const signal = (_c = (_b = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _b === void 0 ? void 0 : _b.signal) !== null && _c !== void 0 ? _c : webAuthnAbortService.createNewAbortSignal();\n            const { data: credential, error: credentialError } = await getCredential({\n                publicKey: publicKeyOptions,\n                signal,\n            });\n            if (credentialError || !credential) {\n                return this._returnResult({\n                    data: null,\n                    error: credentialError !== null && credentialError !== void 0 ? credentialError : new AuthUnknownError('WebAuthn ceremony failed', null),\n                });\n            }\n            // 3. Serialize and verify with server\n            const serialized = serializeCredentialRequestResponse(credential);\n            return this._verifyPasskeyAuthentication({\n                challengeId: options.challenge_id,\n                credential: serialized,\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Register a passkey for the current authenticated user. Handles the full WebAuthn ceremony:\n     * 1. Fetches registration challenge from server\n     * 2. Prompts user via navigator.credentials.create()\n     * 3. Verifies credential with server\n     *\n     * Requires an active session. Requires `auth.experimental.passkey: true`.\n     *\n     * @category Auth\n     */\n    async registerPasskey(credentials) {\n        var _a, _b;\n        assertPasskeyExperimentalEnabled(this.experimental);\n        try {\n            if (!browserSupportsWebAuthn()) {\n                return this._returnResult({\n                    data: null,\n                    error: new AuthUnknownError('Browser does not support WebAuthn', null),\n                });\n            }\n            // 1. Get challenge options from server\n            const { data: options, error: optionsError } = await this._startPasskeyRegistration();\n            if (optionsError || !options) {\n                return this._returnResult({ data: null, error: optionsError });\n            }\n            // 2. Deserialize and prompt user via browser WebAuthn API\n            const publicKeyOptions = deserializeCredentialCreationOptions(options.options);\n            const signal = (_b = (_a = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a === void 0 ? void 0 : _a.signal) !== null && _b !== void 0 ? _b : webAuthnAbortService.createNewAbortSignal();\n            const { data: credential, error: credentialError } = await createCredential({\n                publicKey: publicKeyOptions,\n                signal,\n            });\n            if (credentialError || !credential) {\n                return this._returnResult({\n                    data: null,\n                    error: credentialError !== null && credentialError !== void 0 ? credentialError : new AuthUnknownError('WebAuthn ceremony failed', null),\n                });\n            }\n            // 3. Serialize and verify with server\n            const serialized = serializeCredentialCreationResponse(credential);\n            return this._verifyPasskeyRegistration({\n                challengeId: options.challenge_id,\n                credential: serialized,\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Start passkey registration for the current authenticated user.\n     * Returns WebAuthn credential creation options to pass to navigator.credentials.create().\n     */\n    async _startPasskeyRegistration() {\n        assertPasskeyExperimentalEnabled(this.experimental);\n        try {\n            return await this._useSession(async (result) => {\n                const { data: { session }, error: sessionError, } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                if (!session) {\n                    return this._returnResult({ data: null, error: new AuthSessionMissingError() });\n                }\n                const { data, error } = await _request(this.fetch, 'POST', `${this.url}/passkeys/registration/options`, {\n                    headers: this.headers,\n                    jwt: session.access_token,\n                    body: {},\n                });\n                if (error) {\n                    return this._returnResult({ data: null, error });\n                }\n                return this._returnResult({ data, error: null });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Verify passkey registration with the credential response.\n     * The credentialResponse should be the serialized output of navigator.credentials.create().\n     */\n    async _verifyPasskeyRegistration(params) {\n        assertPasskeyExperimentalEnabled(this.experimental);\n        try {\n            return await this._useSession(async (result) => {\n                const { data: { session }, error: sessionError, } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                if (!session) {\n                    return this._returnResult({ data: null, error: new AuthSessionMissingError() });\n                }\n                const { data, error } = await _request(this.fetch, 'POST', `${this.url}/passkeys/registration/verify`, {\n                    headers: this.headers,\n                    jwt: session.access_token,\n                    body: {\n                        challenge_id: params.challengeId,\n                        credential: params.credential,\n                    },\n                });\n                if (error) {\n                    return this._returnResult({ data: null, error });\n                }\n                return this._returnResult({ data, error: null });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Start passkey authentication.\n     * Returns WebAuthn credential request options to pass to navigator.credentials.get().\n     */\n    async _startPasskeyAuthentication(params) {\n        var _a;\n        assertPasskeyExperimentalEnabled(this.experimental);\n        try {\n            const { data, error } = await _request(this.fetch, 'POST', `${this.url}/passkeys/authentication/options`, {\n                headers: this.headers,\n                body: {\n                    gotrue_meta_security: { captcha_token: (_a = params === null || params === void 0 ? void 0 : params.options) === null || _a === void 0 ? void 0 : _a.captchaToken },\n                },\n            });\n            if (error) {\n                return this._returnResult({ data: null, error });\n            }\n            return this._returnResult({ data, error: null });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Verify passkey authentication and create a session.\n     * The credential should be the serialized output of navigator.credentials.get().\n     */\n    async _verifyPasskeyAuthentication(params) {\n        assertPasskeyExperimentalEnabled(this.experimental);\n        try {\n            const { data, error } = await _request(this.fetch, 'POST', `${this.url}/passkeys/authentication/verify`, {\n                headers: this.headers,\n                body: {\n                    challenge_id: params.challengeId,\n                    credential: params.credential,\n                },\n                xform: _sessionResponse,\n            });\n            if (error) {\n                return this._returnResult({ data: null, error });\n            }\n            if (data.session) {\n                await this._saveSession(data.session);\n                await this._notifyAllSubscribers('SIGNED_IN', data.session);\n            }\n            return this._returnResult({ data, error: null });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * List all passkeys for the current user.\n     */\n    async _listPasskeys() {\n        assertPasskeyExperimentalEnabled(this.experimental);\n        try {\n            return await this._useSession(async (result) => {\n                const { data: { session }, error: sessionError, } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                if (!session) {\n                    return this._returnResult({ data: null, error: new AuthSessionMissingError() });\n                }\n                const { data, error } = await _request(this.fetch, 'GET', `${this.url}/passkeys`, {\n                    headers: this.headers,\n                    jwt: session.access_token,\n                    xform: (data) => ({ data, error: null }),\n                });\n                if (error) {\n                    return this._returnResult({ data: null, error });\n                }\n                return this._returnResult({ data, error: null });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Update a passkey.\n     */\n    async _updatePasskey(params) {\n        assertPasskeyExperimentalEnabled(this.experimental);\n        try {\n            return await this._useSession(async (result) => {\n                const { data: { session }, error: sessionError, } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                if (!session) {\n                    return this._returnResult({ data: null, error: new AuthSessionMissingError() });\n                }\n                const { data, error } = await _request(this.fetch, 'PATCH', `${this.url}/passkeys/${params.passkeyId}`, {\n                    headers: this.headers,\n                    jwt: session.access_token,\n                    body: { friendly_name: params.friendlyName },\n                });\n                if (error) {\n                    return this._returnResult({ data: null, error });\n                }\n                return this._returnResult({ data, error: null });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n    /**\n     * Delete a passkey.\n     */\n    async _deletePasskey(params) {\n        assertPasskeyExperimentalEnabled(this.experimental);\n        try {\n            return await this._useSession(async (result) => {\n                const { data: { session }, error: sessionError, } = result;\n                if (sessionError) {\n                    return this._returnResult({ data: null, error: sessionError });\n                }\n                if (!session) {\n                    return this._returnResult({ data: null, error: new AuthSessionMissingError() });\n                }\n                const { error } = await _request(this.fetch, 'DELETE', `${this.url}/passkeys/${params.passkeyId}`, {\n                    headers: this.headers,\n                    jwt: session.access_token,\n                    noResolveJson: true,\n                });\n                if (error) {\n                    return this._returnResult({ data: null, error });\n                }\n                return this._returnResult({ data: null, error: null });\n            });\n        }\n        catch (error) {\n            if (isAuthError(error)) {\n                return this._returnResult({ data: null, error });\n            }\n            throw error;\n        }\n    }\n}\nGoTrueClient.nextInstanceID = {};\nexport default GoTrueClient;\n//# sourceMappingURL=GoTrueClient.js.map","import GoTrueClient from './GoTrueClient';\nconst AuthClient = GoTrueClient;\nexport default AuthClient;\n//# sourceMappingURL=AuthClient.js.map","import { t as getTraceContextExtractor } from \"./tracingRegistry.mjs\";\nimport { FunctionRegion, FunctionsClient, FunctionsError, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError } from \"@supabase/functions-js\";\nimport { PostgrestClient, PostgrestError } from \"@supabase/postgrest-js\";\nimport { RealtimeClient } from \"@supabase/realtime-js\";\nimport { StorageApiError, StorageClient } from \"@supabase/storage-js\";\nimport { AuthClient } from \"@supabase/auth-js\";\n\nexport * from \"@supabase/realtime-js\"\n\nexport * from \"@supabase/auth-js\"\n\n//#region src/lib/version.ts\nconst version = \"2.116.0\";\n\n//#endregion\n//#region src/lib/constants.ts\nlet JS_ENV = \"\";\nlet JS_RUNTIME_VERSION;\nif (typeof Deno !== \"undefined\") {\n\tvar _Deno$version;\n\tJS_ENV = \"deno\";\n\tJS_RUNTIME_VERSION = (_Deno$version = Deno.version) === null || _Deno$version === void 0 ? void 0 : _Deno$version.deno;\n} else if (typeof document !== \"undefined\") JS_ENV = \"web\";\nelse if (typeof navigator !== \"undefined\" && navigator.product === \"ReactNative\") JS_ENV = \"react-native\";\nelse {\n\tvar _process$version;\n\tJS_ENV = \"node\";\n\tconst _process = globalThis[\"process\"];\n\tJS_RUNTIME_VERSION = _process === null || _process === void 0 || (_process$version = _process[\"version\"]) === null || _process$version === void 0 ? void 0 : _process$version.replace(/^v/, \"\");\n}\nconst _runtimeMeta = [`runtime=${JS_ENV}`];\nif (JS_RUNTIME_VERSION) _runtimeMeta.push(`runtime-version=${JS_RUNTIME_VERSION}`);\nconst DEFAULT_HEADERS = { \"X-Client-Info\": `supabase-js/${version}; ${_runtimeMeta.join(\"; \")}` };\nconst DEFAULT_GLOBAL_OPTIONS = { headers: DEFAULT_HEADERS };\nconst DEFAULT_DB_OPTIONS = { schema: \"public\" };\nconst DEFAULT_AUTH_OPTIONS = {\n\tautoRefreshToken: true,\n\tpersistSession: true,\n\tdetectSessionInUrl: true,\n\tflowType: \"implicit\"\n};\nconst DEFAULT_REALTIME_OPTIONS = {};\nconst DEFAULT_TRACE_PROPAGATION_OPTIONS = {\n\tenabled: false,\n\trespectSamplingDecision: true\n};\n\n//#endregion\n//#region ../../shared/tracing/dist/module/parse.js\n/**\n* Parse W3C traceparent header according to the specification.\n*\n* The traceparent header format is: version-traceid-parentid-traceflags\n* - version: 2 hex digits (currently always \"00\")\n* - traceid: 32 hex digits (128-bit trace identifier)\n* - parentid: 16 hex digits (64-bit span/parent identifier)\n* - traceflags: 2 hex digits (8-bit flags, bit 0 is sampled flag)\n*\n* @param traceparent - The traceparent header value\n* @returns Parsed traceparent object, or null if invalid format\n*\n* @see https://www.w3.org/TR/trace-context/#traceparent-header\n*\n* @example\n* ```typescript\n* const parsed = parseTraceParent('00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01')\n*\n* console.log(parsed)\n* // {\n* //   version: '00',\n* //   traceId: '0af7651916cd43dd8448eb211c80319c',\n* //   parentId: 'b7ad6b7169203331',\n* //   traceFlags: '01',\n* //   isSampled: true\n* // }\n* ```\n*/\nfunction parseTraceParent(traceparent) {\n\tif (!traceparent || typeof traceparent !== \"string\") return null;\n\tconst parts = traceparent.split(\"-\");\n\tif (parts.length !== 4) return null;\n\tconst [version$1, traceId, parentId, traceFlags] = parts;\n\tif (version$1.length !== 2 || traceId.length !== 32 || parentId.length !== 16 || traceFlags.length !== 2) return null;\n\tconst hexRegex = /^[0-9a-f]+$/i;\n\tif (!hexRegex.test(version$1) || !hexRegex.test(traceId) || !hexRegex.test(parentId) || !hexRegex.test(traceFlags)) return null;\n\tif (traceId === \"00000000000000000000000000000000\" || parentId === \"0000000000000000\") return null;\n\treturn {\n\t\tversion: version$1,\n\t\ttraceId,\n\t\tparentId,\n\t\ttraceFlags,\n\t\tisSampled: (parseInt(traceFlags, 16) & 1) === 1\n\t};\n}\n\n//#endregion\n//#region ../../shared/tracing/dist/module/validate.js\n/**\n* Check if trace context should be propagated to the target URL.\n*\n* This function checks if the target URL matches any of the configured\n* propagation targets. Targets can be:\n* - String: Exact hostname match or wildcard domain (*.example.com)\n* - RegExp: Pattern matching hostname\n* - Function: Custom logic to determine if URL should receive trace context\n*\n* @param targetUrl - The URL to check\n* @param targets - Array of propagation targets\n* @returns True if trace context should be propagated, false otherwise\n*\n* @example\n* ```typescript\n* const targets = [\n*   'myproject.supabase.co',           // Exact match\n*   '*.supabase.co',                   // Wildcard domain\n*   /.*\\.supabase\\.co$/,               // Regex pattern\n*   (url) => url.hostname === 'localhost' // Custom function\n* ]\n*\n* shouldPropagateToTarget('https://myproject.supabase.co/rest/v1/table', targets)\n* // true\n*\n* shouldPropagateToTarget('https://evil.com/api', targets)\n* // false\n* ```\n*/\nfunction shouldPropagateToTarget(targetUrl, targets) {\n\tif (!targetUrl || !targets || targets.length === 0) return false;\n\tlet url;\n\tif (targetUrl instanceof URL) url = targetUrl;\n\telse try {\n\t\turl = new URL(targetUrl);\n\t} catch (error) {\n\t\treturn false;\n\t}\n\tfor (const target of targets) try {\n\t\tif (typeof target === \"string\") {\n\t\t\tif (matchStringTarget(url.hostname, target)) return true;\n\t\t} else if (target instanceof RegExp) {\n\t\t\tif (target.test(url.hostname)) return true;\n\t\t} else if (typeof target === \"function\") {\n\t\t\tif (target(url)) return true;\n\t\t}\n\t} catch (error) {\n\t\tcontinue;\n\t}\n\treturn false;\n}\n/**\n* Match hostname against string target (exact match or wildcard)\n*\n* @param hostname - The hostname to check\n* @param target - The target pattern (exact or wildcard)\n* @returns True if hostname matches target\n*/\nfunction matchStringTarget(hostname, target) {\n\tif (target === hostname) return true;\n\tif (target.startsWith(\"*.\")) {\n\t\tconst domain = target.slice(2);\n\t\tif (hostname.endsWith(domain)) {\n\t\t\tif (hostname === domain || hostname.endsWith(\".\" + domain)) return true;\n\t\t}\n\t}\n\treturn false;\n}\n\n//#endregion\n//#region ../../shared/tracing/dist/module/defaults.js\n/**\n* Generate default propagation targets based on the Supabase project URL.\n*\n* By default, trace context is only propagated to Supabase domains for\n* security. This prevents leaking trace context to potentially malicious\n* third-party services.\n*\n* Wildcard strings (e.g. `*.supabase.co`) are matched with linear string\n* operations rather than regex, avoiding ReDoS risk.\n*\n* @param supabaseUrl - The Supabase project URL\n* @returns Array of default propagation targets\n*/\nfunction getDefaultPropagationTargets(supabaseUrl) {\n\tconst targets = [];\n\ttry {\n\t\tconst url = new URL(supabaseUrl);\n\t\ttargets.push(url.hostname);\n\t} catch (error) {}\n\ttargets.push(\"*.supabase.co\", \"*.supabase.in\");\n\ttargets.push(\"localhost\", \"127.0.0.1\", \"[::1]\");\n\treturn targets;\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.103.0/helpers/typeof.js\nfunction _typeof(o) {\n\t\"@babel/helpers - typeof\";\n\treturn _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function(o$1) {\n\t\treturn typeof o$1;\n\t} : function(o$1) {\n\t\treturn o$1 && \"function\" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? \"symbol\" : typeof o$1;\n\t}, _typeof(o);\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.103.0/helpers/toPrimitive.js\nfunction toPrimitive(t, r) {\n\tif (\"object\" != _typeof(t) || !t) return t;\n\tvar e = t[Symbol.toPrimitive];\n\tif (void 0 !== e) {\n\t\tvar i = e.call(t, r || \"default\");\n\t\tif (\"object\" != _typeof(i)) return i;\n\t\tthrow new TypeError(\"@@toPrimitive must return a primitive value.\");\n\t}\n\treturn (\"string\" === r ? String : Number)(t);\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.103.0/helpers/toPropertyKey.js\nfunction toPropertyKey(t) {\n\tvar i = toPrimitive(t, \"string\");\n\treturn \"symbol\" == _typeof(i) ? i : i + \"\";\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.103.0/helpers/defineProperty.js\nfunction _defineProperty(e, r, t) {\n\treturn (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n\t\tvalue: t,\n\t\tenumerable: !0,\n\t\tconfigurable: !0,\n\t\twritable: !0\n\t}) : e[r] = t, e;\n}\n\n//#endregion\n//#region \\0@oxc-project+runtime@0.103.0/helpers/objectSpread2.js\nfunction ownKeys(e, r) {\n\tvar t = Object.keys(e);\n\tif (Object.getOwnPropertySymbols) {\n\t\tvar o = Object.getOwnPropertySymbols(e);\n\t\tr && (o = o.filter(function(r$1) {\n\t\t\treturn Object.getOwnPropertyDescriptor(e, r$1).enumerable;\n\t\t})), t.push.apply(t, o);\n\t}\n\treturn t;\n}\nfunction _objectSpread2(e) {\n\tfor (var r = 1; r < arguments.length; r++) {\n\t\tvar t = null != arguments[r] ? arguments[r] : {};\n\t\tr % 2 ? ownKeys(Object(t), !0).forEach(function(r$1) {\n\t\t\t_defineProperty(e, r$1, t[r$1]);\n\t\t}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) {\n\t\t\tObject.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1));\n\t\t});\n\t}\n\treturn e;\n}\n\n//#endregion\n//#region src/lib/fetch.ts\nconst resolveFetch = (customFetch) => {\n\tif (customFetch) return (...args) => customFetch(...args);\n\treturn (...args) => fetch(...args);\n};\nconst resolveHeadersConstructor = () => {\n\treturn Headers;\n};\n/**\n* New-format Supabase API keys (`sb_publishable_…` / `sb_secret_…`) are not JWTs and\n* must never be sent as a Bearer token — they belong only in the `apikey` header.\n* All other keys (legacy JWT keys, `sb_temp_…` temporary keys, unrecognized `sb_`\n* subtypes) keep the Bearer fallback.\n*/\nconst isNewApiKey = (key) => key.startsWith(\"sb_publishable_\") || key.startsWith(\"sb_secret_\");\nconst TEMP_KEY_PREFIX = \"sb_temp_\";\nconst warnedKeySubtypes = /* @__PURE__ */ new Set();\n/**\n* Warn (once per subtype) when an `sb_` key isn't a subtype this SDK version recognizes.\n* Never throws — the server, not the SDK, decides key validity. The key value is never\n* included in the message.\n*/\nconst checkApiKeyFormat = (key) => {\n\tvar _key$match$, _key$match;\n\tif (!key.startsWith(\"sb_\") || isNewApiKey(key) || key.startsWith(TEMP_KEY_PREFIX)) return;\n\tconst subtype = (_key$match$ = (_key$match = key.match(/^sb_[a-zA-Z0-9]+_/)) === null || _key$match === void 0 ? void 0 : _key$match[0]) !== null && _key$match$ !== void 0 ? _key$match$ : \"unknown\";\n\tif (warnedKeySubtypes.has(subtype)) return;\n\twarnedKeySubtypes.add(subtype);\n\tconsole.warn(\"@supabase/supabase-js: Unrecognized Supabase API key format. The client will proceed and send this key as-is; if you see authentication errors you may need to upgrade @supabase/supabase-js to a version that recognizes this key type.\");\n};\nconst fetchWithAuth = (supabaseKey, supabaseUrl, getAccessToken, customFetch, tracePropagationOptions, options) => {\n\tconst fetch$1 = resolveFetch(customFetch);\n\tconst HeadersConstructor = resolveHeadersConstructor();\n\tconst traceEnabled = (tracePropagationOptions === null || tracePropagationOptions === void 0 ? void 0 : tracePropagationOptions.enabled) === true;\n\tconst respectSampling = (tracePropagationOptions === null || tracePropagationOptions === void 0 ? void 0 : tracePropagationOptions.respectSamplingDecision) !== false;\n\tconst traceTargets = traceEnabled ? getDefaultPropagationTargets(supabaseUrl) : null;\n\tconst allowKeyAsBearer = !((options === null || options === void 0 ? void 0 : options.omitApiKeyAsBearer) && isNewApiKey(supabaseKey));\n\treturn async (input, init) => {\n\t\tconst realToken = await getAccessToken();\n\t\tlet headers = new HeadersConstructor(init === null || init === void 0 ? void 0 : init.headers);\n\t\tif (!headers.has(\"apikey\")) headers.set(\"apikey\", supabaseKey);\n\t\tif (!headers.has(\"Authorization\")) {\n\t\t\tconst bearer = realToken !== null && realToken !== void 0 ? realToken : allowKeyAsBearer ? supabaseKey : null;\n\t\t\tif (bearer) headers.set(\"Authorization\", `Bearer ${bearer}`);\n\t\t}\n\t\tif (traceTargets) {\n\t\t\tconst traceHeaders = getTraceHeaders(input, traceTargets, respectSampling);\n\t\t\tif (traceHeaders) {\n\t\t\t\tif (traceHeaders.traceparent && !headers.has(\"traceparent\")) headers.set(\"traceparent\", traceHeaders.traceparent);\n\t\t\t\tif (traceHeaders.tracestate && !headers.has(\"tracestate\")) headers.set(\"tracestate\", traceHeaders.tracestate);\n\t\t\t\tif (traceHeaders.baggage && !headers.has(\"baggage\")) headers.set(\"baggage\", traceHeaders.baggage);\n\t\t\t}\n\t\t}\n\t\treturn fetch$1(input, _objectSpread2(_objectSpread2({}, init), {}, { headers }));\n\t};\n};\nlet warnedMissingTracingRuntime = false;\nlet warnedNonW3CPropagator = false;\nfunction getTraceHeaders(input, targets, respectSampling) {\n\tconst extractTraceContext = getTraceContextExtractor();\n\tif (!extractTraceContext) {\n\t\tif (!warnedMissingTracingRuntime) {\n\t\t\twarnedMissingTracingRuntime = true;\n\t\t\tconsole.warn(\"@supabase/supabase-js: tracePropagation is enabled but the tracing runtime is not loaded, so trace headers will not be attached. Add `import '@supabase/supabase-js/tracing'` at your application entry point (requires the OpenTelemetry API package to be installed). The CDN/UMD build does not support trace propagation.\");\n\t\t}\n\t\treturn null;\n\t}\n\tif (!shouldPropagateToTarget(typeof input === \"string\" ? input : input instanceof URL ? input : input.url, targets)) return null;\n\tconst traceContext = extractTraceContext();\n\tif (!traceContext || !traceContext.traceparent) {\n\t\tvar _traceContext$carrier;\n\t\tif ((traceContext === null || traceContext === void 0 || (_traceContext$carrier = traceContext.carrierKeys) === null || _traceContext$carrier === void 0 ? void 0 : _traceContext$carrier.length) && !warnedNonW3CPropagator) {\n\t\t\twarnedNonW3CPropagator = true;\n\t\t\tconst sentryHint = traceContext.carrierKeys.includes(\"sentry-trace\") ? \" Sentry detected: set `propagateTraceparent: true` in Sentry.init() to emit it.\" : \" Configure your tracing SDK to emit W3C trace context on outgoing requests.\";\n\t\t\tconsole.warn(`@supabase/supabase-js: tracePropagation is enabled and a tracing SDK is active, but its propagator wrote [${traceContext.carrierKeys.join(\", \")}] and no W3C traceparent header, so trace headers will not be attached.` + sentryHint);\n\t\t}\n\t\treturn null;\n\t}\n\tif (respectSampling) {\n\t\tconst parsed = parseTraceParent(traceContext.traceparent);\n\t\tif (parsed && !parsed.isSampled) return { traceparent: traceContext.traceparent };\n\t}\n\treturn traceContext;\n}\n\n//#endregion\n//#region src/lib/helpers.ts\nfunction normalizeTracePropagation(value) {\n\treturn typeof value === \"boolean\" ? { enabled: value } : value;\n}\nfunction ensureTrailingSlash(url) {\n\treturn url.endsWith(\"/\") ? url : url + \"/\";\n}\nlet warnedTopLevelSchema = false;\n/**\n* Warn (once per process) when `schema` is passed at the top level of the client options\n* instead of under `db`. A top-level `schema` is not part of the options shape and is\n* ignored, so queries silently go to the default schema. Never throws.\n*\n* Only `undefined` counts as unset, matching `db.schema`, where any other value is sent\n* as the profile header.\n*/\nfunction checkTopLevelSchemaOption(options) {\n\tif (warnedTopLevelSchema) return;\n\tif (typeof options !== \"object\" || options === null || !(\"schema\" in options) || options.schema === void 0) return;\n\twarnedTopLevelSchema = true;\n\tconsole.warn(\"@supabase/supabase-js: The \\\"schema\\\" option must be nested under \\\"db\\\", e.g. createClient(url, key, { db: { schema: 'myschema' } }). A top-level \\\"schema\\\" is ignored and queries go to the default schema.\");\n}\nfunction applySettingDefaults(options, defaults) {\n\tvar _DEFAULT_GLOBAL_OPTIO, _globalOptions$header, _ref, _tracePropagationOpti, _ref2, _tracePropagationOpti2;\n\tconst { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions } = options;\n\tconst { db: DEFAULT_DB_OPTIONS$1, auth: DEFAULT_AUTH_OPTIONS$1, realtime: DEFAULT_REALTIME_OPTIONS$1, global: DEFAULT_GLOBAL_OPTIONS$1 } = defaults;\n\tconst tracePropagationOptions = normalizeTracePropagation(options.tracePropagation);\n\tconst DEFAULT_TRACE_PROPAGATION_OPTIONS$1 = normalizeTracePropagation(defaults.tracePropagation);\n\tconst result = {\n\t\tdb: _objectSpread2(_objectSpread2({}, DEFAULT_DB_OPTIONS$1), dbOptions),\n\t\tauth: _objectSpread2(_objectSpread2({}, DEFAULT_AUTH_OPTIONS$1), authOptions),\n\t\trealtime: _objectSpread2(_objectSpread2({}, DEFAULT_REALTIME_OPTIONS$1), realtimeOptions),\n\t\tstorage: {},\n\t\tglobal: _objectSpread2(_objectSpread2(_objectSpread2({}, DEFAULT_GLOBAL_OPTIONS$1), globalOptions), {}, { headers: _objectSpread2(_objectSpread2({}, (_DEFAULT_GLOBAL_OPTIO = DEFAULT_GLOBAL_OPTIONS$1 === null || DEFAULT_GLOBAL_OPTIONS$1 === void 0 ? void 0 : DEFAULT_GLOBAL_OPTIONS$1.headers) !== null && _DEFAULT_GLOBAL_OPTIO !== void 0 ? _DEFAULT_GLOBAL_OPTIO : {}), (_globalOptions$header = globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.headers) !== null && _globalOptions$header !== void 0 ? _globalOptions$header : {}) }),\n\t\ttracePropagation: {\n\t\t\tenabled: (_ref = (_tracePropagationOpti = tracePropagationOptions === null || tracePropagationOptions === void 0 ? void 0 : tracePropagationOptions.enabled) !== null && _tracePropagationOpti !== void 0 ? _tracePropagationOpti : DEFAULT_TRACE_PROPAGATION_OPTIONS$1 === null || DEFAULT_TRACE_PROPAGATION_OPTIONS$1 === void 0 ? void 0 : DEFAULT_TRACE_PROPAGATION_OPTIONS$1.enabled) !== null && _ref !== void 0 ? _ref : false,\n\t\t\trespectSamplingDecision: (_ref2 = (_tracePropagationOpti2 = tracePropagationOptions === null || tracePropagationOptions === void 0 ? void 0 : tracePropagationOptions.respectSamplingDecision) !== null && _tracePropagationOpti2 !== void 0 ? _tracePropagationOpti2 : DEFAULT_TRACE_PROPAGATION_OPTIONS$1 === null || DEFAULT_TRACE_PROPAGATION_OPTIONS$1 === void 0 ? void 0 : DEFAULT_TRACE_PROPAGATION_OPTIONS$1.respectSamplingDecision) !== null && _ref2 !== void 0 ? _ref2 : true\n\t\t},\n\t\taccessToken: async () => \"\"\n\t};\n\tif (options.accessToken) result.accessToken = options.accessToken;\n\telse delete result.accessToken;\n\treturn result;\n}\n/**\n* Validates a Supabase client URL\n*\n* @param {string} supabaseUrl - The Supabase client URL string.\n* @returns {URL} - The validated base URL.\n* @throws {Error}\n*/\nfunction validateSupabaseUrl(supabaseUrl) {\n\tconst trimmedUrl = supabaseUrl === null || supabaseUrl === void 0 ? void 0 : supabaseUrl.trim();\n\tif (!trimmedUrl) throw new Error(\"supabaseUrl is required.\");\n\tif (!trimmedUrl.match(/^https?:\\/\\//i)) throw new Error(\"Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.\");\n\ttry {\n\t\treturn new URL(ensureTrailingSlash(trimmedUrl));\n\t} catch (_unused) {\n\t\tthrow Error(\"Invalid supabaseUrl: Provided URL is malformed.\");\n\t}\n}\n\n//#endregion\n//#region src/lib/SupabaseAuthClient.ts\nvar SupabaseAuthClient = class extends AuthClient {\n\tconstructor(options) {\n\t\tsuper(options);\n\t}\n};\n\n//#endregion\n//#region src/SupabaseClient.ts\n/**\n* Supabase Client.\n*\n* An isomorphic Javascript client for interacting with Postgres.\n*/\nvar SupabaseClient = class {\n\t/**\n\t* Create a new client for use in the browser.\n\t*\n\t* @category Initializing\n\t*\n\t* @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard.\n\t* @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard.\n\t* @param options Optional configuration for the client:\n\t* - `db.schema` — You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase.\n\t* - `auth.autoRefreshToken` — Set to `true` if you want to automatically refresh the token before expiring.\n\t* - `auth.persistSession` — Set to `true` if you want to automatically save the user session into local storage.\n\t* - `auth.detectSessionInUrl` — Set to `true` if you want to automatically detect OAuth grants in the URL and sign in the user.\n\t* - `realtime` — Options passed along to the realtime-js constructor.\n\t* - `storage` — Options passed along to the storage-js constructor.\n\t* - `global.fetch` — A custom fetch implementation.\n\t* - `global.headers` — Any additional headers to send with each network request.\n\t*\n\t* @example Creating a client\n\t* ```js\n\t* import { createClient } from '@supabase/supabase-js'\n\t*\n\t* // Create a single supabase client for interacting with your database\n\t* const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n\t* ```\n\t*\n\t* @example With a custom domain\n\t* ```js\n\t* import { createClient } from '@supabase/supabase-js'\n\t*\n\t* // Use a custom domain as the supabase URL\n\t* const supabase = createClient('https://my-custom-domain.com', 'your-publishable-key')\n\t* ```\n\t*\n\t* @example With additional parameters\n\t* ```js\n\t* import { createClient } from '@supabase/supabase-js'\n\t*\n\t* const options = {\n\t*   db: {\n\t*     schema: 'public',\n\t*   },\n\t*   auth: {\n\t*     autoRefreshToken: true,\n\t*     persistSession: true,\n\t*     detectSessionInUrl: true\n\t*   },\n\t*   global: {\n\t*     headers: { 'x-my-custom-header': 'my-app-name' },\n\t*   },\n\t* }\n\t* const supabase = createClient(\"https://xyzcompany.supabase.co\", \"your-publishable-key\", options)\n\t* ```\n\t*\n\t* @exampleDescription With custom schemas\n\t* By default the API server points to the `public` schema. You can enable other database schemas within the Dashboard.\n\t* Go to [Settings > API > Exposed schemas](/dashboard/project/_/settings/api) and add the schema which you want to expose to the API.\n\t*\n\t* Note: each client connection can only access a single schema, so the code above can access the `other_schema` schema but cannot access the `public` schema.\n\t*\n\t* @example With custom schemas\n\t* ```js\n\t* import { createClient } from '@supabase/supabase-js'\n\t*\n\t* const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key', {\n\t*   // Provide a custom schema. Defaults to \"public\".\n\t*   db: { schema: 'other_schema' }\n\t* })\n\t* ```\n\t*\n\t* @exampleDescription Custom fetch implementation\n\t* `supabase-js` uses the runtime's global `fetch` to make HTTP requests,\n\t* but an alternative `fetch` implementation can be provided as an option.\n\t* This is useful in environments where the global `fetch` is unavailable or where you want to customize request behavior.\n\t*\n\t* @example Custom fetch implementation\n\t* ```js\n\t* import { createClient } from '@supabase/supabase-js'\n\t*\n\t* const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key', {\n\t*   global: { fetch: fetch.bind(globalThis) }\n\t* })\n\t* ```\n\t*\n\t* @exampleDescription React Native options with AsyncStorage\n\t* For React Native we recommend using `AsyncStorage` as the storage implementation for Supabase Auth.\n\t*\n\t* @example React Native options with AsyncStorage\n\t* ```js\n\t* import 'react-native-url-polyfill/auto'\n\t* import { createClient } from '@supabase/supabase-js'\n\t* import AsyncStorage from \"@react-native-async-storage/async-storage\";\n\t*\n\t* const supabase = createClient(\"https://xyzcompany.supabase.co\", \"your-publishable-key\", {\n\t*   auth: {\n\t*     storage: AsyncStorage,\n\t*     autoRefreshToken: true,\n\t*     persistSession: true,\n\t*     detectSessionInUrl: false,\n\t*   },\n\t* });\n\t* ```\n\t*\n\t* @exampleDescription React Native options with Expo SecureStore\n\t* If you wish to encrypt the user's session information, you can use `aes-js` and store the encryption key in Expo SecureStore.\n\t* The `aes-js` library, a reputable JavaScript-only implementation of the AES encryption algorithm in CTR mode.\n\t* A new 256-bit encryption key is generated using the `react-native-get-random-values` library.\n\t* This key is stored inside Expo's SecureStore, while the value is encrypted and placed inside AsyncStorage.\n\t*\n\t* Please make sure that:\n\t* - You keep the `expo-secure-store`, `aes-js` and `react-native-get-random-values` libraries up-to-date.\n\t* - Choose the correct [`SecureStoreOptions`](https://docs.expo.dev/versions/latest/sdk/securestore/#securestoreoptions) for your app's needs.\n\t*   E.g. [`SecureStore.WHEN_UNLOCKED`](https://docs.expo.dev/versions/latest/sdk/securestore/#securestorewhen_unlocked) regulates when the data can be accessed.\n\t* - Carefully consider optimizations or other modifications to the above example, as those can lead to introducing subtle security vulnerabilities.\n\t*\n\t* @example React Native options with Expo SecureStore\n\t* ```ts\n\t* import 'react-native-url-polyfill/auto'\n\t* import { createClient } from '@supabase/supabase-js'\n\t* import AsyncStorage from '@react-native-async-storage/async-storage';\n\t* import * as SecureStore from 'expo-secure-store';\n\t* import * as aesjs from 'aes-js';\n\t* import 'react-native-get-random-values';\n\t*\n\t* // As Expo's SecureStore does not support values larger than 2048\n\t* // bytes, an AES-256 key is generated and stored in SecureStore, while\n\t* // it is used to encrypt/decrypt values stored in AsyncStorage.\n\t* class LargeSecureStore {\n\t*   private async _encrypt(key: string, value: string) {\n\t*     const encryptionKey = crypto.getRandomValues(new Uint8Array(256 / 8));\n\t*\n\t*     const cipher = new aesjs.ModeOfOperation.ctr(encryptionKey, new aesjs.Counter(1));\n\t*     const encryptedBytes = cipher.encrypt(aesjs.utils.utf8.toBytes(value));\n\t*\n\t*     await SecureStore.setItemAsync(key, aesjs.utils.hex.fromBytes(encryptionKey));\n\t*\n\t*     return aesjs.utils.hex.fromBytes(encryptedBytes);\n\t*   }\n\t*\n\t*   private async _decrypt(key: string, value: string) {\n\t*     const encryptionKeyHex = await SecureStore.getItemAsync(key);\n\t*     if (!encryptionKeyHex) {\n\t*       return encryptionKeyHex;\n\t*     }\n\t*\n\t*     const cipher = new aesjs.ModeOfOperation.ctr(aesjs.utils.hex.toBytes(encryptionKeyHex), new aesjs.Counter(1));\n\t*     const decryptedBytes = cipher.decrypt(aesjs.utils.hex.toBytes(value));\n\t*\n\t*     return aesjs.utils.utf8.fromBytes(decryptedBytes);\n\t*   }\n\t*\n\t*   async getItem(key: string) {\n\t*     const encrypted = await AsyncStorage.getItem(key);\n\t*     if (!encrypted) { return encrypted; }\n\t*\n\t*     return await this._decrypt(key, encrypted);\n\t*   }\n\t*\n\t*   async removeItem(key: string) {\n\t*     await AsyncStorage.removeItem(key);\n\t*     await SecureStore.deleteItemAsync(key);\n\t*   }\n\t*\n\t*   async setItem(key: string, value: string) {\n\t*     const encrypted = await this._encrypt(key, value);\n\t*\n\t*     await AsyncStorage.setItem(key, encrypted);\n\t*   }\n\t* }\n\t*\n\t* const supabase = createClient(\"https://xyzcompany.supabase.co\", \"your-publishable-key\", {\n\t*   auth: {\n\t*     storage: new LargeSecureStore(),\n\t*     autoRefreshToken: true,\n\t*     persistSession: true,\n\t*     detectSessionInUrl: false,\n\t*   },\n\t* });\n\t* ```\n\t*\n\t* @example With a database query\n\t* ```ts\n\t* import { createClient } from '@supabase/supabase-js'\n\t*\n\t* const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n\t*\n\t* const { data } = await supabase.from('profiles').select('*')\n\t* ```\n\t*\n\t* @exampleDescription With OpenTelemetry tracing\n\t* Opt in to W3C trace context propagation so the `trace_id` from your\n\t* client-side spans is attached to Supabase requests and appears in API\n\t* Gateway and Edge Function logs. Requires `@opentelemetry/api` to be\n\t* installed in your application and the tracing runtime to be loaded via\n\t* `import '@supabase/supabase-js/tracing'`. See [Tracing with the JS SDK](https://supabase.com/docs/guides/telemetry/client-side-tracing).\n\t*\n\t* @example With OpenTelemetry tracing\n\t* ```ts\n\t* import '@supabase/supabase-js/tracing'\n\t* import { createClient } from '@supabase/supabase-js'\n\t* import { trace } from '@opentelemetry/api'\n\t*\n\t* const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key', {\n\t*   tracePropagation: true,\n\t* })\n\t*\n\t* const tracer = trace.getTracer('my-app')\n\t*\n\t* await tracer.startActiveSpan('fetch-users', async (span) => {\n\t*   // Outgoing request carries the active trace context.\n\t*   const { data, error } = await supabase.from('users').select('*')\n\t*   span.end()\n\t* })\n\t* ```\n\t*/\n\tconstructor(supabaseUrl, supabaseKey, options) {\n\t\tvar _settings$auth$storag, _settings$global$head;\n\t\tthis.supabaseUrl = supabaseUrl;\n\t\tthis.supabaseKey = supabaseKey;\n\t\tconst baseUrl = validateSupabaseUrl(supabaseUrl);\n\t\tif (!supabaseKey) throw new Error(\"supabaseKey is required.\");\n\t\tcheckApiKeyFormat(supabaseKey);\n\t\tcheckTopLevelSchemaOption(options);\n\t\tthis.realtimeUrl = new URL(\"realtime/v1\", baseUrl);\n\t\tthis.realtimeUrl.protocol = this.realtimeUrl.protocol.replace(\"http\", \"ws\");\n\t\tthis.authUrl = new URL(\"auth/v1\", baseUrl);\n\t\tthis.storageUrl = new URL(\"storage/v1\", baseUrl);\n\t\tthis.functionsUrl = new URL(\"functions/v1\", baseUrl);\n\t\tconst defaultStorageKey = `sb-${baseUrl.hostname.split(\".\")[0]}-auth-token`;\n\t\tconst DEFAULTS = {\n\t\t\tdb: DEFAULT_DB_OPTIONS,\n\t\t\trealtime: DEFAULT_REALTIME_OPTIONS,\n\t\t\tauth: _objectSpread2(_objectSpread2({}, DEFAULT_AUTH_OPTIONS), {}, { storageKey: defaultStorageKey }),\n\t\t\tglobal: DEFAULT_GLOBAL_OPTIONS,\n\t\t\ttracePropagation: DEFAULT_TRACE_PROPAGATION_OPTIONS\n\t\t};\n\t\tconst settings = applySettingDefaults(options !== null && options !== void 0 ? options : {}, DEFAULTS);\n\t\tthis.settings = settings;\n\t\tthis.storageKey = (_settings$auth$storag = settings.auth.storageKey) !== null && _settings$auth$storag !== void 0 ? _settings$auth$storag : \"\";\n\t\tthis.headers = (_settings$global$head = settings.global.headers) !== null && _settings$global$head !== void 0 ? _settings$global$head : {};\n\t\tif (!settings.accessToken) {\n\t\t\tvar _settings$auth;\n\t\t\tthis.auth = this._initSupabaseAuthClient((_settings$auth = settings.auth) !== null && _settings$auth !== void 0 ? _settings$auth : {}, this.headers, settings.global.fetch);\n\t\t} else {\n\t\t\tthis.accessToken = settings.accessToken;\n\t\t\tthis.auth = new Proxy({}, { get: (_, prop) => {\n\t\t\t\tthrow new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(prop)} is not possible`);\n\t\t\t} });\n\t\t}\n\t\tthis.fetch = fetchWithAuth(supabaseKey, supabaseUrl, this._getSessionToken.bind(this), settings.global.fetch, settings.tracePropagation);\n\t\tthis.functionsFetch = fetchWithAuth(supabaseKey, supabaseUrl, this._getSessionToken.bind(this), settings.global.fetch, settings.tracePropagation, { omitApiKeyAsBearer: true });\n\t\tthis.realtime = this._initRealtimeClient(_objectSpread2({\n\t\t\theaders: this.headers,\n\t\t\taccessToken: this._getAccessToken.bind(this),\n\t\t\tfetch: this.fetch\n\t\t}, settings.realtime));\n\t\tif (this.accessToken) Promise.resolve(this.accessToken()).then((token) => this.realtime.setAuth(token)).catch((e) => console.warn(\"Failed to set initial Realtime auth token:\", e));\n\t\tthis.rest = new PostgrestClient(new URL(\"rest/v1\", baseUrl).href, {\n\t\t\theaders: this.headers,\n\t\t\tschema: settings.db.schema,\n\t\t\tfetch: this.fetch,\n\t\t\ttimeout: settings.db.timeout,\n\t\t\turlLengthLimit: settings.db.urlLengthLimit,\n\t\t\tretry: settings.db.retry\n\t\t});\n\t\tthis.storage = new StorageClient(this.storageUrl.href, this.headers, this.fetch, options === null || options === void 0 ? void 0 : options.storage);\n\t\tif (!settings.accessToken) this._listenForAuthEvents();\n\t}\n\t/**\n\t* Supabase Functions allows you to deploy and invoke edge functions.\n\t*/\n\tget functions() {\n\t\treturn new FunctionsClient(this.functionsUrl.href, {\n\t\t\theaders: this.headers,\n\t\t\tcustomFetch: this.functionsFetch\n\t\t});\n\t}\n\t/**\n\t* Perform a query on a table or a view.\n\t*\n\t* @param relation - The table or view name to query\n\t*/\n\tfrom(relation) {\n\t\treturn this.rest.from(relation);\n\t}\n\t/**\n\t* Select a schema to query or perform an function (rpc) call.\n\t*\n\t* The schema needs to be on the list of exposed schemas inside Supabase.\n\t*\n\t* @param schema - The schema to query\n\t*/\n\tschema(schema) {\n\t\treturn this.rest.schema(schema);\n\t}\n\t/**\n\t* Fetch the OpenAPI description PostgREST publishes for this client's schema.\n\t*\n\t* The document lists only the tables, views and functions the caller's role\n\t* holds privileges on. The request carries the same `apikey` and\n\t* `Authorization` headers as every other query, so the description is scoped\n\t* to the signed-in user. Call `.schema()` first to describe a schema other\n\t* than the client default.\n\t*\n\t* @example\n\t* ```ts\n\t* const { data, error } = await supabase.getOpenApiSpec()\n\t* ```\n\t*/\n\tgetOpenApiSpec() {\n\t\treturn this.rest.getOpenApiSpec();\n\t}\n\t/**\n\t* Perform a function call.\n\t*\n\t* @param fn - The function name to call\n\t* @param args - The arguments to pass to the function call\n\t* @param options - Named parameters\n\t* @param options.head - When set to `true`, `data` will not be returned.\n\t* Useful if you only need the count.\n\t* @param options.get - When set to `true`, the function will be called with\n\t* read-only access mode.\n\t* @param options.count - Count algorithm to use to count rows returned by the\n\t* function. Only applicable for [set-returning\n\t* functions](https://www.postgresql.org/docs/current/functions-srf.html).\n\t*\n\t* `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n\t* hood.\n\t*\n\t* `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n\t* statistics under the hood.\n\t*\n\t* `\"estimated\"`: Uses exact count for low numbers and planned count for high\n\t* numbers.\n\t*/\n\trpc(fn, args = {}, options = {\n\t\thead: false,\n\t\tget: false,\n\t\tcount: void 0\n\t}) {\n\t\treturn this.rest.rpc(fn, args, options);\n\t}\n\t/**\n\t* Creates a Realtime channel with Broadcast, Presence, and Postgres Changes.\n\t*\n\t* @param {string} name - The name of the Realtime channel.\n\t* @param {Object} opts - The options to pass to the Realtime channel.\n\t*\n\t* @category Realtime\n\t*/\n\tchannel(name, opts = { config: {} }) {\n\t\treturn this.realtime.channel(name, opts);\n\t}\n\t/**\n\t* Returns all Realtime channels.\n\t*\n\t* @category Realtime\n\t*\n\t* @example Get all channels\n\t* ```js\n\t* const channels = supabase.getChannels()\n\t* ```\n\t*/\n\tgetChannels() {\n\t\treturn this.realtime.getChannels();\n\t}\n\t/**\n\t* Unsubscribes and removes Realtime channel from Realtime client.\n\t*\n\t* @param {RealtimeChannel} channel - The name of the Realtime channel.\n\t*\n\t*\n\t* @category Realtime\n\t*\n\t* @remarks\n\t* - Removing a channel is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.\n\t*\n\t* @example Removes a channel\n\t* ```js\n\t* supabase.removeChannel(myChannel)\n\t* ```\n\t*/\n\tremoveChannel(channel) {\n\t\treturn this.realtime.removeChannel(channel);\n\t}\n\t/**\n\t* Unsubscribes and removes all Realtime channels from Realtime client.\n\t*\n\t* @category Realtime\n\t*\n\t* @remarks\n\t* - Removing channels is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.\n\t*\n\t* @example Remove all channels\n\t* ```js\n\t* supabase.removeAllChannels()\n\t* ```\n\t*/\n\tremoveAllChannels() {\n\t\treturn this.realtime.removeAllChannels();\n\t}\n\t/**\n\t* The raw session token — the custom `accessToken` result or the signed-in user's JWT —\n\t* or `null` when there is no session. Unlike {@link _getAccessToken} it does not fall back\n\t* to `supabaseKey`, so callers can distinguish \"no session\" from \"has session\".\n\t*/\n\tasync _getSessionToken() {\n\t\tvar _this = this;\n\t\tvar _data$session$access_, _data$session;\n\t\tif (_this.accessToken) return await _this.accessToken();\n\t\tconst { data } = await _this.auth.getSession();\n\t\treturn (_data$session$access_ = (_data$session = data.session) === null || _data$session === void 0 ? void 0 : _data$session.access_token) !== null && _data$session$access_ !== void 0 ? _data$session$access_ : null;\n\t}\n\tasync _getAccessToken() {\n\t\tvar _this2 = this;\n\t\tvar _await$this$_getSessi;\n\t\treturn (_await$this$_getSessi = await _this2._getSessionToken()) !== null && _await$this$_getSessi !== void 0 ? _await$this$_getSessi : _this2.supabaseKey;\n\t}\n\t_initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, userStorage, storageKey, flowType, lock, debug, throwOnError, experimental, lockAcquireTimeout, skipAutoInitialize }, headers, fetch$1) {\n\t\tconst authHeaders = {\n\t\t\tAuthorization: `Bearer ${this.supabaseKey}`,\n\t\t\tapikey: `${this.supabaseKey}`\n\t\t};\n\t\treturn new SupabaseAuthClient({\n\t\t\turl: this.authUrl.href,\n\t\t\theaders: _objectSpread2(_objectSpread2({}, authHeaders), headers),\n\t\t\tstorageKey,\n\t\t\tautoRefreshToken,\n\t\t\tpersistSession,\n\t\t\tdetectSessionInUrl,\n\t\t\tstorage,\n\t\t\tuserStorage,\n\t\t\tflowType,\n\t\t\tlock,\n\t\t\tdebug,\n\t\t\tthrowOnError,\n\t\t\texperimental,\n\t\t\tfetch: fetch$1,\n\t\t\tlockAcquireTimeout,\n\t\t\tskipAutoInitialize,\n\t\t\thasCustomAuthorizationHeader: Object.keys(this.headers).some((key) => key.toLowerCase() === \"authorization\")\n\t\t});\n\t}\n\t_initRealtimeClient(options) {\n\t\treturn new RealtimeClient(this.realtimeUrl.href, _objectSpread2(_objectSpread2({}, options), {}, { params: _objectSpread2(_objectSpread2({}, { apikey: this.supabaseKey }), options === null || options === void 0 ? void 0 : options.params) }));\n\t}\n\t_listenForAuthEvents() {\n\t\treturn this.auth.onAuthStateChange((event, session) => {\n\t\t\tthis._handleTokenChanged(event, \"CLIENT\", session === null || session === void 0 ? void 0 : session.access_token);\n\t\t});\n\t}\n\t_handleTokenChanged(event, source, token) {\n\t\tif ((event === \"TOKEN_REFRESHED\" || event === \"SIGNED_IN\" || event === \"INITIAL_SESSION\") && this.changedAccessToken !== token) {\n\t\t\tthis.changedAccessToken = token;\n\t\t\tthis.realtime.setAuth(token);\n\t\t} else if (event === \"SIGNED_OUT\") {\n\t\t\tthis.realtime.setAuth();\n\t\t\tif (source == \"STORAGE\") this.auth.signOut();\n\t\t\tthis.changedAccessToken = void 0;\n\t\t}\n\t}\n};\n\n//#endregion\n//#region src/index.ts\n/**\n* Creates a new Supabase Client.\n*\n* @example Creating a Supabase client\n* ```ts\n* import { createClient } from '@supabase/supabase-js'\n*\n* const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n* const { data, error } = await supabase.from('profiles').select('*')\n* ```\n*/\nconst createClient = (supabaseUrl, supabaseKey, options) => {\n\treturn new SupabaseClient(supabaseUrl, supabaseKey, options);\n};\nfunction shouldShowDeprecationWarning() {\n\tif (typeof window !== \"undefined\" || globalThis[\"Deno\"] !== void 0) return false;\n\tconst _process = globalThis[\"process\"];\n\tif (!_process) return false;\n\tconst processVersion = _process[\"version\"];\n\tif (processVersion === void 0 || processVersion === null) return false;\n\tconst versionMatch = processVersion.match(/^v(\\d+)\\./);\n\tif (!versionMatch) return false;\n\treturn parseInt(versionMatch[1], 10) <= 20;\n}\nif (shouldShowDeprecationWarning()) console.warn(\"⚠️  Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715\");\n\n//#endregion\nexport { FunctionRegion, FunctionsError, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError, PostgrestError, StorageApiError, SupabaseClient, createClient };\n//# sourceMappingURL=index.mjs.map","/**\n * Helpers to simplify Supabase client creation for package consumers.\n */\n\nimport { createClient, type SupabaseClient } from '@supabase/supabase-js';\n\n/**\n * Create a Supabase client from URL and anon key.\n * This is a convenience helper for package consumers who want to pass credentials directly.\n */\nexport function createSupabaseClient(\n  supabaseUrl: string,\n  supabaseAnonKey: string\n): SupabaseClient {\n  if (!supabaseUrl || !supabaseAnonKey) {\n    throw new Error('Supabase URL and anon key are required');\n  }\n  const client = createClient(supabaseUrl, supabaseAnonKey);\n  return client;\n}\n","import type { SupabaseClient } from '@supabase/supabase-js';\nimport type { SriMandirPuja } from './sriMandirPujaHelpers';\n\nfunction splitCSVLine(line: string): string[] {\n  const result: string[] = [];\n  let current = '';\n  let inQuotes = false;\n  for (let i = 0; i < line.length; i++) {\n    const char = line[i];\n    if (char === '\"') {\n      if (inQuotes && line[i + 1] === '\"') {\n        current += '\"';\n        i++;\n      } else {\n        inQuotes = !inQuotes;\n      }\n    } else if (char === ',' && !inQuotes) {\n      result.push(current);\n      current = '';\n    } else {\n      current += char;\n    }\n  }\n  result.push(current);\n  return result.map((v) => v.trim().replace(/^\"|\"$/g, ''));\n}\n\nfunction getField(row: Record<string, string>, ...keys: string[]): string {\n  const normalize = (value: string) =>\n    value\n      .trim()\n      .toLowerCase()\n      .replace(/[_\\s]+/g, ' ')\n      .trim();\n\n  const map = new Map<string, string>();\n  Object.entries(row).forEach(([key, value]) => map.set(normalize(key), value));\n\n  for (const key of keys) {\n    const value = map.get(normalize(key));\n    if (value !== undefined && value.trim()) return value.trim();\n  }\n\n  return '';\n}\n\nexport function parsePujasCSV(csvText: string): SriMandirPuja[] {\n  const text = csvText.replace(/^\\uFEFF/, '').replace(/\\r\\n?/g, '\\n');\n  const lines = text.trim().split('\\n');\n  if (lines.length < 2) return [];\n\n  const headers = splitCSVLine(lines[0]);\n  const pujas: SriMandirPuja[] = [];\n\n  for (let i = 1; i < lines.length; i++) {\n    const values = splitCSVLine(lines[i]);\n    if (values.length < headers.length) continue;\n\n    const row: Record<string, string> = {};\n    headers.forEach((header, index) => {\n      row[header] = values[index] ?? '';\n    });\n\n    const storeId = getField(row, 'store_id', 'store id');\n    const poojaTitle = getField(row, 'pooja_title', 'pooja title', 'puja title');\n    if (!storeId || !poojaTitle) continue;\n\n    const coverHindi = getField(row, 'cover_media_url', 'cover media url', 'cover image');\n    const coverEnglish = getField(row, 'cover_media_url_english', 'cover media url english', 'cover image english');\n\n    pujas.push({\n      store_id: storeId,\n      pooja_title: poojaTitle,\n      temple_name: getField(row, 'temple_name', 'temple name') || '',\n      pooja_title_english:\n        getField(row, 'pooja_title_english', 'pooja title english', 'puja title english') ||\n        undefined,\n      temple_name_english: getField(row, 'temple_name_english', 'temple name english') || undefined,\n      cover_media_url: coverHindi || undefined,\n      cover_media_url_english: coverEnglish || undefined,\n      puja_link:\n        getField(row, 'puja_link', 'puja link', 'pooja link') ||\n        getField(row, 'puja link', 'pooja link') ||\n        '',\n      puja_link_hindi:\n        getField(row, 'puja_link_hindi', 'puja link hindi', 'pooja link hindi') || undefined,\n      individual_pack_price_inr:\n        parseFloat(\n          getField(row, 'individual_pack_price_inr', 'individual pack price inr', 'price')\n        ) || 0,\n      schedule_date_ist:\n        getField(row, 'schedule_date_ist', 'schedule date ist', 'schedule date') || '',\n    });\n  }\n\n  return pujas;\n}\n\nconst DOSHA_KEYWORDS: Record<string, string[]> = {\n  mangal: ['mangal', 'manglik', 'kuja', 'मंगल', 'मांगलिक', '30 day', '30-day', '30 din'],\n  'kaal-sarp': ['kaal sarp', 'kaal-sarp', 'kaalsarp', 'काल सर्प', 'कालसर्प', 'sarp'],\n  kaalSarp: ['kaal sarp', 'kaal-sarp', 'kaalsarp', 'काल सर्प', 'कालसर्प', 'sarp'],\n  pitra: ['pitru', 'pitra', 'पितृ', 'पितर', 'pitra dosha', 'pitru dosha'],\n  shani: ['shani', 'saturn', 'शनि', 'sade sati', 'साढ़े साती', 'साढ़ेसाती', 'sade saati'],\n  sadeSati: ['shani', 'saturn', 'शनि', 'sade sati', 'साढ़े साती', 'साढ़ेसाती', 'sade saati'],\n};\n\nfunction parseIndianDate(dateStr: string): Date | null {\n  const parts = dateStr.split('/');\n  if (parts.length !== 3) return null;\n  const day = parseInt(parts[0], 10);\n  const month = parseInt(parts[1], 10) - 1;\n  const year = parseInt(parts[2], 10);\n  return new Date(year, month, day);\n}\n\nexport function getPujaForDosha(pujas: SriMandirPuja[], doshaType: string): SriMandirPuja | null {\n  const keywords = DOSHA_KEYWORDS[doshaType] || DOSHA_KEYWORDS[doshaType.toLowerCase()];\n  if (!keywords || keywords.length === 0) return null;\n\n  const filtered = pujas.filter((puja) => {\n    const title = (puja.pooja_title || '').toLowerCase();\n    const englishTitle = (puja.pooja_title_english || '').toLowerCase();\n    if (title.includes('rashi') || englishTitle.includes('rashi')) return false;\n    return keywords.some(\n      (keyword) =>\n        title.includes(keyword.toLowerCase()) || englishTitle.includes(keyword.toLowerCase())\n    );\n  });\n\n  if (filtered.length === 0) return null;\n\n  const today = new Date();\n  today.setHours(0, 0, 0, 0);\n\n  const upcoming = filtered.filter((puja) => {\n    const date = parseIndianDate(puja.schedule_date_ist);\n    if (!date) return true;\n    return date.getTime() >= today.getTime();\n  });\n\n  return (upcoming[0] ?? filtered[0]) || null;\n}\n\nlet cachedPujas: SriMandirPuja[] = [];\nlet cacheTime = 0;\nconst CACHE_MS = 60 * 60 * 1000;\n\nexport async function fetchPujas(supabase: SupabaseClient): Promise<SriMandirPuja[]> {\n  const now = Date.now();\n  if (cachedPujas.length > 0 && now - cacheTime < CACHE_MS) return cachedPujas;\n\n  try {\n    const { data, error } = await supabase.functions.invoke('fetch-pujas');\n    if (error) {\n      console.warn('[DoshaCalculator] fetch-pujas error:', error);\n      return cachedPujas;\n    }\n\n    const csvText = typeof data === 'string' ? data : '';\n    if (!csvText) return cachedPujas;\n\n    const pujas = parsePujasCSV(csvText);\n    cachedPujas = pujas;\n    cacheTime = now;\n    return pujas;\n  } catch (error) {\n    console.warn('[DoshaCalculator] fetchPujas error:', error);\n    return cachedPujas;\n  }\n}","/**\n * Sri Mandir Puja display helpers — same logic as celestial-puja-finder.\n * Used by SriMandirPujaVerticalCard for title, temple, date, link, cover image.\n */\n\nexport interface SriMandirPuja {\n  store_id: string;\n  pooja_title: string;\n  temple_name: string;\n  pooja_title_english?: string;\n  temple_name_english?: string;\n  cover_media_url?: string;\n  cover_media_url_english?: string;\n  puja_link: string;\n  puja_link_hindi?: string;\n  individual_pack_price_inr: number;\n  schedule_date_ist: string;\n}\n\n// Hindi to English translations for puja titles (same as celestial)\nconst HINDI_TO_ENGLISH_TITLES: Record<string, string> = {\n  'पितृ दोष निवारण महायज्ञ एवं काशी गंगा महाआरती': 'Pitru Dosha Nivaran Mahayagya & Kashi Ganga Maha Aarti',\n  'पितृ दोष शांति महापूजा एवं काशी गंगा आरती': 'Pitra Dosha Shanti Mahapuja & Kashi Ganga Aarti',\n  'पितृ दोष निवारण पूजा एवं काशी गंगा आरती': 'Pitra Dosha Nivaran Puja & Kashi Ganga Aarti',\n  'त्र्यंबकेश्वर ज्योतिर्लिंग रुद्राभिषेक और काल सर्प दोष निवारण पूजा': 'Trimbakeshwar Jyotirlinga Rudrabhishek & Kaal Sarp Dosha Nivaran Puja',\n  'काल सर्प दोष निवारण पूजा एवं त्र्यंबकेश्वर ज्योतिर्लिंग रुद्राभिषेक': 'Kaal Sarp Dosha Nivaran Puja & Trimbakeshwar Jyotirlinga Rudrabhishek',\n  'राहु-सूर्य दोष निवारण पूजा': 'Rahu-Surya Dosha Nivaran Puja',\n  'मंगल दोष निवारण पूजा': 'Mangal Dosha Nivaran Puja',\n  'शनि शांति पूजा': 'Shani Shanti Puja',\n  'शनि साढ़े साती शांति पूजा': 'Shani Sade Sati Shanti Puja',\n  'नवग्रह शांति पूजा': 'Navagraha Shanti Puja',\n  'गुरु चांडाल दोष निवारण पूजा': 'Guru Chandal Dosha Nivaran Puja',\n  'श्रापित दोष निवारण पूजा': 'Shrapit Dosha Nivaran Puja',\n  'काल सर्प दोष पूजा': 'Kaal Sarp Dosha Puja',\n  'मंगल पूजा': 'Mangal Puja',\n  'शनि पूजा': 'Shani Puja',\n  'राहु पूजा': 'Rahu Puja',\n  'केतु पूजा': 'Ketu Puja',\n  'नवग्रह शांति पूजा, शनि तिल तेल अभिषेक और पाप ग्रह शांति यज्ञ': 'Navagraha Shanti Puja, Shani Til Tel Abhishek and Paap Graha Shanti Yagya',\n  '30 दिन मंगल दोष निवारण पूजा': '30-Day Mangal Dosha Nivaran Puja',\n  '30 दिनों में मंगल दोष निवारण पूजा': '30-Day Mangal Dosha Nivaran Puja',\n  '30 दिन मंगल पूजा': '30-Day Mangal Puja',\n  '30 लाख मंगल जाप': '30 Lakh Mangal Jaap',\n  'शनि साढ़ेसाती शांति पूजा': 'Shani Sade Sati Shanti Puja',\n  'शनि महादशा शांति पूजा': 'Shani Mahadasha Shanti Puja',\n  'शनि दोष निवारण पूजा': 'Shani Dosha Nivaran Puja',\n  'काल सर्प दोष निवारण महापूजा': 'Kaal Sarp Dosha Nivaran Mahapuja',\n  'पिशाच मोचन कुंड पूजा': 'Pishach Mochan Kund Puja',\n  'पितृ तर्पण पूजा': 'Pitru Tarpan Puja',\n};\n\nconst HINDI_WORD_TRANSLATIONS: Record<string, string> = {\n  'पूजा': 'Puja', 'महापूजा': 'Mahapuja', 'दोष': 'Dosha', 'निवारण': 'Nivaran', 'शांति': 'Shanti',\n  'महायज्ञ': 'Mahayagya', 'यज्ञ': 'Yagya', 'अभिषेक': 'Abhishek', 'रुद्राभिषेक': 'Rudrabhishek',\n  'आरती': 'Aarti', 'महाआरती': 'Maha Aarti', 'महादशा': 'Mahadasha', 'मंदिर': 'Temple',\n  'ज्योतिर्लिंग': 'Jyotirlinga', 'देव': 'Dev', 'एवं': '&', 'और': 'and', 'तिल': 'Til', 'तेल': 'Tel',\n  'गंगा': 'Ganga', 'पाप': 'Paap', 'ग्रह': 'Graha', 'नवग्रह': 'Navagraha', 'मंगल': 'Mangal',\n  'शनि': 'Shani', 'साढ़े साती': 'Sade Sati', 'साढ़ेसाती': 'Sade Sati', 'राहु': 'Rahu', 'केतु': 'Ketu',\n  'गुरु': 'Guru', 'सूर्य': 'Surya', 'चंद्र': 'Chandra', 'चन्द्र': 'Chandra', 'बुध': 'Budh', 'शुक्र': 'Shukra',\n  'काल सर्प': 'Kaal Sarp', 'कालसर्प': 'Kaal Sarp', 'पितृ': 'Pitru', 'पितर': 'Pitra', 'श्रापित': 'Shrapit',\n  'चांडाल': 'Chandal', 'काशी': 'Kashi', 'त्र्यंबकेश्वर': 'Trimbakeshwar', 'हथला': 'Hathla',\n};\n\nconst HINDI_TO_ENGLISH_TEMPLES: Record<string, string> = {\n  'काशी विश्वनाथ मंदिर': 'Kashi Vishwanath Temple',\n  'त्र्यंबकेश्वर मंदिर': 'Trimbakeshwar Temple',\n  'त्र्यंबकेश्वर ज्योतिर्लिंग': 'Trimbakeshwar Jyotirlinga',\n  'महाकालेश्वर मंदिर': 'Mahakaleshwar Temple',\n  'सोमनाथ मंदिर': 'Somnath Temple',\n  'केदारनाथ मंदिर': 'Kedarnath Temple',\n  'बद्रीनाथ मंदिर': 'Badrinath Temple',\n  'रामेश्वरम मंदिर': 'Rameshwaram Temple',\n  'द्वारकाधीश मंदिर': 'Dwarkadhish Temple',\n  'जगन्नाथ पुरी मंदिर': 'Jagannath Puri Temple',\n  'हथला शनि देव मंदिर': 'Hathla Shani Dev Temple',\n};\n\nfunction parseIndianDate(dateStr: string): Date | null {\n  const parts = dateStr.split('/');\n  if (parts.length !== 3) return null;\n  const day = parseInt(parts[0], 10);\n  const month = parseInt(parts[1], 10) - 1;\n  const year = parseInt(parts[2], 10);\n  return new Date(year, month, day);\n}\n\nfunction fallbackTranslation(hindiText: string): string {\n  let result = hindiText;\n  const sorted = Object.entries(HINDI_WORD_TRANSLATIONS).sort((a, b) => b[0].length - a[0].length);\n  sorted.forEach(([hindi, english]) => {\n    const regex = new RegExp(hindi.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'gi');\n    result = result.replace(regex, english);\n  });\n  return result.replace(/\\s+/g, ' ').trim();\n}\n\nexport function getPujaTitle(puja: SriMandirPuja | string, language: string): string {\n  const isHindi = language?.toLowerCase().startsWith('hi');\n  const originalTitle = typeof puja === 'string' ? puja : puja.pooja_title;\n  const englishTitle = typeof puja === 'string' ? undefined : puja.pooja_title_english;\n  if (isHindi) return originalTitle;\n  if (englishTitle?.trim()) return englishTitle;\n  if (HINDI_TO_ENGLISH_TITLES[originalTitle]) return HINDI_TO_ENGLISH_TITLES[originalTitle];\n  const fallback = fallbackTranslation(originalTitle);\n  return fallback !== originalTitle ? fallback : originalTitle;\n}\n\nexport function getTempleName(puja: SriMandirPuja | string, language: string): string {\n  const isHindi = language?.toLowerCase().startsWith('hi');\n  const originalName = typeof puja === 'string' ? puja : puja.temple_name;\n  const englishName = typeof puja === 'string' ? undefined : puja.temple_name_english;\n  if (isHindi) return originalName;\n  if (englishName?.trim()) return englishName;\n  if (HINDI_TO_ENGLISH_TEMPLES[originalName]) return HINDI_TO_ENGLISH_TEMPLES[originalName];\n  const fallback = fallbackTranslation(originalName);\n  return fallback !== originalName ? fallback : originalName;\n}\n\nexport function formatScheduleDate(dateStr: string, language: string = 'en'): string {\n  const date = parseIndianDate(dateStr);\n  if (!date) return dateStr;\n  const isHindi = language?.toLowerCase().startsWith('hi');\n  const locale = isHindi ? 'hi-IN' : 'en-GB';\n  return new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short', year: 'numeric' }).format(date);\n}\n\n/** Append UTM params from current page URL (same behavior as celestial). */\nfunction appendUTMToUrl(baseUrl: string): string {\n  if (!baseUrl) return baseUrl;\n  if (typeof window === 'undefined') return baseUrl;\n  try {\n    const params = new URLSearchParams(window.location.search);\n    const utm_source = params.get('utm_source');\n    const utm_medium = params.get('utm_medium');\n    const utm_content = params.get('utm_content');\n    if (!utm_source && !utm_medium && !utm_content) return baseUrl;\n    const url = new URL(baseUrl);\n    if (utm_source) url.searchParams.set('utm_source', utm_source);\n    if (utm_medium) url.searchParams.set('utm_medium', utm_medium);\n    if (utm_content) url.searchParams.set('utm_content', utm_content);\n    return url.toString();\n  } catch {\n    return baseUrl;\n  }\n}\n\nexport function getPujaLink(puja: SriMandirPuja, language: string): string {\n  const isHindi = language?.toLowerCase().startsWith('hi');\n  const baseLink = isHindi ? (puja.puja_link_hindi || puja.puja_link) : (puja.puja_link || puja.puja_link_hindi);\n  return appendUTMToUrl(baseLink || '');\n}\n\nexport function getCoverImageUrl(puja: SriMandirPuja, language: string): string {\n  const isHindi = language?.toLowerCase().startsWith('hi');\n  if (isHindi) return puja.cover_media_url || puja.cover_media_url_english || '';\n  return puja.cover_media_url_english || puja.cover_media_url || '';\n}\n","/** Same locale and key shape as Kundli for shared header/reviews/FAQ. */\nexport type SupportedLocale = \"en\" | \"hi\";\n\nexport const SUPPORTED_LOCALES: SupportedLocale[] = [\"en\", \"hi\"];\n\nexport const LOCALE_LABELS: Record<SupportedLocale, string> = {\n  en: \"English\",\n  hi: \"हिन्दी\",\n};\n\nexport const translations: Record<SupportedLocale, Record<string, string>> = {\n  en: {\n    language: \"Language\",\n    guest: \"Guest\",\n    sriMandir: \"Sri Mandir\",\n    ratingText: \"3 Crore+ app downloads\",\n    feedbackTitle: \"What Others Discovered Through Their Dosha Analysis\",\n    feedbackTrust: \"Trusted by over 5 crore users worldwide\",\n    feedbackRating: \"4.9\",\n    feedbackTestimonial1:\n      \"I was facing delay in marriage and also tension in career. After checking my kundli I understood the problems clearly. I followed the remedies with faith and slowly things started improving. Now my marriage is fixed and job situation is also better. Feeling very thankful.\",\n    feedbackTestimonial2:\n      \"My health was not good from long time and money problems also coming again and again. The report explained everything in simple way. After doing small remedies I feel more positive and health is improving. Very good experience.\",\n    feedbackTestimonial3:\n      \"Career was fully stuck and no promotion from 3 years. I created my kundli here and got to know about some dosha affecting work life. After remedies within few months I changed job with better salary. Really happy.\",\n    feedbackTestimonial4:\n      \"I checked kundli for marriage but it also told about finance issues. Remedies were easy to follow. Slowly money stability came and good rishta also came in family. Feeling peaceful now.\",\n    feedbackTestimonial5:\n      \"Simple and clear guidance. Problems in job and health both reduced after remedies. Good service.\",\n    feedbackTestimonial6:\n      \"Too much stress in life related to marriage and future. Kundli reading was very detailed but easy to understand. After doing puja and mantra I feel calm and recently got good marriage proposal. Thank you so much.\",\n    feedbackTestimonial7:\n      \"Finance loss was happening again and again in business. They told reason from kundli and suggested remedy. I followed for few weeks and situation slowly became stable. Good support.\",\n    feedbackTestimonial8:\n      \"I almost lost hope for marriage and career both. But this kundli analysis gave me new confidence. Within 2 months I got interview call and also one good match from relatives. Things are moving finally.\",\n    feedbackTestimonial9:\n      \"Very genuine report not copy paste. Health issue reason also explained. After remedies I feel more energy and mind peace. Satisfied.\",\n    feedbackTestimonial10:\n      \"Marriage delay, money tension, family stress everything was going wrong. Remedies were small but powerful. Now engagement done and finance also improving slowly. Feeling blessed.\",\n    feedbackTestimonial11:\n      \"I was not believing before but result surprised me. Career growth started after long time and new opportunities coming. Good guidance and honest prediction.\",\n    feedbackTestimonial12:\n      \"Health problems and negative thoughts were too much. After following remedies I feel mentally strong and peaceful. Family also noticing the change. Very grateful.\",\n    feedbackTestimonial13:\n      \"Short review. Career better now and money flow also improved after remedy. Thank you.\",\n    feedbackTestimonial14:\n      \"Kundli reading helped me understand many hidden issues in life like marriage delay and job confusion. Remedies were simple daily things. Slowly life becoming stable. Nice experience overall.\",\n    feedbackTestimonial15:\n      \"Good for anyone facing problems in marriage career or finance. Simple language and true guidance. I saw positive change in few months only. Highly recommended.\",\n    feedbackAuthor1: \"Abhishek Mishra\",\n    feedbackAuthor2: \"Pooja Verma\",\n    feedbackAuthor3: \"Amit Patel\",\n    feedbackAuthor4: \"Sneha Gupta\",\n    feedbackAuthor5: \"Vikas Yadav\",\n    feedbackAuthor6: \"Neha Singh\",\n    feedbackAuthor7: \"Rahul Jain\",\n    feedbackAuthor8: \"Kavita Mishra\",\n    feedbackAuthor9: \"Sandeep Kumar\",\n    feedbackAuthor10: \"Anjali Mehta\",\n    feedbackAuthor11: \"Deepak Arora\",\n    feedbackAuthor12: \"Ritu Saxena\",\n    feedbackAuthor13: \"Manoj Tiwari\",\n    feedbackAuthor14: \"Priya Nair\",\n    feedbackAuthor15: \"Karan Malhotra\",\n    feedbackAuthor1AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639330970.png\",\n    feedbackAuthor2AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639293055.png\",\n    feedbackAuthor3AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639358174.png\",\n    feedbackAuthor4AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639427379.png\",\n    feedbackAuthor5AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639381899.png\",\n    feedbackAuthor6AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639416587.png\",\n    feedbackAuthor7AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639454626.png\",\n    feedbackAuthor8AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639319028.png\",\n    feedbackAuthor9AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639271096.png\",\n    feedbackAuthor10AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639254172.png\",\n    feedbackAuthor11AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639345411.png\",\n    feedbackAuthor12AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639306698.png\",\n    feedbackAuthor13AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639330970.png\",\n    feedbackAuthor14AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639402894.png\",\n    feedbackAuthor15AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639358174.png\",\n    readMoreReviews: \"Read More Reviews\",\n    readLess: \"Read Less\",\n    // Marriage-specific reviews\n    feedbackTitleMarriage: \"What others facing marriage delay discovered\",\n    feedbackTestimonialMarriage1:\n      \"My marriage was getting delayed again and again and we were very worried. After creating my kundli here I came to know about Mangal dosh and some other issues. The remedies suggested were simple and within few months things started moving. Now my engagement is fixed. Feeling very thankful.\",\n    feedbackTestimonialMarriage2:\n      \"I was honestly not believing in kundli much but my parents forced me to try. They found a marriage dosha in my chart and gave puja guidance. After doing it I met a very good person through relatives. Sometimes these things really work.\",\n    feedbackTestimonialMarriage3:\n      \"Got my kundli checked because nothing was working for my wedding. Every match was breaking. The report clearly explained the doshas and what to do. Followed the remedy for 40 days and suddenly one perfect match came. Married now and happy.\",\n    feedbackTestimonialMarriage4:\n      \"Very helpful service. Found reason for delay in marriage and solution also given. Things improved slowly.\",\n    feedbackTestimonialMarriage5:\n      \"I was 32 and tension in home was too much. Kundli showed Shani related problem affecting marriage. Did the suggested donation and mantra. Within 3 months alliance got finalised. Still feels like miracle honestly.\",\n    feedbackTestimonialMarriage6:\n      \"The explanation was simple and easy to understand. I liked that they did not scare me but gave practical remedies. After doing them my long pending relationship got approval from both families and we are getting married soon.\",\n    feedbackTestimonialMarriage7:\n      \"Short review but true. Marriage dosh removed after remedies and now wedding date fixed. Thank you so much.\",\n    feedbackTestimonialMarriage8:\n      \"Many astrologers told different things and I was confused. Here the kundli analysis felt genuine and detailed. They pointed out exact dosha causing breakups. After remedies my partner came back and families agreed. Feeling peaceful now.\",\n    feedbackTestimonialMarriage9:\n      \"I created my kundli just casually but result shocked me. There was strong manglik issue. Followed puja on Tuesday as told. Within few months I got good proposal from same city. Everything went smooth after that.\",\n    feedbackTestimonialMarriage10:\n      \"Service is good and fast. Report is clear. My marriage problem solved after remedy. Satisfied.\",\n    feedbackTestimonialMarriage11:\n      \"For 5 years nothing was happening in my life regarding marriage. After kundli matching they told to wait few months and do certain prayers. Exactly in that time I met my husband through office. Now happily married for 1 year.\",\n    feedbackTestimonialMarriage12:\n      \"Very emotional moment for me writing this. I had almost lost hope. The dosha remedies gave me confidence and positivity also. Slowly situations changed and today my roka ceremony is done. Truly grateful.\",\n    feedbackTestimonialMarriage13:\n      \"Nice guidance and honest prediction. No false promises. Remedies worked for my delayed marriage issue.\",\n    feedbackTestimonialMarriage14:\n      \"My daughter kundli was checked here. They found dosha and suggested simple temple visit and fasting. We followed sincerely. Within short time good proposal came from nice family. As parents we are very relieved.\",\n    feedbackTestimonialMarriage15:\n      \"I recommend this to anyone facing marriage delay. Kundli analysis felt real not copy paste. Small small remedies but big change in life. Thank you from heart.\",\n    faqTitle: \"Frequently Asked Questions\",\n    faqQ1: \"Is this really free?\",\n    faqA1:\n      \"Yes, the Dosha Calculator is completely free to use. You can check your kundli for doshas and get detailed analysis at no cost.\",\n    faqQ2: \"What if I don't know birth time?\",\n    faqA2:\n      \"You can enter an approximate birth time or use 12:00 PM as default. Some doshas like Mangal Dosha and Kaal Sarp Dosha can still be detected with approximate time.\",\n    faqQ3: \"Is this a generic report?\",\n    faqA3:\n      \"No, your report is personalized based on your exact date, time, and place of birth. Each kundli analysis is unique and the dosha detection is specific to your birth chart.\",\n    // Marriage-specific FAQs\n    faqQ1Marriage: \"Is this really free?\",\n    faqA1Marriage:\n      \"Yes, the Dosha Calculator is completely free to use. You can check your kundli for doshas and get detailed analysis at no cost.\",\n    faqQ2Marriage: \"What if I don't know birth time?\",\n    faqA2Marriage:\n      \"You can enter an approximate birth time or use 12:00 PM as default. Some doshas like Mangal Dosha and Kaal Sarp Dosha can still be detected with approximate time.\",\n    faqQ3Marriage: \"Is this a generic report?\",\n    faqA3Marriage:\n      \"No, your report is personalized based on your exact date, time, and place of birth. Each kundli analysis is unique and the dosha detection is specific to your birth chart.\",\n    faqQ4Marriage: \"Will this fix my marriage delay?\",\n    faqA4Marriage:\n      \"The calculator identifies doshas that may be causing marriage delay. Once detected, we recommend specific pujas and remedies that have helped thousands of users overcome marriage obstacles.\",\n    // Dosha form\n    formPrivacyBanner: \"100% Private & Secure\",\n    formTitle: \"Enter your details\",\n    formSubtitle: \"We'll generate your kundli to know your doshas\",\n    formNameLabel: \"Enter Your Name\",\n    formNamePlaceholder: \"Your Name\",\n    formGenderLabel: \"Your Gender\",\n    formGenderMale: \"Male\",\n    formGenderFemale: \"Female\",\n    formProblemLabel: \"What problem is bothering you?\",\n    formProblemMarriage: \"Marriage\",\n    formProblemMoney: \"Money\",\n    formProblemOther: \"Others\",\n    formProblemHealth: \"Health\",\n    formProblemEducation: \"Education\",\n    formProblemCareer: \"Career\",\n    formProblemOtherPlaceholder: \"Please describe your problem\",\n    formProblemOtherHint: \"Max 100 characters\",\n    formDobLabel: \"Select Date of Birth\",\n    formDobInfo: \"Your date of birth is used to calculate your dosha balance.\",\n    formTimeLabel: \"Exact Time of Birth\",\n    formTimeInfo: \"Birth time helps improve accuracy of the analysis.\",\n    formTimeUnknown: \"I don't know my birth time\",\n    formTimeUnknownHelp: \"Note - Without exact birth time, accuracy will be reduced. We'll run Moon-based checks only.\",\n    formPlaceLabel: \"Enter your birth place\",\n    formPlaceInfo: \"City and state/country help us refine your result.\",\n    formPlacePlaceholder: \"City, State\",\n    formFooterNote: \"Analysis Takes Only 60 seconds\",\n    formFooterNoteBefore: \"Analysis Takes Only \",\n    formFooterNoteBold: \"60 seconds\",\n    formFooterNoteAfter: \"\",\n    formCta: \"Check My Dosha for FREE\",\n    formCtaCalculate: \"Calculate my Dosha\",\n    calculating: \"Calculating...\",\n    bookPuja: \"Book Puja\",\n    resultPageTitle: \"Find Puja Remedy for Free\",\n    resultPageSubtitle:\n      \"Analyse your kundli to find out which doshas (if any) appear in your Vedic chart—and see devotional remedies.\",\n    calculationSuccess: \"Your dosha analysis is ready.\",\n    calculationError: \"Something went wrong. Please try again.\",\n    formError: \"Please correct the highlighted fields.\",\n    formNameRequired: \"Name is required.\",\n    formGenderRequired: \"Gender is required.\",\n    formDobRequired: \"Date of birth is required.\",\n    formTimeRequired: \"Time is required when birth time is known.\",\n    formPlaceRequired: \"Birth place is required.\",\n    formPlaceSelectFromDropdown: \"Please select a place from the dropdown list.\",\n    formAgeMarriageRestriction: \"Please select appropriate problem areas. Marriage, financial, career, and business-related issues are applicable for users above 18 years.\",\n    locationError: \"Could not get location coordinates. Please try again.\",\n    calculationResolvingPlace: \"Resolving place…\",\n    info: \"Info\",\n    // Results view\n    resultTitle: \"Your Dosha Analysis\",\n    resultSomeDoshas: \"Some Doshas Have Been Detected\",\n    resultNoDoshas: \"No Major Doshas Found\",\n    resultNoDoshasDesc: \"Your birth chart shows no major doshas.\",\n    resultMangal: \"Mangal Dosha\",\n    resultKaalSarp: \"Kaal Sarp Dosha\",\n    resultPitra: \"Pitra Dosha\",\n    resultSadeSati: \"Shani Sade Sati\",\n    resultStatusPresent: \"Present\",\n    resultStatusAbsent: \"Absent\",\n    resultStatusInactive: \"Inactive\",\n    resultExplanation: \"Explanation\",\n    resultRemedies: \"Remedies\",\n    resultEditForm: \"Edit details\",\n    // Detailed results (celestial-puja-finder style)\n    drStatus: \"Status\",\n    drSeverity: \"Severity\",\n    drType: \"Type\",\n    drPhase: \"Phase\",\n    drExplanation: \"Explanation\",\n    drWhyPresent: \"Why Present\",\n    drWhyAbsent: \"Why Absent\",\n    drImpact: \"Impact\",\n    drPlanetaryPositions: \"Planetary Positions\",\n    drTraditionalRemedies: \"Traditional Remedies\",\n    drDetailedAnalysis: \"Detailed Analysis & Remedies\",\n    drBasedOnChart: \"Based on your birth chart calculations\",\n    drDisclaimer:\n      \"While we follow established astrological rules, dosha interpretation can vary among astrologers. We recommend consulting an astrologer you trust if you wish to explore additional viewpoints.\",\n    drStatusPresent: \"Present\",\n    drStatusAbsent: \"Absent\",\n    drStatusInactive: \"Inactive\",\n    drStatusActive: \"Active\",\n    drStatusSuggested: \"Suggested\",\n    drStatusNullified: \"Present (Nullified)\",\n    drMangalName: \"Mangal Dosha (Manglik)\",\n    drMangalDesc:\n      \"Mangal (Manglik/Kuja) Dosha — Linked with Mars in certain houses; traditionally associated with friction in relationships and decisiveness.\",\n    drMangalImpact:\n      \"Greater likelihood of friction in close relationships, impatience/anger spikes, or delays and stops/starts in marriage or partnerships.\",\n    drMangalRemedies:\n      \"Recite Hanuman Chalisa daily\\nFast on Tuesdays\\nDonate red items like lentils or cloth\\nWear a coral gemstone after consultation\",\n    drKaalSarpName: \"Kaal Sarp Dosha\",\n    drKaalSarpDesc:\n      \"Kaal Sarp Dosha — All planets hemmed between Rahu and Ketu; often framed as a pattern indicating inner tension and transformation.\",\n    drKaalSarpImpact:\n      \"A pattern of inner restlessness and periodic setbacks; plans may feel blocked or get delayed despite effort, requiring extra persistence.\",\n    drKaalSarpRemedies:\n      \"Recite Maha Mrityunjaya Mantra 108 times daily\\nFeed stray dogs regularly\\nDonate to snake welfare or Naga temples\\nKeep a silver snake idol at home\",\n    drPitraName: \"Pitra Dosha\",\n    drPitraDesc:\n      \"Pitra (Pitru) Dosha — Traditional indicators around the 9th house and Sun–node links; associated with duties, lineage, and guidance.\",\n    drPitraImpact:\n      \"Recurring duties/obligations toward family or elders; guilt, disputes, or legacy issues can surface and demand resolution.\",\n    drPitraRemedies:\n      \"Perform Shraddha ceremony on tithis\\nFeed brahmins or the needy on Amavasya\\nRecite Pitra Gayatri mantra\\nOffer water to ancestors every morning\",\n    drSadeSatiName: \"Shani Sade Sati\",\n    drSadeSatiDesc:\n      \"Shani Sade Sati — Saturn's transit across the natal Moon's neighborhood; a 7.5-year cycle emphasizing discipline and patience.\",\n    drSadeSatiImpact:\n      \"Heavier responsibilities, slower progress, and tests of patience; results tend to come with consistent discipline rather than speed.\",\n    drSadeSatiRemedies:\n      \"Recite Shani mantra on Saturdays\\nLight mustard oil lamp on Saturdays\\nDonate black items like sesame, blankets\\nFeed crows and help the disabled\",\n    drWhyMarked: \"Why is this dosha marked in your kundli?\",\n    drViewKundli: \"View Kundli\",\n    drPhaseMeaning: \"Current Phase Meaning:\",\n    drPhaseRising:\n      \"Rising Phase: Saturn is in the sign before your Moon sign. This marks the beginning of Sade Sati.\",\n    drPhasePeak:\n      \"Peak Phase: Saturn is in your Moon sign. This is the most intense period of Sade Sati.\",\n    drPhaseSetting:\n      \"Setting Phase: Saturn is in the sign after your Moon sign. Sade Sati is nearing its end.\",\n    drImpactIfPresent: \"Impact if Present\",\n    drPujaRecommendation: \"Puja Recommendation\",\n    drHowPujaHelps: \"How this Puja will help\",\n    drNoPujaAvailable: \"No specific puja available for this dosha\",\n    drFeedbackContact: \"For feedback or suggestions, please contact\",\n    drGoBack: \"Go Back\",\n    drDoshaOf: \"Dosha {{index}} of {{total}}\",\n    drTranslating: \"Translating...\",\n    drAnalyzingImpact: \"Analyzing impact...\",\n    drSeverityHigh: \"High\",\n    drSeverityMedium: \"Medium\",\n    drSeverityLow: \"Low\",\n    drBasedOnPositions: \"Based on planetary positions\",\n    drPujaBenefitsMangal:\n      \"Calms aggressive Mars energy causing conflict and instability.\\nReduces hurdles through fire offerings to pacify Mangal.\\nStrengthens harmony in relationships and domestic life.\\nProtects from impulsive decisions and heated confrontations.\",\n    drPujaBenefitsKaalSarp:\n      \"Balances Rahu-Ketu energies causing sudden setbacks.\\nRituals reduce fear, confusion, and unexpected losses.\\nStrengthens protection against karmic disturbances.\\nRestores direction and stability in major life areas.\",\n    drPujaBenefitsPitra:\n      \"Brings peace to ancestors through Tarpan offerings.\\nRemoves unseen family obstacles blocking progress.\\nRestores blessings lost due to ancestral imbalance.\\nImproves health, stability, and family harmony.\",\n    drPujaBenefitsShani:\n      \"Pacifies Saturn's pressure through Shani Abhishek rituals.\\nReduces delays, financial strain, and mental burden.\\nIncreases resilience during Saturn's testing phase.\\nBrings steady progress and long-term protection.\",\n    drFomoLine:\n      \"The pujas are conducted only on select dates at the temples, and slots are limited to maintain ritual purity.\",\n    drOtherDoshas: \"Other Doshas\",\n    drOtherDoshasStatusActive: \"Status: Some doshas active\",\n    drOtherDoshasStatusNone: \"Status: No other doshas found\",\n    drYourKundali: \"Your Kundali\",\n    kundaliChartNorth: \"North\",\n    kundaliChartSouth: \"South\",\n    kundaliChartRetry: \"Retry\",\n    kundaliChartLoadError: \"Couldn't load Kundali image\",\n    drPlanetaryPositionsCausing: \"Planetary Positions Causing These Doshas\",\n    drOtherGrahan: \"Rahu-Ketu / Grahan Dosha\",\n    drOtherShrapit: \"Shrapit Dosha\",\n    drOtherGuruChandal: \"Guru Chandal Dosha\",\n    drOtherPunarphoo: \"Punarphoo Dosha\",\n    drOtherKemadruma: \"Kemadruma Yoga\",\n    drOtherGandmool: \"Gandmool Dosha\",\n    drOtherKalathra: \"Kalathra Dosha\",\n    drOtherVishDaridra: \"Vish Daridra Yoga\",\n    drOtherKetuNaga: \"Ketu Naga Dosha\",\n    drOtherNavagraha: \"Navagraha Imbalance\",\n    // Other Doshas - Descriptions\n    drOtherGrahanDesc: \"Occurs when Rahu-Ketu eclipse the Sun or Moon; traditionally linked to sudden challenges or hidden fears.\",\n    drOtherShrapitDesc: \"Saturn-Rahu conjunction in any house; often framed as ancestral karmic debts requiring resolution.\",\n    drOtherGuruChandalDesc: \"Jupiter afflicted by Rahu/Ketu; can cause conflict between higher wisdom and material desires.\",\n    drOtherPunarphooDesc: \"Saturn-Moon affliction indicating recurring emotional cycles or repeated patterns.\",\n    drOtherKemadrumaDesc: \"Moon isolated from benefic support; can indicate periods of emotional vulnerability.\",\n    drOtherGandmoolDesc: \"Birth in specific Moon nakshatras (Ashwini, Revati, etc.); traditionally requires special rituals.\",\n    drOtherKalathraDec: \"Affliction in 7th house or its lord; primarily associated with partnership and marriage themes.\",\n    drOtherVishDaridraDesc: \"Mars-Saturn challenging aspect creating tension between action and caution.\",\n    drOtherKetuNagaDesc: \"Ketu-related serpent energy; linked to spiritual transformation and past-life patterns.\",\n    drOtherNavagrahaDesc: \"Multiple planetary afflictions suggesting need for comprehensive planetary peace rituals.\",\n    // Other Doshas - Impact (when present)\n    drOtherGrahanImpact: \"Sudden setbacks, hidden anxieties, or eclipse-related sensitivities may arise; emotional ups and downs.\",\n    drOtherShrapitImpact: \"Ancestral obligations, recurring obstacles, or karmic lessons that demand patience and resolution.\",\n    drOtherGuruChandalImpact: \"Judgment issues, mentor problems, or misalignment between promises and outcomes in spiritual/ethical matters.\",\n    drOtherPunarphooImpact: \"Emotional cycles repeating; relationships or situations may loop back requiring renewed effort.\",\n    drOtherKemadrumaImpact: \"Periods of emotional isolation or lack of support; resilience needed during vulnerable phases.\",\n    drOtherGandmoolImpact: \"Birth nakshatra challenges; traditional remedies advised for smoother life transitions.\",\n    drOtherKalathraImpact: \"Partnership friction, marriage delays, or 7th house matters requiring attention and patience.\",\n    drOtherVishDaridraImpact: \"Action-caution conflict; financial strain or Mars-Saturn tension creating stop-start patterns.\",\n    drOtherKetuNagaImpact: \"Spiritual restlessness, past-life echoes, or serpent-energy themes needing acknowledgment.\",\n    drOtherNavagrahaImpact: \"Multiple planetary imbalances creating varied life challenges; comprehensive remedies recommended.\",\n    // Other Doshas - Remedies (when present)\n    drOtherGrahanRemedies: \"Chant Rahu-Ketu mantras during eclipses\\nDonate to eclipse-related charities\\nWear Gomed or Cat's Eye after consultation\\nPerform Grahan Shanti puja\",\n    drOtherShrapitRemedies: \"Worship Shani and Rahu on Saturdays\\nRecite Shani-Rahu mantras\\nDonate black and blue items\\nPerform ancestral rites regularly\",\n    drOtherGuruChandalRemedies: \"Recite Guru mantras (Brihaspati mantra)\\nDonate yellow items on Thursdays\\nSeek blessings from learned teachers\\nWear Yellow Sapphire after consultation\",\n    drOtherPunarphooRemedies: \"Chant Shani and Chandra mantras\\nDonate to elderly and mothers\\nWear Pearl and Blue Sapphire (if advised)\\nPerform Shani-Chandra shanti\",\n    drOtherKemadrumaRemedies: \"Recite Chandra mantras daily\\nFast on Mondays\\nDonate white items like milk, rice\\nWear Pearl gemstone after consultation\",\n    drOtherGandmoolRemedies: \"Perform Gandmool Nakshatra Shanti puja\\nRecite birth nakshatra mantra\\nDonate as per nakshatra guidelines\\nSeek priest guidance for rituals\",\n    drOtherKalathraRemedies: \"Worship Venus and 7th lord\\nRecite Kalathra dosha mantras\\nDonate to marriage/partnership causes\\nWear Diamond/Opal after consultation\",\n    drOtherVishDaridraRemedies: \"Balance Mars-Saturn energy with mantras\\nDonate red and black items\\nPerform Mangal-Shani shanti puja\\nWear Red Coral with Blue Sapphire (if advised)\",\n    drOtherKetuNagaRemedies: \"Worship serpent deities at Naga temples\\nRecite Ketu mantras\\nDonate to snake welfare\\nWear Cat's Eye after consultation\",\n    drOtherNavagrahaRemedies: \"Perform comprehensive Navagraha Shanti puja\\nRecite Navagraha mantras\\nDonate items for all nine planets\\nVisit Navagraha temples\",\n    // Trust badges (marquee under header)\n    ctaKundliCreated: \"3L+ Kundli Reports Created.\",\n    ctaCertified: \"BHU Certified Astrologer.\",\n    ctaSecurePayment: \"Secure Payment.\",\n    contactTitle: \"Contact Us\",\n    contactBrandName: \"Sri Mandir\",\n    contactWhatsAppGlobal: \"Whatsapp: 8296947757\",\n    contactWhatsAppDomestic: \"Whatsapp: 08071174417\",\n    contactEmail: \"Email: pujaseva@appsforbharat.com\",\n    whatFromAnalysisTitle: \"What You'll Get From This Analysis\",\n    // Marriage-specific content\n    whatFromAnalysisMarriage1Title: \"Marriage Impact Assessment\",\n    whatFromAnalysisMarriage1Desc:\n      \"Whether it causes delay, conflict, or mismatch\",\n    whatFromAnalysisMarriage2Title: \"Dosha Confirmation\",\n    whatFromAnalysisMarriage2Desc:\n      \"Know if Mangal Dosha exists and how strong it is\",\n    whatFromAnalysisMarriage3Title: \"Remedy Direction\",\n    whatFromAnalysisMarriage3Desc: \"Which remedy or puja is recommended\",\n    // Generic content\n    whatFromAnalysisGeneric1Title: \"Life Impact Overview\",\n    whatFromAnalysisGeneric1Desc:\n      \"See possible delays, challenges, or opportunities in marriage, career, finances, health, and education.\",\n    whatFromAnalysisGeneric2Title: \"Dosha Confirmation\",\n    whatFromAnalysisGeneric2Desc:\n      \"Find out if any dosha or planetary imbalance is affecting your progress.\",\n    whatFromAnalysisGeneric3Title: \"Remedy Direction\",\n    whatFromAnalysisGeneric3Desc: \"Which remedy or puja is recommended\",\n  },\n  hi: {\n    language: \"भाषा\",\n    guest: \"अतिथि\",\n    sriMandir: \"श्री मंदिर\",\n    ratingText: \"3 करोड़+ ऐप डाउनलोड\",\n    feedbackTitle: \"अन्य लोगों ने अपने दोष विश्लेषण के माध्यम से क्या खोजा\",\n    feedbackTrust:\n      \"दुनिया भर में 5 करोड़ से अधिक उपयोगकर्ताओं द्वारा विश्वसनीय\",\n    feedbackRating: \"4.9\",\n    feedbackTestimonial1:\n      \"मेरी शादी में देरी हो रही थी और करियर को लेकर भी टेंशन था। कुंडली चेक करने के बाद मुझे समस्याएं साफ समझ आईं। मैंने विश्वास से उपाय किए और धीरे-धीरे चीजें बेहतर होने लगीं। अब मेरी शादी तय हो गई है और जॉब की स्थिति भी अच्छी है। बहुत धन्यवाद।\",\n    feedbackTestimonial2:\n      \"मेरी हेल्थ लंबे समय से ठीक नहीं थी और पैसों की परेशानी भी बार-बार आ रही थी। रिपोर्ट में सब कुछ आसान तरीके से समझाया गया। छोटे-छोटे उपाय करने के बाद अब ज्यादा पॉजिटिव महसूस करती हूं और हेल्थ भी सुधर रही है। बहुत अच्छा एक्सपीरियंस।\",\n    feedbackTestimonial3:\n      \"करियर पूरी तरह रुका हुआ था और 3 साल से प्रमोशन नहीं मिला। यहां कुंडली बनाई तो पता चला कुछ दोष काम को प्रभावित कर रहा है। उपाय करने के कुछ महीनों में ही बेहतर सैलरी वाली नई जॉब मिल गई। सच में बहुत खुश हूं।\",\n    feedbackTestimonial4:\n      \"मैंने शादी के लिए कुंडली चेक करवाई थी लेकिन इसमें फाइनेंस की समस्या भी बताई गई। उपाय आसान थे। धीरे-धीरे पैसों की स्थिरता आई और अच्छा रिश्ता भी आया। अब मन शांत है।\",\n    feedbackTestimonial5:\n      \"सिंपल और क्लियर गाइडेंस मिली। जॉब और हेल्थ दोनों की समस्या उपाय के बाद कम हुई। अच्छी सर्विस।\",\n    feedbackTestimonial6:\n      \"शादी और भविष्य को लेकर बहुत स्ट्रेस था। कुंडली रीडिंग डिटेल में थी लेकिन समझने में आसान। पूजा और मंत्र करने के बाद मन शांत हुआ और हाल ही में अच्छा रिश्ता मिला। बहुत धन्यवाद।\",\n    feedbackTestimonial7:\n      \"बिजनेस में बार-बार फाइनेंस लॉस हो रहा था। कुंडली से कारण बताया और उपाय सुझाया। कुछ हफ्तों तक करने के बाद स्थिति धीरे-धीरे स्टेबल होने लगी। अच्छा सपोर्ट मिला।\",\n    feedbackTestimonial8:\n      \"मैंने शादी और करियर दोनों की उम्मीद लगभग छोड़ दी थी। लेकिन इस कुंडली एनालिसिस से नया कॉन्फिडेंस मिला। 2 महीने में इंटरव्यू कॉल आया और रिश्तेदारों से अच्छा रिश्ता भी आया। अब चीजें आगे बढ़ रही हैं।\",\n    feedbackTestimonial9:\n      \"बहुत जेन्युइन रिपोर्ट थी, कॉपी पेस्ट नहीं लगी। हेल्थ इश्यू का कारण भी समझाया गया। उपाय के बाद ज्यादा एनर्जी और मन की शांति महसूस हो रही है। संतुष्ट हूं।\",\n    feedbackTestimonial10:\n      \"शादी में देरी, पैसों की टेंशन और फैमिली स्ट्रेस सब एक साथ चल रहा था। उपाय छोटे थे लेकिन असरदार। अब एंगेजमेंट हो चुकी है और फाइनेंस भी धीरे-धीरे सुधर रहा है। खुद को ब्लेस्ड महसूस करती हूं।\",\n    feedbackTestimonial11:\n      \"पहले मुझे विश्वास नहीं था लेकिन रिजल्ट देखकर हैरान रह गया। लंबे समय बाद करियर ग्रोथ शुरू हुई और नई ऑपर्च्युनिटी मिल रही है। अच्छी गाइडेंस और सच्ची भविष्यवाणी।\",\n    feedbackTestimonial12:\n      \"हेल्थ प्रॉब्लम और नेगेटिव सोच बहुत ज्यादा थी। उपाय करने के बाद अब मेंटली स्ट्रॉन्ग और शांत महसूस करती हूं। परिवार वाले भी बदलाव देख रहे हैं। बहुत ग्रेटफुल हूं।\",\n    feedbackTestimonial13:\n      \"छोटा सा रिव्यू। करियर अब बेहतर है और पैसे का फ्लो भी उपाय के बाद सुधरा। धन्यवाद।\",\n    feedbackTestimonial14:\n      \"कुंडली रीडिंग से मुझे जिंदगी की कई छुपी समस्याएं समझ आईं जैसे शादी में देरी और जॉब कन्फ्यूजन। उपाय रोज करने वाले आसान काम थे। धीरे-धीरे लाइफ स्टेबल हो रही है। अच्छा एक्सपीरियंस।\",\n    feedbackTestimonial15:\n      \"जिसे शादी, करियर या फाइनेंस की समस्या हो उसे मैं जरूर रिकमेंड करूंगा। सिंपल लैंग्वेज और सच्ची गाइडेंस। कुछ ही महीनों में पॉजिटिव बदलाव देखा। बहुत अच्छा।\",\n    feedbackAuthor1: \"अभिषेक मिश्रा\",\n    feedbackAuthor2: \"पूजा वर्मा\",\n    feedbackAuthor3: \"अमित पटेल\",\n    feedbackAuthor4: \"स्नेहा गुप्ता\",\n    feedbackAuthor5: \"विकास यादव\",\n    feedbackAuthor6: \"नेहा सिंह\",\n    feedbackAuthor7: \"राहुल जैन\",\n    feedbackAuthor8: \"कविता मिश्रा\",\n    feedbackAuthor9: \"संदीप कुमार\",\n    feedbackAuthor10: \"अंजलि मेहता\",\n    feedbackAuthor11: \"दीपक अरोड़ा\",\n    feedbackAuthor12: \"रितु सक्सेना\",\n    feedbackAuthor13: \"मनोज तिवारी\",\n    feedbackAuthor14: \"प्रिया नायर\",\n    feedbackAuthor15: \"करन मल्होत्रा\",\n    feedbackAuthor1AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639330970.png\",\n    feedbackAuthor2AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639293055.png\",\n    feedbackAuthor3AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639358174.png\",\n    feedbackAuthor4AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639427379.png\",\n    feedbackAuthor5AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639381899.png\",\n    feedbackAuthor6AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639416587.png\",\n    feedbackAuthor7AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639454626.png\",\n    feedbackAuthor8AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639319028.png\",\n    feedbackAuthor9AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639271096.png\",\n    feedbackAuthor10AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639254172.png\",\n    feedbackAuthor11AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639345411.png\",\n    feedbackAuthor12AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639306698.png\",\n    feedbackAuthor13AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639330970.png\",\n    feedbackAuthor14AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639402894.png\",\n    feedbackAuthor15AvatarUrl: \"https://srm-cdn.a4b.io/yoda/1770639358174.png\",\n    readMoreReviews: \"और समीक्षाएं पढ़ें\",\n    readLess: \"कम पढ़ें\",\n    // Marriage-specific reviews\n    feedbackTitleMarriage:\n      \"अन्य लोगों ने शादी में देरी का सामना करते समय क्या खोजा\",\n    feedbackTestimonialMarriage1:\n      \"मेरी शादी बार-बार लेट हो रही थी और हम बहुत परेशान थे। यहां कुंडली बनवाने के बाद मुझे मंगल दोष और कुछ दूसरी समस्याओं के बारे में पता चला। जो उपाय बताए गए थे वो आसान थे और कुछ ही महीनों में सब ठीक होने लगा। अब मेरी सगाई तय हो गई है। बहुत धन्यवाद।\",\n    feedbackTestimonialMarriage2:\n      \"मैं पहले कुंडली पर ज्यादा भरोसा नहीं करता था, लेकिन मेरे माता-पिता ने मुझे इसे करने को कहा। उन्होंने मेरी कुंडली में शादी का दोष बताया और पूजा करने को कहा। पूजा करने के बाद मेरी मुलाकात रिश्तेदारों के जरिए एक अच्छे इंसान से हुई। कभी-कभी ये चीजें सच में काम करती हैं।\",\n    feedbackTestimonialMarriage3:\n      \"मैंने अपनी कुंडली चेक करवाई क्योंकि शादी के लिए कुछ भी सही नहीं हो रहा था। हर रिश्ता टूट जाता था। रिपोर्ट में साफ बताया गया कि समस्या क्या है और क्या करना है। 40 दिन तक उपाय करने के बाद अचानक एक अच्छा रिश्ता मिला। अब मेरी शादी हो चुकी है और मैं खुश हूं।\",\n    feedbackTestimonialMarriage4:\n      \"बहुत मददगार सेवा है। शादी में देरी का कारण भी बताया और उसका समाधान भी दिया। धीरे-धीरे सब ठीक होने लगा।\",\n    feedbackTestimonialMarriage5:\n      \"मैं 32 साल की थी और घर में बहुत तनाव था। कुंडली में शनि से जुड़ी समस्या बताई गई जो शादी में रुकावट डाल रही थी। बताए गए दान और मंत्र किए। 3 महीने के अंदर रिश्ता पक्का हो गया। आज भी ये किसी चमत्कार जैसा लगता है।\",\n    feedbackTestimonialMarriage6:\n      \"समझाना बहुत आसान था और सब कुछ साफ बताया गया। मुझे अच्छा लगा कि उन्होंने डराया नहीं बल्कि आसान उपाय बताए। उपाय करने के बाद मेरा पुराना रिश्ता दोनों परिवारों से मान्य हो गया और अब हमारी शादी होने वाली है।\",\n    feedbackTestimonialMarriage7:\n      \"छोटा रिव्यू है लेकिन सच है। उपाय करने के बाद शादी का दोष खत्म हुआ और अब शादी की तारीख तय हो गई है। बहुत धन्यवाद।\",\n    feedbackTestimonialMarriage8:\n      \"कई ज्योतिषियों ने अलग-अलग बातें बताईं जिससे मैं कन्फ्यूज हो गया था। यहां की कुंडली रिपोर्ट सच्ची और डिटेल में लगी। उन्होंने सही समस्या बताई जो रिश्ते टूटने का कारण थी। उपाय करने के बाद मेरा पार्टनर वापस आ गया और परिवार भी मान गए। अब मन शांत है।\",\n    feedbackTestimonialMarriage9:\n      \"मैंने बस ऐसे ही कुंडली बनवाई थी लेकिन रिजल्ट देखकर हैरान रह गई। उसमें मजबूत मंगल दोष था। बताए अनुसार मंगलवार को पूजा की। कुछ महीनों में उसी शहर से अच्छा रिश्ता मिला। उसके बाद सब कुछ आसानी से हो गया।\",\n    feedbackTestimonialMarriage10:\n      \"सेवा अच्छी और तेज है। रिपोर्ट साफ और समझ में आने वाली है। उपाय करने के बाद मेरी शादी की समस्या हल हो गई। संतुष्ट हूं।\",\n    feedbackTestimonialMarriage11:\n      \"5 साल से मेरी शादी को लेकर कुछ भी नहीं हो रहा था। कुंडली मिलान के बाद उन्होंने कुछ महीनों तक इंतजार और पूजा करने को कहा। उसी समय मुझे ऑफिस में अपने पति मिले। अब हमारी शादी को 1 साल हो गया है और हम खुश हैं।\",\n    feedbackTestimonialMarriage12:\n      \"ये लिखते समय मेरे लिए बहुत भावुक पल है। मैंने लगभग उम्मीद छोड़ दी थी। उपाय करने से मुझे भरोसा और पॉजिटिव सोच मिली। धीरे-धीरे सब ठीक हुआ और आज मेरी रोका सेरेमनी हो गई है। दिल से धन्यवाद।\",\n    feedbackTestimonialMarriage13:\n      \"अच्छी सलाह और सही भविष्यवाणी। कोई झूठे वादे नहीं किए। उपायों से मेरी शादी में देरी की समस्या दूर हुई।\",\n    feedbackTestimonialMarriage14:\n      \"मेरी बेटी की कुंडली यहां चेक करवाई। उन्होंने दोष बताया और आसान मंदिर जाने और व्रत करने को कहा। हमने पूरी श्रद्धा से किया। कुछ ही समय में अच्छे परिवार से रिश्ता आया। माता-पिता होने के नाते हम बहुत राहत महसूस कर रहे हैं।\",\n    feedbackTestimonialMarriage15:\n      \"मैं उन सभी लोगों को ये सेवा सुझाता हूं जिनकी शादी में देरी हो रही है। कुंडली रिपोर्ट असली लगी, कॉपी-पेस्ट नहीं। छोटे-छोटे उपाय लेकिन जीवन में बड़ा बदलाव आया। दिल से धन्यवाद।\",\n    faqTitle: \"अक्सर पूछे जाने वाले प्रश्न\",\n    faqQ1: \"क्या यह वास्तव में मुफ्त है?\",\n    faqA1:\n      \"हाँ, दोष कैलकुलेटर बिल्कुल मुफ्त है। आप बिना किसी लागत के अपनी कुंडली में दोष जांच सकते हैं और विस्तृत विश्लेषण प्राप्त कर सकते हैं।\",\n    faqQ2: \"अगर मुझे जन्म का समय नहीं पता तो?\",\n    faqA2:\n      \"आप एक अनुमानित जन्म समय दर्ज कर सकते हैं या डिफ़ॉल्ट के रूप में 12:00 PM का उपयोग कर सकते हैं। मंगल दोष और काल सर्प दोष जैसे कुछ दोषों का पता अनुमानित समय से भी लगाया जा सकता है।\",\n    faqQ3: \"क्या यह एक सामान्य रिपोर्ट है?\",\n    faqA3:\n      \"नहीं, आपकी रिपोर्ट आपकी सटीक जन्म तिथि, समय और जन्म स्थान के आधार पर व्यक्तिगत है। प्रत्येक कुंडली विश्लेषण अद्वितीय है और दोष पहचान आपकी जन्म कुंडली के लिए विशिष्ट है।\",\n    // Marriage-specific FAQs\n    faqQ1Marriage: \"क्या यह वास्तव में मुफ्त है?\",\n    faqA1Marriage:\n      \"हाँ, दोष कैलकुलेटर बिल्कुल मुफ्त है। आप बिना किसी लागत के अपनी कुंडली में दोष जांच सकते हैं और विस्तृत विश्लेषण प्राप्त कर सकते हैं।\",\n    faqQ2Marriage: \"अगर मुझे जन्म का समय नहीं पता तो?\",\n    faqA2Marriage:\n      \"आप एक अनुमानित जन्म समय दर्ज कर सकते हैं या डिफ़ॉल्ट के रूप में 12:00 PM का उपयोग कर सकते हैं। मंगल दोष और काल सर्प दोष जैसे कुछ दोषों का पता अनुमानित समय से भी लगाया जा सकता है।\",\n    faqQ3Marriage: \"क्या यह एक सामान्य रिपोर्ट है?\",\n    faqA3Marriage:\n      \"नहीं, आपकी रिपोर्ट आपकी सटीक जन्म तिथि, समय और जन्म स्थान के आधार पर व्यक्तिगत है। प्रत्येक कुंडली विश्लेषण अद्वितीय है और दोष पहचान आपकी जन्म कुंडली के लिए विशिष्ट है।\",\n    faqQ4Marriage: \"क्या यह मेरी शादी में देरी को ठीक करेगा?\",\n    faqA4Marriage:\n      \"कैलकुलेटर उन दोषों की पहचान करता है जो शादी में देरी का कारण हो सकते हैं। एक बार पता लगने के बाद, हम विशिष्ट पूजा और उपायों की अनुशंसा करते हैं जिन्होंने हजारों उपयोगकर्ताओं को विवाह की बाधाओं को दूर करने में मदद की है।\",\n    // Dosha form\n    formPrivacyBanner: \"100% प्राइवेट और सुरक्षित\",\n    formTitle: \"अपना विवरण दर्ज करें\",\n    formSubtitle: \"हम आपके दोष जानने के लिए आपकी कुंडली बनाएंगे।\",\n    formNameLabel: \"अपना नाम दर्ज करें\",\n    formNamePlaceholder: \"आपका नाम\",\n    formGenderLabel: \"आपका लिंग\",\n    formGenderMale: \"पुरुष\",\n    formGenderFemale: \"महिला\",\n    formProblemLabel: \"कौन सी समस्या आपको परेशान कर रही है?\",\n    formProblemMarriage: \"विवाह\",\n    formProblemMoney: \"धन\",\n    formProblemOther: \"अन्य\",\n    formProblemHealth: \"स्वास्थ्य\",\n    formProblemEducation: \"शिक्षा\",\n    formProblemCareer: \"करियर\",\n    formProblemOtherPlaceholder: \"कृपया अपनी समस्या बताएं\",\n    formProblemOtherHint: \"अधिकतम 100 अक्षर\",\n    formDobLabel: \"जन्म तिथि चुनें\",\n    formDobInfo:\n      \"आपकी जन्म तिथि का उपयोग आपके दोष संतुलन की गणना के लिए किया जाता है।\",\n    formTimeLabel: \"जन्म का सटीक समय\",\n    formTimeInfo: \"जन्म समय विश्लेषण की सटीकता बढ़ाने में मदद करता है।\",\n    formTimeUnknown: \"मुझे अपने जन्म का समय नहीं पता\",\n    formTimeUnknownHelp: \"नोट - जन्म का सटीक समय न होने पर सटीकता कम हो जाएगी। हम केवल चंद्रमा आधारित जाँच ही करेंगे।\",\n    formPlaceLabel: \"अपना जन्म स्थान दर्ज करें\",\n    formPlaceInfo:\n      \"शहर और राज्य/देश हमें आपका परिणाम बेहतर बनाने में मदद करते हैं।\",\n    formPlacePlaceholder: \"शहर, राज्य\",\n    formFooterNote: \"विश्लेषण में केवल 60 सेकंड लगते हैं\",\n    formFooterNoteBefore: \"विश्लेषण में केवल \",\n    formFooterNoteBold: \"60 सेकंड\",\n    formFooterNoteAfter: \" लगते हैं\",\n    formCta: \"मेरा दोष मुफ्त में जांचें\",\n    formCtaCalculate: \"मेरा दोष गणना करें\",\n    calculating: \"गणना हो रही है...\",\n    bookPuja: \"पूजा बुक करें\",\n    resultPageTitle: \"मुफ्त में पूजा उपाय खोजें\",\n    resultPageSubtitle:\n      \"अपनी कुंडली का विश्लेषण करें और जानें कि आपकी वैदिक कुंडली में कौन से दोष (यदि कोई हों) हैं—और भक्ति उपाय देखें।\",\n    calculationSuccess: \"आपका दोष विश्लेषण तैयार है।\",\n    calculationError: \"कुछ गड़बड़ हो गई। कृपया पुनः प्रयास करें।\",\n    formError: \"कृपया चिन्हित फ़ील्ड सही करें।\",\n    formNameRequired: \"नाम आवश्यक है।\",\n    formGenderRequired: \"लिंग आवश्यक है।\",\n    formDobRequired: \"जन्म तिथि आवश्यक है।\",\n    formTimeRequired: \"यदि जन्म समय ज्ञात है, तो समय आवश्यक है।\",\n    formPlaceRequired: \"जन्म स्थान आवश्यक है।\",\n    formPlaceSelectFromDropdown: \"कृपया ड्रॉपडाउन सूची से स्थान चुनें।\",\n    formAgeMarriageRestriction: \"कृपया उचित समस्या क्षेत्र चुनें। विवाह, वित्तीय, करियर और व्यापार संबंधी समस्याएं 18 वर्ष से अधिक आयु के उपयोगकर्ताओं के लिए हैं।\",\n    locationError: \"लोकेशन निर्देशांक प्राप्त नहीं हो सके। कृपया पुनः प्रयास करें।\",\n    calculationResolvingPlace: \"स्थान जांच रहे हैं…\",\n    info: \"जानकारी\",\n    // Results view\n    resultTitle: \"आपका दोष विश्लेषण\",\n    resultSomeDoshas: \"कुछ दोष पाए गए हैं\",\n    resultNoDoshas: \"कोई प्रमुख दोष नहीं मिला\",\n    resultNoDoshasDesc: \"आपकी कुंडली में कोई प्रमुख दोष नहीं है।\",\n    resultMangal: \"मंगल दोष\",\n    resultKaalSarp: \"काल सर्प दोष\",\n    resultPitra: \"पित्र दोष\",\n    resultSadeSati: \"शनि साढ़े साती\",\n    resultStatusPresent: \"उपस्थित\",\n    resultStatusAbsent: \"अनुपस्थित\",\n    resultStatusInactive: \"निष्क्रिय\",\n    resultExplanation: \"व्याख्या\",\n    resultRemedies: \"उपाय\",\n    resultEditForm: \"विवरण संपादित करें\",\n    // Detailed results (celestial-puja-finder style)\n    drStatus: \"स्थिति\",\n    drSeverity: \"गंभीरता\",\n    drType: \"प्रकार\",\n    drPhase: \"चरण\",\n    drExplanation: \"व्याख्या\",\n    drWhyPresent: \"क्यों मौजूद\",\n    drWhyAbsent: \"क्यों अनुपस्थित\",\n    drImpact: \"प्रभाव\",\n    drPlanetaryPositions: \"ग्रहों की स्थिति\",\n    drTraditionalRemedies: \"पारंपरिक उपचार\",\n    drDetailedAnalysis: \"विस्तृत विश्लेषण और उपचार\",\n    drBasedOnChart: \"आपके जन्म चार्ट गणना के आधार पर\",\n    drDisclaimer:\n      \"हम स्थापित ज्योतिषीय नियमों का पालन करते हैं, परंतु दोष की व्याख्या विभिन्न ज्योतिषियों में भिन्न हो सकती है। यदि आप अन्य दृष्टिकोण जानना चाहें तो किसी विश्वसनीय ज्योतिषी से परामर्श करें।\",\n    drStatusPresent: \"उपस्थित\",\n    drStatusAbsent: \"अनुपस्थित\",\n    drStatusInactive: \"निष्क्रिय\",\n    drStatusActive: \"सक्रिय\",\n    drStatusSuggested: \"सुझाया गया\",\n    drStatusNullified: \"उपस्थित (निरस्त)\",\n    drMangalName: \"मंगल दोष (मांगलिक)\",\n    drMangalDesc:\n      \"मंगल (मांगलिक/कुजा) दोष — कुछ घरों में मंगल से जुड़ा; पारंपरिक रूप से रिश्तों में घर्षण और निर्णायकता से जुड़ा है।\",\n    drMangalImpact:\n      \"करीबी रिश्तों में घर्षण की अधिक संभावना, अधीरता/क्रोध के झटके, या विवाह या साझेदारी में देरी और रुक-रुक कर शुरुआत।\",\n    drMangalRemedies:\n      \"प्रतिदिन हनुमान चालीसा का पाठ करें\\nमंगलवार को व्रत रखें\\nलाल दाल या कपड़े का दान करें\\nपरामर्श के बाद मूंगा रत्न पहनें\",\n    drKaalSarpName: \"काल सर्प दोष\",\n    drKaalSarpDesc:\n      \"काल सर्प दोष — सभी ग्रह राहु और केतु के बीच फंसे; अक्सर आंतरिक तनाव और परिवर्तन के पैटर्न के रूप में तैयार किया जाता है।\",\n    drKaalSarpImpact:\n      \"आंतरिक बेचैनी और आवधिक असफलताओं का एक पैटर्न; प्रयास के बावजूद योजनाएं अवरुद्ध या विलंबित हो सकती हैं।\",\n    drKaalSarpRemedies:\n      \"प्रतिदिन 108 बार महा मृत्युंजय मंत्र का जाप करें\\nनियमित रूप से आवारा कुत्तों को खाना खिलाएं\\nसांप कल्याण या नाग मंदिरों में दान करें\\nघर में चांदी का नाग रखें\",\n    drPitraName: \"पितृ दोष\",\n    drPitraDesc:\n      \"पितृ (पितृ) दोष — 9वें घर और सूर्य-नोड लिंक के आसपास पारंपरिक संकेतक; कर्तव्यों, वंश और मार्गदर्शन से जुड़े।\",\n    drPitraImpact:\n      \"परिवार या बड़ों के प्रति बार-बार कर्तव्य/दायित्व; अपराधबोध, विवाद, या विरासत के मुद्दे सामने आ सकते हैं।\",\n    drPitraRemedies:\n      \"तिथियों पर श्राद्ध समारोह करें\\nअमावस्या को जरूरतमंदों को भोजन कराएं\\nपितृ गायत्री मंत्र का पाठ करें\\nप्रतिदिन सुबह पूर्वजों को जल अर्पित करें\",\n    drSadeSatiName: \"शनि साढ़े साती\",\n    drSadeSatiDesc:\n      \"शनि साढ़े साती — जन्म चंद्रमा के पड़ोस में शनि का संक्रमण; अनुशासन और धैर्य पर जोर देने वाला 7.5 साल का चक्र।\",\n    drSadeSatiImpact:\n      \"भारी जिम्मेदारियां, धीमी प्रगति, और धैर्य की परीक्षा; गति के बजाय लगातार अनुशासन के साथ परिणाम आते हैं।\",\n    drSadeSatiRemedies:\n      \"शनिवार को शनि मंत्र का जाप करें\\nशनिवार को सरसों के तेल का दीपक जलाएं\\nतिल, कंबल जैसी काली वस्तुओं का दान करें\\nकौवों को खिलाएं और विकलांगों की सेवा करें\",\n    drWhyMarked: \"यह दोष आपकी कुंडली में क्यों है?\",\n    drViewKundli: \"कुंडली देखें\",\n    drPhaseMeaning: \"वर्तमान चरण का अर्थ:\",\n    drPhaseRising:\n      \"उदय चरण: शनि आपकी चंद्र राशि से पहले की राशि में है। यह साढ़े साती की शुरुआत है।\",\n    drPhasePeak:\n      \"शिखर चरण: शनि आपकी चंद्र राशि में है। यह साढ़े साती का सबसे प्रभावशाली समय है।\",\n    drPhaseSetting:\n      \"अस्त चरण: शनि आपकी चंद्र राशि के बाद की राशि में है। साढ़े साती समाप्त होने वाली है।\",\n    drImpactIfPresent: \"प्रभाव\",\n    drPujaRecommendation: \"पूजा उपाय\",\n    drHowPujaHelps: \"यह पूजा कैसे मदद करेगी\",\n    drNoPujaAvailable: \"इस दोष के लिए कोई विशेष पूजा उपलब्ध नहीं है\",\n    drFeedbackContact: \"प्रतिक्रिया या सुझाव के लिए संपर्क करें\",\n    drGoBack: \"वापस जाएं\",\n    drDoshaOf: \"दोष {{index}} का {{total}}\",\n    drTranslating: \"अनुवाद हो रहा है...\",\n    drAnalyzingImpact: \"प्रभाव विश्लेषण हो रहा है...\",\n    drSeverityHigh: \"उच्च\",\n    drSeverityMedium: \"मध्यम\",\n    drSeverityLow: \"निम्न\",\n    drBasedOnPositions: \"ग्रहों की स्थिति के आधार पर\",\n    drPujaBenefitsMangal:\n      \"संघर्ष और अस्थिरता पैदा करने वाली आक्रामक मंगल ऊर्जा को शांत करती है।\\nमंगल को शांत करने के लिए हवन से बाधाओं को कम करती है।\\nरिश्तों और पारिवारिक जीवन में सामंजस्य को मजबूत करती है।\\nआवेगपूर्ण निर्णयों और गरमागरम टकराव से बचाती है।\",\n    drPujaBenefitsKaalSarp:\n      \"अचानक झटके देने वाली राहु-केतु ऊर्जाओं को संतुलित करती है।\\nअनुष्ठान भय, भ्रम और अप्रत्याशित नुकसान को कम करते हैं।\\nकर्म संबंधी गड़बड़ियों से सुरक्षा को मजबूत करती है।\\nजीवन के प्रमुख क्षेत्रों में दिशा और स्थिरता बहाल करती है।\",\n    drPujaBenefitsPitra:\n      \"तर्पण के माध्यम से पूर्वजों को शांति प्रदान करती है।\\nप्रगति में बाधा डालने वाली अदृश्य पारिवारिक बाधाओं को दूर करती है।\\nपैतृक असंतुलन के कारण खोए हुए आशीर्वाद को पुनर्स्थापित करती है।\\nस्वास्थ्य, स्थिरता और पारिवारिक सद्भाव में सुधार करती है।\",\n    drPujaBenefitsShani:\n      \"शनि अभिषेक अनुष्ठानों से शनि के दबाव को शांत करती है।\\nदेरी, वित्तीय तनाव और मानसिक बोझ को कम करती है।\\nशनि की परीक्षा अवधि में लचीलापन बढ़ाती है।\\nस्थिर प्रगति और दीर्घकालिक सुरक्षा लाती है।\",\n    drFomoLine:\n      \"पूजाएं केवल चुनिंदा तिथियों पर मंदिरों में आयोजित की जाती हैं, और अनुष्ठान की पवित्रता बनाए रखने के लिए स्थान सीमित हैं।\",\n    drOtherDoshas: \"अन्य दोष\",\n    drOtherDoshasStatusActive: \"स्थिति: कुछ दोष सक्रिय\",\n    drOtherDoshasStatusNone: \"स्थिति: कोई अन्य दोष नहीं मिला\",\n    drYourKundali: \"आपकी कुंडली\",\n    kundaliChartNorth: \"उत्तर\",\n    kundaliChartSouth: \"दक्षिण\",\n    kundaliChartRetry: \"पुनः प्रयास करें\",\n    kundaliChartLoadError: \"कुंडली लोड नहीं हो सकी\",\n    drPlanetaryPositionsCausing: \"दोषों का कारण - ग्रह स्थिति\",\n    drOtherGrahan: \"राहु-केतु / ग्रहण दोष\",\n    drOtherShrapit: \"श्रापित दोष\",\n    drOtherGuruChandal: \"गुरु चांडाल दोष\",\n    drOtherPunarphoo: \"पुनर्फू दोष\",\n    drOtherKemadruma: \"केमद्रुम योग\",\n    drOtherGandmool: \"गण्डमूल दोष\",\n    drOtherKalathra: \"कलात्र दोष\",\n    drOtherVishDaridra: \"विष दरिद्र योग\",\n    drOtherKetuNaga: \"केतु नाग दोष\",\n    drOtherNavagraha: \"नवग्रह असंतुलन\",\n    // Other Doshas - Descriptions\n    drOtherGrahanDesc: \"जब राहु-केतु सूर्य या चंद्र को ग्रसित करते हैं; अचानक चुनौतियों या छिपे हुए भय से जुड़ा होता है।\",\n    drOtherShrapitDesc: \"किसी भी भाव में शनि-राहु युति; पूर्वजों के कर्म ऋण जिन्हें समाधान की आवश्यकता है।\",\n    drOtherGuruChandalDesc: \"बृहस्पति राहु/केतु से पीड़ित; उच्च ज्ञान और भौतिक इच्छाओं के बीच संघर्ष।\",\n    drOtherPunarphooDesc: \"शनि-चंद्र पीड़ा जो बार-बार भावनात्मक चक्र या दोहराए जाने वाले पैटर्न को दर्शाती है।\",\n    drOtherKemadrumaDesc: \"चंद्रमा शुभ समर्थन से अलग; भावनात्मक कमजोरी की अवधि का संकेत।\",\n    drOtherGandmoolDesc: \"विशिष्ट चंद्र नक्षत्रों (अश्विनी, रेवती, आदि) में जन्म; पारंपरिक रूप से विशेष अनुष्ठान की आवश्यकता।\",\n    drOtherKalathraDec: \"7वें भाव या उसके स्वामी में पीड़ा; मुख्य रूप से साझेदारी और विवाह विषयों से जुड़ा।\",\n    drOtherVishDaridraDesc: \"मंगल-शनि चुनौतीपूर्ण पहलू कार्य और सावधानी के बीच तनाव पैदा करता है।\",\n    drOtherKetuNagaDesc: \"केतु से संबंधित सर्प ऊर्जा; आध्यात्मिक परिवर्तन और पूर्वजन्म पैटर्न से जुड़ा।\",\n    drOtherNavagrahaDesc: \"कई ग्रह पीड़ाएं व्यापक ग्रह शांति अनुष्ठानों की आवश्यकता का सुझाव देती हैं।\",\n    // Other Doshas - Impact (when present)\n    drOtherGrahanImpact: \"अचानक असफलताएं, छिपी चिंताएँ, या ग्रहण संबंधी संवेदनशीलता उत्पन्न हो सकती है; भावनात्मक उतार-चढ़ाव।\",\n    drOtherShrapitImpact: \"पूर्वजों के दायित्व, बार-बार आने वाली बाधाएं, या कर्म पाठ जो धैर्य और समाधान की मांग करते हैं।\",\n    drOtherGuruChandalImpact: \"निर्णय के मुद्दे, गुरु समस्याएं, या आध्यात्मिक/नैतिक मामलों में वादों और परिणामों के बीच असंतुलन।\",\n    drOtherPunarphooImpact: \"भावनात्मक चक्र दोहराना; रिश्ते या स्थितियां नए प्रयास की आवश्यकता वाली वापसी कर सकती हैं।\",\n    drOtherKemadrumaImpact: \"भावनात्मक अलगाव या समर्थन की कमी की अवधि; कमजोर चरणों में लचीलेपन की आवश्यकता।\",\n    drOtherGandmoolImpact: \"जन्म नक्षत्र चुनौतियां; सुरक्षित जीवन संक्रमण के लिए पारंपरिक उपाय सलाह दी जाती है।\",\n    drOtherKalathraImpact: \"साझेदारी घर्षण, विवाह में देरी, या 7वें भाव मामले जो ध्यान और धैर्य की आवश्यकता है।\",\n    drOtherVishDaridraImpact: \"कार्य-सावधानी संघर्ष; वित्तीय तनाव या मंगल-शनि तनाव रुक-रुक कर पैटर्न बनाता है।\",\n    drOtherKetuNagaImpact: \"आध्यात्मिक बेचैनी, पूर्व जीवन की प्रतिध्वनि, या सर्प-ऊर्जा विषय जिन्हें मान्यता की आवश्यकता है।\",\n    drOtherNavagrahaImpact: \"कई ग्रह असंतुलन विविध जीवन चुनौतियां पैदा करते हैं; व्यापक उपाय अनुशंसित।\",\n    // Other Doshas - Remedies (when present)\n    drOtherGrahanRemedies: \"ग्रहण के दौरान राहु-केतु मंत्र जाप करें\\nग्रहण संबंधी धर्मार्थों को दान दें\\nपरामर्श के बाद गोमेद या लहसुनिया पहनें\\nग्रहण शांति पूजा करें\",\n    drOtherShrapitRemedies: \"शनिवार को शनि और राहु की पूजा करें\\nशनि-राहु मंत्र का पाठ करें\\nकाले और नीले वस्तुओं का दान करें\\nनियमित रूप से पितरों के संस्कार करें\",\n    drOtherGuruChandalRemedies: \"गुरु मंत्र (बृहस्पति मंत्र) का पाठ करें\\nगुरुवार को पीली वस्तुओं का दान करें\\nविद्वान शिक्षकों से आशीर्वाद लें\\nपरामर्श के बाद पुखराज पहनें\",\n    drOtherPunarphooRemedies: \"शनि और चंद्र मंत्र का जाप करें\\nबुजुर्गों और माताओं को दान दें\\nमोती और नीलम पहनें (यदि सलाह दी जाए)\\nशनि-चंद्र शांति करें\",\n    drOtherKemadrumaRemedies: \"प्रतिदिन चंद्र मंत्र का पाठ करें\\nसोमवार को व्रत रखें\\nदूध, चावल जैसी सफेद वस्तुओं का दान करें\\nपरामर्श के बाद मोती रत्न पहनें\",\n    drOtherGandmoolRemedies: \"गण्डमूल नक्षत्र शांति पूजा करें\\nजन्म नक्षत्र मंत्र का पाठ करें\\nनक्षत्र दिशानिर्देशों के अनुसार दान दें\\nअनुष्ठानों के लिए पुजारी मार्गदर्शन लें\",\n    drOtherKalathraRemedies: \"शुक्र और 7वें स्वामी की पूजा करें\\nकलात्र दोष मंत्र का पाठ करें\\nविवाह/साझेदारी कारणों के लिए दान करें\\nपरामर्श के बाद हीरा/ओपल पहनें\",\n    drOtherVishDaridraRemedies: \"मंत्रों के साथ मंगल-शनि ऊर्जा संतुलित करें\\nलाल और काली वस्तुओं का दान करें\\nमंगल-शनि शांति पूजा करें\\nलाल मूंगा और नीलम पहनें (यदि सलाह दी जाए)\",\n    drOtherKetuNagaRemedies: \"नाग मंदिरों में सर्प देवताओं की पूजा करें\\nकेतु मंत्र का पाठ करें\\nसांप कल्याण के लिए दान दें\\nपरामर्श के बाद लहसुनिया पहनें\",\n    drOtherNavagrahaRemedies: \"व्यापक नवग्रह शांति पूजा करें\\nनवग्रह मंत्र का पाठ करें\\nसभी नौ ग्रहों के लिए वस्तुओं का दान करें\\nनवग्रह मंदिरों में जाएं\",\n    // Trust badges (marquee under header)\n    ctaKundliCreated: \"3L+ कुंडली रिपोर्ट बनाई।\",\n    ctaCertified: \"BHU प्रमाणित ज्योतिषी।\",\n    ctaSecurePayment: \"सुरक्षित भुगतान।\",\n    contactTitle: \"संपर्क करें\",\n    contactBrandName: \"श्री मंदिर\",\n    contactWhatsAppGlobal: \"व्हाट्सएप: 8296947757\",\n    contactWhatsAppDomestic: \"व्हाट्सएप: 08071174417\",\n    contactEmail: \"ईमेल: pujaseva@appsforbharat.com\",\n    whatFromAnalysisTitle: \"इस विश्लेषण से आपको क्या मिलेगा\",\n    // Marriage-specific content\n    whatFromAnalysisMarriage1Title: \"शादी पर प्रभाव जानें\",\n    whatFromAnalysisMarriage1Desc:\n      \"क्या शादी में देरी होगी, कोई समस्या आएगी या मैच सही रहेगा।\",\n    whatFromAnalysisMarriage2Title: \"मंगल दोष की पुष्टि\",\n    whatFromAnalysisMarriage2Desc:\n      \"जानें कि मंगल दोष है या नहीं और वह कितना मजबूत है।\",\n    whatFromAnalysisMarriage3Title: \"उपाय और पूजा की जानकारी\",\n    whatFromAnalysisMarriage3Desc: \"कौन सा उपाय या पूजा आपके लिए सही रहेगा।\",\n    // Generic content\n    whatFromAnalysisGeneric1Title: \"जीवन पर प्रभाव का संक्षेप\",\n    whatFromAnalysisGeneric1Desc:\n      \"शादी, करियर, पैसे, सेहत और पढ़ाई में होने वाली देरी, परेशानी या अवसरों को समझें\",\n    whatFromAnalysisGeneric2Title: \"दोष की पुष्टि\",\n    whatFromAnalysisGeneric2Desc:\n      \"जानें कि कोई दोष या ग्रहों का असंतुलन आपकी प्रगति को प्रभावित कर रहा है या नहीं\",\n    whatFromAnalysisGeneric3Title: \"उपाय की दिशा\",\n    whatFromAnalysisGeneric3Desc: \"कौन सा उपाय या पूजा आपके लिए सही रहेगा।\",\n  },\n};\n","import { createContext, useContext, useEffect, useMemo, useState } from 'react';\nimport type { SupportedLocale } from './translations';\nimport { translations } from './translations';\n\ninterface I18nContextValue {\n  locale: SupportedLocale;\n  setLocale: (locale: SupportedLocale) => void;\n  t: (key: string) => string;\n}\n\nconst I18nContext = createContext<I18nContextValue | null>(null);\n\ninterface I18nProviderProps {\n  locale?: SupportedLocale;\n  onLocaleChange?: (locale: SupportedLocale) => void;\n  children: React.ReactNode;\n}\n\n// Get locale from URL path (e.g., /en/dosha or /hi/dosha)\nfunction getLocaleFromUrl(): SupportedLocale {\n  if (typeof window === 'undefined') return 'en';\n  const path = window.location.pathname.split('/').filter(Boolean);\n  return path[0] === 'hi' ? 'hi' : 'en';\n}\n\n// Update URL with new locale\nfunction updateUrl(newLocale: SupportedLocale) {\n  const { pathname, search, hash } = window.location;\n  const segments = pathname.split('/').filter(Boolean);\n  const firstIsLocale = segments[0] === 'en' || segments[0] === 'hi';\n  \n  if (firstIsLocale) segments[0] = newLocale;\n  else segments.unshift(newLocale);\n  \n  window.location.href = '/' + segments.join('/') + search + hash;\n}\n\nexport function I18nProvider({ locale, onLocaleChange, children }: I18nProviderProps) {\n  const [currentLocale, setCurrentLocale] = useState<SupportedLocale>(\n    () => locale || getLocaleFromUrl()\n  );\n\n  useEffect(() => {\n    if (locale) setCurrentLocale(locale);\n    else {\n      const handlePop = () => setCurrentLocale(getLocaleFromUrl());\n      window.addEventListener('popstate', handlePop);\n      return () => window.removeEventListener('popstate', handlePop);\n    }\n  }, [locale]);\n\n  const handleSetLocale = (newLocale: SupportedLocale) => {\n    onLocaleChange ? onLocaleChange(newLocale) : updateUrl(newLocale);\n  };\n\n  const t = useMemo(\n    () => (key: string) => translations[currentLocale]?.[key] ?? key,\n    [currentLocale]\n  );\n\n  return (\n    <I18nContext.Provider value={{ locale: currentLocale, setLocale: handleSetLocale, t }}>\n      {children}\n    </I18nContext.Provider>\n  );\n}\n\nexport function useI18n(): I18nContextValue | null {\n  return useContext(I18nContext);\n}\n","import styles from './FooterTrustBadge.module.scss';\nimport { useI18n } from '../../i18n';\n\nexport function FooterTrustBadge() {\n  const i18n = useI18n();\n  const isHindi = i18n?.locale === 'hi';\n\n  return (\n    <div className={styles.container}>\n      {isHindi \n        ? '100% सटीक • सुरक्षित • 30 लाख+ परिवारों द्वारा विश्वसनीय'\n        : '100% Accurate • Secure • Trusted by 30L+ families'\n      }\n    </div>\n  );\n}","import * as React from 'react';\n\nconst sizeProps = (size: number) => ({ width: size, height: size });\n\nexport function AlertTriangle(props: React.SVGAttributes<SVGElement> & { size?: number }) {\n  const { size = 24, ...rest } = props;\n  return (\n    <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" {...sizeProps(size)} {...rest}>\n      <path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z\" />\n      <path d=\"M12 9v4\" />\n      <path d=\"M12 17h.01\" />\n    </svg>\n  );\n}\n\nexport function CheckCircle(props: React.SVGAttributes<SVGElement> & { size?: number }) {\n  const { size = 24, ...rest } = props;\n  return (\n    <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" {...sizeProps(size)} {...rest}>\n      <path d=\"M22 11.08V12a10 10 0 1 1-5.93-9.14\" />\n      <path d=\"m9 11 3 3L22 4\" />\n    </svg>\n  );\n}\n\nexport function Info(props: React.SVGAttributes<SVGElement> & { size?: number }) {\n  const { size = 24, ...rest } = props;\n  return (\n    <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" {...sizeProps(size)} {...rest}>\n      <circle cx=\"12\" cy=\"12\" r=\"10\" />\n      <path d=\"M12 16v-4\" />\n      <path d=\"M12 8h.01\" />\n    </svg>\n  );\n}\n\nexport function Flame(props: React.SVGAttributes<SVGElement> & { size?: number }) {\n  const { size = 24, ...rest } = props;\n  return (\n    <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" {...sizeProps(size)} {...rest}>\n      <path d=\"M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z\" />\n    </svg>\n  );\n}\n\nexport function Waves(props: React.SVGAttributes<SVGElement> & { size?: number }) {\n  const { size = 24, ...rest } = props;\n  return (\n    <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" {...sizeProps(size)} {...rest}>\n      <path d=\"M2 6c.6.5 1.2 1 2.5 1C7 7 7 5 9.5 5c2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1\" />\n      <path d=\"M2 12c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1\" />\n      <path d=\"M2 18c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1\" />\n    </svg>\n  );\n}\n\nexport function Users(props: React.SVGAttributes<SVGElement> & { size?: number }) {\n  const { size = 24, ...rest } = props;\n  return (\n    <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" {...sizeProps(size)} {...rest}>\n      <path d=\"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2\" />\n      <circle cx=\"9\" cy=\"7\" r=\"4\" />\n      <path d=\"M22 21v-2a4 4 0 0 0-3-3.87\" />\n      <path d=\"M16 3.13a4 4 0 0 1 0 7.75\" />\n    </svg>\n  );\n}\n\nexport function Moon(props: React.SVGAttributes<SVGElement> & { size?: number }) {\n  const { size = 24, ...rest } = props;\n  return (\n    <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" {...sizeProps(size)} {...rest}>\n      <path d=\"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z\" />\n    </svg>\n  );\n}\n\nexport function ArrowUp(props: React.SVGAttributes<SVGElement> & { size?: number }) {\n  const { size = 24, ...rest } = props;\n  return (\n    <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" {...sizeProps(size)} {...rest}>\n      <path d=\"m5 12 7-7 7 7\" />\n      <path d=\"M12 19V5\" />\n    </svg>\n  );\n}\n\nexport function ChevronDown(props: React.SVGAttributes<SVGElement> & { size?: number }) {\n  const { size = 24, ...rest } = props;\n  return (\n    <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" {...sizeProps(size)} {...rest}>\n      <path d=\"m6 9 6 6 6-6\" />\n    </svg>\n  );\n}\n\nexport function Loader2(props: React.SVGAttributes<SVGElement> & { size?: number }) {\n  const { size = 24, className = '', ...rest } = props;\n  return (\n    <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" className={`animate-spin ${className}`} style={{ animation: 'spin 1s linear infinite' }} {...sizeProps(size)} {...rest}>\n      <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />\n    </svg>\n  );\n}\n\nexport function ExternalLink(props: React.SVGAttributes<SVGElement> & { size?: number }) {\n  const { size = 24, ...rest } = props;\n  return (\n    <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" {...sizeProps(size)} {...rest}>\n      <path d=\"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6\" />\n      <polyline points=\"15 3 21 3 21 9\" />\n      <line x1=\"10\" x2=\"21\" y1=\"14\" y2=\"3\" />\n    </svg>\n  );\n}\n\nexport function RotateCcw(props: React.SVGAttributes<SVGElement> & { size?: number }) {\n  const { size = 24, ...rest } = props;\n  return (\n    <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" {...sizeProps(size)} {...rest}>\n      <path d=\"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8\" />\n      <path d=\"M3 3v5h5\" />\n    </svg>\n  );\n}\n","import React from \"react\";\n\n/** Props for an image component used by the package (e.g. next/image adapter on host). */\nexport interface DoshaImageProps {\n  src: string;\n  alt: string;\n  width?: number;\n  height?: number;\n  className?: string;\n  loading?: \"lazy\" | \"eager\";\n  sizes?: string;\n  /** When true, host can map to next/image priority (for LCP image). */\n  priority?: boolean;\n  /** Hint for LCP: pass \"high\" for above-the-fold images (e.g. next/image fetchPriority). */\n  fetchPriority?: \"high\" | \"low\" | \"auto\";\n}\n\nexport type DoshaImageComponent = React.ComponentType<DoshaImageProps>;\n\n/** Default image renderer when host does not provide one. */\nexport const DefaultDoshaImage: DoshaImageComponent = (props) => {\n  const { priority, fetchPriority, width, height, ...imgProps } = props;\n  return React.createElement(\"img\", {\n    ...imgProps,\n    width: width ?? 1,\n    height: height ?? 1,\n    decoding: \"async\",\n    loading: imgProps.loading ?? (priority ? \"eager\" : \"lazy\"),\n    ...(fetchPriority && { fetchPriority }),\n  });\n};\n","import { FooterCTAButton } from \"@srimandir/astrology-common\";\nimport { Loader2 } from \"../icons\";\nimport styles from \"./DoshaFooterCTA.module.scss\";\nimport { DefaultDoshaImage } from \"../../types/image\";\n\nconst ICON_CHEVRON_RIGHT = \"https://srm-cdn.a4b.io/yoda/1771588545907.svg\";\n\nexport interface DoshaFooterCTAProps {\n  /** Whether all required form fields are filled */\n  isFormComplete: boolean;\n  /** Called when the CTA is clicked (e.g. scroll to form or submit) */\n  onPress: () => void;\n  /** Label when form is incomplete (e.g. \"Check My Dosha for FREE\") */\n  labelDefault: string;\n  /** Label when form is complete (e.g. \"Calculate my dosha\") */\n  labelFilled: string;\n  /** When true, show loading state and disable click */\n  isLoading?: boolean;\n  /** Mode: 'form' for form submission, 'book-puja' for booking first puja */\n  mode?: \"form\" | \"book-puja\";\n  /** First puja data (for book-puja mode) */\n  firstPuja?: {\n    name: string;\n    price: number;\n  };\n  /** Whether results are being shown (switches to edit mode label) */\n  showingResults?: boolean;\n  /** Label for the book puja button (e.g. \"Book Puja\" or \"Book Now\") */\n  bookPujaLabel?: string;\n  /** Loading label for calculate mode (e.g. \"Calculating...\") */\n  loadingLabel?: string;\n}\n\nexport function DoshaFooterCTA({\n  isFormComplete,\n  onPress,\n  labelDefault,\n  labelFilled,\n  isLoading = false,\n  mode = \"form\",\n  firstPuja,\n  showingResults = false,\n  bookPujaLabel = \"Book Puja\",\n  loadingLabel = \"Calculating...\",\n}: DoshaFooterCTAProps) {\n  // Book Puja mode - show first puja with price\n  if (mode === \"book-puja\" && firstPuja && showingResults) {\n    return (\n      <FooterCTAButton\n        onClick={onPress}\n        disabled={isLoading}\n        className={styles.bookPujaButton}\n      >\n        <div className={styles.bookPujaContent}>\n          <div className={styles.pujaInfo}>\n            <span className={styles.pujaName}>{firstPuja.name}</span>\n            {firstPuja.price > 0 && (\n              <div className={styles.pujaPrice}>\n                <span className={styles.priceLabel}>Starting from </span>\n                <span className={styles.priceAmount}>₹{firstPuja.price}</span>\n              </div>\n            )}\n          </div>\n          <span className={styles.bookButton}>{bookPujaLabel} →</span>\n        </div>\n      </FooterCTAButton>\n    );\n  }\n\n  // Form mode - regular behavior\n  return (\n    <FooterCTAButton\n      onClick={onPress}\n      disabled={isLoading}\n      className={isFormComplete ? styles.ctaFilled : undefined}\n    >\n      {isLoading ? (\n        <span className={styles.ctaFilledContent}>\n          <Loader2 className=\"w-5 h-5 animate-spin\" />\n          {loadingLabel}\n        </span>\n      ) : isFormComplete ? (\n        <span className={styles.ctaFilledContent}>\n          {labelFilled}\n          <DefaultDoshaImage\n            src={ICON_CHEVRON_RIGHT}\n            alt=\"\"\n            className={styles.chevronRight}\n            width={20}\n            height={20}\n            loading=\"lazy\"\n          />\n        </span>\n      ) : (\n        labelDefault\n      )}\n    </FooterCTAButton>\n  );\n}\n","import React from \"react\";\nimport styles from \"./DoshaBanner.module.scss\";\nimport type { BannerConfig } from \"../../constants/bannerConfig\";\nimport type { DoshaImageComponent } from \"../../types/image\";\nimport { DefaultDoshaImage } from \"../../types/image\";\n\nexport interface DoshaBannerProps {\n  /** Banner configuration containing image URL and alt text */\n  bannerConfig: BannerConfig;\n  /** Optional additional CSS class */\n  className?: string;\n  /** Optional image component for optimization */\n  imageComponent?: DoshaImageComponent;\n}\n\n/**\n * DoshaBanner - Displays promotional banner based on utm_term and locale\n */\nexport function DoshaBanner({\n  bannerConfig,\n  className = \"\",\n  imageComponent = DefaultDoshaImage,\n}: DoshaBannerProps) {\n  const Img = imageComponent;\n  return (\n    <section className={`${styles.bannerContainer} ${className}`}>\n      <Img\n        src={bannerConfig.imageUrl}\n        alt={bannerConfig.alt}\n        className={styles.bannerImage}\n        loading=\"eager\"\n        priority={true}\n        fetchPriority=\"high\"\n      />\n      <div className={styles.ticker}>\n        <div className={styles.tickerContent}>{bannerConfig.tickerText}</div>\n      </div>\n    </section>\n  );\n}\n","import { useRef, useEffect } from \"react\";\n\nconst FOOTER_HEIGHT_PX = 112;\n\nexport interface SectionWithImpressionProps {\n  /** Section identifier for the impression event */\n  section: string;\n  children: React.ReactNode;\n  /** Called once when the section enters the viewport */\n  onImpression: (section: string) => void;\n}\n\n/** Wraps a section and fires onImpression when it enters the viewport. */\nexport function SectionWithImpression({\n  section,\n  children,\n  onImpression,\n}: SectionWithImpressionProps) {\n  const ref = useRef<HTMLDivElement>(null);\n  const reported = useRef(false);\n  useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(\n      ([entry]) => {\n        if (!entry?.isIntersecting || reported.current) return;\n        reported.current = true;\n        onImpression(section);\n      },\n      {\n        threshold: 0.1,\n        rootMargin: `0px 0px -${FOOTER_HEIGHT_PX}px 0px`,\n      }\n    );\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [section, onImpression]);\n  return <div ref={ref}>{children}</div>;\n}\n","import { useRef, useMemo } from 'react';\nimport styles from './DoshaDateField.module.scss';\nimport { DefaultDoshaImage } from '../../types/image';\n\nconst ICON_DATE = 'https://srm-cdn.a4b.io/yoda/1770372045894.svg';\n\nconst formatDateDisplay = (dateStr: string): string => {\n  if (!dateStr) return '';\n  const [year, month, day] = dateStr.split('-');\n  return `${day}/${month}/${year}`;\n};\n\nexport interface DoshaDateFieldProps {\n  id: string;\n  value: string;\n  onChange: (value: string) => void;\n  /** Called when the date picker is opened */\n  onOpen?: () => void;\n  className?: string;\n}\n\nexport function DoshaDateField({\n  id,\n  value,\n  onChange,\n  onOpen,\n  className = '',\n}: DoshaDateFieldProps) {\n  const inputRef = useRef<HTMLInputElement>(null);\n\n  const maxDate = useMemo(() => {\n    const d = new Date();\n    const pad = (n: number) => String(n).padStart(2, '0');\n    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;\n  }, []);\n\n  const openPicker = () => {\n    onOpen?.();\n    const el = inputRef.current;\n    if (\n      el &&\n      typeof (el as HTMLInputElement & { showPicker?: () => void })\n        .showPicker === 'function'\n    ) {\n      try {\n        (el as HTMLInputElement & { showPicker: () => void }).showPicker();\n      } catch (error) {\n        // Fallback to focus if showPicker fails (e.g., requires user gesture)\n        el?.focus();\n      }\n    } else {\n      el?.focus();\n    }\n  };\n\n  return (\n    <div className={`${styles.wrap} ${className}`}>\n      {!value && (\n        <span className={styles.placeholder}>\n          Select Date of Birth\n        </span>\n      )}\n      {value && (\n        <div className={styles.dateDisplay}>{formatDateDisplay(value)}</div>\n      )}\n      <input\n        ref={inputRef}\n        id={id}\n        type=\"date\"\n        className={styles.input}\n        value={value}\n        max={maxDate}\n        onChange={(e) => {\n          const v = e.target.value;\n          const today = new Date();\n          const pad = (n: number) => String(n).padStart(2, '0');\n          const max = `${today.getFullYear()}-${pad(today.getMonth() + 1)}-${pad(today.getDate())}`;\n          if (v && v > max) return;\n          onChange(v);\n        }}\n        onClick={openPicker}\n        onFocus={openPicker}\n      />\n      <button\n        type=\"button\"\n        className={styles.iconBtn}\n        aria-label=\"Open date picker\"\n        onMouseDown={(e) => e.preventDefault()}\n        onClick={(e) => {\n          e.preventDefault();\n          e.stopPropagation();\n          openPicker();\n        }}\n      >\n        <DefaultDoshaImage\n          className={styles.iconImg}\n          src={ICON_DATE}\n          alt=\"\"\n          width={22}\n          height={22}\n          loading=\"lazy\"\n        />\n      </button>\n    </div>\n  );\n}\n","import { useState, useEffect, useRef } from 'react';\nimport styles from './DoshaTimeField.module.scss';\nimport { DefaultDoshaImage } from '../../types/image';\n\nconst ICON_TIME = 'https://srm-cdn.a4b.io/yoda/1770372014782.svg';\n\nconst pad2 = (n: number) => String(n).padStart(2, '0');\n\nfunction to12HourDisplay(hhmm: string): string {\n  const m = /^([01]\\d|2[0-3]):([0-5]\\d)$/.exec(hhmm);\n  if (!m) return hhmm;\n  const hour24 = Number(m[1]);\n  const minute = m[2];\n  const meridiem: 'AM' | 'PM' = hour24 >= 12 ? 'PM' : 'AM';\n  const hour12 = hour24 % 12 === 0 ? 12 : hour24 % 12;\n  return `${hour12}:${minute} ${meridiem}`;\n}\n\nfunction from24ToDraft(hhmm: string): {\n  hour12: number;\n  minute: string;\n  meridiem: 'AM' | 'PM';\n} {\n  const m = /^([01]\\d|2[0-3]):([0-5]\\d)$/.exec(hhmm);\n  if (!m) return { hour12: 12, minute: '00', meridiem: 'AM' as const };\n  const hour24 = Number(m[1]);\n  const minute = m[2];\n  const meridiem: 'AM' | 'PM' = hour24 >= 12 ? 'PM' : 'AM';\n  const hour12 = hour24 % 12 === 0 ? 12 : hour24 % 12;\n  return { hour12, minute, meridiem };\n}\n\nfunction draftTo24(draft: {\n  hour12: number;\n  minute: string;\n  meridiem: 'AM' | 'PM';\n}): string {\n  const hour12 = Math.min(12, Math.max(1, draft.hour12));\n  const minute = /^([0-5]\\d)$/.test(draft.minute) ? draft.minute : '00';\n  let hour24 = hour12 % 12;\n  if (draft.meridiem === 'PM') hour24 += 12;\n  return `${pad2(hour24)}:${minute}`;\n}\n\nexport interface DoshaTimeFieldProps {\n  id: string;\n  value: string;\n  onChange: (value: string) => void;\n  /** Called when the time picker popover is opened */\n  onOpen?: () => void;\n  placeholder?: string;\n  disabled?: boolean;\n  className?: string;\n}\n\nexport function DoshaTimeField({\n  id,\n  value,\n  onChange,\n  onOpen,\n  placeholder = 'Exact Time of Birth',\n  disabled = false,\n  className = '',\n}: DoshaTimeFieldProps) {\n  const timeWrapRef = useRef<HTMLDivElement>(null);\n  const [timeOpen, setTimeOpen] = useState(false);\n  const [timeDraft, setTimeDraft] = useState<{\n    hour12: number;\n    minute: string;\n    meridiem: 'AM' | 'PM';\n  }>({ hour12: 12, minute: '00', meridiem: 'AM' });\n\n  useEffect(() => {\n    const onDocMouseDown = (e: MouseEvent) => {\n      if (!timeWrapRef.current) return;\n      if (!timeWrapRef.current.contains(e.target as Node)) {\n        setTimeOpen(false);\n      }\n    };\n    document.addEventListener('mousedown', onDocMouseDown);\n    return () => document.removeEventListener('mousedown', onDocMouseDown);\n  }, []);\n\n  const handleOpen = () => {\n    if (disabled) return;\n    onOpen?.();\n    setTimeDraft(from24ToDraft(value || '12:00'));\n    setTimeOpen((o) => !o);\n  };\n\n  const handleOk = () => {\n    const v = draftTo24(timeDraft);\n    onChange(v);\n    setTimeOpen(false);\n  };\n\n  return (\n    <div className={`${styles.wrap} ${className}`} ref={timeWrapRef}>\n      <input\n        id={id}\n        className={styles.input}\n        type=\"text\"\n        value={value ? to12HourDisplay(value) : ''}\n        readOnly\n        disabled={disabled}\n        placeholder={placeholder}\n        onClick={handleOpen}\n      />\n      <button\n        type=\"button\"\n        className={styles.iconBtn}\n        aria-label=\"Open time picker\"\n        disabled={disabled}\n        onMouseDown={(e) => e.preventDefault()}\n        onClick={(e) => {\n          e.preventDefault();\n          e.stopPropagation();\n          handleOpen();\n        }}\n      >\n        <DefaultDoshaImage\n          className={styles.iconImg}\n          src={ICON_TIME}\n          alt=\"\"\n          width={22}\n          height={22}\n          loading=\"lazy\"\n        />\n      </button>\n\n      {timeOpen && !disabled && (\n        <div\n          className={styles.timePopover}\n          role=\"dialog\"\n          aria-label=\"Select time\"\n        >\n          <div className={styles.timePickerRow}>\n            <select\n              className={styles.timePickerSelect}\n              value={timeDraft.hour12}\n              onChange={(e) =>\n                setTimeDraft((d) => ({\n                  ...d,\n                  hour12: Number(e.target.value),\n                }))\n              }\n              aria-label=\"Hour\"\n            >\n              {Array.from({ length: 12 }, (_, i) => i + 1).map((h) => (\n                <option key={h} value={h}>\n                  {h}\n                </option>\n              ))}\n            </select>\n            <span className={styles.timePickerColon}>:</span>\n            <select\n              className={styles.timePickerSelect}\n              value={timeDraft.minute}\n              onChange={(e) =>\n                setTimeDraft((d) => ({ ...d, minute: e.target.value }))\n              }\n              aria-label=\"Minute\"\n            >\n              {Array.from({ length: 60 }, (_, i) => pad2(i)).map((m) => (\n                <option key={m} value={m}>\n                  {m}\n                </option>\n              ))}\n            </select>\n            <div className={styles.meridiemToggle} aria-label=\"AM/PM\">\n              <button\n                type=\"button\"\n                className={`${styles.meridiemBtn} ${\n                  timeDraft.meridiem === 'AM' ? styles.meridiemActive : ''\n                }`}\n                onClick={() =>\n                  setTimeDraft((d) => ({ ...d, meridiem: 'AM' }))\n                }\n              >\n                AM\n              </button>\n              <button\n                type=\"button\"\n                className={`${styles.meridiemBtn} ${\n                  timeDraft.meridiem === 'PM' ? styles.meridiemActive : ''\n                }`}\n                onClick={() =>\n                  setTimeDraft((d) => ({ ...d, meridiem: 'PM' }))\n                }\n              >\n                PM\n              </button>\n            </div>\n          </div>\n          <div className={styles.timePopoverActions}>\n            <button\n              type=\"button\"\n              className={styles.timePopoverBtn}\n              onClick={() => setTimeOpen(false)}\n            >\n              Cancel\n            </button>\n            <button\n              type=\"button\"\n              className={`${styles.timePopoverBtn} ${styles.timePopoverOk}`}\n              onClick={handleOk}\n              aria-label=\"OK\"\n            >\n              <svg\n                width=\"18\"\n                height=\"18\"\n                viewBox=\"0 0 24 24\"\n                fill=\"none\"\n                xmlns=\"http://www.w3.org/2000/svg\"\n                aria-hidden=\"true\"\n              >\n                <path\n                  d=\"M20 6L9 17l-5-5\"\n                  stroke=\"currentColor\"\n                  strokeWidth=\"2\"\n                  strokeLinecap=\"round\"\n                  strokeLinejoin=\"round\"\n                />\n              </svg>\n            </button>\n          </div>\n        </div>\n      )}\n    </div>\n  );\n}\n","/**\n * Supabase integration for dosha calculator: session_problem_statements + calculate-dosha Edge Function.\n * Compatible with Lovable / celestial-puja-finder backend.\n */\n\nimport type { SupabaseClient } from \"@supabase/supabase-js\";\nimport type {\n  DoshaSubmissionPayload,\n  DoshaCalculationResponse,\n  DoshaCalculationResult,\n} from \"../types/dosha-api\";\n\nexport interface SubmitDoshaOptions {\n  visitorId?: string;\n  sessionId?: string;\n  /** If true, insert into session_problem_statements (default true) */\n  trackProblemStatements?: boolean;\n  /** Problem statements and language for session_problem_statements */\n  problemStatements?: string[];\n  language?: string;\n}\n\n/**\n * Insert session problem statements (fire-and-forget).\n */\nexport async function insertSessionProblemStatements(\n  supabase: SupabaseClient,\n  options: {\n    visitorId: string;\n    sessionId: string;\n    problemStatements: string[];\n    language?: string;\n  },\n): Promise<void> {\n  const { visitorId, sessionId, problemStatements, language } = options;\n  if (problemStatements.length === 0) return;\n  try {\n    await supabase.from(\"session_problem_statements\").insert({\n      visitor_id: visitorId,\n      session_id: sessionId,\n      problem_statements: problemStatements,\n      language: language ?? \"en\",\n    });\n  } catch {\n    // Non-blocking; ignore\n  }\n}\n\n/**\n * Invoke the calculate-dosha Edge Function and return the parsed response.\n */\nexport async function invokeCalculateDosha(\n  supabase: SupabaseClient,\n  payload: DoshaSubmissionPayload,\n  headers?: { \"x-visitor-id\"?: string; \"x-session-id\"?: string },\n): Promise<DoshaCalculationResponse> {\n  const { data, error } = await supabase.functions.invoke(\"calculate-dosha\", {\n    body: payload,\n    headers: headers ?? {},\n  });\n\n  if (error) {\n    return {\n      success: false,\n      error: error.message || \"Calculation failed\",\n    };\n  }\n\n  if (data && typeof data === \"object\" && \"success\" in data) {\n    if (data.success === true) {\n      return data as DoshaCalculationResult;\n    }\n    return {\n      success: false,\n      error: (data as { error?: string }).error ?? \"Unknown error\",\n      details: (data as { details?: DoshaCalculationResponse[] }).details as\n        | Array<{ field?: string; message?: string }>\n        | undefined,\n    };\n  }\n\n  return {\n    success: false,\n    error: \"Invalid response from server\",\n  };\n}\n\n/**\n * Full submit: optionally insert session_problem_statements, then invoke calculate-dosha.\n */\nexport async function submitDoshaCalculation(\n  supabase: SupabaseClient,\n  payload: DoshaSubmissionPayload,\n  options: SubmitDoshaOptions = {},\n): Promise<DoshaCalculationResponse> {\n  const {\n    visitorId = \"unknown\",\n    sessionId = \"unknown\",\n    trackProblemStatements = true,\n    problemStatements = [],\n    language = \"en\",\n  } = options;\n\n  if (trackProblemStatements && problemStatements.length > 0) {\n    await insertSessionProblemStatements(supabase, {\n      visitorId,\n      sessionId,\n      problemStatements,\n      language,\n    });\n  }\n\n  return invokeCalculateDosha(supabase, payload, {\n    \"x-visitor-id\": visitorId,\n    \"x-session-id\": sessionId,\n  });\n}\n","import { useCallback, useEffect, useRef, useState } from \"react\";\n\nexport interface PlacePrediction {\n  place_id: string;\n  description: string;\n  structured_formatting: {\n    main_text: string;\n    secondary_text: string;\n  };\n}\n\nexport interface PlaceDetails {\n  display_name: string;\n  lat: number;\n  lng: number;\n  city?: string;\n  state?: string;\n  country?: string;\n}\n\nlet googleMapsPromise: Promise<void> | null = null;\n\nconst loadGoogleMapsScript = (\n  apiKey: string,\n  language?: string,\n): Promise<void> => {\n  if (typeof window === \"undefined\") return Promise.resolve();\n\n  if (window.google?.maps?.places) {\n    return Promise.resolve();\n  }\n\n  if (googleMapsPromise) return googleMapsPromise;\n\n  googleMapsPromise = new Promise((resolve, reject) => {\n    const existing = document.querySelector<HTMLScriptElement>(\n      'script[data-google-maps-places=\"true\"]',\n    );\n\n    if (existing) {\n      const start = Date.now();\n      const checkReady = () => {\n        if (window.google?.maps?.places) {\n          resolve();\n          return;\n        }\n        if (Date.now() - start > 5000) {\n          reject(\n            new Error(\n              \"Google Maps script present but Places library did not become available.\",\n            ),\n          );\n          return;\n        }\n        window.setTimeout(checkReady, 50);\n      };\n      if (existing.getAttribute(\"src\")) {\n        checkReady();\n      } else {\n        existing.addEventListener(\"load\", () => checkReady());\n        existing.addEventListener(\"error\", () =>\n          reject(new Error(\"Failed to load Google Maps API\")),\n        );\n      }\n      return;\n    }\n\n    const script = document.createElement(\"script\");\n    const url = new URL(\"https://maps.googleapis.com/maps/api/js\");\n    url.searchParams.set(\"key\", apiKey);\n    url.searchParams.set(\"libraries\", \"places\");\n    url.searchParams.set(\"loading\", \"async\");\n    if (language) url.searchParams.set(\"language\", language);\n\n    script.src = url.toString();\n    script.async = true;\n    script.defer = true;\n    script.setAttribute(\"data-google-maps-places\", \"true\");\n\n    script.onload = () => {\n      const start = Date.now();\n      const check = () => {\n        if (window.google?.maps?.places) {\n          resolve();\n          return;\n        }\n        if (Date.now() - start > 2000) {\n          reject(\n            new Error(\n              \"Google Maps loaded but Places library is unavailable. Check API key restrictions / enabled APIs.\",\n            ),\n          );\n          return;\n        }\n        window.setTimeout(check, 50);\n      };\n      check();\n    };\n\n    script.onerror = () => reject(new Error(\"Failed to load Google Maps API\"));\n\n    document.head.appendChild(script);\n  });\n\n  return googleMapsPromise;\n};\n\nexport const useGooglePlacesAutocomplete = (\n  params: {\n    apiKey?: string;\n    language?: string;\n    restrictCountry?: string;\n  } = {},\n) => {\n  const { apiKey, language = \"en\", restrictCountry } = params;\n\n  const [isLoaded, setIsLoaded] = useState(false);\n  const [predictions, setPredictions] = useState<PlacePrediction[]>([]);\n  const [isSearching, setIsSearching] = useState(false);\n  const [loadError, setLoadError] = useState<string | null>(null);\n\n  const autocompleteService =\n    useRef<google.maps.places.AutocompleteService | null>(null);\n  const placesService = useRef<google.maps.places.PlacesService | null>(null);\n  const sessionToken =\n    useRef<google.maps.places.AutocompleteSessionToken | null>(null);\n\n  useEffect(() => {\n    if (!apiKey) {\n      setIsLoaded(false);\n      setLoadError(null);\n      return;\n    }\n\n    loadGoogleMapsScript(apiKey, language)\n      .then(() => {\n        try {\n          autocompleteService.current =\n            new google.maps.places.AutocompleteService();\n          const div = document.createElement(\"div\");\n          placesService.current = new google.maps.places.PlacesService(div);\n          sessionToken.current =\n            new google.maps.places.AutocompleteSessionToken();\n          setIsLoaded(true);\n          setLoadError(null);\n        } catch (err) {\n          setIsLoaded(false);\n          setLoadError(\n            err instanceof Error\n              ? err.message\n              : \"Failed to create Places services\",\n          );\n        }\n      })\n      .catch((err: unknown) => {\n        setIsLoaded(false);\n        setLoadError(\n          err instanceof Error\n            ? err.message\n            : \"Failed to load location service\",\n        );\n      });\n  }, [apiKey, language]);\n\n  const searchPlaces = useCallback(\n    async (query: string): Promise<void> => {\n      if (!query || query.length < 2 || !autocompleteService.current) {\n        setPredictions([]);\n        return;\n      }\n\n      setIsSearching(true);\n\n      try {\n        const request: google.maps.places.AutocompletionRequest = {\n          input: query,\n          types: [\"(cities)\"],\n          sessionToken: sessionToken.current ?? undefined,\n        };\n\n        if (restrictCountry) {\n          request.componentRestrictions = { country: restrictCountry };\n        }\n\n        const response = await new Promise<\n          google.maps.places.AutocompletePrediction[]\n        >((resolve, reject) => {\n          autocompleteService.current!.getPlacePredictions(\n            request,\n            (preds, status) => {\n              if (\n                status === google.maps.places.PlacesServiceStatus.OK &&\n                preds\n              ) {\n                resolve(preds);\n              } else if (\n                status === google.maps.places.PlacesServiceStatus.ZERO_RESULTS\n              ) {\n                resolve([]);\n              } else {\n                reject(new Error(`Places API error: ${status}`));\n              }\n            },\n          );\n        });\n\n        setPredictions(\n          response.map((p) => ({\n            place_id: p.place_id,\n            description: p.description,\n            structured_formatting: {\n              main_text: p.structured_formatting?.main_text || p.description,\n              secondary_text: p.structured_formatting?.secondary_text || \"\",\n            },\n          })),\n        );\n      } catch {\n        setPredictions([]);\n      } finally {\n        setIsSearching(false);\n      }\n    },\n    [restrictCountry],\n  );\n\n  const getPlaceDetails = useCallback(\n    async (placeId: string): Promise<PlaceDetails | null> => {\n      if (!placesService.current) return null;\n\n      try {\n        const place = await new Promise<google.maps.places.PlaceResult>(\n          (resolve, reject) => {\n            placesService.current!.getDetails(\n              {\n                placeId,\n                fields: [\"geometry\", \"address_components\", \"formatted_address\"],\n                sessionToken: sessionToken.current ?? undefined,\n              },\n              (result, status) => {\n                if (\n                  status === google.maps.places.PlacesServiceStatus.OK &&\n                  result\n                ) {\n                  resolve(result);\n                } else {\n                  reject(new Error(`Place details error: ${status}`));\n                }\n              },\n            );\n          },\n        );\n\n        sessionToken.current =\n          new google.maps.places.AutocompleteSessionToken();\n\n        const lat = place.geometry?.location?.lat() || 0;\n        const lng = place.geometry?.location?.lng() || 0;\n\n        let city = \"\";\n        let state = \"\";\n        let country = \"\";\n\n        place.address_components?.forEach((component) => {\n          if (component.types.includes(\"locality\")) city = component.long_name;\n          if (component.types.includes(\"administrative_area_level_1\"))\n            state = component.long_name;\n          if (component.types.includes(\"country\"))\n            country = component.long_name;\n        });\n\n        return {\n          display_name: place.formatted_address || \"\",\n          lat,\n          lng,\n          city,\n          state,\n          country,\n        };\n      } catch {\n        return null;\n      }\n    },\n    [],\n  );\n\n  const clearPredictions = useCallback(() => setPredictions([]), []);\n\n  return {\n    isLoaded,\n    predictions,\n    isSearching,\n    loadError,\n    searchPlaces,\n    getPlaceDetails,\n    clearPredictions,\n  };\n};\n","import { forwardRef, useImperativeHandle, useRef, useState, useEffect, useCallback } from 'react';\nimport type { DoshaAnalytics } from '../../analytics';\nimport {\n  FormContainer,\n  FormSectionHeader,\n  PrivacyBanner,\n  FormField,\n  FormTextInput,\n  FormLocationInput,\n  FormSegmentedControl,\n  FormTagPills,\n  FormCheckboxWithHelp,\n  FormFooterNote,\n} from '@srimandir/astrology-common';\nimport { DoshaDateField } from '../DoshaDateField/DoshaDateField';\nimport { DoshaTimeField } from '../DoshaTimeField/DoshaTimeField';\nimport type { SupabaseClient } from '@supabase/supabase-js';\nimport type { ResolvedPlace, DoshaCalculationResult, DoshaCalculationResponse, BirthDetails } from '../../types/dosha-api';\nimport { submitDoshaCalculation } from '../../lib/supabase-dosha';\nimport { useGooglePlacesAutocomplete } from '../../hooks/useGooglePlacesAutocomplete';\n\nconst PROBLEM_KEYS = [\n  'formProblemMarriage',\n  'formProblemMoney',\n  'formProblemHealth',\n  'formProblemEducation',\n  'formProblemCareer',\n  'formProblemOther',\n] as const;\n\nfunction getVisitorId(): string {\n  try {\n    const key = 'analytics_visitor_id';\n    let id = typeof localStorage !== 'undefined' ? localStorage.getItem(key) : null;\n    if (!id) {\n      id = typeof crypto !== 'undefined' && 'randomUUID' in crypto\n        ? crypto.randomUUID()\n        : `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;\n      try {\n        localStorage.setItem(key, id);\n      } catch {\n        // ignore\n      }\n    }\n    return id ?? 'unknown';\n  } catch {\n    return 'unknown';\n  }\n}\n\nfunction getSessionId(): string {\n  try {\n    const key = 'analytics_session_id';\n    let id = typeof localStorage !== 'undefined' ? localStorage.getItem(key) : null;\n    if (!id) {\n      id = typeof crypto !== 'undefined' && 'randomUUID' in crypto\n        ? crypto.randomUUID()\n        : `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;\n      try {\n        localStorage.setItem(key, id);\n      } catch {\n        // ignore\n      }\n    }\n    return id ?? 'unknown';\n  } catch {\n    return 'unknown';\n  }\n}\n\nfunction calculateAgeFromDate(dateString: string): number {\n  if (!dateString) return 0;\n  const birthDate = new Date(dateString);\n  if (Number.isNaN(birthDate.getTime())) return 0;\n  const today = new Date();\n  let age = today.getFullYear() - birthDate.getFullYear();\n  const monthDiff = today.getMonth() - birthDate.getMonth();\n  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {\n    age--;\n  }\n  return age;\n}\n\nexport interface DoshaFormValues {\n  name: string;\n  gender: 'male' | 'female' | '';\n  problems: string[];\n  otherProblemText?: string;\n  dateOfBirth: string;\n  birthTime: string;\n  birthTimeUnknown: boolean;\n  birthPlace: string;\n}\n\nexport interface DoshaFormSectionProps {\n  t: (key: string) => string;\n  className?: string;\n  /** Pre-fill the form with these values (e.g. when returning from results to edit) */\n  initialValues?: Partial<DoshaFormValues>;\n  /** Called with the latest form values whenever any field changes */\n  onValuesChange?: (values: DoshaFormValues) => void;\n  /** Called when required form fields become valid or invalid */\n  onFormValidityChange?: (isValid: boolean) => void;\n  /** Supabase client for submission (when set, footer CTA will submit) */\n  supabase?: SupabaseClient | null;\n  /** Resolve place string to lat, lon, tz (optional fallback for dev/testing when googleMapsApiKey not provided) */\n  resolvePlace?: (place: string) => Promise<ResolvedPlace | null>;\n  /** Google Maps API key for place autocomplete and timezone resolution (required for form submission) */\n  googleMapsApiKey?: string;\n  /** Called with result on successful calculation. Second arg is birth details for Kundali chart when available. */\n  onResult?: (result: DoshaCalculationResult, birthDetails?: BirthDetails) => void;\n  /** Called with error message on failure */\n  onError?: (error: string) => void;\n  /** Called when submit starts/finishes */\n  onLoadingChange?: (loading: boolean) => void;\n  /** Optional analytics implementation for tracking field interactions */\n  analytics?: DoshaAnalytics;\n}\n\nexport interface DoshaFormSectionRef {\n  submit: () => Promise<void>;\n}\n\nexport const DoshaFormSection = forwardRef<DoshaFormSectionRef, DoshaFormSectionProps>(\n  function DoshaFormSection(\n    {\n      t,\n      className = '',\n      initialValues,\n      onValuesChange,\n      onFormValidityChange,\n      supabase,\n      resolvePlace,\n      onResult,\n      onError,\n      onLoadingChange,\n      analytics,\n      googleMapsApiKey,\n    },\n    ref\n  ) {\n    type FieldErrorMap = {\n      name?: string;\n      gender?: string;\n      dateOfBirth?: string;\n      birthTime?: string;\n      birthPlace?: string;\n    };\n\n    const sanitizePlaceInput = (value: string) =>\n      value\n        .replace(/[^a-zA-Z\\u0900-\\u097F\\s]/g, '')\n        .replace(/\\s{2,}/g, ' ');\n\n    const [name, setName] = useState(initialValues?.name ?? '');\n    const [gender, setGender] = useState<'male' | 'female' | ''>(initialValues?.gender ?? '');\n    const [problems, setProblems] = useState<string[]>(initialValues?.problems ?? []);\n    const [dateOfBirth, setDateOfBirth] = useState(initialValues?.dateOfBirth ?? '');\n    const [birthTime, setBirthTime] = useState(initialValues?.birthTime ?? '');\n    const [birthTimeUnknown, setBirthTimeUnknown] = useState(initialValues?.birthTimeUnknown ?? false);\n    const [birthPlace, setBirthPlace] = useState(initialValues?.birthPlace ?? '');\n    const [otherProblemText, setOtherProblemText] = useState(initialValues?.otherProblemText ?? '');\n    const [placeCoordinates, setPlaceCoordinates] = useState<{ lat: number; lon: number; tz?: string } | null>(null);\n    const [placeOpen, setPlaceOpen] = useState(false);\n    const [submitError, setSubmitError] = useState<string | null>(null);\n    const [fieldErrors, setFieldErrors] = useState<FieldErrorMap>({});\n\n    const focusField = useCallback((field: keyof FieldErrorMap) => {\n      const focusById = (id: string) => {\n        const el = document.getElementById(id) as HTMLElement | null;\n        if (!el) return false;\n        el.focus();\n        el.scrollIntoView({ behavior: 'smooth', block: 'center' });\n        return true;\n      };\n\n      if (field === 'name') {\n        focusById('dosha-name');\n        return;\n      }\n\n      if (field === 'gender') {\n        const firstGenderOption = document.querySelector<HTMLElement>(\n          '[role=\"group\"][aria-labelledby=\"dosha-gender-label\"] button',\n        );\n        if (firstGenderOption) {\n          firstGenderOption.focus();\n          firstGenderOption.scrollIntoView({ behavior: 'smooth', block: 'center' });\n        }\n        return;\n      }\n\n      if (field === 'dateOfBirth') {\n        focusById('dosha-dob');\n        return;\n      }\n\n      if (field === 'birthTime') {\n        focusById('dosha-time');\n        return;\n      }\n\n      if (field === 'birthPlace') {\n        focusById('dosha-place');\n      }\n    }, []);\n\n    const formFillInitiatedRef = useRef(false);\n    const nameFilledRef = useRef(false);\n    const dobFilledRef = useRef(false);\n    const timeFilledRef = useRef(false);\n    const placeFilledRef = useRef(false);\n    const placeWrapRef = useRef<HTMLDivElement>(null);\n\n    // Google Places Autocomplete\n    const {\n      predictions: placeSuggestions,\n      isSearching: placeLoading,\n      loadError: placeLoadError,\n      searchPlaces,\n      getPlaceDetails,\n      clearPredictions,\n    } = useGooglePlacesAutocomplete({\n      apiKey: googleMapsApiKey,\n      language: 'en',\n    });\n\n    const handleFirstInteraction = useCallback(() => {\n      if (!formFillInitiatedRef.current) {\n        formFillInitiatedRef.current = true;\n        analytics?.trackFormFillInitiated?.();\n      }\n    }, [analytics]);\n\n    // Close autocomplete when clicking outside\n    useEffect(() => {\n      const onDocMouseDown = (e: MouseEvent) => {\n        if (!placeWrapRef.current) return;\n        if (!placeWrapRef.current.contains(e.target as Node)) {\n          setPlaceOpen(false);\n        }\n      };\n      document.addEventListener('mousedown', onDocMouseDown);\n      return () => document.removeEventListener('mousedown', onDocMouseDown);\n    }, []);\n\n    // Search for places as user types\n    useEffect(() => {\n      if (!placeOpen) return;\n      if (birthPlace.length < 2) {\n        clearPredictions();\n        return;\n      }\n\n      const handle = window.setTimeout(async () => {\n        await searchPlaces(birthPlace);\n      }, 300);\n\n      return () => window.clearTimeout(handle);\n    }, [birthPlace, clearPredictions, placeOpen, searchPlaces]);\n\n    const isFormValid =\n      name.trim() !== '' &&\n      (gender === 'male' || gender === 'female') &&\n      dateOfBirth !== '' &&\n      (birthTime !== '' || birthTimeUnknown) &&\n      birthPlace.trim() !== '';\n\n    useEffect(() => {\n      onFormValidityChange?.(isFormValid);\n    }, [isFormValid, onFormValidityChange]);\n\n    useEffect(() => {\n      onValuesChange?.({ name, gender, problems, otherProblemText, dateOfBirth, birthTime, birthTimeUnknown, birthPlace });\n    }, [name, gender, problems, otherProblemText, dateOfBirth, birthTime, birthTimeUnknown, birthPlace, onValuesChange]);\n\n    useEffect(() => {\n      if (!problems.includes('formProblemOther') && otherProblemText) {\n        setOtherProblemText('');\n      }\n    }, [problems, otherProblemText]);\n\n    // Fetch timezone from Google Maps Timezone API\n    const fetchTimezone = useCallback(async (lat: number, lon: number): Promise<string> => {\n      if (!googleMapsApiKey) {\n        return 'UTC';\n      }\n\n      try {\n        const timestamp = Math.floor(Date.now() / 1000);\n        const url = `https://maps.googleapis.com/maps/api/timezone/json?location=${lat},${lon}&timestamp=${timestamp}&key=${googleMapsApiKey}`;\n        const response = await fetch(url);\n        const data = await response.json();\n\n        if (data.status === 'OK' && data.timeZoneId) {\n          return data.timeZoneId;\n        }\n        \n        return 'UTC';\n      } catch (error) {\n        return 'UTC';\n      }\n    }, [googleMapsApiKey]);\n\n    const submit = useCallback(async () => {\n      const reportError = (\n        message: string,\n        field?: keyof FieldErrorMap,\n        showBottomAlert = false,\n      ) => {\n        if (field) {\n          setFieldErrors((prev) => ({ ...prev, [field]: message }));\n          focusField(field);\n        }\n        setSubmitError(showBottomAlert ? message : null);\n        onError?.(message);\n      };\n\n      setFieldErrors({});\n      setSubmitError(null);\n\n      if (!supabase) {\n        reportError(t('calculationError'));\n        return;\n      }\n\n      if (!name.trim()) {\n        reportError(t('formNameRequired'), 'name');\n        return;\n      }\n\n      if (gender !== 'male' && gender !== 'female') {\n        reportError(t('formGenderRequired'), 'gender');\n        return;\n      }\n\n      if (!dateOfBirth) {\n        reportError(t('formDobRequired'), 'dateOfBirth');\n        return;\n      }\n\n      if (!birthTimeUnknown && !birthTime) {\n        reportError(t('formTimeRequired'), 'birthTime');\n        return;\n      }\n\n      const place = birthPlace.trim();\n      if (!place) {\n        reportError(t('formPlaceRequired'), 'birthPlace');\n        return;\n      }\n\n      const sanitizedPlace = sanitizePlaceInput(place).trim();\n      if (!sanitizedPlace) {\n        reportError(t('formPlaceRequired'), 'birthPlace');\n        return;\n      }\n\n      const age = calculateAgeFromDate(dateOfBirth);\n      const restrictedProblems = new Set([\n        'formProblemMarriage',\n        'formProblemMoney',\n        'formProblemCareer',\n        'formProblemBusiness',\n        'marriage',\n        'financial',\n        'career',\n        'business',\n      ]);\n      const hasRestrictedProblem = problems.some((problem) => restrictedProblems.has(problem));\n\n      if (age < 18 && hasRestrictedProblem) {\n        reportError(t('formAgeMarriageRestriction'), undefined, true);\n        return;\n      }\n\n      // Check if we have coordinates from autocomplete or need to use resolvePlace\n      if (!placeCoordinates && !resolvePlace) {\n        reportError(t('formPlaceSelectFromDropdown'), 'birthPlace');\n        return;\n      }\n      \n      onLoadingChange?.(true);\n      \n      try {\n        let lat: number, lon: number, tz: string;\n        \n        // Use coordinates from autocomplete if available, otherwise use resolvePlace\n        if (placeCoordinates) {\n          lat = placeCoordinates.lat;\n          lon = placeCoordinates.lon;\n          // Fetch timezone if not already available\n          if (placeCoordinates.tz) {\n            tz = placeCoordinates.tz;\n          } else {\n            tz = await fetchTimezone(lat, lon);\n            setPlaceCoordinates({ ...placeCoordinates, tz });\n          }\n        } else if (resolvePlace) {\n          // Fallback to resolvePlace function (for dev/testing)\n          const resolved = await resolvePlace(place);\n          if (!resolved) {\n            reportError(t('locationError'));\n            onLoadingChange?.(false);\n            return;\n          }\n          lat = resolved.lat;\n          lon = resolved.lon;\n          tz = resolved.tz;\n        } else {\n          reportError(t('formPlaceSelectFromDropdown'), 'birthPlace');\n          onLoadingChange?.(false);\n          return;\n        }\n        const payload = {\n          problemAreaValues: [\n            ...problems\n              .filter((key) => key !== 'formProblemOther')\n              .map((key) => t(key))\n              .filter(Boolean),\n            ...(problems.includes('formProblemOther') && otherProblemText.trim()\n              ? [otherProblemText.trim()]\n              : []),\n          ],\n          name: name.trim(),\n          gender: gender === 'male' ? ('M' as const) : ('F' as const),\n          date: dateOfBirth,\n          time: birthTimeUnknown ? '' : (birthTime || '12:00'),\n          unknownTime: birthTimeUnknown,\n          tz: tz || 'UTC',\n          lat,\n          lon,\n          place: sanitizedPlace,\n          problemArea: undefined as string | undefined,\n        };\n        payload.problemArea = payload.problemAreaValues.length > 0\n          ? payload.problemAreaValues.join(', ')\n          : undefined;\n        \n        const visitorId = getVisitorId();\n        const sessionId = getSessionId();\n        const problemStatements = payload.problemAreaValues;\n        const language = (typeof navigator !== 'undefined' && navigator.language?.toLowerCase().startsWith('hi'))\n          ? 'hi'\n          : 'en';\n        \n        const response: DoshaCalculationResponse = await submitDoshaCalculation(supabase, payload, {\n          visitorId,\n          sessionId,\n          trackProblemStatements: true,\n          problemStatements,\n          language,\n        });\n        \n        if (response.success) {\n          setSubmitError(null);\n          const [y, m, d] = (payload.date || '').split('-').map(Number);\n          const timeStr = payload.time || '12:00';\n          const [hr, min] = timeStr.split(':').map((x) => parseInt(x, 10) || 0);\n          const birthDetails: BirthDetails = {\n            day: d || 1,\n            month: m || 1,\n            year: y || 2000,\n            hour: hr,\n            minute: min,\n            lat,\n            lon,\n            tzone: 5.5, // Default timezone offset for India\n          };\n          onResult?.(response, birthDetails);\n        } else {\n          // Map server-side validation errors to user-friendly messages\n          let errorMessage = response.error ?? t('calculationError');\n          if (errorMessage.includes(\"Expected 'M' | 'F'\") || errorMessage.includes(\"gender\")) {\n            errorMessage = t('formGenderRequired');\n          }\n          reportError(errorMessage);\n        }\n      } catch (err) {\n        const msg = err instanceof Error ? err.message : String(err);\n        reportError(msg);\n      } finally {\n        onLoadingChange?.(false);\n      }\n    }, [supabase, resolvePlace, placeCoordinates, birthPlace, name, gender, dateOfBirth, birthTime, birthTimeUnknown, problems, t, onError, onLoadingChange, analytics, onResult, fetchTimezone, focusField]);\n\n    useImperativeHandle(ref, () => ({ submit }), [submit]);\n\n    const problemOptions = PROBLEM_KEYS.map((key) => ({\n      key,\n      label: t(key),\n    }));\n\n    return (\n      <FormContainer className={className} aria-label={t('formTitle')}>\n        <PrivacyBanner text={t('formPrivacyBanner')} />\n        <FormSectionHeader\n          title={t('formTitle')}\n          subtitle={t('formSubtitle')}\n        />\n        <div onFocusCapture={() => { handleFirstInteraction(); analytics?.trackNameSectionClicked?.(); }}>\n          <FormField id=\"dosha-name\" label={t('formNameLabel')} required>\n            <FormTextInput\n              id=\"dosha-name\"\n              value={name}\n              onChange={(e) => {\n                const v = e.target.value;\n                if (v && !nameFilledRef.current) {\n                  nameFilledRef.current = true;\n                  analytics?.trackNameSectionFilled?.();\n                }\n                setName(v);\n                if (fieldErrors.name) {\n                  setFieldErrors((prev) => ({ ...prev, name: undefined }));\n                }\n                if (submitError) {\n                  setSubmitError(null);\n                }\n              }}\n              placeholder={t('formNamePlaceholder')}\n              autoComplete=\"name\"\n            />\n            {fieldErrors.name && (\n              <p style={{ marginTop: '6px', fontSize: '12px', color: '#dc2626' }}>{fieldErrors.name}</p>\n            )}\n          </FormField>\n        </div>\n        <FormField id=\"dosha-gender\" label={t('formGenderLabel')} required>\n          <FormSegmentedControl\n            id=\"dosha-gender\"\n            options={[\n              { value: 'male', label: t('formGenderMale') },\n              { value: 'female', label: t('formGenderFemale') },\n            ]}\n            value={gender}\n            onChange={(v) => {\n              setGender(v as 'male' | 'female' | '');\n              if (fieldErrors.gender) {\n                setFieldErrors((prev) => ({ ...prev, gender: undefined }));\n              }\n              if (submitError) {\n                setSubmitError(null);\n              }\n            }}\n          />\n          {fieldErrors.gender && (\n            <p style={{ marginTop: '6px', fontSize: '12px', color: '#dc2626' }}>{fieldErrors.gender}</p>\n          )}\n        </FormField>\n        <FormField id=\"dosha-problems\" label={t('formProblemLabel')}>\n          <FormTagPills\n            id=\"dosha-problems\"\n            options={problemOptions}\n            selected={problems}\n            onChange={(nextProblems) => {\n              setProblems(nextProblems);\n              if (!nextProblems.includes('formProblemOther')) {\n                setOtherProblemText('');\n              }\n            }}\n          />\n          {problems.includes('formProblemOther') && (\n            <div style={{ marginTop: '8px' }}>\n              <FormTextInput\n                id=\"dosha-problem-other\"\n                value={otherProblemText}\n                onChange={(e) => {\n                  const next = e.target.value.slice(0, 100);\n                  setOtherProblemText(next);\n                }}\n                placeholder={t('formProblemOtherPlaceholder')}\n              />\n              <p style={{ marginTop: '6px', fontSize: '12px', color: '#8f6e56' }}>{t('formProblemOtherHint')}</p>\n            </div>\n          )}\n        </FormField>\n        <FormField\n          id=\"dosha-dob\"\n          label={t('formDobLabel')}\n          required\n        >\n          <div style={{ minHeight: fieldErrors.dateOfBirth ? '72px' : '48px', transition: 'min-height 0.2s' }}>\n            <DoshaDateField\n              id=\"dosha-dob\"\n              value={dateOfBirth}\n              onOpen={() => { handleFirstInteraction(); analytics?.trackDobClicked?.(); }}\n              onChange={(v) => {\n                if (v && !dobFilledRef.current) {\n                  dobFilledRef.current = true;\n                  analytics?.trackDobFilled?.();\n                }\n                setDateOfBirth(v);\n                if (fieldErrors.dateOfBirth) {\n                  setFieldErrors((prev) => ({ ...prev, dateOfBirth: undefined }));\n                }\n                if (submitError) {\n                  setSubmitError(null);\n                }\n              }}\n            />\n            {fieldErrors.dateOfBirth && (\n              <p style={{ marginTop: '6px', fontSize: '12px', color: '#dc2626' }}>{fieldErrors.dateOfBirth}</p>\n            )}\n          </div>\n        </FormField>\n        <FormField\n          id=\"dosha-time\"\n          label={t('formTimeLabel')}\n          required\n        >\n          <div style={{ minHeight: fieldErrors.birthTime ? '72px' : '48px', transition: 'min-height 0.2s' }}>\n            <DoshaTimeField\n              id=\"dosha-time\"\n              value={birthTime}\n              onOpen={() => { handleFirstInteraction(); analytics?.trackTimeClicked?.(); }}\n              onChange={(v) => {\n                if (v && !timeFilledRef.current) {\n                  timeFilledRef.current = true;\n                  analytics?.trackTimeFilled?.();\n                }\n                setBirthTime(v);\n                if (fieldErrors.birthTime) {\n                  setFieldErrors((prev) => ({ ...prev, birthTime: undefined }));\n                }\n                if (submitError) {\n                  setSubmitError(null);\n                }\n              }}\n              disabled={birthTimeUnknown}\n            />\n            {fieldErrors.birthTime && (\n              <p style={{ marginTop: '6px', fontSize: '12px', color: '#dc2626' }}>{fieldErrors.birthTime}</p>\n            )}\n          </div>\n        </FormField>\n        <FormCheckboxWithHelp\n          id=\"dosha-time-unknown\"\n          checked={birthTimeUnknown}\n          onChange={(v) => { \n            handleFirstInteraction(); \n            analytics?.trackTimeCheckboxClicked?.(); \n            setBirthTimeUnknown(v);\n            if (v && fieldErrors.birthTime) {\n              // Clear time error when checkbox is checked (time no longer required)\n              setFieldErrors((prev) => ({ ...prev, birthTime: undefined }));\n            }\n          }}\n          primaryText={t('formTimeUnknown')}\n          helpText={t('formTimeUnknownHelp')}\n        />\n        <div onFocusCapture={() => { handleFirstInteraction(); analytics?.trackPlaceOfBirthClicked?.(); }}>\n          <FormField\n            id=\"dosha-place\"\n            label={t('formPlaceLabel')}\n            required\n          >\n            <div ref={placeWrapRef} style={{ position: 'relative' }}>\n              <FormLocationInput\n                id=\"dosha-place\"\n                value={birthPlace}\n                onChange={(e) => {\n                  const v = sanitizePlaceInput(e.target.value);\n                  setBirthPlace(v);\n                  setPlaceCoordinates(null);\n                  setPlaceOpen(true);\n                  if (v && !placeFilledRef.current) {\n                    placeFilledRef.current = true;\n                    analytics?.trackPlaceOfBirthChosen?.(v);\n                  }\n                  if (fieldErrors.birthPlace) {\n                    setFieldErrors((prev) => ({ ...prev, birthPlace: undefined }));\n                  }\n                  if (submitError) {\n                    setSubmitError(null);\n                  }\n                }}\n                onFocus={() => setPlaceOpen(true)}\n                placeholder={t('formPlacePlaceholder')}\n              />\n              {fieldErrors.birthPlace && (\n                <p style={{ marginTop: '6px', fontSize: '12px', color: '#dc2626' }}>{fieldErrors.birthPlace}</p>\n              )}\n              \n              {/* Autocomplete suggestions */}\n              {placeOpen && placeSuggestions.length > 0 && (\n                <div\n                  style={{\n                    position: 'absolute',\n                    top: 'calc(100% + 6px)',\n                    left: 0,\n                    right: 0,\n                    backgroundColor: '#fff',\n                    border: '1px solid rgba(229, 231, 235, 0.95)',\n                    borderRadius: '12px',\n                    maxHeight: '240px',\n                    overflowY: 'auto',\n                    boxShadow: '0 10px 24px rgba(17, 24, 39, 0.12)',\n                    zIndex: 9999,\n                  }}\n                  role=\"listbox\"\n                >\n                  {placeSuggestions.slice(0, 8).map((p) => (\n                    <button\n                      key={p.place_id}\n                      type=\"button\"\n                      onClick={async () => {\n                        setBirthPlace(sanitizePlaceInput(p.description));\n                        \n                        // Get coordinates from place details\n                        if (getPlaceDetails) {\n                          const details = await getPlaceDetails(p.place_id);\n                          if (details) {\n                            setPlaceCoordinates({\n                              lat: details.lat,\n                              lon: details.lng,\n                            });\n                            if (fieldErrors.birthPlace) {\n                              setFieldErrors((prev) => ({ ...prev, birthPlace: undefined }));\n                            }\n                            if (submitError) {\n                              setSubmitError(null);\n                            }\n                          }\n                        }\n                        \n                        clearPredictions();\n                        setPlaceOpen(false);\n                        if (!placeFilledRef.current) {\n                          placeFilledRef.current = true;\n                          analytics?.trackPlaceOfBirthChosen?.(p.description);\n                        }\n                      }}\n                      style={{\n                        width: '100%',\n                        padding: '10px 12px',\n                        textAlign: 'left',\n                        border: 'none',\n                        backgroundColor: 'transparent',\n                        cursor: 'pointer',\n                        display: 'flex',\n                        flexDirection: 'column',\n                        gap: '2px',\n                        outline: 'none',\n                      }}\n                      onMouseEnter={(e) => {\n                        e.currentTarget.style.backgroundColor = 'rgba(247, 94, 34, 0.06)';\n                      }}\n                      onMouseLeave={(e) => {\n                        e.currentTarget.style.backgroundColor = 'transparent';\n                      }}\n                      onFocus={(e) => {\n                        e.currentTarget.style.backgroundColor = 'rgba(247, 94, 34, 0.06)';\n                      }}\n                      onBlur={(e) => {\n                        e.currentTarget.style.backgroundColor = 'transparent';\n                      }}\n                    >\n                      <span style={{ fontSize: '14px', fontWeight: 600, color: '#111827' }}>\n                        {p.structured_formatting?.main_text ?? p.description}\n                      </span>\n                      {p.structured_formatting?.secondary_text && (\n                        <span style={{ fontSize: '12px', color: '#6b7280' }}>\n                          {p.structured_formatting.secondary_text}\n                        </span>\n                      )}\n                    </button>\n                  ))}\n                </div>\n              )}\n\n              {/* Loading state */}\n              {placeOpen && googleMapsApiKey && placeLoading && (\n                <div\n                  style={{\n                    position: 'absolute',\n                    top: 'calc(100% + 6px)',\n                    left: 0,\n                    right: 0,\n                    padding: '10px 12px',\n                    backgroundColor: '#fff',\n                    border: '1px solid rgba(229, 231, 235, 0.95)',\n                    borderRadius: '12px',\n                    fontSize: '12px',\n                    color: '#6b7280',\n                    boxShadow: '0 10px 24px rgba(17, 24, 39, 0.12)',\n                    zIndex: 9999,\n                  }}\n                >\n                  Loading…\n                </div>\n              )}\n\n              {/* Error state */}\n              {placeOpen && googleMapsApiKey && !placeLoading && placeLoadError && (\n                <div\n                  style={{\n                    position: 'absolute',\n                    top: 'calc(100% + 6px)',\n                    left: 0,\n                    right: 0,\n                    padding: '10px 12px',\n                    backgroundColor: '#fff',\n                    border: '1px solid rgba(229, 231, 235, 0.95)',\n                    borderRadius: '12px',\n                    fontSize: '12px',\n                    color: '#dc2626',\n                    boxShadow: '0 10px 24px rgba(17, 24, 39, 0.12)',\n                    zIndex: 9999,\n                  }}\n                >\n                  {placeLoadError}\n                </div>\n              )}\n            </div>\n          </FormField>\n        </div>\n        <FormFooterNote>\n          {'⚡ '}\n          {t('formFooterNoteBefore')}\n          <strong>{t('formFooterNoteBold')}</strong>\n          {t('formFooterNoteAfter')}\n        </FormFooterNote>\n        {submitError && (\n          <div\n            style={{\n              marginTop: '4px',\n              width: '100%',\n              borderRadius: '14px',\n              border: '1px solid #FCA5A5',\n              background: '#FEF2F2',\n              padding: '16px',\n              display: 'flex',\n              alignItems: 'flex-start',\n              gap: '10px',\n            }}\n            role=\"alert\"\n            aria-live=\"assertive\"\n          >\n            <svg\n              xmlns=\"http://www.w3.org/2000/svg\"\n              width=\"24\"\n              height=\"24\"\n              viewBox=\"0 0 24 24\"\n              fill=\"none\"\n              stroke=\"#ef4444\"\n              strokeWidth=\"2\"\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              style={{ width: '16px', height: '16px', marginTop: '2px', flexShrink: 0 }}\n              aria-hidden=\"true\"\n            >\n              <circle cx=\"12\" cy=\"12\" r=\"10\" />\n              <line x1=\"12\" x2=\"12\" y1=\"8\" y2=\"12\" />\n              <line x1=\"12\" x2=\"12.01\" y1=\"16\" y2=\"16\" />\n            </svg>\n            <p style={{ margin: 0, fontSize: '14px', lineHeight: '1.5', color: '#EF4444' }}>{submitError}</p>\n          </div>\n        )}\n      </FormContainer>\n    );\n  }\n);\n","import * as React from 'react';\n\nexport interface SkeletonProps extends React.HTMLAttributes<HTMLDivElement> {}\n\nconst Skeleton = React.forwardRef<HTMLDivElement, SkeletonProps>(\n  ({ className = '', ...props }, ref) => (\n    <div\n      ref={ref}\n      className={`animate-pulse rounded-md bg-muted ${className}`}\n      {...props}\n    />\n  )\n);\nSkeleton.displayName = 'Skeleton';\n\nexport { Skeleton };\n","import * as React from 'react';\n\nconst Card = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement>\n>(({ className = '', ...props }, ref) => (\n  <div\n    ref={ref}\n    className={`rounded-lg border border-border bg-card text-card-foreground shadow-sm ${className}`}\n    {...props}\n  />\n));\nCard.displayName = 'Card';\n\nconst CardHeader = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement>\n>(({ className = '', ...props }, ref) => (\n  <div ref={ref} className={`flex flex-col space-y-1.5 p-6 ${className}`} {...props} />\n));\nCardHeader.displayName = 'CardHeader';\n\nconst CardTitle = React.forwardRef<\n  HTMLParagraphElement,\n  React.HTMLAttributes<HTMLHeadingElement>\n>(({ className = '', ...props }, ref) => (\n  <h3\n    ref={ref}\n    className={`text-2xl font-semibold leading-none tracking-tight ${className}`}\n    {...props}\n  />\n));\nCardTitle.displayName = 'CardTitle';\n\nconst CardDescription = React.forwardRef<\n  HTMLParagraphElement,\n  React.HTMLAttributes<HTMLParagraphElement>\n>(({ className = '', ...props }, ref) => (\n  <p ref={ref} className={`text-sm text-muted-foreground ${className}`} {...props} />\n));\nCardDescription.displayName = 'CardDescription';\n\nconst CardContent = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement>\n>(({ className = '', ...props }, ref) => (\n  <div ref={ref} className={`p-6 pt-0 ${className}`} {...props} />\n));\nCardContent.displayName = 'CardContent';\n\nexport { Card, CardHeader, CardTitle, CardDescription, CardContent };\n","import * as React from 'react';\n\nexport interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {\n  size?: 'default' | 'sm' | 'lg';\n  variant?: 'default' | 'destructive' | 'outline' | 'secondary' | 'ghost' | 'link';\n  className?: string;\n  children?: React.ReactNode;\n}\n\nconst Button = React.forwardRef<HTMLButtonElement, ButtonProps>(\n  ({ className = '', size = 'default', variant = 'default', ...props }, ref) => {\n    const sizeClasses = {\n      default: 'h-10 px-4 py-2',\n      sm: 'h-9 rounded-md px-3',\n      lg: 'h-11 rounded-md px-8',\n    };\n    const variantClasses = {\n      default: 'bg-primary text-primary-foreground hover:bg-primary/90',\n      destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90',\n      outline: 'border border-input bg-background hover:bg-accent hover:text-accent-foreground',\n      secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',\n      ghost: 'hover:bg-accent hover:text-accent-foreground',\n      link: 'text-primary underline-offset-4 hover:underline',\n    };\n    return (\n      <button\n        ref={ref}\n        type=\"button\"\n        className={`inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 ${sizeClasses[size]} ${variantClasses[variant]} ${className}`}\n        {...props}\n      />\n    );\n  }\n);\nButton.displayName = 'Button';\n\nexport { Button };\n","import React from 'react';\nimport { Card } from '../ui/Card';\nimport { Button } from '../ui/Button';\nimport { ExternalLink } from '../icons';\nimport {\n  getPujaTitle,\n  getTempleName,\n  formatScheduleDate,\n  getPujaLink,\n  getCoverImageUrl,\n  type SriMandirPuja,\n} from '../../lib/sriMandirPujaHelpers';\nimport type { DoshaImageComponent } from '../../types/image';\nimport { DefaultDoshaImage } from '../../types/image';\nimport type { DoshaAnalytics } from '../../analytics';\n\nexport interface SriMandirPujaVerticalCardProps {\n  puja: SriMandirPuja;\n  doshaType: string;\n  /** Current language (e.g. 'en' or 'hi') for title/temple/date/link. */\n  language: string;\n  onBookClick?: () => void | Promise<void>;\n  variant?: string;\n  /** Optional image component for optimization */\n  imageComponent?: DoshaImageComponent;\n  /** Optional analytics callback */\n  analytics?: DoshaAnalytics;\n}\n\nexport function SriMandirPujaVerticalCard({\n  puja,\n  doshaType,\n  language,\n  onBookClick,\n  imageComponent = DefaultDoshaImage,\n  analytics,\n}: SriMandirPujaVerticalCardProps) {\n  const Img = imageComponent;\n  const isHindi = language?.toLowerCase().startsWith('hi');\n\n  const displayTitle = getPujaTitle(puja, language);\n  const displayTempleName = getTempleName(puja, language);\n  const formattedDate = formatScheduleDate(puja.schedule_date_ist, language);\n  const pujaLink = getPujaLink(puja, language);\n  const coverImageUrl = getCoverImageUrl(puja, language);\n\n  const handleBookClick = async () => {\n    // Track book CTA click\n    analytics?.trackDoshaCalculatorResultBookCtaClicked?.({\n      position: 'puja_card',\n      url: pujaLink,\n      isOldDosha: false,\n    });\n    \n    if (onBookClick) {\n      try {\n        await onBookClick();\n      } catch (err) {\n        console.error('Error in onBookClick:', err);\n      }\n    }\n    window.open(pujaLink, '_blank', 'noopener,noreferrer');\n  };\n\n  return (\n    <Card className=\"overflow-hidden hover:shadow-lg transition-shadow relative\">\n      <div className=\"relative\">\n        {/* Limited Seats Tag - FOMO Element (same as celestial) */}\n        <div className=\"absolute -top-1 -left-1 z-10\">\n          <span className=\"inline-flex items-center px-2 py-1 text-[10px] font-medium bg-destructive/90 text-destructive-foreground rounded-br-md shadow-sm\">\n            {isHindi ? 'सीमित सीटें' : 'Limited Seats'}\n          </span>\n        </div>\n\n        {/* Image */}\n        {coverImageUrl && (\n          <div className=\"relative aspect-[16/10] w-full overflow-hidden bg-muted\">\n            <Img\n              src={coverImageUrl}\n              alt={displayTitle}\n              className=\"w-full h-full object-contain\"\n              loading=\"lazy\"\n            />\n          </div>\n        )}\n\n        {/* Details */}\n        <div className=\"p-3 space-y-2\">\n          <h4 className=\"font-semibold text-sm line-clamp-2 text-card-foreground\">{displayTitle}</h4>\n\n          {puja.temple_name && (\n            <p className=\"text-sm text-muted-foreground\">{displayTempleName}</p>\n          )}\n\n          {puja.schedule_date_ist && (\n            <p className=\"text-sm font-medium text-card-foreground\">{formattedDate}</p>\n          )}\n\n          {puja.individual_pack_price_inr > 0 && (\n            <p className=\"text-base font-bold text-primary\">\n              {isHindi\n                ? `₹${puja.individual_pack_price_inr} से शुरू`\n                : `Starting from ₹${puja.individual_pack_price_inr}`}\n            </p>\n          )}\n\n          <Button\n            size=\"lg\"\n            className=\"book-puja-cta w-full h-14 text-lg font-bold\"\n            onClick={async (e) => {\n              e.preventDefault();\n              await handleBookClick();\n            }}\n          >\n            {isHindi ? 'पूजा बुक करें' : 'Book Puja'}\n            <ExternalLink className=\"ml-1.5 h-3.5 w-3.5\" size={14} />\n          </Button>\n\n          <p className=\"text-[10px] text-center text-muted-foreground\">\n            {isHindi ? 'श्री मंदिर द्वारा संचालित' : 'Powered by Sri Mandir'}\n          </p>\n        </div>\n      </div>\n    </Card>\n  );\n}\n","import React from \"react\";\nimport styles from \"./WhatFromAnalysis.module.scss\";\nimport type { BannerType } from \"../../constants/bannerConfig\";\n\nexport interface WhatFromAnalysisProps {\n  t: (key: string) => string;\n  className?: string;\n  /** Banner type to determine which content to show */\n  bannerType?: BannerType;\n}\n\nexport function WhatFromAnalysis({\n  t,\n  className = \"\",\n  bannerType = \"generic\",\n}: WhatFromAnalysisProps) {\n  const title = t(\"whatFromAnalysisTitle\");\n\n  // Determine the correct translation key prefix based on banner type\n  const prefix =\n    bannerType === \"marriage\"\n      ? \"whatFromAnalysisMarriage\"\n      : \"whatFromAnalysisGeneric\";\n\n  const itemKeys = [\n    { titleKey: `${prefix}1Title`, descKey: `${prefix}1Desc` },\n    { titleKey: `${prefix}2Title`, descKey: `${prefix}2Desc` },\n    { titleKey: `${prefix}3Title`, descKey: `${prefix}3Desc` },\n  ];\n\n  return (\n    <section\n      className={`${styles.section} ${className}`}\n      aria-labelledby=\"what-from-analysis-heading\"\n    >\n      <h2 id=\"what-from-analysis-heading\" className={styles.heading}>\n        {title}\n      </h2>\n      <ol className={styles.list}>\n        {itemKeys.map(({ titleKey, descKey }, index) => (\n          <li key={titleKey} className={styles.item}>\n            <span className={styles.stepNumber} aria-hidden=\"true\">\n              {index + 1}\n            </span>\n            <div className={styles.itemContent}>\n              <span className={styles.itemTitle}>{t(titleKey)}</span>\n              <span className={styles.itemDesc}>{t(descKey)}</span>\n            </div>\n          </li>\n        ))}\n      </ol>\n    </section>\n  );\n}\n","/**\n * Banner configuration constants for dosha-calculator\n * Images and mapping for utm_term query parameters\n */\n\nimport type { SupportedLocale } from \"../i18n/translations\";\n\nexport type BannerType = \"marriage\" | \"generic\";\n\nexport interface BannerConfig {\n  imageUrl: string;\n  alt: string;\n  tickerText: string;\n}\n\n/**\n * Banner images indexed by type and locale\n */\nexport const BANNER_IMAGES: Record<\n  BannerType,\n  Record<SupportedLocale, BannerConfig>\n> = {\n  marriage: {\n    en: {\n      imageUrl: \"https://srm-cdn.a4b.io/yoda/1773137437775.webp\",\n      alt: \"Marriage dosha analysis banner\",\n      tickerText: \"★ 4.9 Rated By Users Facing Marriage Delay\",\n    },\n    hi: {\n      imageUrl: \"https://srm-cdn.a4b.io/yoda/1773137493287.webp\",\n      alt: \"विवाह दोष विश्लेषण बैनर\",\n      tickerText:\n        \"★ 4.9 शादी में देरी का सामना कर रहे उपयोगकर्ताओं द्वारा रेटेड\",\n    },\n  },\n  generic: {\n    en: {\n      imageUrl: \"https://srm-cdn.a4b.io/yoda/1773137415503.webp\",\n      alt: \"Dosha analysis banner\",\n      tickerText: \"★ 4.9 Rated By Users Seeking Clarity\",\n    },\n    hi: {\n      imageUrl: \"https://srm-cdn.a4b.io/yoda/1773137476046.webp\",\n      alt: \"दोष विश्लेषण बैनर\",\n      tickerText: \"★ 4.9 रेटिंग अपने दोषा को जानने वाले यूज़र्स ने दी\",\n    },\n  },\n};\n\n/**\n * Mapping of utm_term values to banner types\n */\nexport const UTM_TERM_TO_BANNER: Record<string, BannerType> = {\n  \"marriage-what-you'll-get-first\": \"marriage\",\n  \"marriage-form-first\": \"marriage\",\n  \"generic-what-you'll-get-first\": \"generic\",\n  \"generic-form-first\": \"generic\",\n};\n\n/**\n * Get banner config based on utm_term and locale\n * Checks if utm_term includes any of the defined patterns\n * Falls back to generic banner if no pattern matches\n */\nexport function getBannerConfig(\n  utmTerm: string | null,\n  locale: SupportedLocale,\n): BannerConfig {\n  let bannerType: BannerType = \"generic\";\n\n  if (utmTerm) {\n    // Check if utm_term includes any of the defined patterns\n    for (const [pattern, type] of Object.entries(UTM_TERM_TO_BANNER)) {\n      if (utmTerm.includes(pattern)) {\n        bannerType = type;\n        break;\n      }\n    }\n  }\n\n  return BANNER_IMAGES[bannerType][locale];\n}\n","/**\n * Utility functions for dosha-calculator\n */\n\n/**\n * Get a query parameter value from the current URL\n * @param param - The query parameter name\n * @returns The parameter value or null if not found\n */\nexport function getQueryParam(param: string): string | null {\n  if (typeof window === \"undefined\") {\n    return null;\n  }\n\n  const urlParams = new URLSearchParams(window.location.search);\n  return urlParams.get(param);\n}\n\n/**\n * Get the utm_term query parameter from the current URL\n * @returns The utm_term value or null if not present\n */\nexport function getUtmTerm(): string | null {\n  return getQueryParam(\"utm_term\");\n}\n","import { useRef, useState, useMemo, useEffect, useCallback, lazy, Suspense } from \"react\";\nimport { FLOATING_CTA_STATUS, type DoshaAnalytics } from \"../../analytics\";\nimport type { SupabaseClient } from \"@supabase/supabase-js\";\nimport { createSupabaseClient } from \"../../lib/supabase-helpers\";\nimport {\n  fetchPujas,\n  getPujaForDosha,\n} from \"../../lib/puja-recommendation\";\nimport {\n  getPujaLink,\n  getPujaTitle,\n} from \"../../lib/sriMandirPujaHelpers\";\nimport {\n  PageHeader,\n  UserReviewsSection,\n  FAQAccordion,\n  FooterShell,\n  MarqueeStrip,\n  ContactUsSection,\n  footerShellStyles,\n} from \"@srimandir/astrology-common\";\nimport { FooterTrustBadge } from \"../FooterTrustBadge/FooterTrustBadge\";\nimport { DoshaFooterCTA } from \"../DoshaFooterCTA/DoshaFooterCTA\";\nimport { DoshaBanner } from \"../DoshaBanner\";\nimport { SectionWithImpression } from \"../SectionWithImpression\";\nimport { useI18n } from \"../../i18n\";\nimport { DoshaFormSection } from \"../DoshaFormSection/DoshaFormSection\";\nimport { Skeleton } from \"../ui/Skeleton\";\nimport { SriMandirPujaVerticalCard } from \"../SriMandirPujaVerticalCard/SriMandirPujaVerticalCard\";\nimport { WhatFromAnalysis } from \"../WhatFromAnalysis/WhatFromAnalysis\";\n\n// Lazy load the results component - only loads after form submission\nconst DoshaResultsFull = lazy(() => \n  import(\"../DoshaResultsFull/DoshaResultsFull\").then(module => ({ \n    default: module.DoshaResultsFull \n  }))\n);\nimport { getBannerConfig, type BannerType } from \"../../constants/bannerConfig\";\nimport { getUtmTerm } from \"../../utils/queryParams\";\nimport type {\n  DoshaSummary,\n  DoshaCalculationResult,\n  ResolvedPlace,\n  BirthDetails,\n} from \"../../types/dosha-api\";\nimport type { SriMandirPuja } from \"../../lib/sriMandirPujaHelpers\";\nimport type { DoshaFormValues } from \"../DoshaFormSection/DoshaFormSection\";\nimport type { DoshaImageComponent } from \"../../types/image\";\nimport { DefaultDoshaImage } from \"../../types/image\";\n\nconst DEFAULT_LOGO_URL = \"https://srm-cdn.a4b.io/yoda/1770362904947.svg\";\n\nconst ICON_KUNDLI_CREATED = \"https://srm-cdn.a4b.io/yoda/1770375694934.svg\";\nconst ICON_CERTIFIED = \"https://srm-cdn.a4b.io/yoda/1770375720933.svg\";\nconst ICON_SECURE_PAYMENT = \"https://srm-cdn.a4b.io/yoda/1770707793537.svg\";\nconst ICON_GLOBE = \"https://srm-cdn.a4b.io/yoda/1770362713543.svg\";\n\nfunction getPujaDoshaTypeCandidates(doshaType: string): string[] {\n  const candidates = new Set<string>([doshaType]);\n\n  switch (doshaType) {\n    case \"kaal-sarp\":\n      candidates.add(\"kaalSarp\");\n      candidates.add(\"kaalsarp\");\n      candidates.add(\"kaal_sarp\");\n      break;\n    case \"shani\":\n      candidates.add(\"sadeSati\");\n      candidates.add(\"shaniSadeSati\");\n      candidates.add(\"sade-sati\");\n      break;\n    case \"mangal\":\n      candidates.add(\"mangalDosha\");\n      candidates.add(\"manglik\");\n      break;\n    case \"pitra\":\n      candidates.add(\"pitru\");\n      candidates.add(\"pitraDosha\");\n      break;\n    default:\n      break;\n  }\n\n  return Array.from(candidates);\n}\n\nfunction isActiveDoshaStatus(status: string | undefined): boolean {\n  if (!status) return false;\n  const normalized = status.toLowerCase();\n  return (\n    normalized === \"present\" ||\n    normalized === \"active\" ||\n    normalized === \"partial\" ||\n    normalized === \"suggested\"\n  );\n}\n\nfunction getSeverityScore(severity?: string): number {\n  if (!severity) return 2;\n  const normalized = severity.toLowerCase();\n  if (normalized === \"severe\" || normalized === \"high\") return 3;\n  if (normalized === \"moderate\" || normalized === \"medium\") return 2;\n  if (normalized === \"mild\" || normalized === \"low\") return 1;\n  return 2;\n}\n\nfunction appendCurrentQueryParams(urlString: string): string {\n  if (!urlString) return urlString;\n  if (typeof window === \"undefined\") return urlString;\n\n  try {\n    const currentParams = new URLSearchParams(window.location.search);\n    if (Array.from(currentParams.keys()).length === 0) {\n      return urlString;\n    }\n\n    const targetUrl = new URL(urlString, window.location.href);\n    currentParams.forEach((value, key) => {\n      targetUrl.searchParams.set(key, value);\n    });\n    return targetUrl.toString();\n  } catch {\n    return urlString;\n  }\n}\n\nfunction getFirstActiveDoshaType(summary: DoshaSummary): string | null {\n  const doshas: Array<{ type: string; severity?: string }> = [];\n\n  if (isActiveDoshaStatus(summary.kaalSarp)) {\n    doshas.push({\n      type: \"kaal-sarp\",\n      severity: typeof summary.kaalSarpSeverity === \"string\" ? summary.kaalSarpSeverity : undefined,\n    });\n  }\n\n  if (isActiveDoshaStatus(summary.pitra)) {\n    doshas.push({\n      type: \"pitra\",\n      severity: typeof summary.pitraSeverity === \"string\" ? summary.pitraSeverity : undefined,\n    });\n  }\n\n  if (\n    isActiveDoshaStatus(summary.shaniSadeSati || summary.sadeSati)\n  ) {\n    doshas.push({\n      type: \"shani\",\n      severity: typeof summary.sadeSatiSeverity === \"string\" ? summary.sadeSatiSeverity : undefined,\n    });\n  }\n\n  if (\n    isActiveDoshaStatus(summary.mangal) &&\n    !summary.mangal?.toLowerCase().includes(\"nullified\")\n  ) {\n    doshas.push({\n      type: \"mangal\",\n      severity: typeof summary.mangalSeverity === \"string\" ? summary.mangalSeverity : undefined,\n    });\n  }\n\n  if (doshas.length === 0) return null;\n\n  doshas.sort((a, b) => getSeverityScore(b.severity) - getSeverityScore(a.severity));\n  return doshas[0]?.type ?? null;\n}\n\nfunction TrustBadgesRow({ t }: { t: (key: string) => string }) {\n  return (\n    <div className={footerShellStyles.marqueeContent}>\n      <span className={footerShellStyles.badge}>\n        <DefaultDoshaImage\n          src={ICON_KUNDLI_CREATED}\n          alt=\"\"\n          className={footerShellStyles.badgeIcon}\n          width={16}\n          height={16}\n          loading=\"lazy\"\n        />\n        {t(\"ctaKundliCreated\")}\n      </span>\n      <span className={footerShellStyles.badge}>\n        <DefaultDoshaImage\n          src={ICON_CERTIFIED}\n          alt=\"\"\n          className={footerShellStyles.badgeIcon}\n          width={16}\n          height={16}\n          loading=\"lazy\"\n        />\n        {t(\"ctaCertified\")}\n      </span>\n      <span className={footerShellStyles.badge}>\n        <DefaultDoshaImage\n          src={ICON_SECURE_PAYMENT}\n          alt=\"\"\n          className={footerShellStyles.badgeIcon}\n          width={16}\n          height={16}\n          loading=\"lazy\"\n        />\n        {t(\"ctaSecurePayment\")}\n      </span>\n    </div>\n  );\n}\n\nconst FAQ_ITEMS = [\n  { qKey: \"faqQ1\", aKey: \"faqA1\" },\n  { qKey: \"faqQ2\", aKey: \"faqA2\" },\n  { qKey: \"faqQ3\", aKey: \"faqA3\" },\n];\n\nconst FAQ_ITEMS_MARRIAGE = [\n  { qKey: \"faqQ1Marriage\", aKey: \"faqA1Marriage\" },\n  { qKey: \"faqQ2Marriage\", aKey: \"faqA2Marriage\" },\n  { qKey: \"faqQ3Marriage\", aKey: \"faqA3Marriage\" },\n  { qKey: \"faqQ4Marriage\", aKey: \"faqA4Marriage\" },\n];\n\nexport interface DoshaCalculatorProps {\n  /** Optional class name for the container */\n  className?: string;\n  /** Logo URL (optional) */\n  logoUrl?: string;\n  /** Optional language selector slot */\n  languageSelector?: React.ReactNode;\n  /** Whether to show language selector */\n  showLanguageSelector?: boolean;\n  /** Whether the user is global (hides language toggle when true) */\n  isGlobal?: boolean;\n  /** Read more reviews link (optional) */\n  readMoreReviewsHref?: string;\n  \n  // Configuration options (simplified API)\n  /** Supabase project URL - if provided with supabaseAnonKey, a client will be created automatically */\n  supabaseUrl?: string;\n  /** Supabase anon/publishable key - if provided with supabaseUrl, a client will be created automatically */\n  supabaseAnonKey?: string;\n  /** Google Maps API key - if provided, place resolution will be handled automatically */\n  googleMapsApiKey?: string;\n  \n  // Advanced options (for custom implementations)\n  /** Supabase client for backend submission (Lovable / celestial-puja-finder compatible). Use this if you want to pass a pre-configured client instead of supabaseUrl + supabaseAnonKey. */\n  supabase?: SupabaseClient | null;\n  /** Resolve birth place string to { lat, lon, tz }. Use this as an alternative to googleMapsApiKey for custom place resolution or dev/testing environments. If both are provided, autocomplete will use googleMapsApiKey but submit will fallback to resolvePlace if coordinates aren't available. */\n  resolvePlace?: (place: string) => Promise<ResolvedPlace | null>;\n  /** Called with result when calculation succeeds; second arg is birth details for Kundali when available */\n  onResult?: (\n    result: DoshaCalculationResult,\n    birthDetails?: BirthDetails,\n  ) => void;\n  /** Called with error message when calculation fails */\n  onError?: (error: string) => void;\n  /** Render a puja card for the given dosha type (e.g. mangal, kaal-sarp, pitra, shani). Optional: when omitted, package auto-fetches pujas and renders built-in cards. */\n  renderPujaCard?: (doshaType: string) => React.ReactNode;\n  /** When true, show a loading state in the puja recommendation area (e.g. while host fetches pujas). */\n  isLoadingPujas?: boolean;\n  /** Optional: render the Kundali chart section (e.g. KundaliCard). When provided, \"Go Back\" and \"Planetary Positions Causing These Doshas\" are shown. */\n  renderKundali?: () => React.ReactNode;\n  /** Optional: id for the kundali section (e.g. \"kundali-chart-section\") for \"View Kundli\" deep link. */\n  kundaliSectionId?: string;\n  /** Optional analytics implementation for tracking user interactions */\n  analytics?: DoshaAnalytics;\n  /**\n  * Function to get first puja info for the given dosha type.\n  * Optional: when omitted, package auto-fetches pujas and computes CTA info internally.\n  * Return null if no puja is available for that dosha.\n   */\n  getFirstPujaInfo?: (doshaType: string) => {\n    name: string;\n    price: number;\n    link?: string;\n  } | null;\n  /** Called when Book Puja CTA is clicked (optional, defaults to opening the puja link) */\n  onBookPujaClick?: () => void;\n  /** Optional image component (e.g. next/image adapter) for optimized images. */\n  imageComponent?: DoshaImageComponent;\n}\n\nexport function DoshaCalculator({\n  className = \"\",\n  logoUrl = DEFAULT_LOGO_URL,\n  languageSelector,\n  showLanguageSelector = true,\n  isGlobal = false,\n  readMoreReviewsHref,\n  supabaseUrl,\n  supabaseAnonKey,\n  googleMapsApiKey,\n  supabase: supabaseProp,\n  resolvePlace: resolvePlaceProp,\n  onResult,\n  onError,\n  renderPujaCard,\n  isLoadingPujas = false,\n  renderKundali,\n  kundaliSectionId = \"kundali-chart-section\",\n  analytics,\n  getFirstPujaInfo,\n  onBookPujaClick,\n  imageComponent = DefaultDoshaImage,\n}: DoshaCalculatorProps) {\n  // Create Supabase client from URL and key if provided\n  const supabase = useMemo(() => {\n    if (supabaseProp) {\n      return supabaseProp;\n    }\n    if (supabaseUrl && supabaseAnonKey) {\n      try {\n        const client = createSupabaseClient(supabaseUrl, supabaseAnonKey);\n        return client;\n      } catch (error) {\n        return null;\n      }\n    }\n    return null;\n  }, [supabaseProp, supabaseUrl, supabaseAnonKey]);\n\n\n\n  const Img = imageComponent;\n  const i18n = useI18n();\n  const t = i18n?.t ?? ((key: string) => key);\n  const locale = i18n?.locale ?? \"en\";\n  const setLocale = i18n?.setLocale;\n  const isHindi = locale.toLowerCase().startsWith(\"hi\");\n  const formSectionRef = useRef<HTMLDivElement>(null);\n  const formSubmitRef = useRef<{ submit: () => Promise<void> } | null>(null);\n  const [isFormComplete, setIsFormComplete] = useState(false);\n  const [isLoading, setIsLoading] = useState(false);\n  const [result, setResult] = useState<DoshaCalculationResult | null>(null);\n  const [birthDetails, setBirthDetails] = useState<BirthDetails | null>(null);\n  const [savedFormValues, setSavedFormValues] = useState<\n    DoshaFormValues | undefined\n  >(undefined);\n  const [isEditing, setIsEditing] = useState(false);\n  const [fallbackPujas, setFallbackPujas] = useState<SriMandirPuja[]>([]);\n  const [isLoadingFallbackPujas, setIsLoadingFallbackPujas] = useState(false);\n  const [firstPujaInfo, setFirstPujaInfo] = useState<{\n    name: string;\n    price: number;\n    link?: string;\n  } | null>(null);\n  const webViewTrackedRef = useRef(false);\n\n  useEffect(() => {\n    if (webViewTrackedRef.current) return;\n    webViewTrackedRef.current = true;\n    analytics?.trackDoshaCalculatorWebView?.();\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  const needsInternalPujaFallback = !renderPujaCard || !getFirstPujaInfo;\n\n  useEffect(() => {\n    if (!needsInternalPujaFallback || !supabase) return;\n\n    let isMounted = true;\n    setIsLoadingFallbackPujas(true);\n\n    fetchPujas(supabase)\n      .then((pujas) => {\n        if (!isMounted) return;\n        setFallbackPujas(pujas);\n      })\n      .finally(() => {\n        if (!isMounted) return;\n        setIsLoadingFallbackPujas(false);\n      });\n\n    return () => {\n      isMounted = false;\n    };\n  }, [needsInternalPujaFallback, supabase]);\n\n  const fallbackRenderPujaCard = useCallback(\n    (doshaType: string) => {\n      const puja = getPujaForDosha(fallbackPujas, doshaType);\n      if (!puja) return null;\n      return (\n        <SriMandirPujaVerticalCard\n          puja={puja}\n          doshaType={doshaType}\n          language={locale}\n          imageComponent={imageComponent}\n          analytics={analytics}\n        />\n      );\n    },\n    [fallbackPujas, locale, imageComponent, analytics],\n  );\n\n  const fallbackGetFirstPujaInfo = useCallback(\n    (doshaType: string) => {\n      const puja = getPujaForDosha(fallbackPujas, doshaType);\n      if (!puja) return null;\n      return {\n        name: getPujaTitle(puja, locale),\n        price: puja.individual_pack_price_inr,\n        link: getPujaLink(puja, locale),\n      };\n    },\n    [fallbackPujas, locale],\n  );\n\n  const pujaCardRenderer = renderPujaCard ?? fallbackRenderPujaCard;\n  const firstPujaInfoResolver = getFirstPujaInfo ?? fallbackGetFirstPujaInfo;\n  const resolvedIsLoadingPujas =\n    isLoadingPujas || (!renderPujaCard && isLoadingFallbackPujas);\n\n  // Get banner config based on utm_term and current locale\n  // Use state to avoid hydration mismatch (URL params not available during SSR)\n  const [bannerConfig, setBannerConfig] = useState(() => {\n    const utmTerm = typeof window !== 'undefined' ? getUtmTerm() : null;\n    return getBannerConfig(utmTerm, locale);\n  });\n  const [bannerType, setBannerType] = useState<BannerType>(() => {\n    if (typeof window === 'undefined') return \"generic\";\n    const utmTerm = getUtmTerm();\n    if (utmTerm && utmTerm.toLowerCase().includes(\"marriage\")) {\n      return \"marriage\";\n    }\n    return \"generic\";\n  });\n  \n  useEffect(() => {\n    const utmTerm = getUtmTerm();\n    const config = getBannerConfig(utmTerm, locale);\n    setBannerConfig(config);\n    \n    // Determine banner type based on utm_term\n    let type: BannerType = \"generic\";\n    if (utmTerm) {\n      const lowerUtm = utmTerm.toLowerCase();\n      if (lowerUtm.includes(\"marriage\")) {\n        type = \"marriage\";\n      }\n    }\n    setBannerType(type);\n  }, [locale]);\n\n  // Check if \"what you'll get\" section should be shown first\n  // Use state to avoid hydration mismatch (URL params not available during SSR)\n  const [showWhatYouGetFirst, setShowWhatYouGetFirst] = useState(false);\n  \n  useEffect(() => {\n    const utmTerm = getUtmTerm();\n    if (utmTerm && utmTerm.toLowerCase().includes(\"what-you\")) {\n      setShowWhatYouGetFirst(true);\n    }\n  }, []);\n\n  const scrollToForm = () => {\n    formSectionRef.current?.scrollIntoView({ behavior: \"smooth\" });\n  };\n\n  const handleSectionImpression = useCallback(\n    (section: string) => {\n      analytics?.trackDoshaSectionImpression?.({\n        section,\n        timestamp: new Date().toISOString(),\n      });\n    },\n    [analytics],\n  );\n\n  const handleResult = (\n    data: DoshaCalculationResult,\n    details?: BirthDetails,\n  ) => {\n    setResult(data);\n    setBirthDetails(details ?? null);\n    setIsEditing(false);\n\n    // Extract first puja info if available\n    if (data.summary) {\n      const summary = data.summary;\n      const firstDoshaType = getFirstActiveDoshaType(summary);\n\n      if (firstDoshaType) {\n        const pujaInfo = getPujaDoshaTypeCandidates(firstDoshaType)\n          .map((type) => firstPujaInfoResolver(type))\n          .find(Boolean) ?? null;\n        setFirstPujaInfo(pujaInfo);\n      } else {\n        setFirstPujaInfo(null);\n      }\n    } else {\n      setFirstPujaInfo(null);\n    }\n\n    onResult?.(data, details);\n  };\n\n  useEffect(() => {\n    if (getFirstPujaInfo || !result?.summary) return;\n\n    const firstDoshaType = getFirstActiveDoshaType(result.summary);\n    if (!firstDoshaType) {\n      setFirstPujaInfo(null);\n      return;\n    }\n\n    const pujaInfo = getPujaDoshaTypeCandidates(firstDoshaType)\n      .map((type) => fallbackGetFirstPujaInfo(type))\n      .find(Boolean) ?? null;\n    setFirstPujaInfo(pujaInfo);\n  }, [fallbackGetFirstPujaInfo, getFirstPujaInfo, result]);\n\n  const handleEditForm = () => {\n    setIsEditing(true);\n    window.scrollTo({ top: 0, behavior: \"smooth\" });\n  };\n\n  const handleCtaPress = () => {\n    // If showing results and not editing, handle book puja\n    if (result && !isEditing && firstPujaInfo) {\n      // Track book CTA click\n      if (firstPujaInfo.link) {\n        const linkWithQueryParams = appendCurrentQueryParams(firstPujaInfo.link);\n        analytics?.trackDoshaCalculatorResultBookCtaClicked?.({\n          position: 'floating_cta',\n          url: linkWithQueryParams,\n          isOldDosha: false,\n        });\n      }\n      \n      if (onBookPujaClick) {\n        onBookPujaClick();\n      } else if (firstPujaInfo.link) {\n        const linkWithQueryParams = appendCurrentQueryParams(firstPujaInfo.link);\n        window.open(linkWithQueryParams, \"_blank\", \"noopener,noreferrer\");\n      }\n      return;\n    }\n\n    console.log(\"supabase\", supabase);\n    console.log(\"resolvePlaceProp\", resolvePlaceProp);\n    console.log(\"isFormComplete\", isFormComplete);\n    console.log(\"formSubmitRef.current\", formSubmitRef.current);\n    // Otherwise, handle form submission or scroll\n    if (supabase && formSubmitRef.current) {\n      analytics?.trackFloatingCtaClicked?.(\n        isFormComplete\n          ? FLOATING_CTA_STATUS.all_fields_filled\n          : FLOATING_CTA_STATUS.fields_not_filled,\n      );\n      if (!isFormComplete) {\n        scrollToForm();\n      }\n      formSubmitRef.current.submit();\n    } else {\n      analytics?.trackFloatingCtaClicked?.(\n        FLOATING_CTA_STATUS.fields_not_filled,\n      );\n      scrollToForm();\n    }\n  };\n\n  const defaultLanguageSelector = (showLanguageSelector && !isGlobal) ? (\n    <button\n      type=\"button\"\n      onClick={() => {\n        if (setLocale) {\n          setLocale(isHindi ? \"en\" : \"hi\");\n        }\n      }}\n      aria-label={isHindi ? \"Switch to English\" : \"हिंदी में बदलें\"}\n      className=\"flex items-center justify-center gap-1.5 py-2 rounded-lg text-white text-sm font-medium hover:opacity-90 transition-colors\"\n      style={{ backgroundColor: \"#E13A44\", borderRadius: \"8px\", width: \"100px\" }}\n      disabled={!setLocale}\n    >\n      <Img src={ICON_GLOBE} alt=\"\" className=\"w-5 h-5 brightness-0 invert\" width={20} height={20} loading=\"lazy\" />\n      <span>{isHindi ? \"English\" : \"हिंदी\"}</span>\n    </button>\n  ) : null;\n\n  const resolvedLanguageSelector = defaultLanguageSelector;\n\n  return (\n    <div className={className}>\n      <PageHeader\n        t={t}\n        logoUrl={logoUrl}\n        languageSelector={resolvedLanguageSelector}\n        showLanguageSelector={showLanguageSelector}\n      />\n      <MarqueeStrip>\n        <TrustBadgesRow t={t} />\n      </MarqueeStrip>\n      {!result && (\n        <SectionWithImpression\n          section=\"banner\"\n          onImpression={handleSectionImpression}\n        >\n          <DoshaBanner bannerConfig={bannerConfig} imageComponent={imageComponent} />\n        </SectionWithImpression>\n      )}\n      <main className=\"pb-28\">\n        {result ? (\n          <SectionWithImpression\n            section=\"result\"\n            onImpression={handleSectionImpression}\n          >\n            <Suspense fallback={\n              <div className=\"container mx-auto px-4 py-8 space-y-4\">\n                <Skeleton className=\"h-12 w-3/4 mx-auto\" />\n                <Skeleton className=\"h-32 w-full\" />\n                <Skeleton className=\"h-48 w-full\" />\n                <Skeleton className=\"h-48 w-full\" />\n              </div>\n            }>\n              <DoshaResultsFull\n                result={result}\n                t={t}\n                onEdit={!isEditing ? handleEditForm : undefined}\n                inlineEditForm={\n                  isEditing ? (\n                    <DoshaFormSection\n                      ref={formSubmitRef}\n                      t={t}\n                      initialValues={savedFormValues}\n                      onValuesChange={setSavedFormValues}\n                      onFormValidityChange={setIsFormComplete}\n                      supabase={supabase ?? undefined}\n                      resolvePlace={resolvePlaceProp}\n                      googleMapsApiKey={googleMapsApiKey}\n                      onResult={handleResult}\n                      onError={onError}\n                      onLoadingChange={setIsLoading}\n                      analytics={analytics}\n                    />\n                  ) : undefined\n                }\n                renderPujaCard={pujaCardRenderer}\n                isLoadingPujas={resolvedIsLoadingPujas}\n                renderKundali={renderKundali}\n                kundaliSectionId={kundaliSectionId}\n                birthDetails={birthDetails}\n                supabase={supabase}\n                language={i18n?.locale ?? \"en\"}\n                readMoreReviewsHref={readMoreReviewsHref}\n                analytics={analytics}\n                problemArea={(() => {\n                  const problems = savedFormValues?.problems || [];\n                  const translatedProblems = problems\n                    .filter((key) => key !== 'formProblemOther')\n                    .map((key) => t(key))\n                    .filter(Boolean);\n                  const otherText = savedFormValues?.otherProblemText?.trim();\n                  if (problems.includes('formProblemOther') && otherText) {\n                    translatedProblems.push(otherText);\n                  }\n                  return translatedProblems.join(', ');\n                })()}\n                problemAreaIds={savedFormValues?.problems || []}\n                customProblemText={savedFormValues?.otherProblemText || \"\"}\n              />\n            </Suspense>\n          </SectionWithImpression>\n        ) : (\n          /* Landing page */\n          <>\n            {showWhatYouGetFirst && (\n              <SectionWithImpression\n                section=\"what_from_analysis\"\n                onImpression={handleSectionImpression}\n              >\n                <WhatFromAnalysis t={t} bannerType={bannerType} />\n              </SectionWithImpression>\n            )}\n            <SectionWithImpression\n              section=\"form\"\n              onImpression={handleSectionImpression}\n            >\n              <div ref={formSectionRef}>\n                <DoshaFormSection\n                  ref={formSubmitRef}\n                  t={t}\n                  initialValues={savedFormValues}\n                  onValuesChange={setSavedFormValues}\n                  onFormValidityChange={setIsFormComplete}\n                  supabase={supabase ?? undefined}\n                  resolvePlace={resolvePlaceProp}\n                  googleMapsApiKey={googleMapsApiKey}\n                  onResult={handleResult}\n                  onError={onError}\n                  onLoadingChange={setIsLoading}\n                  analytics={analytics}\n                />\n              </div>\n            </SectionWithImpression>\n            {!showWhatYouGetFirst && (\n              <SectionWithImpression\n                section=\"what_from_analysis\"\n                onImpression={handleSectionImpression}\n              >\n                <WhatFromAnalysis t={t} bannerType={bannerType} />\n              </SectionWithImpression>\n            )}\n            <SectionWithImpression\n              section=\"user_reviews\"\n              onImpression={handleSectionImpression}\n            >\n              <UserReviewsSection\n                t={(key: string) => {\n                  if (bannerType === \"marriage\") {\n                    if (key === \"feedbackTitle\")\n                      return t(\"feedbackTitleMarriage\");\n                    if (key.startsWith(\"feedbackTestimonial\")) {\n                      const num = key.replace(\"feedbackTestimonial\", \"\");\n                      const marriageKey = `feedbackTestimonialMarriage${num}`;\n                      const val = t(marriageKey);\n                      return val === marriageKey ? t(key) : val;\n                    }\n                  }\n                  return t(key);\n                }}\n                readMoreHref={readMoreReviewsHref}\n                onReadMore={\n                  analytics?.trackReadMoreReviewsClicked\n                    ? () => analytics.trackReadMoreReviewsClicked!()\n                    : undefined\n                }\n              />\n            </SectionWithImpression>\n            <SectionWithImpression\n              section=\"faq\"\n              onImpression={handleSectionImpression}\n            >\n              <FAQAccordion\n                t={t}\n                items={\n                  bannerType === \"marriage\" ? FAQ_ITEMS_MARRIAGE : FAQ_ITEMS\n                }\n                defaultOpenIndex={0}\n                onItemOpen={(questionText: string) =>\n                  analytics?.trackFaqQuestionClicked?.(questionText)\n                }\n              />\n            </SectionWithImpression>\n            <SectionWithImpression\n              section=\"contact\"\n              onImpression={handleSectionImpression}\n            >\n              <ContactUsSection\n                title={t(\"contactTitle\")}\n                brandName={t(\"contactBrandName\")}\n                whatsAppLine={t(\"contactWhatsAppDomestic\")}\n                emailLine={t(\"contactEmail\")}\n              />\n            </SectionWithImpression>\n          </>\n        )}\n      </main>\n      {/* Hide floating CTA when showing results with no active doshas */}\n      {!(result && !isEditing && getFirstActiveDoshaType(result.summary) === null) && (\n        <FooterShell>\n          {/* Hide trust badge when showing book puja CTA */}\n          {!(result && !isEditing && firstPujaInfo) && <FooterTrustBadge />}\n          <DoshaFooterCTA\n            isFormComplete={isFormComplete}\n            onPress={handleCtaPress}\n            labelDefault={t(\"formCta\")}\n            labelFilled={t(\"formCtaCalculate\")}\n            loadingLabel={t(\"calculating\")}\n            isLoading={isLoading}\n            mode={result && !isEditing && firstPujaInfo ? \"book-puja\" : \"form\"}\n            firstPuja={firstPujaInfo || undefined}\n            showingResults={!!result && !isEditing}\n            bookPujaLabel={t(\"bookPuja\")}\n          />\n        </FooterShell>\n      )}\n    </div>\n  );\n}\n","import React from 'react';\nimport type { DoshaCalculationResult, DoshaSummary } from '../../types/dosha-api';\nimport styles from './DoshaResultsView.module.scss';\n\nconst DOSHA_KEYS = [\n  { key: 'mangal', labelKey: 'resultMangal', summaryKey: 'mangal' as keyof DoshaSummary },\n  { key: 'kaalSarp', labelKey: 'resultKaalSarp', summaryKey: 'kaalSarp' as keyof DoshaSummary },\n  { key: 'pitra', labelKey: 'resultPitra', summaryKey: 'pitra' as keyof DoshaSummary },\n  { key: 'sadeSati', labelKey: 'resultSadeSati', summaryKey: 'shaniSadeSati' as keyof DoshaSummary },\n] as const;\n\nfunction isPresent(status: string | undefined): boolean {\n  if (!status) return false;\n  const s = status.toLowerCase();\n  return s === 'present' || s === 'active' || s === 'partial' || s === 'suggested';\n}\n\nfunction getDetail(\n  details: DoshaCalculationResult['details'],\n  detailKey: string\n): { explanation?: string; remedies?: string } | undefined {\n  if (Array.isArray(details)) {\n    const item = details.find((d: Record<string, unknown>) => (d.name ?? d.type) === detailKey);\n    return item as { explanation?: string; remedies?: string } | undefined;\n  }\n  if (details && typeof details === 'object' && detailKey in details) {\n    const raw = (details as Record<string, { explanation?: string; remedies?: string | string[] }>)[detailKey];\n    if (!raw) return undefined;\n    const remedies =\n      typeof raw.remedies === 'string'\n        ? raw.remedies\n        : Array.isArray(raw.remedies)\n          ? raw.remedies.join('\\n')\n          : undefined;\n    return { explanation: raw.explanation, remedies };\n  }\n  return undefined;\n}\n\nfunction translateStatus(status: string | undefined, t: (k: string) => string): string {\n  if (!status) return '';\n  const s = status.toLowerCase();\n  if (s.includes('nullified')) return t('resultStatusPresent');\n  if (s === 'present' || s === 'active' || s === 'partial' || s === 'suggested') return t('resultStatusPresent');\n  if (s === 'absent') return t('resultStatusAbsent');\n  if (s === 'inactive') return t('resultStatusInactive');\n  return status;\n}\n\nexport interface DoshaResultsViewProps {\n  result: DoshaCalculationResult;\n  t: (key: string) => string;\n  onEdit?: () => void;\n  className?: string;\n}\n\nexport function DoshaResultsView({ result, t, onEdit, className = '' }: DoshaResultsViewProps) {\n  const summary = result.summary ?? {};\n  const details = result.details ?? {};\n  const shaniSadeSati = summary.shaniSadeSati ?? summary.sadeSati;\n  const hasAnyDosha =\n    isPresent(summary.mangal) ||\n    isPresent(summary.kaalSarp) ||\n    isPresent(summary.pitra) ||\n    isPresent(shaniSadeSati);\n\n  return (\n    <section className={`${styles.section} ${className}`} aria-labelledby=\"dosha-results-heading\">\n      <h2 id=\"dosha-results-heading\" className={hasAnyDosha ? `${styles.heading} ${styles.headingSuccess}` : styles.heading}>\n        {hasAnyDosha ? t('resultSomeDoshas') : t('resultNoDoshas')}\n      </h2>\n\n      {!hasAnyDosha ? (\n        <div className={styles.noDoshas}>\n          <p>{t('resultNoDoshas')}</p>\n          <p className={styles.noDoshasDesc}>{t('resultNoDoshasDesc')}</p>\n        </div>\n      ) : (\n        <div>\n          {DOSHA_KEYS.map(({ key, labelKey, summaryKey }) => {\n            const status = summaryKey === 'shaniSadeSati' ? shaniSadeSati : (summary[summaryKey] as string | undefined);\n            const present = isPresent(status);\n            const detail = getDetail(details, key === 'sadeSati' ? 'sadeSati' : key);\n            const explanation = detail?.explanation;\n            const remedies = typeof detail?.remedies === 'string' ? detail.remedies : undefined;\n\n            return (\n              <div\n                key={key}\n                className={`${styles.card} ${present ? styles.cardPresent : styles.cardAbsent}`}\n              >\n                <div className={styles.cardHeader}>\n                  <span className={styles.doshaName}>{t(labelKey)}</span>\n                  <span\n                    className={`${styles.badge} ${\n                      present ? styles.badgePresent : status === 'inactive' ? styles.badgeInactive : styles.badgeAbsent\n                    }`}\n                  >\n                    {translateStatus(status, t)}\n                  </span>\n                </div>\n                {(explanation || remedies) && (\n                  <div className={styles.body}>\n                    {explanation && (\n                      <div>\n                        <div className={styles.bodyLabel}>{t('resultExplanation')}</div>\n                        <p className={styles.accordionContent}>{explanation}</p>\n                      </div>\n                    )}\n                    {remedies && (\n                      <div style={{ marginTop: explanation ? '0.75rem' : 0 }}>\n                        <div className={styles.bodyLabel}>{t('resultRemedies')}</div>\n                        <p className={styles.accordionContent}>{remedies}</p>\n                      </div>\n                    )}\n                  </div>\n                )}\n              </div>\n            );\n          })}\n        </div>\n      )}\n\n      {onEdit && (\n        <button type=\"button\" className={styles.editBtn} onClick={onEdit} aria-label={t('resultEditForm')}>\n          {t('resultEditForm')}\n        </button>\n      )}\n    </section>\n  );\n}\n","import * as React from 'react';\n\nexport interface BadgeProps extends React.HTMLAttributes<HTMLDivElement> {\n  variant?: 'default' | 'secondary' | 'destructive' | 'outline';\n}\n\nconst Badge = React.forwardRef<HTMLDivElement, BadgeProps>(\n  ({ className = '', variant = 'default', ...props }, ref) => {\n    const variantClasses = {\n      default: 'border-transparent bg-primary text-primary-foreground',\n      secondary: 'border-transparent bg-secondary text-secondary-foreground',\n      destructive: 'border-transparent bg-destructive/10 text-destructive',\n      outline: 'border-border text-muted-foreground bg-transparent',\n    };\n    return (\n      <div\n        ref={ref}\n        className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors ${variantClasses[variant]} ${className}`}\n        {...props}\n      />\n    );\n  }\n);\nBadge.displayName = 'Badge';\n\nexport { Badge };\n","import * as React from 'react';\nimport { ChevronDown } from '../icons';\n\ninterface AccordionContextValue {\n  value: string | null;\n  onToggle: (v: string) => void;\n}\nconst AccordionContext = React.createContext<AccordionContextValue | null>(null);\n\nexport interface AccordionProps {\n  type?: 'single';\n  collapsible?: boolean;\n  className?: string;\n  children: React.ReactNode;\n  onValueChange?: (value: string | null) => void;\n}\n\nexport function Accordion({\n  type = 'single',\n  collapsible = true,\n  className = '',\n  children,\n  onValueChange,\n}: AccordionProps) {\n  const [value, setValue] = React.useState<string | null>(null);\n  const onToggle = React.useCallback(\n    (v: string) => {\n      setValue((prev) => {\n        const next = prev === v ? (collapsible ? null : prev) : v;\n        onValueChange?.(next);\n        return next;\n      });\n    },\n    [collapsible, onValueChange]\n  );\n  return (\n    <AccordionContext.Provider value={{ value, onToggle }}>\n      <div className={className}>{children}</div>\n    </AccordionContext.Provider>\n  );\n}\n\nexport interface AccordionItemProps {\n  value: string;\n  className?: string;\n  children: React.ReactNode;\n}\n\nexport function AccordionItem({ value, className = '', children }: AccordionItemProps) {\n  return (\n    <div data-state={value} className={`border-b border-border ${className}`}>\n      {children}\n    </div>\n  );\n}\n\nexport interface AccordionTriggerProps {\n  className?: string;\n  children: React.ReactNode;\n  value: string;\n}\n\nexport function AccordionTrigger({\n  className = '',\n  children,\n  value,\n}: AccordionTriggerProps) {\n  const ctx = React.useContext(AccordionContext);\n  const isOpen = ctx?.value === value;\n  return (\n    <button\n      type=\"button\"\n      onClick={() => ctx?.onToggle(value)}\n      className={`flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline w-full text-left ${className}`}\n      aria-expanded={isOpen}\n    >\n      {children}\n      <ChevronDown\n        className={`h-4 w-4 shrink-0 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}\n      />\n    </button>\n  );\n}\n\nexport interface AccordionContentProps {\n  className?: string;\n  children: React.ReactNode;\n  value: string;\n}\n\nexport function AccordionContent({\n  className = '',\n  children,\n  value,\n}: AccordionContentProps) {\n  const ctx = React.useContext(AccordionContext);\n  const isOpen = ctx?.value === value;\n  if (!isOpen) return null;\n  return (\n    <div className={`overflow-hidden text-sm pb-4 pt-0 ${className}`}>\n      {children}\n    </div>\n  );\n}\n","import type { SupabaseClient } from '@supabase/supabase-js';\nimport type { BirthDetails } from '../types/dosha-api';\n\nexport type { BirthDetails };\nexport type ChartType = 'North' | 'South';\n\ninterface CacheEntry {\n  svg: string;\n  timestamp: number;\n}\n\nconst svgCache = new Map<string, CacheEntry>();\nconst CACHE_TTL = 30 * 60 * 1000;\n\nfunction getCacheKey(birthDetails: BirthDetails, chartType: ChartType, language: string): string {\n  return `D1|${chartType}|svg|${birthDetails.day}-${birthDetails.month}-${birthDetails.year}-${birthDetails.hour}-${birthDetails.minute}-${birthDetails.lat}-${birthDetails.lon}-${birthDetails.tzone}|${language}`;\n}\n\nfunction getFromCache(key: string): string | null {\n  const memEntry = svgCache.get(key);\n  if (memEntry && Date.now() - memEntry.timestamp < CACHE_TTL) {\n    return memEntry.svg;\n  }\n  try {\n    const stored = sessionStorage.getItem(`kundali_${key}`);\n    if (stored) {\n      const parsed = JSON.parse(stored) as CacheEntry;\n      if (Date.now() - parsed.timestamp < CACHE_TTL) {\n        svgCache.set(key, parsed);\n        return parsed.svg;\n      }\n      sessionStorage.removeItem(`kundali_${key}`);\n    }\n  } catch {\n    // ignore\n  }\n  return null;\n}\n\nfunction setCache(key: string, svg: string): void {\n  const entry: CacheEntry = { svg, timestamp: Date.now() };\n  svgCache.set(key, entry);\n  try {\n    sessionStorage.setItem(`kundali_${key}`, JSON.stringify(entry));\n  } catch {\n    // ignore\n  }\n}\n\nfunction makeResponsiveSvg(svgString: string): string {\n  try {\n    const parser = new DOMParser();\n    const doc = parser.parseFromString(svgString, 'image/svg+xml');\n    const svg = doc.querySelector('svg');\n    if (!svg) return svgString;\n    svg.removeAttribute('width');\n    svg.removeAttribute('height');\n    if (!svg.getAttribute('viewBox')) {\n      svg.setAttribute('viewBox', '0 0 350 350');\n    }\n    svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');\n    svg.setAttribute('style', 'width:100%;height:auto;display:block;');\n    return new XMLSerializer().serializeToString(doc);\n  } catch (e) {\n    console.error('[kundaliChart] SVG transform error:', e);\n    return svgString;\n  }\n}\n\nexport interface FetchKundaliOptions {\n  birthDetails: BirthDetails;\n  chartType: ChartType;\n  language: 'en' | 'hi';\n  signal?: AbortSignal;\n}\n\nexport async function fetchKundaliSvg(\n  supabase: SupabaseClient,\n  options: FetchKundaliOptions\n): Promise<string> {\n  const { birthDetails, chartType, language, signal } = options;\n  const cacheKey = getCacheKey(birthDetails, chartType, language);\n  const cached = getFromCache(cacheKey);\n  if (cached) return cached;\n\n  const response = await supabase.functions.invoke('get-kundali-chart', {\n    body: {\n      ...birthDetails,\n      chartType,\n      language,\n    },\n  });\n\n  if (signal?.aborted) {\n    throw new DOMException('Aborted', 'AbortError');\n  }\n  if (response.error) {\n    throw new Error(response.error.message || 'Failed to fetch kundali chart');\n  }\n  const svg = response.data?.data?.svg;\n  if (!svg) {\n    throw new Error('No SVG data in response');\n  }\n  const responsiveSvg = makeResponsiveSvg(svg);\n  setCache(cacheKey, responsiveSvg);\n  return responsiveSvg;\n}\n","import React, { useState, useEffect, useRef, useCallback } from 'react';\nimport type { SupabaseClient } from '@supabase/supabase-js';\nimport { Card, CardContent, CardHeader, CardTitle } from '../ui/Card';\nimport { Button } from '../ui/Button';\nimport { Skeleton } from '../ui/Skeleton';\nimport { RotateCcw } from '../icons';\nimport { fetchKundaliSvg, type BirthDetails, type ChartType } from '../../lib/kundaliChart';\n\nexport interface KundaliCardProps {\n  birthDetails: BirthDetails;\n  supabase: SupabaseClient;\n  /** Current language for chart labels (e.g. 'en' or 'hi') */\n  language: string;\n  /** Translation function for UI strings */\n  t: (key: string) => string;\n}\n\nexport function KundaliCard({ birthDetails, supabase, language, t }: KundaliCardProps) {\n  const [chartType, setChartType] = useState<ChartType>('North');\n  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');\n  const [svgString, setSvgString] = useState<string>('');\n  const [errorMsg, setErrorMsg] = useState<string>('');\n  const abortControllerRef = useRef<AbortController | null>(null);\n  const cardRef = useRef<HTMLDivElement>(null);\n\n  const isHindi = (language || '').toLowerCase().startsWith('hi');\n  const lang = isHindi ? 'hi' : 'en';\n\n  const fetchChart = useCallback(\n    async (type: ChartType) => {\n      if (abortControllerRef.current) {\n        abortControllerRef.current.abort();\n      }\n      const controller = new AbortController();\n      abortControllerRef.current = controller;\n      setStatus('loading');\n      setErrorMsg('');\n      try {\n        const svg = await fetchKundaliSvg(supabase, {\n          birthDetails,\n          chartType: type,\n          language: lang,\n          signal: controller.signal,\n        });\n        if (!controller.signal.aborted) {\n          setSvgString(svg);\n          setStatus('success');\n        }\n      } catch (error: unknown) {\n        if (error instanceof Error && error.name === 'AbortError') return;\n        console.error('[KundaliCard] Fetch error:', error);\n        if (!controller.signal.aborted) {\n          setErrorMsg(error instanceof Error ? error.message : 'Failed to load chart');\n          setStatus('error');\n        }\n      }\n    },\n    [birthDetails, supabase, lang]\n  );\n\n  useEffect(() => {\n    fetchChart(chartType);\n    return () => {\n      if (abortControllerRef.current) {\n        abortControllerRef.current.abort();\n      }\n    };\n  }, [chartType, fetchChart]);\n\n  const handleChartTypeChange = (type: ChartType) => {\n    if (type !== chartType) setChartType(type);\n  };\n\n  const handleRetry = () => {\n    fetchChart(chartType);\n  };\n\n  return (\n    <Card ref={cardRef} className=\"spiritual-glow border border-primary/10\">\n      <CardHeader className=\"pb-3\">\n        <CardTitle className=\"text-xl font-bold\">{t('drYourKundali')}</CardTitle>\n        <div className=\"flex gap-2 mt-3 pt-2\">\n          <Button\n            type=\"button\"\n            size=\"sm\"\n            variant={chartType === 'North' ? 'default' : 'outline'}\n            className=\"rounded-full px-4\"\n            onClick={() => handleChartTypeChange('North')}\n          >\n            {t('kundaliChartNorth')}\n          </Button>\n          <Button\n            type=\"button\"\n            size=\"sm\"\n            variant={chartType === 'South' ? 'default' : 'outline'}\n            className=\"rounded-full px-4\"\n            onClick={() => handleChartTypeChange('South')}\n          >\n            {t('kundaliChartSouth')}\n          </Button>\n        </div>\n      </CardHeader>\n      <CardContent>\n        <div className=\"w-full max-w-[360px] mx-auto\">\n          {status === 'loading' && (\n            <Skeleton className=\"w-full aspect-square rounded-lg\" />\n          )}\n          {status === 'success' && svgString && (\n            <div\n              className=\"w-full aspect-square\"\n              dangerouslySetInnerHTML={{ __html: svgString }}\n            />\n          )}\n          {status === 'error' && (\n            <div className=\"w-full aspect-square flex flex-col items-center justify-center bg-muted/30 rounded-lg border border-border\">\n              <p className=\"text-sm text-muted-foreground mb-3\">{t('kundaliChartLoadError')}</p>\n              <Button\n                type=\"button\"\n                variant=\"outline\"\n                size=\"sm\"\n                onClick={handleRetry}\n                className=\"gap-2\"\n              >\n                <RotateCcw className=\"w-4 h-4\" />\n                {t('kundaliChartRetry')}\n              </Button>\n            </div>\n          )}\n        </div>\n      </CardContent>\n    </Card>\n  );\n}\n","import React, { useState, useEffect, useRef } from 'react';\nimport {\n  Card,\n  CardContent,\n  CardDescription,\n  CardHeader,\n  CardTitle,\n} from '../ui/Card';\nimport { Badge } from '../ui/Badge';\nimport {\n  Accordion,\n  AccordionContent,\n  AccordionItem,\n  AccordionTrigger,\n} from '../ui/Accordion';\nimport {\n  AlertTriangle,\n  CheckCircle,\n  Info,\n  Flame,\n  Waves,\n  Users,\n  Moon,\n  ArrowUp,\n  Loader2,\n  ChevronDown,\n} from '../icons';\nimport type { DoshaCalculationResult, DoshaSummary, BirthDetails } from '../../types/dosha-api';\nimport type { SupabaseClient } from '@supabase/supabase-js';\nimport type { DoshaAnalytics } from '../../analytics';\nimport { KundaliCard } from '../KundaliCard/KundaliCard';\nimport {\n  UserReviewsSection,\n  FAQAccordion,\n  ContactUsSection,\n} from '@srimandir/astrology-common';\n\nconst FAQ_ITEMS = [\n  { qKey: 'faqQ1', aKey: 'faqA1' },\n  { qKey: 'faqQ2', aKey: 'faqA2' },\n  { qKey: 'faqQ3', aKey: 'faqA3' },\n];\n\nconst DOSHA_CONFIG = [\n  {\n    type: 'kaal-sarp',\n    detailKey: 'kaalSarp',\n    nameKey: 'drKaalSarpName',\n    descKey: 'drKaalSarpDesc',\n    impactKey: 'drKaalSarpImpact',\n    remediesKey: 'drKaalSarpRemedies',\n    benefitsKey: 'drPujaBenefitsKaalSarp',\n    icon: Waves,\n    summaryKey: 'kaalSarp' as keyof DoshaSummary,\n    severityKey: 'kaalSarpSeverity',\n  },\n  {\n    type: 'pitra',\n    detailKey: 'pitra',\n    nameKey: 'drPitraName',\n    descKey: 'drPitraDesc',\n    impactKey: 'drPitraImpact',\n    remediesKey: 'drPitraRemedies',\n    benefitsKey: 'drPujaBenefitsPitra',\n    icon: Users,\n    summaryKey: 'pitra' as keyof DoshaSummary,\n    severityKey: 'pitraSeverity',\n  },\n  {\n    type: 'shani',\n    detailKey: 'sadeSati',\n    nameKey: 'drSadeSatiName',\n    descKey: 'drSadeSatiDesc',\n    impactKey: 'drSadeSatiImpact',\n    remediesKey: 'drSadeSatiRemedies',\n    benefitsKey: 'drPujaBenefitsShani',\n    icon: Moon,\n    summaryKey: 'shaniSadeSati' as keyof DoshaSummary,\n    severityKey: 'sadeSatiSeverity',\n  },\n  {\n    type: 'mangal',\n    detailKey: 'mangal',\n    nameKey: 'drMangalName',\n    descKey: 'drMangalDesc',\n    impactKey: 'drMangalImpact',\n    remediesKey: 'drMangalRemedies',\n    benefitsKey: 'drPujaBenefitsMangal',\n    icon: Flame,\n    summaryKey: 'mangal' as keyof DoshaSummary,\n    severityKey: 'mangalSeverity',\n  },\n];\n\nfunction getPujaDoshaTypeCandidates(doshaType: string, detailKey?: string): string[] {\n  const candidates = new Set<string>([doshaType]);\n\n  if (detailKey) {\n    candidates.add(detailKey);\n  }\n\n  switch (doshaType) {\n    case 'kaal-sarp':\n      candidates.add('kaalSarp');\n      candidates.add('kaalsarp');\n      candidates.add('kaal_sarp');\n      break;\n    case 'shani':\n      candidates.add('sadeSati');\n      candidates.add('shaniSadeSati');\n      candidates.add('sade-sati');\n      break;\n    case 'mangal':\n      candidates.add('mangalDosha');\n      candidates.add('manglik');\n      break;\n    case 'pitra':\n      candidates.add('pitru');\n      candidates.add('pitraDosha');\n      break;\n    default:\n      break;\n  }\n\n  return Array.from(candidates);\n}\n\nfunction isPresent(status: string | undefined): boolean {\n  if (!status) return false;\n  const s = status.toLowerCase();\n  return s === 'present' || s === 'active' || s === 'partial' || s === 'suggested';\n}\n\nfunction isNullified(status: string | undefined): boolean {\n  if (!status) return false;\n  return status.toLowerCase().includes('nullified');\n}\n\nfunction getDetail(\n  details: DoshaCalculationResult['details'],\n  detailKey: string\n): { explanation?: string; remedies?: string; placements?: string[] } | undefined {\n  if (Array.isArray(details)) {\n    const item = details.find(\n      (d: Record<string, unknown>) => (d.name ?? d.type) === detailKey\n    ) as Record<string, unknown> | undefined;\n    if (!item) return undefined;\n    const remedies =\n      typeof item.remedies === 'string'\n        ? item.remedies\n        : Array.isArray(item.remedies)\n          ? (item.remedies as string[]).join('\\n')\n          : undefined;\n    const placements = Array.isArray(item.placements) ? (item.placements as string[]) : undefined;\n    return {\n      explanation: item.explanation as string | undefined,\n      remedies,\n      placements,\n    };\n  }\n  if (details && typeof details === 'object' && detailKey in details) {\n    const raw = (details as Record<string, { explanation?: string; remedies?: string | string[]; placements?: string[] }>)[\n      detailKey\n    ];\n    if (!raw) return undefined;\n    const remedies =\n      typeof raw.remedies === 'string'\n        ? raw.remedies\n        : Array.isArray(raw.remedies)\n          ? raw.remedies.join('\\n')\n          : undefined;\n    return {\n      explanation: raw.explanation,\n      remedies,\n      placements: raw.placements,\n    };\n  }\n  return undefined;\n}\n\nfunction translateStatus(status: string | undefined, t: (k: string) => string): string {\n  if (!status) return '';\n  const s = status.toLowerCase();\n  if (s.includes('nullified')) return t('drStatusNullified');\n  if (s === 'present' || s === 'active' || s === 'partial' || s === 'suggested')\n    return t('drStatusPresent');\n  if (s === 'absent') return t('drStatusAbsent');\n  if (s === 'inactive') return t('drStatusInactive');\n  return status;\n}\n\nfunction getSeverityScore(severity?: string): number {\n  if (!severity) return 2;\n  const s = severity.toLowerCase();\n  if (s === 'severe' || s === 'high') return 3;\n  if (s === 'moderate' || s === 'medium') return 2;\n  if (s === 'mild' || s === 'low') return 1;\n  return 2;\n}\n\nfunction mapSeverityToLabel(severity: string | undefined, t: (k: string) => string): string {\n  if (!severity) return t('drSeverityMedium');\n  const s = severity.toLowerCase();\n  if (s === 'severe' || s === 'high') return t('drSeverityHigh');\n  if (s === 'moderate' || s === 'medium') return t('drSeverityMedium');\n  if (s === 'mild' || s === 'low') return t('drSeverityLow');\n  return t('drSeverityMedium');\n}\n\nfunction looksEnglishOnlyText(value: string): boolean {\n  if (!value) return false;\n  const containsDevanagari = /[\\u0900-\\u097F]/.test(value);\n  if (containsDevanagari) return false;\n  const containsLatin = /[A-Za-z]/.test(value);\n  return containsLatin;\n}\n\nexport interface DoshaResultsFullProps {\n  result: DoshaCalculationResult;\n  t: (key: string) => string;\n  onEdit?: () => void;\n  className?: string;\n  /** Optional: scroll target id for \"View Kundli\" / \"Go Back\" (e.g. \"kundali-chart-section\"). If not set, those links are hidden. */\n  kundaliSectionId?: string;\n  /** Optional: contact email for feedback section */\n  feedbackEmail?: string;\n  /** Render a puja card for the given dosha type (mangal, kaal-sarp, pitra, shani). When provided, shown in the \"Puja Recommendation\" section per dosha. */\n  renderPujaCard?: (doshaType: string) => React.ReactNode;\n  /** When true, show loading state in the puja recommendation area. */\n  isLoadingPujas?: boolean;\n  /** Optional: render the Kundali chart section (e.g. KundaliCard). When provided, overrides built-in KundaliCard. */\n  renderKundali?: () => React.ReactNode;\n  /** Birth details from form submit; when set with supabase, built-in KundaliCard is shown (unless renderKundali is provided). */\n  birthDetails?: BirthDetails | null;\n  /** Supabase client for fetching Kundali chart; required for built-in KundaliCard. */\n  supabase?: SupabaseClient | null;\n  /** Current locale (e.g. 'en' or 'hi') for KundaliCard. */\n  language?: string;\n  /** Optional link for \"Read More Reviews\" in the UserReviewsSection. */\n  readMoreReviewsHref?: string;\n  /** When provided, replaces the edit button with this slot (e.g. an inline edit form). */\n  inlineEditForm?: React.ReactNode;\n  /** Optional analytics implementation for tracking user interactions */\n  analytics?: DoshaAnalytics;\n  /** Problem area text for personalized impact generation */\n  problemArea?: string;\n  /** Array of problem area IDs */\n  problemAreaIds?: string[];\n  /** Custom problem text when \"other\" is selected */\n  customProblemText?: string;\n}\n\nexport function DoshaResultsFull({\n  result,\n  t,\n  onEdit,\n  className = '',\n  kundaliSectionId,\n  feedbackEmail = 'pujaseva@appsforbharat.com',\n  renderPujaCard,\n  isLoadingPujas = false,\n  renderKundali,\n  birthDetails,\n  supabase,\n  language = 'en',\n  readMoreReviewsHref,\n  inlineEditForm,\n  analytics,\n  problemArea,\n  problemAreaIds,\n  customProblemText,\n}: DoshaResultsFullProps) {\n  const [personalizedImpacts, setPersonalizedImpacts] = useState<Record<string, { title: string; text: string }>>({});\n  const [isLoadingImpacts, setIsLoadingImpacts] = useState(false);\n\n  const showBuiltInKundali = !renderKundali && birthDetails && supabase;\n  const summary = result.summary ?? {};\n  const details = result.details ?? {};\n\n  // Generate personalized impacts when problemArea is provided\n  useEffect(() => {\n    if (!problemArea || !problemArea.trim() || !supabase) {\n      setIsLoadingImpacts(false);\n      return;\n    }\n\n    setIsLoadingImpacts(true);\n    setPersonalizedImpacts({});\n\n    const generateImpacts = async () => {\n      const impacts: Record<string, { title: string; text: string }> = {};\n      \n      const doshaTypes = ['mangal', 'kaal-sarp', 'pitra', 'shani'];\n      const activeTypes = doshaTypes.filter(type => {\n        if (type === 'mangal') return isPresent(summary.mangal) && !isNullified(summary.mangal);\n        if (type === 'kaal-sarp') return isPresent(summary.kaalSarp);\n        if (type === 'pitra') return isPresent(summary.pitra);\n        if (type === 'shani') return isPresent(summary.shaniSadeSati ?? summary.sadeSati);\n        return false;\n      });\n\n      console.log('[DoshaResultsFull] Generating impacts for:', activeTypes, 'problemArea:', problemArea);\n\n      const promises = activeTypes.map(async (doshaType) => {\n        try {\n          // Map form IDs to simple lowercase identifiers for API\n          const problemIdMap: Record<string, string> = {\n            'formProblemMarriage': 'marriage',\n            'formProblemMoney': 'financial',\n            'formProblemHealth': 'health',\n            'formProblemEducation': 'education',\n            'formProblemCareer': 'career',\n            'formProblemBusiness': 'business',\n            'formProblemFamily': 'family',\n            'formProblemFinancial': 'financial',\n            'formProblemOther': 'other',\n          };\n          \n          const mappedProblemAreaIds = problemAreaIds\n            ?.filter((id) => id !== 'formProblemOther')\n            .map((id) => problemIdMap[id] || id.toLowerCase())\n            .filter(Boolean) || [];\n          \n          // Add 'other' if custom problem text present\n          if (problemAreaIds?.includes('formProblemOther') && customProblemText?.trim()) {\n            mappedProblemAreaIds.push('other');\n          }\n          \n          const relevantProblemId = mappedProblemAreaIds[0] || undefined;\n          \n          console.log(`[DoshaResultsFull] Calling generate-impact for ${doshaType}`, {\n            originalProblemAreaIds: problemAreaIds,\n            mappedProblemAreaIds,\n            problemArea,\n            problemAreaId: relevantProblemId,\n            customProblemText,\n            language: language?.toLowerCase().startsWith('hi') ? 'hi' : 'en'\n          });\n\n          const response = await supabase.functions.invoke('generate-impact', {\n            body: {\n              doshaType,\n              problemArea,\n              problemAreaId: relevantProblemId,\n              problemAreaIds: mappedProblemAreaIds,\n              customProblemText: customProblemText,\n              language: language?.toLowerCase().startsWith('hi') ? 'hi' : 'en'\n            }\n          });\n          \n          console.log(`[DoshaResultsFull] Impact response for ${doshaType}:`, response.data);\n          \n          if (response.error) {\n            console.error(`[DoshaResultsFull] Error generating impact for ${doshaType}:`, response.error);\n            return;\n          }\n          \n          if (response.data?.impactText) {\n            impacts[doshaType] = {\n              title: response.data.impactTitle || t('drImpactIfPresent'),\n              text: response.data.impactText\n            };\n          }\n        } catch (error) {\n          console.error(`[DoshaResultsFull] Failed to generate impact for ${doshaType}:`, error);\n        }\n      });\n\n      await Promise.all(promises);\n      console.log('[DoshaResultsFull] Final personalized impacts:', impacts);\n      setPersonalizedImpacts(impacts);\n      setIsLoadingImpacts(false);\n    };\n\n    generateImpacts();\n  }, [problemArea, problemAreaIds, customProblemText, language, supabase, summary]);\n\n  // Track result page view\n  useEffect(() => {\n    analytics?.trackDoshaCalculatorResultPageView?.();\n  }, [analytics]);\n\n  const shaniSadeSati = summary.shaniSadeSati ?? summary.sadeSati;\n  \n  // Other doshas (grahan, shrapit, etc.) — keys and label keys\n  const OTHER_DOSHA_KEYS: Array<{ summaryKey: string; detailKey: string; labelKey: string; descKey: string; impactKey: string; remediesKey: string }> = [\n    { summaryKey: 'grahan', detailKey: 'grahan', labelKey: 'drOtherGrahan', descKey: 'drOtherGrahanDesc', impactKey: 'drOtherGrahanImpact', remediesKey: 'drOtherGrahanRemedies' },\n    { summaryKey: 'shrapit', detailKey: 'shrapit', labelKey: 'drOtherShrapit', descKey: 'drOtherShrapitDesc', impactKey: 'drOtherShrapitImpact', remediesKey: 'drOtherShrapitRemedies' },\n    { summaryKey: 'guruChandal', detailKey: 'guruChandal', labelKey: 'drOtherGuruChandal', descKey: 'drOtherGuruChandalDesc', impactKey: 'drOtherGuruChandalImpact', remediesKey: 'drOtherGuruChandalRemedies' },\n    { summaryKey: 'punarphoo', detailKey: 'punarphoo', labelKey: 'drOtherPunarphoo', descKey: 'drOtherPunarphooDesc', impactKey: 'drOtherPunarphooImpact', remediesKey: 'drOtherPunarphooRemedies' },\n    { summaryKey: 'kemadruma', detailKey: 'kemadruma', labelKey: 'drOtherKemadruma', descKey: 'drOtherKemadrumaDesc', impactKey: 'drOtherKemadrumaImpact', remediesKey: 'drOtherKemadrumaRemedies' },\n    { summaryKey: 'gandmool', detailKey: 'gandmool', labelKey: 'drOtherGandmool', descKey: 'drOtherGandmoolDesc', impactKey: 'drOtherGandmoolImpact', remediesKey: 'drOtherGandmoolRemedies' },\n    { summaryKey: 'kalathra', detailKey: 'kalathra', labelKey: 'drOtherKalathra', descKey: 'drOtherKalathraDec', impactKey: 'drOtherKalathraImpact', remediesKey: 'drOtherKalathraRemedies' },\n    { summaryKey: 'vishDaridra', detailKey: 'vishDaridra', labelKey: 'drOtherVishDaridra', descKey: 'drOtherVishDaridraDesc', impactKey: 'drOtherVishDaridraImpact', remediesKey: 'drOtherVishDaridraRemedies' },\n    { summaryKey: 'ketuNaga', detailKey: 'ketuNaga', labelKey: 'drOtherKetuNaga', descKey: 'drOtherKetuNagaDesc', impactKey: 'drOtherKetuNagaImpact', remediesKey: 'drOtherKetuNagaRemedies' },\n    { summaryKey: 'navagrahaUmbrella', detailKey: 'navagraha', labelKey: 'drOtherNavagraha', descKey: 'drOtherNavagrahaDesc', impactKey: 'drOtherNavagrahaImpact', remediesKey: 'drOtherNavagrahaRemedies' },\n  ];\n  const otherDoshasPresent = OTHER_DOSHA_KEYS.filter(\n    (o) => isPresent((summary as Record<string, string>)[o.summaryKey])\n  );\n  const hasOtherDoshas = otherDoshasPresent.length > 0;\n  \n  const hasAnyDosha =\n    (isPresent(summary.mangal) && !isNullified(summary.mangal)) ||\n    isPresent(summary.kaalSarp) ||\n    isPresent(summary.pitra) ||\n    isPresent(shaniSadeSati) ||\n    hasOtherDoshas;\n\n  const activeDoshas: Array<{\n    type: string;\n    detailKey: string;\n    label: string;\n    icon: typeof Flame;\n    status: string;\n    severity?: string;\n    phase?: number | null;\n    explanation: string;\n    placements?: string[];\n    impact: string;\n    remedies: string[];\n    benefits: string[];\n  }> = [];\n\n  for (const cfg of DOSHA_CONFIG) {\n    const status =\n      cfg.summaryKey === 'shaniSadeSati' ? shaniSadeSati : (summary[cfg.summaryKey] as string | undefined);\n    if (!isPresent(status)) continue;\n    if (cfg.type === 'mangal' && isNullified(status)) continue;\n    const severity = (summary as Record<string, string>)[cfg.severityKey];\n    const phase = cfg.type === 'shani' ? summary.shaniPhase ?? (summary as Record<string, number>).shaniPhase : undefined;\n    const detail = getDetail(details, cfg.detailKey === 'sadeSati' ? 'sadeSati' : cfg.detailKey);\n    const rawExplanation = detail?.explanation;\n    const explanation =\n      rawExplanation && !(\n        language.toLowerCase().startsWith('hi') && looksEnglishOnlyText(rawExplanation)\n      )\n        ? rawExplanation\n        : t(cfg.descKey);\n    const remediesStr =\n      detail?.remedies ?? t(cfg.remediesKey);\n    const remedies = remediesStr.split('\\n').map((s) => s.trim()).filter(Boolean);\n    const benefitsStr = t(cfg.benefitsKey);\n    const benefits = benefitsStr.split('\\n').map((s) => s.trim()).filter(Boolean);\n    activeDoshas.push({\n      type: cfg.type,\n      detailKey: cfg.detailKey,\n      label: t(cfg.nameKey),\n      icon: cfg.icon,\n      status: status ?? '',\n      severity: severity || 'moderate',\n      phase: phase ?? undefined,\n      explanation,\n      placements: detail?.placements,\n      impact: t(cfg.impactKey),\n      remedies,\n      benefits,\n    });\n  }\n\n  activeDoshas.sort((a, b) => getSeverityScore(b.severity) - getSeverityScore(a.severity));\n\n  const [isOtherExpanded, setIsOtherExpanded] = useState(false);\n\n  // Build \"Planetary Positions Causing These Doshas\" list (main 4 + other doshas with evidence)\n  const positionHintRegex = /\\b(house|lagna|ascendant|moon|mars|saturn|rahu|ketu|sun|jupiter|venus|mercury|sign|degree|H\\d+|conjunction|aspect)\\b|भाव|लग्न|चंद्र|मंगल|शनि|राहु|केतु|सूर्य|बृहस्पति|शुक्र|बुध/i;\n  const detailsRecord = details && typeof details === 'object' && !Array.isArray(details) ? (details as Record<string, { placements?: string[]; triggeredBy?: string[]; notes?: string[] }>) : {};\n  const allDoshaItems: Array<{ label: string; evidence: string[] }> = [];\n  activeDoshas.forEach((dosha) => {\n    const detail = detailsRecord[dosha.detailKey === 'sadeSati' ? 'sadeSati' : dosha.detailKey] || {};\n    const rawEvidence: string[] = [\n      ...(detail.placements || []),\n      ...(detail.triggeredBy || []),\n      ...(detail.notes || []),\n    ].map((s) => String(s || '').trim()).filter(Boolean);\n    const uniqueEvidence = Array.from(new Set(rawEvidence));\n    const evidence = uniqueEvidence.filter((l) => positionHintRegex.test(l));\n    const finalEvidence = evidence.length > 0 ? evidence : uniqueEvidence;\n    if (finalEvidence.length > 0) allDoshaItems.push({ label: dosha.label, evidence: finalEvidence });\n  });\n  OTHER_DOSHA_KEYS.forEach((o) => {\n    if (!isPresent((summary as Record<string, string>)[o.summaryKey])) return;\n    const detail = detailsRecord[o.detailKey] || {};\n    const rawEvidence: string[] = [\n      ...(detail.placements || []),\n      ...(detail.triggeredBy || []),\n      ...(detail.notes || []),\n    ].map((s) => String(s || '').trim()).filter(Boolean);\n    const uniqueEvidence = Array.from(new Set(rawEvidence));\n    const evidence = uniqueEvidence.filter((l) => positionHintRegex.test(l));\n    const finalEvidence = evidence.length > 0 ? evidence : uniqueEvidence;\n    if (finalEvidence.length > 0) {\n      const label = t(o.labelKey);\n      if (!allDoshaItems.some((d) => d.label === label)) allDoshaItems.push({ label, evidence: finalEvidence });\n    }\n  });\n\n  const getPhaseExplanation = (phase: number): string => {\n    if (phase === 1) return t('drPhaseRising');\n    if (phase === 2) return t('drPhasePeak');\n    if (phase === 3) return t('drPhaseSetting');\n    return '';\n  };\n\n  const sectionColors = [\n    'bg-orange-50/50 border-l-4 border-l-orange-400',\n    'bg-blue-50/50 border-l-4 border-l-blue-400',\n    'bg-purple-50/50 border-l-4 border-l-purple-400',\n    'bg-amber-50/50 border-l-4 border-l-amber-400',\n  ];\n\n  return (\n    <div className={`w-full max-w-2xl mx-auto space-y-6 ${className}`}>\n      {/* Page header */}\n      <div className=\"px-4 pt-4 pb-2 mb-6\">\n        <div className=\"text-center\">\n          <h1\n            className=\"text-2xl font-bold mb-2\"\n            style={{ color: '#1F2937', fontFamily: '\"Plus Jakarta Sans\", sans-serif' }}\n          >\n            {t('resultPageTitle')}\n          </h1>\n          <p\n            className=\"text-sm leading-relaxed\"\n            style={{ color: '#6B7280', fontFamily: '\"Plus Jakarta Sans\", sans-serif' }}\n          >\n            {t('resultPageSubtitle')}\n          </p>\n        </div>\n        {inlineEditForm ? (\n          <div className=\"mt-4\">{inlineEditForm}</div>\n        ) : onEdit ? (\n          <button\n            type=\"button\"\n            onClick={onEdit}\n            className=\"mt-4 inline-flex items-center gap-2 min-h-[44px] px-4 text-sm font-medium border border-gray-300 bg-white rounded-md hover:bg-gray-50 transition-colors text-gray-700\"\n            style={{ fontFamily: '\"Plus Jakarta Sans\", sans-serif' }}\n          >\n            <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n              <path d=\"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7\" />\n              <path d=\"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z\" />\n            </svg>\n            {t('resultEditForm')}\n          </button>\n        ) : null}\n      </div>\n\n      {/* Status Header */}\n      <Card className=\"spiritual-glow border-2 border-primary/20 mx-4\">\n        <CardHeader>\n          <CardTitle\n            id=\"dosha-results-heading\"\n            className={`text-2xl sm:text-3xl font-bold break-words ${\n              hasAnyDosha ? 'text-primary' : 'text-success'\n            }`}\n          >\n            {hasAnyDosha ? t('resultSomeDoshas') : `✓ ${t('resultNoDoshas')}`}\n          </CardTitle>\n        </CardHeader>\n        <CardContent>\n          {!hasAnyDosha ? (\n            <div className=\"text-center py-8\">\n              <CheckCircle className=\"w-12 h-12 mx-auto mb-4 text-success\" />\n              <p className=\"text-lg font-medium text-foreground\">{t('resultNoDoshas')}</p>\n              <p className=\"text-sm text-muted-foreground mt-2\">{t('resultNoDoshasDesc')}</p>\n            </div>\n          ) : (\n            <div className=\"flex flex-wrap gap-2\">\n              {activeDoshas.map((dosha) => (\n                <div\n                  key={dosha.type}\n                  className=\"inline-flex items-center gap-2 bg-accent/20 border border-accent/30 px-4 py-2 rounded-full\"\n                >\n                  <AlertTriangle className=\"w-4 h-4 text-primary\" />\n                  <span className=\"font-medium text-sm text-foreground\">\n                    {dosha.label}: {translateStatus(dosha.status, t)}\n                  </span>\n                </div>\n              ))}\n            </div>\n          )}\n        </CardContent>\n      </Card>\n\n      {/* Individual Dosha Sections */}\n      {activeDoshas.map((dosha, index) => {\n        const DoshaIcon = dosha.icon;\n        const phaseExplanation =\n          dosha.type === 'shani' && dosha.phase ? getPhaseExplanation(dosha.phase) : '';\n        const sectionColor = sectionColors[index % sectionColors.length];\n        const doshaOfLabel = t('drDoshaOf')\n          .replace('{{index}}', String(index + 1))\n          .replace('{{total}}', String(activeDoshas.length));\n\n        return (\n          <Card\n            key={dosha.type}\n            className={`spiritual-glow border border-primary/10 mx-4 ${sectionColor}`}\n          >\n            <div className=\"px-4 pt-3\">\n              <Badge variant=\"outline\" className=\"text-xs font-normal text-muted-foreground\">\n                {doshaOfLabel}\n              </Badge>\n            </div>\n            <CardHeader className=\"pb-3 pt-2\">\n              <CardTitle className=\"flex items-center gap-3 text-xl\">\n                <DoshaIcon className=\"w-6 h-6 text-primary\" />\n                {dosha.label}\n              </CardTitle>\n              <CardDescription>\n                {t('drSeverity')}: {mapSeverityToLabel(dosha.severity, t)}\n                {dosha.phase != null && ` • ${t('drPhase')}: ${dosha.phase}`}\n              </CardDescription>\n            </CardHeader>\n            <CardContent className=\"space-y-4\">\n              <div className=\"space-y-2\">\n                <h4 className=\"font-semibold text-base flex items-center gap-2\">\n                  <Info className=\"w-4 h-4 text-primary\" />\n                  {t('drWhyMarked')}\n                  {kundaliSectionId && (\n                    <button\n                      type=\"button\"\n                      onClick={() => {\n                        analytics?.trackDoshaCalculatorResultViewKundliClick?.();\n                        const el = document.getElementById(kundaliSectionId);\n                        if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });\n                      }}\n                      className=\"text-xs text-primary hover:underline ml-auto whitespace-nowrap\"\n                    >\n                      {t('drViewKundli')} ↓\n                    </button>\n                  )}\n                </h4>\n                <p className=\"text-sm text-muted-foreground leading-relaxed\">{dosha.explanation}</p>\n                {phaseExplanation && (\n                  <div className=\"mt-3 p-3 bg-warning/10 rounded-md border border-warning/20\">\n                    <h5 className=\"font-medium text-sm mb-2\">{t('drPhaseMeaning')}</h5>\n                    <p className=\"text-sm text-muted-foreground\">{phaseExplanation}</p>\n                  </div>\n                )}\n                {dosha.type !== 'pitra' && dosha.placements && dosha.placements.length > 0 && (\n                  <div className=\"mt-3 p-3 bg-accent/10 rounded-md border border-accent/20\">\n                    <h5 className=\"font-medium text-sm mb-2\">{t('drPlanetaryPositions')}</h5>\n                    <ul className=\"list-disc list-inside text-sm text-muted-foreground space-y-1\">\n                      {dosha.placements.map((p, i) => (\n                        <li key={i}>{p}</li>\n                      ))}\n                    </ul>\n                  </div>\n                )}\n              </div>\n\n              <div className=\"p-4 bg-destructive/10 border border-destructive/20 rounded-lg\">\n                <h4 className=\"font-semibold text-sm mb-2 text-destructive\">\n                  {personalizedImpacts[dosha.type]?.title || t('drImpactIfPresent')}\n                </h4>\n                {isLoadingImpacts ? (\n                  <div className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n                    <Loader2 className=\"w-4 h-4 animate-spin\" />\n                    <span>{language === 'hi' ? 'प्रभाव विश्लेषण हो रहा है...' : 'Analyzing impact...'}</span>\n                  </div>\n                ) : (\n                  <p className=\"text-sm text-muted-foreground\">\n                    {personalizedImpacts[dosha.type]?.text || dosha.impact}\n                  </p>\n                )}\n              </div>\n\n              <div className=\"space-y-2\">\n                <h4 className=\"font-semibold text-base\">{t('drPujaRecommendation')}</h4>\n                {renderPujaCard ? (\n                  isLoadingPujas ? (\n                    <div className=\"flex items-center justify-center py-6\">\n                      <Loader2 className=\"w-6 h-6 text-primary animate-spin\" size={24} />\n                    </div>\n                  ) : (\n                    (() => {\n                      const doshaTypeCandidates = getPujaDoshaTypeCandidates(\n                        dosha.type,\n                        dosha.detailKey\n                      );\n                      const card = doshaTypeCandidates\n                        .map((type) => renderPujaCard(type))\n                        .find(Boolean);\n                      if (!card && typeof window !== 'undefined') {\n                        // eslint-disable-next-line no-console\n                        console.warn(\n                          `[DoshaCalculator] renderPujaCard returned null/undefined for dosha type: ${dosha.type} (tried: ${doshaTypeCandidates.join(', ')})`\n                        );\n                      }\n                      return card || (\n                        <p className=\"text-sm text-muted-foreground italic\">{t('drNoPujaAvailable')}</p>\n                      );\n                    })()\n                  )\n                ) : (\n                  <p className=\"text-sm text-muted-foreground italic\">\n                    {t('drNoPujaAvailable')}\n                    {typeof window !== 'undefined' && (() => {\n                      // eslint-disable-next-line no-console\n                      console.warn('[DoshaCalculator] renderPujaCard prop not provided. Pass renderPujaCard to show puja recommendations.');\n                      return null;\n                    })()}\n                  </p>\n                )}\n              </div>\n\n              {dosha.benefits.length > 0 && (\n                <div className=\"space-y-2\">\n                  <h4 className=\"font-semibold text-base flex items-center gap-2\">\n                    {t('drHowPujaHelps')}\n                  </h4>\n                  <ul className=\"text-sm text-muted-foreground space-y-3 ml-1\">\n                    {dosha.benefits.map((benefit, i) => (\n                      <li key={i} className=\"flex items-start gap-3\">\n                        <span className=\"text-primary mt-1.5 flex-shrink-0\">•</span>\n                        <span>{benefit}</span>\n                      </li>\n                    ))}\n                  </ul>\n                </div>\n              )}\n            </CardContent>\n          </Card>\n        );\n      })}\n\n      {activeDoshas.length > 0 && (\n        <p className=\"text-xs text-muted-foreground text-center italic px-4\">{t('drFomoLine')}</p>\n      )}\n\n      {/* Feedback Section */}\n      <div className=\"mx-4 p-4 bg-muted/30 rounded-lg border border-border/50 text-center\">\n        <p className=\"text-sm text-foreground/80 font-medium\">{t('drFeedbackContact')}</p>\n        <a\n          href={`mailto:${feedbackEmail}`}\n          className=\"text-primary hover:underline font-semibold text-base mt-1 inline-block\"\n        >\n          {feedbackEmail}\n        </a>\n      </div>\n\n      {/* Detailed Analysis & Remedies */}\n      <Card className=\"spiritual-glow mx-4\">\n        <CardHeader>\n          <CardTitle className=\"text-2xl font-bold text-center gradient-spiritual bg-clip-text text-transparent\">\n            {t('drDetailedAnalysis')}\n          </CardTitle>\n          <CardDescription className=\"text-center\">{t('drBasedOnChart')}</CardDescription>\n        </CardHeader>\n        <CardContent className=\"space-y-4\">\n          <Accordion type=\"single\" collapsible className=\"w-full space-y-4\">\n            {DOSHA_CONFIG.map((cfg) => {\n              const accordionKey = cfg.detailKey === 'sadeSati' ? 'sadeSati' : cfg.detailKey;\n              const status =\n                cfg.summaryKey === 'shaniSadeSati'\n                  ? shaniSadeSati\n                  : (summary[cfg.summaryKey] as string | undefined);\n              const detail = getDetail(\n                details,\n                cfg.detailKey === 'sadeSati' ? 'sadeSati' : cfg.detailKey\n              );\n              const severity = (summary as Record<string, string>)[cfg.severityKey];\n              const phase = cfg.type === 'shani' ? summary.shaniPhase : undefined;\n              const Icon = cfg.icon;\n              const apiRemedies = detail?.remedies?.trim();\n              const remediesStr = apiRemedies || t(cfg.remediesKey);\n              const remediesList = remediesStr.split('\\n').map((s) => s.trim()).filter(Boolean);\n\n              return (\n                <AccordionItem key={accordionKey} value={accordionKey} className=\"border border-border rounded-lg px-4\">\n                  <AccordionTrigger value={accordionKey} className=\"hover:no-underline\">\n                    <div className=\"flex items-center gap-3\">\n                      <Icon className=\"w-5 h-5 text-destructive\" />\n                      <div className=\"text-left\">\n                        <h3 className=\"font-semibold text-lg\">{t(cfg.nameKey)}</h3>\n                        <p className=\"text-sm text-muted-foreground\">\n                          {t('drStatus')}: {translateStatus(status, t)}\n                          {severity && !isNullified(status) && ` • ${t('drSeverity')}: ${mapSeverityToLabel(severity, t)}`}\n                          {cfg.type === 'shani' && phase != null && ` • ${t('drPhase')}: ${phase}`}\n                        </p>\n                      </div>\n                    </div>\n                  </AccordionTrigger>\n                  <AccordionContent value={accordionKey} className=\"pt-4 space-y-4\">\n                    <p className=\"text-sm text-muted-foreground italic\">{t(cfg.descKey)}</p>\n                    {detail?.explanation && (\n                      <div>\n                        <h4 className=\"font-medium mb-2\">{t('drExplanation')}</h4>\n                        <p className=\"text-sm text-muted-foreground\">{detail.explanation}</p>\n                      </div>\n                    )}\n                    {detail?.placements && detail.placements.length > 0 && (\n                      <div className=\"p-3 bg-accent/10 rounded-md\">\n                        <h4 className=\"font-medium mb-2\">{t('drPlanetaryPositions')}</h4>\n                        <ul className=\"list-disc list-inside text-sm text-muted-foreground space-y-1\">\n                          {detail.placements.map((p, i) => (\n                            <li key={i}>{p}</li>\n                          ))}\n                        </ul>\n                      </div>\n                    )}\n                    <div>\n                      <h4 className=\"font-medium mb-2\">{t('drTraditionalRemedies')}</h4>\n                      <ul className=\"list-disc list-inside text-sm text-muted-foreground space-y-1\">\n                        {remediesList.map((remedy, i) => (\n                          <li key={i}>{remedy}</li>\n                        ))}\n                      </ul>\n                    </div>\n                  </AccordionContent>\n                </AccordionItem>\n              );\n            })}\n          </Accordion>\n        </CardContent>\n      </Card>\n\n      {/* Other Doshas */}\n      <Card className=\"mx-4\">\n        <CardHeader\n          className=\"cursor-pointer hover:bg-accent/5 transition-colors\"\n          onClick={() => setIsOtherExpanded((v: boolean) => !v)}\n        >\n          <div className=\"flex items-center justify-between gap-2\">\n            <div className=\"text-left flex-1 min-w-0\">\n              <CardTitle className=\"text-xl font-semibold\">{t('drOtherDoshas')}</CardTitle>\n              <CardDescription>\n                {hasOtherDoshas ? t('drOtherDoshasStatusActive') : t('drOtherDoshasStatusNone')}\n              </CardDescription>\n            </div>\n            <ChevronDown\n              className={`h-5 w-5 flex-shrink-0 text-muted-foreground transition-transform duration-200 ${isOtherExpanded ? 'rotate-180' : ''}`}\n            />\n          </div>\n        </CardHeader>\n        {isOtherExpanded && (\n          <CardContent>\n            <Accordion type=\"single\" collapsible className=\"w-full space-y-2\">\n              {OTHER_DOSHA_KEYS.map((o) => {\n                const status = (summary as Record<string, string>)[o.summaryKey];\n                const present = isPresent(status);\n                const detail = (detailsRecord as Record<string, { placements?: string[]; explanation?: string } | undefined>)[o.detailKey] ?? {};\n                const explanation = detail.explanation;\n                const placements = detail.placements;\n                return (\n                  <AccordionItem\n                    key={o.summaryKey}\n                    value={o.summaryKey}\n                    className=\"border border-border rounded-lg px-3\"\n                  >\n                    <AccordionTrigger value={o.summaryKey} className=\"hover:no-underline py-3\">\n                      <div className=\"flex items-center justify-between gap-2 flex-1 min-w-0 mr-2\">\n                        <div className=\"flex items-center gap-2\">\n                          <span className=\"font-semibold text-sm text-left leading-tight\">{t(o.labelKey)}</span>\n                          <Info size={14} className=\"text-muted-foreground flex-shrink-0\" />\n                        </div>\n                        {present ? (\n                          <Badge variant=\"destructive\" className=\"flex-shrink-0 text-xs flex items-center gap-1 pointer-events-none\">\n                            <AlertTriangle size={10} />\n                            {t('drStatusPresent')}\n                          </Badge>\n                        ) : (\n                          <Badge variant=\"secondary\" className=\"flex-shrink-0 text-xs flex items-center gap-1 bg-white border pointer-events-none\" style={{ borderColor: '#e4decd', color: '#000000' }}>\n                            <CheckCircle size={10} color=\"#000000\" />\n                            {t('drStatusAbsent')}\n                          </Badge>\n                        )}\n                      </div>\n                    </AccordionTrigger>\n                    <AccordionContent value={o.summaryKey} className=\"space-y-3 pt-0 pb-3\">\n                      {/* 1. What it is - Always shown */}\n                      <div className=\"border-l-4 border-orange-500 bg-orange-50 rounded-lg pl-3 py-2\">\n                        <p className=\"text-sm text-muted-foreground italic\">{t(o.descKey)}</p>\n                      </div>\n                      \n                      {/* 2. Planetary Positions - If placements exists */}\n                      {placements && placements.length > 0 && (\n                        <div className=\"p-3 bg-accent/10 rounded-md border border-accent/20\">\n                          <h5 className=\"font-medium mb-2 flex items-center gap-2 text-sm\">\n                            <Info size={14} />\n                            {t('drPlanetaryPositions')}\n                          </h5>\n                          <ul className=\"list-disc list-inside text-sm text-muted-foreground space-y-1 leading-relaxed\">\n                            {placements.map((p, i) => (\n                              <li key={i}>{p}</li>\n                            ))}\n                          </ul>\n                        </div>\n                      )}\n                      \n                      {/* 3. Explanation - If explanation exists */}\n                      {explanation && (\n                        <div className=\"border-l-4 border-orange-500 bg-orange-50 rounded-lg pl-3 py-2\">\n                          <h5 className=\"font-medium mb-2 text-sm flex items-center gap-2\">\n                            <Info size={14} />\n                            {present ? t('drWhyPresent') : t('drWhyAbsent')}\n                          </h5>\n                          <p className=\"text-sm text-muted-foreground leading-relaxed\">{explanation}</p>\n                        </div>\n                      )}\n                      \n                      {/* 4. Impact - Only if present */}\n                      {present && (\n                        <div className=\"border-l-4 border-red-500 bg-red-50 rounded-lg pl-3 py-2\">\n                          <h5 className=\"font-medium mb-2 text-sm flex items-center gap-2 text-red-600\">\n                            <AlertTriangle size={14} />\n                            {t('drImpact')}\n                          </h5>\n                          <p className=\"text-sm text-muted-foreground\">{t(o.impactKey)}</p>\n                        </div>\n                      )}\n                      \n                      {/* 5. Traditional Remedies - Only if present */}\n                      {present && (\n                        <div>\n                          <h5 className=\"font-medium mb-2 text-sm\">{t('drTraditionalRemedies')}</h5>\n                          <ul className=\"list-disc list-inside text-sm text-muted-foreground space-y-1\">\n                            {t(o.remediesKey).split('\\n').map((remedy, i) => (\n                              <li key={i}>{remedy}</li>\n                            ))}\n                          </ul>\n                        </div>\n                      )}\n                    </AccordionContent>\n                  </AccordionItem>\n                );\n              })}\n            </Accordion>\n          </CardContent>\n        )}\n      </Card>\n\n      {/* Kundali section: Go Back + Your Kundali (custom or built-in KundaliCard) + Planetary Positions Causing These Doshas */}\n      <div id={kundaliSectionId || 'kundali-chart-section'} className=\"px-4\">\n        {(renderKundali || showBuiltInKundali || allDoshaItems.length > 0) && (\n          <>\n            <div className=\"flex justify-end mb-2\">\n              <button\n                type=\"button\"\n                onClick={() => document.getElementById('dosha-results-heading')?.scrollIntoView({ behavior: 'smooth', block: 'start' })}\n                className=\"inline-flex items-center gap-1.5 text-sm text-primary hover:text-primary/80 transition-colors font-medium\"\n              >\n                <ArrowUp className=\"w-4 h-4\" />\n                {t('drGoBack')}\n              </button>\n            </div>\n            {renderKundali ? (\n              <div className=\"mt-2\">\n                <h2 className=\"text-xl font-semibold text-foreground mb-3\">{t('drYourKundali')}</h2>\n                {renderKundali()}\n              </div>\n            ) : showBuiltInKundali && birthDetails && supabase ? (\n              <div className=\"mt-2\">\n                <KundaliCard\n                  birthDetails={birthDetails}\n                  supabase={supabase}\n                  language={language}\n                  t={t}\n                />\n              </div>\n            ) : null}\n            {allDoshaItems.length > 0 && (\n              <Card className=\"mt-4 bg-accent/10 border border-accent/30\">\n                <CardHeader className=\"pb-2\">\n                  <CardTitle className=\"text-base font-semibold\">\n                    {t('drPlanetaryPositionsCausing')}\n                  </CardTitle>\n                </CardHeader>\n                <CardContent className=\"pt-0\">\n                  <ul className=\"space-y-3 text-sm text-muted-foreground\">\n                    {allDoshaItems.map((item, idx) => (\n                      <li key={idx}>\n                        <div className=\"font-semibold text-foreground mb-1\">{item.label}:</div>\n                        <ul className=\"ml-4 space-y-1\">\n                          {item.evidence.map((line, i) => (\n                            <li key={i} className=\"flex items-start gap-2\">\n                              <span className=\"text-primary flex-shrink-0\">→</span>\n                              <span>{line}</span>\n                            </li>\n                          ))}\n                        </ul>\n                      </li>\n                    ))}\n                  </ul>\n                </CardContent>\n              </Card>\n            )}\n          </>\n        )}\n      </div>\n\n      {/* Disclaimer */}\n      <p className=\"text-xs text-muted-foreground/70 text-center px-4\">{t('drDisclaimer')}</p>\n\n      {/* Reviews */}\n      <UserReviewsSection \n        t={t} \n        readMoreHref={readMoreReviewsHref}\n        onReadMore={\n          analytics?.trackReadMoreReviewsClicked\n            ? () => analytics.trackReadMoreReviewsClicked!()\n            : undefined\n        }\n      />\n\n      {/* FAQ */}\n      <FAQAccordion t={t} items={FAQ_ITEMS} defaultOpenIndex={0} />\n\n      {/* Contact */}\n      <ContactUsSection\n        title={t('contactTitle')}\n        brandName={t('contactBrandName')}\n        whatsAppLine={t('contactWhatsAppDomestic')}\n        emailLine={t('contactEmail')}\n      />\n    </div>\n  );\n}\n","/**\n * Google Maps API helpers for resolving places to coordinates and timezone.\n * Uses Geocoding API + Timezone API\n */\n\nimport type { ResolvedPlace } from '../types/dosha-api';\n\n/**\n * Create a resolvePlace function that uses Google Maps Geocoding and Timezone APIs.\n * \n * Required APIs to enable in Google Cloud Console:\n * - Places API (for autocomplete suggestions)\n * - Geocoding API (for coordinate lookup)  \n * - Time Zone API (for timezone lookup)\n * \n * @param apiKey - Your Google Maps API key\n * @returns A function that resolves place names to coordinates and timezone\n */\nexport function createGoogleMapsResolver(\n  apiKey: string\n): (place: string) => Promise<ResolvedPlace | null> {\n  if (!apiKey || apiKey.trim() === '') {\n    return async () => null;\n  }\n\n  return async (place: string): Promise<ResolvedPlace | null> => {\n    try {\n      if (!place?.trim()) {\n        return null;\n      }\n\n      // Step 1: Geocode the place to get lat/lon\n      const geocodeUrl = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(place)}&key=${apiKey}`;\n      const geocodeResponse = await fetch(geocodeUrl);\n      const geocodeData = await geocodeResponse.json();\n\n      if (geocodeData.status !== 'OK') {\n        return null;\n      }\n\n      if (!geocodeData.results?.[0]) {\n        return null;\n      }\n\n      const { lat, lng } = geocodeData.results[0].geometry.location;\n\n      // Step 2: Get timezone for the coordinates\n      const timestamp = Math.floor(Date.now() / 1000);\n      const timezoneUrl = `https://maps.googleapis.com/maps/api/timezone/json?location=${lat},${lng}&timestamp=${timestamp}&key=${apiKey}`;\n      const timezoneResponse = await fetch(timezoneUrl);\n      const timezoneData = await timezoneResponse.json();\n\n      if (timezoneData.status !== 'OK') {\n        return null;\n      }\n\n      const tz = timezoneData.timeZoneId;\n      const tzoneOffset = (timezoneData.rawOffset + timezoneData.dstOffset) / 3600;\n\n      const result = {\n        lat,\n        lon: lng,\n        tz,\n        tzoneOffset,\n      };\n\n      return result;\n    } catch (error) {\n      return null;\n    }\n  };\n}\n"],"names":["f","require$$0","k","l","m","p","q","c","a","g","b","d","e","h","reactJsxRuntime_production_min","React","REACT_ELEMENT_TYPE","REACT_PORTAL_TYPE","REACT_FRAGMENT_TYPE","REACT_STRICT_MODE_TYPE","REACT_PROFILER_TYPE","REACT_PROVIDER_TYPE","REACT_CONTEXT_TYPE","REACT_FORWARD_REF_TYPE","REACT_SUSPENSE_TYPE","REACT_SUSPENSE_LIST_TYPE","REACT_MEMO_TYPE","REACT_LAZY_TYPE","REACT_OFFSCREEN_TYPE","MAYBE_ITERATOR_SYMBOL","FAUX_ITERATOR_SYMBOL","getIteratorFn","maybeIterable","maybeIterator","ReactSharedInternals","error","format","_len2","args","_key2","printWarning","level","ReactDebugCurrentFrame","stack","argsWithFormat","item","enableScopeAPI","enableCacheElement","enableTransitionTracing","enableLegacyHidden","enableDebugTracing","REACT_MODULE_REFERENCE","isValidElementType","type","getWrappedName","outerType","innerType","wrapperName","displayName","functionName","getContextName","getComponentNameFromType","context","provider","outerName","lazyComponent","payload","init","assign","disabledDepth","prevLog","prevInfo","prevWarn","prevError","prevGroup","prevGroupCollapsed","prevGroupEnd","disabledLog","disableLogs","props","reenableLogs","ReactCurrentDispatcher","prefix","describeBuiltInComponentFrame","name","source","ownerFn","x","match","reentry","componentFrameCache","PossiblyWeakMap","describeNativeComponentFrame","fn","construct","frame","control","previousPrepareStackTrace","previousDispatcher","Fake","sample","sampleLines","controlLines","s","_frame","syntheticFrame","describeFunctionComponentFrame","shouldConstruct","Component","prototype","describeUnknownElementTypeFrameInDEV","hasOwnProperty","loggedTypeFailures","setCurrentlyValidatingElement","element","owner","checkPropTypes","typeSpecs","values","location","componentName","has","typeSpecName","error$1","err","ex","isArrayImpl","isArray","typeName","value","hasToStringTag","willCoercionThrow","testStringCoercion","checkKeyStringCoercion","ReactCurrentOwner","RESERVED_PROPS","specialPropKeyWarningShown","specialPropRefWarningShown","hasValidRef","config","getter","hasValidKey","warnIfStringRefCannotBeAutoConverted","self","defineKeyPropWarningGetter","warnAboutAccessingKey","defineRefPropWarningGetter","warnAboutAccessingRef","ReactElement","key","ref","jsxDEV","maybeKey","propName","defaultProps","ReactCurrentOwner$1","ReactDebugCurrentFrame$1","setCurrentlyValidatingElement$1","propTypesMisspellWarningShown","isValidElement","object","getDeclarationErrorAddendum","getSourceInfoErrorAddendum","ownerHasKeyUseWarning","getCurrentComponentErrorInfo","parentType","info","parentName","validateExplicitKey","currentComponentErrorInfo","childOwner","validateChildKeys","node","i","child","iteratorFn","iterator","step","validatePropTypes","propTypes","_name","validateFragmentProps","fragment","keys","didWarnAboutKeySpread","jsxWithValidation","isStaticChildren","validType","sourceInfo","typeString","children","beforeExample","afterExample","jsxWithValidationStatic","jsxWithValidationDynamic","jsx","jsxs","reactJsxRuntime_development","jsxRuntimeModule","require$$1","FLOATING_CTA_STATUS","EXTRACTOR_KEY","getTraceContextExtractor","__rest","t","__awaiter","thisArg","_arguments","P","generator","adopt","resolve","reject","fulfilled","rejected","result","resolveFetch","customFetch","FunctionsError","message","FunctionsFetchError","FunctionsRelayError","FunctionsHttpError","FunctionRegion","FunctionsClient","url","headers","region","token","functionName_1","options","_a","_b","timeoutId","timeoutController","onAbort","method","functionArgs","signal","timeout","_headers","body","hasContentTypeHeader","effectiveSignal","response","fetchError","isRelayError","responseType","data","PostgrestError","DEFAULT_MAX_RETRIES","getRetryDelay","attemptIndex","RETRYABLE_STATUS_CODES","RETRYABLE_METHODS","_typeof","o","o$1","toPrimitive","r","toPropertyKey","_defineProperty","ownKeys","r$1","_objectSpread2","sleep","ms","id","shouldRetry","status","attemptCount","retryEnabled","fetchWithRetry","fetchImpl","request","res","delay","_res$headers$get","_res$headers","retryAfterHeader","PostgrestBuilder","builder","_builder$shouldThrowO","_builder$isMaybeSingl","_builder$shouldStripN","_builder$urlLengthLim","_builder$retry","enabled","onfulfilled","onrejected","_this","currentAccept","_fetch","res$1","_","_fetchError$name2","errorDetails","hint","code","cause","_cause$message","_cause$code","_fetchError$name","_cause$name","causeMessage","causeCode","_fetchError$stack","urlLength","_this2","count","statusText","_this$headers$get2","_this$headers$get","countHeader","contentRange","_error$hint","PostgrestTransformBuilder","columns","quoted","cleanedColumns","column","ascending","nullsFirst","foreignTable","referencedTable","existingOrder","rows","from","to","keyOffset","keyLimit","analyze","verbose","settings","buffers","wal","forMediatype","PostgrestReservedCharsRegexp","PostgrestFilterBuilder","pattern","patterns","cleanedValues","range","query","typePart","configPart","operator","filters","PostgrestQueryBuilder","schema","fetch$1","urlLengthLimit","retry","head","defaultToNull","_this$fetch","acc","uniqueColumns","onConflict","ignoreDuplicates","_this$fetch2","_this$fetch3","_this$fetch4","toOpenApiError","parsed","_parsed$message","_parsed$details","_parsed$hint","_parsed$code","toTransportFailure","_err$name","PostgrestClient","originalFetch","input","controller","existingSignal","abortHandler","relation","requestHeaders","_this$retry","readError","get","_isObject","v","_hasObjectArg","WebSocketFactory","gt","gl","_process","processVersions","env","errorMessage","DEFAULT_VERSION","VSN_1_0_0","VSN_2_0_0","DEFAULT_VSN","DEFAULT_TIMEOUT","DEFAULT_POSTGRES_CHANGES_WAIT_TIMEOUT","POSTGRES_CHANGES_WAIT_ERROR_GRACE","MAX_PUSH_BUFFER_SIZE","CHANNEL_STATES","CHANNEL_EVENTS","CONNECTION_STATE","Serializer","allowedMetadataKeys","msg","callback","userPayload","encodedUserPayload","encodingType","encodedPayload","encoder","topic","joinRef","userEvent","rest","metadata","metaLength","header","view","bytes","offset","combined","rawPayload","jsonPayload","join_ref","event","buffer","kind","decoder","topicSize","userEventSize","metadataSize","payloadEncoding","parsedPayload","obj","PostgresTypes","convertChangeData","record","skipTypes","rec_key","convertColumn","columnName","colType","convertCell","noop","dataType","toArray","toBoolean","toNumber","toJson","toTimestampString","parsedValue","lastIdx","closeBrace","arr","valTrim","val","httpEndpointURL","socketUrl","wsUrl","closure","globalSelf","phxWindow","global","WS_CLOSE_NORMAL","MAX_LONGPOLL_BATCH_SIZE","SOCKET_STATES","TRANSPORTS","XHR_STATES","AUTH_TOKEN_PREFIX","Push","channel","_ref","Timer","timerCalc","Channel","params","socket","pushEvent","reason","push","bind","onClose","leavePush","_event","_binding","_payload","handledPayload","eventBindings","Ajax","endPoint","ontimeout","req","resp","parentKey","queryStr","paramKey","paramVal","arrayBufferToBase64","binary","len","LongPoll","protocols","wasClean","messages","next","batch","opts","onCallerTimeout","Presence","_Presence","events","newState","onJoin","onLeave","onSync","diff","by","currentState","state","joins","leaves","presence","newPresence","currentPresence","newRefs","curRefs","joinedMetas","leftMetas","joinedRefs","curMetas","leftPresence","refsToRemove","presences","chooser","pres","func","cleaned","serializer_default","joinRefBytes","refBytes","topicBytes","eventBytes","headerBytes","size","joinRefSize","eventSize","refSize","Socket","envSessionStorage","awaitingConnectionOnPageShow","_e","tries","newTransport","uri","startTime","onMsgRef","transport","fallbackTransport","fallbackThreshold","established","primaryTransport","openRef","errorRef","fallbackTransportName","fallback","fallbackTransportName2","rtt","connToClose","conn","transportBefore","establishedBefore","refs","chanParams","chan","newRef","rawMessage","latency","dupChannel","PresenceAdapter","phoenixOptions","phoenixPresenceOptions","onJoinPayload","onLeavePayload","cloneState","transformState","currentPresences","parseCurrentPresences","newPresences","leftPresences","descriptors","transformedPresence","REALTIME_PRESENCE_LISTEN_EVENTS","RealtimePresence","normalizeChannelError","detail","ChannelAdapter","phoenixParams","phoenixChannelParams","refNumber","removedPush","oldPayload","filterBindings","needsQuoting","quote","serializeScalar","serialized","serializeIsValue","serialize","RealtimePostgresFilterBuilder","negate","REALTIME_POSTGRES_CHANGES_LISTEN_EVENT","REALTIME_LISTEN_TYPES","REALTIME_SUBSCRIBE_STATES","RealtimeChannel","_c","_d","broadcast","isPrivate","postgres_changes_options","postgres_changes","presence_enabled","accessTokenPayload","joinTimeout","clientPostgresBindings","bindingsLen","newPostgresBindings","clientPostgresBinding","table","filter","serverPostgresFilter","stateCheck","typeCheck","isBinary","errorBody","fallbackWarning","endpoint_payload","typeLower","filterValue","binding","_f","_g","bindId","bindEvent","close","leave","join","postgresChanges","commit_timestamp","errors","other","serverValue","clientValue","selectA","selectB","records","Transformers.convertChangeData","SocketAdapter","CONNECTION_TIMEOUTS","RECONNECT_INTERVALS","DEFAULT_RECONNECT_FALLBACK","createMemorySessionStorage","store","index","resolveSessionStorage","WORKER_SCRIPT","RealtimeClient","socketAdapterOptions","promises","realtimeTopic","exists","authGeneration","authPromise","tokenToSend","isManualToken","heartbeatCallback","objectUrl","result_url","blob","_h","_j","_k","_l","_m","defaultEncode","defaultDecode","vsn","IcebergError","buildUrl","baseUrl","path","buildAuthHeaders","auth","createFetchClient","fetchFn","authHeaders","text","isJson","errBody","errorDetail","namespaceToPath","namespace","NamespaceOperations","client","parent","ns","namespaceToPath2","TableOperations","accessDelegation","IcebergRestCatalog","StorageError","statusCode","isStorageError","StorageApiError","StorageUnknownError","originalError","setHeader","nameLower","normalizeHeaders","isPlainObject","recursiveToCamel","el","newKey","isValidBucketName","bucketName","encodeStoragePath","_getErrorMessage","nested","handleError","responseError","_getRequestParams","parameters","_contentType","contentType","_handleRequest","fetcher","createFetchApi","defaultApi","post","put","remove","vectorsApi","BaseApiClient","operation","_Symbol$toStringTag$1","StreamDownloadBuilder","downloadFn","shouldThrowOnError","onfinally","_Symbol$toStringTag","BlobDownloadBuilder","DEFAULT_SEARCH_OPTIONS","DEFAULT_FILE_OPTIONS","StorageFileApi","bucketId","fileBody","fileOptions","cleanPath","_path","_this3","_this4","fromPath","toPath","_this6","_this7","expiresIn","_this8","hasTransform","queryString","paths","_this9","datum","renderPath","_this10","_this11","_error$originalError","_this12","_this13","_this14","sortBy","_this15","transform","DEFAULT_HEADERS","StorageBucketApi","finalUrl","finalHeaders","_this5","configuration","StorageAnalyticsClient","queryParams","catalog","target","prop","VectorIndexApi","vectorBucketName","indexName","VectorDataApi","VectorBucketApi","StorageVectorsClient","VectorBucketScope","_superprop_getCreateBucket","_superprop_getGetBucket","_superprop_getListBuckets","_superprop_getDeleteBucket","_superprop_getCreateIndex","_superprop_getListIndexes","_superprop_getGetIndex","_superprop_getDeleteIndex","VectorIndexScope","_superprop_getPutVectors","_superprop_getGetVectors","_superprop_getListVectors","_superprop_getQueryVectors","_superprop_getDeleteVectors","StorageClient","version","AUTO_REFRESH_TICK_DURATION_MS","AUTO_REFRESH_TICK_THRESHOLD","EXPIRY_MARGIN_MS","REFRESH_FAILURE_COOLDOWN_MS","GOTRUE_URL","STORAGE_KEY","API_VERSION_HEADER_NAME","API_VERSIONS","BASE64URL_REGEX","PKCE_FLOW_ID_PARAM","PKCE_MAX_CONCURRENT_FLOWS","JWKS_TTL","AuthError","isAuthError","AuthApiError","isAuthApiError","AuthUnknownError","CustomAuthError","AuthSessionMissingError","isAuthSessionMissingError","AuthInvalidTokenResponseError","AuthInvalidCredentialsError","AuthImplicitGrantRedirectError","details","isAuthImplicitGrantRedirectError","AuthPKCEGrantCodeExchangeError","AuthPKCECodeVerifierMissingError","AuthRetryableFetchError","isAuthRetryableFetchError","AuthRefreshDiscardedError","isAuthRefreshDiscardedError","AuthWeakPasswordError","reasons","AuthInvalidJwtError","TO_BASE64URL","IGNORE_BASE64URL","FROM_BASE64URL","charMap","byteToBase64URL","byte","emit","pos","byteFromBase64URL","charCode","bits","stringFromBase64URL","str","conv","utf8Emit","codepoint","utf8State","b64State","byteEmit","stringFromUTF8","codepointToUTF8","stringToUTF8","highSurrogate","leadingBit","base64UrlToUint8Array","onByte","stringToUint8Array","bytesToBase64URL","onChar","char","expiresAt","generateCallbackId","isBrowser","localStorageWriteTests","supportsLocalStorage","randomKey","parseParametersFromURL","href","looksLikeFetchResponse","maybeResponse","setItemAsync","storage","getItemAsync","removeItemAsync","Deferred","rej","decodeJWT","parts","time","accept","retryable","isRetryable","attempt","dec2hex","dec","generatePKCEVerifier","array","charSet","charSetLen","verifier","sha256","randomString","encodedData","hash","generatePKCEChallenge","hashed","PKCE_FLOW_ID_PATTERN","validatePKCEFlowId","flowId","generatePKCEFlowId","pkceVerifierSlotKey","storageKey","pkceFlowIndexKey","getPKCEFlowIndex","storePKCEVerifier","onEvictFlow","evicted","retrievePKCEVerifier","removePKCEVerifier","legacyKey","slotKey","slotValue","remaining","removeAllPKCEVerifiers","appendFlowIdToRedirectTo","redirectTo","hashIndex","base","queryIndex","pair","separator","getCodeChallengeAndMethod","isPasswordRecovery","codeVerifier","storedCodeVerifier","codeChallenge","API_VERSION_REGEX","parseResponseAPIVersion","apiVersion","validateExp","exp","timeNow","getAlgorithm","alg","UUID_REGEX","validateUUID","assertPasskeyExperimentalEnabled","experimental","assertRecoveryCodesExperimentalEnabled","userNotAvailableProxy","proxyTarget","sProp","_target","insecureUserWarningProxy","user","suppressWarningRef","receiver","deepClone","NETWORK_ERROR_CODES","errorCode","responseAPIVersion","_request","qs","requestParams","_sessionResponse","session","hasSession","_sessionResponsePassword","_userResponse","_ssoResponse","_generateLinkResponse","action_link","email_otp","hashed_token","redirect_to","verification_type","properties","_noResolveJsonResponse","SIGN_OUT_SCOPES","GoTrueAdminApi","fetch","jwt","scope","email","attributes","pagination","users","total","links","link","page","rel","uid","shouldSoftDelete","factors","clients","clientId","identifier","memoryLocalStorageAdapter","LockAcquireTimeoutError","polyfillGlobalThis","getAddress","address","fromHex","hex","toHex","createSiweMessage","chainId","domain","expirationTime","issuedAt","nonce","notBefore","requestId","resources","scheme","origin","statement","suffix","content","resource","WebAuthnError","WebAuthnUnknownError","identifyRegistrationError","publicKey","param","effectiveDomain","isValidDomain","identifyAuthenticationError","WebAuthnAbortService","abortError","newController","webAuthnAbortService","deserializeCredentialCreationOptions","challengeStr","userOpts","excludeCredentials","restOptions","challenge","cred","deserializeCredentialRequestOptions","allowCredentials","serializeCredentialCreationResponse","credential","credentialWithAttachment","serializeCredentialRequestResponse","clientExtensionResults","assertionResponse","hostname","browserSupportsWebAuthn","createCredential","getCredential","DEFAULT_CREATION_OPTIONS","DEFAULT_REQUEST_OPTIONS","deepMerge","sources","isObject","isArrayBufferLike","existing","mergeCredentialCreationOptions","baseOptions","overrides","mergeCredentialRequestOptions","WebAuthnApi","factorId","webauthn","friendlyName","challengeResponse","challengeError","abortSignal","nameToUse","userData","fallbackName","challengeId","rpId","rpOrigins","factor","enrollError","DEFAULT_OPTIONS","GLOBAL_JWKS","deprecatedLockWarned","GoTrueClient","queue","callbackUrlType","redirectType","credentials","password","codeChallengeMethod","phone","invalidTokenError","authCode","chain","signature","wallet","resolvedWallet","windowAny","accounts","accs","chainIdHex","siweMessage","_o","output","outputToProcess","maybeSignature","hasExplicitFlowId","requestedFlowId","storageItem","access_token","captchaToken","sessionError","endpoint","acquireTimeout","last","waitOn","currentSession","maybeSession","hasExpired","maybeUser","stillStored","sessionData","userError","refreshedSession","provider_token","provider_refresh_token","refresh_token","expires_in","expires_at","token_type","actuallyExpiresIn","removeCurrentSession","accessToken","subscription","urlFlowId","identity","refreshToken","debugName","startedAt","nextBackOffInterval","separateUser","expiresWithMargin","getUserError","storedAtStart","storedAfter","discarded","epochBeforeSave","storedNow","sessionToProcess","userIsProxy","mainSessionData","clonedMainSessionData","clonedSession","ticker","now","expiresInTicks","calledFromInitialize","methodName","urlParams","flowParams","evictedFlowId","run","challengeData","currentLevel","nextLevel","currentAuthenticationMethods","authorizationId","kid","jwks","jwk","rawHeader","signingKey","algorithm","optionsError","publicKeyOptions","credentialError","AuthClient","JS_ENV","JS_RUNTIME_VERSION","_Deno$version","_process$version","_runtimeMeta","DEFAULT_GLOBAL_OPTIONS","DEFAULT_DB_OPTIONS","DEFAULT_AUTH_OPTIONS","DEFAULT_REALTIME_OPTIONS","DEFAULT_TRACE_PROPAGATION_OPTIONS","parseTraceParent","traceparent","version$1","traceId","parentId","traceFlags","hexRegex","shouldPropagateToTarget","targetUrl","targets","matchStringTarget","getDefaultPropagationTargets","supabaseUrl","resolveHeadersConstructor","isNewApiKey","TEMP_KEY_PREFIX","warnedKeySubtypes","checkApiKeyFormat","_key$match$","_key$match","subtype","fetchWithAuth","supabaseKey","getAccessToken","tracePropagationOptions","HeadersConstructor","traceEnabled","respectSampling","traceTargets","allowKeyAsBearer","realToken","bearer","traceHeaders","getTraceHeaders","warnedMissingTracingRuntime","warnedNonW3CPropagator","extractTraceContext","traceContext","_traceContext$carrier","sentryHint","normalizeTracePropagation","ensureTrailingSlash","warnedTopLevelSchema","checkTopLevelSchemaOption","applySettingDefaults","defaults","_DEFAULT_GLOBAL_OPTIO","_globalOptions$header","_tracePropagationOpti","_ref2","_tracePropagationOpti2","dbOptions","authOptions","realtimeOptions","globalOptions","DEFAULT_DB_OPTIONS$1","DEFAULT_AUTH_OPTIONS$1","DEFAULT_REALTIME_OPTIONS$1","DEFAULT_GLOBAL_OPTIONS$1","DEFAULT_TRACE_PROPAGATION_OPTIONS$1","validateSupabaseUrl","trimmedUrl","SupabaseAuthClient","SupabaseClient","_settings$auth$storag","_settings$global$head","defaultStorageKey","DEFAULTS","_settings$auth","_data$session$access_","_data$session","_await$this$_getSessi","autoRefreshToken","persistSession","detectSessionInUrl","userStorage","flowType","lock","debug","throwOnError","lockAcquireTimeout","skipAutoInitialize","createClient","shouldShowDeprecationWarning","processVersion","versionMatch","createSupabaseClient","supabaseAnonKey","splitCSVLine","line","current","inQuotes","getField","row","normalize","map","parsePujasCSV","csvText","lines","pujas","storeId","poojaTitle","coverHindi","coverEnglish","DOSHA_KEYWORDS","parseIndianDate","dateStr","day","month","year","getPujaForDosha","doshaType","keywords","filtered","puja","title","englishTitle","keyword","today","date","cachedPujas","cacheTime","CACHE_MS","fetchPujas","supabase","HINDI_TO_ENGLISH_TITLES","HINDI_WORD_TRANSLATIONS","HINDI_TO_ENGLISH_TEMPLES","fallbackTranslation","hindiText","hindi","english","regex","getPujaTitle","language","isHindi","originalTitle","getTempleName","originalName","englishName","formatScheduleDate","locale","appendUTMToUrl","utm_source","utm_medium","utm_content","getPujaLink","baseLink","getCoverImageUrl","SUPPORTED_LOCALES","LOCALE_LABELS","translations","I18nContext","createContext","getLocaleFromUrl","updateUrl","newLocale","pathname","search","segments","I18nProvider","onLocaleChange","currentLocale","setCurrentLocale","useState","useEffect","handlePop","handleSetLocale","useMemo","useI18n","useContext","FooterTrustBadge","styles","sizeProps","AlertTriangle","CheckCircle","Info","Flame","Waves","Users","Moon","ArrowUp","ChevronDown","Loader2","className","ExternalLink","RotateCcw","DefaultDoshaImage","priority","fetchPriority","width","height","imgProps","ICON_CHEVRON_RIGHT","DoshaFooterCTA","isFormComplete","onPress","labelDefault","labelFilled","isLoading","mode","firstPuja","showingResults","bookPujaLabel","loadingLabel","FooterCTAButton","DoshaBanner","bannerConfig","imageComponent","Img","FOOTER_HEIGHT_PX","SectionWithImpression","section","onImpression","useRef","reported","observer","entry","ICON_DATE","formatDateDisplay","DoshaDateField","onChange","onOpen","inputRef","maxDate","pad","n","openPicker","max","ICON_TIME","pad2","to12HourDisplay","hhmm","hour24","minute","meridiem","from24ToDraft","draftTo24","draft","hour12","DoshaTimeField","placeholder","disabled","timeWrapRef","timeOpen","setTimeOpen","timeDraft","setTimeDraft","onDocMouseDown","handleOpen","handleOk","insertSessionProblemStatements","visitorId","sessionId","problemStatements","invokeCalculateDosha","submitDoshaCalculation","trackProblemStatements","googleMapsPromise","loadGoogleMapsScript","apiKey","start","checkReady","script","check","useGooglePlacesAutocomplete","restrictCountry","isLoaded","setIsLoaded","predictions","setPredictions","isSearching","setIsSearching","loadError","setLoadError","autocompleteService","placesService","sessionToken","div","searchPlaces","useCallback","preds","getPlaceDetails","placeId","place","lat","lng","city","country","component","clearPredictions","PROBLEM_KEYS","getVisitorId","getSessionId","calculateAgeFromDate","dateString","birthDate","age","monthDiff","DoshaFormSection","forwardRef","initialValues","onValuesChange","onFormValidityChange","resolvePlace","onResult","onError","onLoadingChange","analytics","googleMapsApiKey","sanitizePlaceInput","setName","gender","setGender","problems","setProblems","dateOfBirth","setDateOfBirth","birthTime","setBirthTime","birthTimeUnknown","setBirthTimeUnknown","birthPlace","setBirthPlace","otherProblemText","setOtherProblemText","placeCoordinates","setPlaceCoordinates","placeOpen","setPlaceOpen","submitError","setSubmitError","fieldErrors","setFieldErrors","focusField","field","focusById","firstGenderOption","formFillInitiatedRef","nameFilledRef","dobFilledRef","timeFilledRef","placeFilledRef","placeWrapRef","placeSuggestions","placeLoading","placeLoadError","handleFirstInteraction","handle","isFormValid","fetchTimezone","lon","timestamp","submit","reportError","showBottomAlert","prev","sanitizedPlace","restrictedProblems","hasRestrictedProblem","problem","tz","resolved","y","timeStr","hr","min","useImperativeHandle","problemOptions","FormContainer","PrivacyBanner","FormSectionHeader","FormField","FormTextInput","FormSegmentedControl","FormTagPills","nextProblems","FormCheckboxWithHelp","FormLocationInput","FormFooterNote","Skeleton","Card","CardHeader","CardTitle","CardDescription","CardContent","Button","variant","sizeClasses","variantClasses","SriMandirPujaVerticalCard","onBookClick","displayTitle","displayTempleName","formattedDate","pujaLink","coverImageUrl","handleBookClick","WhatFromAnalysis","bannerType","itemKeys","titleKey","descKey","BANNER_IMAGES","UTM_TERM_TO_BANNER","getBannerConfig","utmTerm","getQueryParam","getUtmTerm","DoshaResultsFull","lazy","DoshaResultsFull$1","module","DEFAULT_LOGO_URL","ICON_KUNDLI_CREATED","ICON_CERTIFIED","ICON_SECURE_PAYMENT","ICON_GLOBE","getPujaDoshaTypeCandidates","candidates","isActiveDoshaStatus","normalized","getSeverityScore","severity","appendCurrentQueryParams","urlString","currentParams","getFirstActiveDoshaType","summary","doshas","TrustBadgesRow","footerShellStyles","FAQ_ITEMS","FAQ_ITEMS_MARRIAGE","DoshaCalculator","logoUrl","languageSelector","showLanguageSelector","isGlobal","readMoreReviewsHref","supabaseProp","resolvePlaceProp","renderPujaCard","isLoadingPujas","renderKundali","kundaliSectionId","getFirstPujaInfo","onBookPujaClick","i18n","setLocale","formSectionRef","formSubmitRef","setIsFormComplete","setIsLoading","setResult","birthDetails","setBirthDetails","savedFormValues","setSavedFormValues","isEditing","setIsEditing","fallbackPujas","setFallbackPujas","isLoadingFallbackPujas","setIsLoadingFallbackPujas","firstPujaInfo","setFirstPujaInfo","webViewTrackedRef","needsInternalPujaFallback","isMounted","fallbackRenderPujaCard","fallbackGetFirstPujaInfo","pujaCardRenderer","firstPujaInfoResolver","resolvedIsLoadingPujas","setBannerConfig","setBannerType","showWhatYouGetFirst","setShowWhatYouGetFirst","scrollToForm","handleSectionImpression","handleResult","firstDoshaType","pujaInfo","handleEditForm","handleCtaPress","linkWithQueryParams","resolvedLanguageSelector","PageHeader","MarqueeStrip","Suspense","translatedProblems","otherText","Fragment","UserReviewsSection","marriageKey","FAQAccordion","questionText","ContactUsSection","FooterShell","DOSHA_KEYS","isPresent","getDetail","detailKey","raw","remedies","translateStatus","DoshaResultsView","onEdit","shaniSadeSati","hasAnyDosha","labelKey","summaryKey","present","explanation","Badge","AccordionContext","Accordion","collapsible","onValueChange","setValue","onToggle","AccordionItem","AccordionTrigger","ctx","isOpen","AccordionContent","svgCache","CACHE_TTL","getCacheKey","chartType","getFromCache","memEntry","stored","setCache","svg","makeResponsiveSvg","svgString","doc","fetchKundaliSvg","cacheKey","cached","responsiveSvg","KundaliCard","setChartType","setStatus","setSvgString","errorMsg","setErrorMsg","abortControllerRef","cardRef","lang","fetchChart","handleChartTypeChange","handleRetry","DOSHA_CONFIG","isNullified","placements","mapSeverityToLabel","looksEnglishOnlyText","feedbackEmail","inlineEditForm","problemArea","problemAreaIds","customProblemText","personalizedImpacts","setPersonalizedImpacts","isLoadingImpacts","setIsLoadingImpacts","showBuiltInKundali","impacts","activeTypes","problemIdMap","mappedProblemAreaIds","relevantProblemId","OTHER_DOSHA_KEYS","hasOtherDoshas","activeDoshas","cfg","phase","rawExplanation","benefits","isOtherExpanded","setIsOtherExpanded","positionHintRegex","detailsRecord","allDoshaItems","dosha","rawEvidence","uniqueEvidence","evidence","finalEvidence","label","getPhaseExplanation","sectionColors","DoshaIcon","phaseExplanation","sectionColor","doshaOfLabel","doshaTypeCandidates","card","benefit","accordionKey","Icon","remediesList","remedy","idx","createGoogleMapsResolver","geocodeUrl","geocodeData","timezoneUrl","timezoneData","tzoneOffset"],"mappings":"qsBASa,IAAIA,EAAEC,EAAiBC,EAAE,OAAO,IAAI,eAAe,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U,OACV,MAAO,QACP,UAAW,aACX,WAAY,sBACZ,cAAe,yDACf,cACE,8DACF,eAAgB,MAChB,qBACE,kPACF,qBACE,wOACF,qBACE,+MACF,qBACE,qKACF,qBACE,+FACF,qBACE,gLACF,qBACE,gKACF,qBACE,sMACF,qBACE,2JACF,sBACE,8LACF,sBACE,iKACF,sBACE,kKACF,sBACE,mFACF,sBACE,oLACF,sBACE,2JACF,gBAAiB,gBACjB,gBAAiB,aACjB,gBAAiB,YACjB,gBAAiB,gBACjB,gBAAiB,aACjB,gBAAiB,YACjB,gBAAiB,YACjB,gBAAiB,eACjB,gBAAiB,cACjB,iBAAkB,cAClB,iBAAkB,cAClB,iBAAkB,eAClB,iBAAkB,cAClB,iBAAkB,cAClB,iBAAkB,gBAClB,yBAA0B,gDAC1B,yBAA0B,gDAC1B,yBAA0B,gDAC1B,yBAA0B,gDAC1B,yBAA0B,gDAC1B,yBAA0B,gDAC1B,yBAA0B,gDAC1B,yBAA0B,gDAC1B,yBAA0B,gDAC1B,0BAA2B,gDAC3B,0BAA2B,gDAC3B,0BAA2B,gDAC3B,0BAA2B,gDAC3B,0BAA2B,gDAC3B,0BAA2B,gDAC3B,gBAAiB,qBACjB,SAAU,WAEV,sBACE,0DACF,6BACE,uPACF,6BACE,6QACF,6BACE,gQACF,6BACE,yGACF,6BACE,oNACF,6BACE,6MACF,6BACE,mHACF,6BACE,uPACF,6BACE,yMACF,8BACE,wHACF,8BACE,gNACF,8BACE,4LACF,8BACE,wGACF,8BACE,6NACF,8BACE,gLACF,SAAU,8BACV,MAAO,+BACP,MACE,uIACF,MAAO,oCACP,MACE,qLACF,MAAO,iCACP,MACE,2KAEF,cAAe,+BACf,cACE,uIACF,cAAe,oCACf,cACE,qLACF,cAAe,iCACf,cACE,2KACF,cAAe,2CACf,cACE,8NAEF,kBAAmB,4BACnB,UAAW,uBACX,aAAc,gDACd,cAAe,qBACf,oBAAqB,WACrB,gBAAiB,YACjB,eAAgB,QAChB,iBAAkB,QACl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