@srimandir/dosha-calculator 3.30.13 → 3.30.14

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,30 +1,30 @@
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 ea(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 Re=ea(v);var lr={exports:{}},Mt={};var fs;function ta(){if(fs)return Mt;fs=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 Mt.Fragment=r,Mt.jsx=i,Mt.jsxs=i,Mt}var Bt={};var ms;function ra(){return ms||(ms=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 T(f){if(f===null||typeof f!="object")return null;var w=g&&f[g]||f[b];return typeof w=="function"?w:null}var k=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function S(f){{for(var w=arguments.length,x=new Array(w>1?w-1:0),D=1;D<w;D++)x[D-1]=arguments[D];_("error",f,x)}}function _(f,w,x){{var D=k.ReactDebugCurrentFrame,Y=D.getStackAddendum();Y!==""&&(w+="%s",x=x.concat([Y]));var X=x.map(function(H){return String(H)});X.unshift("Warning: "+w),Function.prototype.apply.call(console[f],console,X)}}var R=!1,O=!1,B=!1,E=!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||E||f===p||R||O||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,w,x){var D=f.displayName;if(D)return D;var Y=w.displayName||w.name||"";return Y!==""?x+"("+Y+")":x}function Pe(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 w=f;return Pe(w)+".Consumer";case i:var x=f;return Pe(x._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,Qe,Oe,re,fe,ke,Q,y;function K(){}K.__reactDisabledLog=!0;function z(){{if(he===0){Qe=console.log,Oe=console.info,re=console.warn,fe=console.error,ke=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:Qe}),info:te({},f,{value:Oe}),warn:te({},f,{value:re}),error:te({},f,{value:fe}),group:te({},f,{value:ke}),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=k.ReactCurrentDispatcher,M;function L(f,w,x){{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,w){if(!f||J)return"";{var x=se.get(f);if(x!==void 0)return x}var D;J=!0;var Y=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var X;X=V.current,V.current=null,z();try{if(w){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
- `),Ae=D.stack.split(`
4
- `),ue=F.length-1,pe=Ae.length-1;ue>=1&&pe>=0&&F[ue]!==Ae[pe];)pe--;for(;ue>=1&&pe>=0;ue--,pe--)if(F[ue]!==Ae[pe]){if(ue!==1||pe!==1)do if(ue--,pe--,pe<0||F[ue]!==Ae[pe]){var He=`
5
- `+F[ue].replace(" at new "," at ");return f.displayName&&He.includes("<anonymous>")&&(He=He.replace("<anonymous>",f.displayName)),typeof f=="function"&&se.set(f,He),He}while(ue>=1&&pe>=0);break}}}finally{J=!1,V.current=X,W(),Error.prepareStackTrace=Y}var Ut=f?f.displayName||f.name:"",wt=Ut?L(Ut):"";return typeof f=="function"&&se.set(f,wt),wt}function Te(f,w,x){return le(f,!1)}function Lt(f){var w=f.prototype;return!!(w&&w.isReactComponent)}function Fe(f,w,x){if(f==null)return"";if(typeof f=="function")return le(f,Lt(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 Te(f.render);case h:return Fe(f.type,w,x);case m:{var D=f,Y=D._payload,X=D._init;try{return Fe(X(Y),w,x)}catch{}}}return""}var $e=Object.prototype.hasOwnProperty,bt={},vt=k.ReactDebugCurrentFrame;function rt(f){if(f){var w=f._owner,x=Fe(f.type,f._source,w?w.type:null);vt.setExtraStackFrame(x)}else vt.setExtraStackFrame(null)}function rr(f,w,x,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 Ae=Error((D||"React class")+": "+x+" 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 Ae.name="Invariant Violation",Ae}F=f[H](w,H,D,x,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(ue){F=ue}F&&!(F instanceof Error)&&(rt(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",x,H,typeof F),rt(null)),F instanceof Error&&!(F.message in bt)&&(bt[F.message]=!0,rt(Y),S("Failed %s type: %s",x,F.message),rt(null))}}}var j=Array.isArray;function I(f){return j(f)}function ie(f){{var w=typeof Symbol=="function"&&Symbol.toStringTag,x=w&&f[Symbol.toStringTag]||f.constructor.name||"Object";return x}}function ze(f){try{return lt(f),!1}catch{return!0}}function lt(f){return""+f}function _e(f){if(ze(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)),lt(f)}var ce=k.ReactCurrentOwner,je={key:!0,ref:!0,__self:!0,__source:!0},qe,Le;function sr(f){if($e.call(f,"ref")){var w=Object.getOwnPropertyDescriptor(f,"ref").get;if(w&&w.isReactWarning)return!1}return f.ref!==void 0}function C(f){if($e.call(f,"key")){var w=Object.getOwnPropertyDescriptor(f,"key").get;if(w&&w.isReactWarning)return!1}return f.key!==void 0}function ne(f,w){typeof f.ref=="string"&&ce.current}function Se(f,w){{var x=function(){qe||(qe=!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)",w))};x.isReactWarning=!0,Object.defineProperty(f,"key",{get:x,configurable:!0})}}function xe(f,w){{var x=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)",w))};x.isReactWarning=!0,Object.defineProperty(f,"ref",{get:x,configurable:!0})}}var ye=function(f,w,x,D,Y,X,H){var F={$$typeof:e,type:f,key:w,ref:x,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 nr(f,w,x,D,Y){{var X,H={},F=null,Ae=null;x!==void 0&&(_e(x),F=""+x),C(w)&&(_e(w.key),F=""+w.key),sr(w)&&(Ae=w.ref,ne(w,Y));for(X in w)$e.call(w,X)&&!je.hasOwnProperty(X)&&(H[X]=w[X]);if(f&&f.defaultProps){var ue=f.defaultProps;for(X in ue)H[X]===void 0&&(H[X]=ue[X])}if(F||Ae){var pe=typeof f=="function"?f.displayName||f.name||"Unknown":f;F&&Se(H,pe),Ae&&xe(H,pe)}return ye(f,F,Ae,Y,D,ce.current,H)}}var ar=k.ReactCurrentOwner,Dr=k.ReactDebugCurrentFrame;function ct(f){if(f){var w=f._owner,x=Fe(f.type,f._source,w?w.type:null);Dr.setExtraStackFrame(x)}else Dr.setExtraStackFrame(null)}var ir;ir=!1;function $r(f){return typeof f=="object"&&f!==null&&f.$$typeof===e}function Lr(){{if(ar.current){var f=ee(ar.current.type);if(f)return`
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`
6
6
 
7
- Check the render method of \``+f+"`."}return""}}function ic(f){return""}var Vn={};function oc(f){{var w=Lr();if(!w){var x=typeof f=="string"?f:f.displayName||f.name;x&&(w=`
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&&(_=`
8
8
 
9
- Check the top-level render call using <`+x+">.")}return w}}function Jn(f,w){{if(!f._store||f._store.validated||f.key!=null)return;f._store.validated=!0;var x=oc(w);if(Vn[x])return;Vn[x]=!0;var D="";f&&f._owner&&f._owner!==ar.current&&(D=" It was passed a child from "+ee(f._owner.type)+"."),ct(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.',x,D),ct(null)}}function Yn(f,w){{if(typeof f!="object")return;if(I(f))for(var x=0;x<f.length;x++){var D=f[x];$r(D)&&Jn(D,w)}else if($r(f))f._store&&(f._store.validated=!0);else if(f){var Y=T(f);if(typeof Y=="function"&&Y!==f.entries)for(var X=Y.call(f),H;!(H=X.next()).done;)$r(H.value)&&Jn(H.value,w)}}}function lc(f){{var w=f.type;if(w==null||typeof w=="string")return;var x;if(typeof w=="function")x=w.propTypes;else if(typeof w=="object"&&(w.$$typeof===l||w.$$typeof===h))x=w.propTypes;else return;if(x){var D=ee(w);rr(x,f.props,"prop",D,f)}else if(w.PropTypes!==void 0&&!ir){ir=!0;var Y=ee(w);S("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",Y||"Unknown")}typeof w.getDefaultProps=="function"&&!w.getDefaultProps.isReactClassApproved&&S("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function cc(f){{for(var w=Object.keys(f.props),x=0;x<w.length;x++){var D=w[x];if(D!=="children"&&D!=="key"){ct(f),S("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",D),ct(null);break}}f.ref!==null&&(ct(f),S("Invalid attribute `ref` supplied to `React.Fragment`."),ct(null))}}var Qn={};function Xn(f,w,x,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 Ae=ic();Ae?F+=Ae:F+=Lr();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=nr(f,w,x,Y,X);if(pe==null)return pe;if(H){var He=w.children;if(He!==void 0)if(D)if(I(He)){for(var Ut=0;Ut<He.length;Ut++)Yn(He[Ut],f);Object.freeze&&Object.freeze(He)}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 Yn(He,f)}if($e.call(w,"key")){var wt=ee(f),Ce=Object.keys(w).filter(function(pc){return pc!=="key"}),hs=Ce.length>0?"{key: someKey, "+Ce.join(": ..., ")+": ...}":"{key: someKey}";if(!Qn[wt+hs]){var mc=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 <`+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:
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} />`,hs,wt,mc,wt),Qn[wt+hs]=!0}}return f===s?cc(pe):lc(pe),pe}}function uc(f,w,x){return Xn(f,w,x,!0)}function dc(f,w,x){return Xn(f,w,x,!1)}var hc=dc,fc=uc;Bt.Fragment=s,Bt.jsx=hc,Bt.jsxs=fc})()),Bt}var ps;function sa(){return ps||(ps=1,process.env.NODE_ENV==="production"?lr.exports=ta():lr.exports=ra()),lr.exports}var c=sa();const cr={all_fields_filled:"all_fields_filled",fields_not_filled:"fields_not_filled",puja_clicked:"puja_clicked"};function ur(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 na(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 aa=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class Ur 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 ia extends Ur{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class gs extends Ur{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class ys extends Ur{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Mr;(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"})(Mr||(Mr={}));class oa{constructor(e,{headers:r={},customFetch:s,region:n=Mr.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=aa(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return na(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 T=d;h&&(i=new AbortController,a=setTimeout(()=>i.abort(),h),d?(T=i.signal,d.addEventListener("abort",()=>i.abort())):T=i.signal);const k=yield this.fetch(g.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},m),this.headers),o),body:b,signal:T}).catch(O=>{throw new ia(O)}),S=k.headers.get("x-relay-error");if(S&&S==="true")throw new gs(k);if(!k.ok)throw new ys(k);let _=((n=k.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),R;return _==="application/json"?R=yield k.json():_==="application/octet-stream"||_==="application/pdf"?R=yield k.blob():_==="text/event-stream"?R=k:_==="multipart/form-data"?R=yield k.formData():R=yield k.text(),{data:R,error:null,response:k}}catch(o){return{data:null,error:o,response:o instanceof ys||o instanceof gs?o.context:void 0}}finally{a&&clearTimeout(a)}})}}const bs=3,vs=t=>Math.min(1e3*2**t,3e4),la=[520,503],ws=["GET","HEAD","OPTIONS"];var ca=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 _s(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 ua(t,e,r,s){return!(!s||r>=bs||!ws.includes(t)||!la.includes(e))}var da=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"||!ws.includes(r.method))throw h;if(r.retryEnabled&&i<bs){const m=vs(i);i++,await _s(m,r.signal);continue}throw h}if(ua(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:vs(i);await d.text(),i++,await _s(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:"",_=(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} />`,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+=`
15
15
 
16
- Caused by: ${(b=h?.name)!==null&&b!==void 0?b:"Error"}: ${S}`,_&&(l+=` (${_})`),h?.stack&&(l+=`
17
- ${h.stack}`)}else{var T;l=(T=i?.stack)!==null&&T!==void 0?T:""}const k=this.url.toString().length;return i?.name==="AbortError"||i?.code==="ABORT_ERR"?(d="",u="Request was aborted (timeout or manual cancellation)",k>this.urlLengthLimit&&(u+=`. Note: Your request URL is ${k} 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)",k>this.urlLengthLimit&&(u+=`. Your request URL is ${k} 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 ca(r)}return{success:r===null,error:r,data:s,count:n,status:a,statusText:i}}returns(){return this}overrideTypes(){return this}},ha=class extends da{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 ks=new RegExp("[,()]");var _t=class extends ha{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"&&ks.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"&&ks.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}},fa=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 _t({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 _t({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 _t({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 _t({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 _t({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 Kt(t){"@babel/helpers - typeof";return Kt=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},Kt(t)}function ma(t,e){if(Kt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(Kt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function pa(t){var e=ma(t,"string");return Kt(e)=="symbol"?e:e+""}function ga(t,e,r){return(e=pa(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Ss(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 dr(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Ss(Object(r),!0).forEach(function(s){ga(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Ss(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var ya=class Zn{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,dr(dr({},d),{},{signal:h.signal})).finally(()=>{clearTimeout(m),p.removeEventListener("abort",g)})}return l(u,dr(dr({},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 fa(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 Zn(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 _t({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 ba{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:
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
18
  import ws from "ws"
19
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+=`
20
20
 
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 va="realtime-js/2.104.0",wa="1.0.0",xs="2.0.0",_a=xs,ka=1e4,Sa=100,st={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Ts={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},Br={connecting:"connecting",closing:"closing",closed:"closed"};class xa{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,k=>g.setUint8(b++,k.charCodeAt(0))),Array.from(o,k=>g.setUint8(b++,k.charCodeAt(0))),Array.from(i,k=>g.setUint8(b++,k.charCodeAt(0))),Array.from(u,k=>g.setUint8(b++,k.charCodeAt(0))),Array.from(h,k=>g.setUint8(b++,k.charCodeAt(0)));var T=new Uint8Array(p.byteLength+s.byteLength);return T.set(new Uint8Array(p),0),T.set(new Uint8Array(s),p.byteLength),T.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 js=(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]=Ta(i,t,e,n),a),{}):{}},Ta=(t,e,r,s)=>{const n=e.find(o=>o.name===t),a=n?.type,i=r[t];return a&&!s.includes(a)?As(a,i):Kr(i)},As=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return Pa(e,r)}switch(t){case Z.bool:return ja(e);case Z.float4:case Z.float8:case Z.int2:case Z.int4:case Z.int8:case Z.numeric:case Z.oid:return Aa(e);case Z.json:case Z.jsonb:return Ea(e);case Z.timestamp:return Oa(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 Kr(e);default:return Kr(e)}},Kr=t=>t,ja=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},Aa=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},Ea=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Pa=(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=>As(e,o))}return t},Oa=t=>typeof t=="string"?t.replace(" ","T"):t,Es=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 Ft=t=>typeof t=="function"?t:function(){return t},Ca=typeof self<"u"?self:null,kt=typeof window<"u"?window:null,Ve=Ca||kt||globalThis,Ra="2.0.0",Na=1e4,Ia=1e3,Je={connecting:0,open:1,closing:2,closed:3},Ee={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Xe={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Fr={longpoll:"longpoll",websocket:"websocket"},Da={complete:4},qr="base64url.bearer.phx.",hr=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})}},Ps=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))}},$a=class{constructor(t,e,r){this.state=Ee.closed,this.topic=t,this.params=Ft(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new hr(this,Xe.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Ps(()=>{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=Ee.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",s=>{this.state=Ee.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=Ee.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=Ee.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 hr(this,Xe.leave,Ft({}),this.timeout).send(),this.state=Ee.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(Xe.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=Ee.closed,this.bindings=[]}onClose(t){this.on(Xe.close,t)}onError(t){return this.on(Xe.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 hr(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=Ee.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Xe.close,"leave")},r=new hr(this,Xe.leave,Ft({}),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=Ee.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===Ee.closed}isErrored(){return this.state===Ee.errored}isJoined(){return this.state===Ee.joined}isJoining(){return this.state===Ee.joining}isLeaving(){return this.state===Ee.leaving}},fr=class{static request(t,e,r,s,n,a,i){if(Ve.XDomainRequest){let o=new Ve.XDomainRequest;return this.xdomainRequest(o,t,e,s,n,a,i)}else if(Ve.XMLHttpRequest){let o=new Ve.XMLHttpRequest;return this.xhrRequest(o,t,e,r,s,n,a,i)}else{if(Ve.fetch&&Ve.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),Ve.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===Da.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)}`}},La=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)},St=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(qr)&&(this.authToken=atob(e[1].slice(qr.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=Je.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Fr.websocket),"$1/"+Fr.longpoll)}endpointURL(){return fr.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=Je.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Je.open||this.readyState===Je.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=Je.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=La(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=Je.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=fr.request(t,this.endpointURL(),e,r,this.timeout,i,o=>{this.reqs.delete(a),this.isActive()&&n(o)}),this.reqs.add(a)}},Ua=class or{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=or.syncState(this.state,n,a,i),this.pendingDiffs.forEach(l=>{this.state=or.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=or.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 or.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))}},mr={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:Xe.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}}},Ma=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Na,this.transport=e.transport||Ve.WebSocket||St,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||Ve&&Ve.sessionStorage,this.establishedConnections=0,this.defaultEncoder=mr.encode.bind(mr),this.defaultDecoder=mr.decode.bind(mr),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!==St?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;kt&&kt.addEventListener&&(kt.addEventListener("pagehide",s=>{this.conn&&(this.disconnect(),r=this.connectClock)}),kt.addEventListener("pageshow",s=>{r===this.connectClock&&(r=null,this.connect())}),kt.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=Ft(e.params||{}),this.endPoint=`${t}/${Fr.websocket}`,this.vsn=e.vsn||Ra,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Ps(()=>{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 St}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=fr.appendParams(fr.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=Ft(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==St?this.connectWithFallback(St,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===St?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${qr}${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(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Ia,"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===Je.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(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(Xe.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case Je.connecting:return"connecting";case Je.open:return"open";case Je.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 $a(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 qt{constructor(e,r){const s=Ka(r);this.presence=new Ua(e.getChannel(),s),this.presence.onJoin((n,a,i)=>{const o=qt.onJoinPayload(n,a,i);e.getChannel().trigger("presence",o)}),this.presence.onLeave((n,a,i)=>{const o=qt.onLeavePayload(n,a,i);e.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return qt.transformState(this.presence.state)}static transformState(e){return e=Ba(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{const n=e[s];return r[s]=pr(n),r},{})}static onJoinPayload(e,r,s){const n=Os(r),a=pr(s);return{event:"join",key:e,currentPresences:n,newPresences:a}}static onLeavePayload(e,r,s){const n=Os(r),a=pr(s);return{event:"leave",key:e,currentPresences:n,leftPresences:a}}}function pr(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function Ba(t){return JSON.parse(JSON.stringify(t))}function Ka(t){return t?.events&&{events:t.events}}function Os(t){return t?.metas?pr(t):[]}var Cs;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Cs||(Cs={}));class Fa{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new qt(this.channel.channelAdapter,r)}}class qa{constructor(e,r,s){const n=Ha(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>Sa){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===st.joined}isJoined(){return this.state===st.joined}isJoining(){return this.state===st.joining}isClosed(){return this.state===st.closed}isLeaving(){return this.state===st.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function Ha(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var Rs;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Rs||(Rs={}));var xt;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(xt||(xt={}));var Ze;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Ze||(Ze={}));class Ht{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 qa(this.socket.socketAdapter,e,this.params),this.presence=new Fa(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Es(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[xt.PRESENCE]&&this.bindings[xt.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?.(Ze.CHANNEL_ERROR,p)}),this._onClose(()=>e?.(Ze.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?.(Ze.SUBSCRIBED);return}this._updatePostgresBindings(p,e)}).receive("error",p=>{this.state=st.errored,e?.(Ze.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(p).join(", ")||"error")))}).receive("timeout",()=>{e?.(Ze.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&&Ht.isFilterValueEqual(p.schema,d)&&Ht.isFilterValueEqual(p.table,h)&&Ht.isFilterValueEqual(p.filter,m))i.push(Object.assign(Object.assign({},l),{id:p.id}));else{this.unsubscribe(),this.state=st.errored,r?.(Ze.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=i,this.state!=st.errored&&r&&r(Ze.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===xt.PRESENCE||e===xt.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}=Ts;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=js(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=js(e.columns,e.old_record)),r}}class Wa{constructor(e,r){this.socket=new Ma(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()==Br.connecting}isDisconnecting(){return this.socket.connectionState()==Br.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const Ga={HEARTBEAT_INTERVAL:25e3},za=[1e3,2e3,5e3,1e4],Va=1e4,Ja=`
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=`
23
23
  addEventListener("message", (e) => {
24
24
  if (e.data.event === "start") {
25
25
  setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
26
26
  }
27
- });`;class Ya{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 xa,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,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 Wa(e,n),this.httpEndpoint=Es(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}
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}
28
28
 
29
29
  To use Realtime in Node.js, you need to provide a WebSocket implementation:
30
30
 
@@ -37,26 +37,26 @@ Option 2: Install and provide the "ws" package:
37
37
  const client = new RealtimeClient(url, {
38
38
  ...options,
39
39
  transport: ws
40
- })`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return 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(),this.channels.length===0&&this.disconnect(),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 this.disconnect(),r}log(e,r,s){this.socketAdapter.log(e,r,s)}connectionState(){return this.socketAdapter.connectionState()||Br.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 Ht(`realtime:${e}`,r,this);return 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)}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:va};r&&n.updateJoinPayload(a),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(Ts.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([Ja],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_initializeOptions(e){var r,s,n,a,i,o,l,u,d;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(s=e?.accessToken)!==null&&s!==void 0?s:null;const h={};h.timeout=(n=e?.timeout)!==null&&n!==void 0?n:ka,h.heartbeatIntervalMs=(a=e?.heartbeatIntervalMs)!==null&&a!==void 0?a:Ga.HEARTBEAT_INTERVAL,h.transport=(i=e?.transport)!==null&&i!==void 0?i:ba.getWebSocketConstructor(),h.params=e?.params,h.logger=e?.logger,h.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),h.reconnectAfterMs=(o=e?.reconnectAfterMs)!==null&&o!==void 0?o:(b=>za[b-1]||Va);let m,p;const g=(l=e?.vsn)!==null&&l!==void 0?l:_a;switch(g){case wa:m=(b,T)=>T(JSON.stringify(b)),p=(b,T)=>T(JSON.parse(b));break;case xs:m=this.serializer.encode.bind(this.serializer),p=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${h.vsn}`)}if(h.vsn=g,h.encode=(u=e?.encode)!==null&&u!==void 0?u:m,h.decode=(d=e?.decode)!==null&&d!==void 0?d:p,h.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,h.params=Object.assign(Object.assign({},h.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,h.autoSendHeartbeat=!this.worker}return h}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var Wt=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 Qa(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 Xa(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 Za(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:a,headers:i}){const o=Qa(t.baseUrl,s,n),l=await Xa(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 Wt(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 gr(t){return t.join("")}var ei=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:gr(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/${gr(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${gr(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${gr(t.namespace)}`}),!0}catch(e){if(e instanceof Wt&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof Wt&&r.status===409)return;throw r}}};function Tt(t){return t.join("")}var ti=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/${Tt(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/${Tt(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/${Tt(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/${Tt(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/${Tt(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/${Tt(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof Wt&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof Wt&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},ri=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Za({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new ei(this.client,e),this.tableOps=new ti(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 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 si(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 ni(t){var e=si(t,"string");return Gt(e)=="symbol"?e:e+""}function ai(t,e,r){return(e=ni(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 N(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){ai(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}var yr=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 br(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var Hr=class extends yr{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 N({},super.toJSON())}},Is=class extends yr{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};function Wr(t,e,r){const s=N({},t),n=e.toLowerCase();for(const a of Object.keys(s))a.toLowerCase()===n&&delete s[a];return s[n]=r,s}function ii(t){const e={};for(const[r,s]of Object.entries(t))e[r.toLowerCase()]=s;return e}const oi=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),li=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)},Gr=t=>{if(Array.isArray(t))return t.map(r=>Gr(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]=Gr(s)}),e},ci=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),Ds=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)},ui=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 Hr(Ds(i),a,o,s))}).catch(()=>{const i=a+"";e(new Hr(n.statusText||`HTTP ${a} error`,a,i,s))})}else e(new Is(Ds(t),t,s))},di=(t,e,r,s)=>{const n={method:t,headers:e?.headers||{}};if(t==="GET"||t==="HEAD"||!s)return N(N({},n),r);if(li(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),N(N({},n),r)};async function zt(t,e,r,s,n,a,i){return new Promise((o,l)=>{t(r,di(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=>ui(u,l,s,i))})}function $s(t="storage"){return{get:async(e,r,s,n)=>zt(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,a)=>zt(e,"POST",r,n,a,s,t),put:async(e,r,s,n,a)=>zt(e,"PUT",r,n,a,s,t),head:async(e,r,s,n)=>zt(e,"HEAD",r,N(N({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,a)=>zt(e,"DELETE",r,n,a,s,t)}}const hi=$s("storage"),{get:Vt,post:We,put:zr,head:fi,remove:Vr}=hi,Ne=$s("vectors");var jt=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=ii(e),this.fetch=oi(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(br(r))return{data:null,error:r};throw r}}},mi=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(br(e))return{data:null,error:e};throw e}}};let Ls;Ls=Symbol.toStringTag;var pi=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Ls]="BlobDownloadBuilder",this.promise=null}asStream(){return new mi(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(br(e))return{data:null,error:e};throw e}}};const gi={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Us={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var yi=class extends jt{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=N(N({},Us),s);let o=N(N({},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"?zr:We)(n.fetch,`${n.url}/object/${d}`,a,N({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=N(N({},Us),s),d=N(N({},n.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",u.cacheControl)):(l=r,d["cache-control"]=`max-age=${u.cacheControl}`,d["content-type"]=u.contentType),{path:a,fullPath:(await zr(n.fetch,o.toString(),l,{headers:d})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t);const n=N({},r.headers);e?.upsert&&(n["x-upsert"]="true");const a=await We(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 yr("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 We(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 We(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 We(s.fetch,`${s.url}/object/sign/${n}`,N({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 We(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=>N(N({},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=()=>Vt(this.fetch,`${this.url}/${s}/${i}${a?`?${a}`:""}`,{headers:this.headers,noResolveJson:!0},r);return new pi(o,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>Gr(await Vt(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await fi(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(br(n)){var s;const a=n instanceof Hr?n.status:n instanceof Is?(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 Vr(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=N(N(N({},gi),e),{},{prefix:t||""});return await We(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=N({},t);return await We(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 Jt={"X-Client-Info":"storage-js/2.104.0"};var bi=class extends jt{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=N(N({},Jt),e);super(a,i,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await Vt(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Vt(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await We(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 zr(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 We(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Vr(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():""}},vi=class extends jt{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=N(N({},Jt),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await We(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 Vt(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Vr(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!ci(t))throw new yr("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 ri({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}}}}})}},wi=class extends jt{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=N(N({},Jt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await Ne.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await Ne.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},_i=class extends jt{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=N(N({},Jt),{},{"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 Ne.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await Ne.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 Ne.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await Ne.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 Ne.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},ki=class extends jt{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=N(N({},Jt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Si=class extends ki{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new xi(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)}},xi=class extends wi{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,N(N({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,N(N({},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 Ti(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Ti=class extends _i{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,N(N({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,N(N({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,N(N({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,N(N({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,N(N({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},ji=class extends bi{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new yi(this.url,this.headers,t,this.fetch)}get vectors(){return new Si(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new vi(this.url+"/iceberg",this.headers,this.fetch)}};const Ms="2.104.0",At=30*1e3,Jr=3,Yr=Jr*At,Ai="http://localhost:9999",Ei="supabase.auth.token",Pi={"X-Client-Info":`gotrue-js/${Ms}`},Qr="X-Supabase-Api-Version",Bs={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Oi=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Ci=600*1e3;class Yt 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 A(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class Ri extends Yt{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}}function Ni(t){return A(t)&&t.name==="AuthApiError"}class ut extends Yt{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class et extends Yt{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}}class Ie extends et{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function vr(t){return A(t)&&t.name==="AuthSessionMissingError"}class Et extends et{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class wr extends et{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class _r 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 Ii(t){return A(t)&&t.name==="AuthImplicitGrantRedirectError"}class Ks 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 Di 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 Xr extends et{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function Zr(t){return A(t)&&t.name==="AuthRetryableFetchError"}class Fs 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 es extends et{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const kr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),qs=`
41
- \r=`.split(""),$i=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<qs.length;e+=1)t[qs[e].charCodeAt(0)]=-2;for(let e=0;e<kr.length;e+=1)t[kr[e].charCodeAt(0)]=e;return t})();function Hs(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(kr[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(kr[s]),e.queuedBits-=6}}function Ws(t,e,r){const s=$i[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 Gs(t){const e=[],r=i=>{e.push(String.fromCodePoint(i))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},a=i=>{Mi(i,s,r)};for(let i=0;i<t.length;i+=1)Ws(t.charCodeAt(i),n,a);return e.join("")}function Li(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 Ui(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}Li(s,e)}}function Mi(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 Pt(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)Ws(t.charCodeAt(n),r,s);return new Uint8Array(e)}function Bi(t){const e=[];return Ui(t,r=>e.push(r)),new Uint8Array(e)}function dt(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>Hs(n,r,s)),Hs(null,r,s),e.join("")}function Ki(t){return Math.round(Date.now()/1e3)+t}function Fi(){return Symbol("auth-callback")}const ve=()=>typeof window<"u"&&typeof document<"u",ht={tested:!1,writable:!1},zs=()=>{if(!ve())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ht.tested)return ht.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),ht.tested=!0,ht.writable=!0}catch{ht.tested=!0,ht.writable=!1}return ht.writable};function qi(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 Vs=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Hi=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Ot=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},ft=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},we=async(t,e)=>{await t.removeItem(e)};class Sr{constructor(){this.promise=new Sr.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}Sr.promiseConstructor=Promise;function xr(t){const e=t.split(".");if(e.length!==3)throw new es("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!Oi.test(e[s]))throw new es("JWT not in base64url format");return{header:JSON.parse(Gs(e[0])),payload:JSON.parse(Gs(e[1])),signature:Pt(e[2]),raw:{header:e[0],payload:e[1]}}}async function Wi(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Gi(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 zi(t){return("0"+t.toString(16)).substr(-2)}function Vi(){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,zi).join("")}async function Ji(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 Yi(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 Ji(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ct(t,e,r=!1){const s=Vi();let n=s;r&&(n+="/PASSWORD_RECOVERY"),await Ot(t,`${e}-code-verifier`,n);const a=await Yi(s);return[a,s===a?"plain":"s256"]}const Qi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Xi(t){const e=t.headers.get(Qr);if(!e||!e.match(Qi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Zi(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 eo(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 to=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Rt(t){if(!to.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function ts(){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 ro(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 Js(t){return JSON.parse(JSON.stringify(t))}const mt=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),so=[502,503,504,520,521,522,523,524,530];async function Ys(t){var e;if(!Hi(t))throw new Xr(mt(t),0);if(so.includes(t.status))throw new Xr(mt(t),t.status);let r;try{r=await t.json()}catch(a){throw new ut(mt(a),a)}let s;const n=Xi(t);if(n&&n.getTime()>=Bs["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 Fs(mt(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new Ie}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 Fs(mt(r),t.status,r.weak_password.reasons);throw new Ri(mt(r),t.status||500,s)}const no=(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 a=Object.assign({},s?.headers);a[Qr]||(a[Qr]=Bs["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 ao(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 ao(t,e,r,s,n,a){const i=no(e,s,n,a);let o;try{o=await t(r,Object.assign({},i))}catch(l){throw console.error(l),new Xr(mt(l),0)}if(o.ok||await Ys(o),s?.noResolveJson)return o;try{return await o.json()}catch(l){await Ys(l)}}function Ge(t){var e;let r=null;lo(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Ki(t.expires_in)));const s=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:s},error:null}}function Qs(t){const e=Ge(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 nt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function io(t){return{data:t,error:null}}function oo(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:a}=t,i=ur(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 Xs(t){return t}function lo(t){return t.access_token&&t.refresh_token&&t.expires_in}const rs=["global","local","others"];class co{constructor({url:e="",headers:r={},fetch:s}){this.url=e,this.headers=r,this.fetch=Vs(s),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)}}async signOut(e,r=rs[0]){if(rs.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${rs.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(A(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:nt})}catch(s){if(A(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:r}=e,s=ur(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:oo,redirectTo:r?.redirectTo})}catch(r){if(A(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:nt})}catch(r){if(A(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 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:(a=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&a!==void 0?a:""},xform:Xs});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)),T=JSON.parse(g.split(";")[1].split("=")[1]);u[`${T}Page`]=b}),u.total=parseInt(m)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(A(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Rt(e);try{return await P(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:nt})}catch(r){if(A(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Rt(e);try{return await P(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:nt})}catch(s){if(A(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){Rt(e);try{return await P(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:nt})}catch(s){if(A(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){Rt(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(A(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Rt(e.userId),Rt(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(A(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 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:(a=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&a!==void 0?a:""},xform:Xs});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)),T=JSON.parse(g.split(";")[1].split("=")[1]);u[`${T}Page`]=b}),u.total=parseInt(m)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(A(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(A(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(A(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(A(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(A(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(A(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(A(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(A(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(A(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(A(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(A(r))return{data:null,error:r};throw r}}}function Zs(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}const Ye={debug:!!(globalThis&&zs()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class en extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class tn extends en{}async function uo(t,e,r){Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const s=new globalThis.AbortController;let n;e>0&&(n=setTimeout(()=>{s.abort(),Ye.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),Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,a.name);try{return await r()}finally{Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,a.name)}}else{if(e===0)throw Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new tn(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(Ye.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 Ye.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){Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,i.name);try{return await r()}finally{Ye.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 Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new tn(`Lock "${t}" was released because another request stole it`)}throw a}}function ho(){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 rn(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function fo(t){return parseInt(t,16)}function mo(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function po(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=rn(t.address),g=d?`${d}://${s}`:s,b=t.statement?`${t.statement}
43
- `:"",T=`${g} wants you to sign in with your Ethereum account:
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
44
  ${p}
45
45
 
46
- ${b}`;let k=`URI: ${h}
46
+ ${b}`;let w=`URI: ${h}
47
47
  Version: ${m}
48
48
  Chain ID: ${r}${i?`
49
49
  Nonce: ${i}`:""}
50
- Issued At: ${a.toISOString()}`;if(n&&(k+=`
51
- Expiration Time: ${n.toISOString()}`),o&&(k+=`
52
- Not Before: ${o.toISOString()}`),l&&(k+=`
50
+ Issued At: ${a.toISOString()}`;if(n&&(w+=`
51
+ Expiration Time: ${n.toISOString()}`),o&&(w+=`
52
+ Not Before: ${o.toISOString()}`),l&&(w+=`
53
53
  Request ID: ${l}`),u){let S=`
54
- Resources:`;for(const _ of u){if(!_||typeof _!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${_}`);S+=`
55
- - ${_}`}k+=S}return`${T}
56
- ${k}`}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 Tr extends de{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function go({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(sn(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 yo({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(sn(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 bo{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 vo=new bo;function wo(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=ur(t,["challenge","user","excludeCredentials"]),a=Pt(e).buffer,i=Object.assign(Object.assign({},r),{id:Pt(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:Pt(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return o}function _o(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=ur(t,["challenge","allowCredentials"]),n=Pt(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:Pt(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return a}function ko(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:dt(new Uint8Array(t.response.attestationObject)),clientDataJSON:dt(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function So(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:dt(new Uint8Array(n.authenticatorData)),clientDataJSON:dt(new Uint8Array(n.clientDataJSON)),signature:dt(new Uint8Array(n.signature)),userHandle:n.userHandle?dt(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function sn(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function nn(){var t,e;return!!(ve()&&"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 xo(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Tr("Browser returned unexpected credential type",e)}:{data:null,error:new Tr("Empty credential response",e)}}catch(e){return{data:null,error:go({error:e,options:t})}}}async function To(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Tr("Browser returned unexpected credential type",e)}:{data:null,error:new Tr("Empty credential response",e)}}catch(e){return{data:null,error:yo({error:e,options:t})}}}const jo={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Ao={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function jr(...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]=jr(o,i):s[a]=jr(i)}else s[a]=i}return s}function Eo(t,e){return jr(jo,t,e||{})}function Po(t,e){return jr(Ao,t,e||{})}class Oo{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??vo.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=Eo(o.webauthn.credential_options.publicKey,a?.create),{data:h,error:m}=await xo({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=Po(o.webauthn.credential_options.publicKey,a?.request),{data:h,error:m}=await To(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 A(o)?{data:null,error:o}:{data:null,error:new ut("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 Yt("rpId is required for WebAuthn authentication")};try{if(!nn())return{data:null,error:new ut("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 A(i)?{data:null,error:i}:{data:null,error:new ut("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 Yt("rpId is required for WebAuthn registration")};try{if(!nn())return{data:null,error:new ut("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 A(i)?{data:null,error:i}:{data:null,error:new ut("Unexpected error in register",i)}}}}ho();const Co={url:Ai,storageKey:Ei,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Pi,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function an(t,e,r){return await r()}const Nt={};class Qt{get jwks(){var e,r;return(r=(e=Nt[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Nt[this.storageKey]=Object.assign(Object.assign({},Nt[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Nt[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Nt[this.storageKey]=Object.assign(Object.assign({},Nt[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.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const a=Object.assign(Object.assign({},Co),e);if(this.storageKey=a.storageKey,this.instanceID=(r=Qt.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,Qt.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!a.debug,typeof a.debug=="function"&&(this.logger=a.debug),this.instanceID>0&&ve()){const i=`${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(i),this.logDebugMessages&&console.trace(i)}if(this.persistSession=a.persistSession,this.autoRefreshToken=a.autoRefreshToken,this.admin=new co({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=Vs(a.fetch),this.lock=a.lock||an,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,this.throwOnError=a.throwOnError,this.lockAcquireTimeout=a.lockAcquireTimeout,a.lock?this.lock=a.lock:this.persistSession&&ve()&&(!((s=globalThis?.navigator)===null||s===void 0)&&s.locks)?this.lock=uo:this.lock=an,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 Oo(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.persistSession?(a.storage?this.storage=a.storage:zs()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Zs(this.memoryStorage)),a.userStorage&&(this.userStorage=a.userStorage)):(this.memoryStorage={},this.storage=Zs(this.memoryStorage)),ve()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i);try{await this._notifyAllSubscribers(i.data.event,i.data.session,!1)}catch(o){this._debug("#broadcastChannel","error",o)}})}a.skipAutoInitialize||this.initialize().catch(i=>{this._debug("#initialize()","error",i)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ms}) ${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(ve()&&(r=qi(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),ve()&&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),Ii(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 A(r)?this._returnResult({error:r}):this._returnResult({error:new ut("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const a=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:Ge}),{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(A(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 Ct(this.storage,this.storageKey)),a=await P(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:Ge})}else if("phone"in e){const{phone:d,password:h,options:m}=e;a=await P(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:Ge})}else throw new wr("You must provide either an email or phone number and a password");const{data:i,error:o}=a;if(o||!i)return await we(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 we(this.storage,`${this.storageKey}-code-verifier`),A(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 P(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:Qs})}else if("phone"in e){const{phone:a,password:i,options:o}=e;r=await P(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:Qs})}else throw new wr("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 Et;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(A(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:T,statement:k,options:S}=e;let _;if(ve())if(typeof T=="object")_=T;else{const $=window;if("ethereum"in $&&typeof $.ethereum=="object"&&"request"in $.ethereum&&typeof $.ethereum.request=="function")_=$.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 T!="object"||!S?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=T}const R=new URL((r=S?.url)!==null&&r!==void 0?r:window.location.href),O=await _.request({method:"eth_requestAccounts"}).then($=>$).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!O||O.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const B=rn(O[0]);let E=(s=S?.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!E){const $=await _.request({method:"eth_chainId"});E=fo($)}const U={domain:R.host,address:B,statement:k,uri:R.href,version:"1",chainId:E,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=po(U),g=await _.request({method:"personal_sign",params:[mo(p),B]})}try{const{data:b,error:T}=await P(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:Ge});if(T)throw T;if(!b||!b.session||!b.user){const k=new Et;return this._returnResult({data:{user:null,session:null},error:k})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:T})}catch(b){if(A(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:T,wallet:k,statement:S,options:_}=e;let R;if(ve())if(typeof k=="object")R=k;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"))R=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 k!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");R=k}const O=new URL((r=_?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in R&&R.signIn){const B=await R.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},_?.signInWithSolana),{version:"1",domain:O.host,uri:O.href}),S?{statement:S}:null));let E;if(Array.isArray(B)&&B[0]&&typeof B[0]=="object")E=B[0];else if(B&&typeof B=="object"&&"signedMessage"in B&&"signature"in B)E=B;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),b=E.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in R)||typeof R.signMessage!="function"||!("publicKey"in R)||typeof R!="object"||!R.publicKey||!("toBase58"in R.publicKey)||typeof R.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${O.host} wants you to sign in with your Solana account:`,R.publicKey.toBase58(),...S?["",S,""]:[""],"Version: 1",`URI: ${O.href}`,`Issued At: ${(n=(s=_?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((a=_?.signInWithSolana)===null||a===void 0)&&a.notBefore?[`Not Before: ${_.signInWithSolana.notBefore}`]:[],...!((i=_?.signInWithSolana)===null||i===void 0)&&i.expirationTime?[`Expiration Time: ${_.signInWithSolana.expirationTime}`]:[],...!((o=_?.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${_.signInWithSolana.chainId}`]:[],...!((l=_?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${_.signInWithSolana.nonce}`]:[],...!((u=_?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${_.signInWithSolana.requestId}`]:[],...!((h=(d=_?.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||h===void 0)&&h.length?["Resources",..._.signInWithSolana.resources.map(E=>`- ${E}`)]:[]].join(`
57
- `);const B=await R.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:T,error:k}=await P(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:dt(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:Ge});if(k)throw k;if(!T||!T.session||!T.user){const S=new Et;return this._returnResult({data:{user:null,session:null},error:S})}return T.session&&(await this._saveSession(T.session),await this._notifyAllSubscribers("SIGNED_IN",T.session)),this._returnResult({data:Object.assign({},T),error:k})}catch(T){if(A(T))return this._returnResult({data:{user:null,session:null},error:T});throw T}}async _exchangeCodeForSession(e){const r=await ft(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new Di;const{data:a,error:i}=await P(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:Ge});if(await we(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!a||!a.session||!a.user){const o=new Et;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:Object.assign(Object.assign({},a),{redirectType:n??null}),error:i})}catch(a){if(await we(this.storage,`${this.storageKey}-code-verifier`),A(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 P(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:Ge}),{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 Et;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(A(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 Ct(this.storage,this.storageKey));const{error:h}=await P(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 P(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 wr("You must provide either an email or phone number.")}catch(o){if(await we(this.storage,`${this.storageKey}-code-verifier`),A(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 P(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:n,xform:Ge});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(A(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 Ct(this.storage,this.storageKey));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:(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:io});return!((a=u.data)===null||a===void 0)&&a.url&&ve()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(o){if(await we(this.storage,`${this.storageKey}-code-verifier`),A(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 Ie;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(A(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 P(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 P(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 wr("You must provide either an email or phone number and a type")}catch(r){if(A(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 ft(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()<Yr:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const i=await ft(this.userStorage,this.storageKey+"-user");i?.user?e.user=i.user:e.user=ts()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const i={value:this.suppressGetSessionWarning};e.user=ro(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 P(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:nt}):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 Ie}:await P(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:nt})})}catch(r){if(A(r))return vr(r)&&(await this._removeSession(),await we(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 Ie;const i=n.session;let o=null,l=null;this.flowType==="pkce"&&e.email!=null&&([o,l]=await Ct(this.storage,this.storageKey));const{data:u,error:d}=await P(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:nt});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 we(this.storage,`${this.storageKey}-code-verifier`),A(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 Ie;const r=Date.now()/1e3;let s=r,n=!0,a=null;const{payload:i}=xr(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(A(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 Ie;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(A(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!ve())throw new _r("No browser detected.");if(e.error||e.error_description||e.error_code)throw new _r(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 Ks("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new _r("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 Ks("No code detected.");const{data:S,error:_}=await this._exchangeCodeForSession(e.code);if(_)throw _;const R=new URL(window.location.href);return R.searchParams.delete("code"),window.history.replaceState(window.history.state,"",R.toString()),{data:{session:S.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:n,access_token:a,refresh_token:i,expires_in:o,expires_at:l,token_type:u}=e;if(!a||!o||!i||!u)throw new _r("No session defined in URL");const d=Math.round(Date.now()/1e3),h=parseInt(o);let m=d+h;l&&(m=parseInt(l));const p=m-d;p*1e3<=At&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);const g=m-h;d-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,m,d):d-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,m,d);const{data:b,error:T}=await this._getUser(a);if(T)throw T;const k={provider_token:s,provider_refresh_token:n,access_token:a,expires_in:h,expires_at:m,refresh_token:i,token_type:u,user:b.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:k,redirectType:e.type},error:null})}catch(s){if(A(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_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 ft(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&&!vr(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&&!(Ni(o)&&(o.status===404||o.status===401||o.status===403)||vr(o)))return this._returnResult({error:o})}return e!=="others"&&(await this._removeSession(),await we(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=Fi(),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),vr(a)?console.warn(a):console.error(a)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await Ct(this.storage,this.storageKey,!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:r.redirectTo})}catch(a){if(await we(this.storage,`${this.storageKey}-code-verifier`),A(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(A(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 P(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 ve()&&!(!((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(A(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 P(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:Ge}),{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 Et}):(m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("USER_UPDATED",m.session)),this._returnResult({data:m,error:p}))}catch(n){if(await we(this.storage,`${this.storageKey}-code-verifier`),A(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 P(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(A(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 Gi(async n=>(n>0&&await Wi(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:Ge})),(n,a)=>{const i=200*Math.pow(2,n);return a&&Zr(a)&&Date.now()+i-s<At})}catch(s){if(this._debug(r,"error",s),A(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),ve()&&!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 ft(this.storage,this.storageKey);if(n&&this.userStorage){let i=await ft(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!i&&(i={user:n.user},await Ot(this.userStorage,this.storageKey+"-user",i)),n.user=(e=i?.user)!==null&&e!==void 0?e:ts()}else if(n&&!n.user&&!n.user){const i=await ft(this.storage,this.storageKey+"-user");i&&i?.user?(n.user=i.user,await we(this.storage,this.storageKey+"-user"),await Ot(this.storage,this.storageKey,n)):n.user=ts()}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()<Yr;if(this._debug(s,`session has${a?"":" not"} expired with margin of ${Yr}s`),a){if(this.autoRefreshToken&&n.refresh_token){const{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),Zr(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 Ie;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Sr;const{data:a,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!a.session)throw new Ie;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),A(a)){const i={data:null,error:a};return Zr(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 we(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 Ot(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const a=Js(n);await Ot(this.storage,this.storageKey,a)}else{const n=Js(r);await Ot(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await we(this.storage,this.storageKey),await we(this.storage,this.storageKey+"-code-verifier"),await we(this.storage,this.storageKey+"-user"),this.userStorage&&await we(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&ve()&&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(),At);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)/At);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${At}ms, refresh threshold is ${Jr} ticks`),n<=Jr&&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 en)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!ve()||!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 Ct(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 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(A(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 P(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(A(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"?ko(e.webauthn.credential_response):So(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:l}=await P(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(A(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 P(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:wo(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:_o(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(A(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}=xr(e);let g=null;p.aal&&(g=p.aal);let b=g;const{data:{user:T},error:k}=await this.getUser(e);if(k)return this._returnResult({data:null,error:k});((s=(r=T?.factors)===null||r===void 0?void 0:r.filter(R=>R.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(b="aal2");const _=p.amr||[];return{data:{currentLevel:g,nextLevel:b,currentAuthenticationMethods:_},error:null}}catch(p){if(A(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}=xr(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 P(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 Ie})})}catch(r){if(A(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 Ie});const i=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 i.data&&i.data.redirect_url&&ve()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(s){if(A(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 Ie});const i=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 i.data&&i.data.redirect_url&&ve()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(s){if(A(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 Ie})})}catch(e){if(A(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 Ie})})}catch(r){if(A(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+Ci>n)return s;const{data:a,error:i}=await P(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}}=xr(s);r?.allowExpired||Zi(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=eo(n.alg),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,i,Bi(`${o}.${l}`)))throw new es("Invalid JWT signature");return{data:{claims:a,header:n,signature:i},error:null}}catch(s){if(A(s))return this._returnResult({data:null,error:s});throw s}}}Qt.nextInstanceID={};const Ro=Qt,No="2.104.0";let Xt="";typeof Deno<"u"?Xt="deno":typeof document<"u"?Xt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Xt="react-native":Xt="node";const Io={headers:{"X-Client-Info":`supabase-js-${Xt}/${No}`}},Do={schema:"public"},$o={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Lo={};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 Uo(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 Mo(t){var e=Uo(t,"string");return Zt(e)=="symbol"?e:e+""}function Bo(t,e,r){return(e=Mo(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function on(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?on(Object(r),!0).forEach(function(s){Bo(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):on(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const Ko=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Fo=()=>Headers,qo=(t,e,r)=>{const s=Ko(r),n=Fo();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 Ho(t){return t.endsWith("/")?t:t+"/"}function Wo(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 Go(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(Ho(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var zo=class extends Ro{constructor(t){super(t)}},Vo=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const a=Go(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:Do,realtime:Lo,auth:ae(ae({},$o),{},{storageKey:i}),global:Io},l=Wo(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=qo(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(ae({headers:this.headers,accessToken:this._getAccessToken.bind(this)},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 ya(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 ji(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new oa(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},d,h){const m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new zo({url:this.authUrl.href,headers:ae(ae({},m),d),storageKey:a,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:i,lock:o,debug:l,throwOnError:u,fetch:h,hasCustomAuthorizationHeader:Object.keys(this.headers).some(p=>p.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Ya(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 Jo=(t,e,r)=>new Vo(t,e,r);function Yo(){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}Yo()&&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 ln(t,e){if(!t||!e)throw new Error("Supabase URL and anon key are required");return Jo(t,e)}function cn(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 Ue(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 Qo(t){const r=t.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
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,`
58
58
  `).trim().split(`
59
- `);if(r.length<2)return[];const s=cn(r[0]),n=[];for(let a=1;a<r.length;a++){const i=cn(r[a]);if(i.length<s.length)continue;const o={};s.forEach((m,p)=>{o[m]=i[p]??""});const l=Ue(o,"store_id","store id"),u=Ue(o,"pooja_title","pooja title","puja title");if(!l||!u)continue;const d=Ue(o,"cover_media_url","cover media url","cover image"),h=Ue(o,"cover_media_url_english","cover media url english","cover image english");n.push({store_id:l,pooja_title:u,temple_name:Ue(o,"temple_name","temple name")||"",pooja_title_english:Ue(o,"pooja_title_english","pooja title english","puja title english")||void 0,temple_name_english:Ue(o,"temple_name_english","temple name english")||void 0,cover_media_url:d||void 0,cover_media_url_english:h||void 0,puja_link:Ue(o,"puja_link","puja link","pooja link")||Ue(o,"puja link","pooja link")||"",puja_link_hindi:Ue(o,"puja_link_hindi","puja link hindi","pooja link hindi")||void 0,individual_pack_price_inr:parseFloat(Ue(o,"individual_pack_price_inr","individual pack price inr","price"))||0,schedule_date_ist:Ue(o,"schedule_date_ist","schedule date ist","schedule date")||""})}return n}const un={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 Xo(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 dn(t,e){const r=un[e]||un[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=Xo(i.schedule_date_ist);return o?o.getTime()>=n.getTime():!0})[0]??s[0])||null}let It=[],hn=0;const Zo=3600*1e3;async function el(t){const e=Date.now();if(It.length>0&&e-hn<Zo)return It;try{const{data:r,error:s}=await t.functions.invoke("fetch-pujas");if(s)return console.warn("[DoshaCalculator] fetch-pujas error:",s),It;const n=typeof r=="string"?r:"";if(!n)return It;const a=Qo(n);return It=a,hn=e,a}catch(r){return console.warn("[DoshaCalculator] fetchPujas error:",r),It}}const fn={"पितृ दोष निवारण महायज्ञ एवं काशी गंगा महाआरती":"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"},tl={पूजा:"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"},mn={"काशी विश्वनाथ मंदिर":"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 rl(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 pn(t){let e=t;return Object.entries(tl).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 ss(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(fn[s])return fn[s];const a=pn(s);return a!==s?a:s}function gn(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(mn[s])return mn[s];const a=pn(s);return a!==s?a:s}function yn(t,e="en"){const r=rl(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 sl(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 ns(t,e){const s=e?.toLowerCase().startsWith("hi")?t.puja_link_hindi||t.puja_link:t.puja_link||t.puja_link_hindi;return sl(s||"")}function bn(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 nl={container:"_container_m8vst_1"},al=["en","hi"],il={en:"English",hi:"हिन्दी"},vn={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
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
60
60
  Fast on Tuesdays
61
61
  Donate red items like lentils or cloth
62
62
  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 +164,12 @@ Visit Navagraha temples`,ctaKundliCreated:"3L+ Kundli Reports Created.",ctaCerti
164
164
  परामर्श के बाद लहसुनिया पहनें`,drOtherNavagrahaRemedies:`व्यापक नवग्रह शांति पूजा करें
165
165
  नवग्रह मंत्र का पाठ करें
166
166
  सभी नौ ग्रहों के लिए वस्तुओं का दान करें
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:"कौन सा उपाय या पूजा आपके लिए सही रहेगा।"}},wn=v.createContext(null);function _n(){return typeof window>"u"?"en":window.location.pathname.split("/").filter(Boolean)[0]==="hi"?"hi":"en"}function ol(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 ll({locale:t,onLocaleChange:e,children:r}){const[s,n]=v.useState(()=>t||_n());v.useEffect(()=>{if(t)n(t);else{const o=()=>n(_n());return window.addEventListener("popstate",o),()=>window.removeEventListener("popstate",o)}},[t]);const a=o=>{e?e(o):ol(o)},i=v.useMemo(()=>o=>vn[s]?.[o]??o,[s]);return c.jsx(wn.Provider,{value:{locale:s,setLocale:a,t:i},children:r})}function as(){return v.useContext(wn)}function cl(){const e=as()?.locale==="hi";return c.jsx("div",{className:nl.container,children:e?"100% सटीक • सुरक्षित • 30 लाख+ परिवारों द्वारा विश्वसनीय":"100% Accurate • Secure • Trusted by 30L+ families"})}const Me=t=>({width:t,height:t});function is(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",...Me(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 kn(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",...Me(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 Ar(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",...Me(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 ul(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",...Me(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 dl(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",...Me(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 hl(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",...Me(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 fl(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",...Me(e),...r,children:c.jsx("path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"})})}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",...Me(e),...r,children:[c.jsx("path",{d:"m5 12 7-7 7 7"}),c.jsx("path",{d:"M12 19V5"})]})}function Sn(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",...Me(e),...r,children:c.jsx("path",{d:"m6 9 6 6 6-6"})})}function os(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"},...Me(e),...s,children:c.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})}function pl(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",...Me(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 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",...Me(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 Be={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"},tt=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}})},yl="https://srm-cdn.a4b.io/yoda/1771588545907.svg";function bl({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:Be.bookPujaButton,children:c.jsxs("div",{className:Be.bookPujaContent,children:[c.jsxs("div",{className:Be.pujaInfo,children:[c.jsx("span",{className:Be.pujaName,children:i.name}),i.price>0&&c.jsxs("div",{className:Be.pujaPrice,children:[c.jsx("span",{className:Be.priceLabel,children:"Starting from "}),c.jsxs("span",{className:Be.priceAmount,children:["₹",i.price]})]})]}),c.jsxs("span",{className:Be.bookButton,children:[l," →"]})]})}):c.jsx(q.FooterCTAButton,{onClick:e,disabled:n,className:t?Be.ctaFilled:void 0,children:n?c.jsxs("span",{className:Be.ctaFilledContent,children:[c.jsx(os,{className:"w-5 h-5 animate-spin"}),u]}):t?c.jsxs("span",{className:Be.ctaFilledContent,children:[s,c.jsx(tt,{src:yl,alt:"",className:Be.chevronRight,width:20,height:20,loading:"lazy"})]}):r})}const Er={bannerContainer:"_bannerContainer_1s29r_1",bannerImage:"_bannerImage_1s29r_13",ticker:"_ticker_1s29r_20",tickerContent:"_tickerContent_1s29r_30"};function vl({bannerConfig:t,className:e="",imageComponent:r=tt}){const s=r;return c.jsxs("section",{className:`${Er.bannerContainer} ${e}`,children:[c.jsx(s,{src:t.imageUrl,alt:t.alt,className:Er.bannerImage,loading:"eager",priority:!0,fetchPriority:"high"}),c.jsx("div",{className:Er.ticker,children:c.jsx("div",{className:Er.tickerContent,children:t.tickerText})})]})}const wl=112;function at({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 -${wl}px 0px`});return i.observe(a),()=>i.disconnect()},[t,r]),c.jsx("div",{ref:s,children:e})}const Dt={wrap:"_wrap_1mrzx_1",input:"_input_1mrzx_6",iconBtn:"_iconBtn_1mrzx_35",iconImg:"_iconImg_1mrzx_49",placeholder:"_placeholder_1mrzx_53",dateDisplay:"_dateDisplay_1mrzx_65"},_l="https://srm-cdn.a4b.io/yoda/1770372045894.svg",kl=t=>{if(!t)return"";const[e,r,s]=t.split("-");return`${s}/${r}/${e}`};function Sl({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:`${Dt.wrap} ${n}`,children:[!e&&c.jsx("span",{className:Dt.placeholder,children:"Select Date of Birth"}),e&&c.jsx("div",{className:Dt.dateDisplay,children:kl(e)}),c.jsx("input",{ref:a,id:t,type:"date",className:Dt.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:Dt.iconBtn,"aria-label":"Open date picker",onMouseDown:l=>l.preventDefault(),onClick:l=>{l.preventDefault(),l.stopPropagation(),o()},children:c.jsx(tt,{className:Dt.iconImg,src:_l,alt:"",width:22,height:22,loading:"lazy"})})]})}const be={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"},xl="https://srm-cdn.a4b.io/yoda/1770372014782.svg",xn=t=>String(t).padStart(2,"0");function Tl(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 jl(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 Al(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),`${xn(s)}:${r}`}function El({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(jl(e||"12:00")),u(g=>!g))},p=()=>{const g=Al(d);r(g),u(!1)};return c.jsxs("div",{className:`${be.wrap} ${i}`,ref:o,children:[c.jsx("input",{id:t,className:be.input,type:"text",value:e?Tl(e):"",readOnly:!0,disabled:a,placeholder:n,onClick:m}),c.jsx("button",{type:"button",className:be.iconBtn,"aria-label":"Open time picker",disabled:a,onMouseDown:g=>g.preventDefault(),onClick:g=>{g.preventDefault(),g.stopPropagation(),m()},children:c.jsx(tt,{className:be.iconImg,src:xl,alt:"",width:22,height:22,loading:"lazy"})}),l&&!a&&c.jsxs("div",{className:be.timePopover,role:"dialog","aria-label":"Select time",children:[c.jsxs("div",{className:be.timePickerRow,children:[c.jsx("select",{className:be.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:be.timePickerColon,children:":"}),c.jsx("select",{className:be.timePickerSelect,value:d.minute,onChange:g=>h(b=>({...b,minute:g.target.value})),"aria-label":"Minute",children:Array.from({length:60},(g,b)=>xn(b)).map(g=>c.jsx("option",{value:g,children:g},g))}),c.jsxs("div",{className:be.meridiemToggle,"aria-label":"AM/PM",children:[c.jsx("button",{type:"button",className:`${be.meridiemBtn} ${d.meridiem==="AM"?be.meridiemActive:""}`,onClick:()=>h(g=>({...g,meridiem:"AM"})),children:"AM"}),c.jsx("button",{type:"button",className:`${be.meridiemBtn} ${d.meridiem==="PM"?be.meridiemActive:""}`,onClick:()=>h(g=>({...g,meridiem:"PM"})),children:"PM"})]})]}),c.jsxs("div",{className:be.timePopoverActions,children:[c.jsx("button",{type:"button",className:be.timePopoverBtn,onClick:()=>u(!1),children:"Cancel"}),c.jsx("button",{type:"button",className:`${be.timePopoverBtn} ${be.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 Tn(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 jn(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 An(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 Tn(t,{visitorId:s,sessionId:n,problemStatements:i,language:o}),jn(t,e,{"x-visitor-id":s,"x-session-id":n})}let Pr=null;const Pl=(t,e)=>typeof window>"u"||window.google?.maps?.places?Promise.resolve():Pr||(Pr=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)}),Pr),En=(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}Pl(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 _={input:S,types:["(cities)"],sessionToken:g.current??void 0};s&&(_.componentRestrictions={country:s});const R=await new Promise((O,B)=>{m.current.getPlacePredictions(_,(E,U)=>{U===google.maps.places.PlacesServiceStatus.OK&&E?O(E):U===google.maps.places.PlacesServiceStatus.ZERO_RESULTS?O([]):B(new Error(`Places API error: ${U}`))})});o(R.map(O=>({place_id:O.place_id,description:O.description,structured_formatting:{main_text:O.structured_formatting?.main_text||O.description,secondary_text:O.structured_formatting?.secondary_text||""}})))}catch{o([])}finally{u(!1)}},[s]),T=v.useCallback(async S=>{if(!p.current)return null;try{const _=await new Promise(($,De)=>{p.current.getDetails({placeId:S,fields:["geometry","address_components","formatted_address"],sessionToken:g.current??void 0},(ge,Pe)=>{Pe===google.maps.places.PlacesServiceStatus.OK&&ge?$(ge):De(new Error(`Place details error: ${Pe}`))})});g.current=new google.maps.places.AutocompleteSessionToken;const R=_.geometry?.location?.lat()||0,O=_.geometry?.location?.lng()||0;let B="",E="",U="";return _.address_components?.forEach($=>{$.types.includes("locality")&&(B=$.long_name),$.types.includes("administrative_area_level_1")&&(E=$.long_name),$.types.includes("country")&&(U=$.long_name)}),{display_name:_.formatted_address||"",lat:R,lng:O,city:B,state:E,country:U}}catch{return null}},[]),k=v.useCallback(()=>o([]),[]);return{isLoaded:n,predictions:i,isSearching:l,loadError:d,searchPlaces:b,getPlaceDetails:T,clearPredictions:k}},Ol=["formProblemMarriage","formProblemMoney","formProblemHealth","formProblemEducation","formProblemCareer","formProblemOther"];function Cl(){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 Rl(){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 Nl(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 ls=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,T]=v.useState(s?.name??""),[k,S]=v.useState(s?.gender??""),[_,R]=v.useState(s?.problems??[]),[O,B]=v.useState(s?.dateOfBirth??""),[E,U]=v.useState(s?.birthTime??""),[$,De]=v.useState(s?.birthTimeUnknown??!1),[ge,Pe]=v.useState(s?.birthPlace??""),[ee,te]=v.useState(s?.otherProblemText??""),[he,Qe]=v.useState(null),[Oe,re]=v.useState(!1),[fe,ke]=v.useState(null),[Q,y]=v.useState({}),K=v.useCallback(j=>{const I=ie=>{const ze=document.getElementById(ie);return ze?(ze.focus(),ze.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:Te,getPlaceDetails:Lt,clearPredictions:Fe}=En({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){Fe();return}const j=window.setTimeout(async()=>{await Te(ge)},300);return()=>window.clearTimeout(j)},[ge,Fe,Oe,Te]);const bt=b.trim()!==""&&(k==="male"||k==="female")&&O!==""&&(E!==""||$)&&ge.trim()!=="";v.useEffect(()=>{a?.(bt)},[bt,a]),v.useEffect(()=>{n?.({name:b,gender:k,problems:_,otherProblemText:ee,dateOfBirth:O,birthTime:E,birthTimeUnknown:$,birthPlace:ge})},[b,k,_,ee,O,E,$,ge,n]),v.useEffect(()=>{!_.includes("formProblemOther")&&ee&&te("")},[_,ee]);const vt=v.useCallback(async(j,I)=>{if(!m)return"UTC";try{const ie=Math.floor(Date.now()/1e3),ze=`https://maps.googleapis.com/maps/api/timezone/json?location=${j},${I}&timestamp=${ie}&key=${m}`,_e=await(await fetch(ze)).json();return _e.status==="OK"&&_e.timeZoneId?_e.timeZoneId:"UTC"}catch{return"UTC"}},[m]),rt=v.useCallback(async()=>{const j=(ce,je,qe=!1)=>{je&&(y(Le=>({...Le,[je]:ce})),K(je)),ke(qe?ce:null),u?.(ce)};if(y({}),ke(null),!i){j(e("calculationError"));return}if(!b.trim()){j(e("formNameRequired"),"name");return}if(k!=="male"&&k!=="female"){j(e("formGenderRequired"),"gender");return}if(!O){j(e("formDobRequired"),"dateOfBirth");return}if(!$&&!E){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 ze=Nl(O),lt=new Set(["formProblemMarriage","formProblemMoney","formProblemCareer","formProblemBusiness","marriage","financial","career","business"]),_e=_.some(ce=>lt.has(ce));if(ze<18&&_e){j(e("formAgeMarriageRestriction"),void 0,!0);return}if(!he&&!o){j(e("formPlaceSelectFromDropdown"),"birthPlace");return}d?.(!0);try{let ce,je,qe;if(he)ce=he.lat,je=he.lon,he.tz?qe=he.tz:(qe=await vt(ce,je),Qe({...he,tz:qe}));else if(o){const ye=await o(I);if(!ye){j(e("locationError")),d?.(!1);return}ce=ye.lat,je=ye.lon,qe=ye.tz}else{j(e("formPlaceSelectFromDropdown"),"birthPlace"),d?.(!1);return}const Le={problemAreaValues:[..._.filter(ye=>ye!=="formProblemOther").map(ye=>e(ye)).filter(Boolean),..._.includes("formProblemOther")&&ee.trim()?[ee.trim()]:[]],name:b.trim(),gender:k==="male"?"M":"F",date:O,time:$?"":E||"12:00",unknownTime:$,tz:qe||"UTC",lat:ce,lon:je,place:ie,problemArea:void 0};Le.problemArea=Le.problemAreaValues.length>0?Le.problemAreaValues.join(", "):void 0;const sr=Cl(),C=Rl(),ne=Le.problemAreaValues,Se=typeof navigator<"u"&&navigator.language?.toLowerCase().startsWith("hi")?"hi":"en",xe=await An(i,Le,{visitorId:sr,sessionId:C,trackProblemStatements:!0,problemStatements:ne,language:Se});if(xe.success){ke(null);const[ye,nr,ar]=(Le.date||"").split("-").map(Number),Dr=Le.time||"12:00",[ct,ir]=Dr.split(":").map(Lr=>parseInt(Lr,10)||0);l?.(xe,{day:ar||1,month:nr||1,year:ye||2e3,hour:ct,minute:ir,lat:ce,lon:je,tzone:5.5})}else{let ye=xe.error??e("calculationError");(ye.includes("Expected 'M' | 'F'")||ye.includes("gender"))&&(ye=e("formGenderRequired")),j(ye)}}catch(ce){const je=ce instanceof Error?ce.message:String(ce);j(je)}finally{d?.(!1)}},[i,o,he,ge,b,k,O,E,$,_,e,u,d,h,l,vt,K]);v.useImperativeHandle(p,()=>({submit:rt}),[rt]);const rr=Ol.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?.()),T(I),Q.name&&y(ie=>({...ie,name:void 0})),fe&&ke(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:k,onChange:j=>{S(j),Q.gender&&y(I=>({...I,gender:void 0})),fe&&ke(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:rr,selected:_,onChange:j=>{R(j),j.includes("formProblemOther")||te("")}}),_.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(Sl,{id:"dosha-dob",value:O,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&&ke(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(El,{id:"dosha-time",value:E,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&&ke(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);Pe(I),Qe(null),re(!0),I&&!L.current&&(L.current=!0,h?.trackPlaceOfBirthChosen?.(I)),Q.birthPlace&&y(ie=>({...ie,birthPlace:void 0})),fe&&ke(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(Pe(g(j.description)),Lt){const I=await Lt(j.place_id);I&&(Qe({lat:I.lat,lon:I.lng}),Q.birthPlace&&y(ie=>({...ie,birthPlace:void 0})),fe&&ke(null))}Fe(),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})]})]})}),$t=Re.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`animate-pulse rounded-md bg-muted ${t}`,...e}));$t.displayName="Skeleton";const it=Re.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}));it.displayName="Card";const pt=Re.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`flex flex-col space-y-1.5 p-6 ${t}`,...e}));pt.displayName="CardHeader";const gt=Re.forwardRef(({className:t="",...e},r)=>c.jsx("h3",{ref:r,className:`text-2xl font-semibold leading-none tracking-tight ${t}`,...e}));gt.displayName="CardTitle";const Or=Re.forwardRef(({className:t="",...e},r)=>c.jsx("p",{ref:r,className:`text-sm text-muted-foreground ${t}`,...e}));Or.displayName="CardDescription";const yt=Re.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`p-6 pt-0 ${t}`,...e}));yt.displayName="CardContent";const er=Re.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})});er.displayName="Button";function Pn({puja:t,doshaType:e,language:r,onBookClick:s,imageComponent:n=tt,analytics:a}){const i=n,o=r?.toLowerCase().startsWith("hi"),l=ss(t,r),u=gn(t,r),d=yn(t.schedule_date_ist,r),h=ns(t,r),m=bn(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(it,{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(er,{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(pl,{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 ot={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 On({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:`${ot.section} ${e}`,"aria-labelledby":"what-from-analysis-heading",children:[c.jsx("h2",{id:"what-from-analysis-heading",className:ot.heading,children:s}),c.jsx("ol",{className:ot.list,children:a.map(({titleKey:i,descKey:o},l)=>c.jsxs("li",{className:ot.item,children:[c.jsx("span",{className:ot.stepNumber,"aria-hidden":"true",children:l+1}),c.jsxs("div",{className:ot.itemContent,children:[c.jsx("span",{className:ot.itemTitle,children:t(i)}),c.jsx("span",{className:ot.itemDesc,children:t(o)})]})]},i))})]})}const Il={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 रेटिंग अपने दोषा को जानने वाले यूज़र्स ने दी"}}},Dl={"marriage-what-you'll-get-first":"marriage","marriage-form-first":"marriage","generic-what-you'll-get-first":"generic","generic-form-first":"generic"};function Cn(t,e){let r="generic";if(t){for(const[s,n]of Object.entries(Dl))if(t.includes(s)){r=n;break}}return Il[r][e]}function $l(t){return typeof window>"u"?null:new URLSearchParams(window.location.search).get(t)}function Cr(){return $l("utm_term")}const Ll=v.lazy(()=>Promise.resolve().then(()=>nc).then(t=>({default:t.DoshaResultsFull}))),Ul="https://srm-cdn.a4b.io/yoda/1770362904947.svg",Ml="https://srm-cdn.a4b.io/yoda/1770375694934.svg",Bl="https://srm-cdn.a4b.io/yoda/1770375720933.svg",Kl="https://srm-cdn.a4b.io/yoda/1770707793537.svg",Fl="https://srm-cdn.a4b.io/yoda/1770362713543.svg";function Rn(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 Rr(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function Nn(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 In(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 cs(t){const e=[];return Rr(t.kaalSarp)&&e.push({type:"kaal-sarp",severity:typeof t.kaalSarpSeverity=="string"?t.kaalSarpSeverity:void 0}),Rr(t.pitra)&&e.push({type:"pitra",severity:typeof t.pitraSeverity=="string"?t.pitraSeverity:void 0}),Rr(t.shaniSadeSati||t.sadeSati)&&e.push({type:"shani",severity:typeof t.sadeSatiSeverity=="string"?t.sadeSatiSeverity:void 0}),Rr(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)=>Nn(s.severity)-Nn(r.severity)),e[0]?.type??null)}function ql({t}){return c.jsxs("div",{className:q.footerShellStyles.marqueeContent,children:[c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(tt,{src:Ml,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaKundliCreated")]}),c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(tt,{src:Bl,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaCertified")]}),c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(tt,{src:Kl,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaSecurePayment")]})]})}const Hl=[{qKey:"faqQ1",aKey:"faqA1"},{qKey:"faqQ2",aKey:"faqA2"},{qKey:"faqQ3",aKey:"faqA3"}],Wl=[{qKey:"faqQ1Marriage",aKey:"faqA1Marriage"},{qKey:"faqQ2Marriage",aKey:"faqA2Marriage"},{qKey:"faqQ3Marriage",aKey:"faqA3Marriage"},{qKey:"faqQ4Marriage",aKey:"faqA4Marriage"}];function Gl({className:t="",logoUrl:e=Ul,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:T="kundali-chart-section",analytics:k,getFirstPujaInfo:S,onBookPujaClick:_,imageComponent:R=tt}){const O=v.useMemo(()=>{if(u)return u;if(i&&o)try{return ln(i,o)}catch{return null}return null},[u,i,o]),B=R,E=as(),U=E?.t??(C=>C),$=E?.locale??"en",De=E?.setLocale,ge=$.toLowerCase().startsWith("hi"),Pe=v.useRef(null),ee=v.useRef(null),[te,he]=v.useState(!1),[Qe,Oe]=v.useState(!1),[re,fe]=v.useState(null),[ke,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,k?.trackDoshaCalculatorWebView?.())},[]);const Te=!p||!S;v.useEffect(()=>{if(!Te||!O)return;let C=!0;return J(!0),el(O).then(ne=>{C&&M(ne)}).finally(()=>{C&&J(!1)}),()=>{C=!1}},[Te,O]);const Lt=v.useCallback(C=>{const ne=dn(V,C);return ne?c.jsx(Pn,{puja:ne,doshaType:C,language:$,imageComponent:R,analytics:k}):null},[V,$,R,k]),Fe=v.useCallback(C=>{const ne=dn(V,C);return ne?{name:ss(ne,$),price:ne.individual_pack_price_inr,link:ns(ne,$)}:null},[V,$]),$e=p??Lt,bt=S??Fe,vt=g||!p&&L,[rt,rr]=v.useState(()=>{const C=typeof window<"u"?Cr():null;return Cn(C,$)}),[j,I]=v.useState(()=>{if(typeof window>"u")return"generic";const C=Cr();return C&&C.toLowerCase().includes("marriage")?"marriage":"generic"});v.useEffect(()=>{const C=Cr(),ne=Cn(C,$);rr(ne);let Se="generic";C&&C.toLowerCase().includes("marriage")&&(Se="marriage"),I(Se)},[$]);const[ie,ze]=v.useState(!1);v.useEffect(()=>{const C=Cr();C&&C.toLowerCase().includes("what-you")&&ze(!0)},[]);const lt=()=>{Pe.current?.scrollIntoView({behavior:"smooth"})},_e=v.useCallback(C=>{k?.trackDoshaSectionImpression?.({section:C,timestamp:new Date().toISOString()})},[k]),ce=(C,ne)=>{if(fe(C),Q(ne??null),W(!1),C.summary){const Se=C.summary,xe=cs(Se);if(xe){const ye=Rn(xe).map(nr=>bt(nr)).find(Boolean)??null;me(ye)}else me(null)}else me(null);h?.(C,ne)};v.useEffect(()=>{if(S||!re?.summary)return;const C=cs(re.summary);if(!C){me(null);return}const ne=Rn(C).map(Se=>Fe(Se)).find(Boolean)??null;me(ne)},[Fe,S,re]);const je=()=>{W(!0),window.scrollTo({top:0,behavior:"smooth"})},qe=()=>{if(re&&!z&&se){if(se.link){const C=In(se.link);k?.trackDoshaCalculatorResultBookCtaClicked?.({position:"floating_cta",url:C,isOldDosha:!1})}if(_)_();else if(se.link){const C=In(se.link);window.open(C,"_blank","noopener,noreferrer")}return}console.log("supabase",O),console.log("resolvePlaceProp",d),console.log("isFormComplete",te),console.log("formSubmitRef.current",ee.current),O&&ee.current?(k?.trackFloatingCtaClicked?.(te?cr.all_fields_filled:cr.fields_not_filled),te||lt(),ee.current.submit()):(k?.trackFloatingCtaClicked?.(cr.fields_not_filled),lt())},sr=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:Fl,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:sr,showLanguageSelector:s}),c.jsx(q.MarqueeStrip,{children:c.jsx(ql,{t:U})}),!re&&c.jsx(at,{section:"banner",onImpression:_e,children:c.jsx(vl,{bannerConfig:rt,imageComponent:R})}),c.jsx("main",{className:"pb-28",children:re?c.jsx(at,{section:"result",onImpression:_e,children:c.jsx(v.Suspense,{fallback:c.jsxs("div",{className:"container mx-auto px-4 py-8 space-y-4",children:[c.jsx($t,{className:"h-12 w-3/4 mx-auto"}),c.jsx($t,{className:"h-32 w-full"}),c.jsx($t,{className:"h-48 w-full"}),c.jsx($t,{className:"h-48 w-full"})]}),children:c.jsx(Ll,{result:re,t:U,onEdit:z?void 0:je,inlineEditForm:z?c.jsx(ls,{ref:ee,t:U,initialValues:y,onValuesChange:K,onFormValidityChange:he,supabase:O??void 0,resolvePlace:d,googleMapsApiKey:l,onResult:ce,onError:m,onLoadingChange:Oe,analytics:k}):void 0,renderPujaCard:$e,isLoadingPujas:vt,renderKundali:b,kundaliSectionId:T,birthDetails:ke,supabase:O,language:E?.locale??"en",readMoreReviewsHref:a,analytics:k,problemArea:(()=>{const C=y?.problems||[],ne=C.filter(xe=>xe!=="formProblemOther").map(xe=>U(xe)).filter(Boolean),Se=y?.otherProblemText?.trim();return C.includes("formProblemOther")&&Se&&ne.push(Se),ne.join(", ")})(),problemAreaIds:y?.problems||[],customProblemText:y?.otherProblemText||""})})}):c.jsxs(c.Fragment,{children:[ie&&c.jsx(at,{section:"what_from_analysis",onImpression:_e,children:c.jsx(On,{t:U,bannerType:j})}),c.jsx(at,{section:"form",onImpression:_e,children:c.jsx("div",{ref:Pe,children:c.jsx(ls,{ref:ee,t:U,initialValues:y,onValuesChange:K,onFormValidityChange:he,supabase:O??void 0,resolvePlace:d,googleMapsApiKey:l,onResult:ce,onError:m,onLoadingChange:Oe,analytics:k})})}),!ie&&c.jsx(at,{section:"what_from_analysis",onImpression:_e,children:c.jsx(On,{t:U,bannerType:j})}),c.jsx(at,{section:"user_reviews",onImpression:_e,children:c.jsx(q.UserReviewsSection,{t:C=>{if(j==="marriage"){if(C==="feedbackTitle")return U("feedbackTitleMarriage");if(C.startsWith("feedbackTestimonial")){const Se=`feedbackTestimonialMarriage${C.replace("feedbackTestimonial","")}`,xe=U(Se);return xe===Se?U(C):xe}}return U(C)},readMoreHref:a,onReadMore:k?.trackReadMoreReviewsClicked?()=>k.trackReadMoreReviewsClicked():void 0})}),c.jsx(at,{section:"faq",onImpression:_e,children:c.jsx(q.FAQAccordion,{t:U,items:j==="marriage"?Wl:Hl,defaultOpenIndex:0,onItemOpen:C=>k?.trackFaqQuestionClicked?.(C)})}),c.jsx(at,{section:"contact",onImpression:_e,children:c.jsx(q.ContactUsSection,{title:U("contactTitle"),brandName:U("contactBrandName"),whatsAppLine:U("contactWhatsAppDomestic"),emailLine:U("contactEmail")})})]})}),!(re&&!z&&cs(re.summary)===null)&&c.jsxs(q.FooterShell,{children:[!(re&&!z&&se)&&c.jsx(cl,{}),c.jsx(bl,{isFormComplete:te,onPress:qe,labelDefault:U("formCta"),labelFilled:U("formCtaCalculate"),loadingLabel:U("calculating"),isLoading:Qe,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"},zl=[{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 tr(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function Vl(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 Jl(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 Yl({result:t,t:e,onEdit:r,className:s=""}){const n=t.summary??{},a=t.details??{},i=n.shaniSadeSati??n.sadeSati,o=tr(n.mangal)||tr(n.kaalSarp)||tr(n.pitra)||tr(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:zl.map(({key:l,labelKey:u,summaryKey:d})=>{const h=d==="shaniSadeSati"?i:n[d],m=tr(h),p=Vl(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:Jl(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 Nr=Re.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})});Nr.displayName="Badge";const us=Re.createContext(null);function Dn({type:t="single",collapsible:e=!0,className:r="",children:s,onValueChange:n}){const[a,i]=Re.useState(null),o=Re.useCallback(l=>{i(u=>{const d=u===l?e?null:u:l;return n?.(d),d})},[e,n]);return c.jsx(us.Provider,{value:{value:a,onToggle:o},children:c.jsx("div",{className:r,children:s})})}function $n({value:t,className:e="",children:r}){return c.jsx("div",{"data-state":t,className:`border-b border-border ${e}`,children:r})}function Ln({className:t="",children:e,value:r}){const s=Re.useContext(us),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(Sn,{className:`h-4 w-4 shrink-0 transition-transform duration-200 ${n?"rotate-180":""}`})]})}function Un({className:t="",children:e,value:r}){return Re.useContext(us)?.value===r?c.jsx("div",{className:`overflow-hidden text-sm pb-4 pt-0 ${t}`,children:e}):null}const ds=new Map,Mn=1800*1e3;function Ql(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 Xl(t){const e=ds.get(t);if(e&&Date.now()-e.timestamp<Mn)return e.svg;try{const r=sessionStorage.getItem(`kundali_${t}`);if(r){const s=JSON.parse(r);if(Date.now()-s.timestamp<Mn)return ds.set(t,s),s.svg;sessionStorage.removeItem(`kundali_${t}`)}}catch{}return null}function Zl(t,e){const r={svg:e,timestamp:Date.now()};ds.set(t,r);try{sessionStorage.setItem(`kundali_${t}`,JSON.stringify(r))}catch{}}function ec(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 Bn(t,e){const{birthDetails:r,chartType:s,language:n,signal:a}=e,i=Ql(r,s,n),o=Xl(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=ec(u);return Zl(i,d),d}function Kn({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",T=v.useCallback(async _=>{m.current&&m.current.abort();const R=new AbortController;m.current=R,o("loading"),h("");try{const O=await Bn(e,{birthDetails:t,chartType:_,language:b,signal:R.signal});R.signal.aborted||(u(O),o("success"))}catch(O){if(O instanceof Error&&O.name==="AbortError")return;console.error("[KundaliCard] Fetch error:",O),R.signal.aborted||(h(O instanceof Error?O.message:"Failed to load chart"),o("error"))}},[t,e,b]);v.useEffect(()=>(T(n),()=>{m.current&&m.current.abort()}),[n,T]);const k=_=>{_!==n&&a(_)},S=()=>{T(n)};return c.jsxs(it,{ref:p,className:"spiritual-glow border border-primary/10",children:[c.jsxs(pt,{className:"pb-3",children:[c.jsx(gt,{className:"text-xl font-bold",children:s("drYourKundali")}),c.jsxs("div",{className:"flex gap-2 mt-3 pt-2",children:[c.jsx(er,{type:"button",size:"sm",variant:n==="North"?"default":"outline",className:"rounded-full px-4",onClick:()=>k("North"),children:s("kundaliChartNorth")}),c.jsx(er,{type:"button",size:"sm",variant:n==="South"?"default":"outline",className:"rounded-full px-4",onClick:()=>k("South"),children:s("kundaliChartSouth")})]})]}),c.jsx(yt,{children:c.jsxs("div",{className:"w-full max-w-[360px] mx-auto",children:[i==="loading"&&c.jsx($t,{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(er,{type:"button",variant:"outline",size:"sm",onClick:S,className:"gap-2",children:[c.jsx(gl,{className:"w-4 h-4"}),s("kundaliChartRetry")]})]})]})})]})}const tc=[{qKey:"faqQ1",aKey:"faqA1"},{qKey:"faqQ2",aKey:"faqA2"},{qKey:"faqQ3",aKey:"faqA3"}],Fn=[{type:"kaal-sarp",detailKey:"kaalSarp",nameKey:"drKaalSarpName",descKey:"drKaalSarpDesc",impactKey:"drKaalSarpImpact",remediesKey:"drKaalSarpRemedies",benefitsKey:"drPujaBenefitsKaalSarp",icon:dl,summaryKey:"kaalSarp",severityKey:"kaalSarpSeverity"},{type:"pitra",detailKey:"pitra",nameKey:"drPitraName",descKey:"drPitraDesc",impactKey:"drPitraImpact",remediesKey:"drPitraRemedies",benefitsKey:"drPujaBenefitsPitra",icon:hl,summaryKey:"pitra",severityKey:"pitraSeverity"},{type:"shani",detailKey:"sadeSati",nameKey:"drSadeSatiName",descKey:"drSadeSatiDesc",impactKey:"drSadeSatiImpact",remediesKey:"drSadeSatiRemedies",benefitsKey:"drPujaBenefitsShani",icon:fl,summaryKey:"shaniSadeSati",severityKey:"sadeSatiSeverity"},{type:"mangal",detailKey:"mangal",nameKey:"drMangalName",descKey:"drMangalDesc",impactKey:"drMangalImpact",remediesKey:"drMangalRemedies",benefitsKey:"drPujaBenefitsMangal",icon:ul,summaryKey:"mangal",severityKey:"mangalSeverity"}];function rc(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 Ke(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function Ir(t){return t?t.toLowerCase().includes("nullified"):!1}function qn(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(`
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(`
169
169
  `):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 Hn(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 Wn(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 Gn(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 sc(t){return!t||/[\u0900-\u097F]/.test(t)?!1:/[A-Za-z]/.test(t)}function zn({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:T,customProblemText:k}){const[S,_]=v.useState({}),[R,O]=v.useState(!1),B=!l&&u&&d,E=t.summary??{},U=t.details??{};v.useEffect(()=>{if(!b||!b.trim()||!d){O(!1);return}O(!0),_({}),(async()=>{const K={},W=["mangal","kaal-sarp","pitra","shani"].filter(M=>M==="mangal"?Ke(E.mangal)&&!Ir(E.mangal):M==="kaal-sarp"?Ke(E.kaalSarp):M==="pitra"?Ke(E.pitra):M==="shani"?Ke(E.shaniSadeSati??E.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=T?.filter(le=>le!=="formProblemOther").map(le=>L[le]||le.toLowerCase()).filter(Boolean)||[];T?.includes("formProblemOther")&&k?.trim()&&J.push("other");const se=J[0]||void 0;console.log(`[DoshaResultsFull] Calling generate-impact for ${M}`,{originalProblemAreaIds:T,mappedProblemAreaIds:J,problemArea:b,problemAreaId:se,customProblemText:k,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:k,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),O(!1)})()},[b,T,k,h,d,E]),v.useEffect(()=>{g?.trackDoshaCalculatorResultPageView?.()},[g]);const $=E.shaniSadeSati??E.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"}],Pe=De.filter(y=>Ke(E[y.summaryKey])).length>0,ee=Ke(E.mangal)&&!Ir(E.mangal)||Ke(E.kaalSarp)||Ke(E.pitra)||Ke($)||Pe,te=[];for(const y of Fn){const K=y.summaryKey==="shaniSadeSati"?$:E[y.summaryKey];if(!Ke(K)||y.type==="mangal"&&Ir(K))continue;const z=E[y.severityKey],W=y.type==="shani"?E.shaniPhase??E.shaniPhase:void 0,V=qn(U,y.detailKey==="sadeSati"?"sadeSati":y.detailKey),M=V?.explanation,L=M&&!(h.toLowerCase().startsWith("hi")&&sc(M))?M:e(y.descKey),se=(V?.remedies??e(y.remediesKey)).split(`
171
- `).map(Te=>Te.trim()).filter(Boolean),le=e(y.benefitsKey).split(`
172
- `).map(Te=>Te.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)=>Wn(K.severity)-Wn(y.severity));const[he,Qe]=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(!Ke(E[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 ke=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(it,{className:"spiritual-glow border-2 border-primary/20 mx-4",children:[c.jsx(pt,{children:c.jsx(gt,{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(yt,{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(is,{className:"w-4 h-4 text-primary"}),c.jsxs("span",{className:"font-medium text-sm text-foreground",children:[y.label,": ",Hn(y.status,e)]})]},y.type))}):c.jsxs("div",{className:"text-center py-8",children:[c.jsx(kn,{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?ke(y.phase):"",V=Q[K%Q.length],M=e("drDoshaOf").replace("{{index}}",String(K+1)).replace("{{total}}",String(te.length));return c.jsxs(it,{className:`spiritual-glow border border-primary/10 mx-4 ${V}`,children:[c.jsx("div",{className:"px-4 pt-3",children:c.jsx(Nr,{variant:"outline",className:"text-xs font-normal text-muted-foreground",children:M})}),c.jsxs(pt,{className:"pb-3 pt-2",children:[c.jsxs(gt,{className:"flex items-center gap-3 text-xl",children:[c.jsx(z,{className:"w-6 h-6 text-primary"}),y.label]}),c.jsxs(Or,{children:[e("drSeverity"),": ",Gn(y.severity,e),y.phase!=null&&` • ${e("drPhase")}: ${y.phase}`]})]}),c.jsxs(yt,{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(Ar,{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")}),R?c.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[c.jsx(os,{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(os,{className:"w-6 h-6 text-primary animate-spin",size:24})}):(()=>{const L=rc(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(it,{className:"spiritual-glow mx-4",children:[c.jsxs(pt,{children:[c.jsx(gt,{className:"text-2xl font-bold text-center gradient-spiritual bg-clip-text text-transparent",children:e("drDetailedAnalysis")}),c.jsx(Or,{className:"text-center",children:e("drBasedOnChart")})]}),c.jsx(yt,{className:"space-y-4",children:c.jsx(Dn,{type:"single",collapsible:!0,className:"w-full space-y-4",children:Fn.map(y=>{const K=y.detailKey==="sadeSati"?"sadeSati":y.detailKey,z=y.summaryKey==="shaniSadeSati"?$:E[y.summaryKey],W=qn(U,y.detailKey==="sadeSati"?"sadeSati":y.detailKey),V=E[y.severityKey],M=y.type==="shani"?E.shaniPhase:void 0,L=y.icon,me=(W?.remedies?.trim()||e(y.remediesKey)).split(`
173
- `).map(le=>le.trim()).filter(Boolean);return c.jsxs($n,{value:K,className:"border border-border rounded-lg px-4",children:[c.jsx(Ln,{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"),": ",Hn(z,e),V&&!Ir(z)&&` • ${e("drSeverity")}: ${Gn(V,e)}`,y.type==="shani"&&M!=null&&` • ${e("drPhase")}: ${M}`]})]})]})}),c.jsxs(Un,{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,Te)=>c.jsx("li",{children:le},Te))})]}),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,Te)=>c.jsx("li",{children:le},Te))})]})]})]},K)})})})]}),c.jsxs(it,{className:"mx-4",children:[c.jsx(pt,{className:"cursor-pointer hover:bg-accent/5 transition-colors",onClick:()=>Qe(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(gt,{className:"text-xl font-semibold",children:e("drOtherDoshas")}),c.jsx(Or,{children:e(Pe?"drOtherDoshasStatusActive":"drOtherDoshasStatusNone")})]}),c.jsx(Sn,{className:`h-5 w-5 flex-shrink-0 text-muted-foreground transition-transform duration-200 ${he?"rotate-180":""}`})]})}),he&&c.jsx(yt,{children:c.jsx(Dn,{type:"single",collapsible:!0,className:"w-full space-y-2",children:De.map(y=>{const K=E[y.summaryKey],z=Ke(K),W=re[y.detailKey]??{},V=W.explanation,M=W.placements;return c.jsxs($n,{value:y.summaryKey,className:"border border-border rounded-lg px-3",children:[c.jsx(Ln,{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(Ar,{size:14,className:"text-muted-foreground flex-shrink-0"})]}),z?c.jsxs(Nr,{variant:"destructive",className:"flex-shrink-0 text-xs flex items-center gap-1 pointer-events-none",children:[c.jsx(is,{size:10}),e("drStatusPresent")]}):c.jsxs(Nr,{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(kn,{size:10,color:"#000000"}),e("drStatusAbsent")]})]})}),c.jsxs(Un,{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(Ar,{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(Ar,{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(is,{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(ml,{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(Kn,{birthDetails:u,supabase:d,language:h,t:e})}):null,fe.length>0&&c.jsxs(it,{className:"mt-4 bg-accent/10 border border-accent/30",children:[c.jsx(pt,{className:"pb-2",children:c.jsx(gt,{className:"text-base font-semibold",children:e("drPlanetaryPositionsCausing")})}),c.jsx(yt,{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:tc,defaultOpenIndex:0}),c.jsx(q.ContactUsSection,{title:e("contactTitle"),brandName:e("contactBrandName"),whatsAppLine:e("contactWhatsAppDomestic"),emailLine:e("contactEmail")})]})}const nc=Object.freeze(Object.defineProperty({__proto__:null,DoshaResultsFull:zn},Symbol.toStringTag,{value:"Module"}));function ac(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=Gl,G.DoshaFormSection=ls,G.DoshaResultsFull=zn,G.DoshaResultsView=Yl,G.FLOATING_CTA_STATUS=cr,G.I18nProvider=ll,G.KundaliCard=Kn,G.LOCALE_LABELS=il,G.SUPPORTED_LOCALES=al,G.SriMandirPujaVerticalCard=Pn,G.createGoogleMapsResolver=ac,G.createSupabaseClient=ln,G.fetchKundaliSvg=Bn,G.formatScheduleDate=yn,G.getCoverImageUrl=bn,G.getPujaLink=ns,G.getPujaTitle=ss,G.getTempleName=gn,G.insertSessionProblemStatements=Tn,G.invokeCalculateDosha=jn,G.submitDoshaCalculation=An,G.translations=vn,G.useGooglePlacesAutocomplete=En,G.useI18n=as,Object.defineProperty(G,Symbol.toStringTag,{value:"Module"})}));
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"})}));
175
175
  //# sourceMappingURL=dosha-calculator.umd.cjs.map