@srimandir/dosha-calculator 7.4.2 → 7.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,62 +1,47 @@
1
- (function(G,v){typeof exports=="object"&&typeof module<"u"?v(exports,require("react"),require("@srimandir/astrology-common")):typeof define=="function"&&define.amd?define(["exports","react","@srimandir/astrology-common"],v):(G=typeof globalThis<"u"?globalThis:G||self,v(G.DoshaCalculator={},G.React,G.AstrologyCommon))})(this,(function(G,v,q){"use strict";function ca(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,s.get?s:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const Ne=ca(v);var cr={exports:{}},Bt={};var gs;function ua(){if(gs)return Bt;gs=1;var t=v,e=Symbol.for("react.element"),r=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,n=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,a={key:!0,ref:!0,__self:!0,__source:!0};function i(o,l,u){var d,h={},m=null,p=null;u!==void 0&&(m=""+u),l.key!==void 0&&(m=""+l.key),l.ref!==void 0&&(p=l.ref);for(d in l)s.call(l,d)&&!a.hasOwnProperty(d)&&(h[d]=l[d]);if(o&&o.defaultProps)for(d in l=o.defaultProps,l)h[d]===void 0&&(h[d]=l[d]);return{$$typeof:e,type:o,key:m,ref:p,props:h,_owner:n.current}}return Bt.Fragment=r,Bt.jsx=i,Bt.jsxs=i,Bt}var Kt={};var ys;function da(){return ys||(ys=1,process.env.NODE_ENV!=="production"&&(function(){var t=v,e=Symbol.for("react.element"),r=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),i=Symbol.for("react.provider"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),p=Symbol.for("react.offscreen"),g=Symbol.iterator,b="@@iterator";function A(f){if(f===null||typeof f!="object")return null;var _=g&&f[g]||f[b];return typeof _=="function"?_:null}var w=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function S(f){{for(var _=arguments.length,T=new Array(_>1?_-1:0),D=1;D<_;D++)T[D-1]=arguments[D];k("error",f,T)}}function k(f,_,T){{var D=w.ReactDebugCurrentFrame,Y=D.getStackAddendum();Y!==""&&(_+="%s",T=T.concat([Y]));var X=T.map(function(H){return String(H)});X.unshift("Warning: "+_),Function.prototype.apply.call(console[f],console,X)}}var N=!1,R=!1,B=!1,P=!1,U=!1,$;$=Symbol.for("react.module.reference");function De(f){return!!(typeof f=="string"||typeof f=="function"||f===s||f===a||U||f===n||f===u||f===d||P||f===p||N||R||B||typeof f=="object"&&f!==null&&(f.$$typeof===m||f.$$typeof===h||f.$$typeof===i||f.$$typeof===o||f.$$typeof===l||f.$$typeof===$||f.getModuleId!==void 0))}function ge(f,_,T){var D=f.displayName;if(D)return D;var Y=_.displayName||_.name||"";return Y!==""?T+"("+Y+")":T}function Re(f){return f.displayName||"Context"}function ee(f){if(f==null)return null;if(typeof f.tag=="number"&&S("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof f=="function")return f.displayName||f.name||null;if(typeof f=="string")return f;switch(f){case s:return"Fragment";case r:return"Portal";case a:return"Profiler";case n:return"StrictMode";case u:return"Suspense";case d:return"SuspenseList"}if(typeof f=="object")switch(f.$$typeof){case o:var _=f;return Re(_)+".Consumer";case i:var T=f;return Re(T._context)+".Provider";case l:return ge(f,f.render,"ForwardRef");case h:var D=f.displayName||null;return D!==null?D:ee(f.type)||"Memo";case m:{var Y=f,X=Y._payload,H=Y._init;try{return ee(H(X))}catch{return null}}}return null}var te=Object.assign,he=0,Ze,Oe,re,fe,Se,Q,y;function K(){}K.__reactDisabledLog=!0;function z(){{if(he===0){Ze=console.log,Oe=console.info,re=console.warn,fe=console.error,Se=console.group,Q=console.groupCollapsed,y=console.groupEnd;var f={configurable:!0,enumerable:!0,value:K,writable:!0};Object.defineProperties(console,{info:f,log:f,warn:f,error:f,group:f,groupCollapsed:f,groupEnd:f})}he++}}function W(){{if(he--,he===0){var f={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:te({},f,{value:Ze}),info:te({},f,{value:Oe}),warn:te({},f,{value:re}),error:te({},f,{value:fe}),group:te({},f,{value:Se}),groupCollapsed:te({},f,{value:Q}),groupEnd:te({},f,{value:y})})}he<0&&S("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var V=w.ReactCurrentDispatcher,M;function L(f,_,T){{if(M===void 0)try{throw Error()}catch(Y){var D=Y.stack.trim().match(/\n( *(at )?)/);M=D&&D[1]||""}return`
2
- `+M+f}}var J=!1,se;{var me=typeof WeakMap=="function"?WeakMap:Map;se=new me}function le(f,_){if(!f||J)return"";{var T=se.get(f);if(T!==void 0)return T}var D;J=!0;var Y=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var X;X=V.current,V.current=null,z();try{if(_){var H=function(){throw Error()};if(Object.defineProperty(H.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(H,[])}catch(Ce){D=Ce}Reflect.construct(f,[],H)}else{try{H.call()}catch(Ce){D=Ce}f.call(H.prototype)}}else{try{throw Error()}catch(Ce){D=Ce}f()}}catch(Ce){if(Ce&&D&&typeof Ce.stack=="string"){for(var F=Ce.stack.split(`
3
- `),Ee=D.stack.split(`
4
- `),ue=F.length-1,pe=Ee.length-1;ue>=1&&pe>=0&&F[ue]!==Ee[pe];)pe--;for(;ue>=1&&pe>=0;ue--,pe--)if(F[ue]!==Ee[pe]){if(ue!==1||pe!==1)do if(ue--,pe--,pe<0||F[ue]!==Ee[pe]){var We=`
5
- `+F[ue].replace(" at new "," at ");return f.displayName&&We.includes("<anonymous>")&&(We=We.replace("<anonymous>",f.displayName)),typeof f=="function"&&se.set(f,We),We}while(ue>=1&&pe>=0);break}}}finally{J=!1,V.current=X,W(),Error.prepareStackTrace=Y}var Mt=f?f.displayName||f.name:"",kt=Mt?L(Mt):"";return typeof f=="function"&&se.set(f,kt),kt}function je(f,_,T){return le(f,!1)}function Ut(f){var _=f.prototype;return!!(_&&_.isReactComponent)}function qe(f,_,T){if(f==null)return"";if(typeof f=="function")return le(f,Ut(f));if(typeof f=="string")return L(f);switch(f){case u:return L("Suspense");case d:return L("SuspenseList")}if(typeof f=="object")switch(f.$$typeof){case l:return je(f.render);case h:return qe(f.type,_,T);case m:{var D=f,Y=D._payload,X=D._init;try{return qe(X(Y),_,T)}catch{}}}return""}var $e=Object.prototype.hasOwnProperty,wt={},_t=w.ReactDebugCurrentFrame;function at(f){if(f){var _=f._owner,T=qe(f.type,f._source,_?_.type:null);_t.setExtraStackFrame(T)}else _t.setExtraStackFrame(null)}function sr(f,_,T,D,Y){{var X=Function.call.bind($e);for(var H in f)if(X(f,H)){var F=void 0;try{if(typeof f[H]!="function"){var Ee=Error((D||"React class")+": "+T+" type `"+H+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof f[H]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw Ee.name="Invariant Violation",Ee}F=f[H](_,H,D,T,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(ue){F=ue}F&&!(F instanceof Error)&&(at(Y),S("%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).",D||"React class",T,H,typeof F),at(null)),F instanceof Error&&!(F.message in wt)&&(wt[F.message]=!0,at(Y),S("Failed %s type: %s",T,F.message),at(null))}}}var j=Array.isArray;function I(f){return j(f)}function ie(f){{var _=typeof Symbol=="function"&&Symbol.toStringTag,T=_&&f[Symbol.toStringTag]||f.constructor.name||"Object";return T}}function Je(f){try{return dt(f),!1}catch{return!0}}function dt(f){return""+f}function ke(f){if(Je(f))return S("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",ie(f)),dt(f)}var ce=w.ReactCurrentOwner,Ae={key:!0,ref:!0,__self:!0,__source:!0},He,Le;function nr(f){if($e.call(f,"ref")){var _=Object.getOwnPropertyDescriptor(f,"ref").get;if(_&&_.isReactWarning)return!1}return f.ref!==void 0}function O(f){if($e.call(f,"key")){var _=Object.getOwnPropertyDescriptor(f,"key").get;if(_&&_.isReactWarning)return!1}return f.key!==void 0}function ne(f,_){typeof f.ref=="string"&&ce.current}function xe(f,_){{var T=function(){He||(He=!0,S("%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)",_))};T.isReactWarning=!0,Object.defineProperty(f,"key",{get:T,configurable:!0})}}function Te(f,_){{var T=function(){Le||(Le=!0,S("%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)",_))};T.isReactWarning=!0,Object.defineProperty(f,"ref",{get:T,configurable:!0})}}var ye=function(f,_,T,D,Y,X,H){var F={$$typeof:e,type:f,key:_,ref:T,props:H,_owner:X};return F._store={},Object.defineProperty(F._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(F,"_self",{configurable:!1,enumerable:!1,writable:!1,value:D}),Object.defineProperty(F,"_source",{configurable:!1,enumerable:!1,writable:!1,value:Y}),Object.freeze&&(Object.freeze(F.props),Object.freeze(F)),F};function ar(f,_,T,D,Y){{var X,H={},F=null,Ee=null;T!==void 0&&(ke(T),F=""+T),O(_)&&(ke(_.key),F=""+_.key),nr(_)&&(Ee=_.ref,ne(_,Y));for(X in _)$e.call(_,X)&&!Ae.hasOwnProperty(X)&&(H[X]=_[X]);if(f&&f.defaultProps){var ue=f.defaultProps;for(X in ue)H[X]===void 0&&(H[X]=ue[X])}if(F||Ee){var pe=typeof f=="function"?f.displayName||f.name||"Unknown":f;F&&xe(H,pe),Ee&&Te(H,pe)}return ye(f,F,Ee,Y,D,ce.current,H)}}var ir=w.ReactCurrentOwner,Ur=w.ReactDebugCurrentFrame;function ht(f){if(f){var _=f._owner,T=qe(f.type,f._source,_?_.type:null);Ur.setExtraStackFrame(T)}else Ur.setExtraStackFrame(null)}var or;or=!1;function Mr(f){return typeof f=="object"&&f!==null&&f.$$typeof===e}function Br(){{if(ir.current){var f=ee(ir.current.type);if(f)return`
1
+ (function(G,w){typeof exports=="object"&&typeof module<"u"?w(exports,require("react"),require("@srimandir/astrology-common")):typeof define=="function"&&define.amd?define(["exports","react","@srimandir/astrology-common"],w):(G=typeof globalThis<"u"?globalThis:G||self,w(G.DoshaCalculator={},G.React,G.AstrologyCommon))})(this,(function(G,w,q){"use strict";function Oi(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,s.get?s:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const Ie=Oi(w);var mr={exports:{}},Wt={};var Ts;function Ci(){if(Ts)return Wt;Ts=1;var t=w,e=Symbol.for("react.element"),r=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,n=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function a(o,l,u){var d,h={},p=null,m=null;u!==void 0&&(p=""+u),l.key!==void 0&&(p=""+l.key),l.ref!==void 0&&(m=l.ref);for(d in l)s.call(l,d)&&!i.hasOwnProperty(d)&&(h[d]=l[d]);if(o&&o.defaultProps)for(d in l=o.defaultProps,l)h[d]===void 0&&(h[d]=l[d]);return{$$typeof:e,type:o,key:p,ref:m,props:h,_owner:n.current}}return Wt.Fragment=r,Wt.jsx=a,Wt.jsxs=a,Wt}var Ht={};var Es;function Ni(){return Es||(Es=1,process.env.NODE_ENV!=="production"&&(function(){var t=w,e=Symbol.for("react.element"),r=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),a=Symbol.for("react.provider"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),m=Symbol.for("react.offscreen"),g=Symbol.iterator,y="@@iterator";function x(f){if(f===null||typeof f!="object")return null;var S=g&&f[g]||f[y];return typeof S=="function"?S:null}var v=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function _(f){{for(var S=arguments.length,j=new Array(S>1?S-1:0),D=1;D<S;D++)j[D-1]=arguments[D];k("error",f,j)}}function k(f,S,j){{var D=v.ReactDebugCurrentFrame,Y=D.getStackAddendum();Y!==""&&(S+="%s",j=j.concat([Y]));var X=j.map(function(W){return String(W)});X.unshift("Warning: "+S),Function.prototype.apply.call(console[f],console,X)}}var O=!1,R=!1,M=!1,E=!1,$=!1,L;L=Symbol.for("react.module.reference");function $e(f){return!!(typeof f=="string"||typeof f=="function"||f===s||f===i||$||f===n||f===u||f===d||E||f===m||O||R||M||typeof f=="object"&&f!==null&&(f.$$typeof===p||f.$$typeof===h||f.$$typeof===a||f.$$typeof===o||f.$$typeof===l||f.$$typeof===L||f.getModuleId!==void 0))}function ge(f,S,j){var D=f.displayName;if(D)return D;var Y=S.displayName||S.name||"";return Y!==""?j+"("+Y+")":j}function Oe(f){return f.displayName||"Context"}function ee(f){if(f==null)return null;if(typeof f.tag=="number"&&_("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof f=="function")return f.displayName||f.name||null;if(typeof f=="string")return f;switch(f){case s:return"Fragment";case r:return"Portal";case i:return"Profiler";case n:return"StrictMode";case u:return"Suspense";case d:return"SuspenseList"}if(typeof f=="object")switch(f.$$typeof){case o:var S=f;return Oe(S)+".Consumer";case a:var j=f;return Oe(j._context)+".Provider";case l:return ge(f,f.render,"ForwardRef");case h:var D=f.displayName||null;return D!==null?D:ee(f.type)||"Memo";case p:{var Y=f,X=Y._payload,W=Y._init;try{return ee(W(X))}catch{return null}}}return null}var te=Object.assign,he=0,tt,Ce,re,fe,Se,Q,b;function F(){}F.__reactDisabledLog=!0;function z(){{if(he===0){tt=console.log,Ce=console.info,re=console.warn,fe=console.error,Se=console.group,Q=console.groupCollapsed,b=console.groupEnd;var f={configurable:!0,enumerable:!0,value:F,writable:!0};Object.defineProperties(console,{info:f,log:f,warn:f,error:f,group:f,groupCollapsed:f,groupEnd:f})}he++}}function H(){{if(he--,he===0){var f={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:te({},f,{value:tt}),info:te({},f,{value:Ce}),warn:te({},f,{value:re}),error:te({},f,{value:fe}),group:te({},f,{value:Se}),groupCollapsed:te({},f,{value:Q}),groupEnd:te({},f,{value:b})})}he<0&&_("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var V=v.ReactCurrentDispatcher,B;function U(f,S,j){{if(B===void 0)try{throw Error()}catch(Y){var D=Y.stack.trim().match(/\n( *(at )?)/);B=D&&D[1]||""}return`
2
+ `+B+f}}var J=!1,se;{var me=typeof WeakMap=="function"?WeakMap:Map;se=new me}function le(f,S){if(!f||J)return"";{var j=se.get(f);if(j!==void 0)return j}var D;J=!0;var Y=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var X;X=V.current,V.current=null,z();try{if(S){var W=function(){throw Error()};if(Object.defineProperty(W.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(W,[])}catch(Ne){D=Ne}Reflect.construct(f,[],W)}else{try{W.call()}catch(Ne){D=Ne}f.call(W.prototype)}}else{try{throw Error()}catch(Ne){D=Ne}f()}}catch(Ne){if(Ne&&D&&typeof Ne.stack=="string"){for(var K=Ne.stack.split(`
3
+ `),Ae=D.stack.split(`
4
+ `),ue=K.length-1,pe=Ae.length-1;ue>=1&&pe>=0&&K[ue]!==Ae[pe];)pe--;for(;ue>=1&&pe>=0;ue--,pe--)if(K[ue]!==Ae[pe]){if(ue!==1||pe!==1)do if(ue--,pe--,pe<0||K[ue]!==Ae[pe]){var Ge=`
5
+ `+K[ue].replace(" at new "," at ");return f.displayName&&Ge.includes("<anonymous>")&&(Ge=Ge.replace("<anonymous>",f.displayName)),typeof f=="function"&&se.set(f,Ge),Ge}while(ue>=1&&pe>=0);break}}}finally{J=!1,V.current=X,H(),Error.prepareStackTrace=Y}var qt=f?f.displayName||f.name:"",jt=qt?U(qt):"";return typeof f=="function"&&se.set(f,jt),jt}function Ee(f,S,j){return le(f,!1)}function Kt(f){var S=f.prototype;return!!(S&&S.isReactComponent)}function We(f,S,j){if(f==null)return"";if(typeof f=="function")return le(f,Kt(f));if(typeof f=="string")return U(f);switch(f){case u:return U("Suspense");case d:return U("SuspenseList")}if(typeof f=="object")switch(f.$$typeof){case l:return Ee(f.render);case h:return We(f.type,S,j);case p:{var D=f,Y=D._payload,X=D._init;try{return We(X(Y),S,j)}catch{}}}return""}var Le=Object.prototype.hasOwnProperty,Tt={},Et=v.ReactDebugCurrentFrame;function ct(f){if(f){var S=f._owner,j=We(f.type,f._source,S?S.type:null);Et.setExtraStackFrame(j)}else Et.setExtraStackFrame(null)}function lr(f,S,j,D,Y){{var X=Function.call.bind(Le);for(var W in f)if(X(f,W)){var K=void 0;try{if(typeof f[W]!="function"){var Ae=Error((D||"React class")+": "+j+" type `"+W+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof f[W]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw Ae.name="Invariant Violation",Ae}K=f[W](S,W,D,j,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(ue){K=ue}K&&!(K instanceof Error)&&(ct(Y),_("%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).",D||"React class",j,W,typeof K),ct(null)),K instanceof Error&&!(K.message in Tt)&&(Tt[K.message]=!0,ct(Y),_("Failed %s type: %s",j,K.message),ct(null))}}}var A=Array.isArray;function I(f){return A(f)}function ae(f){{var S=typeof Symbol=="function"&&Symbol.toStringTag,j=S&&f[Symbol.toStringTag]||f.constructor.name||"Object";return j}}function Qe(f){try{return pt(f),!1}catch{return!0}}function pt(f){return""+f}function _e(f){if(Qe(f))return _("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",ae(f)),pt(f)}var ce=v.ReactCurrentOwner,je={key:!0,ref:!0,__self:!0,__source:!0},He,Me;function cr(f){if(Le.call(f,"ref")){var S=Object.getOwnPropertyDescriptor(f,"ref").get;if(S&&S.isReactWarning)return!1}return f.ref!==void 0}function N(f){if(Le.call(f,"key")){var S=Object.getOwnPropertyDescriptor(f,"key").get;if(S&&S.isReactWarning)return!1}return f.key!==void 0}function ne(f,S){typeof f.ref=="string"&&ce.current}function xe(f,S){{var j=function(){He||(He=!0,_("%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)",S))};j.isReactWarning=!0,Object.defineProperty(f,"key",{get:j,configurable:!0})}}function Te(f,S){{var j=function(){Me||(Me=!0,_("%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)",S))};j.isReactWarning=!0,Object.defineProperty(f,"ref",{get:j,configurable:!0})}}var ye=function(f,S,j,D,Y,X,W){var K={$$typeof:e,type:f,key:S,ref:j,props:W,_owner:X};return K._store={},Object.defineProperty(K._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(K,"_self",{configurable:!1,enumerable:!1,writable:!1,value:D}),Object.defineProperty(K,"_source",{configurable:!1,enumerable:!1,writable:!1,value:Y}),Object.freeze&&(Object.freeze(K.props),Object.freeze(K)),K};function ur(f,S,j,D,Y){{var X,W={},K=null,Ae=null;j!==void 0&&(_e(j),K=""+j),N(S)&&(_e(S.key),K=""+S.key),cr(S)&&(Ae=S.ref,ne(S,Y));for(X in S)Le.call(S,X)&&!je.hasOwnProperty(X)&&(W[X]=S[X]);if(f&&f.defaultProps){var ue=f.defaultProps;for(X in ue)W[X]===void 0&&(W[X]=ue[X])}if(K||Ae){var pe=typeof f=="function"?f.displayName||f.name||"Unknown":f;K&&xe(W,pe),Ae&&Te(W,pe)}return ye(f,K,Ae,Y,D,ce.current,W)}}var dr=v.ReactCurrentOwner,zr=v.ReactDebugCurrentFrame;function gt(f){if(f){var S=f._owner,j=We(f.type,f._source,S?S.type:null);zr.setExtraStackFrame(j)}else zr.setExtraStackFrame(null)}var hr;hr=!1;function Vr(f){return typeof f=="object"&&f!==null&&f.$$typeof===e}function Jr(){{if(dr.current){var f=ee(dr.current.type);if(f)return`
6
6
 
7
- Check the render method of \``+f+"`."}return""}}function lc(f){return""}var sa={};function cc(f){{var _=Br();if(!_){var T=typeof f=="string"?f:f.displayName||f.name;T&&(_=`
7
+ Check the render method of \``+f+"`."}return""}}function Xc(f){return""}var Ti={};function Zc(f){{var S=Jr();if(!S){var j=typeof f=="string"?f:f.displayName||f.name;j&&(S=`
8
8
 
9
- Check the top-level render call using <`+T+">.")}return _}}function na(f,_){{if(!f._store||f._store.validated||f.key!=null)return;f._store.validated=!0;var T=cc(_);if(sa[T])return;sa[T]=!0;var D="";f&&f._owner&&f._owner!==ir.current&&(D=" It was passed a child from "+ee(f._owner.type)+"."),ht(f),S('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',T,D),ht(null)}}function aa(f,_){{if(typeof f!="object")return;if(I(f))for(var T=0;T<f.length;T++){var D=f[T];Mr(D)&&na(D,_)}else if(Mr(f))f._store&&(f._store.validated=!0);else if(f){var Y=A(f);if(typeof Y=="function"&&Y!==f.entries)for(var X=Y.call(f),H;!(H=X.next()).done;)Mr(H.value)&&na(H.value,_)}}}function uc(f){{var _=f.type;if(_==null||typeof _=="string")return;var T;if(typeof _=="function")T=_.propTypes;else if(typeof _=="object"&&(_.$$typeof===l||_.$$typeof===h))T=_.propTypes;else return;if(T){var D=ee(_);sr(T,f.props,"prop",D,f)}else if(_.PropTypes!==void 0&&!or){or=!0;var Y=ee(_);S("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",Y||"Unknown")}typeof _.getDefaultProps=="function"&&!_.getDefaultProps.isReactClassApproved&&S("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function dc(f){{for(var _=Object.keys(f.props),T=0;T<_.length;T++){var D=_[T];if(D!=="children"&&D!=="key"){ht(f),S("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",D),ht(null);break}}f.ref!==null&&(ht(f),S("Invalid attribute `ref` supplied to `React.Fragment`."),ht(null))}}var ia={};function oa(f,_,T,D,Y,X){{var H=De(f);if(!H){var F="";(f===void 0||typeof f=="object"&&f!==null&&Object.keys(f).length===0)&&(F+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var Ee=lc();Ee?F+=Ee:F+=Br();var ue;f===null?ue="null":I(f)?ue="array":f!==void 0&&f.$$typeof===e?(ue="<"+(ee(f.type)||"Unknown")+" />",F=" Did you accidentally export a JSX literal instead of a component?"):ue=typeof f,S("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",ue,F)}var pe=ar(f,_,T,Y,X);if(pe==null)return pe;if(H){var We=_.children;if(We!==void 0)if(D)if(I(We)){for(var Mt=0;Mt<We.length;Mt++)aa(We[Mt],f);Object.freeze&&Object.freeze(We)}else S("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else aa(We,f)}if($e.call(_,"key")){var kt=ee(f),Ce=Object.keys(_).filter(function(yc){return yc!=="key"}),ps=Ce.length>0?"{key: someKey, "+Ce.join(": ..., ")+": ...}":"{key: someKey}";if(!ia[kt+ps]){var gc=Ce.length>0?"{"+Ce.join(": ..., ")+": ...}":"{}";S(`A props object containing a "key" prop is being spread into JSX:
9
+ Check the top-level render call using <`+j+">.")}return S}}function Ei(f,S){{if(!f._store||f._store.validated||f.key!=null)return;f._store.validated=!0;var j=Zc(S);if(Ti[j])return;Ti[j]=!0;var D="";f&&f._owner&&f._owner!==dr.current&&(D=" It was passed a child from "+ee(f._owner.type)+"."),gt(f),_('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',j,D),gt(null)}}function ji(f,S){{if(typeof f!="object")return;if(I(f))for(var j=0;j<f.length;j++){var D=f[j];Vr(D)&&Ei(D,S)}else if(Vr(f))f._store&&(f._store.validated=!0);else if(f){var Y=x(f);if(typeof Y=="function"&&Y!==f.entries)for(var X=Y.call(f),W;!(W=X.next()).done;)Vr(W.value)&&Ei(W.value,S)}}}function eu(f){{var S=f.type;if(S==null||typeof S=="string")return;var j;if(typeof S=="function")j=S.propTypes;else if(typeof S=="object"&&(S.$$typeof===l||S.$$typeof===h))j=S.propTypes;else return;if(j){var D=ee(S);lr(j,f.props,"prop",D,f)}else if(S.PropTypes!==void 0&&!hr){hr=!0;var Y=ee(S);_("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",Y||"Unknown")}typeof S.getDefaultProps=="function"&&!S.getDefaultProps.isReactClassApproved&&_("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function tu(f){{for(var S=Object.keys(f.props),j=0;j<S.length;j++){var D=S[j];if(D!=="children"&&D!=="key"){gt(f),_("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",D),gt(null);break}}f.ref!==null&&(gt(f),_("Invalid attribute `ref` supplied to `React.Fragment`."),gt(null))}}var Ai={};function Pi(f,S,j,D,Y,X){{var W=$e(f);if(!W){var K="";(f===void 0||typeof f=="object"&&f!==null&&Object.keys(f).length===0)&&(K+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var Ae=Xc();Ae?K+=Ae:K+=Jr();var ue;f===null?ue="null":I(f)?ue="array":f!==void 0&&f.$$typeof===e?(ue="<"+(ee(f.type)||"Unknown")+" />",K=" Did you accidentally export a JSX literal instead of a component?"):ue=typeof f,_("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",ue,K)}var pe=ur(f,S,j,Y,X);if(pe==null)return pe;if(W){var Ge=S.children;if(Ge!==void 0)if(D)if(I(Ge)){for(var qt=0;qt<Ge.length;qt++)ji(Ge[qt],f);Object.freeze&&Object.freeze(Ge)}else _("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else ji(Ge,f)}if(Le.call(S,"key")){var jt=ee(f),Ne=Object.keys(S).filter(function(ou){return ou!=="key"}),xs=Ne.length>0?"{key: someKey, "+Ne.join(": ..., ")+": ...}":"{key: someKey}";if(!Ai[jt+xs]){var au=Ne.length>0?"{"+Ne.join(": ..., ")+": ...}":"{}";_(`A props object containing a "key" prop is being spread into JSX:
10
10
  let props = %s;
11
11
  <%s {...props} />
12
12
  React keys must be passed directly to JSX without using spread:
13
13
  let props = %s;
14
- <%s key={someKey} {...props} />`,ps,kt,gc,kt),ia[kt+ps]=!0}}return f===s?dc(pe):uc(pe),pe}}function hc(f,_,T){return oa(f,_,T,!0)}function fc(f,_,T){return oa(f,_,T,!1)}var mc=fc,pc=hc;Kt.Fragment=s,Kt.jsx=mc,Kt.jsxs=pc})()),Kt}var bs;function ha(){return bs||(bs=1,process.env.NODE_ENV==="production"?cr.exports=ua():cr.exports=da()),cr.exports}var c=ha();const ur={all_fields_filled:"all_fields_filled",fields_not_filled:"fields_not_filled",puja_clicked:"puja_clicked"};function dr(t,e){var r={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(r[s[n]]=t[s[n]]);return r}function fa(t,e,r,s){function n(a){return a instanceof r?a:new r(function(i){i(a)})}return new(r||(r=Promise))(function(a,i){function o(d){try{u(s.next(d))}catch(h){i(h)}}function l(d){try{u(s.throw(d))}catch(h){i(h)}}function u(d){d.done?a(d.value):n(d.value).then(o,l)}u((s=s.apply(t,e||[])).next())})}typeof SuppressedError=="function"&&SuppressedError;const ma=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class Kr extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class pa extends Kr{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class vs extends Kr{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class ws extends Kr{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Fr;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(Fr||(Fr={}));class ga{constructor(e,{headers:r={},customFetch:s,region:n=Fr.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=ma(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return fa(this,arguments,void 0,function*(r,s={}){var n;let a,i;try{const{headers:o,method:l,body:u,signal:d,timeout:h}=s;let m={},{region:p}=s;p||(p=this.region);const g=new URL(`${this.url}/${r}`);p&&p!=="any"&&(m["x-region"]=p,g.searchParams.set("forceFunctionRegion",p));let b;u&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(m["Content-Type"]="application/octet-stream",b=u):typeof u=="string"?(m["Content-Type"]="text/plain",b=u):typeof FormData<"u"&&u instanceof FormData?b=u:(m["Content-Type"]="application/json",b=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?b=JSON.stringify(u):b=u;let A=d;h&&(i=new AbortController,a=setTimeout(()=>i.abort(),h),d?(A=i.signal,d.addEventListener("abort",()=>i.abort())):A=i.signal);const w=yield this.fetch(g.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},m),this.headers),o),body:b,signal:A}).catch(R=>{throw new pa(R)}),S=w.headers.get("x-relay-error");if(S&&S==="true")throw new vs(w);if(!w.ok)throw new ws(w);let k=((n=w.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),N;return k==="application/json"?N=yield w.json():k==="application/octet-stream"||k==="application/pdf"?N=yield w.blob():k==="text/event-stream"?N=w:k==="multipart/form-data"?N=yield w.formData():N=yield w.text(),{data:N,error:null,response:w}}catch(o){return{data:null,error:o,response:o instanceof ws||o instanceof vs?o.context:void 0}}finally{a&&clearTimeout(a)}})}}const _s=3,ks=t=>Math.min(1e3*2**t,3e4),ya=[520,503],Ss=["GET","HEAD","OPTIONS"];var ba=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function xs(t,e){return new Promise(r=>{if(e?.aborted){r();return}const s=setTimeout(()=>{e?.removeEventListener("abort",n),r()},t);function n(){clearTimeout(s),r()}e?.addEventListener("abort",n)})}function va(t,e,r,s){return!(!s||r>=_s||!Ss.includes(t)||!ya.includes(e))}var wa=class{constructor(t){var e,r,s,n,a;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.shouldStripNulls=(s=t.shouldStripNulls)!==null&&s!==void 0?s:!1,this.urlLengthLimit=(n=t.urlLengthLimit)!==null&&n!==void 0?n:8e3,this.retryEnabled=(a=t.retry)!==null&&a!==void 0?a:!0,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}retry(t){return this.retryEnabled=t,this}then(t,e){var r=this;if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){const i=this.headers.get("Accept");i==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!i||i==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const s=this.fetch;let a=(async()=>{let i=0;for(;;){const u=new Headers(r.headers);i>0&&u.set("X-Retry-Count",String(i));let d;try{d=await s(r.url.toString(),{method:r.method,headers:u,body:JSON.stringify(r.body,(h,m)=>typeof m=="bigint"?m.toString():m),signal:r.signal})}catch(h){if(h?.name==="AbortError"||h?.code==="ABORT_ERR"||!Ss.includes(r.method))throw h;if(r.retryEnabled&&i<_s){const m=ks(i);i++,await xs(m,r.signal);continue}throw h}if(va(r.method,d.status,i,r.retryEnabled)){var o,l;const h=(o=(l=d.headers)===null||l===void 0?void 0:l.get("Retry-After"))!==null&&o!==void 0?o:null,m=h!==null?Math.max(0,parseInt(h,10)||0)*1e3:ks(i);await d.text(),i++,await xs(m,r.signal);continue}return await r.processResponse(d)}})();return this.shouldThrowOnError||(a=a.catch(i=>{var o;let l="",u="",d="";const h=i?.cause;if(h){var m,p,g,b;const S=(m=h?.message)!==null&&m!==void 0?m:"",k=(p=h?.code)!==null&&p!==void 0?p:"";l=`${(g=i?.name)!==null&&g!==void 0?g:"FetchError"}: ${i?.message}`,l+=`
14
+ <%s key={someKey} {...props} />`,xs,jt,au,jt),Ai[jt+xs]=!0}}return f===s?tu(pe):eu(pe),pe}}function ru(f,S,j){return Pi(f,S,j,!0)}function su(f,S,j){return Pi(f,S,j,!1)}var nu=su,iu=ru;Ht.Fragment=s,Ht.jsx=nu,Ht.jsxs=iu})()),Ht}var js;function Ii(){return js||(js=1,process.env.NODE_ENV==="production"?mr.exports=Ci():mr.exports=Ni()),mr.exports}var c=Ii();const pr={all_fields_filled:"all_fields_filled",fields_not_filled:"fields_not_filled",puja_clicked:"puja_clicked"},Di=Symbol.for("@supabase/supabase-js.traceContextExtractor");function $i(){return globalThis[Di]}function gr(t,e){var r={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(r[s[n]]=t[s[n]]);return r}function Li(t,e,r,s){function n(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function o(d){try{u(s.next(d))}catch(h){a(h)}}function l(d){try{u(s.throw(d))}catch(h){a(h)}}function u(d){d.done?i(d.value):n(d.value).then(o,l)}u((s=s.apply(t,e||[])).next())})}typeof SuppressedError=="function"&&SuppressedError;const Mi=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class Yr extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class Ui extends Yr{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class As extends Yr{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Ps extends Yr{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Qr;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(Qr||(Qr={}));class Bi{constructor(e,{headers:r={},customFetch:s,region:n=Qr.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=Mi(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Li(this,arguments,void 0,function*(r,s={}){var n,i;let a,o,l;try{const{headers:u,method:d,body:h,signal:p,timeout:m}=s;let g={},{region:y}=s;y||(y=this.region);const x=new URL(`${this.url}/${r}`);y&&y!=="any"&&(g["x-region"]=y,x.searchParams.set("forceFunctionRegion",y));let v;const _=!!u&&Object.keys(u).some($=>$.toLowerCase()==="content-type");h&&!_?typeof Blob<"u"&&h instanceof Blob||h instanceof ArrayBuffer?(g["Content-Type"]="application/octet-stream",v=h):typeof h=="string"?(g["Content-Type"]="text/plain",v=h):typeof FormData<"u"&&h instanceof FormData?v=h:(g["Content-Type"]="application/json",v=JSON.stringify(h)):h&&typeof h!="string"&&!(typeof Blob<"u"&&h instanceof Blob)&&!(h instanceof ArrayBuffer)&&!(typeof FormData<"u"&&h instanceof FormData)?v=JSON.stringify(h):v=h;let k=p;m&&(o=new AbortController,a=setTimeout(()=>o.abort(),m),p?(k=o.signal,l=()=>o.abort(),p.addEventListener("abort",l)):k=o.signal);const O=yield this.fetch(x.toString(),{method:d||"POST",headers:Object.assign(Object.assign(Object.assign({},g),this.headers),u),body:v,signal:k}).catch($=>{throw new Ui($)}),R=O.headers.get("x-relay-error");if(R&&R==="true")throw new As(O);if(!O.ok)throw new Ps(O);let M=((n=O.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim().toLowerCase(),E;return M==="application/json"?E=yield O.json():M==="application/octet-stream"||M==="application/pdf"?E=yield O.blob():M==="text/event-stream"?E=O:M==="multipart/form-data"?E=yield O.formData():E=yield O.text(),{data:E,error:null,response:O}}catch(u){return{data:null,error:u,response:u instanceof Ps||u instanceof As?u.context:void 0}}finally{a&&clearTimeout(a),l&&((i=s.signal)===null||i===void 0||i.removeEventListener("abort",l))}})}}const Rs=3,Os=t=>Math.min(1e3*2**t,3e4),Fi=[520,503],Cs=["GET","HEAD","OPTIONS"];var Xr=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function Gt(t){"@babel/helpers - typeof";return Gt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Gt(t)}function Ki(t,e){if(Gt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(Gt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function qi(t){var e=Ki(t,"string");return Gt(e)=="symbol"?e:e+""}function Wi(t,e,r){return(e=qi(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Ns(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function At(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Ns(Object(r),!0).forEach(function(s){Wi(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Ns(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}function Is(t,e){return new Promise(r=>{if(e?.aborted){r();return}const s=setTimeout(()=>{e?.removeEventListener("abort",n),r()},t);function n(){clearTimeout(s),r()}e?.addEventListener("abort",n)})}function Hi(t,e,r,s){return!(!s||r>=Rs||!Cs.includes(t)||!Fi.includes(e))}var Gi=class{constructor(t){var e,r,s,n,i;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.shouldStripNulls=(s=t.shouldStripNulls)!==null&&s!==void 0?s:!1,this.urlLengthLimit=(n=t.urlLengthLimit)!==null&&n!==void 0?n:8e3,this.retryEnabled=(i=t.retry)!==null&&i!==void 0?i:!0,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}retry(t){return this.retryEnabled=t,this}then(t,e){var r=this;if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){const a=this.headers.get("Accept");a==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!a||a==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const s=this.fetch;let i=(async()=>{let a=0;for(;;){const u={};r.headers.forEach((h,p)=>{u[p]=h}),a>0&&(u["X-Retry-Count"]=String(a));let d;try{d=await s(r.url.toString(),{method:r.method,headers:u,body:JSON.stringify(r.body,(h,p)=>typeof p=="bigint"?p.toString():p),signal:r.signal})}catch(h){if(h?.name==="AbortError"||h?.code==="ABORT_ERR"||!Cs.includes(r.method))throw h;if(r.retryEnabled&&a<Rs){const p=Os(a);a++,await Is(p,r.signal);continue}throw h}if(Hi(r.method,d.status,a,r.retryEnabled)){var o,l;const h=(o=(l=d.headers)===null||l===void 0?void 0:l.get("Retry-After"))!==null&&o!==void 0?o:null,p=h!==null?Math.max(0,parseInt(h,10)||0)*1e3:Os(a);await d.text(),a++,await Is(p,r.signal);continue}return await r.processResponse(d)}})();return this.shouldThrowOnError||(i=i.catch(a=>{var o;let l="",u="",d="";const h=a?.cause;if(h){var p,m,g,y;const _=(p=h?.message)!==null&&p!==void 0?p:"",k=(m=h?.code)!==null&&m!==void 0?m:"";l=`${(g=a?.name)!==null&&g!==void 0?g:"FetchError"}: ${a?.message}`,l+=`
15
15
 
16
- Caused by: ${(b=h?.name)!==null&&b!==void 0?b:"Error"}: ${S}`,k&&(l+=` (${k})`),h?.stack&&(l+=`
17
- ${h.stack}`)}else{var A;l=(A=i?.stack)!==null&&A!==void 0?A:""}const w=this.url.toString().length;return i?.name==="AbortError"||i?.code==="ABORT_ERR"?(d="",u="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(u+=`. Note: Your request URL is ${w} 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.`)):(h?.name==="HeadersOverflowError"||h?.code==="UND_ERR_HEADERS_OVERFLOW")&&(d="",u="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(u+=`. Your request URL is ${w} 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.`)),{success:!1,error:{message:`${(o=i?.name)!==null&&o!==void 0?o:"FetchError"}: ${i?.message}`,details:l,hint:u,code:d},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}async processResponse(t){var e=this;let r=null,s=null,n=null,a=t.status,i=t.statusText;if(t.ok){var o,l;if(e.method!=="HEAD"){var u;const m=await t.text();m===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((u=e.headers.get("Accept"))===null||u===void 0)&&u.includes("application/vnd.pgrst.plan+text"))?s=m:s=JSON.parse(m))}const d=(o=e.headers.get("Prefer"))===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),h=(l=t.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");d&&h&&h.length>1&&(n=parseInt(h[1])),e.isMaybeSingle&&Array.isArray(s)&&(s.length>1?(r={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,n=null,a=406,i="Not Acceptable"):s.length===1?s=s[0]:s=null)}else{const d=await t.text();try{r=JSON.parse(d),Array.isArray(r)&&t.status===404&&(s=[],r=null,a=200,i="OK")}catch{t.status===404&&d===""?(a=204,i="No Content"):r={message:d}}if(r&&e.shouldThrowOnError)throw new ba(r)}return{success:r===null,error:r,data:s,count:n,status:a,statusText:i}}returns(){return this}overrideTypes(){return this}},_a=class extends wa{select(t){let e=!1;const r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){const a=n?`${n}.order`:"order",i=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${i?`${i},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){const s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){const n=typeof s>"u"?"offset":`${s}.offset`,a=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(a,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:a="text"}={}){var i;const o=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(i=this.headers.get("Accept"))!==null&&i!==void 0?i:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${a}; for="${l}"; options=${o};`),a==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}};const Ts=new RegExp("[,()]");var St=class extends _a{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&Ts.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&Ts.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");const a=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${a}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},ka=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:n=8e3,retry:a}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=s,this.urlLengthLimit=n,this.retry=a}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){const{head:r=!1,count:s}=e??{},n=r?"HEAD":"GET";let a=!1;const i=(t??"*").split("").map(u=>/\s/.test(u)&&!a?"":(u==='"'&&(a=!a),u)).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",i),s&&l.append("Prefer",`count=${s}`),new St({method:n,url:o,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;const n="POST",{url:a,headers:i}=this.cloneRequestState();if(e&&i.append("Prefer",`count=${e}`),r||i.append("Prefer","missing=default"),Array.isArray(t)){const o=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(o.length>0){const l=[...new Set(o)].map(u=>`"${u}"`);a.searchParams.set("columns",l.join(","))}}return new St({method:n,url:a,headers:i,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var a;const i="POST",{url:o,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&l.append("Prefer",`count=${s}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){const u=t.reduce((d,h)=>d.concat(Object.keys(h)),[]);if(u.length>0){const d=[...new Set(u)].map(h=>`"${h}"`);o.searchParams.set("columns",d.join(","))}}return new St({method:i,url:o,headers:l,schema:this.schema,body:t,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var r;const s="PATCH",{url:n,headers:a}=this.cloneRequestState();return e&&a.append("Prefer",`count=${e}`),new St({method:s,url:n,headers:a,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:t}={}){var e;const r="DELETE",{url:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new St({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function Ft(t){"@babel/helpers - typeof";return Ft=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ft(t)}function Sa(t,e){if(Ft(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(Ft(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function xa(t){var e=Sa(t,"string");return Ft(e)=="symbol"?e:e+""}function Ta(t,e,r){return(e=xa(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function js(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function hr(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?js(Object(r),!0).forEach(function(s){Ta(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):js(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var ja=class la{constructor(e,{headers:r={},schema:s,fetch:n,timeout:a,urlLengthLimit:i=8e3,retry:o}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.urlLengthLimit=i;const l=n??globalThis.fetch;a!==void 0&&a>0?this.fetch=(u,d)=>{const h=new AbortController,m=setTimeout(()=>h.abort(),a),p=d?.signal;if(p){if(p.aborted)return clearTimeout(m),l(u,d);const g=()=>{clearTimeout(m),h.abort()};return p.addEventListener("abort",g,{once:!0}),l(u,hr(hr({},d),{},{signal:h.signal})).finally(()=>{clearTimeout(m),p.removeEventListener("abort",g)})}return l(u,hr(hr({},d),{},{signal:h.signal})).finally(()=>clearTimeout(m))}:this.fetch=l,this.retry=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new ka(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new la(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,r={},{head:s=!1,get:n=!1,count:a}={}){var i;let o;const l=new URL(`${this.url}/rpc/${e}`);let u;const d=p=>p!==null&&typeof p=="object"&&(!Array.isArray(p)||p.some(d)),h=s&&Object.values(r).some(d);h?(o="POST",u=r):s||n?(o=s?"HEAD":"GET",Object.entries(r).filter(([p,g])=>g!==void 0).map(([p,g])=>[p,Array.isArray(g)?`{${g.join(",")}}`:`${g}`]).forEach(([p,g])=>{l.searchParams.append(p,g)})):(o="POST",u=r);const m=new Headers(this.headers);return h?m.set("Prefer",a?`count=${a},return=minimal`:"return=minimal"):a&&m.set("Prefer",`count=${a}`),new St({method:o,url:l,headers:m,schema:this.schemaName,body:u,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class Aa{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const r=globalThis.process;if(r){const s=r.versions;if(s&&s.node){const n=s.node,a=parseInt(n.replace(/^v/,"").split(".")[0]);return a>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${a} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${a} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
18
- import ws from "ws"
19
- new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
16
+ Caused by: ${(y=h?.name)!==null&&y!==void 0?y:"Error"}: ${_}`,k&&(l+=` (${k})`),h?.stack&&(l+=`
17
+ ${h.stack}`)}else{var x;l=(x=a?.stack)!==null&&x!==void 0?x:""}const v=this.url.toString().length;return a?.name==="AbortError"||a?.code==="ABORT_ERR"?(d="",u="Request was aborted (timeout or manual cancellation)",v>this.urlLengthLimit&&(u+=`. Note: Your request URL is ${v} 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.`)):(h?.name==="HeadersOverflowError"||h?.code==="UND_ERR_HEADERS_OVERFLOW")&&(d="",u="HTTP headers exceeded server limits (typically 16KB)",v>this.urlLengthLimit&&(u+=`. Your request URL is ${v} 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.`)),{success:!1,error:{message:`${(o=a?.name)!==null&&o!==void 0?o:"FetchError"}: ${a?.message}`,details:l,hint:u,code:d},data:null,count:null,status:0,statusText:""}})),i.then(t,e)}async processResponse(t){var e=this;let r=null,s=null,n=null,i=t.status,a=t.statusText;if(t.ok){var o,l;if(e.method!=="HEAD"){var u;const m=await t.text();if(m!=="")if(e.headers.get("Accept")==="text/csv")s=m;else if(e.headers.get("Accept")&&(!((u=e.headers.get("Accept"))===null||u===void 0)&&u.includes("application/vnd.pgrst.plan+text")))s=m;else try{s=JSON.parse(m)}catch{if(r={message:m},s=null,e.shouldThrowOnError)throw new Xr({message:m,details:"",hint:"",code:""})}}const h=(o=e.headers.get("Prefer"))===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),p=(l=t.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");if(h&&p&&p.length>1&&(n=parseInt(p[1])),e.isMaybeSingle&&Array.isArray(s))if(s.length>1){if(r={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,n=null,i=406,a="Not Acceptable",e.shouldThrowOnError){var d;throw new Xr(At(At({},r),{},{hint:(d=r.hint)!==null&&d!==void 0?d:""}))}}else s.length===1?s=s[0]:s=null}else{const h=await t.text();try{r=JSON.parse(h),Array.isArray(r)&&t.status===404&&(s=[],r=null,i=200,a="OK")}catch{t.status===404&&h===""?(i=204,a="No Content"):r={message:h}}if(r&&e.shouldThrowOnError)throw new Xr(r)}return{success:r===null,error:r,data:s,count:n,status:i,statusText:a}}returns(){return this}overrideTypes(){return this}},zi=class extends Gi{throwOnError(){return super.throwOnError()}select(t){let e=!1;const r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){const i=n?`${n}.order`:"order",a=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${a?`${a},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){const s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){const n=typeof s>"u"?"offset":`${s}.offset`,i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(i,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:i="text"}={}){var a;const o=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${o};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}};const Ds=new RegExp("[,()]");var Pt=class extends zi{throwOnError(){return super.throwOnError()}eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&Ds.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&Ds.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");const i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${i}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Vi=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:n=8e3,retry:i}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=s,this.urlLengthLimit=n,this.retry=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){const{head:r=!1,count:s}=e??{},n=r?"HEAD":"GET";let i=!1;const a=(t??"*").split("").map(u=>/\s/.test(u)&&!i?"":(u==='"'&&(i=!i),u)).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",a),s&&l.append("Prefer",`count=${s}`),new Pt({method:n,url:o,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;const n="POST",{url:i,headers:a}=this.cloneRequestState();if(e&&a.append("Prefer",`count=${e}`),r||a.append("Prefer","missing=default"),Array.isArray(t)){const o=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(o.length>0){const l=[...new Set(o)].map(u=>`"${u}"`);i.searchParams.set("columns",l.join(","))}}return new Pt({method:n,url:i,headers:a,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var i;const a="POST",{url:o,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&l.append("Prefer",`count=${s}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){const u=t.reduce((d,h)=>d.concat(Object.keys(h)),[]);if(u.length>0){const d=[...new Set(u)].map(h=>`"${h}"`);o.searchParams.set("columns",d.join(","))}}return new Pt({method:a,url:o,headers:l,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var r;const s="PATCH",{url:n,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Pt({method:s,url:n,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:t}={}){var e;const r="DELETE",{url:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new Pt({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}},Ji=class Ri{constructor(e,{headers:r={},schema:s,fetch:n,timeout:i,urlLengthLimit:a=8e3,retry:o}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.urlLengthLimit=a;const l=n??globalThis.fetch;i!==void 0&&i>0?this.fetch=(u,d)=>{const h=new AbortController,p=setTimeout(()=>h.abort(),i),m=d?.signal;if(m){if(m.aborted)return clearTimeout(p),l(u,d);const g=()=>{clearTimeout(p),h.abort()};return m.addEventListener("abort",g,{once:!0}),l(u,At(At({},d),{},{signal:h.signal})).finally(()=>{clearTimeout(p),m.removeEventListener("abort",g)})}return l(u,At(At({},d),{},{signal:h.signal})).finally(()=>clearTimeout(p))}:this.fetch=l,this.retry=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Vi(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new Ri(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,r={},{head:s=!1,get:n=!1,count:i}={}){var a;let o;const l=new URL(`${this.url}/rpc/${e}`);let u;const d=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(d)),h=s&&Object.values(r).some(d);h?(o="POST",u=r):s||n?(o=s?"HEAD":"GET",Object.entries(r).filter(([m,g])=>g!==void 0).map(([m,g])=>[m,Array.isArray(g)?`{${g.join(",")}}`:`${g}`]).forEach(([m,g])=>{l.searchParams.append(m,g)})):(o="POST",u=r);const p=new Headers(this.headers);return h?p.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&p.set("Prefer",`count=${i}`),new Pt({method:o,url:l,headers:p,schema:this.schemaName,body:u,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class Yi{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};const r=globalThis;if(typeof globalThis<"u"&&typeof r.WebSocket<"u")return{type:"native",wsConstructor:r.WebSocket};const s=typeof global<"u"?global:void 0;if(s&&typeof s.WebSocket<"u")return{type:"native",wsConstructor:s.WebSocket};if(typeof globalThis<"u"&&typeof r.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&r.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const n=globalThis.process;if(n){const i=n.versions;if(i&&i.node)return{type:"unsupported",error:"Node.js detected but native WebSocket not found.",workaround:"Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option."}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
20
18
 
21
- Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const Ea="realtime-js/2.105.1",Pa="1.0.0",As="2.0.0",Ra=As,Oa=1e4,Ca=100,it={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Es={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},qr={connecting:"connecting",closing:"closing",closed:"closed"};class Na{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:{},i=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,r,s){var n,a;const i=e.topic,o=(n=e.ref)!==null&&n!==void 0?n:"",l=(a=e.join_ref)!==null&&a!==void 0?a:"",u=e.payload.event,d=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=Object.keys(d).length===0?"":JSON.stringify(d);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const m=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+o.length+i.length+u.length+h.length,p=new ArrayBuffer(this.HEADER_LENGTH+m);let g=new DataView(p),b=0;g.setUint8(b++,this.KINDS.userBroadcastPush),g.setUint8(b++,l.length),g.setUint8(b++,o.length),g.setUint8(b++,i.length),g.setUint8(b++,u.length),g.setUint8(b++,h.length),g.setUint8(b++,r),Array.from(l,w=>g.setUint8(b++,w.charCodeAt(0))),Array.from(o,w=>g.setUint8(b++,w.charCodeAt(0))),Array.from(i,w=>g.setUint8(b++,w.charCodeAt(0))),Array.from(u,w=>g.setUint8(b++,w.charCodeAt(0))),Array.from(h,w=>g.setUint8(b++,w.charCodeAt(0)));var A=new Uint8Array(p.byteLength+s.byteLength);return A.set(new Uint8Array(p),0),A.set(new Uint8Array(s),p.byteLength),A.buffer}decode(e,r){if(this._isArrayBuffer(e)){let s=this._binaryDecode(e);return r(s)}if(typeof e=="string"){const s=JSON.parse(e),[n,a,i,o,l]=s;return r({join_ref:n,ref:a,topic:i,event:o,payload:l})}return r({})}_binaryDecode(e){const r=new DataView(e),s=r.getUint8(0),n=new TextDecoder;if(s===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,n)}_decodeUserBroadcast(e,r,s){const n=r.getUint8(1),a=r.getUint8(2),i=r.getUint8(3),o=r.getUint8(4);let l=this.HEADER_LENGTH+4;const u=s.decode(e.slice(l,l+n));l=l+n;const d=s.decode(e.slice(l,l+a));l=l+a;const h=s.decode(e.slice(l,l+i));l=l+i;const m=e.slice(l,e.byteLength),p=o===this.JSON_ENCODING?JSON.parse(s.decode(m)):m,g={type:this.BROADCAST_EVENT,event:d,payload:p};return i>0&&(g.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:g}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([s])=>r.includes(s)))}}var Z;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(Z||(Z={}));const Ps=(t,e,r={})=>{var s;const n=(s=r.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((a,i)=>(a[i]=Ia(i,t,e,n),a),{}):{}},Ia=(t,e,r,s)=>{const n=e.find(o=>o.name===t),a=n?.type,i=r[t];return a&&!s.includes(a)?Rs(a,i):Hr(i)},Rs=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return Ua(e,r)}switch(t){case Z.bool:return Da(e);case Z.float4:case Z.float8:case Z.int2:case Z.int4:case Z.int8:case Z.numeric:case Z.oid:return $a(e);case Z.json:case Z.jsonb:return La(e);case Z.timestamp:return Ma(e);case Z.abstime:case Z.date:case Z.daterange:case Z.int4range:case Z.int8range:case Z.money:case Z.reltime:case Z.text:case Z.time:case Z.timestamptz:case Z.timetz:case Z.tsrange:case Z.tstzrange:return Hr(e);default:return Hr(e)}},Hr=t=>t,Da=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},$a=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},La=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Ua=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,s=t[r];if(t[0]==="{"&&s==="}"){let a;const i=t.slice(1,r);try{a=JSON.parse("["+i+"]")}catch{a=i?i.split(","):[]}return a.map(o=>Rs(e,o))}return t},Ma=t=>typeof t=="string"?t.replace(" ","T"):t,Os=t=>{const e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var qt=t=>typeof t=="function"?t:function(){return t},Ba=typeof self<"u"?self:null,xt=typeof window<"u"?window:null,Ye=Ba||xt||globalThis,Ka="2.0.0",Fa=1e4,qa=1e3,Qe={connecting:0,open:1,closing:2,closed:3},Pe={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},et={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Wr={longpoll:"longpoll",websocket:"websocket"},Ha={complete:4},Gr="base64url.bearer.phx.",fr=class{constructor(t,e,r,s){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(s=>s.status===t).forEach(s=>s.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},Cs=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Wa=class{constructor(t,e,r){this.state=Pe.closed,this.topic=t,this.params=qt(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new fr(this,et.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Cs(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=Pe.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",s=>{this.state=Pe.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Pe.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=Pe.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new fr(this,et.leave,qt({}),this.timeout).send(),this.state=Pe.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(et.reply,(s,n)=>{this.trigger(this.replyEventName(n),s)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Pe.closed,this.bindings=[]}onClose(t){this.on(et.close,t)}onError(t){return this.on(et.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new fr(this,t,function(){return e},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Pe.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(et.close,"leave")},r=new fr(this,et.leave,qt({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,s){return this.topic!==t?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Pe.joining,this.joinPush.resend(t))}trigger(t,e,r,s){let n=this.onMessage(t,e,r,s);if(e&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let a=this.bindings.filter(i=>i.event===t&&this.filterBindings(i,e,r));for(let i=0;i<a.length;i++)a[i].callback(n,r,s||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===Pe.closed}isErrored(){return this.state===Pe.errored}isJoined(){return this.state===Pe.joined}isJoining(){return this.state===Pe.joining}isLeaving(){return this.state===Pe.leaving}},mr=class{static request(t,e,r,s,n,a,i){if(Ye.XDomainRequest){let o=new Ye.XDomainRequest;return this.xdomainRequest(o,t,e,s,n,a,i)}else if(Ye.XMLHttpRequest){let o=new Ye.XMLHttpRequest;return this.xhrRequest(o,t,e,r,s,n,a,i)}else{if(Ye.fetch&&Ye.AbortController)return this.fetchRequest(t,e,r,s,n,a,i);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,s,n,a,i){let o={method:t,headers:r,body:s},l=null;return n&&(l=new AbortController,setTimeout(()=>l.abort(),n),o.signal=l.signal),Ye.fetch(e,o).then(u=>u.text()).then(u=>this.parseJSON(u)).then(u=>i&&i(u)).catch(u=>{u.name==="AbortError"&&a?a():i&&i(null)}),l}static xdomainRequest(t,e,r,s,n,a,i){return t.timeout=n,t.open(e,r),t.onload=()=>{let o=this.parseJSON(t.responseText);i&&i(o)},a&&(t.ontimeout=a),t.onprogress=()=>{},t.send(s),t}static xhrRequest(t,e,r,s,n,a,i,o){t.open(e,r,!0),t.timeout=a;for(let[l,u]of Object.entries(s))t.setRequestHeader(l,u);return t.onerror=()=>o&&o(null),t.onreadystatechange=()=>{if(t.readyState===Ha.complete&&o){let l=this.parseJSON(t.responseText);o(l)}},i&&(t.ontimeout=i),t.send(n),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let n=e?`${e}[${s}]`:s,a=t[s];typeof a=="object"?r.push(this.serialize(a,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(a))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},Ga=t=>{let e="",r=new Uint8Array(t),s=r.byteLength;for(let n=0;n<s;n++)e+=String.fromCharCode(r[n]);return btoa(e)},Tt=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(Gr)&&(this.authToken=atob(e[1].slice(Gr.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=Qe.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Wr.websocket),"$1/"+Wr.longpoll)}endpointURL(){return mr.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=Qe.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Qe.open||this.readyState===Qe.connecting}poll(){const t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:s,messages:n}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=s}else r=0;switch(r){case 200:n.forEach(a=>{setTimeout(()=>this.onmessage({data:a}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=Qe.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=Ga(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
22
- `),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,r){for(let n of this.reqs)n.abort();this.readyState=Qe.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(t,e,r,s,n){let a,i=()=>{this.reqs.delete(a),s()};a=mr.request(t,this.endpointURL(),e,r,this.timeout,i,o=>{this.reqs.delete(a),this.isActive()&&n(o)}),this.reqs.add(a)}},za=class lr{constructor(e,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,n=>{let{onJoin:a,onLeave:i,onSync:o}=this.caller;this.joinRef=this.channel.joinRef(),this.state=lr.syncState(this.state,n,a,i),this.pendingDiffs.forEach(l=>{this.state=lr.syncDiff(this.state,l,a,i)}),this.pendingDiffs=[],o()}),this.channel.on(s.diff,n=>{let{onJoin:a,onLeave:i,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=lr.syncDiff(this.state,n,a,i),o())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return lr.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,s,n){let a=this.clone(e),i={},o={};return this.map(a,(l,u)=>{r[l]||(o[l]=u)}),this.map(r,(l,u)=>{let d=a[l];if(d){let h=u.metas.map(b=>b.phx_ref),m=d.metas.map(b=>b.phx_ref),p=u.metas.filter(b=>m.indexOf(b.phx_ref)<0),g=d.metas.filter(b=>h.indexOf(b.phx_ref)<0);p.length>0&&(i[l]=u,i[l].metas=p),g.length>0&&(o[l]=this.clone(d),o[l].metas=g)}else i[l]=u}),this.syncDiff(a,{joins:i,leaves:o},s,n)}static syncDiff(e,r,s,n){let{joins:a,leaves:i}=this.clone(r);return s||(s=function(){}),n||(n=function(){}),this.map(a,(o,l)=>{let u=e[o];if(e[o]=this.clone(l),u){let d=e[o].metas.map(m=>m.phx_ref),h=u.metas.filter(m=>d.indexOf(m.phx_ref)<0);e[o].metas.unshift(...h)}s(o,u,l)}),this.map(i,(o,l)=>{let u=e[o];if(!u)return;let d=l.metas.map(h=>h.phx_ref);u.metas=u.metas.filter(h=>d.indexOf(h.phx_ref)<0),n(o,u,l),u.metas.length===0&&delete e[o]}),e}static list(e,r){return r||(r=function(s,n){return n}),this.map(e,(s,n)=>r(s,n))}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static clone(e){return JSON.parse(JSON.stringify(e))}},pr={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,s,n,a,i]=JSON.parse(t);return e({join_ref:r,ref:s,topic:n,event:a,payload:i})}},binaryEncode(t){let{join_ref:e,ref:r,event:s,topic:n,payload:a}=t,i=this.META_LENGTH+e.length+r.length+n.length+s.length,o=new ArrayBuffer(this.HEADER_LENGTH+i),l=new DataView(o),u=0;l.setUint8(u++,this.KINDS.push),l.setUint8(u++,e.length),l.setUint8(u++,r.length),l.setUint8(u++,n.length),l.setUint8(u++,s.length),Array.from(e,h=>l.setUint8(u++,h.charCodeAt(0))),Array.from(r,h=>l.setUint8(u++,h.charCodeAt(0))),Array.from(n,h=>l.setUint8(u++,h.charCodeAt(0))),Array.from(s,h=>l.setUint8(u++,h.charCodeAt(0)));var d=new Uint8Array(o.byteLength+a.byteLength);return d.set(new Uint8Array(o),0),d.set(new Uint8Array(a),o.byteLength),d.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,s);case this.KINDS.reply:return this.decodeReply(t,e,s);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,s)}},decodePush(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),a=e.getUint8(3),i=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(t.slice(i,i+s));i=i+s;let l=r.decode(t.slice(i,i+n));i=i+n;let u=r.decode(t.slice(i,i+a));i=i+a;let d=t.slice(i,t.byteLength);return{join_ref:o,ref:null,topic:l,event:u,payload:d}},decodeReply(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),a=e.getUint8(3),i=e.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(o,o+s));o=o+s;let u=r.decode(t.slice(o,o+n));o=o+n;let d=r.decode(t.slice(o,o+a));o=o+a;let h=r.decode(t.slice(o,o+i));o=o+i;let m=t.slice(o,t.byteLength),p={status:h,response:m};return{join_ref:l,ref:u,topic:d,event:et.reply,payload:p}},decodeBroadcast(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),a=this.HEADER_LENGTH+2,i=r.decode(t.slice(a,a+s));a=a+s;let o=r.decode(t.slice(a,a+n));a=a+n;let l=t.slice(a,t.byteLength);return{join_ref:null,ref:null,topic:i,event:o,payload:l}}},Va=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Fa,this.transport=e.transport||Ye.WebSocket||Tt,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||Ye&&Ye.sessionStorage,this.establishedConnections=0,this.defaultEncoder=pr.encode.bind(pr),this.defaultDecoder=pr.decode.bind(pr),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==Tt?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;xt&&xt.addEventListener&&(xt.addEventListener("pagehide",s=>{this.conn&&(this.disconnect(),r=this.connectClock)}),xt.addEventListener("pageshow",s=>{r===this.connectClock&&(r=null,this.connect())}),xt.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=s=>e.rejoinAfterMs?e.rejoinAfterMs(s):[1e3,2e3,5e3][s-1]||1e4,this.reconnectAfterMs=s=>e.reconnectAfterMs?e.reconnectAfterMs(s):[10,50,100,150,200,250,500,1e3,2e3][s-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(s,n,a)=>{console.log(`${s}: ${n}`,a)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=qt(e.params||{}),this.endPoint=`${t}/${Wr.websocket}`,this.vsn=e.vsn||Ka,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Cs(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return Tt}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=mr.appendParams(mr.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=qt(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Tt?this.connectWithFallback(Tt,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let s=this.onMessage(n=>{n.ref===e&&(this.off([s]),t(Date.now()-r))});return!0}transportName(t){return t===Tt?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${Gr}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,s=!0,n,a,i=this.transportName(t),o=l=>{this.log("transport",`falling back to ${i}...`,l),this.off([n,a]),s=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${i}`))return o("memorized");this.fallbackTimer=setTimeout(o,e),a=this.onError(l=>{this.log("transport","error",l),s&&!r&&(clearTimeout(this.fallbackTimer),o(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!s){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),qa,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();const s=this.conn;this.waitForBufferDone(s,()=>{e?s.close(e,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===Qe.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(t),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport","error",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError(t)}triggerChanError(t){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(et.error,t)})}connectionState(){switch(this.conn&&this.conn.readyState){case Qe.connecting:return"connecting";case Qe.open:return"open";case Qe.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new Wa(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:s,ref:n,join_ref:a}=t;this.log("push",`${e} ${r} (${a}, ${n})`,s)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:s,payload:n,ref:a,join_ref:i}=e;if(a&&a===this.pendingHeartbeatRef){const o=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(n.status==="ok"?"ok":"error",o)}catch(l){this.log("error","error in heartbeat callback",l)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${n.status||""} ${r} ${s} ${a&&"("+a+")"||""}`.trim(),n);for(let o=0;o<this.channels.length;o++){const l=this.channels[o];l.isMember(r,s,n,i)&&l.trigger(s,n,a,i)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,s])=>{try{s(...e)}catch(n){this.log("error",`error in ${t} callback`,n)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};class Ht{constructor(e,r){const s=Ya(r);this.presence=new za(e.getChannel(),s),this.presence.onJoin((n,a,i)=>{const o=Ht.onJoinPayload(n,a,i);e.getChannel().trigger("presence",o)}),this.presence.onLeave((n,a,i)=>{const o=Ht.onLeavePayload(n,a,i);e.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return Ht.transformState(this.presence.state)}static transformState(e){return e=Ja(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{const n=e[s];return r[s]=gr(n),r},{})}static onJoinPayload(e,r,s){const n=Ns(r),a=gr(s);return{event:"join",key:e,currentPresences:n,newPresences:a}}static onLeavePayload(e,r,s){const n=Ns(r),a=gr(s);return{event:"leave",key:e,currentPresences:n,leftPresences:a}}}function gr(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function Ja(t){return JSON.parse(JSON.stringify(t))}function Ya(t){return t?.events&&{events:t.events}}function Ns(t){return t?.metas?gr(t):[]}var Is;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Is||(Is={}));class Qa{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Ht(this.channel.channelAdapter,r)}}function Xa(t){if(t instanceof Error)return t;if(typeof t=="string")return new Error(t);if(t&&typeof t=="object"){const e=t;if(typeof e.code=="number"){const r=typeof e.reason=="string"&&e.reason?` (${e.reason})`:"";return new Error(`socket closed: ${e.code}${r}`,{cause:t})}return new Error("channel error: transport failure",{cause:t})}return new Error("channel error: connection lost")}class Za{constructor(e,r,s){const n=ei(s);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,s){let n;try{n=this.channel.push(e,r,s)}catch{throw new Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>Ca){const a=this.channel.pushBuffer.shift();a.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${a.event}`,a.payload())}return n}updateJoinPayload(e){const r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===it.joined}isJoined(){return this.state===it.joined}isJoining(){return this.state===it.joining}isClosed(){return this.state===it.closed}isLeaving(){return this.state===it.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function ei(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var Ds;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Ds||(Ds={}));var jt;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(jt||(jt={}));var tt;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(tt||(tt={}));class Wt{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},s){var n,a;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new Za(this.socket.socketAdapter,e,this.params),this.presence=new Qa(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Os(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((a=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||a===void 0)&&a.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,r=this.timeout){var s,n,a;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:i,presence:o,private:l}}=this.params,u=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(p=>p.filter))!==null&&n!==void 0?n:[],d=!!this.bindings[jt.PRESENCE]&&this.bindings[jt.PRESENCE].length>0||((a=this.params.config.presence)===null||a===void 0?void 0:a.enabled)===!0,h={},m={broadcast:i,presence:Object.assign(Object.assign({},o),{enabled:d}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(p=>{e?.(tt.CHANNEL_ERROR,Xa(p))}),this._onClose(()=>e?.(tt.CLOSED)),this.updateJoinPayload(Object.assign({config:m},h)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:p})=>{if(this.socket._isManualToken()||this.socket.setAuth(),p===void 0){e?.(tt.SUBSCRIBED);return}this._updatePostgresBindings(p,e)}).receive("error",p=>{this.state=it.errored;const g=Object.values(p).join(", ")||"error";e?.(tt.CHANNEL_ERROR,new Error(g,{cause:p}))}).receive("timeout",()=>{e?.(tt.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var s;const n=this.bindings.postgres_changes,a=(s=n?.length)!==null&&s!==void 0?s:0,i=[];for(let o=0;o<a;o++){const l=n[o],{filter:{event:u,schema:d,table:h,filter:m}}=l,p=e&&e[o];if(p&&p.event===u&&Wt.isFilterValueEqual(p.schema,d)&&Wt.isFilterValueEqual(p.table,h)&&Wt.isFilterValueEqual(p.filter,m))i.push(Object.assign(Object.assign({},l),{id:p.id}));else{this.unsubscribe(),this.state=it.errored,r?.(tt.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=i,this.state!=it.errored&&r&&r(tt.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,s){const n=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),a=e===jt.PRESENCE||e===jt.POSTGRES_CHANGES;if(n&&a)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,s)}async httpSend(e,r,s={}){var n;if(r==null)return Promise.reject(new Error("Payload is required for httpSend()"));const a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);const i={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,i,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);if(o.status===202)return{success:!0};let l=o.statusText;try{const u=await o.json();l=u.error||u.message||l}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var s,n;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:a,payload:i}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const l={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:a,payload:i,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(a=>{var i,o,l;const u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(o=(i=this.params)===null||i===void 0?void 0:i.config)===null||o===void 0?void 0:o.broadcast)===null||l===void 0)&&l.ack)&&a("ok"),u.receive("ok",()=>a("ok")),u.receive("error",()=>a("error")),u.receive("timeout",()=>a("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,s){const n=new AbortController,a=setTimeout(()=>n.abort(),s),i=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(a),i}_on(e,r,s){const n=e.toLocaleLowerCase(),a=this.channelAdapter.on(e,s),i={type:n,filter:r,callback:s,ref:a};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,s)=>{var n,a,i,o,l,u,d;const h=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(h,s))return!1;const m=(n=this.bindings[h])===null||n===void 0?void 0:n.find(p=>p.ref===e.ref);if(!m)return!0;if(["broadcast","presence","postgres_changes"].includes(h))if("id"in m){const p=m.id,g=(a=m.filter)===null||a===void 0?void 0:a.event;return p&&((i=r.ids)===null||i===void 0?void 0:i.includes(p))&&(g==="*"||g?.toLocaleLowerCase()===((o=r.data)===null||o===void 0?void 0:o.type.toLocaleLowerCase()))}else{const p=(u=(l=m?.filter)===null||l===void 0?void 0:l.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return p==="*"||p===((d=r?.event)===null||d===void 0?void 0:d.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===h})}_notThisChannelEvent(e,r){const{close:s,error:n,leave:a,join:i}=Es;return r&&[s,n,a,i].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,s)=>{if(typeof r=="object"&&"ids"in r){const n=r.data,{schema:a,table:i,commit_timestamp:o,type:l,errors:u}=n;return Object.assign(Object.assign({},{schema:a,table:i,commit_timestamp:o,eventType:l,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const r in e.bindings)for(const s of e.bindings[r])this._on(s.type,s.filter,s.callback)}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Ps(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Ps(e.columns,e.old_record)),r}}class ti{constructor(e,r){this.socket=new Va(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,s,n=1e4){return new Promise(a=>{setTimeout(()=>a("timeout"),n),this.socket.disconnect(()=>{e(),a("ok")},r,s)})}push(e){this.socket.push(e)}log(e,r,s){this.socket.log(e,r,s)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==qr.connecting}isDisconnecting(){return this.socket.connectionState()==qr.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const $s={HEARTBEAT_INTERVAL:25e3},ri=[1e3,2e3,5e3,1e4],si=1e4,ni=`
19
+ Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{return this.detectEnvironment().type==="native"}catch{return!1}}}const Qi="realtime-js/2.112.4",Xi="1.0.0",$s="2.0.0",Zi=$s,ea=1e4,ta=100,ut={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Ls={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},Zr={connecting:"connecting",closing:"closing",closed:"closed"};class ra{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:{},a=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,a)}_encodeUserBroadcastPush(e,r,s){var n,i;const a=new TextEncoder,o=a.encode(e.topic),l=a.encode((n=e.ref)!==null&&n!==void 0?n:""),u=a.encode((i=e.join_ref)!==null&&i!==void 0?i:""),d=a.encode(e.payload.event),h=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},p=a.encode(Object.keys(h).length===0?"":JSON.stringify(h));if(u.length>255)throw new Error(`joinRef length ${u.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`ref length ${l.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`userEvent length ${d.length} exceeds maximum of 255`);if(p.length>255)throw new Error(`metadata length ${p.length} exceeds maximum of 255`);const m=this.USER_BROADCAST_PUSH_META_LENGTH+u.length+l.length+o.length+d.length+p.length,g=new ArrayBuffer(this.HEADER_LENGTH+m),y=new DataView(g),x=new Uint8Array(g);let v=0;y.setUint8(v++,this.KINDS.userBroadcastPush),y.setUint8(v++,u.length),y.setUint8(v++,l.length),y.setUint8(v++,o.length),y.setUint8(v++,d.length),y.setUint8(v++,p.length),y.setUint8(v++,r),x.set(u,v),v+=u.length,x.set(l,v),v+=l.length,x.set(o,v),v+=o.length,x.set(d,v),v+=d.length,x.set(p,v),v+=p.length;var _=new Uint8Array(g.byteLength+s.byteLength);return _.set(new Uint8Array(g),0),_.set(new Uint8Array(s),g.byteLength),_.buffer}decode(e,r){if(this._isArrayBuffer(e)){let s=this._binaryDecode(e);return r(s)}if(typeof e=="string"){const s=JSON.parse(e),[n,i,a,o,l]=s;return r({join_ref:n,ref:i,topic:a,event:o,payload:l})}return r({})}_binaryDecode(e){const r=new DataView(e),s=r.getUint8(0),n=new TextDecoder;if(s===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,n)}_decodeUserBroadcast(e,r,s){const n=r.getUint8(1),i=r.getUint8(2),a=r.getUint8(3),o=r.getUint8(4);let l=this.HEADER_LENGTH+4;const u=s.decode(e.slice(l,l+n));l=l+n;const d=s.decode(e.slice(l,l+i));l=l+i;const h=s.decode(e.slice(l,l+a));l=l+a;const p=e.slice(l,e.byteLength),m=o===this.JSON_ENCODING?JSON.parse(s.decode(p)):p,g={type:this.BROADCAST_EVENT,event:d,payload:m};return a>0&&(g.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:g}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([s])=>r.includes(s)))}}var Z;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(Z||(Z={}));const Ms=(t,e,r={})=>{var s;const n=(s=r.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((i,a)=>(i[a]=sa(a,t,e,n),i),{}):{}},sa=(t,e,r,s)=>{const n=e.find(o=>o.name===t),i=n?.type,a=r[t];return i&&!s.includes(i)?Us(i,a):es(a)},Us=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return oa(e,r)}switch(t){case Z.bool:return na(e);case Z.float4:case Z.float8:case Z.int2:case Z.int4:case Z.int8:case Z.numeric:case Z.oid:return ia(e);case Z.json:case Z.jsonb:return aa(e);case Z.timestamp:return la(e);case Z.abstime:case Z.date:case Z.daterange:case Z.int4range:case Z.int8range:case Z.money:case Z.reltime:case Z.text:case Z.time:case Z.timestamptz:case Z.timetz:case Z.tsrange:case Z.tstzrange:return es(e);default:return es(e)}},es=t=>t,na=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},ia=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},aa=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},oa=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,s=t[r];if(t[0]==="{"&&s==="}"){let i;const a=t.slice(1,r);try{i=JSON.parse("["+a+"]")}catch{i=a?a.split(","):[]}return i.map(o=>Us(e,o))}return t},la=t=>typeof t=="string"?t.replace(" ","T"):t,Bs=t=>{const e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var Rt=t=>typeof t=="function"?t:function(){return t},ca=typeof self<"u"?self:null,Ot=typeof window<"u"?window:null,Xe=ca||Ot||globalThis,ua="2.0.0",da=1e4,ha=1e3,fa=100,Ze={connecting:0,open:1,closing:2,closed:3},Pe={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},rt={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},ts={longpoll:"longpoll",websocket:"websocket"},ma={complete:4},rs="base64url.bearer.phx.",yr=class{constructor(t,e,r,s){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(s=>s.status===t).forEach(s=>s.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},Fs=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},pa=class{constructor(t,e,r){this.state=Pe.closed,this.topic=t,this.params=Rt(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new yr(this,rt.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Fs(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=Pe.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",s=>{this.state=Pe.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Pe.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=Pe.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new yr(this,rt.leave,Rt({}),this.timeout).send(),this.state=Pe.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(rt.reply,(s,n)=>{this.trigger(this.replyEventName(n),s)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Pe.closed,this.bindings=[]}onClose(t){this.on(rt.close,t)}onError(t){return this.on(rt.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new yr(this,t,function(){return e},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Pe.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(rt.close,"leave")},r=new yr(this,rt.leave,Rt({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,s){return this.topic!==t?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Pe.joining,this.joinPush.resend(t))}trigger(t,e,r,s){let n=this.onMessage(t,e,r,s);if(e&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let i=this.bindings.filter(a=>a.event===t&&this.filterBindings(a,e,r));for(let a=0;a<i.length;a++)i[a].callback(n,r,s||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===Pe.closed}isErrored(){return this.state===Pe.errored}isJoined(){return this.state===Pe.joined}isJoining(){return this.state===Pe.joining}isLeaving(){return this.state===Pe.leaving}},br=class{static request(t,e,r,s,n,i,a){if(Xe.XDomainRequest){let o=new Xe.XDomainRequest;return this.xdomainRequest(o,t,e,s,n,i,a)}else if(Xe.XMLHttpRequest){let o=new Xe.XMLHttpRequest;return this.xhrRequest(o,t,e,r,s,n,i,a)}else{if(Xe.fetch&&Xe.AbortController)return this.fetchRequest(t,e,r,s,n,i,a);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,s,n,i,a){let o={method:t,headers:r,body:s},l=null;return n&&(l=new AbortController,setTimeout(()=>l.abort(),n),o.signal=l.signal),Xe.fetch(e,o).then(u=>u.text()).then(u=>this.parseJSON(u)).then(u=>a&&a(u)).catch(u=>{u.name==="AbortError"&&i?i():a&&a(null)}),l}static xdomainRequest(t,e,r,s,n,i,a){return t.timeout=n,t.open(e,r),t.onload=()=>{let o=this.parseJSON(t.responseText);a&&a(o)},i&&(t.ontimeout=i),t.onprogress=()=>{},t.send(s),t}static xhrRequest(t,e,r,s,n,i,a,o){t.open(e,r,!0),t.timeout=i;for(let[l,u]of Object.entries(s))t.setRequestHeader(l,u);return t.onerror=()=>o&&o(null),t.onreadystatechange=()=>{if(t.readyState===ma.complete&&o){let l=this.parseJSON(t.responseText);o(l)}},a&&(t.ontimeout=a),t.send(n),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let n=e?`${e}[${s}]`:s,i=t[s];typeof i=="object"?r.push(this.serialize(i,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},ga=t=>{let e="",r=new Uint8Array(t),s=r.byteLength;for(let n=0;n<s;n++)e+=String.fromCharCode(r[n]);return btoa(e)},Ct=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(rs)&&(this.authToken=atob(e[1].slice(rs.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=Ze.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+ts.websocket),"$1/"+ts.longpoll)}endpointURL(){return br.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=Ze.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Ze.open||this.readyState===Ze.connecting}poll(){const t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:s,messages:n}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=s}else r=0;switch(r){case 200:n.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=Ze.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=ga(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t,e=0){this.awaitingBatchAck=!0;const r=e+fa,s=t.slice(e,r);this.ajax("POST",{"Content-Type":"application/x-ndjson"},s.join(`
20
+ `),()=>this.onerror("timeout"),n=>{!n||n.status!==200?(this.awaitingBatchAck=!1,this.onerror(n&&n.status),this.closeAndRetry(1011,"internal server error",!1)):r<t.length?this.batchSend(t,r):this.batchBuffer.length>0?(this.batchSend(this.batchBuffer),this.batchBuffer=[]):this.awaitingBatchAck=!1})}close(t,e,r){for(let n of this.reqs)n.abort();this.readyState=Ze.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(t,e,r,s,n){let i,a=()=>{this.reqs.delete(i),s()};i=br.request(t,this.endpointURL(),e,r,this.timeout,a,o=>{this.reqs.delete(i),this.isActive()&&n(o)}),this.reqs.add(i)}},ya=class fr{constructor(e,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state=Object.create(null),this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,n=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.joinRef=this.channel.joinRef(),this.state=fr.syncState(this.state,n,i,a),this.pendingDiffs.forEach(l=>{this.state=fr.syncDiff(this.state,l,i,a)}),this.pendingDiffs=[],o()}),this.channel.on(s.diff,n=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=fr.syncDiff(this.state,n,i,a),o())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return fr.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,s,n){let i=this.toNullProtoObj(this.clone(e));r=this.toNullProtoObj(r);let a=Object.create(null),o=Object.create(null);return this.map(i,(l,u)=>{r[l]||(o[l]=u)}),this.map(r,(l,u)=>{let d=i[l];if(d){let h=u.metas.map(y=>y.phx_ref),p=d.metas.map(y=>y.phx_ref),m=u.metas.filter(y=>p.indexOf(y.phx_ref)<0),g=d.metas.filter(y=>h.indexOf(y.phx_ref)<0);m.length>0&&(a[l]=u,a[l].metas=m),g.length>0&&(o[l]=this.clone(d),o[l].metas=g)}else a[l]=u}),this.syncDiff(i,{joins:a,leaves:o},s,n)}static syncDiff(e,r,s,n){e=this.toNullProtoObj(e);let{joins:i,leaves:a}=this.clone(r);return s||(s=function(){}),n||(n=function(){}),this.map(i,(o,l)=>{let u=e[o];if(e[o]=this.clone(l),u){let d=e[o].metas.map(p=>p.phx_ref),h=u.metas.filter(p=>d.indexOf(p.phx_ref)<0);e[o].metas.unshift(...h)}s(o,u,l)}),this.map(a,(o,l)=>{let u=e[o];if(!u)return;let d=l.metas.map(h=>h.phx_ref);u.metas=u.metas.filter(h=>d.indexOf(h.phx_ref)<0),n(o,u,l),u.metas.length===0&&delete e[o]}),e}static list(e,r){return r||(r=function(s,n){return n}),this.map(e,(s,n)=>r(s,n))}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static toNullProtoObj(e){if(Object.getPrototypeOf(e)===null)return e;let r=Object.create(null);return Object.getOwnPropertyNames(e).forEach(s=>{r[s]=e[s]}),r}static clone(e){return JSON.parse(JSON.stringify(e))}},vr={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,s,n,i,a]=JSON.parse(t);return e({join_ref:r,ref:s,topic:n,event:i,payload:a})}},binaryEncode(t){let{join_ref:e,ref:r,event:s,topic:n,payload:i}=t,a=new TextEncoder,o=a.encode(e),l=a.encode(r),u=a.encode(n),d=a.encode(s);this.assertFieldSize(o.byteLength,"join_ref"),this.assertFieldSize(l.byteLength,"ref"),this.assertFieldSize(u.byteLength,"topic"),this.assertFieldSize(d.byteLength,"event");let h=this.META_LENGTH+o.byteLength+l.byteLength+u.byteLength+d.byteLength,p=new ArrayBuffer(this.HEADER_LENGTH+h),m=new Uint8Array(p),g=new DataView(p),y=0;g.setUint8(y++,this.KINDS.push),g.setUint8(y++,o.byteLength),g.setUint8(y++,l.byteLength),g.setUint8(y++,u.byteLength),g.setUint8(y++,d.byteLength),m.set(o,y),y+=o.byteLength,m.set(l,y),y+=l.byteLength,m.set(u,y),y+=u.byteLength,m.set(d,y),y+=d.byteLength;var x=new Uint8Array(p.byteLength+i.byteLength);return x.set(m,0),x.set(new Uint8Array(i),p.byteLength),x.buffer},assertFieldSize(t,e){if(t>255)throw new Error(`unable to convert ${e} to binary: must be less than or equal to 255 bytes, but is ${t} bytes`)},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,s);case this.KINDS.reply:return this.decodeReply(t,e,s);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,s)}},decodePush(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(t.slice(a,a+s));a=a+s;let l=r.decode(t.slice(a,a+n));a=a+n;let u=r.decode(t.slice(a,a+i));a=a+i;let d=t.slice(a,t.byteLength);return{join_ref:o,ref:null,topic:l,event:u,payload:d}},decodeReply(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),a=e.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(o,o+s));o=o+s;let u=r.decode(t.slice(o,o+n));o=o+n;let d=r.decode(t.slice(o,o+i));o=o+i;let h=r.decode(t.slice(o,o+a));o=o+a;let p=t.slice(o,t.byteLength),m={status:h,response:p};return{join_ref:l,ref:u,topic:d,event:rt.reply,payload:m}},decodeBroadcast(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=this.HEADER_LENGTH+2,a=r.decode(t.slice(i,i+s));i=i+s;let o=r.decode(t.slice(i,i+n));i=i+n;let l=t.slice(i,t.byteLength);return{join_ref:null,ref:null,topic:a,event:o,payload:l}}},ba=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||da,this.transport=e.transport||Xe.WebSocket||Ct,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null;let r=null;try{r=Xe&&Xe.sessionStorage}catch{}this.sessionStore=e.sessionStorage||r,this.establishedConnections=0,this.defaultEncoder=vr.encode.bind(vr),this.defaultDecoder=vr.decode.bind(vr),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==Ct?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let s=null;Ot&&Ot.addEventListener&&(Ot.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),s=this.connectClock)}),Ot.addEventListener("pageshow",n=>{s===this.connectClock&&(s=null,this.connect())}),Ot.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(n,i,a)=>{console.log(`${n}: ${i}`,a)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Rt(e.params||{}),this.endPoint=`${t}/${ts.websocket}`,this.vsn=e.vsn||ua,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Fs(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken&&Rt(e.authToken)}getLongPollTransport(){return Ct}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=br.appendParams(br.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Rt(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Ct?this.connectWithFallback(Ct,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let s=this.onMessage(n=>{n.ref===e&&(this.off([s]),t(Date.now()-r))});return!0}transportName(t){return t===Ct?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${rs}${btoa(this.authToken()).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,s=!0,n,i,a=this.transportName(t),o=l=>{this.log("transport",`falling back to ${a}...`,l),this.off([n,i]),s=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${a}`))return o("memorized");this.fallbackTimer=setTimeout(o,e),i=this.onError(l=>{this.log("transport","error",l),s&&!r&&(clearTimeout(this.fallbackTimer),o(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!s){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),ha,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();const s=this.conn;this.waitForBufferDone(s,()=>{e?s.close(e,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===Ze.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(t),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport","error",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError(t)}triggerChanError(t){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(rt.error,t)})}connectionState(){switch(this.conn&&this.conn.readyState){case Ze.connecting:return"connecting";case Ze.open:return"open";case Ze.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new pa(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:s,ref:n,join_ref:i}=t;this.log("push",`${e} ${r} (${i}, ${n})`,s)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:s,payload:n,ref:i,join_ref:a}=e;if(i&&i===this.pendingHeartbeatRef){const o=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(n.status==="ok"?"ok":"error",o)}catch(l){this.log("error","error in heartbeat callback",l)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${n.status||""} ${r} ${s} ${i&&"("+i+")"||""}`.trim(),n);for(let o=0;o<this.channels.length;o++){const l=this.channels[o];l.isMember(r,s,n,a)&&l.trigger(s,n,i,a)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,s])=>{try{s(...e)}catch(n){this.log("error",`error in ${t} callback`,n)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};class zt{constructor(e,r){const s=wa(r);this.presence=new ya(e.getChannel(),s),this.presence.onJoin((n,i,a)=>{const o=zt.onJoinPayload(n,i,a);e.getChannel().trigger("presence",o)}),this.presence.onLeave((n,i,a)=>{const o=zt.onLeavePayload(n,i,a);e.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return zt.transformState(this.presence.state)}static transformState(e){return e=va(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{const n=e[s];return r[s]=wr(n),r},{})}static onJoinPayload(e,r,s){const n=Ks(r),i=wr(s);return{event:"join",key:e,currentPresences:n,newPresences:i}}static onLeavePayload(e,r,s){const n=Ks(r),i=wr(s);return{event:"leave",key:e,currentPresences:n,leftPresences:i}}}function wr(t){return t.metas.map(e=>{const r=Object.getOwnPropertyDescriptors(e),s=Object.defineProperties({},r);return s.presence_ref=s.phx_ref,delete s.phx_ref,delete s.phx_ref_prev,s})}function va(t){return JSON.parse(JSON.stringify(t))}function wa(t){return t?.events&&{events:t.events}}function Ks(t){return t?.metas?wr(t):[]}var qs;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(qs||(qs={}));class _a{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new zt(this.channel.channelAdapter,r)}}function ka(t){if(t instanceof Error)return t;if(typeof t=="string")return new Error(t);if(t&&typeof t=="object"){const e=t;if(typeof e.code=="number"){const r=typeof e.reason=="string"&&e.reason?` (${e.reason})`:"";return new Error(`socket closed: ${e.code}${r}`,{cause:t})}return new Error("channel error: transport failure",{cause:t})}return new Error("channel error: connection lost")}class Sa{constructor(e,r,s){const n=xa(s);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,s){let n;try{n=this.channel.push(e,r,s)}catch{throw new Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>ta){const i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return n}updateJoinPayload(e){const r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===ut.joined}isJoined(){return this.state===ut.joined}isJoining(){return this.state===ut.joining}isClosed(){return this.state===ut.closed}isLeaving(){return this.state===ut.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function xa(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}const Ta=/[,()"\\]/,Ea=t=>Ta.test(t)||t!==t.trim(),ja=t=>`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,Ws=t=>{const e=t===null?"null":String(t);return Ea(e)?ja(e):e},Aa=t=>t===null?"null":String(t),Pa=(t,e)=>{if(t==="in"){const r=Array.isArray(e)?e:[e];if(r.length===0)throw new Error("Realtime `in` filter requires at least one value.");return`in.(${Array.from(new Set(r)).map(n=>Ws(n)).join(",")})`}return t==="is"?`is.${Aa(e)}`:`${t}.${Ws(e)}`};class Ra{constructor(){this.filters=[]}add(e,r,s,n=!1){const i=n?"not.":"";return this.filters.push(`${e}=${i}${Pa(r,s)}`),this}eq(e,r){return this.add(e,"eq",r)}neq(e,r){return this.add(e,"neq",r)}gt(e,r){return this.add(e,"gt",r)}gte(e,r){return this.add(e,"gte",r)}lt(e,r){return this.add(e,"lt",r)}lte(e,r){return this.add(e,"lte",r)}in(e,r){return this.add(e,"in",r)}like(e,r){return this.add(e,"like",r)}ilike(e,r){return this.add(e,"ilike",r)}match(e,r){return this.add(e,"match",r)}imatch(e,r){return this.add(e,"imatch",r)}is(e,r){return this.add(e,"is",r)}isDistinct(e,r){return this.add(e,"isdistinct",r)}not(e,r,s){return this.add(e,r,s,!0)}build(){return this.filters.join(",")}toString(){return this.build()}}var Hs;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Hs||(Hs={}));var yt;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(yt||(yt={}));var st;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(st||(st={}));class nt{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},s){var n,i;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new Sa(this.socket.socketAdapter,e,this.params),this.presence=new _a(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Bs(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===void 0)&&i.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,r=this.timeout){var s,n,i;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:a,presence:o,private:l}}=this.params,u=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(m=>m.filter))!==null&&n!==void 0?n:[],d=!!this.bindings[yt.PRESENCE]&&this.bindings[yt.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,h={},p={broadcast:a,presence:Object.assign(Object.assign({},o),{enabled:d}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(m=>{e?.(st.CHANNEL_ERROR,ka(m))}),this._onClose(()=>e?.(st.CLOSED)),this.updateJoinPayload(Object.assign({config:p},h)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:m})=>{if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){e?.(st.SUBSCRIBED);return}this._updatePostgresBindings(m,e)}).receive("error",m=>{this.state=ut.errored;const g=Object.values(m).join(", ")||"error";e?.(st.CHANNEL_ERROR,new Error(g,{cause:m}))}).receive("timeout",()=>{e?.(st.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var s;const n=this.bindings.postgres_changes,i=(s=n?.length)!==null&&s!==void 0?s:0,a=[];for(let o=0;o<i;o++){const l=n[o],{filter:{event:u,schema:d,table:h,filter:p}}=l,m=e&&e[o];if(m&&m.event===u&&nt.isFilterValueEqual(m.schema,d)&&nt.isFilterValueEqual(m.table,h)&&nt.isFilterValueEqual(m.filter,p))a.push(Object.assign(Object.assign({},l),{id:m.id}));else{this.unsubscribe(),this.state=ut.errored,r?.(st.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=a,this.state!=ut.errored&&r&&r(st.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,s){const n=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===yt.PRESENCE||e===yt.POSTGRES_CHANGES;if(n&&i)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,s)}async httpSend(e,r,s={}){var n;if(r==null)return Promise.reject(new Error("Payload is required for httpSend()"));const i=r instanceof ArrayBuffer||ArrayBuffer.isView(r),a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":i?"application/octet-stream":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);const o=new URL(this.broadcastEndpointURL);o.pathname+=`/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(e)}`,this.private&&o.searchParams.set("private","true");const l={method:"POST",headers:a,body:i?r:JSON.stringify(r)},u=await this._fetchWithTimeout(o.toString(),l,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);if(u.status===202)return{success:!0};if(u.status===404)return Promise.reject(new Error("httpSend() requires Realtime server v2.97.0 or newer; the endpoint returned 404. Update your Supabase CLI to a recent version, or upgrade the Realtime server in your self-hosted setup. See https://github.com/supabase/supabase-js/blob/master/packages/core/realtime-js/migrations/httpsend-server-version.md"));let d=u.statusText;try{const h=await u.json();d=h.error||h.message||d}catch{}return Promise.reject(new Error(d))}async send(e,r={}){var s,n;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){const i="Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.";this.socket.hasLogger()?this.socket.log("channel",i):console.warn(i);const{event:a,payload:o}=e,l={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(l.Authorization=`Bearer ${this.socket.accessTokenValue}`);const u={method:"POST",headers:l,body:JSON.stringify({messages:[{topic:this.subTopic,event:a,payload:o,private:this.private}]})};try{const d=await this._fetchWithTimeout(this.broadcastEndpointURL,u,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=d.body)===null||n===void 0?void 0:n.cancel()),d.ok?"ok":"error"}catch(d){return d instanceof Error&&d.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var a,o,l;const u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(o=(a=this.params)===null||a===void 0?void 0:a.config)===null||o===void 0?void 0:o.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),u.receive("ok",()=>i("ok")),u.receive("error",()=>i("error")),u.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,s){const n=new AbortController,i=setTimeout(()=>n.abort(),s),a=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(i),a}_on(e,r,s){var n;const i=e.toLocaleLowerCase(),a=r?.filter;if((a instanceof Ra||typeof a=="object"&&a!==null&&typeof a.build=="function")&&(r=Object.assign(Object.assign({},r),{filter:a.build()})),i===yt.POSTGRES_CHANGES&&((n=this.bindings[i])===null||n===void 0?void 0:n.find(d=>nt.isSamePostgresFilter(d.filter,r))))return this.socket.log("error",`duplicate \`postgres_changes\` binding for ${this.topic} ignored`,r),this;const o=this.channelAdapter.on(e,s),l={type:i,filter:r,callback:s,ref:o};return this.bindings[i]?this.bindings[i].push(l):this.bindings[i]=[l],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,s)=>{var n,i,a,o,l,u,d;const h=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(h,s))return!1;const p=(n=this.bindings[h])===null||n===void 0?void 0:n.find(m=>m.ref===e.ref);if(!p)return!0;if(["broadcast","presence","postgres_changes"].includes(h))if("id"in p){const m=p.id,g=(i=p.filter)===null||i===void 0?void 0:i.event;return m&&((a=r.ids)===null||a===void 0?void 0:a.includes(m))&&(g==="*"||g?.toLocaleLowerCase()===((o=r.data)===null||o===void 0?void 0:o.type.toLocaleLowerCase()))}else{const m=(u=(l=p?.filter)===null||l===void 0?void 0:l.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return m==="*"||m===((d=r?.event)===null||d===void 0?void 0:d.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===h})}_notThisChannelEvent(e,r){const{close:s,error:n,leave:i,join:a}=Ls;return r&&[s,n,i,a].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,s)=>{if(typeof r=="object"&&"ids"in r){const n=r.data,{schema:i,table:a,commit_timestamp:o,type:l,errors:u}=n;return Object.assign(Object.assign({},{schema:i,table:a,commit_timestamp:o,eventType:l,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const r in e.bindings)for(const s of e.bindings[r])this._on(s.type,s.filter,s.callback)}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}static isSamePostgresFilter(e,r){var s,n,i,a;const o=(n=(s=e?.select)===null||s===void 0?void 0:s.join())!==null&&n!==void 0?n:void 0,l=(a=(i=r?.select)===null||i===void 0?void 0:i.join())!==null&&a!==void 0?a:void 0;return e?.event===r?.event&&nt.isFilterValueEqual(e?.schema,r?.schema)&&nt.isFilterValueEqual(e?.table,r?.table)&&nt.isFilterValueEqual(e?.filter,r?.filter)&&o===l}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Ms(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Ms(e.columns,e.old_record)),r}}class Oa{constructor(e,r){this.socket=new ba(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,s,n=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),n),this.socket.disconnect(()=>{e(),i("ok")},r,s)})}push(e){this.socket.push(e)}log(e,r,s){this.socket.log(e,r,s)}hasLogger(){return this.socket.hasLogger()}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Zr.connecting}isDisconnecting(){return this.socket.connectionState()==Zr.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const Gs={HEARTBEAT_INTERVAL:25e3},Ca=[1e3,2e3,5e3,1e4],Na=1e4;function Ia(){const t=new Map;return{get length(){return t.size},clear(){t.clear()},getItem(e){return t.has(e)?t.get(e):null},key(e){var r;return(r=Array.from(t.keys())[e])!==null&&r!==void 0?r:null},removeItem(e){t.delete(e)},setItem(e,r){t.set(e,String(r))}}}function Da(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return Ia()}const $a=`
23
21
  addEventListener("message", (e) => {
24
22
  if (e.data.event === "start") {
25
23
  setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
26
24
  }
27
- });`;class ai{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var s;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new Na,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=a=>a?(...i)=>a(...i):(...i)=>fetch(...i),!(!((s=r?.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;const n=this._initializeOptions(r);this.socketAdapter=new ti(e,n),this.httpEndpoint=Os(e),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){const r=e.message;throw r.includes("Node.js")?new Error(`${r}
25
+ });`;class La{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var s;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new ra,this._manuallySetToken=!1,this._authPromise=null,this._authGeneration=0,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=i=>i?(...a)=>i(...a):(...a)=>fetch(...a),!(!((s=r?.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;const n=this._initializeOptions(r);this.socketAdapter=new Oa(e,n),this.httpEndpoint=Bs(e),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){const r=e.message;throw new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return r==="ok"&&e.teardown(),r}async removeAllChannels(){const e=this.channels.map(async s=>{const n=await s.unsubscribe();return s.teardown(),n}),r=await Promise.all(e);return await this.disconnect(),r}log(e,r,s){this.socketAdapter.log(e,r,s)}hasLogger(){return this.socketAdapter.hasLogger()}connectionState(){return this.socketAdapter.connectionState()||Zr.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){const s=`realtime:${e}`,n=this.getChannels().find(i=>i.topic===s);if(n)return n;{const i=new nt(`realtime:${e}`,r,this);return this._cancelPendingDisconnect(),this.channels.push(i),i}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){const r=++this._authGeneration,s=this._performAuth(e,r);r===this._authGeneration&&(this._authPromise=s);try{await s}finally{this._authPromise===s&&(this._authPromise=null)}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic),this.channels.length===0&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e,r){let s,n=!1;if(e)s=e,n=!0;else if(this.accessToken)try{s=await this.accessToken()}catch(i){this.log("error","Error fetching access token from callback",i),s=this.accessTokenValue}else s=this.accessTokenValue;r===this._authGeneration&&(this.accessToken?this._manuallySetToken=!1:n&&(this._manuallySetToken=!0),this.accessTokenValue!=s&&(this.accessTokenValue=s,this.channels.forEach(i=>{const a={access_token:s,version:Qi};i.updateJoinPayload(a),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push(Ls.access_token,{access_token:s})})))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,s)=>{r!=="disconnected"&&(r=="sent"&&this._setAuthSafely(),e&&e(r,s))}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{const s=new Blob([$a],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_initializeOptions(e){var r,s,n,i,a,o,l,u,d,h,p,m;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(s=e?.accessToken)!==null&&s!==void 0?s:null;const g={};g.timeout=(n=e?.timeout)!==null&&n!==void 0?n:ea,g.heartbeatIntervalMs=(i=e?.heartbeatIntervalMs)!==null&&i!==void 0?i:Gs.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(a=e?.disconnectOnEmptyChannelsAfterMs)!==null&&a!==void 0?a:2*((o=e?.heartbeatIntervalMs)!==null&&o!==void 0?o:Gs.HEARTBEAT_INTERVAL),g.transport=(l=e?.transport)!==null&&l!==void 0?l:Yi.getWebSocketConstructor(),g.params=e?.params,g.logger=e?.logger,g.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),g.sessionStorage=(u=e?.sessionStorage)!==null&&u!==void 0?u:Da(),g.reconnectAfterMs=(d=e?.reconnectAfterMs)!==null&&d!==void 0?d:(_=>Ca[_-1]||Na);let y,x;const v=(h=e?.vsn)!==null&&h!==void 0?h:Zi;switch(v){case Xi:y=(_,k)=>k(JSON.stringify(_)),x=(_,k)=>k(JSON.parse(_));break;case $s:y=this.serializer.encode.bind(this.serializer),x=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${g.vsn}`)}if(g.vsn=v,g.encode=(p=e?.encode)!==null&&p!==void 0?p:y,g.decode=(m=e?.decode)!==null&&m!==void 0?m:x,g.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,g.params=Object.assign(Object.assign({},g.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,g.autoSendHeartbeat=!this.worker}return g}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var Vt=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Ma(t,e,r){const s=new URL(e,t);if(r)for(const[n,i]of Object.entries(r))i!==void 0&&s.searchParams.set(n,i);return s.toString()}async function Ua(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function Ba(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:a}){const o=Ma(t.baseUrl,s,n),l=await Ua(t.auth),u=await e(o,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...a},body:i?JSON.stringify(i):void 0}),d=await u.text(),h=(u.headers.get("content-type")||"").includes("application/json"),p=h&&d?JSON.parse(d):d;if(!u.ok){const m=h?p:void 0,g=m?.error;throw new Vt(g?.message??`Request failed with status ${u.status}`,{status:u.status,icebergType:g?.type,icebergCode:g?.code,details:m})}return{status:u.status,headers:u.headers,data:p}}}}function _r(t){return t.join("")}var Fa=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:_r(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(s=>({namespace:s}))}async createNamespace(t,e){const r={namespace:t.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${_r(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${_r(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${_r(t.namespace)}`}),!0}catch(e){if(e instanceof Vt&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof Vt&&r.status===409)return;throw r}}};function Nt(t){return t.join("")}var Ka=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Nt(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){const r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Nt(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Nt(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Nt(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(t){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Nt(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Nt(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof Vt&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof Vt&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},qa=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Ba({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new Fa(this.client,e),this.tableOps=new Ka(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};function Jt(t){"@babel/helpers - typeof";return Jt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Jt(t)}function Wa(t,e){if(Jt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(Jt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ha(t){var e=Wa(t,"string");return Jt(e)=="symbol"?e:e+""}function Ga(t,e,r){return(e=Ha(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function zs(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function C(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?zs(Object(r),!0).forEach(function(s){Ga(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):zs(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var kr=class extends Error{constructor(t,e="storage",r,s){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function Sr(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var ss=class extends kr{constructor(t,e,r,s="storage",n){super(t,s,e,r),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r,this.code=n}toJSON(){return C(C({},super.toJSON()),{},{code:this.code})}},Vs=class extends kr{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};function xr(t,e,r){const s=C({},t),n=e.toLowerCase();for(const i of Object.keys(s))i.toLowerCase()===n&&delete s[i];return s[n]=r,s}function za(t){const e={};for(const[r,s]of Object.entries(t))e[r.toLowerCase()]=s;return e}const Va=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ja=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},ns=t=>{if(Array.isArray(t))return t.map(r=>ns(r));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([r,s])=>{const n=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[n]=ns(s)}),e},Ya=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),Js=t=>t.split("/").map(encodeURIComponent).join("/"),Ys=t=>{if(typeof t=="object"&&t!==null){const e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){const r=e.error;if(typeof r.message=="string")return r.message}}return JSON.stringify(t)},Qa=async(t,e,r,s)=>{if(t!==null&&typeof t=="object"&&"json"in t&&typeof t.json=="function"){const n=t;let i=parseInt(String(n.status),10);Number.isFinite(i)||(i=500),n.json().then(a=>{const o=a?.statusCode||a?.code||i+"";e(new ss(Ys(a),i,o,s,a?.code))}).catch(()=>{const a=i+"";e(new ss(n.statusText||`HTTP ${i} error`,i,a,s))})}else e(new Vs(Ys(t),t,s))},Xa=(t,e,r,s)=>{const n={method:t,headers:e?.headers||{}};if(t==="GET"||t==="HEAD"||!s)return C(C({},n),r);if(Ja(s)){var i;const a=e?.headers||{};let o;for(const[l,u]of Object.entries(a))l.toLowerCase()==="content-type"&&(o=u);n.headers=xr(a,"Content-Type",(i=o)!==null&&i!==void 0?i:"application/json"),n.body=JSON.stringify(s)}else n.body=s;return e?.duplex&&(n.duplex=e.duplex),C(C({},n),r)};async function Yt(t,e,r,s,n,i,a){return new Promise((o,l)=>{t(r,Xa(e,s,n,i)).then(u=>{if(!u.ok)throw u;if(s?.noResolveJson)return u;if(a==="vectors"){const d=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!d||!d.includes("application/json"))return{}}return u.json()}).then(u=>o(u)).catch(u=>Qa(u,l,s,a))})}function Qs(t="storage"){return{get:async(e,r,s,n)=>Yt(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,i)=>Yt(e,"POST",r,n,i,s,t),put:async(e,r,s,n,i)=>Yt(e,"PUT",r,n,i,s,t),head:async(e,r,s,n)=>Yt(e,"HEAD",r,C(C({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,i)=>Yt(e,"DELETE",r,n,i,s,t)}}const Za=Qs("storage"),{get:Qt,post:ze,put:is,head:eo,remove:Xt}=Za,De=Qs("vectors");var It=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=za(e),this.fetch=Va(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=xr(this.headers,t,e),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(Sr(r))return{data:null,error:r};throw r}}};let Xs;Xs=Symbol.toStringTag;var to=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Xs]="StreamDownloadBuilder",this.promise=null}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Sr(e))return{data:null,error:e};throw e}}};let Zs;Zs=Symbol.toStringTag;var ro=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Zs]="BlobDownloadBuilder",this.promise=null}asStream(){return new to(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Sr(e))return{data:null,error:e};throw e}}};const as={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},en={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var so=class extends It{constructor(t,e={},r,s){super(t,e,s,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,s){var n=this;return n.handleOperation(async()=>{let i;const a=C(C({},en),s);let o=C(C({},n.headers),t==="POST"&&{"x-upsert":String(a.upsert)});const l=a.metadata;if(typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),l&&i.append("metadata",n.encodeMetadata(l)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",a.cacheControl),l&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(l))):(i=r,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!a.duplex&&(a.duplex="half")),s?.headers)for(const[p,m]of Object.entries(s.headers))o=xr(o,p,m);const u=n._removeEmptyFolders(e),d=n._getFinalPath(u),h=await(t=="PUT"?is:ze)(n.fetch,`${n.url}/object/${d}`,i,C({headers:o},a?.duplex?{duplex:a.duplex}:{}));return{path:u,id:h.Id,fullPath:h.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,s){var n=this;const i=n._removeEmptyFolders(t),a=n._getFinalPath(i),o=new URL(n.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",e),n.handleOperation(async()=>{let l;const u=C(C({},en),s);let d=C(C({},n.headers),{"x-upsert":String(u.upsert)});const h=u.metadata;if(typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),h&&l.append("metadata",n.encodeMetadata(h)),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.has("cacheControl")||l.append("cacheControl",u.cacheControl),h&&!l.has("metadata")&&l.append("metadata",n.encodeMetadata(h))):(l=r,d["cache-control"]=`max-age=${u.cacheControl}`,d["content-type"]=u.contentType,h&&(d["x-metadata"]=n.toBase64(n.encodeMetadata(h))),(typeof ReadableStream<"u"&&l instanceof ReadableStream||l&&typeof l=="object"&&"pipe"in l&&typeof l.pipe=="function")&&!u.duplex&&(u.duplex="half")),s?.headers)for(const[p,m]of Object.entries(s.headers))d=xr(d,p,m);return{path:i,fullPath:(await is(n.fetch,o.toString(),l,C({headers:d},u?.duplex?{duplex:u.duplex}:{}))).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t);const n=C({},r.headers);e?.upsert&&(n["x-upsert"]="true");const i=await ze(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),a=new URL(r.url+i.url),o=a.searchParams.get("token");if(!o)throw new kr("No token returned by API");return{signedUrl:a.toString(),path:t,token:o}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var s=this;return s.handleOperation(async()=>await ze(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:s.headers}))}async copy(t,e,r){var s=this;return s.handleOperation(async()=>({path:(await ze(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(t,e,r){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(t);const i=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0;let a=await ze(s.fetch,`${s.url}/object/sign/${n}`,C({expiresIn:e},i?{transform:r.transform}:{}),{headers:s.headers});const o=new URLSearchParams;r?.download&&o.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&o.set("cacheNonce",String(r.cacheNonce));const l=o.toString();return{signedUrl:encodeURI(`${s.url}${a.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{const n=await ze(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:t},{headers:s.headers}),i=new URLSearchParams;r?.download&&i.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&i.set("cacheNonce",String(r.cacheNonce));const a=i.toString();return n.map(o=>C(C({},o),{},{signedUrl:o.signedURL?encodeURI(`${s.url}${o.signedURL}${a?`&${a}`:""}`):null}))})}download(t,e,r){const s=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",n=new URLSearchParams;e?.transform&&this.applyTransformOptsToQuery(n,e.transform),e?.cacheNonce!=null&&n.set("cacheNonce",String(e.cacheNonce));const i=n.toString(),a=this._getFinalPath(t),o=()=>Qt(this.fetch,`${this.url}/${s}/${a}${i?`?${i}`:""}`,{headers:this.headers,noResolveJson:!0},r);return new ro(o,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>ns(await Qt(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await eo(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(Sr(n)){var s;const i=n instanceof ss?n.status:n instanceof Vs?(s=n.originalError)===null||s===void 0?void 0:s.status:void 0;if(i!==void 0&&[400,404].includes(i))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){const r=this._getFinalPath(t),s=new URLSearchParams;e?.download&&s.set("download",e.download===!0?"":e.download),e?.transform&&this.applyTransformOptsToQuery(s,e.transform),e?.cacheNonce!=null&&s.set("cacheNonce",String(e.cacheNonce));const n=s.toString(),i=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}`)+(n?`?${n}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await Xt(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async purgeCache(t,e,r){var s=this;return s.handleOperation(async()=>{const n=Js(s._getFinalPath(t)),i=new URLSearchParams;e?.transformations&&i.set("transformations","true");const a=i.toString();return await Xt(s.fetch,`${s.url}/cdn/${n}${a?`?${a}`:""}`,{},{headers:s.headers},r)})}async list(t,e,r){var s=this;return s.handleOperation(async()=>{const n=e?.sortBy?C(C({},as.sortBy),e.sortBy):as.sortBy,i=C(C(C({},as),e),{},{sortBy:n,prefix:t||""});return await ze(s.fetch,`${s.url}/object/list/${s.bucketId}`,i,{headers:s.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{const s=C({},t);return await ze(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("quality",e.quality.toString()),t}};const Zt={"X-Client-Info":"storage-js/2.112.4"};var no=class extends It{constructor(t,e={},r,s){const n=new URL(t);s?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));const i=n.href.replace(/\/$/,""),a=C(C({},Zt),e);super(i,a,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await Qt(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Qt(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await ze(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await is(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await ze(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Xt(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}async purgeBucketCache(t,e,r){var s=this;return s.handleOperation(async()=>{const n=new URLSearchParams;e?.transformations&&n.set("transformations","true");const i=n.toString();return await Xt(s.fetch,`${s.url}/cdn/${Js(t)}${i?`?${i}`:""}`,{},{headers:s.headers},r)})}listBucketOptionsToQueryString(t){const e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},io=class extends It{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},Zt),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await ze(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);const s=r.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await Qt(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Xt(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!Ya(t))throw new kr("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new qa({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(n,i){const a=n[i];return typeof a!="function"?a:async(...o)=>{try{return{data:await a.apply(n,o),error:null}}catch(l){if(s)throw l;return{data:null,error:l}}}}})}},ao=class extends It{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},Zt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await De.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await De.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},oo=class extends It{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},Zt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},lo=class extends It{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},Zt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},co=class extends lo{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new uo(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},uo=class extends ao{constructor(t,e,r,s){super(t,e,s),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new ho(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},ho=class extends oo{constructor(t,e,r,s,n){super(t,e,n),this.vectorBucketName=r,this.indexName=s}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},fo=class extends no{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new so(this.url,this.headers,t,this.fetch)}get vectors(){return new co(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new io(this.url+"/iceberg",this.headers,this.fetch)}};const tn="2.112.4",it=30*1e3,er=3,os=er*it,mo=2*it,po="http://localhost:9999",go="supabase.auth.token",yo={"X-Client-Info":`gotrue-js/${tn}`},ls="X-Supabase-Api-Version",rn={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},bo=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,bt="sb_flow_id",vo=5,wo=600*1e3;class tr extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function T(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class _o extends tr{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}}function sn(t){return T(t)&&t.name==="AuthApiError"}class Ve extends tr{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class et extends tr{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}}class be extends et{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Tr(t){return T(t)&&t.name==="AuthSessionMissingError"}class Dt extends et{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Er extends et{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class jr extends et{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}function ko(t){return T(t)&&t.name==="AuthImplicitGrantRedirectError"}class nn extends et{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class So extends et{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class Ar extends et{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function Pr(t){return T(t)&&t.name==="AuthRetryableFetchError"}class an extends et{constructor(e="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(e,"AuthRefreshDiscardedError",409,void 0)}}function xo(t){return T(t)&&t.name==="AuthRefreshDiscardedError"}class on extends et{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class Rr extends et{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Or="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),ln=`
26
+ \r=`.split(""),To=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<ln.length;e+=1)t[ln[e].charCodeAt(0)]=-2;for(let e=0;e<Or.length;e+=1)t[Or[e].charCodeAt(0)]=e;return t})();function cn(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(Or[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(Or[s]),e.queuedBits-=6}}function un(t,e,r){const s=To[t];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function dn(t){const e=[],r=a=>{e.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=a=>{Ao(a,s,r)};for(let a=0;a<t.length;a+=1)un(t.charCodeAt(a),n,i);return e.join("")}function Eo(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function jo(t,e){for(let r=0;r<t.length;r+=1){let s=t.charCodeAt(r);if(s>55295&&s<=56319){const n=(s-55296)*1024&65535;s=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}Eo(s,e)}}function Ao(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let s=1;s<6;s+=1)if((t>>7-s&1)===0){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function $t(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)un(t.charCodeAt(n),r,s);return new Uint8Array(e)}function Po(t){const e=[];return jo(t,r=>e.push(r)),new Uint8Array(e)}function vt(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>cn(n,r,s)),cn(null,r,s),e.join("")}function Ro(t){return Math.round(Date.now()/1e3)+t}function Oo(){return Symbol("auth-callback")}const we=()=>typeof window<"u"&&typeof document<"u",wt={tested:!1,writable:!1},hn=()=>{if(!we())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(wt.tested)return wt.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),wt.tested=!0,wt.writable=!0}catch{wt.tested=!0,wt.writable=!1}return wt.writable};function fn(t){const e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,i)=>{e[i]=n})}catch{}return r.searchParams.forEach((s,n)=>{e[n]=s}),e}const mn=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Co=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",at=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},ke=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return null}},Re=async(t,e)=>{await t.removeItem(e)};class Cr{constructor(){this.promise=new Cr.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}Cr.promiseConstructor=Promise;function Nr(t){const e=t.split(".");if(e.length!==3)throw new Rr("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!bo.test(e[s]))throw new Rr("JWT not in base64url format");return{header:JSON.parse(dn(e[0])),payload:JSON.parse(dn(e[1])),signature:$t(e[2]),raw:{header:e[0],payload:e[1]}}}async function No(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Io(t,e){return new Promise((s,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{const a=await t(i);if(!e(i,null,a)){s(a);return}}catch(a){if(!e(i,a)){n(a);return}}})()})}function pn(t){return("0"+t.toString(16)).substr(-2)}function Do(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=r.length;let n="";for(let i=0;i<56;i++)n+=r.charAt(Math.floor(Math.random()*s));return n}return crypto.getRandomValues(e),Array.from(e,pn).join("")}async function $o(t){const r=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(s);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}async function Lo(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;const r=await $o(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}const Mo=/^[a-zA-Z0-9_-]{8,64}$/;function Ir(t){return typeof t=="string"&&Mo.test(t)?t:null}function Uo(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,pn).join("")}let t="";for(let e=0;e<32;e++)t+=Math.floor(Math.random()*16).toString(16);return t}const Lt=(t,e)=>`${t}-flow-${e}-code-verifier`,rr=t=>`${t}-flows-code-verifier`;async function cs(t,e){const r=await ke(t,rr(e));return Array.isArray(r)?r.filter(s=>Ir(s)!==null):[]}async function Bo(t,e,r,s,n){await at(t,Lt(e,r),s);const i=(await cs(t,e)).filter(a=>a!==r);for(i.push(r);i.length>vo;){const a=i.shift();await Re(t,Lt(e,a)),n?.(a)}await at(t,rr(e),i),await at(t,`${e}-code-verifier`,s)}async function Fo(t,e,r){if(r){const n=await ke(t,Lt(e,r));return{verifier:typeof n=="string"?n:null,flowId:r}}const s=await ke(t,`${e}-code-verifier`);return{verifier:typeof s=="string"?s:null,flowId:null}}async function Je(t,e,r){const s=`${e}-code-verifier`;if(!r){await Re(t,s);return}const n=Lt(e,r),i=await ke(t,n);await Re(t,n);const a=await cs(t,e),o=a.filter(l=>l!==r);o.length!==a.length&&(o.length>0?await at(t,rr(e),o):await Re(t,rr(e))),i!=null&&i===await ke(t,s)&&await Re(t,s)}async function Ko(t,e){const r=await cs(t,e);for(const s of r)await Re(t,Lt(e,s));await Re(t,rr(e)),await Re(t,`${e}-code-verifier`)}function qo(t,e){const r=t.indexOf("#");let s=r===-1?t:t.slice(0,r);const n=r===-1?"":t.slice(r),i=s.indexOf("?");if(i!==-1){const o=s.slice(0,i),l=s.slice(i+1).split("&").filter(u=>u!==""&&u!==bt&&!u.startsWith(`${bt}=`));s=l.length>0?`${o}?${l.join("&")}`:o}const a=s.includes("?")?"&":"?";return`${s}${a}${bt}=${encodeURIComponent(e)}${n}`}async function Wo(t,e,r=!1,s){const n=Do();let i=n;r&&(i+="/recovery");const a=Uo();await Bo(t,e,a,i,s);const o=await Lo(n);return[o,n===o?"plain":"s256",a]}const Ho=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Go(t){const e=t.headers.get(ls);if(!e||!e.match(Ho))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function zo(t){if(!t)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function Vo(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const Jo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ot(t){if(!Jo.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ye(t){if(!t.passkey)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).")}function us(){const t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){const s=r.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Yo(t,e){return new Proxy(t,{get:(r,s,n)=>{if(s==="__isInsecureUserWarningProxy")return!0;if(typeof s=="symbol"){const i=s.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,s,n)}return!e.value&&typeof s=="string"&&(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."),e.value=!0),Reflect.get(r,s,n)}})}function gn(t){return JSON.parse(JSON.stringify(t))}const _t=t=>{if(typeof t=="object"&&t!==null){const e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(t)},yn=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function bn(t){var e;if(!Co(t))throw new Ar(_t(t),0);let r;try{r=await t.json()}catch(i){throw yn.includes(t.status)?new Ar(t.statusText||`HTTP ${t.status}`,t.status):new Ve(_t(i),i)}if(yn.includes(t.status))throw new Ar(_t(r),t.status);let s;const n=Go(t);if(n&&n.getTime()>=rn["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?s=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(s=r.error_code),s){if(s==="weak_password")throw new on(_t(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new be}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,a)=>i&&typeof a=="string",!0))throw new on(_t(r),t.status,r.weak_password.reasons);throw new _o(_t(r),t.status||500,s)}const Qo=(t,e,r,s)=>{const n={method:t,headers:e?.headers||{}};return t==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))};async function P(t,e,r,s){var n;const i=Object.assign({},s?.headers);i[ls]||(i[ls]=rn["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);const a=(n=s?.query)!==null&&n!==void 0?n:{};s?.redirectTo&&(a.redirect_to=s.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await Xo(t,e,r+o,{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function Xo(t,e,r,s,n,i){const a=Qo(e,s,n,i);let o;try{o=await t(r,Object.assign({},a))}catch(l){throw new Ar(_t(l),0)}if(o.ok||await bn(o),s?.noResolveJson)return o;try{return await o.json()}catch(l){await bn(l)}}function Ue(t){var e;let r=null;tl(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Ro(t.expires_in)));const s=(e=t.user)!==null&&e!==void 0?e:typeof t?.id=="string"?t:null;return{data:{session:r,user:s},error:null}}function vn(t){const e=Ue(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,s)=>r&&typeof s=="string",!0)&&(e.data.weak_password=t.weak_password),e}function dt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Zo(t){return{data:t,error:null}}function el(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=t,a=gr(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},l=Object.assign({},a);return{data:{properties:o,user:l},error:null}}function wn(t){return t}function tl(t){return!!t.access_token&&!!t.refresh_token&&!!t.expires_in}const ds=["global","local","others"];class rl{constructor({url:e="",headers:r={},fetch:s,experimental:n}){this.url=e,this.headers=r,this.fetch=mn(s),this.experimental=n??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,r=ds[0]){if(ds.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ds.join(", ")}`);try{return await P(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(T(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await P(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:dt})}catch(s){if(T(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:r}=e,s=gr(e,["options"]),n=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(n.new_email=s?.newEmail,delete n.newEmail),await P(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:el,redirectTo:r?.redirectTo})}catch(r){if(T(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await P(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:dt})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,s,n,i,a,o,l;try{const u={nextPage:null,lastPage:0,total:0},d=await P(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:wn});if(d.error)throw d.error;const h=await d.json(),p=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,m=(l=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),x=JSON.parse(g.split(";")[1].split("=")[1]);u[`${x}Page`]=y}),u.total=parseInt(p)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(T(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){ot(e);try{return await P(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:dt})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){ot(e);try{return await P(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:dt})}catch(s){if(T(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){ot(e);try{return await P(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:dt})}catch(s){if(T(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){ot(e.userId);try{const{data:r,error:s}=await P(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:s}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _deleteFactor(e){ot(e.userId),ot(e.id);try{return{data:await P(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,s,n,i,a,o,l;try{const u={nextPage:null,lastPage:0,total:0},d=await P(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:wn});if(d.error)throw d.error;const h=await d.json(),p=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,m=(l=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),x=JSON.parse(g.split(";")[1].split("=")[1]);u[`${x}Page`]=y}),u.total=parseInt(p)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(T(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await P(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await P(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await P(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(T(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await P(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await P(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{const r={};return e?.type&&(r.type=e.type),await P(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:s=>{var n;return{data:{providers:(n=s?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(T(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await P(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await P(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await P(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(T(s))return{data:null,error:s};throw s}}async _deleteCustomProvider(e){try{return await P(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _adminListPasskeys(e){Ye(this.experimental),ot(e.userId);try{return await P(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _adminDeletePasskey(e){Ye(this.experimental),ot(e.userId),ot(e.passkeyId);try{return await P(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}}function _n(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}globalThis&&hn()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug");class sl extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}function nl(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function kn(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function il(t){return parseInt(t,16)}function al(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function ol(t){var e;const{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:l,resources:u,scheme:d,uri:h,version:p}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!h)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(p!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${p}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
27
+ `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}const m=kn(t.address),g=d?`${d}://${s}`:s,y=t.statement?`${t.statement}
28
+ `:"",x=`${g} wants you to sign in with your Ethereum account:
29
+ ${m}
28
30
 
29
- To use Realtime in Node.js, you need to provide a WebSocket implementation:
30
-
31
- Option 1: Use Node.js 22+ which has native WebSocket support
32
- Option 2: Install and provide the "ws" package:
33
-
34
- npm install ws
35
-
36
- import ws from "ws"
37
- const client = new RealtimeClient(url, {
38
- ...options,
39
- transport: ws
40
- })`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return r==="ok"&&e.teardown(),r}async removeAllChannels(){const e=this.channels.map(async s=>{const n=await s.unsubscribe();return s.teardown(),n}),r=await Promise.all(e);return await this.disconnect(),r}log(e,r,s){this.socketAdapter.log(e,r,s)}connectionState(){return this.socketAdapter.connectionState()||qr.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){const s=`realtime:${e}`,n=this.getChannels().find(a=>a.topic===s);if(n)return n;{const a=new Wt(`realtime:${e}`,r,this);return this._cancelPendingDisconnect(),this.channels.push(a),a}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic),this.channels.length===0&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e=null){let r,s=!1;if(e)r=e,s=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),r=this.accessTokenValue}else r=this.accessTokenValue;s?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{const a={access_token:r,version:Ea};r&&n.updateJoinPayload(a),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(Es.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,s)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,s)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{const s=new Blob([ni],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_initializeOptions(e){var r,s,n,a,i,o,l,u,d,h,m;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(s=e?.accessToken)!==null&&s!==void 0?s:null;const p={};p.timeout=(n=e?.timeout)!==null&&n!==void 0?n:Oa,p.heartbeatIntervalMs=(a=e?.heartbeatIntervalMs)!==null&&a!==void 0?a:$s.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(i=e?.disconnectOnEmptyChannelsAfterMs)!==null&&i!==void 0?i:2*((o=e?.heartbeatIntervalMs)!==null&&o!==void 0?o:$s.HEARTBEAT_INTERVAL),p.transport=(l=e?.transport)!==null&&l!==void 0?l:Aa.getWebSocketConstructor(),p.params=e?.params,p.logger=e?.logger,p.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),p.reconnectAfterMs=(u=e?.reconnectAfterMs)!==null&&u!==void 0?u:(w=>ri[w-1]||si);let g,b;const A=(d=e?.vsn)!==null&&d!==void 0?d:Ra;switch(A){case Pa:g=(w,S)=>S(JSON.stringify(w)),b=(w,S)=>S(JSON.parse(w));break;case As:g=this.serializer.encode.bind(this.serializer),b=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${p.vsn}`)}if(p.vsn=A,p.encode=(h=e?.encode)!==null&&h!==void 0?h:g,p.decode=(m=e?.decode)!==null&&m!==void 0?m:b,p.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,p.params=Object.assign(Object.assign({},p.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,p.autoSendHeartbeat=!this.worker}return p}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var Gt=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function ii(t,e,r){const s=new URL(e,t);if(r)for(const[n,a]of Object.entries(r))a!==void 0&&s.searchParams.set(n,a);return s.toString()}async function oi(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function li(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:a,headers:i}){const o=ii(t.baseUrl,s,n),l=await oi(t.auth),u=await e(o,{method:r,headers:{...a?{"Content-Type":"application/json"}:{},...l,...i},body:a?JSON.stringify(a):void 0}),d=await u.text(),h=(u.headers.get("content-type")||"").includes("application/json"),m=h&&d?JSON.parse(d):d;if(!u.ok){const p=h?m:void 0,g=p?.error;throw new Gt(g?.message??`Request failed with status ${u.status}`,{status:u.status,icebergType:g?.type,icebergCode:g?.code,details:p})}return{status:u.status,headers:u.headers,data:m}}}}function yr(t){return t.join("")}var ci=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:yr(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(s=>({namespace:s}))}async createNamespace(t,e){const r={namespace:t.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${yr(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${yr(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${yr(t.namespace)}`}),!0}catch(e){if(e instanceof Gt&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof Gt&&r.status===409)return;throw r}}};function At(t){return t.join("")}var ui=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${At(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){const r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${At(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${At(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${At(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(t){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${At(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${At(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof Gt&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof Gt&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},di=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=li({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new ci(this.client,e),this.tableOps=new ui(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};function zt(t){"@babel/helpers - typeof";return zt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},zt(t)}function hi(t,e){if(zt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(zt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function fi(t){var e=hi(t,"string");return zt(e)=="symbol"?e:e+""}function mi(t,e,r){return(e=fi(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Ls(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function C(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Ls(Object(r),!0).forEach(function(s){mi(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Ls(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var br=class extends Error{constructor(t,e="storage",r,s){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function vr(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var zr=class extends br{constructor(t,e,r,s="storage"){super(t,s,e,r),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return C({},super.toJSON())}},Us=class extends br{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};function wr(t,e,r){const s=C({},t),n=e.toLowerCase();for(const a of Object.keys(s))a.toLowerCase()===n&&delete s[a];return s[n]=r,s}function pi(t){const e={};for(const[r,s]of Object.entries(t))e[r.toLowerCase()]=s;return e}const gi=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),yi=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},Vr=t=>{if(Array.isArray(t))return t.map(r=>Vr(r));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([r,s])=>{const n=r.replace(/([-_][a-z])/gi,a=>a.toUpperCase().replace(/[-_]/g,""));e[n]=Vr(s)}),e},bi=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),Ms=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},vi=async(t,e,r,s)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){const n=t;let a=parseInt(n.status,10);Number.isFinite(a)||(a=500),n.json().then(i=>{const o=i?.statusCode||i?.code||a+"";e(new zr(Ms(i),a,o,s))}).catch(()=>{const i=a+"";e(new zr(n.statusText||`HTTP ${a} error`,a,i,s))})}else e(new Us(Ms(t),t,s))},wi=(t,e,r,s)=>{const n={method:t,headers:e?.headers||{}};if(t==="GET"||t==="HEAD"||!s)return C(C({},n),r);if(yi(s)){var a;const i=e?.headers||{};let o;for(const[l,u]of Object.entries(i))l.toLowerCase()==="content-type"&&(o=u);n.headers=wr(i,"Content-Type",(a=o)!==null&&a!==void 0?a:"application/json"),n.body=JSON.stringify(s)}else n.body=s;return e?.duplex&&(n.duplex=e.duplex),C(C({},n),r)};async function Vt(t,e,r,s,n,a,i){return new Promise((o,l)=>{t(r,wi(e,s,n,a)).then(u=>{if(!u.ok)throw u;if(s?.noResolveJson)return u;if(i==="vectors"){const d=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!d||!d.includes("application/json"))return{}}return u.json()}).then(u=>o(u)).catch(u=>vi(u,l,s,i))})}function Bs(t="storage"){return{get:async(e,r,s,n)=>Vt(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,a)=>Vt(e,"POST",r,n,a,s,t),put:async(e,r,s,n,a)=>Vt(e,"PUT",r,n,a,s,t),head:async(e,r,s,n)=>Vt(e,"HEAD",r,C(C({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,a)=>Vt(e,"DELETE",r,n,a,s,t)}}const _i=Bs("storage"),{get:Jt,post:Ge,put:Jr,head:ki,remove:Yr}=_i,Ie=Bs("vectors");var Et=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=pi(e),this.fetch=gi(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=wr(this.headers,t,e),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(vr(r))return{data:null,error:r};throw r}}},Si=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(vr(e))return{data:null,error:e};throw e}}};let Ks;Ks=Symbol.toStringTag;var xi=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Ks]="BlobDownloadBuilder",this.promise=null}asStream(){return new Si(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(vr(e))return{data:null,error:e};throw e}}};const Ti={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Fs={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var ji=class extends Et{constructor(t,e={},r,s){super(t,e,s,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,s){var n=this;return n.handleOperation(async()=>{let a;const i=C(C({},Fs),s);let o=C(C({},n.headers),t==="POST"&&{"x-upsert":String(i.upsert)});const l=i.metadata;if(typeof Blob<"u"&&r instanceof Blob?(a=new FormData,a.append("cacheControl",i.cacheControl),l&&a.append("metadata",n.encodeMetadata(l)),a.append("",r)):typeof FormData<"u"&&r instanceof FormData?(a=r,a.has("cacheControl")||a.append("cacheControl",i.cacheControl),l&&!a.has("metadata")&&a.append("metadata",n.encodeMetadata(l))):(a=r,o["cache-control"]=`max-age=${i.cacheControl}`,o["content-type"]=i.contentType,l&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&a instanceof ReadableStream||a&&typeof a=="object"&&"pipe"in a&&typeof a.pipe=="function")&&!i.duplex&&(i.duplex="half")),s?.headers)for(const[m,p]of Object.entries(s.headers))o=wr(o,m,p);const u=n._removeEmptyFolders(e),d=n._getFinalPath(u),h=await(t=="PUT"?Jr:Ge)(n.fetch,`${n.url}/object/${d}`,a,C({headers:o},i?.duplex?{duplex:i.duplex}:{}));return{path:u,id:h.Id,fullPath:h.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,s){var n=this;const a=n._removeEmptyFolders(t),i=n._getFinalPath(a),o=new URL(n.url+`/object/upload/sign/${i}`);return o.searchParams.set("token",e),n.handleOperation(async()=>{let l;const u=C(C({},Fs),s);let d=C(C({},n.headers),{"x-upsert":String(u.upsert)});const h=u.metadata;if(typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),h&&l.append("metadata",n.encodeMetadata(h)),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.has("cacheControl")||l.append("cacheControl",u.cacheControl),h&&!l.has("metadata")&&l.append("metadata",n.encodeMetadata(h))):(l=r,d["cache-control"]=`max-age=${u.cacheControl}`,d["content-type"]=u.contentType,h&&(d["x-metadata"]=n.toBase64(n.encodeMetadata(h))),(typeof ReadableStream<"u"&&l instanceof ReadableStream||l&&typeof l=="object"&&"pipe"in l&&typeof l.pipe=="function")&&!u.duplex&&(u.duplex="half")),s?.headers)for(const[m,p]of Object.entries(s.headers))d=wr(d,m,p);return{path:a,fullPath:(await Jr(n.fetch,o.toString(),l,C({headers:d},u?.duplex?{duplex:u.duplex}:{}))).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t);const n=C({},r.headers);e?.upsert&&(n["x-upsert"]="true");const a=await Ge(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),i=new URL(r.url+a.url),o=i.searchParams.get("token");if(!o)throw new br("No token returned by API");return{signedUrl:i.toString(),path:t,token:o}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var s=this;return s.handleOperation(async()=>await Ge(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:s.headers}))}async copy(t,e,r){var s=this;return s.handleOperation(async()=>({path:(await Ge(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(t,e,r){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(t);const a=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0;let i=await Ge(s.fetch,`${s.url}/object/sign/${n}`,C({expiresIn:e},a?{transform:r.transform}:{}),{headers:s.headers});const o=new URLSearchParams;r?.download&&o.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&o.set("cacheNonce",String(r.cacheNonce));const l=o.toString();return{signedUrl:encodeURI(`${s.url}${i.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{const n=await Ge(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:t},{headers:s.headers}),a=new URLSearchParams;r?.download&&a.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&a.set("cacheNonce",String(r.cacheNonce));const i=a.toString();return n.map(o=>C(C({},o),{},{signedUrl:o.signedURL?encodeURI(`${s.url}${o.signedURL}${i?`&${i}`:""}`):null}))})}download(t,e,r){const s=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",n=new URLSearchParams;e?.transform&&this.applyTransformOptsToQuery(n,e.transform),e?.cacheNonce!=null&&n.set("cacheNonce",String(e.cacheNonce));const a=n.toString(),i=this._getFinalPath(t),o=()=>Jt(this.fetch,`${this.url}/${s}/${i}${a?`?${a}`:""}`,{headers:this.headers,noResolveJson:!0},r);return new xi(o,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>Vr(await Jt(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await ki(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(vr(n)){var s;const a=n instanceof zr?n.status:n instanceof Us?(s=n.originalError)===null||s===void 0?void 0:s.status:void 0;if(a!==void 0&&[400,404].includes(a))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){const r=this._getFinalPath(t),s=new URLSearchParams;e?.download&&s.set("download",e.download===!0?"":e.download),e?.transform&&this.applyTransformOptsToQuery(s,e.transform),e?.cacheNonce!=null&&s.set("cacheNonce",String(e.cacheNonce));const n=s.toString(),a=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}`)+(n?`?${n}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await Yr(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var s=this;return s.handleOperation(async()=>{const n=C(C(C({},Ti),e),{},{prefix:t||""});return await Ge(s.fetch,`${s.url}/object/list/${s.bucketId}`,n,{headers:s.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{const s=C({},t);return await Ge(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("quality",e.quality.toString()),t}};const Yt={"X-Client-Info":"storage-js/2.105.1"};var Ai=class extends Et{constructor(t,e={},r,s){const n=new URL(t);s?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));const a=n.href.replace(/\/$/,""),i=C(C({},Yt),e);super(a,i,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await Jt(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Jt(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await Ge(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await Jr(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await Ge(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Yr(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){const e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},Ei=class extends Et{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},Yt),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ge(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);const s=r.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await Jt(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Yr(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!bi(t))throw new br("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new di({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(n,a){const i=n[a];return typeof i!="function"?i:async(...o)=>{try{return{data:await i.apply(n,o),error:null}}catch(l){if(s)throw l;return{data:null,error:l}}}}})}},Pi=class extends Et{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},Yt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await Ie.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await Ie.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},Ri=class extends Et{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},Yt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},Oi=class extends Et{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},Yt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Ci=class extends Oi{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Ni(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},Ni=class extends Pi{constructor(t,e,r,s){super(t,e,s),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new Ii(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Ii=class extends Ri{constructor(t,e,r,s,n){super(t,e,n),this.vectorBucketName=r,this.indexName=s}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},Di=class extends Ai{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new ji(this.url,this.headers,t,this.fetch)}get vectors(){return new Ci(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Ei(this.url+"/iceberg",this.headers,this.fetch)}};const qs="2.105.1",Pt=30*1e3,Qr=3,Xr=Qr*Pt,$i="http://localhost:9999",Li="supabase.auth.token",Ui={"X-Client-Info":`gotrue-js/${qs}`},Zr="X-Supabase-Api-Version",Hs={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Mi=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Bi=600*1e3;class Qt extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function x(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class Ki extends Qt{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}}function Fi(t){return x(t)&&t.name==="AuthApiError"}class ze extends Qt{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class rt extends Qt{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}}class be extends rt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function _r(t){return x(t)&&t.name==="AuthSessionMissingError"}class Rt extends rt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class kr extends rt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Sr extends rt{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}function qi(t){return x(t)&&t.name==="AuthImplicitGrantRedirectError"}class Ws extends rt{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class Hi extends rt{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class es extends rt{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function ts(t){return x(t)&&t.name==="AuthRetryableFetchError"}class Gs extends rt{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class rs extends rt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const xr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),zs=`
41
- \r=`.split(""),Wi=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<zs.length;e+=1)t[zs[e].charCodeAt(0)]=-2;for(let e=0;e<xr.length;e+=1)t[xr[e].charCodeAt(0)]=e;return t})();function Vs(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(xr[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(xr[s]),e.queuedBits-=6}}function Js(t,e,r){const s=Wi[t];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Ys(t){const e=[],r=i=>{e.push(String.fromCodePoint(i))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},a=i=>{Vi(i,s,r)};for(let i=0;i<t.length;i+=1)Js(t.charCodeAt(i),n,a);return e.join("")}function Gi(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function zi(t,e){for(let r=0;r<t.length;r+=1){let s=t.charCodeAt(r);if(s>55295&&s<=56319){const n=(s-55296)*1024&65535;s=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}Gi(s,e)}}function Vi(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let s=1;s<6;s+=1)if((t>>7-s&1)===0){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function Ot(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)Js(t.charCodeAt(n),r,s);return new Uint8Array(e)}function Ji(t){const e=[];return zi(t,r=>e.push(r)),new Uint8Array(e)}function ft(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>Vs(n,r,s)),Vs(null,r,s),e.join("")}function Yi(t){return Math.round(Date.now()/1e3)+t}function Qi(){return Symbol("auth-callback")}const we=()=>typeof window<"u"&&typeof document<"u",mt={tested:!1,writable:!1},Qs=()=>{if(!we())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(mt.tested)return mt.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),mt.tested=!0,mt.writable=!0}catch{mt.tested=!0,mt.writable=!1}return mt.writable};function Xi(t){const e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,a)=>{e[a]=n})}catch{}return r.searchParams.forEach((s,n)=>{e[n]=s}),e}const Xs=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Zi=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Ct=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},pt=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},_e=async(t,e)=>{await t.removeItem(e)};class Tr{constructor(){this.promise=new Tr.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}Tr.promiseConstructor=Promise;function jr(t){const e=t.split(".");if(e.length!==3)throw new rs("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!Mi.test(e[s]))throw new rs("JWT not in base64url format");return{header:JSON.parse(Ys(e[0])),payload:JSON.parse(Ys(e[1])),signature:Ot(e[2]),raw:{header:e[0],payload:e[1]}}}async function eo(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function to(t,e){return new Promise((s,n)=>{(async()=>{for(let a=0;a<1/0;a++)try{const i=await t(a);if(!e(a,null,i)){s(i);return}}catch(i){if(!e(a,i)){n(i);return}}})()})}function ro(t){return("0"+t.toString(16)).substr(-2)}function so(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=r.length;let n="";for(let a=0;a<56;a++)n+=r.charAt(Math.floor(Math.random()*s));return n}return crypto.getRandomValues(e),Array.from(e,ro).join("")}async function no(t){const r=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(s);return Array.from(n).map(a=>String.fromCharCode(a)).join("")}async function ao(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;const r=await no(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Nt(t,e,r=!1){const s=so();let n=s;r&&(n+="/recovery"),await Ct(t,`${e}-code-verifier`,n);const a=await ao(s);return[a,s===a?"plain":"s256"]}const io=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function oo(t){const e=t.headers.get(Zr);if(!e||!e.match(io))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function lo(t){if(!t)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function co(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const uo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function st(t){if(!uo.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ve(t){if(!t.passkey)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).")}function ss(){const t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){const s=r.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function ho(t,e){return new Proxy(t,{get:(r,s,n)=>{if(s==="__isInsecureUserWarningProxy")return!0;if(typeof s=="symbol"){const a=s.toString();if(a==="Symbol(Symbol.toPrimitive)"||a==="Symbol(Symbol.toStringTag)"||a==="Symbol(util.inspect.custom)"||a==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,s,n)}return!e.value&&typeof s=="string"&&(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."),e.value=!0),Reflect.get(r,s,n)}})}function Zs(t){return JSON.parse(JSON.stringify(t))}const gt=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),fo=[502,503,504,520,521,522,523,524,530];async function en(t){var e;if(!Zi(t))throw new es(gt(t),0);if(fo.includes(t.status))throw new es(gt(t),t.status);let r;try{r=await t.json()}catch(a){throw new ze(gt(a),a)}let s;const n=oo(t);if(n&&n.getTime()>=Hs["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?s=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(s=r.error_code),s){if(s==="weak_password")throw new Gs(gt(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new be}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((a,i)=>a&&typeof i=="string",!0))throw new Gs(gt(r),t.status,r.weak_password.reasons);throw new Ki(gt(r),t.status||500,s)}const mo=(t,e,r,s)=>{const n={method:t,headers:e?.headers||{}};return t==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))};async function E(t,e,r,s){var n;const a=Object.assign({},s?.headers);a[Zr]||(a[Zr]=Hs["2024-01-01"].name),s?.jwt&&(a.Authorization=`Bearer ${s.jwt}`);const i=(n=s?.query)!==null&&n!==void 0?n:{};s?.redirectTo&&(i.redirect_to=s.redirectTo);const o=Object.keys(i).length?"?"+new URLSearchParams(i).toString():"",l=await po(t,e,r+o,{headers:a,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function po(t,e,r,s,n,a){const i=mo(e,s,n,a);let o;try{o=await t(r,Object.assign({},i))}catch(l){throw console.error(l),new es(gt(l),0)}if(o.ok||await en(o),s?.noResolveJson)return o;try{return await o.json()}catch(l){await en(l)}}function Ue(t){var e;let r=null;bo(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Yi(t.expires_in)));const s=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:s},error:null}}function tn(t){const e=Ue(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,s)=>r&&typeof s=="string",!0)&&(e.data.weak_password=t.weak_password),e}function ot(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function go(t){return{data:t,error:null}}function yo(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:a}=t,i=dr(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:a},l=Object.assign({},i);return{data:{properties:o,user:l},error:null}}function rn(t){return t}function bo(t){return t.access_token&&t.refresh_token&&t.expires_in}const ns=["global","local","others"];class vo{constructor({url:e="",headers:r={},fetch:s,experimental:n}){this.url=e,this.headers=r,this.fetch=Xs(s),this.experimental=n??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,r=ns[0]){if(ns.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ns.join(", ")}`);try{return await E(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(x(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await E(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:ot})}catch(s){if(x(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:r}=e,s=dr(e,["options"]),n=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(n.new_email=s?.newEmail,delete n.newEmail),await E(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:yo,redirectTo:r?.redirectTo})}catch(r){if(x(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await E(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ot})}catch(r){if(x(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,s,n,a,i,o,l;try{const u={nextPage:null,lastPage:0,total:0},d=await E(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(a=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&a!==void 0?a:""},xform:rn});if(d.error)throw d.error;const h=await d.json(),m=(i=d.headers.get("x-total-count"))!==null&&i!==void 0?i:0,p=(l=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return p.length>0&&(p.forEach(g=>{const b=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),A=JSON.parse(g.split(";")[1].split("=")[1]);u[`${A}Page`]=b}),u.total=parseInt(m)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(x(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){st(e);try{return await E(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ot})}catch(r){if(x(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){st(e);try{return await E(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:ot})}catch(s){if(x(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){st(e);try{return await E(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:ot})}catch(s){if(x(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){st(e.userId);try{const{data:r,error:s}=await E(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:s}}catch(r){if(x(r))return{data:null,error:r};throw r}}async _deleteFactor(e){st(e.userId),st(e.id);try{return{data:await E(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(x(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,s,n,a,i,o,l;try{const u={nextPage:null,lastPage:0,total:0},d=await E(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(a=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&a!==void 0?a:""},xform:rn});if(d.error)throw d.error;const h=await d.json(),m=(i=d.headers.get("x-total-count"))!==null&&i!==void 0?i:0,p=(l=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return p.length>0&&(p.forEach(g=>{const b=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),A=JSON.parse(g.split(";")[1].split("=")[1]);u[`${A}Page`]=b}),u.total=parseInt(m)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(x(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await E(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(x(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await E(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(x(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await E(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(x(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await E(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(x(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await E(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(x(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{const r={};return e?.type&&(r.type=e.type),await E(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:s=>{var n;return{data:{providers:(n=s?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(x(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await E(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(x(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await E(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(x(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await E(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(x(s))return{data:null,error:s};throw s}}async _deleteCustomProvider(e){try{return await E(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(x(r))return{data:null,error:r};throw r}}async _adminListPasskeys(e){Ve(this.experimental),st(e.userId);try{return await E(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(x(r))return{data:null,error:r};throw r}}async _adminDeletePasskey(e){Ve(this.experimental),st(e.userId),st(e.passkeyId);try{return await E(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(x(r))return{data:null,error:r};throw r}}}function sn(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}const Xe={debug:!!(globalThis&&Qs()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class nn extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class an extends nn{}async function wo(t,e,r){Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const s=new globalThis.AbortController;let n;e>0&&(n=setTimeout(()=>{s.abort(),Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async a=>{if(a){clearTimeout(n),Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,a.name);try{return await r()}finally{Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,a.name)}}else{if(e===0)throw Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new an(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(Xe.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return 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"),clearTimeout(n),await r()}})}catch(a){if(e>0&&clearTimeout(n),a?.name==="AbortError"&&e>0){if(s.signal.aborted)return Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:!0},async i=>{if(i){Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,i.name);try{return await r()}finally{Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,i.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new an(`Lock "${t}" was released because another request stole it`)}throw a}}function _o(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function on(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function ko(t){return parseInt(t,16)}function So(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function xo(t){var e;const{chainId:r,domain:s,expirationTime:n,issuedAt:a=new Date,nonce:i,notBefore:o,requestId:l,resources:u,scheme:d,uri:h,version:m}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(i&&i.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${i}`);if(!h)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(m!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${m}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
42
- `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}const p=on(t.address),g=d?`${d}://${s}`:s,b=t.statement?`${t.statement}
43
- `:"",A=`${g} wants you to sign in with your Ethereum account:
44
- ${p}
45
-
46
- ${b}`;let w=`URI: ${h}
47
- Version: ${m}
48
- Chain ID: ${r}${i?`
49
- Nonce: ${i}`:""}
50
- Issued At: ${a.toISOString()}`;if(n&&(w+=`
51
- Expiration Time: ${n.toISOString()}`),o&&(w+=`
52
- Not Before: ${o.toISOString()}`),l&&(w+=`
53
- Request ID: ${l}`),u){let S=`
54
- Resources:`;for(const k of u){if(!k||typeof k!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${k}`);S+=`
55
- - ${k}`}w+=S}return`${A}
56
- ${w}`}class de extends Error{constructor({message:e,code:r,cause:s,name:n}){var a;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(a=n??(s instanceof Error?s.name:void 0))!==null&&a!==void 0?a:"Unknown Error",this.code=r}}class Ar extends de{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function To({error:t,options:e}){var r,s,n;const{publicKey:a}=e;if(!a)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new de({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=a.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new de({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((s=a.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new de({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=a.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new de({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new de({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new de({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return a.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new de({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new de({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const i=window.location.hostname;if(hn(i)){if(a.rp.id!==i)return new de({message:`The RP ID "${a.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new de({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(a.user.id.byteLength<1||a.user.id.byteLength>64)return new de({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new de({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new de({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function jo({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new de({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new de({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(hn(s)){if(r.rpId!==s)return new de({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new de({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new de({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new de({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class Ao{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const as=new Ao;function ln(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);const{challenge:e,user:r,excludeCredentials:s}=t,n=dr(t,["challenge","user","excludeCredentials"]),a=Ot(e).buffer,i=Object.assign(Object.assign({},r),{id:Ot(r.id).buffer}),o=Object.assign(Object.assign({},n),{challenge:a,user:i});if(s&&s.length>0){o.excludeCredentials=new Array(s.length);for(let l=0;l<s.length;l++){const u=s[l];o.excludeCredentials[l]=Object.assign(Object.assign({},u),{id:Ot(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return o}function cn(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);const{challenge:e,allowCredentials:r}=t,s=dr(t,["challenge","allowCredentials"]),n=Ot(e).buffer,a=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){a.allowCredentials=new Array(r.length);for(let i=0;i<r.length;i++){const o=r[i];a.allowCredentials[i]=Object.assign(Object.assign({},o),{id:Ot(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return a}function un(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t;return{id:t.id,rawId:t.id,response:{attestationObject:ft(new Uint8Array(t.response.attestationObject)),clientDataJSON:ft(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function dn(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t,s=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:ft(new Uint8Array(n.authenticatorData)),clientDataJSON:ft(new Uint8Array(n.clientDataJSON)),signature:ft(new Uint8Array(n.signature)),userHandle:n.userHandle?ft(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function hn(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Er(){var t,e;return!!(we()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function fn(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ar("Browser returned unexpected credential type",e)}:{data:null,error:new Ar("Empty credential response",e)}}catch(e){return{data:null,error:To({error:e,options:t})}}}async function mn(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ar("Browser returned unexpected credential type",e)}:{data:null,error:new Ar("Empty credential response",e)}}catch(e){return{data:null,error:jo({error:e,options:t})}}}const Eo={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Po={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Pr(...t){const e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(const n of t)if(n)for(const a in n){const i=n[a];if(i!==void 0)if(Array.isArray(i))s[a]=i;else if(r(i))s[a]=i;else if(e(i)){const o=s[a];e(o)?s[a]=Pr(o,i):s[a]=Pr(i)}else s[a]=i}return s}function Ro(t,e){return Pr(Eo,t,e||{})}function Oo(t,e){return Pr(Po,t,e||{})}class Co{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:s,signal:n},a){var i;try{const{data:o,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!o)return{data:null,error:l};const u=n??as.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:d}=o.webauthn.credential_options.publicKey;if(!d.name){const h=s;if(h)d.name=`${d.id}:${h}`;else{const p=(await this.client.getUser()).data.user,g=((i=p?.user_metadata)===null||i===void 0?void 0:i.name)||p?.email||p?.id||"User";d.name=`${d.id}:${g}`}}d.displayName||(d.displayName=d.name)}switch(o.webauthn.type){case"create":{const d=Ro(o.webauthn.credential_options.publicKey,a?.create),{data:h,error:m}=await fn({publicKey:d,signal:u});return h?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:h}},error:null}:{data:null,error:m}}case"request":{const d=Oo(o.webauthn.credential_options.publicKey,a?.request),{data:h,error:m}=await mn(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:d,signal:u}));return h?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:h}},error:null}:{data:null,error:m}}}}catch(o){return x(o)?{data:null,error:o}:{data:null,error:new ze("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},a){if(!r)return{data:null,error:new Qt("rpId is required for WebAuthn authentication")};try{if(!Er())return{data:null,error:new ze("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{request:a});if(!i)return{data:null,error:o};const{webauthn:l}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:s,credential_response:l.credential_response}})}catch(i){return x(i)?{data:null,error:i}:{data:null,error:new ze("Unexpected error in authenticate",i)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},a){if(!r)return{data:null,error:new Qt("rpId is required for WebAuthn registration")};try{if(!Er())return{data:null,error:new ze("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(d=>{var h;return(h=d.data)===null||h===void 0?void 0:h.all.find(m=>m.factor_type==="webauthn"&&m.friendly_name===e&&m.status!=="unverified")}).then(d=>d?this.client.mfa.unenroll({factorId:d?.id}):void 0),{data:null,error:o};const{data:l,error:u}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:a});return l?this._verify({factorId:i.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:s,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(i){return x(i)?{data:null,error:i}:{data:null,error:new ze("Unexpected error in register",i)}}}}_o();const No={url:$i,storageKey:Li,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ui,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};async function pn(t,e,r){return await r()}const It={};class Xt{get jwks(){var e,r;return(r=(e=It[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){It[this.storageKey]=Object.assign(Object.assign({},It[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=It[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){It[this.storageKey]=Object.assign(Object.assign({},It[this.storageKey]),{cachedAt:e})}constructor(e){var r,s,n,a;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},No),e);if(this.storageKey=i.storageKey,this.instanceID=(r=Xt.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,Xt.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&we()){const o=`${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.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(s=i.experimental)!==null&&s!==void 0?s:{},this.admin=new vo({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=Xs(i.fetch),this.lock=i.lock||pn,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&we()&&(!((n=globalThis?.navigator)===null||n===void 0)&&n.locks)?this.lock=wo:this.lock=pn,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new Co(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:Qs()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=sn(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=sn(this.memoryStorage)),we()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(a=this.broadcastChannel)===null||a===void 0||a.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${qs}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},s="none";if(we()&&(r=Xi(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),we()&&this.detectSessionInUrl&&s!=="none"){const{data:n,error:a}=await this._getSessionFromURL(r,s);if(a){if(this._debug("#_initialize()","error detecting session from URL",a),qi(a)){const l=(e=a.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:a}}return{error:a}}const{session:i,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",i,"redirect type",o),await this._saveSession(i),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return x(r)?this._returnResult({error:r}):this._returnResult({error:new ze("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const a=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:Ue}),{data:i,error:o}=a;if(o||!i)return this._returnResult({data:{user:null,session:null},error:o});const l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(a){if(x(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signUp(e){var r,s,n;try{let a;if("email"in e){const{email:d,password:h,options:m}=e;let p=null,g=null;this.flowType==="pkce"&&([p,g]=await Nt(this.storage,this.storageKey)),a=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:m?.emailRedirectTo,body:{email:d,password:h,data:(r=m?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:m?.captchaToken},code_challenge:p,code_challenge_method:g},xform:Ue})}else if("phone"in e){const{phone:d,password:h,options:m}=e;a=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:h,data:(s=m?.data)!==null&&s!==void 0?s:{},channel:(n=m?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:m?.captchaToken}},xform:Ue})}else throw new kr("You must provide either an email or phone number and a password");const{data:i,error:o}=a;if(o||!i)return await _e(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});const l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(a){if(await _e(this.storage,`${this.storageKey}-code-verifier`),x(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithPassword(e){try{let r;if("email"in e){const{email:a,password:i,options:o}=e;r=await E(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:a,password:i,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:tn})}else if("phone"in e){const{phone:a,password:i,options:o}=e;r=await E(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:a,password:i,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:tn})}else throw new kr("You must provide either an email or phone number and a password");const{data:s,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){const a=new Rt;return this._returnResult({data:{user:null,session:null},error:a})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(r){if(x(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,n,a;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(a=e.options)===null||a===void 0?void 0:a.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,s,n,a,i,o,l,u,d,h,m;let p,g;if("message"in e)p=e.message,g=e.signature;else{const{chain:b,wallet:A,statement:w,options:S}=e;let k;if(we())if(typeof A=="object")k=A;else{const $=window;if("ethereum"in $&&typeof $.ethereum=="object"&&"request"in $.ethereum&&typeof $.ethereum.request=="function")k=$.ethereum;else 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.")}else{if(typeof A!="object"||!S?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");k=A}const N=new URL((r=S?.url)!==null&&r!==void 0?r:window.location.href),R=await k.request({method:"eth_requestAccounts"}).then($=>$).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!R||R.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const B=on(R[0]);let P=(s=S?.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!P){const $=await k.request({method:"eth_chainId"});P=ko($)}const U={domain:N.host,address:B,statement:w,uri:N.href,version:"1",chainId:P,nonce:(n=S?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(i=(a=S?.signInWithEthereum)===null||a===void 0?void 0:a.issuedAt)!==null&&i!==void 0?i:new Date,expirationTime:(o=S?.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(l=S?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=S?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(d=S?.signInWithEthereum)===null||d===void 0?void 0:d.resources};p=xo(U),g=await k.request({method:"personal_sign",params:[So(p),B]})}try{const{data:b,error:A}=await E(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:g},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:Ue});if(A)throw A;if(!b||!b.session||!b.user){const w=new Rt;return this._returnResult({data:{user:null,session:null},error:w})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:A})}catch(b){if(x(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async signInWithSolana(e){var r,s,n,a,i,o,l,u,d,h,m,p;let g,b;if("message"in e)g=e.message,b=e.signature;else{const{chain:A,wallet:w,statement:S,options:k}=e;let N;if(we())if(typeof w=="object")N=w;else{const B=window;if("solana"in B&&typeof B.solana=="object"&&("signIn"in B.solana&&typeof B.solana.signIn=="function"||"signMessage"in B.solana&&typeof B.solana.signMessage=="function"))N=B.solana;else 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.")}else{if(typeof w!="object"||!k?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");N=w}const R=new URL((r=k?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in N&&N.signIn){const B=await N.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},k?.signInWithSolana),{version:"1",domain:R.host,uri:R.href}),S?{statement:S}:null));let P;if(Array.isArray(B)&&B[0]&&typeof B[0]=="object")P=B[0];else if(B&&typeof B=="object"&&"signedMessage"in B&&"signature"in B)P=B;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)g=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),b=P.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in N)||typeof N.signMessage!="function"||!("publicKey"in N)||typeof N!="object"||!N.publicKey||!("toBase58"in N.publicKey)||typeof N.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${R.host} wants you to sign in with your Solana account:`,N.publicKey.toBase58(),...S?["",S,""]:[""],"Version: 1",`URI: ${R.href}`,`Issued At: ${(n=(s=k?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((a=k?.signInWithSolana)===null||a===void 0)&&a.notBefore?[`Not Before: ${k.signInWithSolana.notBefore}`]:[],...!((i=k?.signInWithSolana)===null||i===void 0)&&i.expirationTime?[`Expiration Time: ${k.signInWithSolana.expirationTime}`]:[],...!((o=k?.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${k.signInWithSolana.chainId}`]:[],...!((l=k?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${k.signInWithSolana.nonce}`]:[],...!((u=k?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${k.signInWithSolana.requestId}`]:[],...!((h=(d=k?.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||h===void 0)&&h.length?["Resources",...k.signInWithSolana.resources.map(P=>`- ${P}`)]:[]].join(`
57
- `);const B=await N.signMessage(new TextEncoder().encode(g),"utf8");if(!B||!(B instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");b=B}}try{const{data:A,error:w}=await E(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:ft(b)},!((m=e.options)===null||m===void 0)&&m.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:Ue});if(w)throw w;if(!A||!A.session||!A.user){const S=new Rt;return this._returnResult({data:{user:null,session:null},error:S})}return A.session&&(await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session)),this._returnResult({data:Object.assign({},A),error:w})}catch(A){if(x(A))return this._returnResult({data:{user:null,session:null},error:A});throw A}}async _exchangeCodeForSession(e){const r=await pt(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new Hi;const{data:a,error:i}=await E(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:Ue});if(await _e(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!a||!a.session||!a.user){const o=new Rt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers(n==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",a.session)),this._returnResult({data:Object.assign(Object.assign({},a),{redirectType:n??null}),error:i})}catch(a){if(await _e(this.storage,`${this.storageKey}-code-verifier`),x(a))return this._returnResult({data:{user:null,session:null,redirectType:null},error:a});throw a}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:a,nonce:i}=e,o=await E(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:a,nonce:i,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:Ue}),{data:l,error:u}=o;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){const d=new Rt;return this._returnResult({data:{user:null,session:null},error:d})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(r){if(x(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,a,i;try{if("email"in e){const{email:o,options:l}=e;let u=null,d=null;this.flowType==="pkce"&&([u,d]=await Nt(this.storage,this.storageKey));const{error:h}=await E(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:u,code_challenge_method:d},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in e){const{phone:o,options:l}=e,{data:u,error:d}=await E(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(n=l?.data)!==null&&n!==void 0?n:{},create_user:(a=l?.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(i=l?.channel)!==null&&i!==void 0?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:d})}throw new kr("You must provide either an email or phone number.")}catch(o){if(await _e(this.storage,`${this.storageKey}-code-verifier`),x(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async verifyOtp(e){var r,s;try{let n,a;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,a=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:i,error:o}=await E(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:n,xform:Ue});if(o)throw o;if(!i)throw new Error("An error occurred on token verification.");const l=i.session,u=i.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(x(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,a,i;try{let o=null,l=null;this.flowType==="pkce"&&([o,l]=await Nt(this.storage,this.storageKey));const u=await E(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e?.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:l}),headers:this.headers,xform:go});return!((a=u.data)===null||a===void 0)&&a.url&&we()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(o){if(await _e(this.storage,`${this.storageKey}-code-verifier`),x(o))return this._returnResult({data:null,error:o});throw o}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new be;const{error:n}=await E(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(x(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:s,type:n,options:a}=e,{error:i}=await E(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:a?.captchaToken}},redirectTo:a?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}else if("phone"in e){const{phone:s,type:n,options:a}=e,{data:i,error:o}=await E(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:a?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:i?.message_id},error:o})}throw new kr("You must provide either an email or phone number and a type")}catch(r){if(x(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await pt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<Xr:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const i=await pt(this.userStorage,this.storageKey+"-user");i?.user?e.user=i.user:e.user=ss()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const i={value:this.suppressGetSessionWarning};e.user=ho(e.user,i),i.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{session:null},error:a}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await E(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ot}):await this._useSession(async r=>{var s,n,a;const{data:i,error:o}=r;if(o)throw o;return!(!((s=i.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new be}:await E(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(a=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&a!==void 0?a:void 0,xform:ot})})}catch(r){if(x(r))return _r(r)&&(await this._removeSession(),await _e(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async s=>{const{data:n,error:a}=s;if(a)throw a;if(!n.session)throw new be;const i=n.session;let o=null,l=null;this.flowType==="pkce"&&e.email!=null&&([o,l]=await Nt(this.storage,this.storageKey));const{data:u,error:d}=await E(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:l}),jwt:i.access_token,xform:ot});if(d)throw d;return i.user=u.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(s){if(await _e(this.storage,`${this.storageKey}-code-verifier`),x(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new be;const r=Date.now()/1e3;let s=r,n=!0,a=null;const{payload:i}=jr(e.access_token);if(i.exp&&(s=i.exp,n=s<=r),n){const{data:o,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o)return{data:{user:null,session:null},error:null};a=o}else{const{data:o,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});a={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)}return this._returnResult({data:{user:a.user,session:a},error:null})}catch(r){if(x(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){const{data:i,error:o}=r;if(o)throw o;e=(s=i.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new be;const{data:n,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{user:null,session:null},error:a}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(x(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var s;try{if(!we())throw new Sr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Sr(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new Ws("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Sr("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Ws("No code detected.");const{data:k,error:N}=await this._exchangeCodeForSession(e.code);if(N)throw N;const R=new URL(window.location.href);return R.searchParams.delete("code"),window.history.replaceState(window.history.state,"",R.toString()),{data:{session:k.session,redirectType:(s=k.redirectType)!==null&&s!==void 0?s:null},error:null}}const{provider_token:n,provider_refresh_token:a,access_token:i,refresh_token:o,expires_in:l,expires_at:u,token_type:d}=e;if(!i||!l||!o||!d)throw new Sr("No session defined in URL");const h=Math.round(Date.now()/1e3),m=parseInt(l);let p=h+m;u&&(p=parseInt(u));const g=p-h;g*1e3<=Pt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${m}s`);const b=p-m;h-b>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",b,p,h):h-b<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",b,p,h);const{data:A,error:w}=await this._getUser(i);if(w)throw w;const S={provider_token:n,provider_refresh_token:a,access_token:i,expires_in:m,expires_at:p,refresh_token:o,token_type:d,user:A.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:S,redirectType:e.type},error:null})}catch(n){if(x(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await pt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;const{data:n,error:a}=r;if(a&&!_r(a))return this._returnResult({error:a});const i=(s=n.session)===null||s===void 0?void 0:s.access_token;if(i){const{error:o}=await this.admin.signOut(i,e);if(o&&!(Fi(o)&&(o.status===404||o.status===401||o.status===403)||_r(o)))return this._returnResult({error:o})}return e!=="others"&&(await this._removeSession(),await _e(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=Qi(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{const{data:{session:a},error:i}=r;if(i)throw i;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",a)),this._debug("INITIAL_SESSION","callback id",e,"session",a)}catch(a){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",a),_r(a)?console.warn(a):console.error(a)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await Nt(this.storage,this.storageKey,!0));try{return await E(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(a){if(await _e(this.storage,`${this.storageKey}-code-verifier`),x(a))return this._returnResult({data:null,error:a});throw a}}async getUserIdentities(){var e;try{const{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:s,error:n}=await this._useSession(async a=>{var i,o,l,u,d;const{data:h,error:m}=a;if(m)throw m;const p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(i=e.options)===null||i===void 0?void 0:i.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await E(this.fetch,"GET",p,{headers:this.headers,jwt:(d=(u=h.session)===null||u===void 0?void 0:u.access_token)!==null&&d!==void 0?d:void 0})});if(n)throw n;return we()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url},error:null})}catch(s){if(x(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{const{error:n,data:{session:a}}=r;if(n)throw n;const{options:i,provider:o,token:l,access_token:u,nonce:d}=e,h=await E(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=a?.access_token)!==null&&s!==void 0?s:void 0,body:{provider:o,id_token:l,access_token:u,nonce:d,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Ue}),{data:m,error:p}=h;return p?this._returnResult({data:{user:null,session:null},error:p}):!m||!m.session||!m.user?this._returnResult({data:{user:null,session:null},error:new Rt}):(m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("USER_UPDATED",m.session)),this._returnResult({data:m,error:p}))}catch(n){if(await _e(this.storage,`${this.storageKey}-code-verifier`),x(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;const{data:a,error:i}=r;if(i)throw i;return await E(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=a.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const s=Date.now();return await to(async n=>(n>0&&await eo(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await E(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Ue})),(n,a)=>{const i=200*Math.pow(2,n);return a&&ts(a)&&Date.now()+i-s<Pt})}catch(s){if(this._debug(r,"error",s),x(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),we()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await pt(this.storage,this.storageKey);if(n&&this.userStorage){let i=await pt(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!i&&(i={user:n.user},await Ct(this.userStorage,this.storageKey+"-user",i)),n.user=(e=i?.user)!==null&&e!==void 0?e:ss()}else if(n&&!n.user&&!n.user){const i=await pt(this.storage,this.storageKey+"-user");i&&i?.user?(n.user=i.user,await _e(this.storage,this.storageKey+"-user"),await Ct(this.storage,this.storageKey,n)):n.user=ss()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}const a=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Xr;if(this._debug(s,`session has${a?"":" not"} expired with margin of ${Xr}s`),a){if(this.autoRefreshToken&&n.refresh_token){const{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),ts(i)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:i,error:o}=await this._getUser(n.access_token);!o&&i?.user?(n.user=i.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(i){console.error("Error getting user data:",i),this._debug(s,"error getting user data, skipping SIGNED_IN notification",i)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new be;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Tr;const{data:a,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!a.session)throw new be;await this._saveSession(a.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const o={data:a.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(a){if(this._debug(n,"error",a),x(a)){const i={data:null,error:a};return ts(a)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(i),i}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(a),a}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const a=[],i=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,r)}catch(l){a.push(l)}});if(await Promise.all(i),a.length>0){for(let o=0;o<a.length;o+=1)console.error(a[o]);throw a[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await _e(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await Ct(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const a=Zs(n);await Ct(this.storage,this.storageKey,a)}else{const n=Zs(r);await Ct(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await _e(this.storage,this.storageKey),await _e(this.storage,this.storageKey+"-code-verifier"),await _e(this.storage,this.storageKey+"-user"),this.userStorage&&await _e(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&we()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Pt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/Pt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Pt}ms, refresh threshold is ${Qr} ticks`),n<=Qr&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof nn)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!we()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){const n=[`provider=${encodeURIComponent(r)}`];if(s?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[a,i]=await Nt(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(a)}`,code_challenge_method:`${encodeURIComponent(i)}`});n.push(o.toString())}if(s?.queryParams){const a=new URLSearchParams(s.queryParams);n.push(a.toString())}return s?.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:n,error:a}=r;return a?this._returnResult({data:null,error:a}):await E(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;const{data:a,error:i}=r;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:u}=await E(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(s=a?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&l.type==="totp"&&(!((n=l?.totp)===null||n===void 0)&&n.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:a}=r;if(a)return this._returnResult({data:null,error:a});const i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?un(e.webauthn.credential_response):dn(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:l}=await E(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:l}))})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:a}=r;if(a)return this._returnResult({data:null,error:a});const i=await E(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});if(i.error)return i;const{data:o}=i;if(o.type!=="webauthn")return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:ln(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:cn(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const a of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(a),a.status==="verified"&&n[a.factor_type].push(a);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,a;if(e)try{const{payload:p}=jr(e);let g=null;p.aal&&(g=p.aal);let b=g;const{data:{user:A},error:w}=await this.getUser(e);if(w)return this._returnResult({data:null,error:w});((s=(r=A?.factors)===null||r===void 0?void 0:r.filter(N=>N.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(b="aal2");const k=p.amr||[];return{data:{currentLevel:g,nextLevel:b,currentAuthenticationMethods:k},error:null}}catch(p){if(x(p))return this._returnResult({data:null,error:p});throw p}const{data:{session:i},error:o}=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=jr(i.access_token);let u=null;l.aal&&(u=l.aal);let d=u;((a=(n=i.user.factors)===null||n===void 0?void 0:n.filter(p=>p.status==="verified"))!==null&&a!==void 0?a:[]).length>0&&(d="aal2");const m=l.amr||[];return{data:{currentLevel:u,nextLevel:d,currentAuthenticationMethods:m},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await E(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:a=>({data:a,error:null})}):this._returnResult({data:null,error:new be})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:a}=s;if(a)return this._returnResult({data:null,error:a});if(!n)return this._returnResult({data:null,error:new be});const i=await E(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return i.data&&i.data.redirect_url&&we()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(s){if(x(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:a}=s;if(a)return this._returnResult({data:null,error:a});if(!n)return this._returnResult({data:null,error:new be});const i=await E(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return i.data&&i.data.redirect_url&&we()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(s){if(x(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await E(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new be})})}catch(e){if(x(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await E(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new be})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(o=>o.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+Bi>n)return s;const{data:a,error:i}=await E(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return!a.keys||a.keys.length===0||(this.jwks=a,this.jwks_cached_at=n,s=a.keys.find(o=>o.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:p,error:g}=await this.getSession();if(g||!p.session)return this._returnResult({data:null,error:g});s=p.session.access_token}const{header:n,payload:a,signature:i,raw:{header:o,payload:l}}=jr(s);r?.allowExpired||lo(a.exp);const u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!u){const{error:p}=await this.getUser(s);if(p)throw p;return{data:{claims:a,header:n,signature:i},error:null}}const d=co(n.alg),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,i,Ji(`${o}.${l}`)))throw new rs("Invalid JWT signature");return{data:{claims:a,header:n,signature:i},error:null}}catch(s){if(x(s))return this._returnResult({data:null,error:s});throw s}}async signInWithPasskey(e){var r,s,n;Ve(this.experimental);try{if(!Er())return this._returnResult({data:null,error:new ze("Browser does not support WebAuthn",null)});const{data:a,error:i}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}});if(i||!a)return this._returnResult({data:null,error:i});const o=cn(a.options),l=(n=(s=e?.options)===null||s===void 0?void 0:s.signal)!==null&&n!==void 0?n:as.createNewAbortSignal(),{data:u,error:d}=await mn({publicKey:o,signal:l});if(d||!u)return this._returnResult({data:null,error:d??new ze("WebAuthn ceremony failed",null)});const h=dn(u);return this._verifyPasskeyAuthentication({challengeId:a.challenge_id,credential:h})}catch(a){if(x(a))return this._returnResult({data:null,error:a});throw a}}async registerPasskey(e){var r,s;Ve(this.experimental);try{if(!Er())return this._returnResult({data:null,error:new ze("Browser does not support WebAuthn",null)});const{data:n,error:a}=await this._startPasskeyRegistration();if(a||!n)return this._returnResult({data:null,error:a});const i=ln(n.options),o=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:as.createNewAbortSignal(),{data:l,error:u}=await fn({publicKey:i,signal:o});if(u||!l)return this._returnResult({data:null,error:u??new ze("WebAuthn ceremony failed",null)});const d=un(l);return this._verifyPasskeyRegistration({challengeId:n.challenge_id,credential:d})}catch(n){if(x(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyRegistration(){Ve(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new be});const{data:n,error:a}=await E(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:n,error:null})})}catch(e){if(x(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){Ve(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new be});const{data:a,error:i}=await E(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:s.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:a,error:null})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;Ve(this.experimental);try{const{data:s,error:n}=await E(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:s,error:null})}catch(s){if(x(s))return this._returnResult({data:null,error:s});throw s}}async _verifyPasskeyAuthentication(e){Ve(this.experimental);try{const{data:r,error:s}=await E(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:Ue});return s?this._returnResult({data:null,error:s}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){Ve(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new be});const{data:n,error:a}=await E(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})});return a?this._returnResult({data:null,error:a}):this._returnResult({data:n,error:null})})}catch(e){if(x(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){Ve(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new be});const{data:a,error:i}=await E(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,body:{friendly_name:e.friendlyName}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:a,error:null})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){Ve(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new be});const{error:a}=await E(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,noResolveJson:!0});return a?this._returnResult({data:null,error:a}):this._returnResult({data:null,error:null})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}}Xt.nextInstanceID={};const Io=Xt,Do="2.105.1";let Zt="";typeof Deno<"u"?Zt="deno":typeof document<"u"?Zt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Zt="react-native":Zt="node";const $o={headers:{"X-Client-Info":`supabase-js-${Zt}/${Do}`}},Lo={schema:"public"},Uo={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Mo={};function er(t){"@babel/helpers - typeof";return er=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},er(t)}function Bo(t,e){if(er(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(er(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ko(t){var e=Bo(t,"string");return er(e)=="symbol"?e:e+""}function Fo(t,e,r){return(e=Ko(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function gn(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function ae(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?gn(Object(r),!0).forEach(function(s){Fo(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):gn(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const qo=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ho=()=>Headers,Wo=(t,e,r)=>{const s=qo(r),n=Ho();return async(a,i)=>{var o;const l=(o=await e())!==null&&o!==void 0?o:t;let u=new n(i?.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),s(a,ae(ae({},i),{},{headers:u}))}};function Go(t){return t.endsWith("/")?t:t+"/"}function zo(t,e){var r,s;const{db:n,auth:a,realtime:i,global:o}=t,{db:l,auth:u,realtime:d,global:h}=e,m={db:ae(ae({},l),n),auth:ae(ae({},u),a),realtime:ae(ae({},d),i),storage:{},global:ae(ae(ae({},h),o),{},{headers:ae(ae({},(r=h?.headers)!==null&&r!==void 0?r:{}),(s=o?.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return t.accessToken?m.accessToken=t.accessToken:delete m.accessToken,m}function Vo(t){const e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Go(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Jo=class extends Io{constructor(t){super(t)}},Yo=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const a=Vo(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const i=`sb-${a.hostname.split(".")[0]}-auth-token`,o={db:Lo,realtime:Mo,auth:ae(ae({},Uo),{},{storageKey:i}),global:$o},l=zo(r??{},o);if(this.storageKey=(s=l.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(d,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=Wo(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(ae({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(d=>this.realtime.setAuth(d)).catch(d=>console.warn("Failed to set initial Realtime auth token:",d)),this.rest=new ja(new URL("rest/v1",a).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new Di(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new ga(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:a,flowType:i,lock:o,debug:l,throwOnError:u,experimental:d},h,m){const p={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Jo({url:this.authUrl.href,headers:ae(ae({},p),h),storageKey:a,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:i,lock:o,debug:l,throwOnError:u,experimental:d,fetch:m,hasCustomAuthorizationHeader:Object.keys(this.headers).some(g=>g.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new ai(this.realtimeUrl.href,ae(ae({},t),{},{params:ae(ae({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const Qo=(t,e,r)=>new Yo(t,e,r);function Xo(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}Xo()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");function yn(t,e){if(!t||!e)throw new Error("Supabase URL and anon key are required");return Qo(t,e)}function bn(t){const e=[];let r="",s=!1;for(let n=0;n<t.length;n++){const a=t[n];a==='"'?s&&t[n+1]==='"'?(r+='"',n++):s=!s:a===","&&!s?(e.push(r),r=""):r+=a}return e.push(r),e.map(n=>n.trim().replace(/^"|"$/g,""))}function Me(t,...e){const r=n=>n.trim().toLowerCase().replace(/[_\s]+/g," ").trim(),s=new Map;Object.entries(t).forEach(([n,a])=>s.set(r(n),a));for(const n of e){const a=s.get(r(n));if(a!==void 0&&a.trim())return a.trim()}return""}function Zo(t){const r=t.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
31
+ ${y}`;let v=`URI: ${h}
32
+ Version: ${p}
33
+ Chain ID: ${r}${a?`
34
+ Nonce: ${a}`:""}
35
+ Issued At: ${i.toISOString()}`;if(n&&(v+=`
36
+ Expiration Time: ${n.toISOString()}`),o&&(v+=`
37
+ Not Before: ${o.toISOString()}`),l&&(v+=`
38
+ Request ID: ${l}`),u){let _=`
39
+ Resources:`;for(const k of u){if(!k||typeof k!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${k}`);_+=`
40
+ - ${k}`}v+=_}return`${x}
41
+ ${v}`}class de extends Error{constructor({message:e,code:r,cause:s,name:n}){var i;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(i=n??(s instanceof Error?s.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class Dr extends de{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function ll({error:t,options:e}){var r,s,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new de({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new de({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new de({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new de({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new de({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new de({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new de({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new de({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const a=window.location.hostname;if(jn(a)){if(i.rp.id!==a)return new de({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new de({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new de({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new de({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new de({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function cl({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new de({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new de({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(jn(s)){if(r.rpId!==s)return new de({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new de({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new de({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new de({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class ul{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const hs=new ul;function Sn(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);const{challenge:e,user:r,excludeCredentials:s}=t,n=gr(t,["challenge","user","excludeCredentials"]),i=$t(e).buffer,a=Object.assign(Object.assign({},r),{id:$t(r.id).buffer}),o=Object.assign(Object.assign({},n),{challenge:i,user:a});if(s&&s.length>0){o.excludeCredentials=new Array(s.length);for(let l=0;l<s.length;l++){const u=s[l];o.excludeCredentials[l]=Object.assign(Object.assign({},u),{id:$t(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return o}function xn(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);const{challenge:e,allowCredentials:r}=t,s=gr(t,["challenge","allowCredentials"]),n=$t(e).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let a=0;a<r.length;a++){const o=r[a];i.allowCredentials[a]=Object.assign(Object.assign({},o),{id:$t(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return i}function Tn(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t;return{id:t.id,rawId:t.id,response:{attestationObject:vt(new Uint8Array(t.response.attestationObject)),clientDataJSON:vt(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function En(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t,s=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:vt(new Uint8Array(n.authenticatorData)),clientDataJSON:vt(new Uint8Array(n.clientDataJSON)),signature:vt(new Uint8Array(n.signature)),userHandle:n.userHandle?vt(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function jn(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function $r(){var t,e;return!!(we()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function An(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Dr("Browser returned unexpected credential type",e)}:{data:null,error:new Dr("Empty credential response",e)}}catch(e){return{data:null,error:ll({error:e,options:t})}}}async function Pn(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Dr("Browser returned unexpected credential type",e)}:{data:null,error:new Dr("Empty credential response",e)}}catch(e){return{data:null,error:cl({error:e,options:t})}}}const dl={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},hl={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Lr(...t){const e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(const n of t)if(n)for(const i in n){const a=n[i];if(a!==void 0)if(Array.isArray(a))s[i]=a;else if(r(a))s[i]=a;else if(e(a)){const o=s[i];e(o)?s[i]=Lr(o,a):s[i]=Lr(a)}else s[i]=a}return s}function fl(t,e){return Lr(dl,t,e||{})}function ml(t,e){return Lr(hl,t,e||{})}class pl{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:s,signal:n},i){var a;try{const{data:o,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!o)return{data:null,error:l};const u=n??hs.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:d}=o.webauthn.credential_options.publicKey;if(!d.name){const h=s;if(h)d.name=`${d.id}:${h}`;else{const m=(await this.client.getUser()).data.user,g=((a=m?.user_metadata)===null||a===void 0?void 0:a.name)||m?.email||m?.id||"User";d.name=`${d.id}:${g}`}}d.displayName||(d.displayName=d.name)}switch(o.webauthn.type){case"create":{const d=fl(o.webauthn.credential_options.publicKey,i?.create),{data:h,error:p}=await An({publicKey:d,signal:u});return h?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:h}},error:null}:{data:null,error:p}}case"request":{const d=ml(o.webauthn.credential_options.publicKey,i?.request),{data:h,error:p}=await Pn(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:d,signal:u}));return h?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:h}},error:null}:{data:null,error:p}}}}catch(o){return T(o)?{data:null,error:o}:{data:null,error:new Ve("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new tr("rpId is required for WebAuthn authentication")};try{if(!$r())return{data:null,error:new Ve("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{request:i});if(!a)return{data:null,error:o};const{webauthn:l}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:s,credential_response:l.credential_response}})}catch(a){return T(a)?{data:null,error:a}:{data:null,error:new Ve("Unexpected error in authenticate",a)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new tr("rpId is required for WebAuthn registration")};try{if(!$r())return{data:null,error:new Ve("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this._enroll({friendlyName:e});if(!a)return await this.client.mfa.listFactors().then(d=>{var h;return(h=d.data)===null||h===void 0?void 0:h.all.find(p=>p.factor_type==="webauthn"&&p.friendly_name===e&&p.status!=="unverified")}).then(d=>d?this.client.mfa.unenroll({factorId:d?.id}):void 0),{data:null,error:o};const{data:l,error:u}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:i});return l?this._verify({factorId:a.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:s,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(a){return T(a)?{data:null,error:a}:{data:null,error:new Ve("Unexpected error in register",a)}}}}nl();const gl={url:po,storageKey:go,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:yo,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},Mt={};let Rn=!1;class sr{get jwks(){var e,r;return(r=(e=Mt[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Mt[this.storageKey]=Object.assign(Object.assign({},Mt[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Mt[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Mt[this.storageKey]=Object.assign(Object.assign({},Mt[this.storageKey]),{cachedAt:e})}constructor(e){var r,s,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},gl),e);if(this.storageKey=i.storageKey,this.instanceID=(r=sr.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,sr.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&we()){const a=`${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.`;console.warn(a),this.logDebugMessages&&console.trace(a)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(s=i.experimental)!==null&&s!==void 0?s:{},this.admin=new rl({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=mn(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock!=null&&(this.lock=i.lock,Rn||(Rn=!0,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`))),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new pl(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:hn()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=_n(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=_n(this.memoryStorage)),we()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a),(a.data.event==="TOKEN_REFRESHED"||a.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(o){this._debug("#broadcastChannel","error",o)}})}i.skipAutoInitialize||this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${tn}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();const r=await this.initializePromise,s=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(const n of s)await this._notifyAllSubscribers(n.event,n.session,n.broadcast);return r}async _initialize(){var e;try{let r={},s="none";if(we()&&(r=fn(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),we()&&this.detectSessionInUrl&&s!=="none"){const{data:n,error:i}=await this._getSessionFromURL(r,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),ko(i)){const l=(e=i.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:a,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",a,"redirect type",o),await this._saveSession(a),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return T(r)?this._returnResult({error:r}):this._returnResult({error:new Ve("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const i=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:Ue}),{data:a,error:o}=i;if(o||!a)return this._returnResult({data:{user:null,session:null},error:o});const l=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(i){if(T(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,s,n;let i=null;try{let a;if("email"in e){const{email:h,password:p,options:m}=e;let g=null,y=null;this.flowType==="pkce"&&([g,y,i]=await this._getCodeChallengeAndMethod()),a=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(m?.emailRedirectTo,i),body:{email:h,password:p,data:(r=m?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:m?.captchaToken},code_challenge:g,code_challenge_method:y},xform:Ue})}else if("phone"in e){const{phone:h,password:p,options:m}=e;a=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:p,data:(s=m?.data)!==null&&s!==void 0?s:{},channel:(n=m?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:m?.captchaToken}},xform:Ue})}else throw new Er("You must provide either an email or phone number and a password");const{data:o,error:l}=a;if(l||!o)return await Je(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:l});const u=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:d,session:u},error:null})}catch(a){if(await Je(this.storage,this.storageKey,i),T(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithPassword(e){try{let r;if("email"in e){const{email:i,password:a,options:o}=e;r=await P(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:vn})}else if("phone"in e){const{phone:i,password:a,options:o}=e;r=await P(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:vn})}else throw new Er("You must provide either an email or phone number and a password");const{data:s,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){const i=new Dt;return this._returnResult({data:{user:null,session:null},error:i})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,r){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,r)):this._exchangeCodeForSession(e,r)}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,s,n,i,a,o,l,u,d,h,p;let m,g;if("message"in e)m=e.message,g=e.signature;else{const{chain:y,wallet:x,statement:v,options:_}=e;let k;if(we())if(typeof x=="object")k=x;else{const L=window;if("ethereum"in L&&typeof L.ethereum=="object"&&"request"in L.ethereum&&typeof L.ethereum.request=="function")k=L.ethereum;else 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.")}else{if(typeof x!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");k=x}const O=new URL((r=_?.url)!==null&&r!==void 0?r:window.location.href),R=await k.request({method:"eth_requestAccounts"}).then(L=>L).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!R||R.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const M=kn(R[0]);let E=(s=_?.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!E){const L=await k.request({method:"eth_chainId"});E=il(L)}const $={domain:O.host,address:M,statement:v,uri:O.href,version:"1",chainId:E,nonce:(n=_?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(a=(i=_?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(o=_?.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(l=_?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=_?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(d=_?.signInWithEthereum)===null||d===void 0?void 0:d.resources};m=ol($),g=await k.request({method:"personal_sign",params:[al(m),M]})}try{const{data:y,error:x}=await P(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:g},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:Ue});if(x)throw x;if(!y||!y.session||!y.user){const v=new Dt;return this._returnResult({data:{user:null,session:null},error:v})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:x})}catch(y){if(T(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async signInWithSolana(e){var r,s,n,i,a,o,l,u,d,h,p,m;let g,y;if("message"in e)g=e.message,y=e.signature;else{const{chain:x,wallet:v,statement:_,options:k}=e;let O;if(we())if(typeof v=="object")O=v;else{const M=window;if("solana"in M&&typeof M.solana=="object"&&("signIn"in M.solana&&typeof M.solana.signIn=="function"||"signMessage"in M.solana&&typeof M.solana.signMessage=="function"))O=M.solana;else 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.")}else{if(typeof v!="object"||!k?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");O=v}const R=new URL((r=k?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in O&&O.signIn){const M=await O.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},k?.signInWithSolana),{version:"1",domain:R.host,uri:R.href}),_?{statement:_}:null));let E;if(Array.isArray(M)&&M[0]&&typeof M[0]=="object")E=M[0];else if(M&&typeof M=="object"&&"signedMessage"in M&&"signature"in M)E=M;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in E&&"signature"in E&&(typeof E.signedMessage=="string"||E.signedMessage instanceof Uint8Array)&&E.signature instanceof Uint8Array)g=typeof E.signedMessage=="string"?E.signedMessage:new TextDecoder().decode(E.signedMessage),y=E.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in O)||typeof O.signMessage!="function"||!("publicKey"in O)||typeof O!="object"||!O.publicKey||!("toBase58"in O.publicKey)||typeof O.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${R.host} wants you to sign in with your Solana account:`,O.publicKey.toBase58(),..._?["",_,""]:[""],"Version: 1",`URI: ${R.href}`,`Issued At: ${(n=(s=k?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=k?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${k.signInWithSolana.notBefore}`]:[],...!((a=k?.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${k.signInWithSolana.expirationTime}`]:[],...!((o=k?.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${k.signInWithSolana.chainId}`]:[],...!((l=k?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${k.signInWithSolana.nonce}`]:[],...!((u=k?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${k.signInWithSolana.requestId}`]:[],...!((h=(d=k?.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||h===void 0)&&h.length?["Resources",...k.signInWithSolana.resources.map(E=>`- ${E}`)]:[]].join(`
42
+ `);const M=await O.signMessage(new TextEncoder().encode(g),"utf8");if(!M||!(M instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");y=M}}try{const{data:x,error:v}=await P(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:vt(y)},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:Ue});if(v)throw v;if(!x||!x.session||!x.user){const _=new Dt;return this._returnResult({data:{user:null,session:null},error:_})}return x.session&&(await this._saveSession(x.session),await this._notifyAllSubscribers("SIGNED_IN",x.session)),this._returnResult({data:Object.assign({},x),error:v})}catch(x){if(T(x))return this._returnResult({data:{user:null,session:null},error:x});throw x}}async _exchangeCodeForSession(e,r){const s=r?.flowId!=null,n=s?Ir(r?.flowId):we()?Ir(fn(window.location.href)[bt]):null;s&&!n&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",r?.flowId);const{verifier:i,flowId:a}=s&&!n?{verifier:null,flowId:null}:await Fo(this.storage,this.storageKey,n),[o,l]=(i??"").split("/");try{if(!o&&this.flowType==="pkce")throw new So;const{data:u,error:d}=await P(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:o},xform:Ue});if(await Je(this.storage,this.storageKey,a),d)throw d;if(!u||!u.session||!u.user){const h=new Dt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:h})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers(l==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:l??null}),error:d})}catch(u){if(await Je(this.storage,this.storageKey,a),T(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:i,nonce:a}=e,o=await P(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:Ue}),{data:l,error:u}=o;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){const d=new Dt;return this._returnResult({data:{user:null,session:null},error:d})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,a;let o=null;try{if("email"in e){const{email:l,options:u}=e;let d=null,h=null;this.flowType==="pkce"&&([d,h,o]=await this._getCodeChallengeAndMethod());const{error:p}=await P(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(r=u?.data)!==null&&r!==void 0?r:{},create_user:(s=u?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},code_challenge:d,code_challenge_method:h},redirectTo:this._maybeAppendFlowIdToRedirect(u?.emailRedirectTo,o)});return this._returnResult({data:{user:null,session:null},error:p})}if("phone"in e){const{phone:l,options:u}=e,{data:d,error:h}=await P(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(n=u?.data)!==null&&n!==void 0?n:{},create_user:(i=u?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},channel:(a=u?.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:d?.message_id},error:h})}throw new Er("You must provide either an email or phone number.")}catch(l){if(await Je(this.storage,this.storageKey,o),T(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:a,error:o}=await P(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:Ue});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");const l=a.session,u=a.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(T(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i;let a=null;try{let o=null,l=null;this.flowType==="pkce"&&([o,l,a]=await this._getCodeChallengeAndMethod());const u=await P(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:this._maybeAppendFlowIdToRedirect((r=e.options)===null||r===void 0?void 0:r.redirectTo,a)}),!((s=e?.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:l}),headers:this.headers,xform:Zo});return!((n=u.data)===null||n===void 0)&&n.url&&we()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(o){if(await Je(this.storage,this.storageKey,a),T(o))return this._returnResult({data:null,error:o});throw o}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new be;const{error:n}=await P(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(T(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let r=null;try{const s=`${this.url}/resend`;if("email"in e){const{email:n,type:i,options:a}=e;let o=null,l=null;this.flowType==="pkce"&&([o,l,r]=await this._getCodeChallengeAndMethod());const{error:u}=await P(this.fetch,"POST",s,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:a?.captchaToken},code_challenge:o,code_challenge_method:l},redirectTo:this._maybeAppendFlowIdToRedirect(a?.emailRedirectTo,r)});return u&&await Je(this.storage,this.storageKey,r),this._returnResult({data:{user:null,session:null},error:u})}else if("phone"in e){const{phone:n,type:i,options:a}=e,{data:o,error:l}=await P(this.fetch,"POST",s,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:a?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:l})}throw new Er("You must provide either an email or phone number and a type")}catch(s){if(await Je(this.storage,this.storageKey,r),T(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await ke(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<os:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await ke(this.userStorage,this.storageKey+"-user");a?.user?e.user=a.user:e.user=us()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=Yo(e.user,a),a.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);if(i){if(!!(e.expires_at&&e.expires_at*1e3>Date.now())){const o=await ke(this.storage,this.storageKey);if(o&&o.refresh_token===e.refresh_token)return this._returnResult({data:{session:e},error:null})}return this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r;return this.lock!=null?r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):r=await this._getUser(),r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await P(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:dt}):await this._useSession(async r=>{var s,n,i;const{data:a,error:o}=r;if(o)throw o;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new be}:await P(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:dt})})}catch(r){if(T(r))return Tr(r)&&await this._removeSession(),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r)):await this._updateUser(e,r)}async _updateUser(e,r={}){let s=null;try{return await this._useSession(async n=>{const{data:i,error:a}=n;if(a)throw a;if(!i.session)throw new be;const o=i.session;let l=null,u=null;this.flowType==="pkce"&&e.email!=null&&([l,u,s]=await this._getCodeChallengeAndMethod());const{data:d,error:h}=await P(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(r?.emailRedirectTo,s),body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:u}),jwt:o.access_token,xform:dt});if(h)throw h;return o.user=d.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await Je(this.storage,this.storageKey,s),T(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new be;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:a}=Nr(e.access_token);if(a.exp&&(s=a.exp,n=s<=r),n){const{data:o,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o)return{data:{user:null,session:null},error:null};i=o}else{const{data:o,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(T(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){const{data:a,error:o}=r;if(o)throw o;e=(s=a.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new be;const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var s;try{if(!we())throw new jr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new jr(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new nn("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new jr("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new nn("No code detected.");const{data:k,error:O}=await this._exchangeCodeForSession(e.code,{flowId:e[bt]});if(O)throw O;const R=new URL(window.location.href);return R.searchParams.delete("code"),R.searchParams.delete(bt),window.history.replaceState(window.history.state,"",R.toString()),{data:{session:k.session,redirectType:(s=k.redirectType)!==null&&s!==void 0?s:null},error:null}}const{provider_token:n,provider_refresh_token:i,access_token:a,refresh_token:o,expires_in:l,expires_at:u,token_type:d}=e;if(!a||!l||!o||!d)throw new jr("No session defined in URL");const h=Math.round(Date.now()/1e3),p=parseInt(l);let m=h+p;u&&(m=parseInt(u));const g=m-h;g*1e3<=it&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${p}s`);const y=m-p;h-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,m,h):h-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",y,m,h);const{data:x,error:v}=await this._getUser(a);if(v)throw v;const _={provider_token:n,provider_refresh_token:i,access_token:a,expires_in:p,expires_at:m,refresh_token:o,token_type:d,user:x.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:_,redirectType:e.type},error:null})}catch(n){if(T(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;const r=Ir(e[bt]);return r&&await ke(this.storage,Lt(this.storageKey,r))?!0:!!await ke(this.storage,`${this.storageKey}-code-verifier`)}async signOut(e={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;const n=async()=>{await this._removeSession()},{data:i,error:a}=r;if(a&&!Tr(a))return this._returnResult({error:a});const o=(s=i.session)===null||s===void 0?void 0:s.access_token;if(o){const{error:l}=await this.admin.signOut(o,e);if(l&&!(sn(l)&&(l.status===404||l.status===401||l.status===403)||Tr(l)))return e!=="others"&&await n(),this._returnResult({error:l})}return e!=="others"&&await n(),this._returnResult({error:null})})}onAuthStateChange(e){const r=Oo(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)}):await this._emitInitialSession(r)))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{const{data:{session:i},error:a}=r;if(a)throw a;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),Tr(i)||Pr(i)||sn(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null,i=null;this.flowType==="pkce"&&([s,n,i]=await this._getCodeChallengeAndMethod(!0));try{return await P(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(r.redirectTo,i)})}catch(a){if(await Je(this.storage,this.storageKey,i),T(a))return this._returnResult({data:null,error:a});throw a}}async getUserIdentities(){var e;try{const{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;let s=null;try{const{data:n,error:i}=await this._useSession(async a=>{var o,l,u,d,h;const{data:p,error:m}=a;if(m)throw m;const{url:g,flowId:y}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(l=e.options)===null||l===void 0?void 0:l.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return s=y,await P(this.fetch,"GET",g,{headers:this.headers,jwt:(h=(d=p.session)===null||d===void 0?void 0:d.access_token)!==null&&h!==void 0?h:void 0})});if(i)throw i;return we()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url,flowId:s},error:null})}catch(n){if(T(n))return this._returnResult({data:{provider:e.provider,url:null,flowId:s},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{const{error:n,data:{session:i}}=r;if(n)throw n;const{options:a,provider:o,token:l,access_token:u,nonce:d}=e,h=await P(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i?.access_token)!==null&&s!==void 0?s:void 0,body:{provider:o,id_token:l,access_token:u,nonce:d,link_identity:!0,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ue}),{data:p,error:m}=h;return m?this._returnResult({data:{user:null,session:null},error:m}):!p||!p.session||!p.user?this._returnResult({data:{user:null,session:null},error:new Dt}):(p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("USER_UPDATED",p.session)),this._returnResult({data:p,error:m}))}catch(n){if(await Je(this.storage,this.storageKey,null),T(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:a}=r;if(a)throw a;return await P(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r="#_refreshAccessToken()";this._debug(r,"begin");try{const s=Date.now();return await Io(async n=>(n>0&&await No(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await P(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Ue})),(n,i)=>{const a=200*Math.pow(2,n);return i&&Pr(i)&&Date.now()+a-s<it})}catch(s){if(this._debug(r,"error",s),T(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const{url:s,flowId:n}=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),we()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s,flowId:n},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await ke(this.storage,this.storageKey);if(n&&this.userStorage){let a=await ke(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:n.user},await at(this.userStorage,this.storageKey+"-user",a)),n.user=(e=a?.user)!==null&&e!==void 0?e:us()}else if(n&&!n.user&&!n.user){const a=await ke(this.storage,this.storageKey+"-user");a&&a?.user?(n.user=a.user,await Re(this.storage,this.storageKey+"-user"),await at(this.storage,this.storageKey,n)):n.user=us()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}const i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<os;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${os}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:a}=await this._callRefreshToken(n.refresh_token);a&&(xo(a)?this._debug(s,"refresh discarded by commit guard",a):this._debug(s,"refresh failed",a))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:o}=await this._getUser(n.access_token);!o&&a?.user?(n.user=a.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(s,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),Pr(n)?console.warn(n):console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new be;if(this.refreshingDeferred)return this.refreshingDeferred.promise;if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===e&&Date.now()<this.lastRefreshFailure.expiresAt)return this._debug("#_callRefreshToken()","returning cached failure (cooldown active)"),this.lastRefreshFailure.result;const n="#_callRefreshToken()";this._debug(n,"begin");try{this.refreshingDeferred=new Cr,this.refreshingDeferred.promise.then(void 0,()=>{});const i=await ke(this.storage,this.storageKey),{data:a,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!a.session)throw new be;const l=await ke(this.storage,this.storageKey);if(i!==null&&(l===null||l.refresh_token!==i.refresh_token)){this._debug(n,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:l?"replaced":"cleared"});const p={data:null,error:new an};return this.refreshingDeferred.resolve(p),p}const d=this._sessionRemovalEpoch;if(await this._saveSession(a.session),this._sessionRemovalEpoch!==d){this._debug(n,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await Re(this.storage,this.storageKey),this.userStorage&&await Re(this.userStorage,this.storageKey+"-user");const p={data:null,error:new an};return this.refreshingDeferred.resolve(p),p}await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const h={data:a.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(h),h}catch(i){if(this._debug(n,"error",i),T(i)){const a={data:null,error:i};if(!Pr(i)){const o=await ke(this.storage,this.storageKey);!!(o?.expires_at&&o.expires_at*1e3>Date.now())?this._debug(n,"proactive refresh failed, access token still valid — preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:a,expiresAt:Date.now()+mo},(r=this.refreshingDeferred)===null||r===void 0||r.resolve(a),a}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){if(this._pendingInitNotifications!==null&&s){this._pendingInitNotifications.push({event:e,session:r,broadcast:s});return}const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const i=[],a=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,r)}catch(l){i.push(l)}});if(await Promise.all(a),i.length>0){for(let o=0;o<i.length;o+=1)console.error(i[o]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await at(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=gn(n);await at(this.storage,this.storageKey,i)}else{const n=gn(r);await at(this.storage,this.storageKey,n)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.lastRefreshFailure=null,this.suppressGetSessionWarning=!1,await Re(this.storage,this.storageKey),await Ko(this.storage,this.storageKey),await Re(this.storage,this.storageKey+"-user"),this.userStorage&&await Re(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&we()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),it);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/it);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${it}ms, refresh threshold is ${er} ticks`),n<=er&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof sl)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{const e=Date.now();try{await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/it);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${it}ms, refresh threshold is ${er} ticks`),n<=er&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!we()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;if(this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(r,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){let n=s?.redirectTo,i=null,a=null,o=null;this.flowType==="pkce"&&([i,a,o]=await this._getCodeChallengeAndMethod(),n=this._maybeAppendFlowIdToRedirect(n,o));const l=[`provider=${encodeURIComponent(r)}`];if(n&&l.push(`redirect_to=${encodeURIComponent(n)}`),s?.scopes&&l.push(`scopes=${encodeURIComponent(s.scopes)}`),i!=null&&a!=null){const u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});l.push(u.toString())}if(s?.queryParams){const u=new URLSearchParams(s.queryParams);l.push(u.toString())}return s?.skipBrowserRedirect&&l.push(`skip_http_redirect=${s.skipBrowserRedirect}`),{url:`${e}?${l.join("&")}`,flowId:o}}_maybeAppendFlowIdToRedirect(e,r){return!e||!r||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:qo(e,r)}async _getCodeChallengeAndMethod(e=!1){return Wo(this.storage,this.storageKey,e,r=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",r))}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await P(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:u}=await P(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&l.type==="totp"&&(!((n=l?.totp)===null||n===void 0)&&n.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){const r=async()=>{try{return await this._useSession(async s=>{var n;const{data:i,error:a}=s;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Tn(e.webauthn.credential_response):En(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:u}=await P(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:u}))})}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challenge(e){const r=async()=>{try{return await this._useSession(async s=>{var n;const{data:i,error:a}=s;if(a)return this._returnResult({data:null,error:a});const o=await P(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;const{data:l}=o;if(l.type!=="webauthn")return{data:l,error:null};switch(l.webauthn.type){case"create":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:Sn(l.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:xn(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challengeAndVerify(e){const{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{const{payload:m}=Nr(e);let g=null;m.aal&&(g=m.aal);let y=g;const{data:{user:x},error:v}=await this.getUser(e);if(v)return this._returnResult({data:null,error:v});((s=(r=x?.factors)===null||r===void 0?void 0:r.filter(O=>O.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(y="aal2");const k=m.amr||[];return{data:{currentLevel:g,nextLevel:y,currentAuthenticationMethods:k},error:null}}catch(m){if(T(m))return this._returnResult({data:null,error:m});throw m}const{data:{session:a},error:o}=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=Nr(a.access_token);let u=null;l.aal&&(u=l.aal);let d=u;((i=(n=a.user.factors)===null||n===void 0?void 0:n.filter(m=>m.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(d="aal2");const p=l.amr||[];return{data:{currentLevel:u,nextLevel:d,currentAuthenticationMethods:p},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await P(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new be})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new be});const a=await P(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&we()&&!r?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new be});const a=await P(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&we()&&!r?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await P(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new be})})}catch(e){if(T(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await P(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new be})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(o=>o.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+wo>n)return s;const{data:i,error:a}=await P(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,s=i.keys.find(o=>o.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:m,error:g}=await this.getSession();if(g||!m.session)return this._returnResult({data:null,error:g});s=m.session.access_token}const{header:n,payload:i,signature:a,raw:{header:o,payload:l}}=Nr(s);if(!r?.allowExpired)try{zo(i.exp)}catch(m){throw new Rr(m instanceof Error?m.message:"JWT validation failed")}const u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!u){const{error:m}=await this.getUser(s);if(m)throw m;return{data:{claims:i,header:n,signature:a},error:null}}const d=Vo(n.alg),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,a,Po(`${o}.${l}`)))throw new Rr("Invalid JWT signature");return{data:{claims:i,header:n,signature:a},error:null}}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}}async signInWithPasskey(e){var r,s,n;Ye(this.experimental);try{if(!$r())return this._returnResult({data:null,error:new Ve("Browser does not support WebAuthn",null)});const{data:i,error:a}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}});if(a||!i)return this._returnResult({data:null,error:a});const o=xn(i.options),l=(n=(s=e?.options)===null||s===void 0?void 0:s.signal)!==null&&n!==void 0?n:hs.createNewAbortSignal(),{data:u,error:d}=await Pn({publicKey:o,signal:l});if(d||!u)return this._returnResult({data:null,error:d??new Ve("WebAuthn ceremony failed",null)});const h=En(u);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:h})}catch(i){if(T(i))return this._returnResult({data:null,error:i});throw i}}async registerPasskey(e){var r,s;Ye(this.experimental);try{if(!$r())return this._returnResult({data:null,error:new Ve("Browser does not support WebAuthn",null)});const{data:n,error:i}=await this._startPasskeyRegistration();if(i||!n)return this._returnResult({data:null,error:i});const a=Sn(n.options),o=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:hs.createNewAbortSignal(),{data:l,error:u}=await An({publicKey:a,signal:o});if(u||!l)return this._returnResult({data:null,error:u??new Ve("WebAuthn ceremony failed",null)});const d=Tn(l);return this._verifyPasskeyRegistration({challengeId:n.challenge_id,credential:d})}catch(n){if(T(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyRegistration(){Ye(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new be});const{data:n,error:i}=await P(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(T(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){Ye(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new be});const{data:i,error:a}=await P(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:s.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;Ye(this.experimental);try{const{data:s,error:n}=await P(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:s,error:null})}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}}async _verifyPasskeyAuthentication(e){Ye(this.experimental);try{const{data:r,error:s}=await P(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:Ue});return s?this._returnResult({data:null,error:s}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){Ye(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new be});const{data:n,error:i}=await P(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:a=>({data:a,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(T(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){Ye(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new be});const{data:i,error:a}=await P(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,body:{friendly_name:e.friendlyName}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){Ye(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new be});const{error:i}=await P(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}}sr.nextInstanceID={};const yl=sr,bl="2.112.4";let nr="",Mr;if(typeof Deno<"u"){var fs;nr="deno",Mr=(fs=Deno.version)===null||fs===void 0?void 0:fs.deno}else if(typeof document<"u")nr="web";else if(typeof navigator<"u"&&navigator.product==="ReactNative")nr="react-native";else{var ms;nr="node";const t=globalThis.process;Mr=t==null||(ms=t.version)===null||ms===void 0?void 0:ms.replace(/^v/,"")}const On=[`runtime=${nr}`];Mr&&On.push(`runtime-version=${Mr}`);const vl={headers:{"X-Client-Info":`supabase-js/${bl}; ${On.join("; ")}`}},wl={schema:"public"},_l={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},kl={},Sl={enabled:!1,respectSamplingDecision:!0};function xl(t){if(!t||typeof t!="string")return null;const e=t.split("-");if(e.length!==4)return null;const[r,s,n,i]=e;if(r.length!==2||s.length!==32||n.length!==16||i.length!==2)return null;const a=/^[0-9a-f]+$/i;return!a.test(r)||!a.test(s)||!a.test(n)||!a.test(i)||s==="00000000000000000000000000000000"||n==="0000000000000000"?null:{version:r,traceId:s,parentId:n,traceFlags:i,isSampled:(parseInt(i,16)&1)===1}}function Tl(t,e){if(!t||!e||e.length===0)return!1;let r;if(t instanceof URL)r=t;else try{r=new URL(t)}catch{return!1}for(const s of e)try{if(typeof s=="string"){if(El(r.hostname,s))return!0}else if(s instanceof RegExp){if(s.test(r.hostname))return!0}else if(typeof s=="function"&&s(r))return!0}catch{continue}return!1}function El(t,e){if(e===t)return!0;if(e.startsWith("*.")){const r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function jl(t){const e=[];try{const r=new URL(t);e.push(r.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function ir(t){"@babel/helpers - typeof";return ir=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ir(t)}function Al(t,e){if(ir(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(ir(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Pl(t){var e=Al(t,"string");return ir(e)=="symbol"?e:e+""}function Rl(t,e,r){return(e=Pl(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Cn(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function ie(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Cn(Object(r),!0).forEach(function(s){Rl(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Cn(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const Ol=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Cl=()=>Headers,Nn=t=>t.startsWith("sb_publishable_")||t.startsWith("sb_secret_"),Nl="sb_temp_",In=new Set,Il=t=>{var e,r;if(!t.startsWith("sb_")||Nn(t)||t.startsWith(Nl))return;const s=(e=(r=t.match(/^sb_[a-zA-Z0-9]+_/))===null||r===void 0?void 0:r[0])!==null&&e!==void 0?e:"unknown";In.has(s)||(In.add(s),console.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."))},Dn=(t,e,r,s,n,i)=>{const a=Ol(s),o=Cl(),l=n?.enabled===!0,u=n?.respectSamplingDecision!==!1,d=l?jl(e):null,h=!(i?.omitApiKeyAsBearer&&Nn(t));return async(p,m)=>{const g=await r();let y=new o(m?.headers);if(y.has("apikey")||y.set("apikey",t),!y.has("Authorization")){const x=g??(h?t:null);x&&y.set("Authorization",`Bearer ${x}`)}if(d){const x=Dl(p,d,u);x&&(x.traceparent&&!y.has("traceparent")&&y.set("traceparent",x.traceparent),x.tracestate&&!y.has("tracestate")&&y.set("tracestate",x.tracestate),x.baggage&&!y.has("baggage")&&y.set("baggage",x.baggage))}return a(p,ie(ie({},m),{},{headers:y}))}};let $n=!1,Ln=!1;function Dl(t,e,r){const s=$i();if(!s)return $n||($n=!0,console.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.")),null;if(!Tl(typeof t=="string"||t instanceof URL?t:t.url,e))return null;const n=s();if(!n||!n.traceparent){var i;if(!(n==null||(i=n.carrierKeys)===null||i===void 0)&&i.length&&!Ln){Ln=!0;const a=n.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.";console.warn(`@supabase/supabase-js: tracePropagation is enabled and a tracing SDK is active, but its propagator wrote [${n.carrierKeys.join(", ")}] and no W3C traceparent header, so trace headers will not be attached.`+a)}return null}if(r){const a=xl(n.traceparent);if(a&&!a.isSampled)return{traceparent:n.traceparent}}return n}function Mn(t){return typeof t=="boolean"?{enabled:t}:t}function $l(t){return t.endsWith("/")?t:t+"/"}function Ll(t,e){var r,s,n,i,a,o;const{db:l,auth:u,realtime:d,global:h}=t,{db:p,auth:m,realtime:g,global:y}=e,x=Mn(t.tracePropagation),v=Mn(e.tracePropagation),_={db:ie(ie({},p),l),auth:ie(ie({},m),u),realtime:ie(ie({},g),d),storage:{},global:ie(ie(ie({},y),h),{},{headers:ie(ie({},(r=y?.headers)!==null&&r!==void 0?r:{}),(s=h?.headers)!==null&&s!==void 0?s:{})}),tracePropagation:{enabled:(n=(i=x?.enabled)!==null&&i!==void 0?i:v?.enabled)!==null&&n!==void 0?n:!1,respectSamplingDecision:(a=(o=x?.respectSamplingDecision)!==null&&o!==void 0?o:v?.respectSamplingDecision)!==null&&a!==void 0?a:!0},accessToken:async()=>""};return t.accessToken?_.accessToken=t.accessToken:delete _.accessToken,_}function Ml(t){const e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL($l(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Ul=class extends yl{constructor(t){super(t)}},Bl=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=Ml(t);if(!e)throw new Error("supabaseKey is required.");Il(e),this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const a=`sb-${i.hostname.split(".")[0]}-auth-token`,o={db:wl,realtime:kl,auth:ie(ie({},_l),{},{storageKey:a}),global:vl,tracePropagation:Sl},l=Ll(r??{},o);if(this.settings=l,this.storageKey=(s=l.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(d,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=Dn(e,t,this._getSessionToken.bind(this),l.global.fetch,l.tracePropagation),this.functionsFetch=Dn(e,t,this._getSessionToken.bind(this),l.global.fetch,l.tracePropagation,{omitApiKeyAsBearer:!0}),this.realtime=this._initRealtimeClient(ie({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(d=>this.realtime.setAuth(d)).catch(d=>console.warn("Failed to set initial Realtime auth token:",d)),this.rest=new Ji(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit,retry:l.db.retry}),this.storage=new fo(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new Bi(this.functionsUrl.href,{headers:this.headers,customFetch:this.functionsFetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getSessionToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:null}async _getAccessToken(){var t=this,e;return(e=await t._getSessionToken())!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:a,lock:o,debug:l,throwOnError:u,experimental:d,lockAcquireTimeout:h,skipAutoInitialize:p},m,g){const y={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Ul({url:this.authUrl.href,headers:ie(ie({},y),m),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:o,debug:l,throwOnError:u,experimental:d,fetch:g,lockAcquireTimeout:h,skipAutoInitialize:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(x=>x.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new La(this.realtimeUrl.href,ie(ie({},t),{},{params:ie(ie({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN"||t==="INITIAL_SESSION")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const Fl=(t,e,r)=>new Bl(t,e,r);function Kl(){if(typeof window<"u"||globalThis.Deno!==void 0)return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=20:!1}Kl()&&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");function Un(t,e){if(!t||!e)throw new Error("Supabase URL and anon key are required");return Fl(t,e)}function Bn(t){const e=[];let r="",s=!1;for(let n=0;n<t.length;n++){const i=t[n];i==='"'?s&&t[n+1]==='"'?(r+='"',n++):s=!s:i===","&&!s?(e.push(r),r=""):r+=i}return e.push(r),e.map(n=>n.trim().replace(/^"|"$/g,""))}function Be(t,...e){const r=n=>n.trim().toLowerCase().replace(/[_\s]+/g," ").trim(),s=new Map;Object.entries(t).forEach(([n,i])=>s.set(r(n),i));for(const n of e){const i=s.get(r(n));if(i!==void 0&&i.trim())return i.trim()}return""}function ql(t){const r=t.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
58
43
  `).trim().split(`
59
- `);if(r.length<2)return[];const s=bn(r[0]),n=[];for(let a=1;a<r.length;a++){const i=bn(r[a]);if(i.length<s.length)continue;const o={};s.forEach((m,p)=>{o[m]=i[p]??""});const l=Me(o,"store_id","store id"),u=Me(o,"pooja_title","pooja title","puja title");if(!l||!u)continue;const d=Me(o,"cover_media_url","cover media url","cover image"),h=Me(o,"cover_media_url_english","cover media url english","cover image english");n.push({store_id:l,pooja_title:u,temple_name:Me(o,"temple_name","temple name")||"",pooja_title_english:Me(o,"pooja_title_english","pooja title english","puja title english")||void 0,temple_name_english:Me(o,"temple_name_english","temple name english")||void 0,cover_media_url:d||void 0,cover_media_url_english:h||void 0,puja_link:Me(o,"puja_link","puja link","pooja link")||Me(o,"puja link","pooja link")||"",puja_link_hindi:Me(o,"puja_link_hindi","puja link hindi","pooja link hindi")||void 0,individual_pack_price_inr:parseFloat(Me(o,"individual_pack_price_inr","individual pack price inr","price"))||0,schedule_date_ist:Me(o,"schedule_date_ist","schedule date ist","schedule date")||""})}return n}const vn={mangal:["mangal","manglik","kuja","मंगल","मांगलिक","30 day","30-day","30 din"],"kaal-sarp":["kaal sarp","kaal-sarp","kaalsarp","काल सर्प","कालसर्प","sarp"],kaalSarp:["kaal sarp","kaal-sarp","kaalsarp","काल सर्प","कालसर्प","sarp"],pitra:["pitru","pitra","पितृ","पितर","pitra dosha","pitru dosha"],shani:["shani","saturn","शनि","sade sati","साढ़े साती","साढ़ेसाती","sade saati"],sadeSati:["shani","saturn","शनि","sade sati","साढ़े साती","साढ़ेसाती","sade saati"]};function el(t){const e=t.split("/");if(e.length!==3)return null;const r=parseInt(e[0],10),s=parseInt(e[1],10)-1,n=parseInt(e[2],10);return new Date(n,s,r)}function wn(t,e){const r=vn[e]||vn[e.toLowerCase()];if(!r||r.length===0)return null;const s=t.filter(i=>{const o=(i.pooja_title||"").toLowerCase(),l=(i.pooja_title_english||"").toLowerCase();return o.includes("rashi")||l.includes("rashi")?!1:r.some(u=>o.includes(u.toLowerCase())||l.includes(u.toLowerCase()))});if(s.length===0)return null;const n=new Date;return n.setHours(0,0,0,0),(s.filter(i=>{const o=el(i.schedule_date_ist);return o?o.getTime()>=n.getTime():!0})[0]??s[0])||null}let Dt=[],_n=0;const tl=3600*1e3;async function rl(t){const e=Date.now();if(Dt.length>0&&e-_n<tl)return Dt;try{const{data:r,error:s}=await t.functions.invoke("fetch-pujas");if(s)return console.warn("[DoshaCalculator] fetch-pujas error:",s),Dt;const n=typeof r=="string"?r:"";if(!n)return Dt;const a=Zo(n);return Dt=a,_n=e,a}catch(r){return console.warn("[DoshaCalculator] fetchPujas error:",r),Dt}}const kn={"पितृ दोष निवारण महायज्ञ एवं काशी गंगा महाआरती":"Pitru Dosha Nivaran Mahayagya & Kashi Ganga Maha Aarti","पितृ दोष शांति महापूजा एवं काशी गंगा आरती":"Pitra Dosha Shanti Mahapuja & Kashi Ganga Aarti","पितृ दोष निवारण पूजा एवं काशी गंगा आरती":"Pitra Dosha Nivaran Puja & Kashi Ganga Aarti","त्र्यंबकेश्वर ज्योतिर्लिंग रुद्राभिषेक और काल सर्प दोष निवारण पूजा":"Trimbakeshwar Jyotirlinga Rudrabhishek & Kaal Sarp Dosha Nivaran Puja","काल सर्प दोष निवारण पूजा एवं त्र्यंबकेश्वर ज्योतिर्लिंग रुद्राभिषेक":"Kaal Sarp Dosha Nivaran Puja & Trimbakeshwar Jyotirlinga Rudrabhishek","राहु-सूर्य दोष निवारण पूजा":"Rahu-Surya Dosha Nivaran Puja","मंगल दोष निवारण पूजा":"Mangal Dosha Nivaran Puja","शनि शांति पूजा":"Shani Shanti Puja","शनि साढ़े साती शांति पूजा":"Shani Sade Sati Shanti Puja","नवग्रह शांति पूजा":"Navagraha Shanti Puja","गुरु चांडाल दोष निवारण पूजा":"Guru Chandal Dosha Nivaran Puja","श्रापित दोष निवारण पूजा":"Shrapit Dosha Nivaran Puja","काल सर्प दोष पूजा":"Kaal Sarp Dosha Puja","मंगल पूजा":"Mangal Puja","शनि पूजा":"Shani Puja","राहु पूजा":"Rahu Puja","केतु पूजा":"Ketu Puja","नवग्रह शांति पूजा, शनि तिल तेल अभिषेक और पाप ग्रह शांति यज्ञ":"Navagraha Shanti Puja, Shani Til Tel Abhishek and Paap Graha Shanti Yagya","30 दिन मंगल दोष निवारण पूजा":"30-Day Mangal Dosha Nivaran Puja","30 दिनों में मंगल दोष निवारण पूजा":"30-Day Mangal Dosha Nivaran Puja","30 दिन मंगल पूजा":"30-Day Mangal Puja","30 लाख मंगल जाप":"30 Lakh Mangal Jaap","शनि साढ़ेसाती शांति पूजा":"Shani Sade Sati Shanti Puja","शनि महादशा शांति पूजा":"Shani Mahadasha Shanti Puja","शनि दोष निवारण पूजा":"Shani Dosha Nivaran Puja","काल सर्प दोष निवारण महापूजा":"Kaal Sarp Dosha Nivaran Mahapuja","पिशाच मोचन कुंड पूजा":"Pishach Mochan Kund Puja","पितृ तर्पण पूजा":"Pitru Tarpan Puja"},sl={पूजा:"Puja",महापूजा:"Mahapuja",दोष:"Dosha",निवारण:"Nivaran",शांति:"Shanti",महायज्ञ:"Mahayagya",यज्ञ:"Yagya",अभिषेक:"Abhishek",रुद्राभिषेक:"Rudrabhishek",आरती:"Aarti",महाआरती:"Maha Aarti",महादशा:"Mahadasha",मंदिर:"Temple",ज्योतिर्लिंग:"Jyotirlinga",देव:"Dev",एवं:"&",और:"and",तिल:"Til",तेल:"Tel",गंगा:"Ganga",पाप:"Paap",ग्रह:"Graha",नवग्रह:"Navagraha",मंगल:"Mangal",शनि:"Shani","साढ़े साती":"Sade Sati",साढ़ेसाती:"Sade Sati",राहु:"Rahu",केतु:"Ketu",गुरु:"Guru",सूर्य:"Surya",चंद्र:"Chandra",चन्द्र:"Chandra",बुध:"Budh",शुक्र:"Shukra","काल सर्प":"Kaal Sarp",कालसर्प:"Kaal Sarp",पितृ:"Pitru",पितर:"Pitra",श्रापित:"Shrapit",चांडाल:"Chandal",काशी:"Kashi",त्र्यंबकेश्वर:"Trimbakeshwar",हथला:"Hathla"},Sn={"काशी विश्वनाथ मंदिर":"Kashi Vishwanath Temple","त्र्यंबकेश्वर मंदिर":"Trimbakeshwar Temple","त्र्यंबकेश्वर ज्योतिर्लिंग":"Trimbakeshwar Jyotirlinga","महाकालेश्वर मंदिर":"Mahakaleshwar Temple","सोमनाथ मंदिर":"Somnath Temple","केदारनाथ मंदिर":"Kedarnath Temple","बद्रीनाथ मंदिर":"Badrinath Temple","रामेश्वरम मंदिर":"Rameshwaram Temple","द्वारकाधीश मंदिर":"Dwarkadhish Temple","जगन्नाथ पुरी मंदिर":"Jagannath Puri Temple","हथला शनि देव मंदिर":"Hathla Shani Dev Temple"};function nl(t){const e=t.split("/");if(e.length!==3)return null;const r=parseInt(e[0],10),s=parseInt(e[1],10)-1,n=parseInt(e[2],10);return new Date(n,s,r)}function xn(t){let e=t;return Object.entries(sl).sort((s,n)=>n[0].length-s[0].length).forEach(([s,n])=>{const a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi");e=e.replace(a,n)}),e.replace(/\s+/g," ").trim()}function is(t,e){const r=e?.toLowerCase().startsWith("hi"),s=typeof t=="string"?t:t.pooja_title,n=typeof t=="string"?void 0:t.pooja_title_english;if(r)return s;if(n?.trim())return n;if(kn[s])return kn[s];const a=xn(s);return a!==s?a:s}function Tn(t,e){const r=e?.toLowerCase().startsWith("hi"),s=typeof t=="string"?t:t.temple_name,n=typeof t=="string"?void 0:t.temple_name_english;if(r)return s;if(n?.trim())return n;if(Sn[s])return Sn[s];const a=xn(s);return a!==s?a:s}function jn(t,e="en"){const r=nl(t);if(!r)return t;const n=e?.toLowerCase().startsWith("hi")?"hi-IN":"en-GB";return new Intl.DateTimeFormat(n,{day:"numeric",month:"short",year:"numeric"}).format(r)}function al(t){if(!t||typeof window>"u")return t;try{const e=new URLSearchParams(window.location.search),r=e.get("utm_source"),s=e.get("utm_medium"),n=e.get("utm_content");if(!r&&!s&&!n)return t;const a=new URL(t);return r&&a.searchParams.set("utm_source",r),s&&a.searchParams.set("utm_medium",s),n&&a.searchParams.set("utm_content",n),a.toString()}catch{return t}}function os(t,e){const s=e?.toLowerCase().startsWith("hi")?t.puja_link_hindi||t.puja_link:t.puja_link||t.puja_link_hindi;return al(s||"")}function An(t,e){return e?.toLowerCase().startsWith("hi")?t.cover_media_url||t.cover_media_url_english||"":t.cover_media_url_english||t.cover_media_url||""}const il={container:"_container_m8vst_1"},ol=["en","hi"],ll={en:"English",hi:"हिन्दी"},En={en:{language:"Language",guest:"Guest",sriMandir:"Sri Mandir",ratingText:"3 Crore+ app downloads",feedbackTitle:"What Others Discovered Through Their Dosha Analysis",feedbackTrust:"Trusted by over 5 crore users worldwide",feedbackRating:"4.9",feedbackTestimonial1:"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.",feedbackTestimonial2:"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.",feedbackTestimonial3:"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.",feedbackTestimonial4:"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.",feedbackTestimonial5:"Simple and clear guidance. Problems in job and health both reduced after remedies. Good service.",feedbackTestimonial6:"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.",feedbackTestimonial7:"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.",feedbackTestimonial8:"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.",feedbackTestimonial9:"Very genuine report not copy paste. Health issue reason also explained. After remedies I feel more energy and mind peace. Satisfied.",feedbackTestimonial10:"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.",feedbackTestimonial11:"I was not believing before but result surprised me. Career growth started after long time and new opportunities coming. Good guidance and honest prediction.",feedbackTestimonial12:"Health problems and negative thoughts were too much. After following remedies I feel mentally strong and peaceful. Family also noticing the change. Very grateful.",feedbackTestimonial13:"Short review. Career better now and money flow also improved after remedy. Thank you.",feedbackTestimonial14:"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.",feedbackTestimonial15:"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.",feedbackAuthor1:"Abhishek Mishra",feedbackAuthor2:"Pooja Verma",feedbackAuthor3:"Amit Patel",feedbackAuthor4:"Sneha Gupta",feedbackAuthor5:"Vikas Yadav",feedbackAuthor6:"Neha Singh",feedbackAuthor7:"Rahul Jain",feedbackAuthor8:"Kavita Mishra",feedbackAuthor9:"Sandeep Kumar",feedbackAuthor10:"Anjali Mehta",feedbackAuthor11:"Deepak Arora",feedbackAuthor12:"Ritu Saxena",feedbackAuthor13:"Manoj Tiwari",feedbackAuthor14:"Priya Nair",feedbackAuthor15:"Karan Malhotra",feedbackAuthor1AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639330970.png",feedbackAuthor2AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639293055.png",feedbackAuthor3AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639358174.png",feedbackAuthor4AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639427379.png",feedbackAuthor5AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639381899.png",feedbackAuthor6AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639416587.png",feedbackAuthor7AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639454626.png",feedbackAuthor8AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639319028.png",feedbackAuthor9AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639271096.png",feedbackAuthor10AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639254172.png",feedbackAuthor11AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639345411.png",feedbackAuthor12AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639306698.png",feedbackAuthor13AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639330970.png",feedbackAuthor14AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639402894.png",feedbackAuthor15AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639358174.png",readMoreReviews:"Read More Reviews",readLess:"Read Less",feedbackTitleMarriage:"What others facing marriage delay discovered",feedbackTestimonialMarriage1:"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.",feedbackTestimonialMarriage2:"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.",feedbackTestimonialMarriage3:"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.",feedbackTestimonialMarriage4:"Very helpful service. Found reason for delay in marriage and solution also given. Things improved slowly.",feedbackTestimonialMarriage5:"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.",feedbackTestimonialMarriage6:"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.",feedbackTestimonialMarriage7:"Short review but true. Marriage dosh removed after remedies and now wedding date fixed. Thank you so much.",feedbackTestimonialMarriage8:"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.",feedbackTestimonialMarriage9:"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.",feedbackTestimonialMarriage10:"Service is good and fast. Report is clear. My marriage problem solved after remedy. Satisfied.",feedbackTestimonialMarriage11:"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.",feedbackTestimonialMarriage12:"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.",feedbackTestimonialMarriage13:"Nice guidance and honest prediction. No false promises. Remedies worked for my delayed marriage issue.",feedbackTestimonialMarriage14:"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.",feedbackTestimonialMarriage15:"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.",faqTitle:"Frequently Asked Questions",faqQ1:"Is this really free?",faqA1:"Yes, the Dosha Calculator is completely free to use. You can check your kundli for doshas and get detailed analysis at no cost.",faqQ2:"What if I don't know birth time?",faqA2:"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.",faqQ3:"Is this a generic report?",faqA3:"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.",faqQ1Marriage:"Is this really free?",faqA1Marriage:"Yes, the Dosha Calculator is completely free to use. You can check your kundli for doshas and get detailed analysis at no cost.",faqQ2Marriage:"What if I don't know birth time?",faqA2Marriage:"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.",faqQ3Marriage:"Is this a generic report?",faqA3Marriage:"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.",faqQ4Marriage:"Will this fix my marriage delay?",faqA4Marriage:"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.",formPrivacyBanner:"100% Private & Secure",formTitle:"Enter your details",formSubtitle:"We'll generate your kundli to know your doshas",formNameLabel:"Enter Your Name",formNamePlaceholder:"Your Name",formGenderLabel:"Your Gender",formGenderMale:"Male",formGenderFemale:"Female",formProblemLabel:"What problem is bothering you?",formProblemMarriage:"Marriage",formProblemMoney:"Money",formProblemOther:"Others",formProblemHealth:"Health",formProblemEducation:"Education",formProblemCareer:"Career",formProblemOtherPlaceholder:"Please describe your problem",formProblemOtherHint:"Max 100 characters",formDobLabel:"Select Date of Birth",formDobInfo:"Your date of birth is used to calculate your dosha balance.",formTimeLabel:"Exact Time of Birth",formTimeInfo:"Birth time helps improve accuracy of the analysis.",formTimeUnknown:"I don't know my birth time",formTimeUnknownHelp:"Note - Without exact birth time, accuracy will be reduced. We'll run Moon-based checks only.",formPlaceLabel:"Enter your birth place",formPlaceInfo:"City and state/country help us refine your result.",formPlacePlaceholder:"City, State",formFooterNote:"Analysis Takes Only 60 seconds",formFooterNoteBefore:"Analysis Takes Only ",formFooterNoteBold:"60 seconds",formFooterNoteAfter:"",formCta:"Check My Dosha for FREE",formCtaCalculate:"Calculate my Dosha",calculating:"Calculating...",bookPuja:"Book Puja",resultPageTitle:"Find Puja Remedy for Free",resultPageSubtitle:"Analyse your kundli to find out which doshas (if any) appear in your Vedic chart—and see devotional remedies.",calculationSuccess:"Your dosha analysis is ready.",calculationError:"Something went wrong. Please try again.",formError:"Please correct the highlighted fields.",formNameRequired:"Name is required.",formGenderRequired:"Gender is required.",formDobRequired:"Date of birth is required.",formTimeRequired:"Time is required when birth time is known.",formPlaceRequired:"Birth place is required.",formPlaceSelectFromDropdown:"Please select a place from the dropdown list.",formAgeMarriageRestriction:"Please select appropriate problem areas. Marriage, financial, career, and business-related issues are applicable for users above 18 years.",locationError:"Could not get location coordinates. Please try again.",calculationResolvingPlace:"Resolving place…",info:"Info",resultTitle:"Your Dosha Analysis",resultSomeDoshas:"Some Doshas Have Been Detected",resultNoDoshas:"No Major Doshas Found",resultNoDoshasDesc:"Your birth chart shows no major doshas.",resultMangal:"Mangal Dosha",resultKaalSarp:"Kaal Sarp Dosha",resultPitra:"Pitra Dosha",resultSadeSati:"Shani Sade Sati",resultStatusPresent:"Present",resultStatusAbsent:"Absent",resultStatusInactive:"Inactive",resultExplanation:"Explanation",resultRemedies:"Remedies",resultEditForm:"Edit details",drStatus:"Status",drSeverity:"Severity",drType:"Type",drPhase:"Phase",drExplanation:"Explanation",drWhyPresent:"Why Present",drWhyAbsent:"Why Absent",drImpact:"Impact",drPlanetaryPositions:"Planetary Positions",drTraditionalRemedies:"Traditional Remedies",drDetailedAnalysis:"Detailed Analysis & Remedies",drBasedOnChart:"Based on your birth chart calculations",drDisclaimer:"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.",drStatusPresent:"Present",drStatusAbsent:"Absent",drStatusInactive:"Inactive",drStatusActive:"Active",drStatusSuggested:"Suggested",drStatusNullified:"Present (Nullified)",drMangalName:"Mangal Dosha (Manglik)",drMangalDesc:"Mangal (Manglik/Kuja) Dosha — Linked with Mars in certain houses; traditionally associated with friction in relationships and decisiveness.",drMangalImpact:"Greater likelihood of friction in close relationships, impatience/anger spikes, or delays and stops/starts in marriage or partnerships.",drMangalRemedies:`Recite Hanuman Chalisa daily
44
+ `);if(r.length<2)return[];const s=Bn(r[0]),n=[];for(let i=1;i<r.length;i++){const a=Bn(r[i]);if(a.length<s.length)continue;const o={};s.forEach((p,m)=>{o[p]=a[m]??""});const l=Be(o,"store_id","store id"),u=Be(o,"pooja_title","pooja title","puja title");if(!l||!u)continue;const d=Be(o,"cover_media_url","cover media url","cover image"),h=Be(o,"cover_media_url_english","cover media url english","cover image english");n.push({store_id:l,pooja_title:u,temple_name:Be(o,"temple_name","temple name")||"",pooja_title_english:Be(o,"pooja_title_english","pooja title english","puja title english")||void 0,temple_name_english:Be(o,"temple_name_english","temple name english")||void 0,cover_media_url:d||void 0,cover_media_url_english:h||void 0,puja_link:Be(o,"puja_link","puja link","pooja link")||Be(o,"puja link","pooja link")||"",puja_link_hindi:Be(o,"puja_link_hindi","puja link hindi","pooja link hindi")||void 0,individual_pack_price_inr:parseFloat(Be(o,"individual_pack_price_inr","individual pack price inr","price"))||0,schedule_date_ist:Be(o,"schedule_date_ist","schedule date ist","schedule date")||""})}return n}const Fn={mangal:["mangal","manglik","kuja","मंगल","मांगलिक","30 day","30-day","30 din"],"kaal-sarp":["kaal sarp","kaal-sarp","kaalsarp","काल सर्प","कालसर्प","sarp"],kaalSarp:["kaal sarp","kaal-sarp","kaalsarp","काल सर्प","कालसर्प","sarp"],pitra:["pitru","pitra","पितृ","पितर","pitra dosha","pitru dosha"],shani:["shani","saturn","शनि","sade sati","साढ़े साती","साढ़ेसाती","sade saati"],sadeSati:["shani","saturn","शनि","sade sati","साढ़े साती","साढ़ेसाती","sade saati"]};function Wl(t){const e=t.split("/");if(e.length!==3)return null;const r=parseInt(e[0],10),s=parseInt(e[1],10)-1,n=parseInt(e[2],10);return new Date(n,s,r)}function Kn(t,e){const r=Fn[e]||Fn[e.toLowerCase()];if(!r||r.length===0)return null;const s=t.filter(a=>{const o=(a.pooja_title||"").toLowerCase(),l=(a.pooja_title_english||"").toLowerCase();return o.includes("rashi")||l.includes("rashi")?!1:r.some(u=>o.includes(u.toLowerCase())||l.includes(u.toLowerCase()))});if(s.length===0)return null;const n=new Date;return n.setHours(0,0,0,0),(s.filter(a=>{const o=Wl(a.schedule_date_ist);return o?o.getTime()>=n.getTime():!0})[0]??s[0])||null}let Ut=[],qn=0;const Hl=3600*1e3;async function Gl(t){const e=Date.now();if(Ut.length>0&&e-qn<Hl)return Ut;try{const{data:r,error:s}=await t.functions.invoke("fetch-pujas");if(s)return console.warn("[DoshaCalculator] fetch-pujas error:",s),Ut;const n=typeof r=="string"?r:"";if(!n)return Ut;const i=ql(n);return Ut=i,qn=e,i}catch(r){return console.warn("[DoshaCalculator] fetchPujas error:",r),Ut}}const Wn={"पितृ दोष निवारण महायज्ञ एवं काशी गंगा महाआरती":"Pitru Dosha Nivaran Mahayagya & Kashi Ganga Maha Aarti","पितृ दोष शांति महापूजा एवं काशी गंगा आरती":"Pitra Dosha Shanti Mahapuja & Kashi Ganga Aarti","पितृ दोष निवारण पूजा एवं काशी गंगा आरती":"Pitra Dosha Nivaran Puja & Kashi Ganga Aarti","त्र्यंबकेश्वर ज्योतिर्लिंग रुद्राभिषेक और काल सर्प दोष निवारण पूजा":"Trimbakeshwar Jyotirlinga Rudrabhishek & Kaal Sarp Dosha Nivaran Puja","काल सर्प दोष निवारण पूजा एवं त्र्यंबकेश्वर ज्योतिर्लिंग रुद्राभिषेक":"Kaal Sarp Dosha Nivaran Puja & Trimbakeshwar Jyotirlinga Rudrabhishek","राहु-सूर्य दोष निवारण पूजा":"Rahu-Surya Dosha Nivaran Puja","मंगल दोष निवारण पूजा":"Mangal Dosha Nivaran Puja","शनि शांति पूजा":"Shani Shanti Puja","शनि साढ़े साती शांति पूजा":"Shani Sade Sati Shanti Puja","नवग्रह शांति पूजा":"Navagraha Shanti Puja","गुरु चांडाल दोष निवारण पूजा":"Guru Chandal Dosha Nivaran Puja","श्रापित दोष निवारण पूजा":"Shrapit Dosha Nivaran Puja","काल सर्प दोष पूजा":"Kaal Sarp Dosha Puja","मंगल पूजा":"Mangal Puja","शनि पूजा":"Shani Puja","राहु पूजा":"Rahu Puja","केतु पूजा":"Ketu Puja","नवग्रह शांति पूजा, शनि तिल तेल अभिषेक और पाप ग्रह शांति यज्ञ":"Navagraha Shanti Puja, Shani Til Tel Abhishek and Paap Graha Shanti Yagya","30 दिन मंगल दोष निवारण पूजा":"30-Day Mangal Dosha Nivaran Puja","30 दिनों में मंगल दोष निवारण पूजा":"30-Day Mangal Dosha Nivaran Puja","30 दिन मंगल पूजा":"30-Day Mangal Puja","30 लाख मंगल जाप":"30 Lakh Mangal Jaap","शनि साढ़ेसाती शांति पूजा":"Shani Sade Sati Shanti Puja","शनि महादशा शांति पूजा":"Shani Mahadasha Shanti Puja","शनि दोष निवारण पूजा":"Shani Dosha Nivaran Puja","काल सर्प दोष निवारण महापूजा":"Kaal Sarp Dosha Nivaran Mahapuja","पिशाच मोचन कुंड पूजा":"Pishach Mochan Kund Puja","पितृ तर्पण पूजा":"Pitru Tarpan Puja"},zl={पूजा:"Puja",महापूजा:"Mahapuja",दोष:"Dosha",निवारण:"Nivaran",शांति:"Shanti",महायज्ञ:"Mahayagya",यज्ञ:"Yagya",अभिषेक:"Abhishek",रुद्राभिषेक:"Rudrabhishek",आरती:"Aarti",महाआरती:"Maha Aarti",महादशा:"Mahadasha",मंदिर:"Temple",ज्योतिर्लिंग:"Jyotirlinga",देव:"Dev",एवं:"&",और:"and",तिल:"Til",तेल:"Tel",गंगा:"Ganga",पाप:"Paap",ग्रह:"Graha",नवग्रह:"Navagraha",मंगल:"Mangal",शनि:"Shani","साढ़े साती":"Sade Sati",साढ़ेसाती:"Sade Sati",राहु:"Rahu",केतु:"Ketu",गुरु:"Guru",सूर्य:"Surya",चंद्र:"Chandra",चन्द्र:"Chandra",बुध:"Budh",शुक्र:"Shukra","काल सर्प":"Kaal Sarp",कालसर्प:"Kaal Sarp",पितृ:"Pitru",पितर:"Pitra",श्रापित:"Shrapit",चांडाल:"Chandal",काशी:"Kashi",त्र्यंबकेश्वर:"Trimbakeshwar",हथला:"Hathla"},Hn={"काशी विश्वनाथ मंदिर":"Kashi Vishwanath Temple","त्र्यंबकेश्वर मंदिर":"Trimbakeshwar Temple","त्र्यंबकेश्वर ज्योतिर्लिंग":"Trimbakeshwar Jyotirlinga","महाकालेश्वर मंदिर":"Mahakaleshwar Temple","सोमनाथ मंदिर":"Somnath Temple","केदारनाथ मंदिर":"Kedarnath Temple","बद्रीनाथ मंदिर":"Badrinath Temple","रामेश्वरम मंदिर":"Rameshwaram Temple","द्वारकाधीश मंदिर":"Dwarkadhish Temple","जगन्नाथ पुरी मंदिर":"Jagannath Puri Temple","हथला शनि देव मंदिर":"Hathla Shani Dev Temple"};function Vl(t){const e=t.split("/");if(e.length!==3)return null;const r=parseInt(e[0],10),s=parseInt(e[1],10)-1,n=parseInt(e[2],10);return new Date(n,s,r)}function Gn(t){let e=t;return Object.entries(zl).sort((s,n)=>n[0].length-s[0].length).forEach(([s,n])=>{const i=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi");e=e.replace(i,n)}),e.replace(/\s+/g," ").trim()}function ps(t,e){const r=e?.toLowerCase().startsWith("hi"),s=typeof t=="string"?t:t.pooja_title,n=typeof t=="string"?void 0:t.pooja_title_english;if(r)return s;if(n?.trim())return n;if(Wn[s])return Wn[s];const i=Gn(s);return i!==s?i:s}function zn(t,e){const r=e?.toLowerCase().startsWith("hi"),s=typeof t=="string"?t:t.temple_name,n=typeof t=="string"?void 0:t.temple_name_english;if(r)return s;if(n?.trim())return n;if(Hn[s])return Hn[s];const i=Gn(s);return i!==s?i:s}function Vn(t,e="en"){const r=Vl(t);if(!r)return t;const n=e?.toLowerCase().startsWith("hi")?"hi-IN":"en-GB";return new Intl.DateTimeFormat(n,{day:"numeric",month:"short",year:"numeric"}).format(r)}function Jl(t){if(!t||typeof window>"u")return t;try{const e=new URLSearchParams(window.location.search),r=e.get("utm_source"),s=e.get("utm_medium"),n=e.get("utm_content");if(!r&&!s&&!n)return t;const i=new URL(t);return r&&i.searchParams.set("utm_source",r),s&&i.searchParams.set("utm_medium",s),n&&i.searchParams.set("utm_content",n),i.toString()}catch{return t}}function gs(t,e){const s=e?.toLowerCase().startsWith("hi")?t.puja_link_hindi||t.puja_link:t.puja_link||t.puja_link_hindi;return Jl(s||"")}function Jn(t,e){return e?.toLowerCase().startsWith("hi")?t.cover_media_url||t.cover_media_url_english||"":t.cover_media_url_english||t.cover_media_url||""}const Yl={container:"_container_m8vst_1"},Ql=["en","hi"],Xl={en:"English",hi:"हिन्दी"},Yn={en:{language:"Language",guest:"Guest",sriMandir:"Sri Mandir",ratingText:"3 Crore+ app downloads",feedbackTitle:"What Others Discovered Through Their Dosha Analysis",feedbackTrust:"Trusted by over 5 crore users worldwide",feedbackRating:"4.9",feedbackTestimonial1:"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.",feedbackTestimonial2:"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.",feedbackTestimonial3:"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.",feedbackTestimonial4:"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.",feedbackTestimonial5:"Simple and clear guidance. Problems in job and health both reduced after remedies. Good service.",feedbackTestimonial6:"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.",feedbackTestimonial7:"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.",feedbackTestimonial8:"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.",feedbackTestimonial9:"Very genuine report not copy paste. Health issue reason also explained. After remedies I feel more energy and mind peace. Satisfied.",feedbackTestimonial10:"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.",feedbackTestimonial11:"I was not believing before but result surprised me. Career growth started after long time and new opportunities coming. Good guidance and honest prediction.",feedbackTestimonial12:"Health problems and negative thoughts were too much. After following remedies I feel mentally strong and peaceful. Family also noticing the change. Very grateful.",feedbackTestimonial13:"Short review. Career better now and money flow also improved after remedy. Thank you.",feedbackTestimonial14:"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.",feedbackTestimonial15:"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.",feedbackAuthor1:"Abhishek Mishra",feedbackAuthor2:"Pooja Verma",feedbackAuthor3:"Amit Patel",feedbackAuthor4:"Sneha Gupta",feedbackAuthor5:"Vikas Yadav",feedbackAuthor6:"Neha Singh",feedbackAuthor7:"Rahul Jain",feedbackAuthor8:"Kavita Mishra",feedbackAuthor9:"Sandeep Kumar",feedbackAuthor10:"Anjali Mehta",feedbackAuthor11:"Deepak Arora",feedbackAuthor12:"Ritu Saxena",feedbackAuthor13:"Manoj Tiwari",feedbackAuthor14:"Priya Nair",feedbackAuthor15:"Karan Malhotra",feedbackAuthor1AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639330970.png",feedbackAuthor2AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639293055.png",feedbackAuthor3AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639358174.png",feedbackAuthor4AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639427379.png",feedbackAuthor5AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639381899.png",feedbackAuthor6AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639416587.png",feedbackAuthor7AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639454626.png",feedbackAuthor8AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639319028.png",feedbackAuthor9AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639271096.png",feedbackAuthor10AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639254172.png",feedbackAuthor11AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639345411.png",feedbackAuthor12AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639306698.png",feedbackAuthor13AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639330970.png",feedbackAuthor14AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639402894.png",feedbackAuthor15AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639358174.png",readMoreReviews:"Read More Reviews",readLess:"Read Less",feedbackTitleMarriage:"What others facing marriage delay discovered",feedbackTestimonialMarriage1:"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.",feedbackTestimonialMarriage2:"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.",feedbackTestimonialMarriage3:"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.",feedbackTestimonialMarriage4:"Very helpful service. Found reason for delay in marriage and solution also given. Things improved slowly.",feedbackTestimonialMarriage5:"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.",feedbackTestimonialMarriage6:"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.",feedbackTestimonialMarriage7:"Short review but true. Marriage dosh removed after remedies and now wedding date fixed. Thank you so much.",feedbackTestimonialMarriage8:"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.",feedbackTestimonialMarriage9:"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.",feedbackTestimonialMarriage10:"Service is good and fast. Report is clear. My marriage problem solved after remedy. Satisfied.",feedbackTestimonialMarriage11:"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.",feedbackTestimonialMarriage12:"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.",feedbackTestimonialMarriage13:"Nice guidance and honest prediction. No false promises. Remedies worked for my delayed marriage issue.",feedbackTestimonialMarriage14:"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.",feedbackTestimonialMarriage15:"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.",faqTitle:"Frequently Asked Questions",faqQ1:"Is this really free?",faqA1:"Yes, the Dosha Calculator is completely free to use. You can check your kundli for doshas and get detailed analysis at no cost.",faqQ2:"What if I don't know birth time?",faqA2:"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.",faqQ3:"Is this a generic report?",faqA3:"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.",faqQ1Marriage:"Is this really free?",faqA1Marriage:"Yes, the Dosha Calculator is completely free to use. You can check your kundli for doshas and get detailed analysis at no cost.",faqQ2Marriage:"What if I don't know birth time?",faqA2Marriage:"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.",faqQ3Marriage:"Is this a generic report?",faqA3Marriage:"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.",faqQ4Marriage:"Will this fix my marriage delay?",faqA4Marriage:"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.",formPrivacyBanner:"100% Private & Secure",formTitle:"Enter your details",formSubtitle:"We'll generate your kundli to know your doshas",formNameLabel:"Enter Your Name",formNamePlaceholder:"Your Name",formGenderLabel:"Your Gender",formGenderMale:"Male",formGenderFemale:"Female",formProblemLabel:"What problem is bothering you?",formProblemMarriage:"Marriage",formProblemMoney:"Money",formProblemOther:"Others",formProblemHealth:"Health",formProblemEducation:"Education",formProblemCareer:"Career",formProblemOtherPlaceholder:"Please describe your problem",formProblemOtherHint:"Max 100 characters",formDobLabel:"Select Date of Birth",formDobInfo:"Your date of birth is used to calculate your dosha balance.",formTimeLabel:"Exact Time of Birth",formTimeInfo:"Birth time helps improve accuracy of the analysis.",formTimeUnknown:"I don't know my birth time",formTimeUnknownHelp:"Note - Without exact birth time, accuracy will be reduced. We'll run Moon-based checks only.",formPlaceLabel:"Enter your birth place",formPlaceInfo:"City and state/country help us refine your result.",formPlacePlaceholder:"City, State",formFooterNote:"Analysis Takes Only 60 seconds",formFooterNoteBefore:"Analysis Takes Only ",formFooterNoteBold:"60 seconds",formFooterNoteAfter:"",formCta:"Check My Dosha for FREE",formCtaCalculate:"Calculate my Dosha",calculating:"Calculating...",bookPuja:"Book Puja",resultPageTitle:"Find Puja Remedy for Free",resultPageSubtitle:"Analyse your kundli to find out which doshas (if any) appear in your Vedic chart—and see devotional remedies.",calculationSuccess:"Your dosha analysis is ready.",calculationError:"Something went wrong. Please try again.",formError:"Please correct the highlighted fields.",formNameRequired:"Name is required.",formGenderRequired:"Gender is required.",formDobRequired:"Date of birth is required.",formTimeRequired:"Time is required when birth time is known.",formPlaceRequired:"Birth place is required.",formPlaceSelectFromDropdown:"Please select a place from the dropdown list.",formAgeMarriageRestriction:"Please select appropriate problem areas. Marriage, financial, career, and business-related issues are applicable for users above 18 years.",locationError:"Could not get location coordinates. Please try again.",calculationResolvingPlace:"Resolving place…",info:"Info",resultTitle:"Your Dosha Analysis",resultSomeDoshas:"Some Doshas Have Been Detected",resultNoDoshas:"No Major Doshas Found",resultNoDoshasDesc:"Your birth chart shows no major doshas.",resultMangal:"Mangal Dosha",resultKaalSarp:"Kaal Sarp Dosha",resultPitra:"Pitra Dosha",resultSadeSati:"Shani Sade Sati",resultStatusPresent:"Present",resultStatusAbsent:"Absent",resultStatusInactive:"Inactive",resultExplanation:"Explanation",resultRemedies:"Remedies",resultEditForm:"Edit details",drStatus:"Status",drSeverity:"Severity",drType:"Type",drPhase:"Phase",drExplanation:"Explanation",drWhyPresent:"Why Present",drWhyAbsent:"Why Absent",drImpact:"Impact",drPlanetaryPositions:"Planetary Positions",drTraditionalRemedies:"Traditional Remedies",drDetailedAnalysis:"Detailed Analysis & Remedies",drBasedOnChart:"Based on your birth chart calculations",drDisclaimer:"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.",drStatusPresent:"Present",drStatusAbsent:"Absent",drStatusInactive:"Inactive",drStatusActive:"Active",drStatusSuggested:"Suggested",drStatusNullified:"Present (Nullified)",drMangalName:"Mangal Dosha (Manglik)",drMangalDesc:"Mangal (Manglik/Kuja) Dosha — Linked with Mars in certain houses; traditionally associated with friction in relationships and decisiveness.",drMangalImpact:"Greater likelihood of friction in close relationships, impatience/anger spikes, or delays and stops/starts in marriage or partnerships.",drMangalRemedies:`Recite Hanuman Chalisa daily
60
45
  Fast on Tuesdays
61
46
  Donate red items like lentils or cloth
62
47
  Wear a coral gemstone after consultation`,drKaalSarpName:"Kaal Sarp Dosha",drKaalSarpDesc:"Kaal Sarp Dosha — All planets hemmed between Rahu and Ketu; often framed as a pattern indicating inner tension and transformation.",drKaalSarpImpact:"A pattern of inner restlessness and periodic setbacks; plans may feel blocked or get delayed despite effort, requiring extra persistence.",drKaalSarpRemedies:`Recite Maha Mrityunjaya Mantra 108 times daily
@@ -164,12 +149,12 @@ Visit Navagraha temples`,ctaKundliCreated:"3L+ Kundli Reports Created.",ctaCerti
164
149
  परामर्श के बाद लहसुनिया पहनें`,drOtherNavagrahaRemedies:`व्यापक नवग्रह शांति पूजा करें
165
150
  नवग्रह मंत्र का पाठ करें
166
151
  सभी नौ ग्रहों के लिए वस्तुओं का दान करें
167
- नवग्रह मंदिरों में जाएं`,ctaKundliCreated:"3L+ कुंडली रिपोर्ट बनाई।",ctaCertified:"BHU प्रमाणित ज्योतिषी।",ctaSecurePayment:"सुरक्षित भुगतान।",contactTitle:"संपर्क करें",contactBrandName:"श्री मंदिर",contactWhatsAppGlobal:"व्हाट्सएप: 8296947757",contactWhatsAppDomestic:"व्हाट्सएप: 08071174417",contactEmail:"ईमेल: pujaseva@appsforbharat.com",whatFromAnalysisTitle:"इस विश्लेषण से आपको क्या मिलेगा",whatFromAnalysisMarriage1Title:"शादी पर प्रभाव जानें",whatFromAnalysisMarriage1Desc:"क्या शादी में देरी होगी, कोई समस्या आएगी या मैच सही रहेगा।",whatFromAnalysisMarriage2Title:"मंगल दोष की पुष्टि",whatFromAnalysisMarriage2Desc:"जानें कि मंगल दोष है या नहीं और वह कितना मजबूत है।",whatFromAnalysisMarriage3Title:"उपाय और पूजा की जानकारी",whatFromAnalysisMarriage3Desc:"कौन सा उपाय या पूजा आपके लिए सही रहेगा।",whatFromAnalysisGeneric1Title:"जीवन पर प्रभाव का संक्षेप",whatFromAnalysisGeneric1Desc:"शादी, करियर, पैसे, सेहत और पढ़ाई में होने वाली देरी, परेशानी या अवसरों को समझें",whatFromAnalysisGeneric2Title:"दोष की पुष्टि",whatFromAnalysisGeneric2Desc:"जानें कि कोई दोष या ग्रहों का असंतुलन आपकी प्रगति को प्रभावित कर रहा है या नहीं",whatFromAnalysisGeneric3Title:"उपाय की दिशा",whatFromAnalysisGeneric3Desc:"कौन सा उपाय या पूजा आपके लिए सही रहेगा।"}},Pn=v.createContext(null);function Rn(){return typeof window>"u"?"en":window.location.pathname.split("/").filter(Boolean)[0]==="hi"?"hi":"en"}function cl(t){const{pathname:e,search:r,hash:s}=window.location,n=e.split("/").filter(Boolean);n[0]==="en"||n[0]==="hi"?n[0]=t:n.unshift(t),window.location.href="/"+n.join("/")+r+s}function ul({locale:t,onLocaleChange:e,children:r}){const[s,n]=v.useState(()=>t||Rn());v.useEffect(()=>{if(t)n(t);else{const o=()=>n(Rn());return window.addEventListener("popstate",o),()=>window.removeEventListener("popstate",o)}},[t]);const a=o=>{e?e(o):cl(o)},i=v.useMemo(()=>o=>En[s]?.[o]??o,[s]);return c.jsx(Pn.Provider,{value:{locale:s,setLocale:a,t:i},children:r})}function ls(){return v.useContext(Pn)}function dl(){const e=ls()?.locale==="hi";return c.jsx("div",{className:il.container,children:e?"100% सटीक • सुरक्षित • 30 लाख+ परिवारों द्वारा विश्वसनीय":"100% Accurate • Secure • Trusted by 30L+ families"})}const Be=t=>({width:t,height:t});function cs(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Be(e),...r,children:[c.jsx("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"}),c.jsx("path",{d:"M12 9v4"}),c.jsx("path",{d:"M12 17h.01"})]})}function On(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Be(e),...r,children:[c.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),c.jsx("path",{d:"m9 11 3 3L22 4"})]})}function Rr(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Be(e),...r,children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("path",{d:"M12 16v-4"}),c.jsx("path",{d:"M12 8h.01"})]})}function hl(t){const{size:e=24,...r}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Be(e),...r,children:c.jsx("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"})})}function fl(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Be(e),...r,children:[c.jsx("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"}),c.jsx("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"}),c.jsx("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"})]})}function ml(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Be(e),...r,children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function pl(t){const{size:e=24,...r}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Be(e),...r,children:c.jsx("path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"})})}function gl(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Be(e),...r,children:[c.jsx("path",{d:"m5 12 7-7 7 7"}),c.jsx("path",{d:"M12 19V5"})]})}function Cn(t){const{size:e=24,...r}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Be(e),...r,children:c.jsx("path",{d:"m6 9 6 6 6-6"})})}function us(t){const{size:e=24,className:r="",...s}=t;return c.jsx("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 ${r}`,style:{animation:"spin 1s linear infinite"},...Be(e),...s,children:c.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})}function yl(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Be(e),...r,children:[c.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("line",{x1:"10",x2:"21",y1:"14",y2:"3"})]})}function bl(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Be(e),...r,children:[c.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),c.jsx("path",{d:"M3 3v5h5"})]})}const Ke={ctaFilled:"_ctaFilled_8nukz_2",ctaFilledContent:"_ctaFilledContent_8nukz_7",chevronRight:"_chevronRight_8nukz_14",bookPujaButton:"_bookPujaButton_8nukz_21",bookPujaContent:"_bookPujaContent_8nukz_27",pujaInfo:"_pujaInfo_8nukz_36",pujaName:"_pujaName_8nukz_44",pujaPrice:"_pujaPrice_8nukz_57",priceLabel:"_priceLabel_8nukz_64",priceAmount:"_priceAmount_8nukz_68",bookButton:"_bookButton_8nukz_74"},nt=t=>{const{priority:e,fetchPriority:r,width:s,height:n,...a}=t;return v.createElement("img",{...a,width:s??1,height:n??1,decoding:"async",loading:a.loading??(e?"eager":"lazy"),...r&&{fetchPriority:r}})},vl="https://srm-cdn.a4b.io/yoda/1771588545907.svg";function wl({isFormComplete:t,onPress:e,labelDefault:r,labelFilled:s,isLoading:n=!1,mode:a="form",firstPuja:i,showingResults:o=!1,bookPujaLabel:l="Book Puja",loadingLabel:u="Calculating..."}){return a==="book-puja"&&i&&o?c.jsx(q.FooterCTAButton,{onClick:e,disabled:n,className:Ke.bookPujaButton,children:c.jsxs("div",{className:Ke.bookPujaContent,children:[c.jsxs("div",{className:Ke.pujaInfo,children:[c.jsx("span",{className:Ke.pujaName,children:i.name}),i.price>0&&c.jsxs("div",{className:Ke.pujaPrice,children:[c.jsx("span",{className:Ke.priceLabel,children:"Starting from "}),c.jsxs("span",{className:Ke.priceAmount,children:["₹",i.price]})]})]}),c.jsxs("span",{className:Ke.bookButton,children:[l," →"]})]})}):c.jsx(q.FooterCTAButton,{onClick:e,disabled:n,className:t?Ke.ctaFilled:void 0,children:n?c.jsxs("span",{className:Ke.ctaFilledContent,children:[c.jsx(us,{className:"w-5 h-5 animate-spin"}),u]}):t?c.jsxs("span",{className:Ke.ctaFilledContent,children:[s,c.jsx(nt,{src:vl,alt:"",className:Ke.chevronRight,width:20,height:20,loading:"lazy"})]}):r})}const Or={bannerContainer:"_bannerContainer_1s29r_1",bannerImage:"_bannerImage_1s29r_13",ticker:"_ticker_1s29r_20",tickerContent:"_tickerContent_1s29r_30"};function _l({bannerConfig:t,className:e="",imageComponent:r=nt}){const s=r;return c.jsxs("section",{className:`${Or.bannerContainer} ${e}`,children:[c.jsx(s,{src:t.imageUrl,alt:t.alt,className:Or.bannerImage,loading:"eager",priority:!0,fetchPriority:"high"}),c.jsx("div",{className:Or.ticker,children:c.jsx("div",{className:Or.tickerContent,children:t.tickerText})})]})}const kl=112;function lt({section:t,children:e,onImpression:r}){const s=v.useRef(null),n=v.useRef(!1);return v.useEffect(()=>{const a=s.current;if(!a)return;const i=new IntersectionObserver(([o])=>{!o?.isIntersecting||n.current||(n.current=!0,r(t))},{threshold:.1,rootMargin:`0px 0px -${kl}px 0px`});return i.observe(a),()=>i.disconnect()},[t,r]),c.jsx("div",{ref:s,children:e})}const $t={wrap:"_wrap_1mrzx_1",input:"_input_1mrzx_6",iconBtn:"_iconBtn_1mrzx_35",iconImg:"_iconImg_1mrzx_49",placeholder:"_placeholder_1mrzx_53",dateDisplay:"_dateDisplay_1mrzx_65"},Sl="https://srm-cdn.a4b.io/yoda/1770372045894.svg",xl=t=>{if(!t)return"";const[e,r,s]=t.split("-");return`${s}/${r}/${e}`};function Tl({id:t,value:e,onChange:r,onOpen:s,className:n=""}){const a=v.useRef(null),i=v.useMemo(()=>{const l=new Date,u=d=>String(d).padStart(2,"0");return`${l.getFullYear()}-${u(l.getMonth()+1)}-${u(l.getDate())}`},[]),o=()=>{s?.();const l=a.current;if(l&&typeof l.showPicker=="function")try{l.showPicker()}catch{l?.focus()}else l?.focus()};return c.jsxs("div",{className:`${$t.wrap} ${n}`,children:[!e&&c.jsx("span",{className:$t.placeholder,children:"Select Date of Birth"}),e&&c.jsx("div",{className:$t.dateDisplay,children:xl(e)}),c.jsx("input",{ref:a,id:t,type:"date",className:$t.input,value:e,max:i,onChange:l=>{const u=l.target.value,d=new Date,h=p=>String(p).padStart(2,"0"),m=`${d.getFullYear()}-${h(d.getMonth()+1)}-${h(d.getDate())}`;u&&u>m||r(u)},onClick:o,onFocus:o}),c.jsx("button",{type:"button",className:$t.iconBtn,"aria-label":"Open date picker",onMouseDown:l=>l.preventDefault(),onClick:l=>{l.preventDefault(),l.stopPropagation(),o()},children:c.jsx(nt,{className:$t.iconImg,src:Sl,alt:"",width:22,height:22,loading:"lazy"})})]})}const ve={wrap:"_wrap_spo2g_1",input:"_input_spo2g_6",iconBtn:"_iconBtn_spo2g_24",iconImg:"_iconImg_spo2g_38",timePopover:"_timePopover_spo2g_42",timePickerRow:"_timePickerRow_spo2g_58",timePickerSelect:"_timePickerSelect_spo2g_64",timePickerColon:"_timePickerColon_spo2g_80",meridiemToggle:"_meridiemToggle_spo2g_88",meridiemBtn:"_meridiemBtn_spo2g_97",meridiemActive:"_meridiemActive_spo2g_112",timePopoverActions:"_timePopoverActions_spo2g_117",timePopoverBtn:"_timePopoverBtn_spo2g_123",timePopoverOk:"_timePopoverOk_spo2g_142"},jl="https://srm-cdn.a4b.io/yoda/1770372014782.svg",Nn=t=>String(t).padStart(2,"0");function Al(t){const e=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(t);if(!e)return t;const r=Number(e[1]),s=e[2],n=r>=12?"PM":"AM";return`${r%12===0?12:r%12}:${s} ${n}`}function El(t){const e=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(t);if(!e)return{hour12:12,minute:"00",meridiem:"AM"};const r=Number(e[1]),s=e[2],n=r>=12?"PM":"AM";return{hour12:r%12===0?12:r%12,minute:s,meridiem:n}}function Pl(t){const e=Math.min(12,Math.max(1,t.hour12)),r=/^([0-5]\d)$/.test(t.minute)?t.minute:"00";let s=e%12;return t.meridiem==="PM"&&(s+=12),`${Nn(s)}:${r}`}function Rl({id:t,value:e,onChange:r,onOpen:s,placeholder:n="Exact Time of Birth",disabled:a=!1,className:i=""}){const o=v.useRef(null),[l,u]=v.useState(!1),[d,h]=v.useState({hour12:12,minute:"00",meridiem:"AM"});v.useEffect(()=>{const g=b=>{o.current&&(o.current.contains(b.target)||u(!1))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[]);const m=()=>{a||(s?.(),h(El(e||"12:00")),u(g=>!g))},p=()=>{const g=Pl(d);r(g),u(!1)};return c.jsxs("div",{className:`${ve.wrap} ${i}`,ref:o,children:[c.jsx("input",{id:t,className:ve.input,type:"text",value:e?Al(e):"",readOnly:!0,disabled:a,placeholder:n,onClick:m}),c.jsx("button",{type:"button",className:ve.iconBtn,"aria-label":"Open time picker",disabled:a,onMouseDown:g=>g.preventDefault(),onClick:g=>{g.preventDefault(),g.stopPropagation(),m()},children:c.jsx(nt,{className:ve.iconImg,src:jl,alt:"",width:22,height:22,loading:"lazy"})}),l&&!a&&c.jsxs("div",{className:ve.timePopover,role:"dialog","aria-label":"Select time",children:[c.jsxs("div",{className:ve.timePickerRow,children:[c.jsx("select",{className:ve.timePickerSelect,value:d.hour12,onChange:g=>h(b=>({...b,hour12:Number(g.target.value)})),"aria-label":"Hour",children:Array.from({length:12},(g,b)=>b+1).map(g=>c.jsx("option",{value:g,children:g},g))}),c.jsx("span",{className:ve.timePickerColon,children:":"}),c.jsx("select",{className:ve.timePickerSelect,value:d.minute,onChange:g=>h(b=>({...b,minute:g.target.value})),"aria-label":"Minute",children:Array.from({length:60},(g,b)=>Nn(b)).map(g=>c.jsx("option",{value:g,children:g},g))}),c.jsxs("div",{className:ve.meridiemToggle,"aria-label":"AM/PM",children:[c.jsx("button",{type:"button",className:`${ve.meridiemBtn} ${d.meridiem==="AM"?ve.meridiemActive:""}`,onClick:()=>h(g=>({...g,meridiem:"AM"})),children:"AM"}),c.jsx("button",{type:"button",className:`${ve.meridiemBtn} ${d.meridiem==="PM"?ve.meridiemActive:""}`,onClick:()=>h(g=>({...g,meridiem:"PM"})),children:"PM"})]})]}),c.jsxs("div",{className:ve.timePopoverActions,children:[c.jsx("button",{type:"button",className:ve.timePopoverBtn,onClick:()=>u(!1),children:"Cancel"}),c.jsx("button",{type:"button",className:`${ve.timePopoverBtn} ${ve.timePopoverOk}`,onClick:p,"aria-label":"OK",children:c.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:c.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})]})}async function In(t,e){const{visitorId:r,sessionId:s,problemStatements:n,language:a}=e;if(n.length!==0)try{await t.from("session_problem_statements").insert({visitor_id:r,session_id:s,problem_statements:n,language:a??"en"})}catch{}}async function Dn(t,e,r){const{data:s,error:n}=await t.functions.invoke("calculate-dosha",{body:e,headers:r??{}});return n?{success:!1,error:n.message||"Calculation failed"}:s&&typeof s=="object"&&"success"in s?s.success===!0?s:{success:!1,error:s.error??"Unknown error",details:s.details}:{success:!1,error:"Invalid response from server"}}async function $n(t,e,r={}){const{visitorId:s="unknown",sessionId:n="unknown",trackProblemStatements:a=!0,problemStatements:i=[],language:o="en"}=r;return a&&i.length>0&&await In(t,{visitorId:s,sessionId:n,problemStatements:i,language:o}),Dn(t,e,{"x-visitor-id":s,"x-session-id":n})}let Cr=null;const Ol=(t,e)=>typeof window>"u"||window.google?.maps?.places?Promise.resolve():Cr||(Cr=new Promise((r,s)=>{const n=document.querySelector('script[data-google-maps-places="true"]');if(n){const o=Date.now(),l=()=>{if(window.google?.maps?.places){r();return}if(Date.now()-o>5e3){s(new Error("Google Maps script present but Places library did not become available."));return}window.setTimeout(l,50)};n.getAttribute("src")?l():(n.addEventListener("load",()=>l()),n.addEventListener("error",()=>s(new Error("Failed to load Google Maps API"))));return}const a=document.createElement("script"),i=new URL("https://maps.googleapis.com/maps/api/js");i.searchParams.set("key",t),i.searchParams.set("libraries","places"),i.searchParams.set("loading","async"),e&&i.searchParams.set("language",e),a.src=i.toString(),a.async=!0,a.defer=!0,a.setAttribute("data-google-maps-places","true"),a.onload=()=>{const o=Date.now(),l=()=>{if(window.google?.maps?.places){r();return}if(Date.now()-o>2e3){s(new Error("Google Maps loaded but Places library is unavailable. Check API key restrictions / enabled APIs."));return}window.setTimeout(l,50)};l()},a.onerror=()=>s(new Error("Failed to load Google Maps API")),document.head.appendChild(a)}),Cr),Ln=(t={})=>{const{apiKey:e,language:r="en",restrictCountry:s}=t,[n,a]=v.useState(!1),[i,o]=v.useState([]),[l,u]=v.useState(!1),[d,h]=v.useState(null),m=v.useRef(null),p=v.useRef(null),g=v.useRef(null);v.useEffect(()=>{if(!e){a(!1),h(null);return}Ol(e,r).then(()=>{try{m.current=new google.maps.places.AutocompleteService;const S=document.createElement("div");p.current=new google.maps.places.PlacesService(S),g.current=new google.maps.places.AutocompleteSessionToken,a(!0),h(null)}catch(S){a(!1),h(S instanceof Error?S.message:"Failed to create Places services")}}).catch(S=>{a(!1),h(S instanceof Error?S.message:"Failed to load location service")})},[e,r]);const b=v.useCallback(async S=>{if(!S||S.length<2||!m.current){o([]);return}u(!0);try{const k={input:S,types:["(cities)"],sessionToken:g.current??void 0};s&&(k.componentRestrictions={country:s});const N=await new Promise((R,B)=>{m.current.getPlacePredictions(k,(P,U)=>{U===google.maps.places.PlacesServiceStatus.OK&&P?R(P):U===google.maps.places.PlacesServiceStatus.ZERO_RESULTS?R([]):B(new Error(`Places API error: ${U}`))})});o(N.map(R=>({place_id:R.place_id,description:R.description,structured_formatting:{main_text:R.structured_formatting?.main_text||R.description,secondary_text:R.structured_formatting?.secondary_text||""}})))}catch{o([])}finally{u(!1)}},[s]),A=v.useCallback(async S=>{if(!p.current)return null;try{const k=await new Promise(($,De)=>{p.current.getDetails({placeId:S,fields:["geometry","address_components","formatted_address"],sessionToken:g.current??void 0},(ge,Re)=>{Re===google.maps.places.PlacesServiceStatus.OK&&ge?$(ge):De(new Error(`Place details error: ${Re}`))})});g.current=new google.maps.places.AutocompleteSessionToken;const N=k.geometry?.location?.lat()||0,R=k.geometry?.location?.lng()||0;let B="",P="",U="";return k.address_components?.forEach($=>{$.types.includes("locality")&&(B=$.long_name),$.types.includes("administrative_area_level_1")&&(P=$.long_name),$.types.includes("country")&&(U=$.long_name)}),{display_name:k.formatted_address||"",lat:N,lng:R,city:B,state:P,country:U}}catch{return null}},[]),w=v.useCallback(()=>o([]),[]);return{isLoaded:n,predictions:i,isSearching:l,loadError:d,searchPlaces:b,getPlaceDetails:A,clearPredictions:w}},Cl=["formProblemMarriage","formProblemMoney","formProblemHealth","formProblemEducation","formProblemCareer","formProblemOther"];function Nl(){try{const t="analytics_visitor_id";let e=typeof localStorage<"u"?localStorage.getItem(t):null;if(!e){e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`;try{localStorage.setItem(t,e)}catch{}}return e??"unknown"}catch{return"unknown"}}function Il(){try{const t="analytics_session_id";let e=typeof localStorage<"u"?localStorage.getItem(t):null;if(!e){e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`;try{localStorage.setItem(t,e)}catch{}}return e??"unknown"}catch{return"unknown"}}function Dl(t){if(!t)return 0;const e=new Date(t);if(Number.isNaN(e.getTime()))return 0;const r=new Date;let s=r.getFullYear()-e.getFullYear();const n=r.getMonth()-e.getMonth();return(n<0||n===0&&r.getDate()<e.getDate())&&s--,s}const ds=v.forwardRef(function({t:e,className:r="",initialValues:s,onValuesChange:n,onFormValidityChange:a,supabase:i,resolvePlace:o,onResult:l,onError:u,onLoadingChange:d,analytics:h,googleMapsApiKey:m},p){const g=j=>j.replace(/[^a-zA-Z\u0900-\u097F\s]/g,"").replace(/\s{2,}/g," "),[b,A]=v.useState(s?.name??""),[w,S]=v.useState(s?.gender??""),[k,N]=v.useState(s?.problems??[]),[R,B]=v.useState(s?.dateOfBirth??""),[P,U]=v.useState(s?.birthTime??""),[$,De]=v.useState(s?.birthTimeUnknown??!1),[ge,Re]=v.useState(s?.birthPlace??""),[ee,te]=v.useState(s?.otherProblemText??""),[he,Ze]=v.useState(null),[Oe,re]=v.useState(!1),[fe,Se]=v.useState(null),[Q,y]=v.useState({}),K=v.useCallback(j=>{const I=ie=>{const Je=document.getElementById(ie);return Je?(Je.focus(),Je.scrollIntoView({behavior:"smooth",block:"center"}),!0):!1};if(j==="name"){I("dosha-name");return}if(j==="gender"){const ie=document.querySelector('[role="group"][aria-labelledby="dosha-gender-label"] button');ie&&(ie.focus(),ie.scrollIntoView({behavior:"smooth",block:"center"}));return}if(j==="dateOfBirth"){I("dosha-dob");return}if(j==="birthTime"){I("dosha-time");return}j==="birthPlace"&&I("dosha-place")},[]),z=v.useRef(!1),W=v.useRef(!1),V=v.useRef(!1),M=v.useRef(!1),L=v.useRef(!1),J=v.useRef(null),{predictions:se,isSearching:me,loadError:le,searchPlaces:je,getPlaceDetails:Ut,clearPredictions:qe}=Ln({apiKey:m,language:"en"}),$e=v.useCallback(()=>{z.current||(z.current=!0,h?.trackFormFillInitiated?.())},[h]);v.useEffect(()=>{const j=I=>{J.current&&(J.current.contains(I.target)||re(!1))};return document.addEventListener("mousedown",j),()=>document.removeEventListener("mousedown",j)},[]),v.useEffect(()=>{if(!Oe)return;if(ge.length<2){qe();return}const j=window.setTimeout(async()=>{await je(ge)},300);return()=>window.clearTimeout(j)},[ge,qe,Oe,je]);const wt=b.trim()!==""&&(w==="male"||w==="female")&&R!==""&&(P!==""||$)&&ge.trim()!=="";v.useEffect(()=>{a?.(wt)},[wt,a]),v.useEffect(()=>{n?.({name:b,gender:w,problems:k,otherProblemText:ee,dateOfBirth:R,birthTime:P,birthTimeUnknown:$,birthPlace:ge})},[b,w,k,ee,R,P,$,ge,n]),v.useEffect(()=>{!k.includes("formProblemOther")&&ee&&te("")},[k,ee]);const _t=v.useCallback(async(j,I)=>{if(!m)return"UTC";try{const ie=Math.floor(Date.now()/1e3),Je=`https://maps.googleapis.com/maps/api/timezone/json?location=${j},${I}&timestamp=${ie}&key=${m}`,ke=await(await fetch(Je)).json();return ke.status==="OK"&&ke.timeZoneId?ke.timeZoneId:"UTC"}catch{return"UTC"}},[m]),at=v.useCallback(async()=>{const j=(ce,Ae,He=!1)=>{Ae&&(y(Le=>({...Le,[Ae]:ce})),K(Ae)),Se(He?ce:null),u?.(ce)};if(y({}),Se(null),!i){j(e("calculationError"));return}if(!b.trim()){j(e("formNameRequired"),"name");return}if(w!=="male"&&w!=="female"){j(e("formGenderRequired"),"gender");return}if(!R){j(e("formDobRequired"),"dateOfBirth");return}if(!$&&!P){j(e("formTimeRequired"),"birthTime");return}const I=ge.trim();if(!I){j(e("formPlaceRequired"),"birthPlace");return}const ie=g(I).trim();if(!ie){j(e("formPlaceRequired"),"birthPlace");return}const Je=Dl(R),dt=new Set(["formProblemMarriage","formProblemMoney","formProblemCareer","formProblemBusiness","marriage","financial","career","business"]),ke=k.some(ce=>dt.has(ce));if(Je<18&&ke){j(e("formAgeMarriageRestriction"),void 0,!0);return}if(!he&&!o){j(e("formPlaceSelectFromDropdown"),"birthPlace");return}d?.(!0);try{let ce,Ae,He;if(he)ce=he.lat,Ae=he.lon,he.tz?He=he.tz:(He=await _t(ce,Ae),Ze({...he,tz:He}));else if(o){const ye=await o(I);if(!ye){j(e("locationError")),d?.(!1);return}ce=ye.lat,Ae=ye.lon,He=ye.tz}else{j(e("formPlaceSelectFromDropdown"),"birthPlace"),d?.(!1);return}const Le={problemAreaValues:[...k.filter(ye=>ye!=="formProblemOther").map(ye=>e(ye)).filter(Boolean),...k.includes("formProblemOther")&&ee.trim()?[ee.trim()]:[]],name:b.trim(),gender:w==="male"?"M":"F",date:R,time:$?"":P||"12:00",unknownTime:$,tz:He||"UTC",lat:ce,lon:Ae,place:ie,problemArea:void 0};Le.problemArea=Le.problemAreaValues.length>0?Le.problemAreaValues.join(", "):void 0;const nr=Nl(),O=Il(),ne=Le.problemAreaValues,xe=typeof navigator<"u"&&navigator.language?.toLowerCase().startsWith("hi")?"hi":"en",Te=await $n(i,Le,{visitorId:nr,sessionId:O,trackProblemStatements:!0,problemStatements:ne,language:xe});if(Te.success){Se(null);const[ye,ar,ir]=(Le.date||"").split("-").map(Number),Ur=Le.time||"12:00",[ht,or]=Ur.split(":").map(Br=>parseInt(Br,10)||0);l?.(Te,{day:ir||1,month:ar||1,year:ye||2e3,hour:ht,minute:or,lat:ce,lon:Ae,tzone:5.5})}else{let ye=Te.error??e("calculationError");(ye.includes("Expected 'M' | 'F'")||ye.includes("gender"))&&(ye=e("formGenderRequired")),j(ye)}}catch(ce){const Ae=ce instanceof Error?ce.message:String(ce);j(Ae)}finally{d?.(!1)}},[i,o,he,ge,b,w,R,P,$,k,e,u,d,h,l,_t,K]);v.useImperativeHandle(p,()=>({submit:at}),[at]);const sr=Cl.map(j=>({key:j,label:e(j)}));return c.jsxs(q.FormContainer,{className:r,"aria-label":e("formTitle"),children:[c.jsx(q.PrivacyBanner,{text:e("formPrivacyBanner")}),c.jsx(q.FormSectionHeader,{title:e("formTitle"),subtitle:e("formSubtitle")}),c.jsx("div",{onFocusCapture:()=>{$e(),h?.trackNameSectionClicked?.()},children:c.jsxs(q.FormField,{id:"dosha-name",label:e("formNameLabel"),required:!0,children:[c.jsx(q.FormTextInput,{id:"dosha-name",value:b,onChange:j=>{const I=j.target.value;I&&!W.current&&(W.current=!0,h?.trackNameSectionFilled?.()),A(I),Q.name&&y(ie=>({...ie,name:void 0})),fe&&Se(null)},placeholder:e("formNamePlaceholder"),autoComplete:"name"}),Q.name&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.name})]})}),c.jsxs(q.FormField,{id:"dosha-gender",label:e("formGenderLabel"),required:!0,children:[c.jsx(q.FormSegmentedControl,{id:"dosha-gender",options:[{value:"male",label:e("formGenderMale")},{value:"female",label:e("formGenderFemale")}],value:w,onChange:j=>{S(j),Q.gender&&y(I=>({...I,gender:void 0})),fe&&Se(null)}}),Q.gender&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.gender})]}),c.jsxs(q.FormField,{id:"dosha-problems",label:e("formProblemLabel"),children:[c.jsx(q.FormTagPills,{id:"dosha-problems",options:sr,selected:k,onChange:j=>{N(j),j.includes("formProblemOther")||te("")}}),k.includes("formProblemOther")&&c.jsxs("div",{style:{marginTop:"8px"},children:[c.jsx(q.FormTextInput,{id:"dosha-problem-other",value:ee,onChange:j=>{const I=j.target.value.slice(0,100);te(I)},placeholder:e("formProblemOtherPlaceholder")}),c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#8f6e56"},children:e("formProblemOtherHint")})]})]}),c.jsx(q.FormField,{id:"dosha-dob",label:e("formDobLabel"),required:!0,children:c.jsxs("div",{style:{minHeight:Q.dateOfBirth?"72px":"48px",transition:"min-height 0.2s"},children:[c.jsx(Tl,{id:"dosha-dob",value:R,onOpen:()=>{$e(),h?.trackDobClicked?.()},onChange:j=>{j&&!V.current&&(V.current=!0,h?.trackDobFilled?.()),B(j),Q.dateOfBirth&&y(I=>({...I,dateOfBirth:void 0})),fe&&Se(null)}}),Q.dateOfBirth&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.dateOfBirth})]})}),c.jsx(q.FormField,{id:"dosha-time",label:e("formTimeLabel"),required:!0,children:c.jsxs("div",{style:{minHeight:Q.birthTime?"72px":"48px",transition:"min-height 0.2s"},children:[c.jsx(Rl,{id:"dosha-time",value:P,onOpen:()=>{$e(),h?.trackTimeClicked?.()},onChange:j=>{j&&!M.current&&(M.current=!0,h?.trackTimeFilled?.()),U(j),Q.birthTime&&y(I=>({...I,birthTime:void 0})),fe&&Se(null)},disabled:$}),Q.birthTime&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.birthTime})]})}),c.jsx(q.FormCheckboxWithHelp,{id:"dosha-time-unknown",checked:$,onChange:j=>{$e(),h?.trackTimeCheckboxClicked?.(),De(j),j&&Q.birthTime&&y(I=>({...I,birthTime:void 0}))},primaryText:e("formTimeUnknown"),helpText:e("formTimeUnknownHelp")}),c.jsx("div",{onFocusCapture:()=>{$e(),h?.trackPlaceOfBirthClicked?.()},children:c.jsx(q.FormField,{id:"dosha-place",label:e("formPlaceLabel"),required:!0,children:c.jsxs("div",{ref:J,style:{position:"relative"},children:[c.jsx(q.FormLocationInput,{id:"dosha-place",value:ge,onChange:j=>{const I=g(j.target.value);Re(I),Ze(null),re(!0),I&&!L.current&&(L.current=!0,h?.trackPlaceOfBirthChosen?.(I)),Q.birthPlace&&y(ie=>({...ie,birthPlace:void 0})),fe&&Se(null)},onFocus:()=>re(!0),placeholder:e("formPlacePlaceholder")}),Q.birthPlace&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.birthPlace}),Oe&&se.length>0&&c.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",maxHeight:"240px",overflowY:"auto",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},role:"listbox",children:se.slice(0,8).map(j=>c.jsxs("button",{type:"button",onClick:async()=>{if(Re(g(j.description)),Ut){const I=await Ut(j.place_id);I&&(Ze({lat:I.lat,lon:I.lng}),Q.birthPlace&&y(ie=>({...ie,birthPlace:void 0})),fe&&Se(null))}qe(),re(!1),L.current||(L.current=!0,h?.trackPlaceOfBirthChosen?.(j.description))},style:{width:"100%",padding:"10px 12px",textAlign:"left",border:"none",backgroundColor:"transparent",cursor:"pointer",display:"flex",flexDirection:"column",gap:"2px",outline:"none"},onMouseEnter:I=>{I.currentTarget.style.backgroundColor="rgba(247, 94, 34, 0.06)"},onMouseLeave:I=>{I.currentTarget.style.backgroundColor="transparent"},onFocus:I=>{I.currentTarget.style.backgroundColor="rgba(247, 94, 34, 0.06)"},onBlur:I=>{I.currentTarget.style.backgroundColor="transparent"},children:[c.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:"#111827"},children:j.structured_formatting?.main_text??j.description}),j.structured_formatting?.secondary_text&&c.jsx("span",{style:{fontSize:"12px",color:"#6b7280"},children:j.structured_formatting.secondary_text})]},j.place_id))}),Oe&&m&&me&&c.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,padding:"10px 12px",backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",fontSize:"12px",color:"#6b7280",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},children:"Loading…"}),Oe&&m&&!me&&le&&c.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,padding:"10px 12px",backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",fontSize:"12px",color:"#dc2626",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},children:le})]})})}),c.jsxs(q.FormFooterNote,{children:["⚡ ",e("formFooterNoteBefore"),c.jsx("strong",{children:e("formFooterNoteBold")}),e("formFooterNoteAfter")]}),fe&&c.jsxs("div",{style:{marginTop:"4px",width:"100%",borderRadius:"14px",border:"1px solid #FCA5A5",background:"#FEF2F2",padding:"16px",display:"flex",alignItems:"flex-start",gap:"10px"},role:"alert","aria-live":"assertive",children:[c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{width:"16px",height:"16px",marginTop:"2px",flexShrink:0},"aria-hidden":"true",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),c.jsx("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]}),c.jsx("p",{style:{margin:0,fontSize:"14px",lineHeight:"1.5",color:"#EF4444"},children:fe})]})]})}),Lt=Ne.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`animate-pulse rounded-md bg-muted ${t}`,...e}));Lt.displayName="Skeleton";const ct=Ne.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`rounded-lg border border-border bg-card text-card-foreground shadow-sm ${t}`,...e}));ct.displayName="Card";const yt=Ne.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`flex flex-col space-y-1.5 p-6 ${t}`,...e}));yt.displayName="CardHeader";const bt=Ne.forwardRef(({className:t="",...e},r)=>c.jsx("h3",{ref:r,className:`text-2xl font-semibold leading-none tracking-tight ${t}`,...e}));bt.displayName="CardTitle";const Nr=Ne.forwardRef(({className:t="",...e},r)=>c.jsx("p",{ref:r,className:`text-sm text-muted-foreground ${t}`,...e}));Nr.displayName="CardDescription";const vt=Ne.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`p-6 pt-0 ${t}`,...e}));vt.displayName="CardContent";const tr=Ne.forwardRef(({className:t="",size:e="default",variant:r="default",...s},n)=>{const a={default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8"},i={default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"};return c.jsx("button",{ref:n,type:"button",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 ${a[e]} ${i[r]} ${t}`,...s})});tr.displayName="Button";function Un({puja:t,doshaType:e,language:r,onBookClick:s,imageComponent:n=nt,analytics:a}){const i=n,o=r?.toLowerCase().startsWith("hi"),l=is(t,r),u=Tn(t,r),d=jn(t.schedule_date_ist,r),h=os(t,r),m=An(t,r),p=async()=>{if(a?.trackDoshaCalculatorResultBookCtaClicked?.({position:"puja_card",url:h,isOldDosha:!1}),s)try{await s()}catch(g){console.error("Error in onBookClick:",g)}window.open(h,"_blank","noopener,noreferrer")};return c.jsx(ct,{className:"overflow-hidden hover:shadow-lg transition-shadow relative",children:c.jsxs("div",{className:"relative",children:[c.jsx("div",{className:"absolute -top-1 -left-1 z-10",children:c.jsx("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",children:o?"सीमित सीटें":"Limited Seats"})}),m&&c.jsx("div",{className:"relative aspect-[16/10] w-full overflow-hidden bg-muted",children:c.jsx(i,{src:m,alt:l,className:"w-full h-full object-contain",loading:"lazy"})}),c.jsxs("div",{className:"p-3 space-y-2",children:[c.jsx("h4",{className:"font-semibold text-sm line-clamp-2 text-card-foreground",children:l}),t.temple_name&&c.jsx("p",{className:"text-sm text-muted-foreground",children:u}),t.schedule_date_ist&&c.jsx("p",{className:"text-sm font-medium text-card-foreground",children:d}),t.individual_pack_price_inr>0&&c.jsx("p",{className:"text-base font-bold text-primary",children:o?`₹${t.individual_pack_price_inr} से शुरू`:`Starting from ₹${t.individual_pack_price_inr}`}),c.jsxs(tr,{size:"lg",className:"book-puja-cta w-full h-14 text-lg font-bold",onClick:async g=>{g.preventDefault(),await p()},children:[o?"पूजा बुक करें":"Book Puja",c.jsx(yl,{className:"ml-1.5 h-3.5 w-3.5",size:14})]}),c.jsx("p",{className:"text-[10px] text-center text-muted-foreground",children:o?"श्री मंदिर द्वारा संचालित":"Powered by Sri Mandir"})]})]})})}const ut={section:"_section_15ygl_1",heading:"_heading_15ygl_5",list:"_list_15ygl_16",item:"_item_15ygl_20",stepNumber:"_stepNumber_15ygl_24",itemContent:"_itemContent_15ygl_30",itemTitle:"_itemTitle_15ygl_34",itemDesc:"_itemDesc_15ygl_39"};function Mn({t,className:e="",bannerType:r="generic"}){const s=t("whatFromAnalysisTitle"),n=r==="marriage"?"whatFromAnalysisMarriage":"whatFromAnalysisGeneric",a=[{titleKey:`${n}1Title`,descKey:`${n}1Desc`},{titleKey:`${n}2Title`,descKey:`${n}2Desc`},{titleKey:`${n}3Title`,descKey:`${n}3Desc`}];return c.jsxs("section",{className:`${ut.section} ${e}`,"aria-labelledby":"what-from-analysis-heading",children:[c.jsx("h2",{id:"what-from-analysis-heading",className:ut.heading,children:s}),c.jsx("ol",{className:ut.list,children:a.map(({titleKey:i,descKey:o},l)=>c.jsxs("li",{className:ut.item,children:[c.jsx("span",{className:ut.stepNumber,"aria-hidden":"true",children:l+1}),c.jsxs("div",{className:ut.itemContent,children:[c.jsx("span",{className:ut.itemTitle,children:t(i)}),c.jsx("span",{className:ut.itemDesc,children:t(o)})]})]},i))})]})}const $l={marriage:{en:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137437775.webp",alt:"Marriage dosha analysis banner",tickerText:"★ 4.9 Rated By Users Facing Marriage Delay"},hi:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137493287.webp",alt:"विवाह दोष विश्लेषण बैनर",tickerText:"★ 4.9 शादी में देरी का सामना कर रहे उपयोगकर्ताओं द्वारा रेटेड"}},generic:{en:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137415503.webp",alt:"Dosha analysis banner",tickerText:"★ 4.9 Rated By Users Seeking Clarity"},hi:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137476046.webp",alt:"दोष विश्लेषण बैनर",tickerText:"★ 4.9 रेटिंग अपने दोषा को जानने वाले यूज़र्स ने दी"}}},Ll={"marriage-what-you'll-get-first":"marriage","marriage-form-first":"marriage","generic-what-you'll-get-first":"generic","generic-form-first":"generic"};function Bn(t,e){let r="generic";if(t){for(const[s,n]of Object.entries(Ll))if(t.includes(s)){r=n;break}}return $l[r][e]}function Ul(t){return typeof window>"u"?null:new URLSearchParams(window.location.search).get(t)}function Ir(){return Ul("utm_term")}const Ml=v.lazy(()=>Promise.resolve().then(()=>ic).then(t=>({default:t.DoshaResultsFull}))),Bl="https://srm-cdn.a4b.io/yoda/1770362904947.svg",Kl="https://srm-cdn.a4b.io/yoda/1770375694934.svg",Fl="https://srm-cdn.a4b.io/yoda/1770375720933.svg",ql="https://srm-cdn.a4b.io/yoda/1770707793537.svg",Hl="https://srm-cdn.a4b.io/yoda/1770362713543.svg";function Kn(t){const e=new Set([t]);switch(t){case"kaal-sarp":e.add("kaalSarp"),e.add("kaalsarp"),e.add("kaal_sarp");break;case"shani":e.add("sadeSati"),e.add("shaniSadeSati"),e.add("sade-sati");break;case"mangal":e.add("mangalDosha"),e.add("manglik");break;case"pitra":e.add("pitru"),e.add("pitraDosha");break}return Array.from(e)}function Dr(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function Fn(t){if(!t)return 2;const e=t.toLowerCase();return e==="severe"||e==="high"?3:e==="moderate"||e==="medium"?2:e==="mild"||e==="low"?1:2}function qn(t){if(!t||typeof window>"u")return t;try{const e=new URLSearchParams(window.location.search);if(Array.from(e.keys()).length===0)return t;const r=new URL(t,window.location.href);return e.forEach((s,n)=>{r.searchParams.set(n,s)}),r.toString()}catch{return t}}function hs(t){const e=[];return Dr(t.kaalSarp)&&e.push({type:"kaal-sarp",severity:typeof t.kaalSarpSeverity=="string"?t.kaalSarpSeverity:void 0}),Dr(t.pitra)&&e.push({type:"pitra",severity:typeof t.pitraSeverity=="string"?t.pitraSeverity:void 0}),Dr(t.shaniSadeSati||t.sadeSati)&&e.push({type:"shani",severity:typeof t.sadeSatiSeverity=="string"?t.sadeSatiSeverity:void 0}),Dr(t.mangal)&&!t.mangal?.toLowerCase().includes("nullified")&&e.push({type:"mangal",severity:typeof t.mangalSeverity=="string"?t.mangalSeverity:void 0}),e.length===0?null:(e.sort((r,s)=>Fn(s.severity)-Fn(r.severity)),e[0]?.type??null)}function Wl({t}){return c.jsxs("div",{className:q.footerShellStyles.marqueeContent,children:[c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(nt,{src:Kl,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaKundliCreated")]}),c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(nt,{src:Fl,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaCertified")]}),c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(nt,{src:ql,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaSecurePayment")]})]})}const Gl=[{qKey:"faqQ1",aKey:"faqA1"},{qKey:"faqQ2",aKey:"faqA2"},{qKey:"faqQ3",aKey:"faqA3"}],zl=[{qKey:"faqQ1Marriage",aKey:"faqA1Marriage"},{qKey:"faqQ2Marriage",aKey:"faqA2Marriage"},{qKey:"faqQ3Marriage",aKey:"faqA3Marriage"},{qKey:"faqQ4Marriage",aKey:"faqA4Marriage"}];function Vl({className:t="",logoUrl:e=Bl,languageSelector:r,showLanguageSelector:s=!0,isGlobal:n=!1,readMoreReviewsHref:a,supabaseUrl:i,supabaseAnonKey:o,googleMapsApiKey:l,supabase:u,resolvePlace:d,onResult:h,onError:m,renderPujaCard:p,isLoadingPujas:g=!1,renderKundali:b,kundaliSectionId:A="kundali-chart-section",analytics:w,getFirstPujaInfo:S,onBookPujaClick:k,imageComponent:N=nt}){const R=v.useMemo(()=>{if(u)return u;if(i&&o)try{return yn(i,o)}catch{return null}return null},[u,i,o]),B=N,P=ls(),U=P?.t??(O=>O),$=P?.locale??"en",De=P?.setLocale,ge=$.toLowerCase().startsWith("hi"),Re=v.useRef(null),ee=v.useRef(null),[te,he]=v.useState(!1),[Ze,Oe]=v.useState(!1),[re,fe]=v.useState(null),[Se,Q]=v.useState(null),[y,K]=v.useState(void 0),[z,W]=v.useState(!1),[V,M]=v.useState([]),[L,J]=v.useState(!1),[se,me]=v.useState(null),le=v.useRef(!1);v.useEffect(()=>{le.current||(le.current=!0,w?.trackDoshaCalculatorWebView?.())},[]);const je=!p||!S;v.useEffect(()=>{if(!je||!R)return;let O=!0;return J(!0),rl(R).then(ne=>{O&&M(ne)}).finally(()=>{O&&J(!1)}),()=>{O=!1}},[je,R]);const Ut=v.useCallback(O=>{const ne=wn(V,O);return ne?c.jsx(Un,{puja:ne,doshaType:O,language:$,imageComponent:N,analytics:w}):null},[V,$,N,w]),qe=v.useCallback(O=>{const ne=wn(V,O);return ne?{name:is(ne,$),price:ne.individual_pack_price_inr,link:os(ne,$)}:null},[V,$]),$e=p??Ut,wt=S??qe,_t=g||!p&&L,[at,sr]=v.useState(()=>{const O=typeof window<"u"?Ir():null;return Bn(O,$)}),[j,I]=v.useState(()=>{if(typeof window>"u")return"generic";const O=Ir();return O&&O.toLowerCase().includes("marriage")?"marriage":"generic"});v.useEffect(()=>{const O=Ir(),ne=Bn(O,$);sr(ne);let xe="generic";O&&O.toLowerCase().includes("marriage")&&(xe="marriage"),I(xe)},[$]);const[ie,Je]=v.useState(!1);v.useEffect(()=>{const O=Ir();O&&O.toLowerCase().includes("what-you")&&Je(!0)},[]);const dt=()=>{Re.current?.scrollIntoView({behavior:"smooth"})},ke=v.useCallback(O=>{w?.trackDoshaSectionImpression?.({section:O,timestamp:new Date().toISOString()})},[w]),ce=(O,ne)=>{if(fe(O),Q(ne??null),W(!1),O.summary){const xe=O.summary,Te=hs(xe);if(Te){const ye=Kn(Te).map(ar=>wt(ar)).find(Boolean)??null;me(ye)}else me(null)}else me(null);h?.(O,ne)};v.useEffect(()=>{if(S||!re?.summary)return;const O=hs(re.summary);if(!O){me(null);return}const ne=Kn(O).map(xe=>qe(xe)).find(Boolean)??null;me(ne)},[qe,S,re]);const Ae=()=>{W(!0),window.scrollTo({top:0,behavior:"smooth"})},He=()=>{if(re&&!z&&se){if(se.link){const O=qn(se.link);w?.trackDoshaCalculatorResultBookCtaClicked?.({position:"floating_cta",url:O,isOldDosha:!1})}if(k)k();else if(se.link){const O=qn(se.link);window.open(O,"_blank","noopener,noreferrer")}return}console.log("supabase",R),console.log("resolvePlaceProp",d),console.log("isFormComplete",te),console.log("formSubmitRef.current",ee.current),R&&ee.current?(w?.trackFloatingCtaClicked?.(te?ur.all_fields_filled:ur.fields_not_filled),te||dt(),ee.current.submit()):(w?.trackFloatingCtaClicked?.(ur.fields_not_filled),dt())},nr=s&&!n?c.jsxs("button",{type:"button",onClick:()=>{De&&De(ge?"en":"hi")},"aria-label":ge?"Switch to English":"हिंदी में बदलें",className:"flex items-center justify-center gap-1.5 py-2 rounded-lg text-white text-sm font-medium hover:opacity-90 transition-colors",style:{backgroundColor:"#E13A44",borderRadius:"8px",width:"100px"},disabled:!De,children:[c.jsx(B,{src:Hl,alt:"",className:"w-5 h-5 brightness-0 invert",width:20,height:20,loading:"lazy"}),c.jsx("span",{children:ge?"English":"हिंदी"})]}):null;return c.jsxs("div",{className:t,children:[c.jsx(q.PageHeader,{t:U,logoUrl:e,languageSelector:nr,showLanguageSelector:s}),c.jsx(q.MarqueeStrip,{children:c.jsx(Wl,{t:U})}),!re&&c.jsx(lt,{section:"banner",onImpression:ke,children:c.jsx(_l,{bannerConfig:at,imageComponent:N})}),c.jsx("main",{className:"pb-28",children:re?c.jsx(lt,{section:"result",onImpression:ke,children:c.jsx(v.Suspense,{fallback:c.jsxs("div",{className:"container mx-auto px-4 py-8 space-y-4",children:[c.jsx(Lt,{className:"h-12 w-3/4 mx-auto"}),c.jsx(Lt,{className:"h-32 w-full"}),c.jsx(Lt,{className:"h-48 w-full"}),c.jsx(Lt,{className:"h-48 w-full"})]}),children:c.jsx(Ml,{result:re,t:U,onEdit:z?void 0:Ae,inlineEditForm:z?c.jsx(ds,{ref:ee,t:U,initialValues:y,onValuesChange:K,onFormValidityChange:he,supabase:R??void 0,resolvePlace:d,googleMapsApiKey:l,onResult:ce,onError:m,onLoadingChange:Oe,analytics:w}):void 0,renderPujaCard:$e,isLoadingPujas:_t,renderKundali:b,kundaliSectionId:A,birthDetails:Se,supabase:R,language:P?.locale??"en",readMoreReviewsHref:a,analytics:w,problemArea:(()=>{const O=y?.problems||[],ne=O.filter(Te=>Te!=="formProblemOther").map(Te=>U(Te)).filter(Boolean),xe=y?.otherProblemText?.trim();return O.includes("formProblemOther")&&xe&&ne.push(xe),ne.join(", ")})(),problemAreaIds:y?.problems||[],customProblemText:y?.otherProblemText||""})})}):c.jsxs(c.Fragment,{children:[ie&&c.jsx(lt,{section:"what_from_analysis",onImpression:ke,children:c.jsx(Mn,{t:U,bannerType:j})}),c.jsx(lt,{section:"form",onImpression:ke,children:c.jsx("div",{ref:Re,children:c.jsx(ds,{ref:ee,t:U,initialValues:y,onValuesChange:K,onFormValidityChange:he,supabase:R??void 0,resolvePlace:d,googleMapsApiKey:l,onResult:ce,onError:m,onLoadingChange:Oe,analytics:w})})}),!ie&&c.jsx(lt,{section:"what_from_analysis",onImpression:ke,children:c.jsx(Mn,{t:U,bannerType:j})}),c.jsx(lt,{section:"user_reviews",onImpression:ke,children:c.jsx(q.UserReviewsSection,{t:O=>{if(j==="marriage"){if(O==="feedbackTitle")return U("feedbackTitleMarriage");if(O.startsWith("feedbackTestimonial")){const xe=`feedbackTestimonialMarriage${O.replace("feedbackTestimonial","")}`,Te=U(xe);return Te===xe?U(O):Te}}return U(O)},readMoreHref:a,onReadMore:w?.trackReadMoreReviewsClicked?()=>w.trackReadMoreReviewsClicked():void 0})}),c.jsx(lt,{section:"faq",onImpression:ke,children:c.jsx(q.FAQAccordion,{t:U,items:j==="marriage"?zl:Gl,defaultOpenIndex:0,onItemOpen:O=>w?.trackFaqQuestionClicked?.(O)})}),c.jsx(lt,{section:"contact",onImpression:ke,children:c.jsx(q.ContactUsSection,{title:U("contactTitle"),brandName:U("contactBrandName"),whatsAppLine:U("contactWhatsAppDomestic"),emailLine:U("contactEmail")})})]})}),!(re&&!z&&hs(re.summary)===null)&&c.jsxs(q.FooterShell,{children:[!(re&&!z&&se)&&c.jsx(dl,{}),c.jsx(wl,{isFormComplete:te,onPress:He,labelDefault:U("formCta"),labelFilled:U("formCtaCalculate"),loadingLabel:U("calculating"),isLoading:Ze,mode:re&&!z&&se?"book-puja":"form",firstPuja:se||void 0,showingResults:!!re&&!z,bookPujaLabel:U("bookPuja")})]})]})}const oe={section:"_section_ji9so_1",heading:"_heading_ji9so_6",headingSuccess:"_headingSuccess_ji9so_13",card:"_card_ji9so_17",cardPresent:"_cardPresent_ji9so_25",cardAbsent:"_cardAbsent_ji9so_29",cardHeader:"_cardHeader_ji9so_33",doshaName:"_doshaName_ji9so_41",badge:"_badge_ji9so_46",badgePresent:"_badgePresent_ji9so_53",badgeAbsent:"_badgeAbsent_ji9so_58",badgeInactive:"_badgeInactive_ji9so_63",body:"_body_ji9so_68",bodyLabel:"_bodyLabel_ji9so_75",noDoshas:"_noDoshas_ji9so_81",noDoshasDesc:"_noDoshasDesc_ji9so_88",editBtn:"_editBtn_ji9so_94",accordionContent:"_accordionContent_ji9so_128"},Jl=[{key:"mangal",labelKey:"resultMangal",summaryKey:"mangal"},{key:"kaalSarp",labelKey:"resultKaalSarp",summaryKey:"kaalSarp"},{key:"pitra",labelKey:"resultPitra",summaryKey:"pitra"},{key:"sadeSati",labelKey:"resultSadeSati",summaryKey:"shaniSadeSati"}];function rr(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function Yl(t,e){if(Array.isArray(t))return t.find(s=>(s.name??s.type)===e);if(t&&typeof t=="object"&&e in t){const r=t[e];if(!r)return;const s=typeof r.remedies=="string"?r.remedies:Array.isArray(r.remedies)?r.remedies.join(`
168
- `):void 0;return{explanation:r.explanation,remedies:s}}}function Ql(t,e){if(!t)return"";const r=t.toLowerCase();return r.includes("nullified")||r==="present"||r==="active"||r==="partial"||r==="suggested"?e("resultStatusPresent"):r==="absent"?e("resultStatusAbsent"):r==="inactive"?e("resultStatusInactive"):t}function Xl({result:t,t:e,onEdit:r,className:s=""}){const n=t.summary??{},a=t.details??{},i=n.shaniSadeSati??n.sadeSati,o=rr(n.mangal)||rr(n.kaalSarp)||rr(n.pitra)||rr(i);return c.jsxs("section",{className:`${oe.section} ${s}`,"aria-labelledby":"dosha-results-heading",children:[c.jsx("h2",{id:"dosha-results-heading",className:o?`${oe.heading} ${oe.headingSuccess}`:oe.heading,children:e(o?"resultSomeDoshas":"resultNoDoshas")}),o?c.jsx("div",{children:Jl.map(({key:l,labelKey:u,summaryKey:d})=>{const h=d==="shaniSadeSati"?i:n[d],m=rr(h),p=Yl(a,l==="sadeSati"?"sadeSati":l),g=p?.explanation,b=typeof p?.remedies=="string"?p.remedies:void 0;return c.jsxs("div",{className:`${oe.card} ${m?oe.cardPresent:oe.cardAbsent}`,children:[c.jsxs("div",{className:oe.cardHeader,children:[c.jsx("span",{className:oe.doshaName,children:e(u)}),c.jsx("span",{className:`${oe.badge} ${m?oe.badgePresent:h==="inactive"?oe.badgeInactive:oe.badgeAbsent}`,children:Ql(h,e)})]}),(g||b)&&c.jsxs("div",{className:oe.body,children:[g&&c.jsxs("div",{children:[c.jsx("div",{className:oe.bodyLabel,children:e("resultExplanation")}),c.jsx("p",{className:oe.accordionContent,children:g})]}),b&&c.jsxs("div",{style:{marginTop:g?"0.75rem":0},children:[c.jsx("div",{className:oe.bodyLabel,children:e("resultRemedies")}),c.jsx("p",{className:oe.accordionContent,children:b})]})]})]},l)})}):c.jsxs("div",{className:oe.noDoshas,children:[c.jsx("p",{children:e("resultNoDoshas")}),c.jsx("p",{className:oe.noDoshasDesc,children:e("resultNoDoshasDesc")})]}),r&&c.jsx("button",{type:"button",className:oe.editBtn,onClick:r,"aria-label":e("resultEditForm"),children:e("resultEditForm")})]})}const $r=Ne.forwardRef(({className:t="",variant:e="default",...r},s)=>{const n={default:"border-transparent bg-primary text-primary-foreground",secondary:"border-transparent bg-secondary text-secondary-foreground",destructive:"border-transparent bg-destructive/10 text-destructive",outline:"border-border text-muted-foreground bg-transparent"};return c.jsx("div",{ref:s,className:`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors ${n[e]} ${t}`,...r})});$r.displayName="Badge";const fs=Ne.createContext(null);function Hn({type:t="single",collapsible:e=!0,className:r="",children:s,onValueChange:n}){const[a,i]=Ne.useState(null),o=Ne.useCallback(l=>{i(u=>{const d=u===l?e?null:u:l;return n?.(d),d})},[e,n]);return c.jsx(fs.Provider,{value:{value:a,onToggle:o},children:c.jsx("div",{className:r,children:s})})}function Wn({value:t,className:e="",children:r}){return c.jsx("div",{"data-state":t,className:`border-b border-border ${e}`,children:r})}function Gn({className:t="",children:e,value:r}){const s=Ne.useContext(fs),n=s?.value===r;return c.jsxs("button",{type:"button",onClick:()=>s?.onToggle(r),className:`flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline w-full text-left ${t}`,"aria-expanded":n,children:[e,c.jsx(Cn,{className:`h-4 w-4 shrink-0 transition-transform duration-200 ${n?"rotate-180":""}`})]})}function zn({className:t="",children:e,value:r}){return Ne.useContext(fs)?.value===r?c.jsx("div",{className:`overflow-hidden text-sm pb-4 pt-0 ${t}`,children:e}):null}const ms=new Map,Vn=1800*1e3;function Zl(t,e,r){return`D1|${e}|svg|${t.day}-${t.month}-${t.year}-${t.hour}-${t.minute}-${t.lat}-${t.lon}-${t.tzone}|${r}`}function ec(t){const e=ms.get(t);if(e&&Date.now()-e.timestamp<Vn)return e.svg;try{const r=sessionStorage.getItem(`kundali_${t}`);if(r){const s=JSON.parse(r);if(Date.now()-s.timestamp<Vn)return ms.set(t,s),s.svg;sessionStorage.removeItem(`kundali_${t}`)}}catch{}return null}function tc(t,e){const r={svg:e,timestamp:Date.now()};ms.set(t,r);try{sessionStorage.setItem(`kundali_${t}`,JSON.stringify(r))}catch{}}function rc(t){try{const r=new DOMParser().parseFromString(t,"image/svg+xml"),s=r.querySelector("svg");return s?(s.removeAttribute("width"),s.removeAttribute("height"),s.getAttribute("viewBox")||s.setAttribute("viewBox","0 0 350 350"),s.setAttribute("preserveAspectRatio","xMidYMid meet"),s.setAttribute("style","width:100%;height:auto;display:block;"),new XMLSerializer().serializeToString(r)):t}catch(e){return console.error("[kundaliChart] SVG transform error:",e),t}}async function Jn(t,e){const{birthDetails:r,chartType:s,language:n,signal:a}=e,i=Zl(r,s,n),o=ec(i);if(o)return o;const l=await t.functions.invoke("get-kundali-chart",{body:{...r,chartType:s,language:n}});if(a?.aborted)throw new DOMException("Aborted","AbortError");if(l.error)throw new Error(l.error.message||"Failed to fetch kundali chart");const u=l.data?.data?.svg;if(!u)throw new Error("No SVG data in response");const d=rc(u);return tc(i,d),d}function Yn({birthDetails:t,supabase:e,language:r,t:s}){const[n,a]=v.useState("North"),[i,o]=v.useState("idle"),[l,u]=v.useState(""),[d,h]=v.useState(""),m=v.useRef(null),p=v.useRef(null),b=(r||"").toLowerCase().startsWith("hi")?"hi":"en",A=v.useCallback(async k=>{m.current&&m.current.abort();const N=new AbortController;m.current=N,o("loading"),h("");try{const R=await Jn(e,{birthDetails:t,chartType:k,language:b,signal:N.signal});N.signal.aborted||(u(R),o("success"))}catch(R){if(R instanceof Error&&R.name==="AbortError")return;console.error("[KundaliCard] Fetch error:",R),N.signal.aborted||(h(R instanceof Error?R.message:"Failed to load chart"),o("error"))}},[t,e,b]);v.useEffect(()=>(A(n),()=>{m.current&&m.current.abort()}),[n,A]);const w=k=>{k!==n&&a(k)},S=()=>{A(n)};return c.jsxs(ct,{ref:p,className:"spiritual-glow border border-primary/10",children:[c.jsxs(yt,{className:"pb-3",children:[c.jsx(bt,{className:"text-xl font-bold",children:s("drYourKundali")}),c.jsxs("div",{className:"flex gap-2 mt-3 pt-2",children:[c.jsx(tr,{type:"button",size:"sm",variant:n==="North"?"default":"outline",className:"rounded-full px-4",onClick:()=>w("North"),children:s("kundaliChartNorth")}),c.jsx(tr,{type:"button",size:"sm",variant:n==="South"?"default":"outline",className:"rounded-full px-4",onClick:()=>w("South"),children:s("kundaliChartSouth")})]})]}),c.jsx(vt,{children:c.jsxs("div",{className:"w-full max-w-[360px] mx-auto",children:[i==="loading"&&c.jsx(Lt,{className:"w-full aspect-square rounded-lg"}),i==="success"&&l&&c.jsx("div",{className:"w-full aspect-square",dangerouslySetInnerHTML:{__html:l}}),i==="error"&&c.jsxs("div",{className:"w-full aspect-square flex flex-col items-center justify-center bg-muted/30 rounded-lg border border-border",children:[c.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:s("kundaliChartLoadError")}),c.jsxs(tr,{type:"button",variant:"outline",size:"sm",onClick:S,className:"gap-2",children:[c.jsx(bl,{className:"w-4 h-4"}),s("kundaliChartRetry")]})]})]})})]})}const sc=[{qKey:"faqQ1",aKey:"faqA1"},{qKey:"faqQ2",aKey:"faqA2"},{qKey:"faqQ3",aKey:"faqA3"}],Qn=[{type:"kaal-sarp",detailKey:"kaalSarp",nameKey:"drKaalSarpName",descKey:"drKaalSarpDesc",impactKey:"drKaalSarpImpact",remediesKey:"drKaalSarpRemedies",benefitsKey:"drPujaBenefitsKaalSarp",icon:fl,summaryKey:"kaalSarp",severityKey:"kaalSarpSeverity"},{type:"pitra",detailKey:"pitra",nameKey:"drPitraName",descKey:"drPitraDesc",impactKey:"drPitraImpact",remediesKey:"drPitraRemedies",benefitsKey:"drPujaBenefitsPitra",icon:ml,summaryKey:"pitra",severityKey:"pitraSeverity"},{type:"shani",detailKey:"sadeSati",nameKey:"drSadeSatiName",descKey:"drSadeSatiDesc",impactKey:"drSadeSatiImpact",remediesKey:"drSadeSatiRemedies",benefitsKey:"drPujaBenefitsShani",icon:pl,summaryKey:"shaniSadeSati",severityKey:"sadeSatiSeverity"},{type:"mangal",detailKey:"mangal",nameKey:"drMangalName",descKey:"drMangalDesc",impactKey:"drMangalImpact",remediesKey:"drMangalRemedies",benefitsKey:"drPujaBenefitsMangal",icon:hl,summaryKey:"mangal",severityKey:"mangalSeverity"}];function nc(t,e){const r=new Set([t]);switch(e&&r.add(e),t){case"kaal-sarp":r.add("kaalSarp"),r.add("kaalsarp"),r.add("kaal_sarp");break;case"shani":r.add("sadeSati"),r.add("shaniSadeSati"),r.add("sade-sati");break;case"mangal":r.add("mangalDosha"),r.add("manglik");break;case"pitra":r.add("pitru"),r.add("pitraDosha");break}return Array.from(r)}function Fe(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function Lr(t){return t?t.toLowerCase().includes("nullified"):!1}function Xn(t,e){if(Array.isArray(t)){const r=t.find(a=>(a.name??a.type)===e);if(!r)return;const s=typeof r.remedies=="string"?r.remedies:Array.isArray(r.remedies)?r.remedies.join(`
152
+ नवग्रह मंदिरों में जाएं`,ctaKundliCreated:"3L+ कुंडली रिपोर्ट बनाई।",ctaCertified:"BHU प्रमाणित ज्योतिषी।",ctaSecurePayment:"सुरक्षित भुगतान।",contactTitle:"संपर्क करें",contactBrandName:"श्री मंदिर",contactWhatsAppGlobal:"व्हाट्सएप: 8296947757",contactWhatsAppDomestic:"व्हाट्सएप: 08071174417",contactEmail:"ईमेल: pujaseva@appsforbharat.com",whatFromAnalysisTitle:"इस विश्लेषण से आपको क्या मिलेगा",whatFromAnalysisMarriage1Title:"शादी पर प्रभाव जानें",whatFromAnalysisMarriage1Desc:"क्या शादी में देरी होगी, कोई समस्या आएगी या मैच सही रहेगा।",whatFromAnalysisMarriage2Title:"मंगल दोष की पुष्टि",whatFromAnalysisMarriage2Desc:"जानें कि मंगल दोष है या नहीं और वह कितना मजबूत है।",whatFromAnalysisMarriage3Title:"उपाय और पूजा की जानकारी",whatFromAnalysisMarriage3Desc:"कौन सा उपाय या पूजा आपके लिए सही रहेगा।",whatFromAnalysisGeneric1Title:"जीवन पर प्रभाव का संक्षेप",whatFromAnalysisGeneric1Desc:"शादी, करियर, पैसे, सेहत और पढ़ाई में होने वाली देरी, परेशानी या अवसरों को समझें",whatFromAnalysisGeneric2Title:"दोष की पुष्टि",whatFromAnalysisGeneric2Desc:"जानें कि कोई दोष या ग्रहों का असंतुलन आपकी प्रगति को प्रभावित कर रहा है या नहीं",whatFromAnalysisGeneric3Title:"उपाय की दिशा",whatFromAnalysisGeneric3Desc:"कौन सा उपाय या पूजा आपके लिए सही रहेगा।"}},Qn=w.createContext(null);function Xn(){return typeof window>"u"?"en":window.location.pathname.split("/").filter(Boolean)[0]==="hi"?"hi":"en"}function Zl(t){const{pathname:e,search:r,hash:s}=window.location,n=e.split("/").filter(Boolean);n[0]==="en"||n[0]==="hi"?n[0]=t:n.unshift(t),window.location.href="/"+n.join("/")+r+s}function ec({locale:t,onLocaleChange:e,children:r}){const[s,n]=w.useState(()=>t||Xn());w.useEffect(()=>{if(t)n(t);else{const o=()=>n(Xn());return window.addEventListener("popstate",o),()=>window.removeEventListener("popstate",o)}},[t]);const i=o=>{e?e(o):Zl(o)},a=w.useMemo(()=>o=>Yn[s]?.[o]??o,[s]);return c.jsx(Qn.Provider,{value:{locale:s,setLocale:i,t:a},children:r})}function ys(){return w.useContext(Qn)}function tc(){const e=ys()?.locale==="hi";return c.jsx("div",{className:Yl.container,children:e?"100% सटीक • सुरक्षित • 30 लाख+ परिवारों द्वारा विश्वसनीय":"100% Accurate • Secure • Trusted by 30L+ families"})}const Fe=t=>({width:t,height:t});function bs(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("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"}),c.jsx("path",{d:"M12 9v4"}),c.jsx("path",{d:"M12 17h.01"})]})}function Zn(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),c.jsx("path",{d:"m9 11 3 3L22 4"})]})}function Ur(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("path",{d:"M12 16v-4"}),c.jsx("path",{d:"M12 8h.01"})]})}function rc(t){const{size:e=24,...r}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:c.jsx("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"})})}function sc(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("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"}),c.jsx("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"}),c.jsx("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"})]})}function nc(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function ic(t){const{size:e=24,...r}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:c.jsx("path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"})})}function ac(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"m5 12 7-7 7 7"}),c.jsx("path",{d:"M12 19V5"})]})}function ei(t){const{size:e=24,...r}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:c.jsx("path",{d:"m6 9 6 6 6-6"})})}function vs(t){const{size:e=24,className:r="",...s}=t;return c.jsx("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 ${r}`,style:{animation:"spin 1s linear infinite"},...Fe(e),...s,children:c.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})}function oc(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("line",{x1:"10",x2:"21",y1:"14",y2:"3"})]})}function lc(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),c.jsx("path",{d:"M3 3v5h5"})]})}const Ke={ctaFilled:"_ctaFilled_8nukz_2",ctaFilledContent:"_ctaFilledContent_8nukz_7",chevronRight:"_chevronRight_8nukz_14",bookPujaButton:"_bookPujaButton_8nukz_21",bookPujaContent:"_bookPujaContent_8nukz_27",pujaInfo:"_pujaInfo_8nukz_36",pujaName:"_pujaName_8nukz_44",pujaPrice:"_pujaPrice_8nukz_57",priceLabel:"_priceLabel_8nukz_64",priceAmount:"_priceAmount_8nukz_68",bookButton:"_bookButton_8nukz_74"},lt=t=>{const{priority:e,fetchPriority:r,width:s,height:n,...i}=t;return w.createElement("img",{...i,width:s??1,height:n??1,decoding:"async",loading:i.loading??(e?"eager":"lazy"),...r&&{fetchPriority:r}})},cc="https://srm-cdn.a4b.io/yoda/1771588545907.svg";function uc({isFormComplete:t,onPress:e,labelDefault:r,labelFilled:s,isLoading:n=!1,mode:i="form",firstPuja:a,showingResults:o=!1,bookPujaLabel:l="Book Puja",loadingLabel:u="Calculating..."}){return i==="book-puja"&&a&&o?c.jsx(q.FooterCTAButton,{onClick:e,disabled:n,className:Ke.bookPujaButton,children:c.jsxs("div",{className:Ke.bookPujaContent,children:[c.jsxs("div",{className:Ke.pujaInfo,children:[c.jsx("span",{className:Ke.pujaName,children:a.name}),a.price>0&&c.jsxs("div",{className:Ke.pujaPrice,children:[c.jsx("span",{className:Ke.priceLabel,children:"Starting from "}),c.jsxs("span",{className:Ke.priceAmount,children:["₹",a.price]})]})]}),c.jsxs("span",{className:Ke.bookButton,children:[l," →"]})]})}):c.jsx(q.FooterCTAButton,{onClick:e,disabled:n,className:t?Ke.ctaFilled:void 0,children:n?c.jsxs("span",{className:Ke.ctaFilledContent,children:[c.jsx(vs,{className:"w-5 h-5 animate-spin"}),u]}):t?c.jsxs("span",{className:Ke.ctaFilledContent,children:[s,c.jsx(lt,{src:cc,alt:"",className:Ke.chevronRight,width:20,height:20,loading:"lazy"})]}):r})}const Br={bannerContainer:"_bannerContainer_1s29r_1",bannerImage:"_bannerImage_1s29r_13",ticker:"_ticker_1s29r_20",tickerContent:"_tickerContent_1s29r_30"};function dc({bannerConfig:t,className:e="",imageComponent:r=lt}){const s=r;return c.jsxs("section",{className:`${Br.bannerContainer} ${e}`,children:[c.jsx(s,{src:t.imageUrl,alt:t.alt,className:Br.bannerImage,loading:"eager",priority:!0,fetchPriority:"high"}),c.jsx("div",{className:Br.ticker,children:c.jsx("div",{className:Br.tickerContent,children:t.tickerText})})]})}const hc=112;function ht({section:t,children:e,onImpression:r}){const s=w.useRef(null),n=w.useRef(!1);return w.useEffect(()=>{const i=s.current;if(!i)return;const a=new IntersectionObserver(([o])=>{!o?.isIntersecting||n.current||(n.current=!0,r(t))},{threshold:.1,rootMargin:`0px 0px -${hc}px 0px`});return a.observe(i),()=>a.disconnect()},[t,r]),c.jsx("div",{ref:s,children:e})}const Bt={wrap:"_wrap_1mrzx_1",input:"_input_1mrzx_6",iconBtn:"_iconBtn_1mrzx_35",iconImg:"_iconImg_1mrzx_49",placeholder:"_placeholder_1mrzx_53",dateDisplay:"_dateDisplay_1mrzx_65"},fc="https://srm-cdn.a4b.io/yoda/1770372045894.svg",mc=t=>{if(!t)return"";const[e,r,s]=t.split("-");return`${s}/${r}/${e}`};function pc({id:t,value:e,onChange:r,onOpen:s,className:n=""}){const i=w.useRef(null),a=w.useMemo(()=>{const l=new Date,u=d=>String(d).padStart(2,"0");return`${l.getFullYear()}-${u(l.getMonth()+1)}-${u(l.getDate())}`},[]),o=()=>{s?.();const l=i.current;if(l&&typeof l.showPicker=="function")try{l.showPicker()}catch{l?.focus()}else l?.focus()};return c.jsxs("div",{className:`${Bt.wrap} ${n}`,children:[!e&&c.jsx("span",{className:Bt.placeholder,children:"Select Date of Birth"}),e&&c.jsx("div",{className:Bt.dateDisplay,children:mc(e)}),c.jsx("input",{ref:i,id:t,type:"date",className:Bt.input,value:e,max:a,onChange:l=>{const u=l.target.value,d=new Date,h=m=>String(m).padStart(2,"0"),p=`${d.getFullYear()}-${h(d.getMonth()+1)}-${h(d.getDate())}`;u&&u>p||r(u)},onClick:o,onFocus:o}),c.jsx("button",{type:"button",className:Bt.iconBtn,"aria-label":"Open date picker",onMouseDown:l=>l.preventDefault(),onClick:l=>{l.preventDefault(),l.stopPropagation(),o()},children:c.jsx(lt,{className:Bt.iconImg,src:fc,alt:"",width:22,height:22,loading:"lazy"})})]})}const ve={wrap:"_wrap_spo2g_1",input:"_input_spo2g_6",iconBtn:"_iconBtn_spo2g_24",iconImg:"_iconImg_spo2g_38",timePopover:"_timePopover_spo2g_42",timePickerRow:"_timePickerRow_spo2g_58",timePickerSelect:"_timePickerSelect_spo2g_64",timePickerColon:"_timePickerColon_spo2g_80",meridiemToggle:"_meridiemToggle_spo2g_88",meridiemBtn:"_meridiemBtn_spo2g_97",meridiemActive:"_meridiemActive_spo2g_112",timePopoverActions:"_timePopoverActions_spo2g_117",timePopoverBtn:"_timePopoverBtn_spo2g_123",timePopoverOk:"_timePopoverOk_spo2g_142"},gc="https://srm-cdn.a4b.io/yoda/1770372014782.svg",ti=t=>String(t).padStart(2,"0");function yc(t){const e=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(t);if(!e)return t;const r=Number(e[1]),s=e[2],n=r>=12?"PM":"AM";return`${r%12===0?12:r%12}:${s} ${n}`}function bc(t){const e=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(t);if(!e)return{hour12:12,minute:"00",meridiem:"AM"};const r=Number(e[1]),s=e[2],n=r>=12?"PM":"AM";return{hour12:r%12===0?12:r%12,minute:s,meridiem:n}}function vc(t){const e=Math.min(12,Math.max(1,t.hour12)),r=/^([0-5]\d)$/.test(t.minute)?t.minute:"00";let s=e%12;return t.meridiem==="PM"&&(s+=12),`${ti(s)}:${r}`}function wc({id:t,value:e,onChange:r,onOpen:s,placeholder:n="Exact Time of Birth",disabled:i=!1,className:a=""}){const o=w.useRef(null),[l,u]=w.useState(!1),[d,h]=w.useState({hour12:12,minute:"00",meridiem:"AM"});w.useEffect(()=>{const g=y=>{o.current&&(o.current.contains(y.target)||u(!1))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[]);const p=()=>{i||(s?.(),h(bc(e||"12:00")),u(g=>!g))},m=()=>{const g=vc(d);r(g),u(!1)};return c.jsxs("div",{className:`${ve.wrap} ${a}`,ref:o,children:[c.jsx("input",{id:t,className:ve.input,type:"text",value:e?yc(e):"",readOnly:!0,disabled:i,placeholder:n,onClick:p}),c.jsx("button",{type:"button",className:ve.iconBtn,"aria-label":"Open time picker",disabled:i,onMouseDown:g=>g.preventDefault(),onClick:g=>{g.preventDefault(),g.stopPropagation(),p()},children:c.jsx(lt,{className:ve.iconImg,src:gc,alt:"",width:22,height:22,loading:"lazy"})}),l&&!i&&c.jsxs("div",{className:ve.timePopover,role:"dialog","aria-label":"Select time",children:[c.jsxs("div",{className:ve.timePickerRow,children:[c.jsx("select",{className:ve.timePickerSelect,value:d.hour12,onChange:g=>h(y=>({...y,hour12:Number(g.target.value)})),"aria-label":"Hour",children:Array.from({length:12},(g,y)=>y+1).map(g=>c.jsx("option",{value:g,children:g},g))}),c.jsx("span",{className:ve.timePickerColon,children:":"}),c.jsx("select",{className:ve.timePickerSelect,value:d.minute,onChange:g=>h(y=>({...y,minute:g.target.value})),"aria-label":"Minute",children:Array.from({length:60},(g,y)=>ti(y)).map(g=>c.jsx("option",{value:g,children:g},g))}),c.jsxs("div",{className:ve.meridiemToggle,"aria-label":"AM/PM",children:[c.jsx("button",{type:"button",className:`${ve.meridiemBtn} ${d.meridiem==="AM"?ve.meridiemActive:""}`,onClick:()=>h(g=>({...g,meridiem:"AM"})),children:"AM"}),c.jsx("button",{type:"button",className:`${ve.meridiemBtn} ${d.meridiem==="PM"?ve.meridiemActive:""}`,onClick:()=>h(g=>({...g,meridiem:"PM"})),children:"PM"})]})]}),c.jsxs("div",{className:ve.timePopoverActions,children:[c.jsx("button",{type:"button",className:ve.timePopoverBtn,onClick:()=>u(!1),children:"Cancel"}),c.jsx("button",{type:"button",className:`${ve.timePopoverBtn} ${ve.timePopoverOk}`,onClick:m,"aria-label":"OK",children:c.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:c.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})]})}async function ri(t,e){const{visitorId:r,sessionId:s,problemStatements:n,language:i}=e;if(n.length!==0)try{await t.from("session_problem_statements").insert({visitor_id:r,session_id:s,problem_statements:n,language:i??"en"})}catch{}}async function si(t,e,r){const{data:s,error:n}=await t.functions.invoke("calculate-dosha",{body:e,headers:r??{}});return n?{success:!1,error:n.message||"Calculation failed"}:s&&typeof s=="object"&&"success"in s?s.success===!0?s:{success:!1,error:s.error??"Unknown error",details:s.details}:{success:!1,error:"Invalid response from server"}}async function ni(t,e,r={}){const{visitorId:s="unknown",sessionId:n="unknown",trackProblemStatements:i=!0,problemStatements:a=[],language:o="en"}=r;return i&&a.length>0&&await ri(t,{visitorId:s,sessionId:n,problemStatements:a,language:o}),si(t,e,{"x-visitor-id":s,"x-session-id":n})}let Fr=null;const _c=(t,e)=>typeof window>"u"||window.google?.maps?.places?Promise.resolve():Fr||(Fr=new Promise((r,s)=>{const n=document.querySelector('script[data-google-maps-places="true"]');if(n){const o=Date.now(),l=()=>{if(window.google?.maps?.places){r();return}if(Date.now()-o>5e3){s(new Error("Google Maps script present but Places library did not become available."));return}window.setTimeout(l,50)};n.getAttribute("src")?l():(n.addEventListener("load",()=>l()),n.addEventListener("error",()=>s(new Error("Failed to load Google Maps API"))));return}const i=document.createElement("script"),a=new URL("https://maps.googleapis.com/maps/api/js");a.searchParams.set("key",t),a.searchParams.set("libraries","places"),a.searchParams.set("loading","async"),e&&a.searchParams.set("language",e),i.src=a.toString(),i.async=!0,i.defer=!0,i.setAttribute("data-google-maps-places","true"),i.onload=()=>{const o=Date.now(),l=()=>{if(window.google?.maps?.places){r();return}if(Date.now()-o>2e3){s(new Error("Google Maps loaded but Places library is unavailable. Check API key restrictions / enabled APIs."));return}window.setTimeout(l,50)};l()},i.onerror=()=>s(new Error("Failed to load Google Maps API")),document.head.appendChild(i)}),Fr),ii=(t={})=>{const{apiKey:e,language:r="en",restrictCountry:s}=t,[n,i]=w.useState(!1),[a,o]=w.useState([]),[l,u]=w.useState(!1),[d,h]=w.useState(null),p=w.useRef(null),m=w.useRef(null),g=w.useRef(null);w.useEffect(()=>{if(!e){i(!1),h(null);return}_c(e,r).then(()=>{try{p.current=new google.maps.places.AutocompleteService;const _=document.createElement("div");m.current=new google.maps.places.PlacesService(_),g.current=new google.maps.places.AutocompleteSessionToken,i(!0),h(null)}catch(_){i(!1),h(_ instanceof Error?_.message:"Failed to create Places services")}}).catch(_=>{i(!1),h(_ instanceof Error?_.message:"Failed to load location service")})},[e,r]);const y=w.useCallback(async _=>{if(!_||_.length<2||!p.current){o([]);return}u(!0);try{const k={input:_,types:["(cities)"],sessionToken:g.current??void 0};s&&(k.componentRestrictions={country:s});const O=await new Promise((R,M)=>{p.current.getPlacePredictions(k,(E,$)=>{$===google.maps.places.PlacesServiceStatus.OK&&E?R(E):$===google.maps.places.PlacesServiceStatus.ZERO_RESULTS?R([]):M(new Error(`Places API error: ${$}`))})});o(O.map(R=>({place_id:R.place_id,description:R.description,structured_formatting:{main_text:R.structured_formatting?.main_text||R.description,secondary_text:R.structured_formatting?.secondary_text||""}})))}catch{o([])}finally{u(!1)}},[s]),x=w.useCallback(async _=>{if(!m.current)return null;try{const k=await new Promise((L,$e)=>{m.current.getDetails({placeId:_,fields:["geometry","address_components","formatted_address"],sessionToken:g.current??void 0},(ge,Oe)=>{Oe===google.maps.places.PlacesServiceStatus.OK&&ge?L(ge):$e(new Error(`Place details error: ${Oe}`))})});g.current=new google.maps.places.AutocompleteSessionToken;const O=k.geometry?.location?.lat()||0,R=k.geometry?.location?.lng()||0;let M="",E="",$="";return k.address_components?.forEach(L=>{L.types.includes("locality")&&(M=L.long_name),L.types.includes("administrative_area_level_1")&&(E=L.long_name),L.types.includes("country")&&($=L.long_name)}),{display_name:k.formatted_address||"",lat:O,lng:R,city:M,state:E,country:$}}catch{return null}},[]),v=w.useCallback(()=>o([]),[]);return{isLoaded:n,predictions:a,isSearching:l,loadError:d,searchPlaces:y,getPlaceDetails:x,clearPredictions:v}},kc=["formProblemMarriage","formProblemMoney","formProblemHealth","formProblemEducation","formProblemCareer","formProblemOther"];function Sc(){try{const t="analytics_visitor_id";let e=typeof localStorage<"u"?localStorage.getItem(t):null;if(!e){e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`;try{localStorage.setItem(t,e)}catch{}}return e??"unknown"}catch{return"unknown"}}function xc(){try{const t="analytics_session_id";let e=typeof localStorage<"u"?localStorage.getItem(t):null;if(!e){e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`;try{localStorage.setItem(t,e)}catch{}}return e??"unknown"}catch{return"unknown"}}function Tc(t){if(!t)return 0;const e=new Date(t);if(Number.isNaN(e.getTime()))return 0;const r=new Date;let s=r.getFullYear()-e.getFullYear();const n=r.getMonth()-e.getMonth();return(n<0||n===0&&r.getDate()<e.getDate())&&s--,s}const ws=w.forwardRef(function({t:e,className:r="",initialValues:s,onValuesChange:n,onFormValidityChange:i,supabase:a,resolvePlace:o,onResult:l,onError:u,onLoadingChange:d,analytics:h,googleMapsApiKey:p},m){const g=A=>A.replace(/[^a-zA-Z\u0900-\u097F\s]/g,"").replace(/\s{2,}/g," "),[y,x]=w.useState(s?.name??""),[v,_]=w.useState(s?.gender??""),[k,O]=w.useState(s?.problems??[]),[R,M]=w.useState(s?.dateOfBirth??""),[E,$]=w.useState(s?.birthTime??""),[L,$e]=w.useState(s?.birthTimeUnknown??!1),[ge,Oe]=w.useState(s?.birthPlace??""),[ee,te]=w.useState(s?.otherProblemText??""),[he,tt]=w.useState(null),[Ce,re]=w.useState(!1),[fe,Se]=w.useState(null),[Q,b]=w.useState({}),F=w.useCallback(A=>{const I=ae=>{const Qe=document.getElementById(ae);return Qe?(Qe.focus(),Qe.scrollIntoView({behavior:"smooth",block:"center"}),!0):!1};if(A==="name"){I("dosha-name");return}if(A==="gender"){const ae=document.querySelector('[role="group"][aria-labelledby="dosha-gender-label"] button');ae&&(ae.focus(),ae.scrollIntoView({behavior:"smooth",block:"center"}));return}if(A==="dateOfBirth"){I("dosha-dob");return}if(A==="birthTime"){I("dosha-time");return}A==="birthPlace"&&I("dosha-place")},[]),z=w.useRef(!1),H=w.useRef(!1),V=w.useRef(!1),B=w.useRef(!1),U=w.useRef(!1),J=w.useRef(null),{predictions:se,isSearching:me,loadError:le,searchPlaces:Ee,getPlaceDetails:Kt,clearPredictions:We}=ii({apiKey:p,language:"en"}),Le=w.useCallback(()=>{z.current||(z.current=!0,h?.trackFormFillInitiated?.())},[h]);w.useEffect(()=>{const A=I=>{J.current&&(J.current.contains(I.target)||re(!1))};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[]),w.useEffect(()=>{if(!Ce)return;if(ge.length<2){We();return}const A=window.setTimeout(async()=>{await Ee(ge)},300);return()=>window.clearTimeout(A)},[ge,We,Ce,Ee]);const Tt=y.trim()!==""&&(v==="male"||v==="female")&&R!==""&&(E!==""||L)&&ge.trim()!=="";w.useEffect(()=>{i?.(Tt)},[Tt,i]),w.useEffect(()=>{n?.({name:y,gender:v,problems:k,otherProblemText:ee,dateOfBirth:R,birthTime:E,birthTimeUnknown:L,birthPlace:ge})},[y,v,k,ee,R,E,L,ge,n]),w.useEffect(()=>{!k.includes("formProblemOther")&&ee&&te("")},[k,ee]);const Et=w.useCallback(async(A,I)=>{if(!p)return"UTC";try{const ae=Math.floor(Date.now()/1e3),Qe=`https://maps.googleapis.com/maps/api/timezone/json?location=${A},${I}&timestamp=${ae}&key=${p}`,_e=await(await fetch(Qe)).json();return _e.status==="OK"&&_e.timeZoneId?_e.timeZoneId:"UTC"}catch{return"UTC"}},[p]),ct=w.useCallback(async()=>{const A=(ce,je,He=!1)=>{je&&(b(Me=>({...Me,[je]:ce})),F(je)),Se(He?ce:null),u?.(ce)};if(b({}),Se(null),!a){A(e("calculationError"));return}if(!y.trim()){A(e("formNameRequired"),"name");return}if(v!=="male"&&v!=="female"){A(e("formGenderRequired"),"gender");return}if(!R){A(e("formDobRequired"),"dateOfBirth");return}if(!L&&!E){A(e("formTimeRequired"),"birthTime");return}const I=ge.trim();if(!I){A(e("formPlaceRequired"),"birthPlace");return}const ae=g(I).trim();if(!ae){A(e("formPlaceRequired"),"birthPlace");return}const Qe=Tc(R),pt=new Set(["formProblemMarriage","formProblemMoney","formProblemCareer","formProblemBusiness","marriage","financial","career","business"]),_e=k.some(ce=>pt.has(ce));if(Qe<18&&_e){A(e("formAgeMarriageRestriction"),void 0,!0);return}if(!he&&!o){A(e("formPlaceSelectFromDropdown"),"birthPlace");return}d?.(!0);try{let ce,je,He;if(he)ce=he.lat,je=he.lon,he.tz?He=he.tz:(He=await Et(ce,je),tt({...he,tz:He}));else if(o){const ye=await o(I);if(!ye){A(e("locationError")),d?.(!1);return}ce=ye.lat,je=ye.lon,He=ye.tz}else{A(e("formPlaceSelectFromDropdown"),"birthPlace"),d?.(!1);return}const Me={problemAreaValues:[...k.filter(ye=>ye!=="formProblemOther").map(ye=>e(ye)).filter(Boolean),...k.includes("formProblemOther")&&ee.trim()?[ee.trim()]:[]],name:y.trim(),gender:v==="male"?"M":"F",date:R,time:L?"":E||"12:00",unknownTime:L,tz:He||"UTC",lat:ce,lon:je,place:ae,problemArea:void 0};Me.problemArea=Me.problemAreaValues.length>0?Me.problemAreaValues.join(", "):void 0;const cr=Sc(),N=xc(),ne=Me.problemAreaValues,xe=typeof navigator<"u"&&navigator.language?.toLowerCase().startsWith("hi")?"hi":"en",Te=await ni(a,Me,{visitorId:cr,sessionId:N,trackProblemStatements:!0,problemStatements:ne,language:xe});if(Te.success){Se(null);const[ye,ur,dr]=(Me.date||"").split("-").map(Number),zr=Me.time||"12:00",[gt,hr]=zr.split(":").map(Jr=>parseInt(Jr,10)||0);l?.(Te,{day:dr||1,month:ur||1,year:ye||2e3,hour:gt,minute:hr,lat:ce,lon:je,tzone:5.5})}else{let ye=Te.error??e("calculationError");(ye.includes("Expected 'M' | 'F'")||ye.includes("gender"))&&(ye=e("formGenderRequired")),A(ye)}}catch(ce){const je=ce instanceof Error?ce.message:String(ce);A(je)}finally{d?.(!1)}},[a,o,he,ge,y,v,R,E,L,k,e,u,d,h,l,Et,F]);w.useImperativeHandle(m,()=>({submit:ct}),[ct]);const lr=kc.map(A=>({key:A,label:e(A)}));return c.jsxs(q.FormContainer,{className:r,"aria-label":e("formTitle"),children:[c.jsx(q.PrivacyBanner,{text:e("formPrivacyBanner")}),c.jsx(q.FormSectionHeader,{title:e("formTitle"),subtitle:e("formSubtitle")}),c.jsx("div",{onFocusCapture:()=>{Le(),h?.trackNameSectionClicked?.()},children:c.jsxs(q.FormField,{id:"dosha-name",label:e("formNameLabel"),required:!0,children:[c.jsx(q.FormTextInput,{id:"dosha-name",value:y,onChange:A=>{const I=A.target.value;I&&!H.current&&(H.current=!0,h?.trackNameSectionFilled?.()),x(I),Q.name&&b(ae=>({...ae,name:void 0})),fe&&Se(null)},placeholder:e("formNamePlaceholder"),autoComplete:"name"}),Q.name&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.name})]})}),c.jsxs(q.FormField,{id:"dosha-gender",label:e("formGenderLabel"),required:!0,children:[c.jsx(q.FormSegmentedControl,{id:"dosha-gender",options:[{value:"male",label:e("formGenderMale")},{value:"female",label:e("formGenderFemale")}],value:v,onChange:A=>{_(A),Q.gender&&b(I=>({...I,gender:void 0})),fe&&Se(null)}}),Q.gender&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.gender})]}),c.jsxs(q.FormField,{id:"dosha-problems",label:e("formProblemLabel"),children:[c.jsx(q.FormTagPills,{id:"dosha-problems",options:lr,selected:k,onChange:A=>{O(A),A.includes("formProblemOther")||te("")}}),k.includes("formProblemOther")&&c.jsxs("div",{style:{marginTop:"8px"},children:[c.jsx(q.FormTextInput,{id:"dosha-problem-other",value:ee,onChange:A=>{const I=A.target.value.slice(0,100);te(I)},placeholder:e("formProblemOtherPlaceholder")}),c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#8f6e56"},children:e("formProblemOtherHint")})]})]}),c.jsx(q.FormField,{id:"dosha-dob",label:e("formDobLabel"),required:!0,children:c.jsxs("div",{style:{minHeight:Q.dateOfBirth?"72px":"48px",transition:"min-height 0.2s"},children:[c.jsx(pc,{id:"dosha-dob",value:R,onOpen:()=>{Le(),h?.trackDobClicked?.()},onChange:A=>{A&&!V.current&&(V.current=!0,h?.trackDobFilled?.()),M(A),Q.dateOfBirth&&b(I=>({...I,dateOfBirth:void 0})),fe&&Se(null)}}),Q.dateOfBirth&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.dateOfBirth})]})}),c.jsx(q.FormField,{id:"dosha-time",label:e("formTimeLabel"),required:!0,children:c.jsxs("div",{style:{minHeight:Q.birthTime?"72px":"48px",transition:"min-height 0.2s"},children:[c.jsx(wc,{id:"dosha-time",value:E,onOpen:()=>{Le(),h?.trackTimeClicked?.()},onChange:A=>{A&&!B.current&&(B.current=!0,h?.trackTimeFilled?.()),$(A),Q.birthTime&&b(I=>({...I,birthTime:void 0})),fe&&Se(null)},disabled:L}),Q.birthTime&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.birthTime})]})}),c.jsx(q.FormCheckboxWithHelp,{id:"dosha-time-unknown",checked:L,onChange:A=>{Le(),h?.trackTimeCheckboxClicked?.(),$e(A),A&&Q.birthTime&&b(I=>({...I,birthTime:void 0}))},primaryText:e("formTimeUnknown"),helpText:e("formTimeUnknownHelp")}),c.jsx("div",{onFocusCapture:()=>{Le(),h?.trackPlaceOfBirthClicked?.()},children:c.jsx(q.FormField,{id:"dosha-place",label:e("formPlaceLabel"),required:!0,children:c.jsxs("div",{ref:J,style:{position:"relative"},children:[c.jsx(q.FormLocationInput,{id:"dosha-place",value:ge,onChange:A=>{const I=g(A.target.value);Oe(I),tt(null),re(!0),I&&!U.current&&(U.current=!0,h?.trackPlaceOfBirthChosen?.(I)),Q.birthPlace&&b(ae=>({...ae,birthPlace:void 0})),fe&&Se(null)},onFocus:()=>re(!0),placeholder:e("formPlacePlaceholder")}),Q.birthPlace&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.birthPlace}),Ce&&se.length>0&&c.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",maxHeight:"240px",overflowY:"auto",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},role:"listbox",children:se.slice(0,8).map(A=>c.jsxs("button",{type:"button",onClick:async()=>{if(Oe(g(A.description)),Kt){const I=await Kt(A.place_id);I&&(tt({lat:I.lat,lon:I.lng}),Q.birthPlace&&b(ae=>({...ae,birthPlace:void 0})),fe&&Se(null))}We(),re(!1),U.current||(U.current=!0,h?.trackPlaceOfBirthChosen?.(A.description))},style:{width:"100%",padding:"10px 12px",textAlign:"left",border:"none",backgroundColor:"transparent",cursor:"pointer",display:"flex",flexDirection:"column",gap:"2px",outline:"none"},onMouseEnter:I=>{I.currentTarget.style.backgroundColor="rgba(247, 94, 34, 0.06)"},onMouseLeave:I=>{I.currentTarget.style.backgroundColor="transparent"},onFocus:I=>{I.currentTarget.style.backgroundColor="rgba(247, 94, 34, 0.06)"},onBlur:I=>{I.currentTarget.style.backgroundColor="transparent"},children:[c.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:"#111827"},children:A.structured_formatting?.main_text??A.description}),A.structured_formatting?.secondary_text&&c.jsx("span",{style:{fontSize:"12px",color:"#6b7280"},children:A.structured_formatting.secondary_text})]},A.place_id))}),Ce&&p&&me&&c.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,padding:"10px 12px",backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",fontSize:"12px",color:"#6b7280",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},children:"Loading…"}),Ce&&p&&!me&&le&&c.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,padding:"10px 12px",backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",fontSize:"12px",color:"#dc2626",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},children:le})]})})}),c.jsxs(q.FormFooterNote,{children:["⚡ ",e("formFooterNoteBefore"),c.jsx("strong",{children:e("formFooterNoteBold")}),e("formFooterNoteAfter")]}),fe&&c.jsxs("div",{style:{marginTop:"4px",width:"100%",borderRadius:"14px",border:"1px solid #FCA5A5",background:"#FEF2F2",padding:"16px",display:"flex",alignItems:"flex-start",gap:"10px"},role:"alert","aria-live":"assertive",children:[c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{width:"16px",height:"16px",marginTop:"2px",flexShrink:0},"aria-hidden":"true",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),c.jsx("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]}),c.jsx("p",{style:{margin:0,fontSize:"14px",lineHeight:"1.5",color:"#EF4444"},children:fe})]})]})}),Ft=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`animate-pulse rounded-md bg-muted ${t}`,...e}));Ft.displayName="Skeleton";const ft=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`rounded-lg border border-border bg-card text-card-foreground shadow-sm ${t}`,...e}));ft.displayName="Card";const kt=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`flex flex-col space-y-1.5 p-6 ${t}`,...e}));kt.displayName="CardHeader";const St=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("h3",{ref:r,className:`text-2xl font-semibold leading-none tracking-tight ${t}`,...e}));St.displayName="CardTitle";const Kr=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("p",{ref:r,className:`text-sm text-muted-foreground ${t}`,...e}));Kr.displayName="CardDescription";const xt=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`p-6 pt-0 ${t}`,...e}));xt.displayName="CardContent";const ar=Ie.forwardRef(({className:t="",size:e="default",variant:r="default",...s},n)=>{const i={default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8"},a={default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"};return c.jsx("button",{ref:n,type:"button",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 ${i[e]} ${a[r]} ${t}`,...s})});ar.displayName="Button";function ai({puja:t,doshaType:e,language:r,onBookClick:s,imageComponent:n=lt,analytics:i}){const a=n,o=r?.toLowerCase().startsWith("hi"),l=ps(t,r),u=zn(t,r),d=Vn(t.schedule_date_ist,r),h=gs(t,r),p=Jn(t,r),m=async()=>{if(i?.trackDoshaCalculatorResultBookCtaClicked?.({position:"puja_card",url:h,isOldDosha:!1}),s)try{await s()}catch(g){console.error("Error in onBookClick:",g)}window.open(h,"_blank","noopener,noreferrer")};return c.jsx(ft,{className:"overflow-hidden hover:shadow-lg transition-shadow relative",children:c.jsxs("div",{className:"relative",children:[c.jsx("div",{className:"absolute -top-1 -left-1 z-10",children:c.jsx("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",children:o?"सीमित सीटें":"Limited Seats"})}),p&&c.jsx("div",{className:"relative aspect-[16/10] w-full overflow-hidden bg-muted",children:c.jsx(a,{src:p,alt:l,className:"w-full h-full object-contain",loading:"lazy"})}),c.jsxs("div",{className:"p-3 space-y-2",children:[c.jsx("h4",{className:"font-semibold text-sm line-clamp-2 text-card-foreground",children:l}),t.temple_name&&c.jsx("p",{className:"text-sm text-muted-foreground",children:u}),t.schedule_date_ist&&c.jsx("p",{className:"text-sm font-medium text-card-foreground",children:d}),t.individual_pack_price_inr>0&&c.jsx("p",{className:"text-base font-bold text-primary",children:o?`₹${t.individual_pack_price_inr} से शुरू`:`Starting from ₹${t.individual_pack_price_inr}`}),c.jsxs(ar,{size:"lg",className:"book-puja-cta w-full h-14 text-lg font-bold",onClick:async g=>{g.preventDefault(),await m()},children:[o?"पूजा बुक करें":"Book Puja",c.jsx(oc,{className:"ml-1.5 h-3.5 w-3.5",size:14})]}),c.jsx("p",{className:"text-[10px] text-center text-muted-foreground",children:o?"श्री मंदिर द्वारा संचालित":"Powered by Sri Mandir"})]})]})})}const mt={section:"_section_15ygl_1",heading:"_heading_15ygl_5",list:"_list_15ygl_16",item:"_item_15ygl_20",stepNumber:"_stepNumber_15ygl_24",itemContent:"_itemContent_15ygl_30",itemTitle:"_itemTitle_15ygl_34",itemDesc:"_itemDesc_15ygl_39"};function oi({t,className:e="",bannerType:r="generic"}){const s=t("whatFromAnalysisTitle"),n=r==="marriage"?"whatFromAnalysisMarriage":"whatFromAnalysisGeneric",i=[{titleKey:`${n}1Title`,descKey:`${n}1Desc`},{titleKey:`${n}2Title`,descKey:`${n}2Desc`},{titleKey:`${n}3Title`,descKey:`${n}3Desc`}];return c.jsxs("section",{className:`${mt.section} ${e}`,"aria-labelledby":"what-from-analysis-heading",children:[c.jsx("h2",{id:"what-from-analysis-heading",className:mt.heading,children:s}),c.jsx("ol",{className:mt.list,children:i.map(({titleKey:a,descKey:o},l)=>c.jsxs("li",{className:mt.item,children:[c.jsx("span",{className:mt.stepNumber,"aria-hidden":"true",children:l+1}),c.jsxs("div",{className:mt.itemContent,children:[c.jsx("span",{className:mt.itemTitle,children:t(a)}),c.jsx("span",{className:mt.itemDesc,children:t(o)})]})]},a))})]})}const Ec={marriage:{en:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137437775.webp",alt:"Marriage dosha analysis banner",tickerText:"★ 4.9 Rated By Users Facing Marriage Delay"},hi:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137493287.webp",alt:"विवाह दोष विश्लेषण बैनर",tickerText:"★ 4.9 शादी में देरी का सामना कर रहे उपयोगकर्ताओं द्वारा रेटेड"}},generic:{en:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137415503.webp",alt:"Dosha analysis banner",tickerText:"★ 4.9 Rated By Users Seeking Clarity"},hi:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137476046.webp",alt:"दोष विश्लेषण बैनर",tickerText:"★ 4.9 रेटिंग अपने दोषा को जानने वाले यूज़र्स ने दी"}}},jc={"marriage-what-you'll-get-first":"marriage","marriage-form-first":"marriage","generic-what-you'll-get-first":"generic","generic-form-first":"generic"};function li(t,e){let r="generic";if(t){for(const[s,n]of Object.entries(jc))if(t.includes(s)){r=n;break}}return Ec[r][e]}function Ac(t){return typeof window>"u"?null:new URLSearchParams(window.location.search).get(t)}function qr(){return Ac("utm_term")}const Pc=w.lazy(()=>Promise.resolve().then(()=>Yc).then(t=>({default:t.DoshaResultsFull}))),Rc="https://srm-cdn.a4b.io/yoda/1770362904947.svg",Oc="https://srm-cdn.a4b.io/yoda/1770375694934.svg",Cc="https://srm-cdn.a4b.io/yoda/1770375720933.svg",Nc="https://srm-cdn.a4b.io/yoda/1770707793537.svg",Ic="https://srm-cdn.a4b.io/yoda/1770362713543.svg";function ci(t){const e=new Set([t]);switch(t){case"kaal-sarp":e.add("kaalSarp"),e.add("kaalsarp"),e.add("kaal_sarp");break;case"shani":e.add("sadeSati"),e.add("shaniSadeSati"),e.add("sade-sati");break;case"mangal":e.add("mangalDosha"),e.add("manglik");break;case"pitra":e.add("pitru"),e.add("pitraDosha");break}return Array.from(e)}function Wr(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function ui(t){if(!t)return 2;const e=t.toLowerCase();return e==="severe"||e==="high"?3:e==="moderate"||e==="medium"?2:e==="mild"||e==="low"?1:2}function di(t){if(!t||typeof window>"u")return t;try{const e=new URLSearchParams(window.location.search);if(Array.from(e.keys()).length===0)return t;const r=new URL(t,window.location.href);return e.forEach((s,n)=>{r.searchParams.set(n,s)}),r.toString()}catch{return t}}function _s(t){const e=[];return Wr(t.kaalSarp)&&e.push({type:"kaal-sarp",severity:typeof t.kaalSarpSeverity=="string"?t.kaalSarpSeverity:void 0}),Wr(t.pitra)&&e.push({type:"pitra",severity:typeof t.pitraSeverity=="string"?t.pitraSeverity:void 0}),Wr(t.shaniSadeSati||t.sadeSati)&&e.push({type:"shani",severity:typeof t.sadeSatiSeverity=="string"?t.sadeSatiSeverity:void 0}),Wr(t.mangal)&&!t.mangal?.toLowerCase().includes("nullified")&&e.push({type:"mangal",severity:typeof t.mangalSeverity=="string"?t.mangalSeverity:void 0}),e.length===0?null:(e.sort((r,s)=>ui(s.severity)-ui(r.severity)),e[0]?.type??null)}function Dc({t}){return c.jsxs("div",{className:q.footerShellStyles.marqueeContent,children:[c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(lt,{src:Oc,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaKundliCreated")]}),c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(lt,{src:Cc,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaCertified")]}),c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(lt,{src:Nc,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaSecurePayment")]})]})}const $c=[{qKey:"faqQ1",aKey:"faqA1"},{qKey:"faqQ2",aKey:"faqA2"},{qKey:"faqQ3",aKey:"faqA3"}],Lc=[{qKey:"faqQ1Marriage",aKey:"faqA1Marriage"},{qKey:"faqQ2Marriage",aKey:"faqA2Marriage"},{qKey:"faqQ3Marriage",aKey:"faqA3Marriage"},{qKey:"faqQ4Marriage",aKey:"faqA4Marriage"}];function Mc({className:t="",logoUrl:e=Rc,languageSelector:r,showLanguageSelector:s=!0,isGlobal:n=!1,readMoreReviewsHref:i,supabaseUrl:a,supabaseAnonKey:o,googleMapsApiKey:l,supabase:u,resolvePlace:d,onResult:h,onError:p,renderPujaCard:m,isLoadingPujas:g=!1,renderKundali:y,kundaliSectionId:x="kundali-chart-section",analytics:v,getFirstPujaInfo:_,onBookPujaClick:k,imageComponent:O=lt}){const R=w.useMemo(()=>{if(u)return u;if(a&&o)try{return Un(a,o)}catch{return null}return null},[u,a,o]),M=O,E=ys(),$=E?.t??(N=>N),L=E?.locale??"en",$e=E?.setLocale,ge=L.toLowerCase().startsWith("hi"),Oe=w.useRef(null),ee=w.useRef(null),[te,he]=w.useState(!1),[tt,Ce]=w.useState(!1),[re,fe]=w.useState(null),[Se,Q]=w.useState(null),[b,F]=w.useState(void 0),[z,H]=w.useState(!1),[V,B]=w.useState([]),[U,J]=w.useState(!1),[se,me]=w.useState(null),le=w.useRef(!1);w.useEffect(()=>{le.current||(le.current=!0,v?.trackDoshaCalculatorWebView?.())},[]);const Ee=!m||!_;w.useEffect(()=>{if(!Ee||!R)return;let N=!0;return J(!0),Gl(R).then(ne=>{N&&B(ne)}).finally(()=>{N&&J(!1)}),()=>{N=!1}},[Ee,R]);const Kt=w.useCallback(N=>{const ne=Kn(V,N);return ne?c.jsx(ai,{puja:ne,doshaType:N,language:L,imageComponent:O,analytics:v}):null},[V,L,O,v]),We=w.useCallback(N=>{const ne=Kn(V,N);return ne?{name:ps(ne,L),price:ne.individual_pack_price_inr,link:gs(ne,L)}:null},[V,L]),Le=m??Kt,Tt=_??We,Et=g||!m&&U,[ct,lr]=w.useState(()=>{const N=typeof window<"u"?qr():null;return li(N,L)}),[A,I]=w.useState(()=>{if(typeof window>"u")return"generic";const N=qr();return N&&N.toLowerCase().includes("marriage")?"marriage":"generic"});w.useEffect(()=>{const N=qr(),ne=li(N,L);lr(ne);let xe="generic";N&&N.toLowerCase().includes("marriage")&&(xe="marriage"),I(xe)},[L]);const[ae,Qe]=w.useState(!1);w.useEffect(()=>{const N=qr();N&&N.toLowerCase().includes("what-you")&&Qe(!0)},[]);const pt=()=>{Oe.current?.scrollIntoView({behavior:"smooth"})},_e=w.useCallback(N=>{v?.trackDoshaSectionImpression?.({section:N,timestamp:new Date().toISOString()})},[v]),ce=(N,ne)=>{if(fe(N),Q(ne??null),H(!1),N.summary){const xe=N.summary,Te=_s(xe);if(Te){const ye=ci(Te).map(ur=>Tt(ur)).find(Boolean)??null;me(ye)}else me(null)}else me(null);h?.(N,ne)};w.useEffect(()=>{if(_||!re?.summary)return;const N=_s(re.summary);if(!N){me(null);return}const ne=ci(N).map(xe=>We(xe)).find(Boolean)??null;me(ne)},[We,_,re]);const je=()=>{H(!0),window.scrollTo({top:0,behavior:"smooth"})},He=()=>{if(re&&!z&&se){if(se.link){const N=di(se.link);v?.trackDoshaCalculatorResultBookCtaClicked?.({position:"floating_cta",url:N,isOldDosha:!1})}if(k)k();else if(se.link){const N=di(se.link);window.open(N,"_blank","noopener,noreferrer")}return}console.log("supabase",R),console.log("resolvePlaceProp",d),console.log("isFormComplete",te),console.log("formSubmitRef.current",ee.current),R&&ee.current?(v?.trackFloatingCtaClicked?.(te?pr.all_fields_filled:pr.fields_not_filled),te||pt(),ee.current.submit()):(v?.trackFloatingCtaClicked?.(pr.fields_not_filled),pt())},cr=s&&!n?c.jsxs("button",{type:"button",onClick:()=>{$e&&$e(ge?"en":"hi")},"aria-label":ge?"Switch to English":"हिंदी में बदलें",className:"flex items-center justify-center gap-1.5 py-2 rounded-lg text-white text-sm font-medium hover:opacity-90 transition-colors",style:{backgroundColor:"#E13A44",borderRadius:"8px",width:"100px"},disabled:!$e,children:[c.jsx(M,{src:Ic,alt:"",className:"w-5 h-5 brightness-0 invert",width:20,height:20,loading:"lazy"}),c.jsx("span",{children:ge?"English":"हिंदी"})]}):null;return c.jsxs("div",{className:t,children:[c.jsx(q.PageHeader,{t:$,logoUrl:e,languageSelector:cr,showLanguageSelector:s}),c.jsx(q.MarqueeStrip,{children:c.jsx(Dc,{t:$})}),!re&&c.jsx(ht,{section:"banner",onImpression:_e,children:c.jsx(dc,{bannerConfig:ct,imageComponent:O})}),c.jsx("main",{className:"pb-28",children:re?c.jsx(ht,{section:"result",onImpression:_e,children:c.jsx(w.Suspense,{fallback:c.jsxs("div",{className:"container mx-auto px-4 py-8 space-y-4",children:[c.jsx(Ft,{className:"h-12 w-3/4 mx-auto"}),c.jsx(Ft,{className:"h-32 w-full"}),c.jsx(Ft,{className:"h-48 w-full"}),c.jsx(Ft,{className:"h-48 w-full"})]}),children:c.jsx(Pc,{result:re,t:$,onEdit:z?void 0:je,inlineEditForm:z?c.jsx(ws,{ref:ee,t:$,initialValues:b,onValuesChange:F,onFormValidityChange:he,supabase:R??void 0,resolvePlace:d,googleMapsApiKey:l,onResult:ce,onError:p,onLoadingChange:Ce,analytics:v}):void 0,renderPujaCard:Le,isLoadingPujas:Et,renderKundali:y,kundaliSectionId:x,birthDetails:Se,supabase:R,language:E?.locale??"en",readMoreReviewsHref:i,analytics:v,problemArea:(()=>{const N=b?.problems||[],ne=N.filter(Te=>Te!=="formProblemOther").map(Te=>$(Te)).filter(Boolean),xe=b?.otherProblemText?.trim();return N.includes("formProblemOther")&&xe&&ne.push(xe),ne.join(", ")})(),problemAreaIds:b?.problems||[],customProblemText:b?.otherProblemText||""})})}):c.jsxs(c.Fragment,{children:[ae&&c.jsx(ht,{section:"what_from_analysis",onImpression:_e,children:c.jsx(oi,{t:$,bannerType:A})}),c.jsx(ht,{section:"form",onImpression:_e,children:c.jsx("div",{ref:Oe,children:c.jsx(ws,{ref:ee,t:$,initialValues:b,onValuesChange:F,onFormValidityChange:he,supabase:R??void 0,resolvePlace:d,googleMapsApiKey:l,onResult:ce,onError:p,onLoadingChange:Ce,analytics:v})})}),!ae&&c.jsx(ht,{section:"what_from_analysis",onImpression:_e,children:c.jsx(oi,{t:$,bannerType:A})}),c.jsx(ht,{section:"user_reviews",onImpression:_e,children:c.jsx(q.UserReviewsSection,{t:N=>{if(A==="marriage"){if(N==="feedbackTitle")return $("feedbackTitleMarriage");if(N.startsWith("feedbackTestimonial")){const xe=`feedbackTestimonialMarriage${N.replace("feedbackTestimonial","")}`,Te=$(xe);return Te===xe?$(N):Te}}return $(N)},readMoreHref:i,onReadMore:v?.trackReadMoreReviewsClicked?()=>v.trackReadMoreReviewsClicked():void 0})}),c.jsx(ht,{section:"faq",onImpression:_e,children:c.jsx(q.FAQAccordion,{t:$,items:A==="marriage"?Lc:$c,defaultOpenIndex:0,onItemOpen:N=>v?.trackFaqQuestionClicked?.(N)})}),c.jsx(ht,{section:"contact",onImpression:_e,children:c.jsx(q.ContactUsSection,{title:$("contactTitle"),brandName:$("contactBrandName"),whatsAppLine:$("contactWhatsAppDomestic"),emailLine:$("contactEmail")})})]})}),!(re&&!z&&_s(re.summary)===null)&&c.jsxs(q.FooterShell,{children:[!(re&&!z&&se)&&c.jsx(tc,{}),c.jsx(uc,{isFormComplete:te,onPress:He,labelDefault:$("formCta"),labelFilled:$("formCtaCalculate"),loadingLabel:$("calculating"),isLoading:tt,mode:re&&!z&&se?"book-puja":"form",firstPuja:se||void 0,showingResults:!!re&&!z,bookPujaLabel:$("bookPuja")})]})]})}const oe={section:"_section_ji9so_1",heading:"_heading_ji9so_6",headingSuccess:"_headingSuccess_ji9so_13",card:"_card_ji9so_17",cardPresent:"_cardPresent_ji9so_25",cardAbsent:"_cardAbsent_ji9so_29",cardHeader:"_cardHeader_ji9so_33",doshaName:"_doshaName_ji9so_41",badge:"_badge_ji9so_46",badgePresent:"_badgePresent_ji9so_53",badgeAbsent:"_badgeAbsent_ji9so_58",badgeInactive:"_badgeInactive_ji9so_63",body:"_body_ji9so_68",bodyLabel:"_bodyLabel_ji9so_75",noDoshas:"_noDoshas_ji9so_81",noDoshasDesc:"_noDoshasDesc_ji9so_88",editBtn:"_editBtn_ji9so_94",accordionContent:"_accordionContent_ji9so_128"},Uc=[{key:"mangal",labelKey:"resultMangal",summaryKey:"mangal"},{key:"kaalSarp",labelKey:"resultKaalSarp",summaryKey:"kaalSarp"},{key:"pitra",labelKey:"resultPitra",summaryKey:"pitra"},{key:"sadeSati",labelKey:"resultSadeSati",summaryKey:"shaniSadeSati"}];function or(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function Bc(t,e){if(Array.isArray(t))return t.find(s=>(s.name??s.type)===e);if(t&&typeof t=="object"&&e in t){const r=t[e];if(!r)return;const s=typeof r.remedies=="string"?r.remedies:Array.isArray(r.remedies)?r.remedies.join(`
153
+ `):void 0;return{explanation:r.explanation,remedies:s}}}function Fc(t,e){if(!t)return"";const r=t.toLowerCase();return r.includes("nullified")||r==="present"||r==="active"||r==="partial"||r==="suggested"?e("resultStatusPresent"):r==="absent"?e("resultStatusAbsent"):r==="inactive"?e("resultStatusInactive"):t}function Kc({result:t,t:e,onEdit:r,className:s=""}){const n=t.summary??{},i=t.details??{},a=n.shaniSadeSati??n.sadeSati,o=or(n.mangal)||or(n.kaalSarp)||or(n.pitra)||or(a);return c.jsxs("section",{className:`${oe.section} ${s}`,"aria-labelledby":"dosha-results-heading",children:[c.jsx("h2",{id:"dosha-results-heading",className:o?`${oe.heading} ${oe.headingSuccess}`:oe.heading,children:e(o?"resultSomeDoshas":"resultNoDoshas")}),o?c.jsx("div",{children:Uc.map(({key:l,labelKey:u,summaryKey:d})=>{const h=d==="shaniSadeSati"?a:n[d],p=or(h),m=Bc(i,l==="sadeSati"?"sadeSati":l),g=m?.explanation,y=typeof m?.remedies=="string"?m.remedies:void 0;return c.jsxs("div",{className:`${oe.card} ${p?oe.cardPresent:oe.cardAbsent}`,children:[c.jsxs("div",{className:oe.cardHeader,children:[c.jsx("span",{className:oe.doshaName,children:e(u)}),c.jsx("span",{className:`${oe.badge} ${p?oe.badgePresent:h==="inactive"?oe.badgeInactive:oe.badgeAbsent}`,children:Fc(h,e)})]}),(g||y)&&c.jsxs("div",{className:oe.body,children:[g&&c.jsxs("div",{children:[c.jsx("div",{className:oe.bodyLabel,children:e("resultExplanation")}),c.jsx("p",{className:oe.accordionContent,children:g})]}),y&&c.jsxs("div",{style:{marginTop:g?"0.75rem":0},children:[c.jsx("div",{className:oe.bodyLabel,children:e("resultRemedies")}),c.jsx("p",{className:oe.accordionContent,children:y})]})]})]},l)})}):c.jsxs("div",{className:oe.noDoshas,children:[c.jsx("p",{children:e("resultNoDoshas")}),c.jsx("p",{className:oe.noDoshasDesc,children:e("resultNoDoshasDesc")})]}),r&&c.jsx("button",{type:"button",className:oe.editBtn,onClick:r,"aria-label":e("resultEditForm"),children:e("resultEditForm")})]})}const Hr=Ie.forwardRef(({className:t="",variant:e="default",...r},s)=>{const n={default:"border-transparent bg-primary text-primary-foreground",secondary:"border-transparent bg-secondary text-secondary-foreground",destructive:"border-transparent bg-destructive/10 text-destructive",outline:"border-border text-muted-foreground bg-transparent"};return c.jsx("div",{ref:s,className:`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors ${n[e]} ${t}`,...r})});Hr.displayName="Badge";const ks=Ie.createContext(null);function hi({type:t="single",collapsible:e=!0,className:r="",children:s,onValueChange:n}){const[i,a]=Ie.useState(null),o=Ie.useCallback(l=>{a(u=>{const d=u===l?e?null:u:l;return n?.(d),d})},[e,n]);return c.jsx(ks.Provider,{value:{value:i,onToggle:o},children:c.jsx("div",{className:r,children:s})})}function fi({value:t,className:e="",children:r}){return c.jsx("div",{"data-state":t,className:`border-b border-border ${e}`,children:r})}function mi({className:t="",children:e,value:r}){const s=Ie.useContext(ks),n=s?.value===r;return c.jsxs("button",{type:"button",onClick:()=>s?.onToggle(r),className:`flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline w-full text-left ${t}`,"aria-expanded":n,children:[e,c.jsx(ei,{className:`h-4 w-4 shrink-0 transition-transform duration-200 ${n?"rotate-180":""}`})]})}function pi({className:t="",children:e,value:r}){return Ie.useContext(ks)?.value===r?c.jsx("div",{className:`overflow-hidden text-sm pb-4 pt-0 ${t}`,children:e}):null}const Ss=new Map,gi=1800*1e3;function qc(t,e,r){return`D1|${e}|svg|${t.day}-${t.month}-${t.year}-${t.hour}-${t.minute}-${t.lat}-${t.lon}-${t.tzone}|${r}`}function Wc(t){const e=Ss.get(t);if(e&&Date.now()-e.timestamp<gi)return e.svg;try{const r=sessionStorage.getItem(`kundali_${t}`);if(r){const s=JSON.parse(r);if(Date.now()-s.timestamp<gi)return Ss.set(t,s),s.svg;sessionStorage.removeItem(`kundali_${t}`)}}catch{}return null}function Hc(t,e){const r={svg:e,timestamp:Date.now()};Ss.set(t,r);try{sessionStorage.setItem(`kundali_${t}`,JSON.stringify(r))}catch{}}function Gc(t){try{const r=new DOMParser().parseFromString(t,"image/svg+xml"),s=r.querySelector("svg");return s?(s.removeAttribute("width"),s.removeAttribute("height"),s.getAttribute("viewBox")||s.setAttribute("viewBox","0 0 350 350"),s.setAttribute("preserveAspectRatio","xMidYMid meet"),s.setAttribute("style","width:100%;height:auto;display:block;"),new XMLSerializer().serializeToString(r)):t}catch(e){return console.error("[kundaliChart] SVG transform error:",e),t}}async function yi(t,e){const{birthDetails:r,chartType:s,language:n,signal:i}=e,a=qc(r,s,n),o=Wc(a);if(o)return o;const l=await t.functions.invoke("get-kundali-chart",{body:{...r,chartType:s,language:n}});if(i?.aborted)throw new DOMException("Aborted","AbortError");if(l.error)throw new Error(l.error.message||"Failed to fetch kundali chart");const u=l.data?.data?.svg;if(!u)throw new Error("No SVG data in response");const d=Gc(u);return Hc(a,d),d}function bi({birthDetails:t,supabase:e,language:r,t:s}){const[n,i]=w.useState("North"),[a,o]=w.useState("idle"),[l,u]=w.useState(""),[d,h]=w.useState(""),p=w.useRef(null),m=w.useRef(null),y=(r||"").toLowerCase().startsWith("hi")?"hi":"en",x=w.useCallback(async k=>{p.current&&p.current.abort();const O=new AbortController;p.current=O,o("loading"),h("");try{const R=await yi(e,{birthDetails:t,chartType:k,language:y,signal:O.signal});O.signal.aborted||(u(R),o("success"))}catch(R){if(R instanceof Error&&R.name==="AbortError")return;console.error("[KundaliCard] Fetch error:",R),O.signal.aborted||(h(R instanceof Error?R.message:"Failed to load chart"),o("error"))}},[t,e,y]);w.useEffect(()=>(x(n),()=>{p.current&&p.current.abort()}),[n,x]);const v=k=>{k!==n&&i(k)},_=()=>{x(n)};return c.jsxs(ft,{ref:m,className:"spiritual-glow border border-primary/10",children:[c.jsxs(kt,{className:"pb-3",children:[c.jsx(St,{className:"text-xl font-bold",children:s("drYourKundali")}),c.jsxs("div",{className:"flex gap-2 mt-3 pt-2",children:[c.jsx(ar,{type:"button",size:"sm",variant:n==="North"?"default":"outline",className:"rounded-full px-4",onClick:()=>v("North"),children:s("kundaliChartNorth")}),c.jsx(ar,{type:"button",size:"sm",variant:n==="South"?"default":"outline",className:"rounded-full px-4",onClick:()=>v("South"),children:s("kundaliChartSouth")})]})]}),c.jsx(xt,{children:c.jsxs("div",{className:"w-full max-w-[360px] mx-auto",children:[a==="loading"&&c.jsx(Ft,{className:"w-full aspect-square rounded-lg"}),a==="success"&&l&&c.jsx("div",{className:"w-full aspect-square",dangerouslySetInnerHTML:{__html:l}}),a==="error"&&c.jsxs("div",{className:"w-full aspect-square flex flex-col items-center justify-center bg-muted/30 rounded-lg border border-border",children:[c.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:s("kundaliChartLoadError")}),c.jsxs(ar,{type:"button",variant:"outline",size:"sm",onClick:_,className:"gap-2",children:[c.jsx(lc,{className:"w-4 h-4"}),s("kundaliChartRetry")]})]})]})})]})}const zc=[{qKey:"faqQ1",aKey:"faqA1"},{qKey:"faqQ2",aKey:"faqA2"},{qKey:"faqQ3",aKey:"faqA3"}],vi=[{type:"kaal-sarp",detailKey:"kaalSarp",nameKey:"drKaalSarpName",descKey:"drKaalSarpDesc",impactKey:"drKaalSarpImpact",remediesKey:"drKaalSarpRemedies",benefitsKey:"drPujaBenefitsKaalSarp",icon:sc,summaryKey:"kaalSarp",severityKey:"kaalSarpSeverity"},{type:"pitra",detailKey:"pitra",nameKey:"drPitraName",descKey:"drPitraDesc",impactKey:"drPitraImpact",remediesKey:"drPitraRemedies",benefitsKey:"drPujaBenefitsPitra",icon:nc,summaryKey:"pitra",severityKey:"pitraSeverity"},{type:"shani",detailKey:"sadeSati",nameKey:"drSadeSatiName",descKey:"drSadeSatiDesc",impactKey:"drSadeSatiImpact",remediesKey:"drSadeSatiRemedies",benefitsKey:"drPujaBenefitsShani",icon:ic,summaryKey:"shaniSadeSati",severityKey:"sadeSatiSeverity"},{type:"mangal",detailKey:"mangal",nameKey:"drMangalName",descKey:"drMangalDesc",impactKey:"drMangalImpact",remediesKey:"drMangalRemedies",benefitsKey:"drPujaBenefitsMangal",icon:rc,summaryKey:"mangal",severityKey:"mangalSeverity"}];function Vc(t,e){const r=new Set([t]);switch(e&&r.add(e),t){case"kaal-sarp":r.add("kaalSarp"),r.add("kaalsarp"),r.add("kaal_sarp");break;case"shani":r.add("sadeSati"),r.add("shaniSadeSati"),r.add("sade-sati");break;case"mangal":r.add("mangalDosha"),r.add("manglik");break;case"pitra":r.add("pitru"),r.add("pitraDosha");break}return Array.from(r)}function qe(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function Gr(t){return t?t.toLowerCase().includes("nullified"):!1}function wi(t,e){if(Array.isArray(t)){const r=t.find(i=>(i.name??i.type)===e);if(!r)return;const s=typeof r.remedies=="string"?r.remedies:Array.isArray(r.remedies)?r.remedies.join(`
169
154
  `):void 0,n=Array.isArray(r.placements)?r.placements:void 0;return{explanation:r.explanation,remedies:s,placements:n}}if(t&&typeof t=="object"&&e in t){const r=t[e];if(!r)return;const s=typeof r.remedies=="string"?r.remedies:Array.isArray(r.remedies)?r.remedies.join(`
170
- `):void 0;return{explanation:r.explanation,remedies:s,placements:r.placements}}}function Zn(t,e){if(!t)return"";const r=t.toLowerCase();return r.includes("nullified")?e("drStatusNullified"):r==="present"||r==="active"||r==="partial"||r==="suggested"?e("drStatusPresent"):r==="absent"?e("drStatusAbsent"):r==="inactive"?e("drStatusInactive"):t}function ea(t){if(!t)return 2;const e=t.toLowerCase();return e==="severe"||e==="high"?3:e==="moderate"||e==="medium"?2:e==="mild"||e==="low"?1:2}function ta(t,e){if(!t)return e("drSeverityMedium");const r=t.toLowerCase();return e(r==="severe"||r==="high"?"drSeverityHigh":r==="moderate"||r==="medium"?"drSeverityMedium":r==="mild"||r==="low"?"drSeverityLow":"drSeverityMedium")}function ac(t){return!t||/[\u0900-\u097F]/.test(t)?!1:/[A-Za-z]/.test(t)}function ra({result:t,t:e,onEdit:r,className:s="",kundaliSectionId:n,feedbackEmail:a="pujaseva@appsforbharat.com",renderPujaCard:i,isLoadingPujas:o=!1,renderKundali:l,birthDetails:u,supabase:d,language:h="en",readMoreReviewsHref:m,inlineEditForm:p,analytics:g,problemArea:b,problemAreaIds:A,customProblemText:w}){const[S,k]=v.useState({}),[N,R]=v.useState(!1),B=!l&&u&&d,P=t.summary??{},U=t.details??{};v.useEffect(()=>{if(!b||!b.trim()||!d){R(!1);return}R(!0),k({}),(async()=>{const K={},W=["mangal","kaal-sarp","pitra","shani"].filter(M=>M==="mangal"?Fe(P.mangal)&&!Lr(P.mangal):M==="kaal-sarp"?Fe(P.kaalSarp):M==="pitra"?Fe(P.pitra):M==="shani"?Fe(P.shaniSadeSati??P.sadeSati):!1);console.log("[DoshaResultsFull] Generating impacts for:",W,"problemArea:",b);const V=W.map(async M=>{try{const L={formProblemMarriage:"marriage",formProblemMoney:"financial",formProblemHealth:"health",formProblemEducation:"education",formProblemCareer:"career",formProblemBusiness:"business",formProblemFamily:"family",formProblemFinancial:"financial",formProblemOther:"other"},J=A?.filter(le=>le!=="formProblemOther").map(le=>L[le]||le.toLowerCase()).filter(Boolean)||[];A?.includes("formProblemOther")&&w?.trim()&&J.push("other");const se=J[0]||void 0;console.log(`[DoshaResultsFull] Calling generate-impact for ${M}`,{originalProblemAreaIds:A,mappedProblemAreaIds:J,problemArea:b,problemAreaId:se,customProblemText:w,language:h?.toLowerCase().startsWith("hi")?"hi":"en"});const me=await d.functions.invoke("generate-impact",{body:{doshaType:M,problemArea:b,problemAreaId:se,problemAreaIds:J,customProblemText:w,language:h?.toLowerCase().startsWith("hi")?"hi":"en"}});if(console.log(`[DoshaResultsFull] Impact response for ${M}:`,me.data),me.error){console.error(`[DoshaResultsFull] Error generating impact for ${M}:`,me.error);return}me.data?.impactText&&(K[M]={title:me.data.impactTitle||e("drImpactIfPresent"),text:me.data.impactText})}catch(L){console.error(`[DoshaResultsFull] Failed to generate impact for ${M}:`,L)}});await Promise.all(V),console.log("[DoshaResultsFull] Final personalized impacts:",K),k(K),R(!1)})()},[b,A,w,h,d,P]),v.useEffect(()=>{g?.trackDoshaCalculatorResultPageView?.()},[g]);const $=P.shaniSadeSati??P.sadeSati,De=[{summaryKey:"grahan",detailKey:"grahan",labelKey:"drOtherGrahan",descKey:"drOtherGrahanDesc",impactKey:"drOtherGrahanImpact",remediesKey:"drOtherGrahanRemedies"},{summaryKey:"shrapit",detailKey:"shrapit",labelKey:"drOtherShrapit",descKey:"drOtherShrapitDesc",impactKey:"drOtherShrapitImpact",remediesKey:"drOtherShrapitRemedies"},{summaryKey:"guruChandal",detailKey:"guruChandal",labelKey:"drOtherGuruChandal",descKey:"drOtherGuruChandalDesc",impactKey:"drOtherGuruChandalImpact",remediesKey:"drOtherGuruChandalRemedies"},{summaryKey:"punarphoo",detailKey:"punarphoo",labelKey:"drOtherPunarphoo",descKey:"drOtherPunarphooDesc",impactKey:"drOtherPunarphooImpact",remediesKey:"drOtherPunarphooRemedies"},{summaryKey:"kemadruma",detailKey:"kemadruma",labelKey:"drOtherKemadruma",descKey:"drOtherKemadrumaDesc",impactKey:"drOtherKemadrumaImpact",remediesKey:"drOtherKemadrumaRemedies"},{summaryKey:"gandmool",detailKey:"gandmool",labelKey:"drOtherGandmool",descKey:"drOtherGandmoolDesc",impactKey:"drOtherGandmoolImpact",remediesKey:"drOtherGandmoolRemedies"},{summaryKey:"kalathra",detailKey:"kalathra",labelKey:"drOtherKalathra",descKey:"drOtherKalathraDec",impactKey:"drOtherKalathraImpact",remediesKey:"drOtherKalathraRemedies"},{summaryKey:"vishDaridra",detailKey:"vishDaridra",labelKey:"drOtherVishDaridra",descKey:"drOtherVishDaridraDesc",impactKey:"drOtherVishDaridraImpact",remediesKey:"drOtherVishDaridraRemedies"},{summaryKey:"ketuNaga",detailKey:"ketuNaga",labelKey:"drOtherKetuNaga",descKey:"drOtherKetuNagaDesc",impactKey:"drOtherKetuNagaImpact",remediesKey:"drOtherKetuNagaRemedies"},{summaryKey:"navagrahaUmbrella",detailKey:"navagraha",labelKey:"drOtherNavagraha",descKey:"drOtherNavagrahaDesc",impactKey:"drOtherNavagrahaImpact",remediesKey:"drOtherNavagrahaRemedies"}],Re=De.filter(y=>Fe(P[y.summaryKey])).length>0,ee=Fe(P.mangal)&&!Lr(P.mangal)||Fe(P.kaalSarp)||Fe(P.pitra)||Fe($)||Re,te=[];for(const y of Qn){const K=y.summaryKey==="shaniSadeSati"?$:P[y.summaryKey];if(!Fe(K)||y.type==="mangal"&&Lr(K))continue;const z=P[y.severityKey],W=y.type==="shani"?P.shaniPhase??P.shaniPhase:void 0,V=Xn(U,y.detailKey==="sadeSati"?"sadeSati":y.detailKey),M=V?.explanation,L=M&&!(h.toLowerCase().startsWith("hi")&&ac(M))?M:e(y.descKey),se=(V?.remedies??e(y.remediesKey)).split(`
171
- `).map(je=>je.trim()).filter(Boolean),le=e(y.benefitsKey).split(`
172
- `).map(je=>je.trim()).filter(Boolean);te.push({type:y.type,detailKey:y.detailKey,label:e(y.nameKey),icon:y.icon,status:K??"",severity:z||"moderate",phase:W??void 0,explanation:L,placements:V?.placements,impact:e(y.impactKey),remedies:se,benefits:le})}te.sort((y,K)=>ea(K.severity)-ea(y.severity));const[he,Ze]=v.useState(!1),Oe=/\b(house|lagna|ascendant|moon|mars|saturn|rahu|ketu|sun|jupiter|venus|mercury|sign|degree|H\d+|conjunction|aspect)\b|भाव|लग्न|चंद्र|मंगल|शनि|राहु|केतु|सूर्य|बृहस्पति|शुक्र|बुध/i,re=U&&typeof U=="object"&&!Array.isArray(U)?U:{},fe=[];te.forEach(y=>{const K=re[y.detailKey==="sadeSati"?"sadeSati":y.detailKey]||{},z=[...K.placements||[],...K.triggeredBy||[],...K.notes||[]].map(L=>String(L||"").trim()).filter(Boolean),W=Array.from(new Set(z)),V=W.filter(L=>Oe.test(L)),M=V.length>0?V:W;M.length>0&&fe.push({label:y.label,evidence:M})}),De.forEach(y=>{if(!Fe(P[y.summaryKey]))return;const K=re[y.detailKey]||{},z=[...K.placements||[],...K.triggeredBy||[],...K.notes||[]].map(L=>String(L||"").trim()).filter(Boolean),W=Array.from(new Set(z)),V=W.filter(L=>Oe.test(L)),M=V.length>0?V:W;if(M.length>0){const L=e(y.labelKey);fe.some(J=>J.label===L)||fe.push({label:L,evidence:M})}});const Se=y=>y===1?e("drPhaseRising"):y===2?e("drPhasePeak"):y===3?e("drPhaseSetting"):"",Q=["bg-orange-50/50 border-l-4 border-l-orange-400","bg-blue-50/50 border-l-4 border-l-blue-400","bg-purple-50/50 border-l-4 border-l-purple-400","bg-amber-50/50 border-l-4 border-l-amber-400"];return c.jsxs("div",{className:`w-full max-w-2xl mx-auto space-y-6 ${s}`,children:[c.jsxs("div",{className:"px-4 pt-4 pb-2 mb-6",children:[c.jsxs("div",{className:"text-center",children:[c.jsx("h1",{className:"text-2xl font-bold mb-2",style:{color:"#1F2937",fontFamily:'"Plus Jakarta Sans", sans-serif'},children:e("resultPageTitle")}),c.jsx("p",{className:"text-sm leading-relaxed",style:{color:"#6B7280",fontFamily:'"Plus Jakarta Sans", sans-serif'},children:e("resultPageSubtitle")})]}),p?c.jsx("div",{className:"mt-4",children:p}):r?c.jsxs("button",{type:"button",onClick:r,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",style:{fontFamily:'"Plus Jakarta Sans", sans-serif'},children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[c.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),c.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),e("resultEditForm")]}):null]}),c.jsxs(ct,{className:"spiritual-glow border-2 border-primary/20 mx-4",children:[c.jsx(yt,{children:c.jsx(bt,{id:"dosha-results-heading",className:`text-2xl sm:text-3xl font-bold break-words ${ee?"text-primary":"text-success"}`,children:ee?e("resultSomeDoshas"):`✓ ${e("resultNoDoshas")}`})}),c.jsx(vt,{children:ee?c.jsx("div",{className:"flex flex-wrap gap-2",children:te.map(y=>c.jsxs("div",{className:"inline-flex items-center gap-2 bg-accent/20 border border-accent/30 px-4 py-2 rounded-full",children:[c.jsx(cs,{className:"w-4 h-4 text-primary"}),c.jsxs("span",{className:"font-medium text-sm text-foreground",children:[y.label,": ",Zn(y.status,e)]})]},y.type))}):c.jsxs("div",{className:"text-center py-8",children:[c.jsx(On,{className:"w-12 h-12 mx-auto mb-4 text-success"}),c.jsx("p",{className:"text-lg font-medium text-foreground",children:e("resultNoDoshas")}),c.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:e("resultNoDoshasDesc")})]})})]}),te.map((y,K)=>{const z=y.icon,W=y.type==="shani"&&y.phase?Se(y.phase):"",V=Q[K%Q.length],M=e("drDoshaOf").replace("{{index}}",String(K+1)).replace("{{total}}",String(te.length));return c.jsxs(ct,{className:`spiritual-glow border border-primary/10 mx-4 ${V}`,children:[c.jsx("div",{className:"px-4 pt-3",children:c.jsx($r,{variant:"outline",className:"text-xs font-normal text-muted-foreground",children:M})}),c.jsxs(yt,{className:"pb-3 pt-2",children:[c.jsxs(bt,{className:"flex items-center gap-3 text-xl",children:[c.jsx(z,{className:"w-6 h-6 text-primary"}),y.label]}),c.jsxs(Nr,{children:[e("drSeverity"),": ",ta(y.severity,e),y.phase!=null&&` • ${e("drPhase")}: ${y.phase}`]})]}),c.jsxs(vt,{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsxs("h4",{className:"font-semibold text-base flex items-center gap-2",children:[c.jsx(Rr,{className:"w-4 h-4 text-primary"}),e("drWhyMarked"),n&&c.jsxs("button",{type:"button",onClick:()=>{g?.trackDoshaCalculatorResultViewKundliClick?.();const L=document.getElementById(n);L&&L.scrollIntoView({behavior:"smooth",block:"center"})},className:"text-xs text-primary hover:underline ml-auto whitespace-nowrap",children:[e("drViewKundli")," ↓"]})]}),c.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:y.explanation}),W&&c.jsxs("div",{className:"mt-3 p-3 bg-warning/10 rounded-md border border-warning/20",children:[c.jsx("h5",{className:"font-medium text-sm mb-2",children:e("drPhaseMeaning")}),c.jsx("p",{className:"text-sm text-muted-foreground",children:W})]}),y.type!=="pitra"&&y.placements&&y.placements.length>0&&c.jsxs("div",{className:"mt-3 p-3 bg-accent/10 rounded-md border border-accent/20",children:[c.jsx("h5",{className:"font-medium text-sm mb-2",children:e("drPlanetaryPositions")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:y.placements.map((L,J)=>c.jsx("li",{children:L},J))})]})]}),c.jsxs("div",{className:"p-4 bg-destructive/10 border border-destructive/20 rounded-lg",children:[c.jsx("h4",{className:"font-semibold text-sm mb-2 text-destructive",children:S[y.type]?.title||e("drImpactIfPresent")}),N?c.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[c.jsx(us,{className:"w-4 h-4 animate-spin"}),c.jsx("span",{children:h==="hi"?"प्रभाव विश्लेषण हो रहा है...":"Analyzing impact..."})]}):c.jsx("p",{className:"text-sm text-muted-foreground",children:S[y.type]?.text||y.impact})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("h4",{className:"font-semibold text-base",children:e("drPujaRecommendation")}),i?o?c.jsx("div",{className:"flex items-center justify-center py-6",children:c.jsx(us,{className:"w-6 h-6 text-primary animate-spin",size:24})}):(()=>{const L=nc(y.type,y.detailKey),J=L.map(se=>i(se)).find(Boolean);return!J&&typeof window<"u"&&console.warn(`[DoshaCalculator] renderPujaCard returned null/undefined for dosha type: ${y.type} (tried: ${L.join(", ")})`),J||c.jsx("p",{className:"text-sm text-muted-foreground italic",children:e("drNoPujaAvailable")})})():c.jsxs("p",{className:"text-sm text-muted-foreground italic",children:[e("drNoPujaAvailable"),typeof window<"u"&&(console.warn("[DoshaCalculator] renderPujaCard prop not provided. Pass renderPujaCard to show puja recommendations."),null)]})]}),y.benefits.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsx("h4",{className:"font-semibold text-base flex items-center gap-2",children:e("drHowPujaHelps")}),c.jsx("ul",{className:"text-sm text-muted-foreground space-y-3 ml-1",children:y.benefits.map((L,J)=>c.jsxs("li",{className:"flex items-start gap-3",children:[c.jsx("span",{className:"text-primary mt-1.5 flex-shrink-0",children:"•"}),c.jsx("span",{children:L})]},J))})]})]})]},y.type)}),te.length>0&&c.jsx("p",{className:"text-xs text-muted-foreground text-center italic px-4",children:e("drFomoLine")}),c.jsxs("div",{className:"mx-4 p-4 bg-muted/30 rounded-lg border border-border/50 text-center",children:[c.jsx("p",{className:"text-sm text-foreground/80 font-medium",children:e("drFeedbackContact")}),c.jsx("a",{href:`mailto:${a}`,className:"text-primary hover:underline font-semibold text-base mt-1 inline-block",children:a})]}),c.jsxs(ct,{className:"spiritual-glow mx-4",children:[c.jsxs(yt,{children:[c.jsx(bt,{className:"text-2xl font-bold text-center gradient-spiritual bg-clip-text text-transparent",children:e("drDetailedAnalysis")}),c.jsx(Nr,{className:"text-center",children:e("drBasedOnChart")})]}),c.jsx(vt,{className:"space-y-4",children:c.jsx(Hn,{type:"single",collapsible:!0,className:"w-full space-y-4",children:Qn.map(y=>{const K=y.detailKey==="sadeSati"?"sadeSati":y.detailKey,z=y.summaryKey==="shaniSadeSati"?$:P[y.summaryKey],W=Xn(U,y.detailKey==="sadeSati"?"sadeSati":y.detailKey),V=P[y.severityKey],M=y.type==="shani"?P.shaniPhase:void 0,L=y.icon,me=(W?.remedies?.trim()||e(y.remediesKey)).split(`
173
- `).map(le=>le.trim()).filter(Boolean);return c.jsxs(Wn,{value:K,className:"border border-border rounded-lg px-4",children:[c.jsx(Gn,{value:K,className:"hover:no-underline",children:c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(L,{className:"w-5 h-5 text-destructive"}),c.jsxs("div",{className:"text-left",children:[c.jsx("h3",{className:"font-semibold text-lg",children:e(y.nameKey)}),c.jsxs("p",{className:"text-sm text-muted-foreground",children:[e("drStatus"),": ",Zn(z,e),V&&!Lr(z)&&` • ${e("drSeverity")}: ${ta(V,e)}`,y.type==="shani"&&M!=null&&` • ${e("drPhase")}: ${M}`]})]})]})}),c.jsxs(zn,{value:K,className:"pt-4 space-y-4",children:[c.jsx("p",{className:"text-sm text-muted-foreground italic",children:e(y.descKey)}),W?.explanation&&c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium mb-2",children:e("drExplanation")}),c.jsx("p",{className:"text-sm text-muted-foreground",children:W.explanation})]}),W?.placements&&W.placements.length>0&&c.jsxs("div",{className:"p-3 bg-accent/10 rounded-md",children:[c.jsx("h4",{className:"font-medium mb-2",children:e("drPlanetaryPositions")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:W.placements.map((le,je)=>c.jsx("li",{children:le},je))})]}),c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium mb-2",children:e("drTraditionalRemedies")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:me.map((le,je)=>c.jsx("li",{children:le},je))})]})]})]},K)})})})]}),c.jsxs(ct,{className:"mx-4",children:[c.jsx(yt,{className:"cursor-pointer hover:bg-accent/5 transition-colors",onClick:()=>Ze(y=>!y),children:c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"text-left flex-1 min-w-0",children:[c.jsx(bt,{className:"text-xl font-semibold",children:e("drOtherDoshas")}),c.jsx(Nr,{children:e(Re?"drOtherDoshasStatusActive":"drOtherDoshasStatusNone")})]}),c.jsx(Cn,{className:`h-5 w-5 flex-shrink-0 text-muted-foreground transition-transform duration-200 ${he?"rotate-180":""}`})]})}),he&&c.jsx(vt,{children:c.jsx(Hn,{type:"single",collapsible:!0,className:"w-full space-y-2",children:De.map(y=>{const K=P[y.summaryKey],z=Fe(K),W=re[y.detailKey]??{},V=W.explanation,M=W.placements;return c.jsxs(Wn,{value:y.summaryKey,className:"border border-border rounded-lg px-3",children:[c.jsx(Gn,{value:y.summaryKey,className:"hover:no-underline py-3",children:c.jsxs("div",{className:"flex items-center justify-between gap-2 flex-1 min-w-0 mr-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"font-semibold text-sm text-left leading-tight",children:e(y.labelKey)}),c.jsx(Rr,{size:14,className:"text-muted-foreground flex-shrink-0"})]}),z?c.jsxs($r,{variant:"destructive",className:"flex-shrink-0 text-xs flex items-center gap-1 pointer-events-none",children:[c.jsx(cs,{size:10}),e("drStatusPresent")]}):c.jsxs($r,{variant:"secondary",className:"flex-shrink-0 text-xs flex items-center gap-1 bg-white border pointer-events-none",style:{borderColor:"#e4decd",color:"#000000"},children:[c.jsx(On,{size:10,color:"#000000"}),e("drStatusAbsent")]})]})}),c.jsxs(zn,{value:y.summaryKey,className:"space-y-3 pt-0 pb-3",children:[c.jsx("div",{className:"border-l-4 border-orange-500 bg-orange-50 rounded-lg pl-3 py-2",children:c.jsx("p",{className:"text-sm text-muted-foreground italic",children:e(y.descKey)})}),M&&M.length>0&&c.jsxs("div",{className:"p-3 bg-accent/10 rounded-md border border-accent/20",children:[c.jsxs("h5",{className:"font-medium mb-2 flex items-center gap-2 text-sm",children:[c.jsx(Rr,{size:14}),e("drPlanetaryPositions")]}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1 leading-relaxed",children:M.map((L,J)=>c.jsx("li",{children:L},J))})]}),V&&c.jsxs("div",{className:"border-l-4 border-orange-500 bg-orange-50 rounded-lg pl-3 py-2",children:[c.jsxs("h5",{className:"font-medium mb-2 text-sm flex items-center gap-2",children:[c.jsx(Rr,{size:14}),e(z?"drWhyPresent":"drWhyAbsent")]}),c.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:V})]}),z&&c.jsxs("div",{className:"border-l-4 border-red-500 bg-red-50 rounded-lg pl-3 py-2",children:[c.jsxs("h5",{className:"font-medium mb-2 text-sm flex items-center gap-2 text-red-600",children:[c.jsx(cs,{size:14}),e("drImpact")]}),c.jsx("p",{className:"text-sm text-muted-foreground",children:e(y.impactKey)})]}),z&&c.jsxs("div",{children:[c.jsx("h5",{className:"font-medium mb-2 text-sm",children:e("drTraditionalRemedies")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:e(y.remediesKey).split(`
174
- `).map((L,J)=>c.jsx("li",{children:L},J))})]})]})]},y.summaryKey)})})})]}),c.jsx("div",{id:n||"kundali-chart-section",className:"px-4",children:(l||B||fe.length>0)&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"flex justify-end mb-2",children:c.jsxs("button",{type:"button",onClick:()=>document.getElementById("dosha-results-heading")?.scrollIntoView({behavior:"smooth",block:"start"}),className:"inline-flex items-center gap-1.5 text-sm text-primary hover:text-primary/80 transition-colors font-medium",children:[c.jsx(gl,{className:"w-4 h-4"}),e("drGoBack")]})}),l?c.jsxs("div",{className:"mt-2",children:[c.jsx("h2",{className:"text-xl font-semibold text-foreground mb-3",children:e("drYourKundali")}),l()]}):B&&u&&d?c.jsx("div",{className:"mt-2",children:c.jsx(Yn,{birthDetails:u,supabase:d,language:h,t:e})}):null,fe.length>0&&c.jsxs(ct,{className:"mt-4 bg-accent/10 border border-accent/30",children:[c.jsx(yt,{className:"pb-2",children:c.jsx(bt,{className:"text-base font-semibold",children:e("drPlanetaryPositionsCausing")})}),c.jsx(vt,{className:"pt-0",children:c.jsx("ul",{className:"space-y-3 text-sm text-muted-foreground",children:fe.map((y,K)=>c.jsxs("li",{children:[c.jsxs("div",{className:"font-semibold text-foreground mb-1",children:[y.label,":"]}),c.jsx("ul",{className:"ml-4 space-y-1",children:y.evidence.map((z,W)=>c.jsxs("li",{className:"flex items-start gap-2",children:[c.jsx("span",{className:"text-primary flex-shrink-0",children:"→"}),c.jsx("span",{children:z})]},W))})]},K))})})]})]})}),c.jsx("p",{className:"text-xs text-muted-foreground/70 text-center px-4",children:e("drDisclaimer")}),c.jsx(q.UserReviewsSection,{t:e,readMoreHref:m,onReadMore:g?.trackReadMoreReviewsClicked?()=>g.trackReadMoreReviewsClicked():void 0}),c.jsx(q.FAQAccordion,{t:e,items:sc,defaultOpenIndex:0}),c.jsx(q.ContactUsSection,{title:e("contactTitle"),brandName:e("contactBrandName"),whatsAppLine:e("contactWhatsAppDomestic"),emailLine:e("contactEmail")})]})}const ic=Object.freeze(Object.defineProperty({__proto__:null,DoshaResultsFull:ra},Symbol.toStringTag,{value:"Module"}));function oc(t){return!t||t.trim()===""?async()=>null:async e=>{try{if(!e?.trim())return null;const r=`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(e)}&key=${t}`,n=await(await fetch(r)).json();if(n.status!=="OK"||!n.results?.[0])return null;const{lat:a,lng:i}=n.results[0].geometry.location,o=Math.floor(Date.now()/1e3),l=`https://maps.googleapis.com/maps/api/timezone/json?location=${a},${i}&timestamp=${o}&key=${t}`,d=await(await fetch(l)).json();if(d.status!=="OK")return null;const h=d.timeZoneId,m=(d.rawOffset+d.dstOffset)/3600;return{lat:a,lon:i,tz:h,tzoneOffset:m}}catch{return null}}}G.DoshaCalculator=Vl,G.DoshaFormSection=ds,G.DoshaResultsFull=ra,G.DoshaResultsView=Xl,G.FLOATING_CTA_STATUS=ur,G.I18nProvider=ul,G.KundaliCard=Yn,G.LOCALE_LABELS=ll,G.SUPPORTED_LOCALES=ol,G.SriMandirPujaVerticalCard=Un,G.createGoogleMapsResolver=oc,G.createSupabaseClient=yn,G.fetchKundaliSvg=Jn,G.formatScheduleDate=jn,G.getCoverImageUrl=An,G.getPujaLink=os,G.getPujaTitle=is,G.getTempleName=Tn,G.insertSessionProblemStatements=In,G.invokeCalculateDosha=Dn,G.submitDoshaCalculation=$n,G.translations=En,G.useGooglePlacesAutocomplete=Ln,G.useI18n=ls,Object.defineProperty(G,Symbol.toStringTag,{value:"Module"})}));
155
+ `):void 0;return{explanation:r.explanation,remedies:s,placements:r.placements}}}function _i(t,e){if(!t)return"";const r=t.toLowerCase();return r.includes("nullified")?e("drStatusNullified"):r==="present"||r==="active"||r==="partial"||r==="suggested"?e("drStatusPresent"):r==="absent"?e("drStatusAbsent"):r==="inactive"?e("drStatusInactive"):t}function ki(t){if(!t)return 2;const e=t.toLowerCase();return e==="severe"||e==="high"?3:e==="moderate"||e==="medium"?2:e==="mild"||e==="low"?1:2}function Si(t,e){if(!t)return e("drSeverityMedium");const r=t.toLowerCase();return e(r==="severe"||r==="high"?"drSeverityHigh":r==="moderate"||r==="medium"?"drSeverityMedium":r==="mild"||r==="low"?"drSeverityLow":"drSeverityMedium")}function Jc(t){return!t||/[\u0900-\u097F]/.test(t)?!1:/[A-Za-z]/.test(t)}function xi({result:t,t:e,onEdit:r,className:s="",kundaliSectionId:n,feedbackEmail:i="pujaseva@appsforbharat.com",renderPujaCard:a,isLoadingPujas:o=!1,renderKundali:l,birthDetails:u,supabase:d,language:h="en",readMoreReviewsHref:p,inlineEditForm:m,analytics:g,problemArea:y,problemAreaIds:x,customProblemText:v}){const[_,k]=w.useState({}),[O,R]=w.useState(!1),M=!l&&u&&d,E=t.summary??{},$=t.details??{};w.useEffect(()=>{if(!y||!y.trim()||!d){R(!1);return}R(!0),k({}),(async()=>{const F={},H=["mangal","kaal-sarp","pitra","shani"].filter(B=>B==="mangal"?qe(E.mangal)&&!Gr(E.mangal):B==="kaal-sarp"?qe(E.kaalSarp):B==="pitra"?qe(E.pitra):B==="shani"?qe(E.shaniSadeSati??E.sadeSati):!1);console.log("[DoshaResultsFull] Generating impacts for:",H,"problemArea:",y);const V=H.map(async B=>{try{const U={formProblemMarriage:"marriage",formProblemMoney:"financial",formProblemHealth:"health",formProblemEducation:"education",formProblemCareer:"career",formProblemBusiness:"business",formProblemFamily:"family",formProblemFinancial:"financial",formProblemOther:"other"},J=x?.filter(le=>le!=="formProblemOther").map(le=>U[le]||le.toLowerCase()).filter(Boolean)||[];x?.includes("formProblemOther")&&v?.trim()&&J.push("other");const se=J[0]||void 0;console.log(`[DoshaResultsFull] Calling generate-impact for ${B}`,{originalProblemAreaIds:x,mappedProblemAreaIds:J,problemArea:y,problemAreaId:se,customProblemText:v,language:h?.toLowerCase().startsWith("hi")?"hi":"en"});const me=await d.functions.invoke("generate-impact",{body:{doshaType:B,problemArea:y,problemAreaId:se,problemAreaIds:J,customProblemText:v,language:h?.toLowerCase().startsWith("hi")?"hi":"en"}});if(console.log(`[DoshaResultsFull] Impact response for ${B}:`,me.data),me.error){console.error(`[DoshaResultsFull] Error generating impact for ${B}:`,me.error);return}me.data?.impactText&&(F[B]={title:me.data.impactTitle||e("drImpactIfPresent"),text:me.data.impactText})}catch(U){console.error(`[DoshaResultsFull] Failed to generate impact for ${B}:`,U)}});await Promise.all(V),console.log("[DoshaResultsFull] Final personalized impacts:",F),k(F),R(!1)})()},[y,x,v,h,d,E]),w.useEffect(()=>{g?.trackDoshaCalculatorResultPageView?.()},[g]);const L=E.shaniSadeSati??E.sadeSati,$e=[{summaryKey:"grahan",detailKey:"grahan",labelKey:"drOtherGrahan",descKey:"drOtherGrahanDesc",impactKey:"drOtherGrahanImpact",remediesKey:"drOtherGrahanRemedies"},{summaryKey:"shrapit",detailKey:"shrapit",labelKey:"drOtherShrapit",descKey:"drOtherShrapitDesc",impactKey:"drOtherShrapitImpact",remediesKey:"drOtherShrapitRemedies"},{summaryKey:"guruChandal",detailKey:"guruChandal",labelKey:"drOtherGuruChandal",descKey:"drOtherGuruChandalDesc",impactKey:"drOtherGuruChandalImpact",remediesKey:"drOtherGuruChandalRemedies"},{summaryKey:"punarphoo",detailKey:"punarphoo",labelKey:"drOtherPunarphoo",descKey:"drOtherPunarphooDesc",impactKey:"drOtherPunarphooImpact",remediesKey:"drOtherPunarphooRemedies"},{summaryKey:"kemadruma",detailKey:"kemadruma",labelKey:"drOtherKemadruma",descKey:"drOtherKemadrumaDesc",impactKey:"drOtherKemadrumaImpact",remediesKey:"drOtherKemadrumaRemedies"},{summaryKey:"gandmool",detailKey:"gandmool",labelKey:"drOtherGandmool",descKey:"drOtherGandmoolDesc",impactKey:"drOtherGandmoolImpact",remediesKey:"drOtherGandmoolRemedies"},{summaryKey:"kalathra",detailKey:"kalathra",labelKey:"drOtherKalathra",descKey:"drOtherKalathraDec",impactKey:"drOtherKalathraImpact",remediesKey:"drOtherKalathraRemedies"},{summaryKey:"vishDaridra",detailKey:"vishDaridra",labelKey:"drOtherVishDaridra",descKey:"drOtherVishDaridraDesc",impactKey:"drOtherVishDaridraImpact",remediesKey:"drOtherVishDaridraRemedies"},{summaryKey:"ketuNaga",detailKey:"ketuNaga",labelKey:"drOtherKetuNaga",descKey:"drOtherKetuNagaDesc",impactKey:"drOtherKetuNagaImpact",remediesKey:"drOtherKetuNagaRemedies"},{summaryKey:"navagrahaUmbrella",detailKey:"navagraha",labelKey:"drOtherNavagraha",descKey:"drOtherNavagrahaDesc",impactKey:"drOtherNavagrahaImpact",remediesKey:"drOtherNavagrahaRemedies"}],Oe=$e.filter(b=>qe(E[b.summaryKey])).length>0,ee=qe(E.mangal)&&!Gr(E.mangal)||qe(E.kaalSarp)||qe(E.pitra)||qe(L)||Oe,te=[];for(const b of vi){const F=b.summaryKey==="shaniSadeSati"?L:E[b.summaryKey];if(!qe(F)||b.type==="mangal"&&Gr(F))continue;const z=E[b.severityKey],H=b.type==="shani"?E.shaniPhase??E.shaniPhase:void 0,V=wi($,b.detailKey==="sadeSati"?"sadeSati":b.detailKey),B=V?.explanation,U=B&&!(h.toLowerCase().startsWith("hi")&&Jc(B))?B:e(b.descKey),se=(V?.remedies??e(b.remediesKey)).split(`
156
+ `).map(Ee=>Ee.trim()).filter(Boolean),le=e(b.benefitsKey).split(`
157
+ `).map(Ee=>Ee.trim()).filter(Boolean);te.push({type:b.type,detailKey:b.detailKey,label:e(b.nameKey),icon:b.icon,status:F??"",severity:z||"moderate",phase:H??void 0,explanation:U,placements:V?.placements,impact:e(b.impactKey),remedies:se,benefits:le})}te.sort((b,F)=>ki(F.severity)-ki(b.severity));const[he,tt]=w.useState(!1),Ce=/\b(house|lagna|ascendant|moon|mars|saturn|rahu|ketu|sun|jupiter|venus|mercury|sign|degree|H\d+|conjunction|aspect)\b|भाव|लग्न|चंद्र|मंगल|शनि|राहु|केतु|सूर्य|बृहस्पति|शुक्र|बुध/i,re=$&&typeof $=="object"&&!Array.isArray($)?$:{},fe=[];te.forEach(b=>{const F=re[b.detailKey==="sadeSati"?"sadeSati":b.detailKey]||{},z=[...F.placements||[],...F.triggeredBy||[],...F.notes||[]].map(U=>String(U||"").trim()).filter(Boolean),H=Array.from(new Set(z)),V=H.filter(U=>Ce.test(U)),B=V.length>0?V:H;B.length>0&&fe.push({label:b.label,evidence:B})}),$e.forEach(b=>{if(!qe(E[b.summaryKey]))return;const F=re[b.detailKey]||{},z=[...F.placements||[],...F.triggeredBy||[],...F.notes||[]].map(U=>String(U||"").trim()).filter(Boolean),H=Array.from(new Set(z)),V=H.filter(U=>Ce.test(U)),B=V.length>0?V:H;if(B.length>0){const U=e(b.labelKey);fe.some(J=>J.label===U)||fe.push({label:U,evidence:B})}});const Se=b=>b===1?e("drPhaseRising"):b===2?e("drPhasePeak"):b===3?e("drPhaseSetting"):"",Q=["bg-orange-50/50 border-l-4 border-l-orange-400","bg-blue-50/50 border-l-4 border-l-blue-400","bg-purple-50/50 border-l-4 border-l-purple-400","bg-amber-50/50 border-l-4 border-l-amber-400"];return c.jsxs("div",{className:`w-full max-w-2xl mx-auto space-y-6 ${s}`,children:[c.jsxs("div",{className:"px-4 pt-4 pb-2 mb-6",children:[c.jsxs("div",{className:"text-center",children:[c.jsx("h1",{className:"text-2xl font-bold mb-2",style:{color:"#1F2937",fontFamily:'"Plus Jakarta Sans", sans-serif'},children:e("resultPageTitle")}),c.jsx("p",{className:"text-sm leading-relaxed",style:{color:"#6B7280",fontFamily:'"Plus Jakarta Sans", sans-serif'},children:e("resultPageSubtitle")})]}),m?c.jsx("div",{className:"mt-4",children:m}):r?c.jsxs("button",{type:"button",onClick:r,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",style:{fontFamily:'"Plus Jakarta Sans", sans-serif'},children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[c.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),c.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),e("resultEditForm")]}):null]}),c.jsxs(ft,{className:"spiritual-glow border-2 border-primary/20 mx-4",children:[c.jsx(kt,{children:c.jsx(St,{id:"dosha-results-heading",className:`text-2xl sm:text-3xl font-bold break-words ${ee?"text-primary":"text-success"}`,children:ee?e("resultSomeDoshas"):`✓ ${e("resultNoDoshas")}`})}),c.jsx(xt,{children:ee?c.jsx("div",{className:"flex flex-wrap gap-2",children:te.map(b=>c.jsxs("div",{className:"inline-flex items-center gap-2 bg-accent/20 border border-accent/30 px-4 py-2 rounded-full",children:[c.jsx(bs,{className:"w-4 h-4 text-primary"}),c.jsxs("span",{className:"font-medium text-sm text-foreground",children:[b.label,": ",_i(b.status,e)]})]},b.type))}):c.jsxs("div",{className:"text-center py-8",children:[c.jsx(Zn,{className:"w-12 h-12 mx-auto mb-4 text-success"}),c.jsx("p",{className:"text-lg font-medium text-foreground",children:e("resultNoDoshas")}),c.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:e("resultNoDoshasDesc")})]})})]}),te.map((b,F)=>{const z=b.icon,H=b.type==="shani"&&b.phase?Se(b.phase):"",V=Q[F%Q.length],B=e("drDoshaOf").replace("{{index}}",String(F+1)).replace("{{total}}",String(te.length));return c.jsxs(ft,{className:`spiritual-glow border border-primary/10 mx-4 ${V}`,children:[c.jsx("div",{className:"px-4 pt-3",children:c.jsx(Hr,{variant:"outline",className:"text-xs font-normal text-muted-foreground",children:B})}),c.jsxs(kt,{className:"pb-3 pt-2",children:[c.jsxs(St,{className:"flex items-center gap-3 text-xl",children:[c.jsx(z,{className:"w-6 h-6 text-primary"}),b.label]}),c.jsxs(Kr,{children:[e("drSeverity"),": ",Si(b.severity,e),b.phase!=null&&` • ${e("drPhase")}: ${b.phase}`]})]}),c.jsxs(xt,{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsxs("h4",{className:"font-semibold text-base flex items-center gap-2",children:[c.jsx(Ur,{className:"w-4 h-4 text-primary"}),e("drWhyMarked"),n&&c.jsxs("button",{type:"button",onClick:()=>{g?.trackDoshaCalculatorResultViewKundliClick?.();const U=document.getElementById(n);U&&U.scrollIntoView({behavior:"smooth",block:"center"})},className:"text-xs text-primary hover:underline ml-auto whitespace-nowrap",children:[e("drViewKundli")," ↓"]})]}),c.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:b.explanation}),H&&c.jsxs("div",{className:"mt-3 p-3 bg-warning/10 rounded-md border border-warning/20",children:[c.jsx("h5",{className:"font-medium text-sm mb-2",children:e("drPhaseMeaning")}),c.jsx("p",{className:"text-sm text-muted-foreground",children:H})]}),b.type!=="pitra"&&b.placements&&b.placements.length>0&&c.jsxs("div",{className:"mt-3 p-3 bg-accent/10 rounded-md border border-accent/20",children:[c.jsx("h5",{className:"font-medium text-sm mb-2",children:e("drPlanetaryPositions")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:b.placements.map((U,J)=>c.jsx("li",{children:U},J))})]})]}),c.jsxs("div",{className:"p-4 bg-destructive/10 border border-destructive/20 rounded-lg",children:[c.jsx("h4",{className:"font-semibold text-sm mb-2 text-destructive",children:_[b.type]?.title||e("drImpactIfPresent")}),O?c.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[c.jsx(vs,{className:"w-4 h-4 animate-spin"}),c.jsx("span",{children:h==="hi"?"प्रभाव विश्लेषण हो रहा है...":"Analyzing impact..."})]}):c.jsx("p",{className:"text-sm text-muted-foreground",children:_[b.type]?.text||b.impact})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("h4",{className:"font-semibold text-base",children:e("drPujaRecommendation")}),a?o?c.jsx("div",{className:"flex items-center justify-center py-6",children:c.jsx(vs,{className:"w-6 h-6 text-primary animate-spin",size:24})}):(()=>{const U=Vc(b.type,b.detailKey),J=U.map(se=>a(se)).find(Boolean);return!J&&typeof window<"u"&&console.warn(`[DoshaCalculator] renderPujaCard returned null/undefined for dosha type: ${b.type} (tried: ${U.join(", ")})`),J||c.jsx("p",{className:"text-sm text-muted-foreground italic",children:e("drNoPujaAvailable")})})():c.jsxs("p",{className:"text-sm text-muted-foreground italic",children:[e("drNoPujaAvailable"),typeof window<"u"&&(console.warn("[DoshaCalculator] renderPujaCard prop not provided. Pass renderPujaCard to show puja recommendations."),null)]})]}),b.benefits.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsx("h4",{className:"font-semibold text-base flex items-center gap-2",children:e("drHowPujaHelps")}),c.jsx("ul",{className:"text-sm text-muted-foreground space-y-3 ml-1",children:b.benefits.map((U,J)=>c.jsxs("li",{className:"flex items-start gap-3",children:[c.jsx("span",{className:"text-primary mt-1.5 flex-shrink-0",children:"•"}),c.jsx("span",{children:U})]},J))})]})]})]},b.type)}),te.length>0&&c.jsx("p",{className:"text-xs text-muted-foreground text-center italic px-4",children:e("drFomoLine")}),c.jsxs("div",{className:"mx-4 p-4 bg-muted/30 rounded-lg border border-border/50 text-center",children:[c.jsx("p",{className:"text-sm text-foreground/80 font-medium",children:e("drFeedbackContact")}),c.jsx("a",{href:`mailto:${i}`,className:"text-primary hover:underline font-semibold text-base mt-1 inline-block",children:i})]}),c.jsxs(ft,{className:"spiritual-glow mx-4",children:[c.jsxs(kt,{children:[c.jsx(St,{className:"text-2xl font-bold text-center gradient-spiritual bg-clip-text text-transparent",children:e("drDetailedAnalysis")}),c.jsx(Kr,{className:"text-center",children:e("drBasedOnChart")})]}),c.jsx(xt,{className:"space-y-4",children:c.jsx(hi,{type:"single",collapsible:!0,className:"w-full space-y-4",children:vi.map(b=>{const F=b.detailKey==="sadeSati"?"sadeSati":b.detailKey,z=b.summaryKey==="shaniSadeSati"?L:E[b.summaryKey],H=wi($,b.detailKey==="sadeSati"?"sadeSati":b.detailKey),V=E[b.severityKey],B=b.type==="shani"?E.shaniPhase:void 0,U=b.icon,me=(H?.remedies?.trim()||e(b.remediesKey)).split(`
158
+ `).map(le=>le.trim()).filter(Boolean);return c.jsxs(fi,{value:F,className:"border border-border rounded-lg px-4",children:[c.jsx(mi,{value:F,className:"hover:no-underline",children:c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(U,{className:"w-5 h-5 text-destructive"}),c.jsxs("div",{className:"text-left",children:[c.jsx("h3",{className:"font-semibold text-lg",children:e(b.nameKey)}),c.jsxs("p",{className:"text-sm text-muted-foreground",children:[e("drStatus"),": ",_i(z,e),V&&!Gr(z)&&` • ${e("drSeverity")}: ${Si(V,e)}`,b.type==="shani"&&B!=null&&` • ${e("drPhase")}: ${B}`]})]})]})}),c.jsxs(pi,{value:F,className:"pt-4 space-y-4",children:[c.jsx("p",{className:"text-sm text-muted-foreground italic",children:e(b.descKey)}),H?.explanation&&c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium mb-2",children:e("drExplanation")}),c.jsx("p",{className:"text-sm text-muted-foreground",children:H.explanation})]}),H?.placements&&H.placements.length>0&&c.jsxs("div",{className:"p-3 bg-accent/10 rounded-md",children:[c.jsx("h4",{className:"font-medium mb-2",children:e("drPlanetaryPositions")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:H.placements.map((le,Ee)=>c.jsx("li",{children:le},Ee))})]}),c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium mb-2",children:e("drTraditionalRemedies")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:me.map((le,Ee)=>c.jsx("li",{children:le},Ee))})]})]})]},F)})})})]}),c.jsxs(ft,{className:"mx-4",children:[c.jsx(kt,{className:"cursor-pointer hover:bg-accent/5 transition-colors",onClick:()=>tt(b=>!b),children:c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"text-left flex-1 min-w-0",children:[c.jsx(St,{className:"text-xl font-semibold",children:e("drOtherDoshas")}),c.jsx(Kr,{children:e(Oe?"drOtherDoshasStatusActive":"drOtherDoshasStatusNone")})]}),c.jsx(ei,{className:`h-5 w-5 flex-shrink-0 text-muted-foreground transition-transform duration-200 ${he?"rotate-180":""}`})]})}),he&&c.jsx(xt,{children:c.jsx(hi,{type:"single",collapsible:!0,className:"w-full space-y-2",children:$e.map(b=>{const F=E[b.summaryKey],z=qe(F),H=re[b.detailKey]??{},V=H.explanation,B=H.placements;return c.jsxs(fi,{value:b.summaryKey,className:"border border-border rounded-lg px-3",children:[c.jsx(mi,{value:b.summaryKey,className:"hover:no-underline py-3",children:c.jsxs("div",{className:"flex items-center justify-between gap-2 flex-1 min-w-0 mr-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"font-semibold text-sm text-left leading-tight",children:e(b.labelKey)}),c.jsx(Ur,{size:14,className:"text-muted-foreground flex-shrink-0"})]}),z?c.jsxs(Hr,{variant:"destructive",className:"flex-shrink-0 text-xs flex items-center gap-1 pointer-events-none",children:[c.jsx(bs,{size:10}),e("drStatusPresent")]}):c.jsxs(Hr,{variant:"secondary",className:"flex-shrink-0 text-xs flex items-center gap-1 bg-white border pointer-events-none",style:{borderColor:"#e4decd",color:"#000000"},children:[c.jsx(Zn,{size:10,color:"#000000"}),e("drStatusAbsent")]})]})}),c.jsxs(pi,{value:b.summaryKey,className:"space-y-3 pt-0 pb-3",children:[c.jsx("div",{className:"border-l-4 border-orange-500 bg-orange-50 rounded-lg pl-3 py-2",children:c.jsx("p",{className:"text-sm text-muted-foreground italic",children:e(b.descKey)})}),B&&B.length>0&&c.jsxs("div",{className:"p-3 bg-accent/10 rounded-md border border-accent/20",children:[c.jsxs("h5",{className:"font-medium mb-2 flex items-center gap-2 text-sm",children:[c.jsx(Ur,{size:14}),e("drPlanetaryPositions")]}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1 leading-relaxed",children:B.map((U,J)=>c.jsx("li",{children:U},J))})]}),V&&c.jsxs("div",{className:"border-l-4 border-orange-500 bg-orange-50 rounded-lg pl-3 py-2",children:[c.jsxs("h5",{className:"font-medium mb-2 text-sm flex items-center gap-2",children:[c.jsx(Ur,{size:14}),e(z?"drWhyPresent":"drWhyAbsent")]}),c.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:V})]}),z&&c.jsxs("div",{className:"border-l-4 border-red-500 bg-red-50 rounded-lg pl-3 py-2",children:[c.jsxs("h5",{className:"font-medium mb-2 text-sm flex items-center gap-2 text-red-600",children:[c.jsx(bs,{size:14}),e("drImpact")]}),c.jsx("p",{className:"text-sm text-muted-foreground",children:e(b.impactKey)})]}),z&&c.jsxs("div",{children:[c.jsx("h5",{className:"font-medium mb-2 text-sm",children:e("drTraditionalRemedies")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:e(b.remediesKey).split(`
159
+ `).map((U,J)=>c.jsx("li",{children:U},J))})]})]})]},b.summaryKey)})})})]}),c.jsx("div",{id:n||"kundali-chart-section",className:"px-4",children:(l||M||fe.length>0)&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"flex justify-end mb-2",children:c.jsxs("button",{type:"button",onClick:()=>document.getElementById("dosha-results-heading")?.scrollIntoView({behavior:"smooth",block:"start"}),className:"inline-flex items-center gap-1.5 text-sm text-primary hover:text-primary/80 transition-colors font-medium",children:[c.jsx(ac,{className:"w-4 h-4"}),e("drGoBack")]})}),l?c.jsxs("div",{className:"mt-2",children:[c.jsx("h2",{className:"text-xl font-semibold text-foreground mb-3",children:e("drYourKundali")}),l()]}):M&&u&&d?c.jsx("div",{className:"mt-2",children:c.jsx(bi,{birthDetails:u,supabase:d,language:h,t:e})}):null,fe.length>0&&c.jsxs(ft,{className:"mt-4 bg-accent/10 border border-accent/30",children:[c.jsx(kt,{className:"pb-2",children:c.jsx(St,{className:"text-base font-semibold",children:e("drPlanetaryPositionsCausing")})}),c.jsx(xt,{className:"pt-0",children:c.jsx("ul",{className:"space-y-3 text-sm text-muted-foreground",children:fe.map((b,F)=>c.jsxs("li",{children:[c.jsxs("div",{className:"font-semibold text-foreground mb-1",children:[b.label,":"]}),c.jsx("ul",{className:"ml-4 space-y-1",children:b.evidence.map((z,H)=>c.jsxs("li",{className:"flex items-start gap-2",children:[c.jsx("span",{className:"text-primary flex-shrink-0",children:"→"}),c.jsx("span",{children:z})]},H))})]},F))})})]})]})}),c.jsx("p",{className:"text-xs text-muted-foreground/70 text-center px-4",children:e("drDisclaimer")}),c.jsx(q.UserReviewsSection,{t:e,readMoreHref:p,onReadMore:g?.trackReadMoreReviewsClicked?()=>g.trackReadMoreReviewsClicked():void 0}),c.jsx(q.FAQAccordion,{t:e,items:zc,defaultOpenIndex:0}),c.jsx(q.ContactUsSection,{title:e("contactTitle"),brandName:e("contactBrandName"),whatsAppLine:e("contactWhatsAppDomestic"),emailLine:e("contactEmail")})]})}const Yc=Object.freeze(Object.defineProperty({__proto__:null,DoshaResultsFull:xi},Symbol.toStringTag,{value:"Module"}));function Qc(t){return!t||t.trim()===""?async()=>null:async e=>{try{if(!e?.trim())return null;const r=`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(e)}&key=${t}`,n=await(await fetch(r)).json();if(n.status!=="OK"||!n.results?.[0])return null;const{lat:i,lng:a}=n.results[0].geometry.location,o=Math.floor(Date.now()/1e3),l=`https://maps.googleapis.com/maps/api/timezone/json?location=${i},${a}&timestamp=${o}&key=${t}`,d=await(await fetch(l)).json();if(d.status!=="OK")return null;const h=d.timeZoneId,p=(d.rawOffset+d.dstOffset)/3600;return{lat:i,lon:a,tz:h,tzoneOffset:p}}catch{return null}}}G.DoshaCalculator=Mc,G.DoshaFormSection=ws,G.DoshaResultsFull=xi,G.DoshaResultsView=Kc,G.FLOATING_CTA_STATUS=pr,G.I18nProvider=ec,G.KundaliCard=bi,G.LOCALE_LABELS=Xl,G.SUPPORTED_LOCALES=Ql,G.SriMandirPujaVerticalCard=ai,G.createGoogleMapsResolver=Qc,G.createSupabaseClient=Un,G.fetchKundaliSvg=yi,G.formatScheduleDate=Vn,G.getCoverImageUrl=Jn,G.getPujaLink=gs,G.getPujaTitle=ps,G.getTempleName=zn,G.insertSessionProblemStatements=ri,G.invokeCalculateDosha=si,G.submitDoshaCalculation=ni,G.translations=Yn,G.useGooglePlacesAutocomplete=ii,G.useI18n=ys,Object.defineProperty(G,Symbol.toStringTag,{value:"Module"})}));
175
160
  //# sourceMappingURL=dosha-calculator.umd.cjs.map