@srimandir/dosha-calculator 8.0.18 → 8.0.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dosha-calculator.js +1488 -1641
- package/dist/dosha-calculator.js.map +1 -1
- package/dist/dosha-calculator.umd.cjs +31 -31
- package/dist/dosha-calculator.umd.cjs.map +1 -1
- package/package.json +2 -2
|
@@ -1,47 +1,47 @@
|
|
|
1
|
-
(function(G,w){typeof exports=="object"&&typeof module<"u"?w(exports,require("react"),require("@srimandir/astrology-common")):typeof define=="function"&&define.amd?define(["exports","react","@srimandir/astrology-common"],w):(G=typeof globalThis<"u"?globalThis:G||self,w(G.DoshaCalculator={},G.React,G.AstrologyCommon))})(this,(function(G,w,q){"use strict";function
|
|
2
|
-
`+B+f}}var J=!1,se;{var me=typeof WeakMap=="function"?WeakMap:Map;se=new me}function le(f,
|
|
1
|
+
(function(G,w){typeof exports=="object"&&typeof module<"u"?w(exports,require("react"),require("@srimandir/astrology-common")):typeof define=="function"&&define.amd?define(["exports","react","@srimandir/astrology-common"],w):(G=typeof globalThis<"u"?globalThis:G||self,w(G.DoshaCalculator={},G.React,G.AstrologyCommon))})(this,(function(G,w,q){"use strict";function Oi(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,s.get?s:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const Ie=Oi(w);var mr={exports:{}},Wt={};var Ts;function Ci(){if(Ts)return Wt;Ts=1;var t=w,e=Symbol.for("react.element"),r=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,n=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function a(o,l,u){var d,h={},p=null,m=null;u!==void 0&&(p=""+u),l.key!==void 0&&(p=""+l.key),l.ref!==void 0&&(m=l.ref);for(d in l)s.call(l,d)&&!i.hasOwnProperty(d)&&(h[d]=l[d]);if(o&&o.defaultProps)for(d in l=o.defaultProps,l)h[d]===void 0&&(h[d]=l[d]);return{$$typeof:e,type:o,key:p,ref:m,props:h,_owner:n.current}}return Wt.Fragment=r,Wt.jsx=a,Wt.jsxs=a,Wt}var Ht={};var Es;function Ni(){return Es||(Es=1,process.env.NODE_ENV!=="production"&&(function(){var t=w,e=Symbol.for("react.element"),r=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),a=Symbol.for("react.provider"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),m=Symbol.for("react.offscreen"),g=Symbol.iterator,y="@@iterator";function x(f){if(f===null||typeof f!="object")return null;var S=g&&f[g]||f[y];return typeof S=="function"?S:null}var v=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function _(f){{for(var S=arguments.length,j=new Array(S>1?S-1:0),D=1;D<S;D++)j[D-1]=arguments[D];k("error",f,j)}}function k(f,S,j){{var D=v.ReactDebugCurrentFrame,Y=D.getStackAddendum();Y!==""&&(S+="%s",j=j.concat([Y]));var X=j.map(function(W){return String(W)});X.unshift("Warning: "+S),Function.prototype.apply.call(console[f],console,X)}}var O=!1,R=!1,M=!1,E=!1,$=!1,L;L=Symbol.for("react.module.reference");function $e(f){return!!(typeof f=="string"||typeof f=="function"||f===s||f===i||$||f===n||f===u||f===d||E||f===m||O||R||M||typeof f=="object"&&f!==null&&(f.$$typeof===p||f.$$typeof===h||f.$$typeof===a||f.$$typeof===o||f.$$typeof===l||f.$$typeof===L||f.getModuleId!==void 0))}function ge(f,S,j){var D=f.displayName;if(D)return D;var Y=S.displayName||S.name||"";return Y!==""?j+"("+Y+")":j}function Oe(f){return f.displayName||"Context"}function ee(f){if(f==null)return null;if(typeof f.tag=="number"&&_("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof f=="function")return f.displayName||f.name||null;if(typeof f=="string")return f;switch(f){case s:return"Fragment";case r:return"Portal";case i:return"Profiler";case n:return"StrictMode";case u:return"Suspense";case d:return"SuspenseList"}if(typeof f=="object")switch(f.$$typeof){case o:var S=f;return Oe(S)+".Consumer";case a:var j=f;return Oe(j._context)+".Provider";case l:return ge(f,f.render,"ForwardRef");case h:var D=f.displayName||null;return D!==null?D:ee(f.type)||"Memo";case p:{var Y=f,X=Y._payload,W=Y._init;try{return ee(W(X))}catch{return null}}}return null}var te=Object.assign,he=0,tt,Ce,re,fe,Se,Q,b;function F(){}F.__reactDisabledLog=!0;function z(){{if(he===0){tt=console.log,Ce=console.info,re=console.warn,fe=console.error,Se=console.group,Q=console.groupCollapsed,b=console.groupEnd;var f={configurable:!0,enumerable:!0,value:F,writable:!0};Object.defineProperties(console,{info:f,log:f,warn:f,error:f,group:f,groupCollapsed:f,groupEnd:f})}he++}}function H(){{if(he--,he===0){var f={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:te({},f,{value:tt}),info:te({},f,{value:Ce}),warn:te({},f,{value:re}),error:te({},f,{value:fe}),group:te({},f,{value:Se}),groupCollapsed:te({},f,{value:Q}),groupEnd:te({},f,{value:b})})}he<0&&_("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var V=v.ReactCurrentDispatcher,B;function U(f,S,j){{if(B===void 0)try{throw Error()}catch(Y){var D=Y.stack.trim().match(/\n( *(at )?)/);B=D&&D[1]||""}return`
|
|
2
|
+
`+B+f}}var J=!1,se;{var me=typeof WeakMap=="function"?WeakMap:Map;se=new me}function le(f,S){if(!f||J)return"";{var j=se.get(f);if(j!==void 0)return j}var D;J=!0;var Y=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var X;X=V.current,V.current=null,z();try{if(S){var W=function(){throw Error()};if(Object.defineProperty(W.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(W,[])}catch(Ne){D=Ne}Reflect.construct(f,[],W)}else{try{W.call()}catch(Ne){D=Ne}f.call(W.prototype)}}else{try{throw Error()}catch(Ne){D=Ne}f()}}catch(Ne){if(Ne&&D&&typeof Ne.stack=="string"){for(var K=Ne.stack.split(`
|
|
3
3
|
`),Ae=D.stack.split(`
|
|
4
4
|
`),ue=K.length-1,pe=Ae.length-1;ue>=1&&pe>=0&&K[ue]!==Ae[pe];)pe--;for(;ue>=1&&pe>=0;ue--,pe--)if(K[ue]!==Ae[pe]){if(ue!==1||pe!==1)do if(ue--,pe--,pe<0||K[ue]!==Ae[pe]){var Ge=`
|
|
5
|
-
`+K[ue].replace(" at new "," at ");return f.displayName&&Ge.includes("<anonymous>")&&(Ge=Ge.replace("<anonymous>",f.displayName)),typeof f=="function"&&se.set(f,Ge),Ge}while(ue>=1&&pe>=0);break}}}finally{J=!1,V.current=X,H(),Error.prepareStackTrace=Y}var
|
|
5
|
+
`+K[ue].replace(" at new "," at ");return f.displayName&&Ge.includes("<anonymous>")&&(Ge=Ge.replace("<anonymous>",f.displayName)),typeof f=="function"&&se.set(f,Ge),Ge}while(ue>=1&&pe>=0);break}}}finally{J=!1,V.current=X,H(),Error.prepareStackTrace=Y}var qt=f?f.displayName||f.name:"",jt=qt?U(qt):"";return typeof f=="function"&&se.set(f,jt),jt}function Ee(f,S,j){return le(f,!1)}function Kt(f){var S=f.prototype;return!!(S&&S.isReactComponent)}function We(f,S,j){if(f==null)return"";if(typeof f=="function")return le(f,Kt(f));if(typeof f=="string")return U(f);switch(f){case u:return U("Suspense");case d:return U("SuspenseList")}if(typeof f=="object")switch(f.$$typeof){case l:return Ee(f.render);case h:return We(f.type,S,j);case p:{var D=f,Y=D._payload,X=D._init;try{return We(X(Y),S,j)}catch{}}}return""}var Le=Object.prototype.hasOwnProperty,Tt={},Et=v.ReactDebugCurrentFrame;function ct(f){if(f){var S=f._owner,j=We(f.type,f._source,S?S.type:null);Et.setExtraStackFrame(j)}else Et.setExtraStackFrame(null)}function lr(f,S,j,D,Y){{var X=Function.call.bind(Le);for(var W in f)if(X(f,W)){var K=void 0;try{if(typeof f[W]!="function"){var Ae=Error((D||"React class")+": "+j+" type `"+W+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof f[W]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw Ae.name="Invariant Violation",Ae}K=f[W](S,W,D,j,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(ue){K=ue}K&&!(K instanceof Error)&&(ct(Y),_("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",D||"React class",j,W,typeof K),ct(null)),K instanceof Error&&!(K.message in Tt)&&(Tt[K.message]=!0,ct(Y),_("Failed %s type: %s",j,K.message),ct(null))}}}var A=Array.isArray;function I(f){return A(f)}function ae(f){{var S=typeof Symbol=="function"&&Symbol.toStringTag,j=S&&f[Symbol.toStringTag]||f.constructor.name||"Object";return j}}function Qe(f){try{return pt(f),!1}catch{return!0}}function pt(f){return""+f}function _e(f){if(Qe(f))return _("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",ae(f)),pt(f)}var ce=v.ReactCurrentOwner,je={key:!0,ref:!0,__self:!0,__source:!0},He,Me;function cr(f){if(Le.call(f,"ref")){var S=Object.getOwnPropertyDescriptor(f,"ref").get;if(S&&S.isReactWarning)return!1}return f.ref!==void 0}function N(f){if(Le.call(f,"key")){var S=Object.getOwnPropertyDescriptor(f,"key").get;if(S&&S.isReactWarning)return!1}return f.key!==void 0}function ne(f,S){typeof f.ref=="string"&&ce.current}function xe(f,S){{var j=function(){He||(He=!0,_("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",S))};j.isReactWarning=!0,Object.defineProperty(f,"key",{get:j,configurable:!0})}}function Te(f,S){{var j=function(){Me||(Me=!0,_("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",S))};j.isReactWarning=!0,Object.defineProperty(f,"ref",{get:j,configurable:!0})}}var ye=function(f,S,j,D,Y,X,W){var K={$$typeof:e,type:f,key:S,ref:j,props:W,_owner:X};return K._store={},Object.defineProperty(K._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(K,"_self",{configurable:!1,enumerable:!1,writable:!1,value:D}),Object.defineProperty(K,"_source",{configurable:!1,enumerable:!1,writable:!1,value:Y}),Object.freeze&&(Object.freeze(K.props),Object.freeze(K)),K};function ur(f,S,j,D,Y){{var X,W={},K=null,Ae=null;j!==void 0&&(_e(j),K=""+j),N(S)&&(_e(S.key),K=""+S.key),cr(S)&&(Ae=S.ref,ne(S,Y));for(X in S)Le.call(S,X)&&!je.hasOwnProperty(X)&&(W[X]=S[X]);if(f&&f.defaultProps){var ue=f.defaultProps;for(X in ue)W[X]===void 0&&(W[X]=ue[X])}if(K||Ae){var pe=typeof f=="function"?f.displayName||f.name||"Unknown":f;K&&xe(W,pe),Ae&&Te(W,pe)}return ye(f,K,Ae,Y,D,ce.current,W)}}var dr=v.ReactCurrentOwner,zr=v.ReactDebugCurrentFrame;function gt(f){if(f){var S=f._owner,j=We(f.type,f._source,S?S.type:null);zr.setExtraStackFrame(j)}else zr.setExtraStackFrame(null)}var hr;hr=!1;function Vr(f){return typeof f=="object"&&f!==null&&f.$$typeof===e}function Jr(){{if(dr.current){var f=ee(dr.current.type);if(f)return`
|
|
6
6
|
|
|
7
|
-
Check the render method of \``+f+"`."}return""}}function
|
|
7
|
+
Check the render method of \``+f+"`."}return""}}function Xc(f){return""}var Ti={};function Zc(f){{var S=Jr();if(!S){var j=typeof f=="string"?f:f.displayName||f.name;j&&(S=`
|
|
8
8
|
|
|
9
|
-
Check the top-level render call using <`+j+">.")}return
|
|
9
|
+
Check the top-level render call using <`+j+">.")}return S}}function Ei(f,S){{if(!f._store||f._store.validated||f.key!=null)return;f._store.validated=!0;var j=Zc(S);if(Ti[j])return;Ti[j]=!0;var D="";f&&f._owner&&f._owner!==dr.current&&(D=" It was passed a child from "+ee(f._owner.type)+"."),gt(f),_('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',j,D),gt(null)}}function ji(f,S){{if(typeof f!="object")return;if(I(f))for(var j=0;j<f.length;j++){var D=f[j];Vr(D)&&Ei(D,S)}else if(Vr(f))f._store&&(f._store.validated=!0);else if(f){var Y=x(f);if(typeof Y=="function"&&Y!==f.entries)for(var X=Y.call(f),W;!(W=X.next()).done;)Vr(W.value)&&Ei(W.value,S)}}}function eu(f){{var S=f.type;if(S==null||typeof S=="string")return;var j;if(typeof S=="function")j=S.propTypes;else if(typeof S=="object"&&(S.$$typeof===l||S.$$typeof===h))j=S.propTypes;else return;if(j){var D=ee(S);lr(j,f.props,"prop",D,f)}else if(S.PropTypes!==void 0&&!hr){hr=!0;var Y=ee(S);_("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",Y||"Unknown")}typeof S.getDefaultProps=="function"&&!S.getDefaultProps.isReactClassApproved&&_("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function tu(f){{for(var S=Object.keys(f.props),j=0;j<S.length;j++){var D=S[j];if(D!=="children"&&D!=="key"){gt(f),_("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",D),gt(null);break}}f.ref!==null&&(gt(f),_("Invalid attribute `ref` supplied to `React.Fragment`."),gt(null))}}var Ai={};function Pi(f,S,j,D,Y,X){{var W=$e(f);if(!W){var K="";(f===void 0||typeof f=="object"&&f!==null&&Object.keys(f).length===0)&&(K+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var Ae=Xc();Ae?K+=Ae:K+=Jr();var ue;f===null?ue="null":I(f)?ue="array":f!==void 0&&f.$$typeof===e?(ue="<"+(ee(f.type)||"Unknown")+" />",K=" Did you accidentally export a JSX literal instead of a component?"):ue=typeof f,_("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",ue,K)}var pe=ur(f,S,j,Y,X);if(pe==null)return pe;if(W){var Ge=S.children;if(Ge!==void 0)if(D)if(I(Ge)){for(var qt=0;qt<Ge.length;qt++)ji(Ge[qt],f);Object.freeze&&Object.freeze(Ge)}else _("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else ji(Ge,f)}if(Le.call(S,"key")){var jt=ee(f),Ne=Object.keys(S).filter(function(ou){return ou!=="key"}),xs=Ne.length>0?"{key: someKey, "+Ne.join(": ..., ")+": ...}":"{key: someKey}";if(!Ai[jt+xs]){var au=Ne.length>0?"{"+Ne.join(": ..., ")+": ...}":"{}";_(`A props object containing a "key" prop is being spread into JSX:
|
|
10
10
|
let props = %s;
|
|
11
11
|
<%s {...props} />
|
|
12
12
|
React keys must be passed directly to JSX without using spread:
|
|
13
13
|
let props = %s;
|
|
14
|
-
<%s key={someKey} {...props} />`,xs,
|
|
14
|
+
<%s key={someKey} {...props} />`,xs,jt,au,jt),Ai[jt+xs]=!0}}return f===s?tu(pe):eu(pe),pe}}function ru(f,S,j){return Pi(f,S,j,!0)}function su(f,S,j){return Pi(f,S,j,!1)}var nu=su,iu=ru;Ht.Fragment=s,Ht.jsx=nu,Ht.jsxs=iu})()),Ht}var js;function Ii(){return js||(js=1,process.env.NODE_ENV==="production"?mr.exports=Ci():mr.exports=Ni()),mr.exports}var c=Ii();const pr={all_fields_filled:"all_fields_filled",fields_not_filled:"fields_not_filled",puja_clicked:"puja_clicked"},Di=Symbol.for("@supabase/supabase-js.traceContextExtractor");function $i(){return globalThis[Di]}function gr(t,e){var r={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(r[s[n]]=t[s[n]]);return r}function Li(t,e,r,s){function n(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function o(d){try{u(s.next(d))}catch(h){a(h)}}function l(d){try{u(s.throw(d))}catch(h){a(h)}}function u(d){d.done?i(d.value):n(d.value).then(o,l)}u((s=s.apply(t,e||[])).next())})}typeof SuppressedError=="function"&&SuppressedError;const Mi=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class Yr extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class Ui extends Yr{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class As extends Yr{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Ps extends Yr{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Qr;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(Qr||(Qr={}));class Bi{constructor(e,{headers:r={},customFetch:s,region:n=Qr.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=Mi(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Li(this,arguments,void 0,function*(r,s={}){var n,i;let a,o,l;try{const{headers:u,method:d,body:h,signal:p,timeout:m}=s;let g={},{region:y}=s;y||(y=this.region);const x=new URL(`${this.url}/${r}`);y&&y!=="any"&&(g["x-region"]=y,x.searchParams.set("forceFunctionRegion",y));let v;const _=!!u&&Object.keys(u).some($=>$.toLowerCase()==="content-type");h&&!_?typeof Blob<"u"&&h instanceof Blob||h instanceof ArrayBuffer?(g["Content-Type"]="application/octet-stream",v=h):typeof h=="string"?(g["Content-Type"]="text/plain",v=h):typeof FormData<"u"&&h instanceof FormData?v=h:(g["Content-Type"]="application/json",v=JSON.stringify(h)):h&&typeof h!="string"&&!(typeof Blob<"u"&&h instanceof Blob)&&!(h instanceof ArrayBuffer)&&!(typeof FormData<"u"&&h instanceof FormData)?v=JSON.stringify(h):v=h;let k=p;m&&(o=new AbortController,a=setTimeout(()=>o.abort(),m),p?(k=o.signal,l=()=>o.abort(),p.addEventListener("abort",l)):k=o.signal);const O=yield this.fetch(x.toString(),{method:d||"POST",headers:Object.assign(Object.assign(Object.assign({},g),this.headers),u),body:v,signal:k}).catch($=>{throw new Ui($)}),R=O.headers.get("x-relay-error");if(R&&R==="true")throw new As(O);if(!O.ok)throw new Ps(O);let M=((n=O.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim().toLowerCase(),E;return M==="application/json"?E=yield O.json():M==="application/octet-stream"||M==="application/pdf"?E=yield O.blob():M==="text/event-stream"?E=O:M==="multipart/form-data"?E=yield O.formData():E=yield O.text(),{data:E,error:null,response:O}}catch(u){return{data:null,error:u,response:u instanceof Ps||u instanceof As?u.context:void 0}}finally{a&&clearTimeout(a),l&&((i=s.signal)===null||i===void 0||i.removeEventListener("abort",l))}})}}const Rs=3,Os=t=>Math.min(1e3*2**t,3e4),Fi=[520,503],Cs=["GET","HEAD","OPTIONS"];var Xr=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function Gt(t){"@babel/helpers - typeof";return Gt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Gt(t)}function Ki(t,e){if(Gt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(Gt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function qi(t){var e=Ki(t,"string");return Gt(e)=="symbol"?e:e+""}function Wi(t,e,r){return(e=qi(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Ns(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function At(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Ns(Object(r),!0).forEach(function(s){Wi(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Ns(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}function Is(t,e){return new Promise(r=>{if(e?.aborted){r();return}const s=setTimeout(()=>{e?.removeEventListener("abort",n),r()},t);function n(){clearTimeout(s),r()}e?.addEventListener("abort",n)})}function Hi(t,e,r,s){return!(!s||r>=Rs||!Cs.includes(t)||!Fi.includes(e))}var Gi=class{constructor(t){var e,r,s,n,i;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.shouldStripNulls=(s=t.shouldStripNulls)!==null&&s!==void 0?s:!1,this.urlLengthLimit=(n=t.urlLengthLimit)!==null&&n!==void 0?n:8e3,this.retryEnabled=(i=t.retry)!==null&&i!==void 0?i:!0,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}retry(t){return this.retryEnabled=t,this}then(t,e){var r=this;if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){const a=this.headers.get("Accept");a==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!a||a==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const s=this.fetch;let i=(async()=>{let a=0;for(;;){const u={};r.headers.forEach((h,p)=>{u[p]=h}),a>0&&(u["X-Retry-Count"]=String(a));let d;try{d=await s(r.url.toString(),{method:r.method,headers:u,body:JSON.stringify(r.body,(h,p)=>typeof p=="bigint"?p.toString():p),signal:r.signal})}catch(h){if(h?.name==="AbortError"||h?.code==="ABORT_ERR"||!Cs.includes(r.method))throw h;if(r.retryEnabled&&a<Rs){const p=Os(a);a++,await Is(p,r.signal);continue}throw h}if(Hi(r.method,d.status,a,r.retryEnabled)){var o,l;const h=(o=(l=d.headers)===null||l===void 0?void 0:l.get("Retry-After"))!==null&&o!==void 0?o:null,p=h!==null?Math.max(0,parseInt(h,10)||0)*1e3:Os(a);await d.text(),a++,await Is(p,r.signal);continue}return await r.processResponse(d)}})();return this.shouldThrowOnError||(i=i.catch(a=>{var o;let l="",u="",d="";const h=a?.cause;if(h){var p,m,g,y;const _=(p=h?.message)!==null&&p!==void 0?p:"",k=(m=h?.code)!==null&&m!==void 0?m:"";l=`${(g=a?.name)!==null&&g!==void 0?g:"FetchError"}: ${a?.message}`,l+=`
|
|
15
15
|
|
|
16
|
-
Caused by: ${(y=h?.name)!==null&&y!==void 0?y:"Error"}: ${
|
|
17
|
-
${h.stack}`)}else{var _;l=(_=a?.stack)!==null&&_!==void 0?_:""}const b=this.url.toString().length;return a?.name==="AbortError"||a?.code==="ABORT_ERR"?(d="",u="Request was aborted (timeout or manual cancellation)",b>this.urlLengthLimit&&(u+=`. Note: Your request URL is ${b} 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)",b>this.urlLengthLimit&&(u+=`. Your request URL is ${b} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${(o=a?.name)!==null&&o!==void 0?o:"FetchError"}: ${a?.message}`,details:l,hint:u,code:d},data:null,count:null,status:0,statusText:""}})),i.then(t,e)}async processResponse(t){var e=this;let r=null,s=null,n=null,i=t.status,a=t.statusText;if(t.ok){var o,l;if(e.method!=="HEAD"){var u;const m=await t.text();if(m!=="")if(e.headers.get("Accept")==="text/csv")s=m;else if(e.headers.get("Accept")&&(!((u=e.headers.get("Accept"))===null||u===void 0)&&u.includes("application/vnd.pgrst.plan+text")))s=m;else try{s=JSON.parse(m)}catch{if(r={message:m},s=null,e.shouldThrowOnError)throw new Pt({message:m,details:"",hint:"",code:""})}}const h=(o=e.headers.get("Prefer"))===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),p=(l=t.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");if(h&&p&&p.length>1&&(n=parseInt(p[1])),e.isMaybeSingle&&Array.isArray(s))if(s.length>1){if(r={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,n=null,i=406,a="Not Acceptable",e.shouldThrowOnError){var d;throw new Pt(yt(yt({},r),{},{hint:(d=r.hint)!==null&&d!==void 0?d:""}))}}else s.length===1?s=s[0]:s=null}else{const h=await t.text();try{r=JSON.parse(h),Array.isArray(r)&&t.status===404&&(s=[],r=null,i=200,a="OK")}catch{t.status===404&&h===""?(i=204,a="No Content"):r={message:h}}if(r&&e.shouldThrowOnError)throw new Pt(r)}return{success:r===null,error:r,data:s,count:n,status:i,statusText:a}}returns(){return this}overrideTypes(){return this}},Ji=class extends Vi{throwOnError(){return super.throwOnError()}select(t){let e=!1;const r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){const i=n?`${n}.order`:"order",a=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${a?`${a},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){const s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){const n=typeof s>"u"?"offset":`${s}.offset`,i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(i,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:i="text"}={}){var a;const o=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${o};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}};const $s=new RegExp("[,()]");var Rt=class extends Ji{throwOnError(){return super.throwOnError()}eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&$s.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"&&$s.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");const i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${i}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Yi=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:n=8e3,retry:i}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=s,this.urlLengthLimit=n,this.retry=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){const{head:r=!1,count:s}=e??{},n=r?"HEAD":"GET";let i=!1;const a=(t??"*").split("").map(u=>/\s/.test(u)&&!i?"":(u==='"'&&(i=!i),u)).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",a),s&&l.append("Prefer",`count=${s}`),new Rt({method:n,url:o,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;const n="POST",{url:i,headers:a}=this.cloneRequestState();if(e&&a.append("Prefer",`count=${e}`),r||a.append("Prefer","missing=default"),Array.isArray(t)){const o=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(o.length>0){const l=[...new Set(o)].map(u=>`"${u}"`);i.searchParams.set("columns",l.join(","))}}return new Rt({method:n,url:i,headers:a,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var i;const a="POST",{url:o,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&l.append("Prefer",`count=${s}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){const u=t.reduce((d,h)=>d.concat(Object.keys(h)),[]);if(u.length>0){const d=[...new Set(u)].map(h=>`"${h}"`);o.searchParams.set("columns",d.join(","))}}return new Rt({method:a,url:o,headers:l,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var r;const s="PATCH",{url:n,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Rt({method:s,url:n,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:t}={}){var e;const r="DELETE",{url:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new Rt({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 Qi(t,e){try{const a=JSON.parse(t);if(a&&typeof a=="object"&&!Array.isArray(a)){var r,s,n,i;return new Pt({message:String((r=a.message)!==null&&r!==void 0?r:t),details:(s=a.details)!==null&&s!==void 0?s:"",hint:(n=a.hint)!==null&&n!==void 0?n:"",code:(i=a.code)!==null&&i!==void 0?i:""})}}catch{}return new Pt({message:t||e,details:"",hint:"",code:""})}function Ls(t,e,r){var s;const n=t;return{success:!1,error:new Pt({message:`${(s=n?.name)!==null&&s!==void 0?s:"FetchError"}: ${n?.message}`,details:"",hint:"",code:""}),data:null,count:null,status:e,statusText:r}}var Xi=class Ci{constructor(e,{headers:r={},schema:s,fetch:n,timeout:i,urlLengthLimit:a=8e3,retry:o}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.urlLengthLimit=a;const l=n??globalThis.fetch;i!==void 0&&i>0?this.fetch=(u,d)=>{const h=new AbortController,p=setTimeout(()=>h.abort(),i),m=d?.signal;if(m){if(m.aborted)return clearTimeout(p),l(u,d);const g=()=>{clearTimeout(p),h.abort()};return m.addEventListener("abort",g,{once:!0}),l(u,yt(yt({},d),{},{signal:h.signal})).finally(()=>{clearTimeout(p),m.removeEventListener("abort",g)})}return l(u,yt(yt({},d),{},{signal:h.signal})).finally(()=>clearTimeout(p))}:this.fetch=l,this.retry=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Yi(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 Ci(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}async getOpenApiSpec(){var e=this,r;const s=new Headers(e.headers);s.set("Accept","application/openapi+json"),e.schemaName&&s.set("Accept-Profile",e.schemaName);const n={};s.forEach((u,d)=>{n[d]=u});const i=(r=e.fetch)!==null&&r!==void 0?r:globalThis.fetch;let a;try{var o;a=await Ds(i,`${e.url}/`,{method:"GET",headers:n},(o=e.retry)!==null&&o!==void 0?o:!0)}catch(u){return Ls(u,0,"")}let l;try{l=await a.text()}catch(u){return Ls(u,a.status,a.statusText)}if(a.ok)try{return{success:!0,error:null,data:JSON.parse(l),count:null,status:a.status,statusText:a.statusText}}catch{}return{success:!1,error:Qi(l,a.statusText),data:null,count:null,status:a.status,statusText:a.statusText}}rpc(e,r={},{head:s=!1,get:n=!1,count:i}={}){var a;let o;const l=new URL(`${this.url}/rpc/${e}`);let u;const d=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(d)),h=s&&Object.values(r).some(d);h?(o="POST",u=r):s||n?(o=s?"HEAD":"GET",Object.entries(r).filter(([m,g])=>g!==void 0).map(([m,g])=>[m,Array.isArray(g)?`{${g.join(",")}}`:`${g}`]).forEach(([m,g])=>{l.searchParams.append(m,g)})):(o="POST",u=r);const p=new Headers(this.headers);return h?p.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&p.set("Prefer",`count=${i}`),new Rt({method:o,url:l,headers:p,schema:this.schemaName,body:u,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class Zi{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};const r=globalThis;if(typeof globalThis<"u"&&typeof r.WebSocket<"u")return{type:"native",wsConstructor:r.WebSocket};const s=typeof global<"u"?global:void 0;if(s&&typeof s.WebSocket<"u")return{type:"native",wsConstructor:s.WebSocket};if(typeof globalThis<"u"&&typeof r.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&r.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const n=globalThis.process;if(n){const i=n.versions;if(i&&i.node)return{type:"unsupported",error:"Node.js detected but native WebSocket not found.",workaround:"Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option."}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
|
|
16
|
+
Caused by: ${(y=h?.name)!==null&&y!==void 0?y:"Error"}: ${_}`,k&&(l+=` (${k})`),h?.stack&&(l+=`
|
|
17
|
+
${h.stack}`)}else{var x;l=(x=a?.stack)!==null&&x!==void 0?x:""}const v=this.url.toString().length;return a?.name==="AbortError"||a?.code==="ABORT_ERR"?(d="",u="Request was aborted (timeout or manual cancellation)",v>this.urlLengthLimit&&(u+=`. Note: Your request URL is ${v} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(h?.name==="HeadersOverflowError"||h?.code==="UND_ERR_HEADERS_OVERFLOW")&&(d="",u="HTTP headers exceeded server limits (typically 16KB)",v>this.urlLengthLimit&&(u+=`. Your request URL is ${v} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${(o=a?.name)!==null&&o!==void 0?o:"FetchError"}: ${a?.message}`,details:l,hint:u,code:d},data:null,count:null,status:0,statusText:""}})),i.then(t,e)}async processResponse(t){var e=this;let r=null,s=null,n=null,i=t.status,a=t.statusText;if(t.ok){var o,l;if(e.method!=="HEAD"){var u;const m=await t.text();if(m!=="")if(e.headers.get("Accept")==="text/csv")s=m;else if(e.headers.get("Accept")&&(!((u=e.headers.get("Accept"))===null||u===void 0)&&u.includes("application/vnd.pgrst.plan+text")))s=m;else try{s=JSON.parse(m)}catch{if(r={message:m},s=null,e.shouldThrowOnError)throw new Xr({message:m,details:"",hint:"",code:""})}}const h=(o=e.headers.get("Prefer"))===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),p=(l=t.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");if(h&&p&&p.length>1&&(n=parseInt(p[1])),e.isMaybeSingle&&Array.isArray(s))if(s.length>1){if(r={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,n=null,i=406,a="Not Acceptable",e.shouldThrowOnError){var d;throw new Xr(At(At({},r),{},{hint:(d=r.hint)!==null&&d!==void 0?d:""}))}}else s.length===1?s=s[0]:s=null}else{const h=await t.text();try{r=JSON.parse(h),Array.isArray(r)&&t.status===404&&(s=[],r=null,i=200,a="OK")}catch{t.status===404&&h===""?(i=204,a="No Content"):r={message:h}}if(r&&e.shouldThrowOnError)throw new Xr(r)}return{success:r===null,error:r,data:s,count:n,status:i,statusText:a}}returns(){return this}overrideTypes(){return this}},zi=class extends Gi{throwOnError(){return super.throwOnError()}select(t){let e=!1;const r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){const i=n?`${n}.order`:"order",a=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${a?`${a},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){const s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){const n=typeof s>"u"?"offset":`${s}.offset`,i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(i,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:i="text"}={}){var a;const o=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${o};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}};const Ds=new RegExp("[,()]");var Pt=class extends zi{throwOnError(){return super.throwOnError()}eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&Ds.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&Ds.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");const i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${i}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Vi=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:n=8e3,retry:i}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=s,this.urlLengthLimit=n,this.retry=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){const{head:r=!1,count:s}=e??{},n=r?"HEAD":"GET";let i=!1;const a=(t??"*").split("").map(u=>/\s/.test(u)&&!i?"":(u==='"'&&(i=!i),u)).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",a),s&&l.append("Prefer",`count=${s}`),new Pt({method:n,url:o,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;const n="POST",{url:i,headers:a}=this.cloneRequestState();if(e&&a.append("Prefer",`count=${e}`),r||a.append("Prefer","missing=default"),Array.isArray(t)){const o=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(o.length>0){const l=[...new Set(o)].map(u=>`"${u}"`);i.searchParams.set("columns",l.join(","))}}return new Pt({method:n,url:i,headers:a,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var i;const a="POST",{url:o,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&l.append("Prefer",`count=${s}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){const u=t.reduce((d,h)=>d.concat(Object.keys(h)),[]);if(u.length>0){const d=[...new Set(u)].map(h=>`"${h}"`);o.searchParams.set("columns",d.join(","))}}return new Pt({method:a,url:o,headers:l,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var r;const s="PATCH",{url:n,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Pt({method:s,url:n,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:t}={}){var e;const r="DELETE",{url:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new Pt({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}},Ji=class Ri{constructor(e,{headers:r={},schema:s,fetch:n,timeout:i,urlLengthLimit:a=8e3,retry:o}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.urlLengthLimit=a;const l=n??globalThis.fetch;i!==void 0&&i>0?this.fetch=(u,d)=>{const h=new AbortController,p=setTimeout(()=>h.abort(),i),m=d?.signal;if(m){if(m.aborted)return clearTimeout(p),l(u,d);const g=()=>{clearTimeout(p),h.abort()};return m.addEventListener("abort",g,{once:!0}),l(u,At(At({},d),{},{signal:h.signal})).finally(()=>{clearTimeout(p),m.removeEventListener("abort",g)})}return l(u,At(At({},d),{},{signal:h.signal})).finally(()=>clearTimeout(p))}:this.fetch=l,this.retry=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Vi(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new Ri(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,r={},{head:s=!1,get:n=!1,count:i}={}){var a;let o;const l=new URL(`${this.url}/rpc/${e}`);let u;const d=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(d)),h=s&&Object.values(r).some(d);h?(o="POST",u=r):s||n?(o=s?"HEAD":"GET",Object.entries(r).filter(([m,g])=>g!==void 0).map(([m,g])=>[m,Array.isArray(g)?`{${g.join(",")}}`:`${g}`]).forEach(([m,g])=>{l.searchParams.append(m,g)})):(o="POST",u=r);const p=new Headers(this.headers);return h?p.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&p.set("Prefer",`count=${i}`),new Pt({method:o,url:l,headers:p,schema:this.schemaName,body:u,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class Yi{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};const r=globalThis;if(typeof globalThis<"u"&&typeof r.WebSocket<"u")return{type:"native",wsConstructor:r.WebSocket};const s=typeof global<"u"?global:void 0;if(s&&typeof s.WebSocket<"u")return{type:"native",wsConstructor:s.WebSocket};if(typeof globalThis<"u"&&typeof r.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&r.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const n=globalThis.process;if(n){const i=n.versions;if(i&&i.node)return{type:"unsupported",error:"Node.js detected but native WebSocket not found.",workaround:"Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option."}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
|
|
18
18
|
|
|
19
|
-
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{return this.detectEnvironment().type==="native"}catch{return!1}}}const ea="realtime-js/2.115.0",ta="1.0.0",Ms="2.0.0",ra=Ms,sa=1e4,na=15e3,ia=1e4,aa=100,ut={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Us={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},Zr={connecting:"connecting",closing:"closing",closed:"closed"};class oa{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:{},a=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,a)}_encodeUserBroadcastPush(e,r,s){var n,i;const a=new TextEncoder,o=a.encode(e.topic),l=a.encode((n=e.ref)!==null&&n!==void 0?n:""),u=a.encode((i=e.join_ref)!==null&&i!==void 0?i:""),d=a.encode(e.payload.event),h=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},p=a.encode(Object.keys(h).length===0?"":JSON.stringify(h));if(u.length>255)throw new Error(`joinRef length ${u.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`ref length ${l.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`userEvent length ${d.length} exceeds maximum of 255`);if(p.length>255)throw new Error(`metadata length ${p.length} exceeds maximum of 255`);const m=this.USER_BROADCAST_PUSH_META_LENGTH+u.length+l.length+o.length+d.length+p.length,g=new ArrayBuffer(this.HEADER_LENGTH+m),y=new DataView(g),_=new Uint8Array(g);let b=0;y.setUint8(b++,this.KINDS.userBroadcastPush),y.setUint8(b++,u.length),y.setUint8(b++,l.length),y.setUint8(b++,o.length),y.setUint8(b++,d.length),y.setUint8(b++,p.length),y.setUint8(b++,r),_.set(u,b),b+=u.length,_.set(l,b),b+=l.length,_.set(o,b),b+=o.length,_.set(d,b),b+=d.length,_.set(p,b),b+=p.length;var k=new Uint8Array(g.byteLength+s.byteLength);return k.set(new Uint8Array(g),0),k.set(new Uint8Array(s),g.byteLength),k.buffer}decode(e,r){if(this._isArrayBuffer(e)){let s=this._binaryDecode(e);return r(s)}if(typeof e=="string"){const s=JSON.parse(e),[n,i,a,o,l]=s;return r({join_ref:n,ref:i,topic:a,event:o,payload:l})}return r({})}_binaryDecode(e){const r=new DataView(e),s=r.getUint8(0),n=new TextDecoder;if(s===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,n)}_decodeUserBroadcast(e,r,s){const n=r.getUint8(1),i=r.getUint8(2),a=r.getUint8(3),o=r.getUint8(4);let l=this.HEADER_LENGTH+4;const u=s.decode(e.slice(l,l+n));l=l+n;const d=s.decode(e.slice(l,l+i));l=l+i;const h=s.decode(e.slice(l,l+a));l=l+a;const p=e.slice(l,e.byteLength),m=o===this.JSON_ENCODING?JSON.parse(s.decode(p)):p,g={type:this.BROADCAST_EVENT,event:d,payload:m};return a>0&&(g.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:g}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([s])=>r.includes(s)))}}var Z;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(Z||(Z={}));const Bs=(t,e,r={})=>{var s;const n=(s=r.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((i,a)=>(i[a]=la(a,t,e,n),i),{}):{}},la=(t,e,r,s)=>{const n=e.find(o=>o.name===t),i=n?.type,a=r[t];return i&&!s.includes(i)?Fs(i,a):es(a)},Fs=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return ha(e,r)}switch(t){case Z.bool:return ca(e);case Z.float4:case Z.float8:case Z.int2:case Z.int4:case Z.int8:case Z.numeric:case Z.oid:return ua(e);case Z.json:case Z.jsonb:return da(e);case Z.timestamp:return fa(e);case Z.abstime:case Z.date:case Z.daterange:case Z.int4range:case Z.int8range:case Z.money:case Z.reltime:case Z.text:case Z.time:case Z.timestamptz:case Z.timetz:case Z.tsrange:case Z.tstzrange:return es(e);default:return es(e)}},es=t=>t,ca=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},ua=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},da=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},ha=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,s=t[r];if(t[0]==="{"&&s==="}"){let i;const a=t.slice(1,r);try{i=JSON.parse("["+a+"]")}catch{i=a?a.split(","):[]}return i.map(o=>Fs(e,o))}return t},fa=t=>typeof t=="string"?t.replace(" ","T"):t,Ks=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 Ot=t=>typeof t=="function"?t:function(){return t},ma=typeof self<"u"?self:null,Ct=typeof window<"u"?window:null,Xe=ma||Ct||globalThis,pa="2.0.0",ga=1e4,ya=1e3,ba=100,Ze={connecting:0,open:1,closing:2,closed:3},Pe={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},rt={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},ts={longpoll:"longpoll",websocket:"websocket"},va={complete:4},rs="base64url.bearer.phx.",br=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})}},qs=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=Ot(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new br(this,rt.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new qs(()=>{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 br(this,rt.leave,Ot({}),this.timeout).send(),this.state=Pe.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(rt.reply,(s,n)=>{this.trigger(this.replyEventName(n),s)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Pe.closed,this.bindings=[]}onClose(t){this.on(rt.close,t)}onError(t){return this.on(rt.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new br(this,t,function(){return e},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Pe.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(rt.close,"leave")},r=new br(this,rt.leave,Ot({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,s){return this.topic!==t?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Pe.joining,this.joinPush.resend(t))}trigger(t,e,r,s){let n=this.onMessage(t,e,r,s);if(e&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let i=this.bindings.filter(a=>a.event===t&&this.filterBindings(a,e,r));for(let a=0;a<i.length;a++)i[a].callback(n,r,s||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===Pe.closed}isErrored(){return this.state===Pe.errored}isJoined(){return this.state===Pe.joined}isJoining(){return this.state===Pe.joining}isLeaving(){return this.state===Pe.leaving}},vr=class{static request(t,e,r,s,n,i,a){if(Xe.XDomainRequest){let o=new Xe.XDomainRequest;return this.xdomainRequest(o,t,e,s,n,i,a)}else if(Xe.XMLHttpRequest){let o=new Xe.XMLHttpRequest;return this.xhrRequest(o,t,e,r,s,n,i,a)}else{if(Xe.fetch&&Xe.AbortController)return this.fetchRequest(t,e,r,s,n,i,a);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,s,n,i,a){let o={method:t,headers:r,body:s},l=null;return n&&(l=new AbortController,setTimeout(()=>l.abort(),n),o.signal=l.signal),Xe.fetch(e,o).then(u=>u.text()).then(u=>this.parseJSON(u)).then(u=>a&&a(u)).catch(u=>{u.name==="AbortError"&&i?i():a&&a(null)}),l}static xdomainRequest(t,e,r,s,n,i,a){return t.timeout=n,t.open(e,r),t.onload=()=>{let o=this.parseJSON(t.responseText);a&&a(o)},i&&(t.ontimeout=i),t.onprogress=()=>{},t.send(s),t}static xhrRequest(t,e,r,s,n,i,a,o){t.open(e,r,!0),t.timeout=i;for(let[l,u]of Object.entries(s))t.setRequestHeader(l,u);return t.onerror=()=>o&&o(null),t.onreadystatechange=()=>{if(t.readyState===va.complete&&o){let l=this.parseJSON(t.responseText);o(l)}},a&&(t.ontimeout=a),t.send(n),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let n=e?`${e}[${s}]`:s,i=t[s];typeof i=="object"?r.push(this.serialize(i,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},_a=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)},Nt=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(rs)&&(this.authToken=atob(e[1].slice(rs.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=Ze.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+ts.websocket),"$1/"+ts.longpoll)}endpointURL(){return vr.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=Ze.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Ze.open||this.readyState===Ze.connecting}poll(){const t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:s,messages:n}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=s}else r=0;switch(r){case 200:n.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=Ze.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=_a(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t,e=0){this.awaitingBatchAck=!0;const r=e+ba,s=t.slice(e,r);this.ajax("POST",{"Content-Type":"application/x-ndjson"},s.join(`
|
|
20
|
-
`),()=>this.onerror("timeout"),n=>{!n||n.status!==200?(this.awaitingBatchAck=!1,this.onerror(n&&n.status),this.closeAndRetry(1011,"internal server error",!1)):r<t.length?this.batchSend(t,r):this.batchBuffer.length>0?(this.batchSend(this.batchBuffer),this.batchBuffer=[]):this.awaitingBatchAck=!1})}close(t,e,r){for(let n of this.reqs)n.abort();this.readyState=Ze.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(t,e,r,s,n){let i,a=()=>{this.reqs.delete(i),s()};i=vr.request(t,this.endpointURL(),e,r,this.timeout,a,o=>{this.reqs.delete(i),this.isActive()&&n(o)}),this.reqs.add(i)}},ka=class mr{constructor(e,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state=Object.create(null),this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,n=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.joinRef=this.channel.joinRef(),this.state=mr.syncState(this.state,n,i,a),this.pendingDiffs.forEach(l=>{this.state=mr.syncDiff(this.state,l,i,a)}),this.pendingDiffs=[],o()}),this.channel.on(s.diff,n=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=mr.syncDiff(this.state,n,i,a),o())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return mr.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,s,n){let i=this.toNullProtoObj(this.clone(e));r=this.toNullProtoObj(r);let a=Object.create(null),o=Object.create(null);return this.map(i,(l,u)=>{r[l]||(o[l]=u)}),this.map(r,(l,u)=>{let d=i[l];if(d){let h=u.metas.map(y=>y.phx_ref),p=d.metas.map(y=>y.phx_ref),m=u.metas.filter(y=>p.indexOf(y.phx_ref)<0),g=d.metas.filter(y=>h.indexOf(y.phx_ref)<0);m.length>0&&(a[l]=u,a[l].metas=m),g.length>0&&(o[l]=this.clone(d),o[l].metas=g)}else a[l]=u}),this.syncDiff(i,{joins:a,leaves:o},s,n)}static syncDiff(e,r,s,n){e=this.toNullProtoObj(e);let{joins:i,leaves:a}=this.clone(r);return s||(s=function(){}),n||(n=function(){}),this.map(i,(o,l)=>{let u=e[o];if(e[o]=this.clone(l),u){let d=e[o].metas.map(p=>p.phx_ref),h=u.metas.filter(p=>d.indexOf(p.phx_ref)<0);e[o].metas.unshift(...h)}s(o,u,l)}),this.map(a,(o,l)=>{let u=e[o];if(!u)return;let d=l.metas.map(h=>h.phx_ref);u.metas=u.metas.filter(h=>d.indexOf(h.phx_ref)<0),n(o,u,l),u.metas.length===0&&delete e[o]}),e}static list(e,r){return r||(r=function(s,n){return n}),this.map(e,(s,n)=>r(s,n))}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static toNullProtoObj(e){if(Object.getPrototypeOf(e)===null)return e;let r=Object.create(null);return Object.getOwnPropertyNames(e).forEach(s=>{r[s]=e[s]}),r}static clone(e){return JSON.parse(JSON.stringify(e))}},wr={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,s,n,i,a]=JSON.parse(t);return e({join_ref:r,ref:s,topic:n,event:i,payload:a})}},binaryEncode(t){let{join_ref:e,ref:r,event:s,topic:n,payload:i}=t,a=new TextEncoder,o=a.encode(e),l=a.encode(r),u=a.encode(n),d=a.encode(s);this.assertFieldSize(o.byteLength,"join_ref"),this.assertFieldSize(l.byteLength,"ref"),this.assertFieldSize(u.byteLength,"topic"),this.assertFieldSize(d.byteLength,"event");let h=this.META_LENGTH+o.byteLength+l.byteLength+u.byteLength+d.byteLength,p=new ArrayBuffer(this.HEADER_LENGTH+h),m=new Uint8Array(p),g=new DataView(p),y=0;g.setUint8(y++,this.KINDS.push),g.setUint8(y++,o.byteLength),g.setUint8(y++,l.byteLength),g.setUint8(y++,u.byteLength),g.setUint8(y++,d.byteLength),m.set(o,y),y+=o.byteLength,m.set(l,y),y+=l.byteLength,m.set(u,y),y+=u.byteLength,m.set(d,y),y+=d.byteLength;var _=new Uint8Array(p.byteLength+i.byteLength);return _.set(m,0),_.set(new Uint8Array(i),p.byteLength),_.buffer},assertFieldSize(t,e){if(t>255)throw new Error(`unable to convert ${e} to binary: must be less than or equal to 255 bytes, but is ${t} bytes`)},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,s);case this.KINDS.reply:return this.decodeReply(t,e,s);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,s)}},decodePush(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(t.slice(a,a+s));a=a+s;let l=r.decode(t.slice(a,a+n));a=a+n;let u=r.decode(t.slice(a,a+i));a=a+i;let d=t.slice(a,t.byteLength);return{join_ref:o,ref:null,topic:l,event:u,payload:d}},decodeReply(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),a=e.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(o,o+s));o=o+s;let u=r.decode(t.slice(o,o+n));o=o+n;let d=r.decode(t.slice(o,o+i));o=o+i;let h=r.decode(t.slice(o,o+a));o=o+a;let p=t.slice(o,t.byteLength),m={status:h,response:p};return{join_ref:l,ref:u,topic:d,event:rt.reply,payload:m}},decodeBroadcast(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=this.HEADER_LENGTH+2,a=r.decode(t.slice(i,i+s));i=i+s;let o=r.decode(t.slice(i,i+n));i=i+n;let l=t.slice(i,t.byteLength);return{join_ref:null,ref:null,topic:a,event:o,payload:l}}},Sa=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||ga,this.transport=e.transport||Xe.WebSocket||Nt,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null;let r=null;try{r=Xe&&Xe.sessionStorage}catch{}this.sessionStore=e.sessionStorage||r,this.establishedConnections=0,this.defaultEncoder=wr.encode.bind(wr),this.defaultDecoder=wr.decode.bind(wr),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!==Nt?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let s=null;Ct&&Ct.addEventListener&&(Ct.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),s=this.connectClock)}),Ct.addEventListener("pageshow",n=>{s===this.connectClock&&(s=null,this.connect())}),Ct.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(n,i,a)=>{console.log(`${n}: ${i}`,a)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Ot(e.params||{}),this.endPoint=`${t}/${ts.websocket}`,this.vsn=e.vsn||pa,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new qs(()=>{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&&Ot(e.authToken)}getLongPollTransport(){return Nt}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=vr.appendParams(vr.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=Ot(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Nt?this.connectWithFallback(Nt,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===Nt?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${rs}${btoa(this.authToken()).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,s=!0,n,i,a=this.transportName(t),o=l=>{this.log("transport",`falling back to ${a}...`,l),this.off([n,i]),s=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${a}`))return o("memorized");this.fallbackTimer=setTimeout(o,e),i=this.onError(l=>{this.log("transport","error",l),s&&!r&&(clearTimeout(this.fallbackTimer),o(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!s){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),ya,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();const s=this.conn;this.waitForBufferDone(s,()=>{e?s.close(e,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===Ze.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(t),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport","error",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError(t)}triggerChanError(t){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(rt.error,t)})}connectionState(){switch(this.conn&&this.conn.readyState){case Ze.connecting:return"connecting";case Ze.open:return"open";case Ze.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new 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:i}=t;this.log("push",`${e} ${r} (${i}, ${n})`,s)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:s,payload:n,ref:i,join_ref:a}=e;if(i&&i===this.pendingHeartbeatRef){const o=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(n.status==="ok"?"ok":"error",o)}catch(l){this.log("error","error in heartbeat callback",l)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${n.status||""} ${r} ${s} ${i&&"("+i+")"||""}`.trim(),n);for(let o=0;o<this.channels.length;o++){const l=this.channels[o];l.isMember(r,s,n,a)&&l.trigger(s,n,i,a)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,s])=>{try{s(...e)}catch(n){this.log("error",`error in ${t} callback`,n)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};class Vt{constructor(e,r){const s=Ta(r);this.presence=new ka(e.getChannel(),s),this.presence.onJoin((n,i,a)=>{const o=Vt.onJoinPayload(n,i,a);e.getChannel().trigger("presence",o)}),this.presence.onLeave((n,i,a)=>{const o=Vt.onLeavePayload(n,i,a);e.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return Vt.transformState(this.presence.state)}static transformState(e){return e=xa(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{const n=e[s];return r[s]=_r(n),r},{})}static onJoinPayload(e,r,s){const n=Ws(r),i=_r(s);return{event:"join",key:e,currentPresences:n,newPresences:i}}static onLeavePayload(e,r,s){const n=Ws(r),i=_r(s);return{event:"leave",key:e,currentPresences:n,leftPresences:i}}}function _r(t){return t.metas.map(e=>{const r=Object.getOwnPropertyDescriptors(e),s=Object.defineProperties({},r);return s.presence_ref=s.phx_ref,delete s.phx_ref,delete s.phx_ref_prev,s})}function xa(t){return JSON.parse(JSON.stringify(t))}function Ta(t){return t?.events&&{events:t.events}}function Ws(t){return t?.metas?_r(t):[]}var Hs;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Hs||(Hs={}));class Ea{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Vt(this.channel.channelAdapter,r)}}function ja(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 Aa{constructor(e,r,s){const n=Pa(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>aa){const i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return n}updateJoinPayload(e){const r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===ut.joined}isJoined(){return this.state===ut.joined}isJoining(){return this.state===ut.joining}isClosed(){return this.state===ut.closed}isLeaving(){return this.state===ut.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function Pa(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}const Ra=/[,()"\\]/,Oa=t=>Ra.test(t)||t!==t.trim(),Ca=t=>`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,Gs=t=>{const e=t===null?"null":String(t);return Oa(e)?Ca(e):e},Na=t=>t===null?"null":String(t),Ia=(t,e)=>{if(t==="in"){const r=Array.isArray(e)?e:[e];if(r.length===0)throw new Error("Realtime `in` filter requires at least one value.");return`in.(${Array.from(new Set(r)).map(n=>Gs(n)).join(",")})`}return t==="is"?`is.${Na(e)}`:`${t}.${Gs(e)}`};class Da{constructor(){this.filters=[]}add(e,r,s,n=!1){const i=n?"not.":"";return this.filters.push(`${e}=${i}${Ia(r,s)}`),this}eq(e,r){return this.add(e,"eq",r)}neq(e,r){return this.add(e,"neq",r)}gt(e,r){return this.add(e,"gt",r)}gte(e,r){return this.add(e,"gte",r)}lt(e,r){return this.add(e,"lt",r)}lte(e,r){return this.add(e,"lte",r)}in(e,r){return this.add(e,"in",r)}like(e,r){return this.add(e,"like",r)}ilike(e,r){return this.add(e,"ilike",r)}match(e,r){return this.add(e,"match",r)}imatch(e,r){return this.add(e,"imatch",r)}is(e,r){return this.add(e,"is",r)}isDistinct(e,r){return this.add(e,"isdistinct",r)}not(e,r,s){return this.add(e,r,s,!0)}build(){return this.filters.join(",")}toString(){return this.build()}}var zs;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(zs||(zs={}));var bt;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(bt||(bt={}));var st;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(st||(st={}));class nt{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},s){var n,i;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new Aa(this.socket.socketAdapter,e,this.params),this.presence=new Ea(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Ks(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===void 0)&&i.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,r=this.timeout){var s,n,i,a;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:o,presence:l,private:u,postgres_changes_options:d}}=this.params,h=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(_=>_.filter))!==null&&n!==void 0?n:[],p=!!this.bindings[bt.PRESENCE]&&this.bindings[bt.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,m={},g=Object.assign({broadcast:o,presence:Object.assign(Object.assign({},l),{enabled:p}),postgres_changes:h,private:u},d?{postgres_changes_options:d}:{});this.socket.accessTokenValue&&(m.access_token=this.socket.accessTokenValue),this._onError(_=>{e?.(st.CHANNEL_ERROR,ja(_))}),this._onClose(()=>e?.(st.CLOSED)),this.updateJoinPayload(Object.assign({config:g},m)),this._updateFilterMessage();const y=d?.wait&&h.length>0?Math.max(r,((a=d.timeout)!==null&&a!==void 0?a:na)+ia):r;this.channelAdapter.subscribe(y).receive("ok",async({postgres_changes:_})=>{if(this.socket._isManualToken()||this.socket.setAuth(),_===void 0){e?.(st.SUBSCRIBED);return}this._updatePostgresBindings(_,e)}).receive("error",_=>{this.state=ut.errored;const b=Object.values(_).join(", ")||"error";e?.(st.CHANNEL_ERROR,new Error(b,{cause:_}))}).receive("timeout",()=>{e?.(st.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var s;const n=this.bindings.postgres_changes,i=(s=n?.length)!==null&&s!==void 0?s:0,a=[];for(let o=0;o<i;o++){const l=n[o],{filter:{event:u,schema:d,table:h,filter:p}}=l,m=e&&e[o];if(m&&m.event===u&&nt.isFilterValueEqual(m.schema,d)&&nt.isFilterValueEqual(m.table,h)&&nt.isFilterValueEqual(m.filter,p))a.push(Object.assign(Object.assign({},l),{id:m.id}));else{this.unsubscribe(),this.state=ut.errored,r?.(st.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=a,this.state!=ut.errored&&r&&r(st.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,s){const n=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===bt.PRESENCE||e===bt.POSTGRES_CHANGES;if(n&&i)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,s)}async httpSend(e,r,s={}){var n;if(r==null)return Promise.reject(new Error("Payload is required for httpSend()"));const i=r instanceof ArrayBuffer||ArrayBuffer.isView(r),a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":i?"application/octet-stream":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);const o=new URL(this.broadcastEndpointURL);o.pathname+=`/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(e)}`,this.private&&o.searchParams.set("private","true");const l={method:"POST",headers:a,body:i?r:JSON.stringify(r)},u=await this._fetchWithTimeout(o.toString(),l,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);if(u.status===202)return{success:!0};if(u.status===404)return Promise.reject(new Error("httpSend() requires Realtime server v2.97.0 or newer; the endpoint returned 404. Update your Supabase CLI to a recent version, or upgrade the Realtime server in your self-hosted setup. See https://github.com/supabase/supabase-js/blob/master/packages/core/realtime-js/migrations/httpsend-server-version.md"));let d=u.statusText;try{const h=await u.json();d=h.error||h.message||d}catch{}return Promise.reject(new Error(d))}async send(e,r={}){var s,n;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){const i="Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.";this.socket.hasLogger()?this.socket.log("channel",i):console.warn(i);const{event:a,payload:o}=e,l={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(l.Authorization=`Bearer ${this.socket.accessTokenValue}`);const u={method:"POST",headers:l,body:JSON.stringify({messages:[{topic:this.subTopic,event:a,payload:o,private:this.private}]})};try{const d=await this._fetchWithTimeout(this.broadcastEndpointURL,u,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=d.body)===null||n===void 0?void 0:n.cancel()),d.ok?"ok":"error"}catch(d){return d instanceof Error&&d.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var a,o,l;const u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(o=(a=this.params)===null||a===void 0?void 0:a.config)===null||o===void 0?void 0:o.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),u.receive("ok",()=>i("ok")),u.receive("error",()=>i("error")),u.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,s){const n=new AbortController,i=setTimeout(()=>n.abort(),s),a=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(i),a}_on(e,r,s){var n;const i=e.toLocaleLowerCase(),a=r?.filter;if((a instanceof Da||typeof a=="object"&&a!==null&&typeof a.build=="function")&&(r=Object.assign(Object.assign({},r),{filter:a.build()})),i===bt.POSTGRES_CHANGES&&((n=this.bindings[i])===null||n===void 0?void 0:n.find(d=>nt.isSamePostgresFilter(d.filter,r))))return this.socket.log("error",`duplicate \`postgres_changes\` binding for ${this.topic} ignored`,r),this;const o=this.channelAdapter.on(e,s),l={type:i,filter:r,callback:s,ref:o};return this.bindings[i]?this.bindings[i].push(l):this.bindings[i]=[l],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,s)=>{var n,i,a,o,l,u,d;const h=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(h,s))return!1;const p=(n=this.bindings[h])===null||n===void 0?void 0:n.find(m=>m.ref===e.ref);if(!p)return!0;if(["broadcast","presence","postgres_changes"].includes(h))if("id"in p){const m=p.id,g=(i=p.filter)===null||i===void 0?void 0:i.event;return m&&((a=r.ids)===null||a===void 0?void 0:a.includes(m))&&(g==="*"||g?.toLocaleLowerCase()===((o=r.data)===null||o===void 0?void 0:o.type.toLocaleLowerCase()))}else{const m=(u=(l=p?.filter)===null||l===void 0?void 0:l.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return m==="*"||m===((d=r?.event)===null||d===void 0?void 0:d.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===h})}_notThisChannelEvent(e,r){const{close:s,error:n,leave:i,join:a}=Us;return r&&[s,n,i,a].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,s)=>{if(typeof r=="object"&&"ids"in r){const n=r.data,{schema:i,table:a,commit_timestamp:o,type:l,errors:u}=n;return Object.assign(Object.assign({},{schema:i,table:a,commit_timestamp:o,eventType:l,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const r in e.bindings)for(const s of e.bindings[r])this._on(s.type,s.filter,s.callback)}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}static isSamePostgresFilter(e,r){var s,n,i,a;const o=(n=(s=e?.select)===null||s===void 0?void 0:s.join())!==null&&n!==void 0?n:void 0,l=(a=(i=r?.select)===null||i===void 0?void 0:i.join())!==null&&a!==void 0?a:void 0;return e?.event===r?.event&&nt.isFilterValueEqual(e?.schema,r?.schema)&&nt.isFilterValueEqual(e?.table,r?.table)&&nt.isFilterValueEqual(e?.filter,r?.filter)&&o===l}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Bs(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Bs(e.columns,e.old_record)),r}}class $a{constructor(e,r){this.socket=new Sa(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,s,n=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),n),this.socket.disconnect(()=>{e(),i("ok")},r,s)})}push(e){this.socket.push(e)}log(e,r,s){this.socket.log(e,r,s)}hasLogger(){return this.socket.hasLogger()}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Zr.connecting}isDisconnecting(){return this.socket.connectionState()==Zr.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const Vs={HEARTBEAT_INTERVAL:25e3},La=[1e3,2e3,5e3,1e4],Ma=1e4;function Ua(){const t=new Map;return{get length(){return t.size},clear(){t.clear()},getItem(e){return t.has(e)?t.get(e):null},key(e){var r;return(r=Array.from(t.keys())[e])!==null&&r!==void 0?r:null},removeItem(e){t.delete(e)},setItem(e,r){t.set(e,String(r))}}}function Ba(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return Ua()}const Fa=`
|
|
19
|
+
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{return this.detectEnvironment().type==="native"}catch{return!1}}}const Qi="realtime-js/2.112.4",Xi="1.0.0",$s="2.0.0",Zi=$s,ea=1e4,ta=100,ut={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Ls={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},Zr={connecting:"connecting",closing:"closing",closed:"closed"};class ra{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:{},a=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,a)}_encodeUserBroadcastPush(e,r,s){var n,i;const a=new TextEncoder,o=a.encode(e.topic),l=a.encode((n=e.ref)!==null&&n!==void 0?n:""),u=a.encode((i=e.join_ref)!==null&&i!==void 0?i:""),d=a.encode(e.payload.event),h=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},p=a.encode(Object.keys(h).length===0?"":JSON.stringify(h));if(u.length>255)throw new Error(`joinRef length ${u.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`ref length ${l.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`userEvent length ${d.length} exceeds maximum of 255`);if(p.length>255)throw new Error(`metadata length ${p.length} exceeds maximum of 255`);const m=this.USER_BROADCAST_PUSH_META_LENGTH+u.length+l.length+o.length+d.length+p.length,g=new ArrayBuffer(this.HEADER_LENGTH+m),y=new DataView(g),x=new Uint8Array(g);let v=0;y.setUint8(v++,this.KINDS.userBroadcastPush),y.setUint8(v++,u.length),y.setUint8(v++,l.length),y.setUint8(v++,o.length),y.setUint8(v++,d.length),y.setUint8(v++,p.length),y.setUint8(v++,r),x.set(u,v),v+=u.length,x.set(l,v),v+=l.length,x.set(o,v),v+=o.length,x.set(d,v),v+=d.length,x.set(p,v),v+=p.length;var _=new Uint8Array(g.byteLength+s.byteLength);return _.set(new Uint8Array(g),0),_.set(new Uint8Array(s),g.byteLength),_.buffer}decode(e,r){if(this._isArrayBuffer(e)){let s=this._binaryDecode(e);return r(s)}if(typeof e=="string"){const s=JSON.parse(e),[n,i,a,o,l]=s;return r({join_ref:n,ref:i,topic:a,event:o,payload:l})}return r({})}_binaryDecode(e){const r=new DataView(e),s=r.getUint8(0),n=new TextDecoder;if(s===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,n)}_decodeUserBroadcast(e,r,s){const n=r.getUint8(1),i=r.getUint8(2),a=r.getUint8(3),o=r.getUint8(4);let l=this.HEADER_LENGTH+4;const u=s.decode(e.slice(l,l+n));l=l+n;const d=s.decode(e.slice(l,l+i));l=l+i;const h=s.decode(e.slice(l,l+a));l=l+a;const p=e.slice(l,e.byteLength),m=o===this.JSON_ENCODING?JSON.parse(s.decode(p)):p,g={type:this.BROADCAST_EVENT,event:d,payload:m};return a>0&&(g.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:g}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([s])=>r.includes(s)))}}var Z;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(Z||(Z={}));const Ms=(t,e,r={})=>{var s;const n=(s=r.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((i,a)=>(i[a]=sa(a,t,e,n),i),{}):{}},sa=(t,e,r,s)=>{const n=e.find(o=>o.name===t),i=n?.type,a=r[t];return i&&!s.includes(i)?Us(i,a):es(a)},Us=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return oa(e,r)}switch(t){case Z.bool:return na(e);case Z.float4:case Z.float8:case Z.int2:case Z.int4:case Z.int8:case Z.numeric:case Z.oid:return ia(e);case Z.json:case Z.jsonb:return aa(e);case Z.timestamp:return la(e);case Z.abstime:case Z.date:case Z.daterange:case Z.int4range:case Z.int8range:case Z.money:case Z.reltime:case Z.text:case Z.time:case Z.timestamptz:case Z.timetz:case Z.tsrange:case Z.tstzrange:return es(e);default:return es(e)}},es=t=>t,na=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},ia=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},aa=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},oa=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,s=t[r];if(t[0]==="{"&&s==="}"){let i;const a=t.slice(1,r);try{i=JSON.parse("["+a+"]")}catch{i=a?a.split(","):[]}return i.map(o=>Us(e,o))}return t},la=t=>typeof t=="string"?t.replace(" ","T"):t,Bs=t=>{const e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var Rt=t=>typeof t=="function"?t:function(){return t},ca=typeof self<"u"?self:null,Ot=typeof window<"u"?window:null,Xe=ca||Ot||globalThis,ua="2.0.0",da=1e4,ha=1e3,fa=100,Ze={connecting:0,open:1,closing:2,closed:3},Pe={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},rt={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},ts={longpoll:"longpoll",websocket:"websocket"},ma={complete:4},rs="base64url.bearer.phx.",yr=class{constructor(t,e,r,s){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(s=>s.status===t).forEach(s=>s.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},Fs=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},pa=class{constructor(t,e,r){this.state=Pe.closed,this.topic=t,this.params=Rt(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new yr(this,rt.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Fs(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=Pe.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",s=>{this.state=Pe.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Pe.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=Pe.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new yr(this,rt.leave,Rt({}),this.timeout).send(),this.state=Pe.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(rt.reply,(s,n)=>{this.trigger(this.replyEventName(n),s)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Pe.closed,this.bindings=[]}onClose(t){this.on(rt.close,t)}onError(t){return this.on(rt.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new yr(this,t,function(){return e},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Pe.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(rt.close,"leave")},r=new yr(this,rt.leave,Rt({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,s){return this.topic!==t?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Pe.joining,this.joinPush.resend(t))}trigger(t,e,r,s){let n=this.onMessage(t,e,r,s);if(e&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let i=this.bindings.filter(a=>a.event===t&&this.filterBindings(a,e,r));for(let a=0;a<i.length;a++)i[a].callback(n,r,s||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===Pe.closed}isErrored(){return this.state===Pe.errored}isJoined(){return this.state===Pe.joined}isJoining(){return this.state===Pe.joining}isLeaving(){return this.state===Pe.leaving}},br=class{static request(t,e,r,s,n,i,a){if(Xe.XDomainRequest){let o=new Xe.XDomainRequest;return this.xdomainRequest(o,t,e,s,n,i,a)}else if(Xe.XMLHttpRequest){let o=new Xe.XMLHttpRequest;return this.xhrRequest(o,t,e,r,s,n,i,a)}else{if(Xe.fetch&&Xe.AbortController)return this.fetchRequest(t,e,r,s,n,i,a);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,s,n,i,a){let o={method:t,headers:r,body:s},l=null;return n&&(l=new AbortController,setTimeout(()=>l.abort(),n),o.signal=l.signal),Xe.fetch(e,o).then(u=>u.text()).then(u=>this.parseJSON(u)).then(u=>a&&a(u)).catch(u=>{u.name==="AbortError"&&i?i():a&&a(null)}),l}static xdomainRequest(t,e,r,s,n,i,a){return t.timeout=n,t.open(e,r),t.onload=()=>{let o=this.parseJSON(t.responseText);a&&a(o)},i&&(t.ontimeout=i),t.onprogress=()=>{},t.send(s),t}static xhrRequest(t,e,r,s,n,i,a,o){t.open(e,r,!0),t.timeout=i;for(let[l,u]of Object.entries(s))t.setRequestHeader(l,u);return t.onerror=()=>o&&o(null),t.onreadystatechange=()=>{if(t.readyState===ma.complete&&o){let l=this.parseJSON(t.responseText);o(l)}},a&&(t.ontimeout=a),t.send(n),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let n=e?`${e}[${s}]`:s,i=t[s];typeof i=="object"?r.push(this.serialize(i,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},ga=t=>{let e="",r=new Uint8Array(t),s=r.byteLength;for(let n=0;n<s;n++)e+=String.fromCharCode(r[n]);return btoa(e)},Ct=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(rs)&&(this.authToken=atob(e[1].slice(rs.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=Ze.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+ts.websocket),"$1/"+ts.longpoll)}endpointURL(){return br.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=Ze.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Ze.open||this.readyState===Ze.connecting}poll(){const t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:s,messages:n}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=s}else r=0;switch(r){case 200:n.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=Ze.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=ga(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t,e=0){this.awaitingBatchAck=!0;const r=e+fa,s=t.slice(e,r);this.ajax("POST",{"Content-Type":"application/x-ndjson"},s.join(`
|
|
20
|
+
`),()=>this.onerror("timeout"),n=>{!n||n.status!==200?(this.awaitingBatchAck=!1,this.onerror(n&&n.status),this.closeAndRetry(1011,"internal server error",!1)):r<t.length?this.batchSend(t,r):this.batchBuffer.length>0?(this.batchSend(this.batchBuffer),this.batchBuffer=[]):this.awaitingBatchAck=!1})}close(t,e,r){for(let n of this.reqs)n.abort();this.readyState=Ze.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(t,e,r,s,n){let i,a=()=>{this.reqs.delete(i),s()};i=br.request(t,this.endpointURL(),e,r,this.timeout,a,o=>{this.reqs.delete(i),this.isActive()&&n(o)}),this.reqs.add(i)}},ya=class fr{constructor(e,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state=Object.create(null),this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,n=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.joinRef=this.channel.joinRef(),this.state=fr.syncState(this.state,n,i,a),this.pendingDiffs.forEach(l=>{this.state=fr.syncDiff(this.state,l,i,a)}),this.pendingDiffs=[],o()}),this.channel.on(s.diff,n=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=fr.syncDiff(this.state,n,i,a),o())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return fr.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,s,n){let i=this.toNullProtoObj(this.clone(e));r=this.toNullProtoObj(r);let a=Object.create(null),o=Object.create(null);return this.map(i,(l,u)=>{r[l]||(o[l]=u)}),this.map(r,(l,u)=>{let d=i[l];if(d){let h=u.metas.map(y=>y.phx_ref),p=d.metas.map(y=>y.phx_ref),m=u.metas.filter(y=>p.indexOf(y.phx_ref)<0),g=d.metas.filter(y=>h.indexOf(y.phx_ref)<0);m.length>0&&(a[l]=u,a[l].metas=m),g.length>0&&(o[l]=this.clone(d),o[l].metas=g)}else a[l]=u}),this.syncDiff(i,{joins:a,leaves:o},s,n)}static syncDiff(e,r,s,n){e=this.toNullProtoObj(e);let{joins:i,leaves:a}=this.clone(r);return s||(s=function(){}),n||(n=function(){}),this.map(i,(o,l)=>{let u=e[o];if(e[o]=this.clone(l),u){let d=e[o].metas.map(p=>p.phx_ref),h=u.metas.filter(p=>d.indexOf(p.phx_ref)<0);e[o].metas.unshift(...h)}s(o,u,l)}),this.map(a,(o,l)=>{let u=e[o];if(!u)return;let d=l.metas.map(h=>h.phx_ref);u.metas=u.metas.filter(h=>d.indexOf(h.phx_ref)<0),n(o,u,l),u.metas.length===0&&delete e[o]}),e}static list(e,r){return r||(r=function(s,n){return n}),this.map(e,(s,n)=>r(s,n))}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static toNullProtoObj(e){if(Object.getPrototypeOf(e)===null)return e;let r=Object.create(null);return Object.getOwnPropertyNames(e).forEach(s=>{r[s]=e[s]}),r}static clone(e){return JSON.parse(JSON.stringify(e))}},vr={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,s,n,i,a]=JSON.parse(t);return e({join_ref:r,ref:s,topic:n,event:i,payload:a})}},binaryEncode(t){let{join_ref:e,ref:r,event:s,topic:n,payload:i}=t,a=new TextEncoder,o=a.encode(e),l=a.encode(r),u=a.encode(n),d=a.encode(s);this.assertFieldSize(o.byteLength,"join_ref"),this.assertFieldSize(l.byteLength,"ref"),this.assertFieldSize(u.byteLength,"topic"),this.assertFieldSize(d.byteLength,"event");let h=this.META_LENGTH+o.byteLength+l.byteLength+u.byteLength+d.byteLength,p=new ArrayBuffer(this.HEADER_LENGTH+h),m=new Uint8Array(p),g=new DataView(p),y=0;g.setUint8(y++,this.KINDS.push),g.setUint8(y++,o.byteLength),g.setUint8(y++,l.byteLength),g.setUint8(y++,u.byteLength),g.setUint8(y++,d.byteLength),m.set(o,y),y+=o.byteLength,m.set(l,y),y+=l.byteLength,m.set(u,y),y+=u.byteLength,m.set(d,y),y+=d.byteLength;var x=new Uint8Array(p.byteLength+i.byteLength);return x.set(m,0),x.set(new Uint8Array(i),p.byteLength),x.buffer},assertFieldSize(t,e){if(t>255)throw new Error(`unable to convert ${e} to binary: must be less than or equal to 255 bytes, but is ${t} bytes`)},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,s);case this.KINDS.reply:return this.decodeReply(t,e,s);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,s)}},decodePush(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(t.slice(a,a+s));a=a+s;let l=r.decode(t.slice(a,a+n));a=a+n;let u=r.decode(t.slice(a,a+i));a=a+i;let d=t.slice(a,t.byteLength);return{join_ref:o,ref:null,topic:l,event:u,payload:d}},decodeReply(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),a=e.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(o,o+s));o=o+s;let u=r.decode(t.slice(o,o+n));o=o+n;let d=r.decode(t.slice(o,o+i));o=o+i;let h=r.decode(t.slice(o,o+a));o=o+a;let p=t.slice(o,t.byteLength),m={status:h,response:p};return{join_ref:l,ref:u,topic:d,event:rt.reply,payload:m}},decodeBroadcast(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=this.HEADER_LENGTH+2,a=r.decode(t.slice(i,i+s));i=i+s;let o=r.decode(t.slice(i,i+n));i=i+n;let l=t.slice(i,t.byteLength);return{join_ref:null,ref:null,topic:a,event:o,payload:l}}},ba=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||da,this.transport=e.transport||Xe.WebSocket||Ct,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null;let r=null;try{r=Xe&&Xe.sessionStorage}catch{}this.sessionStore=e.sessionStorage||r,this.establishedConnections=0,this.defaultEncoder=vr.encode.bind(vr),this.defaultDecoder=vr.decode.bind(vr),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==Ct?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let s=null;Ot&&Ot.addEventListener&&(Ot.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),s=this.connectClock)}),Ot.addEventListener("pageshow",n=>{s===this.connectClock&&(s=null,this.connect())}),Ot.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(n,i,a)=>{console.log(`${n}: ${i}`,a)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Rt(e.params||{}),this.endPoint=`${t}/${ts.websocket}`,this.vsn=e.vsn||ua,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Fs(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken&&Rt(e.authToken)}getLongPollTransport(){return Ct}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=br.appendParams(br.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Rt(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Ct?this.connectWithFallback(Ct,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let s=this.onMessage(n=>{n.ref===e&&(this.off([s]),t(Date.now()-r))});return!0}transportName(t){return t===Ct?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${rs}${btoa(this.authToken()).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,s=!0,n,i,a=this.transportName(t),o=l=>{this.log("transport",`falling back to ${a}...`,l),this.off([n,i]),s=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${a}`))return o("memorized");this.fallbackTimer=setTimeout(o,e),i=this.onError(l=>{this.log("transport","error",l),s&&!r&&(clearTimeout(this.fallbackTimer),o(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!s){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),ha,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();const s=this.conn;this.waitForBufferDone(s,()=>{e?s.close(e,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===Ze.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(t),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport","error",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError(t)}triggerChanError(t){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(rt.error,t)})}connectionState(){switch(this.conn&&this.conn.readyState){case Ze.connecting:return"connecting";case Ze.open:return"open";case Ze.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new pa(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:s,ref:n,join_ref:i}=t;this.log("push",`${e} ${r} (${i}, ${n})`,s)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:s,payload:n,ref:i,join_ref:a}=e;if(i&&i===this.pendingHeartbeatRef){const o=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(n.status==="ok"?"ok":"error",o)}catch(l){this.log("error","error in heartbeat callback",l)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${n.status||""} ${r} ${s} ${i&&"("+i+")"||""}`.trim(),n);for(let o=0;o<this.channels.length;o++){const l=this.channels[o];l.isMember(r,s,n,a)&&l.trigger(s,n,i,a)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,s])=>{try{s(...e)}catch(n){this.log("error",`error in ${t} callback`,n)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};class zt{constructor(e,r){const s=wa(r);this.presence=new ya(e.getChannel(),s),this.presence.onJoin((n,i,a)=>{const o=zt.onJoinPayload(n,i,a);e.getChannel().trigger("presence",o)}),this.presence.onLeave((n,i,a)=>{const o=zt.onLeavePayload(n,i,a);e.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return zt.transformState(this.presence.state)}static transformState(e){return e=va(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{const n=e[s];return r[s]=wr(n),r},{})}static onJoinPayload(e,r,s){const n=Ks(r),i=wr(s);return{event:"join",key:e,currentPresences:n,newPresences:i}}static onLeavePayload(e,r,s){const n=Ks(r),i=wr(s);return{event:"leave",key:e,currentPresences:n,leftPresences:i}}}function wr(t){return t.metas.map(e=>{const r=Object.getOwnPropertyDescriptors(e),s=Object.defineProperties({},r);return s.presence_ref=s.phx_ref,delete s.phx_ref,delete s.phx_ref_prev,s})}function va(t){return JSON.parse(JSON.stringify(t))}function wa(t){return t?.events&&{events:t.events}}function Ks(t){return t?.metas?wr(t):[]}var qs;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(qs||(qs={}));class _a{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new zt(this.channel.channelAdapter,r)}}function ka(t){if(t instanceof Error)return t;if(typeof t=="string")return new Error(t);if(t&&typeof t=="object"){const e=t;if(typeof e.code=="number"){const r=typeof e.reason=="string"&&e.reason?` (${e.reason})`:"";return new Error(`socket closed: ${e.code}${r}`,{cause:t})}return new Error("channel error: transport failure",{cause:t})}return new Error("channel error: connection lost")}class Sa{constructor(e,r,s){const n=xa(s);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,s){let n;try{n=this.channel.push(e,r,s)}catch{throw new Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>ta){const i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return n}updateJoinPayload(e){const r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===ut.joined}isJoined(){return this.state===ut.joined}isJoining(){return this.state===ut.joining}isClosed(){return this.state===ut.closed}isLeaving(){return this.state===ut.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function xa(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}const Ta=/[,()"\\]/,Ea=t=>Ta.test(t)||t!==t.trim(),ja=t=>`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,Ws=t=>{const e=t===null?"null":String(t);return Ea(e)?ja(e):e},Aa=t=>t===null?"null":String(t),Pa=(t,e)=>{if(t==="in"){const r=Array.isArray(e)?e:[e];if(r.length===0)throw new Error("Realtime `in` filter requires at least one value.");return`in.(${Array.from(new Set(r)).map(n=>Ws(n)).join(",")})`}return t==="is"?`is.${Aa(e)}`:`${t}.${Ws(e)}`};class Ra{constructor(){this.filters=[]}add(e,r,s,n=!1){const i=n?"not.":"";return this.filters.push(`${e}=${i}${Pa(r,s)}`),this}eq(e,r){return this.add(e,"eq",r)}neq(e,r){return this.add(e,"neq",r)}gt(e,r){return this.add(e,"gt",r)}gte(e,r){return this.add(e,"gte",r)}lt(e,r){return this.add(e,"lt",r)}lte(e,r){return this.add(e,"lte",r)}in(e,r){return this.add(e,"in",r)}like(e,r){return this.add(e,"like",r)}ilike(e,r){return this.add(e,"ilike",r)}match(e,r){return this.add(e,"match",r)}imatch(e,r){return this.add(e,"imatch",r)}is(e,r){return this.add(e,"is",r)}isDistinct(e,r){return this.add(e,"isdistinct",r)}not(e,r,s){return this.add(e,r,s,!0)}build(){return this.filters.join(",")}toString(){return this.build()}}var Hs;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Hs||(Hs={}));var yt;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(yt||(yt={}));var st;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(st||(st={}));class nt{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},s){var n,i;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new Sa(this.socket.socketAdapter,e,this.params),this.presence=new _a(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Bs(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===void 0)&&i.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,r=this.timeout){var s,n,i;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:a,presence:o,private:l}}=this.params,u=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(m=>m.filter))!==null&&n!==void 0?n:[],d=!!this.bindings[yt.PRESENCE]&&this.bindings[yt.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,h={},p={broadcast:a,presence:Object.assign(Object.assign({},o),{enabled:d}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(m=>{e?.(st.CHANNEL_ERROR,ka(m))}),this._onClose(()=>e?.(st.CLOSED)),this.updateJoinPayload(Object.assign({config:p},h)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:m})=>{if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){e?.(st.SUBSCRIBED);return}this._updatePostgresBindings(m,e)}).receive("error",m=>{this.state=ut.errored;const g=Object.values(m).join(", ")||"error";e?.(st.CHANNEL_ERROR,new Error(g,{cause:m}))}).receive("timeout",()=>{e?.(st.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var s;const n=this.bindings.postgres_changes,i=(s=n?.length)!==null&&s!==void 0?s:0,a=[];for(let o=0;o<i;o++){const l=n[o],{filter:{event:u,schema:d,table:h,filter:p}}=l,m=e&&e[o];if(m&&m.event===u&&nt.isFilterValueEqual(m.schema,d)&&nt.isFilterValueEqual(m.table,h)&&nt.isFilterValueEqual(m.filter,p))a.push(Object.assign(Object.assign({},l),{id:m.id}));else{this.unsubscribe(),this.state=ut.errored,r?.(st.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=a,this.state!=ut.errored&&r&&r(st.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,s){const n=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===yt.PRESENCE||e===yt.POSTGRES_CHANGES;if(n&&i)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,s)}async httpSend(e,r,s={}){var n;if(r==null)return Promise.reject(new Error("Payload is required for httpSend()"));const i=r instanceof ArrayBuffer||ArrayBuffer.isView(r),a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":i?"application/octet-stream":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);const o=new URL(this.broadcastEndpointURL);o.pathname+=`/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(e)}`,this.private&&o.searchParams.set("private","true");const l={method:"POST",headers:a,body:i?r:JSON.stringify(r)},u=await this._fetchWithTimeout(o.toString(),l,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);if(u.status===202)return{success:!0};if(u.status===404)return Promise.reject(new Error("httpSend() requires Realtime server v2.97.0 or newer; the endpoint returned 404. Update your Supabase CLI to a recent version, or upgrade the Realtime server in your self-hosted setup. See https://github.com/supabase/supabase-js/blob/master/packages/core/realtime-js/migrations/httpsend-server-version.md"));let d=u.statusText;try{const h=await u.json();d=h.error||h.message||d}catch{}return Promise.reject(new Error(d))}async send(e,r={}){var s,n;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){const i="Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.";this.socket.hasLogger()?this.socket.log("channel",i):console.warn(i);const{event:a,payload:o}=e,l={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(l.Authorization=`Bearer ${this.socket.accessTokenValue}`);const u={method:"POST",headers:l,body:JSON.stringify({messages:[{topic:this.subTopic,event:a,payload:o,private:this.private}]})};try{const d=await this._fetchWithTimeout(this.broadcastEndpointURL,u,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=d.body)===null||n===void 0?void 0:n.cancel()),d.ok?"ok":"error"}catch(d){return d instanceof Error&&d.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var a,o,l;const u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(o=(a=this.params)===null||a===void 0?void 0:a.config)===null||o===void 0?void 0:o.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),u.receive("ok",()=>i("ok")),u.receive("error",()=>i("error")),u.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,s){const n=new AbortController,i=setTimeout(()=>n.abort(),s),a=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(i),a}_on(e,r,s){var n;const i=e.toLocaleLowerCase(),a=r?.filter;if((a instanceof Ra||typeof a=="object"&&a!==null&&typeof a.build=="function")&&(r=Object.assign(Object.assign({},r),{filter:a.build()})),i===yt.POSTGRES_CHANGES&&((n=this.bindings[i])===null||n===void 0?void 0:n.find(d=>nt.isSamePostgresFilter(d.filter,r))))return this.socket.log("error",`duplicate \`postgres_changes\` binding for ${this.topic} ignored`,r),this;const o=this.channelAdapter.on(e,s),l={type:i,filter:r,callback:s,ref:o};return this.bindings[i]?this.bindings[i].push(l):this.bindings[i]=[l],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,s)=>{var n,i,a,o,l,u,d;const h=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(h,s))return!1;const p=(n=this.bindings[h])===null||n===void 0?void 0:n.find(m=>m.ref===e.ref);if(!p)return!0;if(["broadcast","presence","postgres_changes"].includes(h))if("id"in p){const m=p.id,g=(i=p.filter)===null||i===void 0?void 0:i.event;return m&&((a=r.ids)===null||a===void 0?void 0:a.includes(m))&&(g==="*"||g?.toLocaleLowerCase()===((o=r.data)===null||o===void 0?void 0:o.type.toLocaleLowerCase()))}else{const m=(u=(l=p?.filter)===null||l===void 0?void 0:l.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return m==="*"||m===((d=r?.event)===null||d===void 0?void 0:d.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===h})}_notThisChannelEvent(e,r){const{close:s,error:n,leave:i,join:a}=Ls;return r&&[s,n,i,a].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,s)=>{if(typeof r=="object"&&"ids"in r){const n=r.data,{schema:i,table:a,commit_timestamp:o,type:l,errors:u}=n;return Object.assign(Object.assign({},{schema:i,table:a,commit_timestamp:o,eventType:l,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const r in e.bindings)for(const s of e.bindings[r])this._on(s.type,s.filter,s.callback)}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}static isSamePostgresFilter(e,r){var s,n,i,a;const o=(n=(s=e?.select)===null||s===void 0?void 0:s.join())!==null&&n!==void 0?n:void 0,l=(a=(i=r?.select)===null||i===void 0?void 0:i.join())!==null&&a!==void 0?a:void 0;return e?.event===r?.event&&nt.isFilterValueEqual(e?.schema,r?.schema)&&nt.isFilterValueEqual(e?.table,r?.table)&&nt.isFilterValueEqual(e?.filter,r?.filter)&&o===l}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Ms(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Ms(e.columns,e.old_record)),r}}class Oa{constructor(e,r){this.socket=new ba(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,s,n=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),n),this.socket.disconnect(()=>{e(),i("ok")},r,s)})}push(e){this.socket.push(e)}log(e,r,s){this.socket.log(e,r,s)}hasLogger(){return this.socket.hasLogger()}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Zr.connecting}isDisconnecting(){return this.socket.connectionState()==Zr.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const Gs={HEARTBEAT_INTERVAL:25e3},Ca=[1e3,2e3,5e3,1e4],Na=1e4;function Ia(){const t=new Map;return{get length(){return t.size},clear(){t.clear()},getItem(e){return t.has(e)?t.get(e):null},key(e){var r;return(r=Array.from(t.keys())[e])!==null&&r!==void 0?r:null},removeItem(e){t.delete(e)},setItem(e,r){t.set(e,String(r))}}}function Da(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return Ia()}const $a=`
|
|
21
21
|
addEventListener("message", (e) => {
|
|
22
22
|
if (e.data.event === "start") {
|
|
23
23
|
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
24
24
|
}
|
|
25
|
-
});`;class Ka{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 oa,this._manuallySetToken=!1,this._authPromise=null,this._authGeneration=0,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=i=>i?(...a)=>i(...a):(...a)=>fetch(...a),!(!((s=r?.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;const n=this._initializeOptions(r);this.socketAdapter=new $a(e,n),this.httpEndpoint=Ks(e),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){const r=e.message;throw new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return r==="ok"&&e.teardown(),r}async removeAllChannels(){const e=this.channels.map(async s=>{const n=await s.unsubscribe();return s.teardown(),n}),r=await Promise.all(e);return await this.disconnect(),r}log(e,r,s){this.socketAdapter.log(e,r,s)}hasLogger(){return this.socketAdapter.hasLogger()}connectionState(){return this.socketAdapter.connectionState()||Zr.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){const s=`realtime:${e}`,n=this.getChannels().find(i=>i.topic===s);if(n)return n;{const i=new nt(`realtime:${e}`,r,this);return this._cancelPendingDisconnect(),this.channels.push(i),i}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){const r=++this._authGeneration,s=this._performAuth(e,r);r===this._authGeneration&&(this._authPromise=s);try{await s}finally{this._authPromise===s&&(this._authPromise=null)}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic),this.channels.length===0&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e,r){let s,n=!1;if(e)s=e,n=!0;else if(this.accessToken)try{s=await this.accessToken()}catch(i){this.log("error","Error fetching access token from callback",i),s=this.accessTokenValue}else s=this.accessTokenValue;r===this._authGeneration&&(this.accessToken?this._manuallySetToken=!1:n&&(this._manuallySetToken=!0),this.accessTokenValue!=s&&(this.accessTokenValue=s,this.channels.forEach(i=>{const a={access_token:s,version:ea};i.updateJoinPayload(a),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push(Us.access_token,{access_token:s})})))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,s)=>{r!=="disconnected"&&(r=="sent"&&this._setAuthSafely(),e&&e(r,s))}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{const s=new Blob([Fa],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_initializeOptions(e){var r,s,n,i,a,o,l,u,d,h,p,m;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(s=e?.accessToken)!==null&&s!==void 0?s:null;const g={};g.timeout=(n=e?.timeout)!==null&&n!==void 0?n:sa,g.heartbeatIntervalMs=(i=e?.heartbeatIntervalMs)!==null&&i!==void 0?i:Vs.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(a=e?.disconnectOnEmptyChannelsAfterMs)!==null&&a!==void 0?a:2*((o=e?.heartbeatIntervalMs)!==null&&o!==void 0?o:Vs.HEARTBEAT_INTERVAL),g.transport=(l=e?.transport)!==null&&l!==void 0?l:Zi.getWebSocketConstructor(),g.params=e?.params,g.logger=e?.logger,g.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),g.sessionStorage=(u=e?.sessionStorage)!==null&&u!==void 0?u:Ba(),g.reconnectAfterMs=(d=e?.reconnectAfterMs)!==null&&d!==void 0?d:(k=>La[k-1]||Ma);let y,_;const b=(h=e?.vsn)!==null&&h!==void 0?h:ra;switch(b){case ta:y=(k,S)=>S(JSON.stringify(k)),_=(k,S)=>S(JSON.parse(k));break;case Ms:y=this.serializer.encode.bind(this.serializer),_=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${g.vsn}`)}if(g.vsn=b,g.encode=(p=e?.encode)!==null&&p!==void 0?p:y,g.decode=(m=e?.decode)!==null&&m!==void 0?m:_,g.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,g.params=Object.assign(Object.assign({},g.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,g.autoSendHeartbeat=!this.worker}return g}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var Jt=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,i]of Object.entries(r))i!==void 0&&s.searchParams.set(n,i);return s.toString()}async function Wa(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 Ha(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:a}){const o=qa(t.baseUrl,s,n),l=await Wa(t.auth),u=await e(o,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...a},body:i?JSON.stringify(i):void 0}),d=await u.text(),h=(u.headers.get("content-type")||"").includes("application/json"),p=h&&d?JSON.parse(d):d;if(!u.ok){const m=h?p:void 0,g=m?.error;throw new Jt(g?.message??`Request failed with status ${u.status}`,{status:u.status,icebergType:g?.type,icebergCode:g?.code,details:m})}return{status:u.status,headers:u.headers,data:p}}}}function kr(t){return t.join("")}var Ga=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:kr(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/${kr(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${kr(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${kr(t.namespace)}`}),!0}catch(e){if(e instanceof Jt&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof Jt&&r.status===409)return;throw r}}};function It(t){return t.join("")}var za=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/${It(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/${It(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/${It(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/${It(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/${It(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/${It(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof Jt&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof Jt&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},Va=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Ha({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new Ga(this.client,e),this.tableOps=new za(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 Yt(t){"@babel/helpers - typeof";return Yt=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},Yt(t)}function Ja(t,e){if(Yt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(Yt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ya(t){var e=Ja(t,"string");return Yt(e)=="symbol"?e:e+""}function Qa(t,e,r){return(e=Ya(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 C(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){Qa(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 Sr=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 xr(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var ss=class extends Sr{constructor(t,e,r,s="storage",n){super(t,s,e,r),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r,this.code=n}toJSON(){return C(C({},super.toJSON()),{},{code:this.code})}},Ys=class extends Sr{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};function Tr(t,e,r){const s=C({},t),n=e.toLowerCase();for(const i of Object.keys(s))i.toLowerCase()===n&&delete s[i];return s[n]=r,s}function Xa(t){const e={};for(const[r,s]of Object.entries(t))e[r.toLowerCase()]=s;return e}const Za=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),eo=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},ns=t=>{if(Array.isArray(t))return t.map(r=>ns(r));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([r,s])=>{const n=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[n]=ns(s)}),e},to=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),Qs=t=>t.split("/").map(encodeURIComponent).join("/"),Xs=t=>{if(typeof t=="object"&&t!==null){const e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){const r=e.error;if(typeof r.message=="string")return r.message}}return JSON.stringify(t)},ro=async(t,e,r,s)=>{if(t!==null&&typeof t=="object"&&"json"in t&&typeof t.json=="function"){const n=t;let i=parseInt(String(n.status),10);Number.isFinite(i)||(i=500),n.json().then(a=>{const o=a?.statusCode||a?.code||i+"";e(new ss(Xs(a),i,o,s,a?.code))}).catch(()=>{const a=i+"";e(new ss(n.statusText||`HTTP ${i} error`,i,a,s))})}else e(new Ys(Xs(t),t,s))},so=(t,e,r,s)=>{const n={method:t,headers:e?.headers||{}};if(t==="GET"||t==="HEAD"||!s)return C(C({},n),r);if(eo(s)){var i;const a=e?.headers||{};let o;for(const[l,u]of Object.entries(a))l.toLowerCase()==="content-type"&&(o=u);n.headers=Tr(a,"Content-Type",(i=o)!==null&&i!==void 0?i:"application/json"),n.body=JSON.stringify(s)}else n.body=s;return e?.duplex&&(n.duplex=e.duplex),C(C({},n),r)};async function Qt(t,e,r,s,n,i,a){return new Promise((o,l)=>{t(r,so(e,s,n,i)).then(u=>{if(!u.ok)throw u;if(s?.noResolveJson)return u;if(a==="vectors"){const d=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!d||!d.includes("application/json"))return{}}return u.json()}).then(u=>o(u)).catch(u=>ro(u,l,s,a))})}function Zs(t="storage"){return{get:async(e,r,s,n)=>Qt(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,i)=>Qt(e,"POST",r,n,i,s,t),put:async(e,r,s,n,i)=>Qt(e,"PUT",r,n,i,s,t),head:async(e,r,s,n)=>Qt(e,"HEAD",r,C(C({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,i)=>Qt(e,"DELETE",r,n,i,s,t)}}const no=Zs("storage"),{get:Xt,post:ze,put:is,head:io,remove:Zt}=no,De=Zs("vectors");var Dt=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=Xa(e),this.fetch=Za(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=Tr(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(xr(r))return{data:null,error:r};throw r}}};let en;en=Symbol.toStringTag;var ao=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[en]="StreamDownloadBuilder",this.promise=null}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(xr(e))return{data:null,error:e};throw e}}};let tn;tn=Symbol.toStringTag;var oo=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[tn]="BlobDownloadBuilder",this.promise=null}asStream(){return new ao(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(xr(e))return{data:null,error:e};throw e}}};const as={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},rn={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var lo=class extends Dt{constructor(t,e={},r,s){super(t,e,s,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,s){var n=this;return n.handleOperation(async()=>{let i;const a=C(C({},rn),s);let o=C(C({},n.headers),t==="POST"&&{"x-upsert":String(a.upsert)});const l=a.metadata;if(typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),l&&i.append("metadata",n.encodeMetadata(l)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",a.cacheControl),l&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(l))):(i=r,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!a.duplex&&(a.duplex="half")),s?.headers)for(const[p,m]of Object.entries(s.headers))o=Tr(o,p,m);const u=n._removeEmptyFolders(e),d=n._getFinalPath(u),h=await(t=="PUT"?is:ze)(n.fetch,`${n.url}/object/${d}`,i,C({headers:o},a?.duplex?{duplex:a.duplex}:{}));return{path:u,id:h.Id,fullPath:h.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,s){var n=this;const i=n._removeEmptyFolders(t),a=n._getFinalPath(i),o=new URL(n.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",e),n.handleOperation(async()=>{let l;const u=C(C({},rn),s);let d=C(C({},n.headers),{"x-upsert":String(u.upsert)});const h=u.metadata;if(typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),h&&l.append("metadata",n.encodeMetadata(h)),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.has("cacheControl")||l.append("cacheControl",u.cacheControl),h&&!l.has("metadata")&&l.append("metadata",n.encodeMetadata(h))):(l=r,d["cache-control"]=`max-age=${u.cacheControl}`,d["content-type"]=u.contentType,h&&(d["x-metadata"]=n.toBase64(n.encodeMetadata(h))),(typeof ReadableStream<"u"&&l instanceof ReadableStream||l&&typeof l=="object"&&"pipe"in l&&typeof l.pipe=="function")&&!u.duplex&&(u.duplex="half")),s?.headers)for(const[p,m]of Object.entries(s.headers))d=Tr(d,p,m);return{path:i,fullPath:(await is(n.fetch,o.toString(),l,C({headers:d},u?.duplex?{duplex:u.duplex}:{}))).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t);const n=C({},r.headers);e?.upsert&&(n["x-upsert"]="true");const i=await ze(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),a=new URL(r.url+i.url),o=a.searchParams.get("token");if(!o)throw new Sr("No token returned by API");return{signedUrl:a.toString(),path:t,token:o}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var s=this;return s.handleOperation(async()=>await ze(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket,sourceVersionId:r?.sourceVersionId},{headers:s.headers}))}async copy(t,e,r){var s=this;return s.handleOperation(async()=>({path:(await ze(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket,sourceVersionId:r?.sourceVersionId},{headers:s.headers})).Key}))}async createSignedUrl(t,e,r){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(t);const i=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0;let a=await ze(s.fetch,`${s.url}/object/sign/${n}`,C({expiresIn:e},i?{transform:r.transform}:{}),{headers:s.headers});const o=new URLSearchParams;r?.download&&o.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&o.set("cacheNonce",String(r.cacheNonce));const l=o.toString();return{signedUrl:encodeURI(`${s.url}${a.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{const n=await ze(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:t},{headers:s.headers}),i=new URLSearchParams;r?.download&&i.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&i.set("cacheNonce",String(r.cacheNonce));const a=i.toString();return n.map(o=>C(C({},o),{},{signedUrl:o.signedURL?encodeURI(`${s.url}${o.signedURL}${a?`&${a}`:""}`):null}))})}download(t,e,r){const s=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",n=new URLSearchParams;e?.transform&&this.applyTransformOptsToQuery(n,e.transform),e?.cacheNonce!=null&&n.set("cacheNonce",String(e.cacheNonce)),e?.versionId!=null&&n.set("versionId",String(e.versionId));const i=n.toString(),a=this._getFinalPath(t),o=()=>Xt(this.fetch,`${this.url}/${s}/${a}${i?`?${i}`:""}`,{headers:this.headers,noResolveJson:!0},r);return new oo(o,this.shouldThrowOnError)}async info(t,e){var r=this;const s=r._getFinalPath(t),n=new URLSearchParams;e?.versionId!=null&&n.set("versionId",String(e.versionId));const i=n.toString();return r.handleOperation(async()=>ns(await Xt(r.fetch,`${r.url}/object/info/${s}${i?`?${i}`:""}`,{headers:r.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await io(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(xr(n)){var s;const i=n instanceof ss?n.status:n instanceof Ys?(s=n.originalError)===null||s===void 0?void 0:s.status:void 0;if(i!==void 0&&[400,404].includes(i))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){const r=this._getFinalPath(t),s=new URLSearchParams;e?.download&&s.set("download",e.download===!0?"":e.download),e?.transform&&this.applyTransformOptsToQuery(s,e.transform),e?.cacheNonce!=null&&s.set("cacheNonce",String(e.cacheNonce));const n=s.toString(),i=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}`)+(n?`?${n}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await Zt(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async purgeCache(t,e,r){var s=this;return s.handleOperation(async()=>{const n=Qs(s._getFinalPath(t)),i=new URLSearchParams;e?.transformations&&i.set("transformations","true");const a=i.toString();return await Zt(s.fetch,`${s.url}/cdn/${n}${a?`?${a}`:""}`,{},{headers:s.headers},r)})}async list(t,e,r){var s=this;return s.handleOperation(async()=>{const n=e?.sortBy?C(C({},as.sortBy),e.sortBy):as.sortBy,i=C(C(C({},as),e),{},{sortBy:n,prefix:t||""});return await ze(s.fetch,`${s.url}/object/list/${s.bucketId}`,i,{headers:s.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{const s=C({},t);return await ze(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("quality",e.quality.toString()),t}};const er={"X-Client-Info":"storage-js/2.115.0"};var co=class extends Dt{constructor(t,e={},r,s){const n=new URL(t);s?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));const i=n.href.replace(/\/$/,""),a=C(C({},er),e);super(i,a,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await Xt(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Xt(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await ze(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes,versioning_status:e.versioningStatus},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await is(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes,versioning_status:e.versioningStatus},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await ze(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Zt(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}async purgeBucketCache(t,e,r){var s=this;return s.handleOperation(async()=>{const n=new URLSearchParams;e?.transformations&&n.set("transformations","true");const i=n.toString();return await Zt(s.fetch,`${s.url}/cdn/${Qs(t)}${i?`?${i}`:""}`,{},{headers:s.headers},r)})}listBucketOptionsToQueryString(t){const e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},uo=class extends Dt{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},er),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await ze(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);const s=r.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await Xt(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Zt(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!to(t))throw new Sr("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 Va({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(n,i){const a=n[i];return typeof a!="function"?a:async(...o)=>{try{return{data:await a.apply(n,o),error:null}}catch(l){if(s)throw l;return{data:null,error:l}}}}})}},ho=class extends Dt{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},er),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await De.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await De.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},fo=class extends Dt{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},er),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},mo=class extends Dt{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},er),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},po=class extends mo{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new go(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)}},go=class extends ho{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 yo(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},yo=class extends fo{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}))}},bo=class extends co{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new lo(this.url,this.headers,t,this.fetch)}get vectors(){return new po(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new uo(this.url+"/iceberg",this.headers,this.fetch)}};const sn="2.115.0",it=30*1e3,tr=3,os=tr*it,vo=2*it,wo="http://localhost:9999",_o="supabase.auth.token",ko={"X-Client-Info":`gotrue-js/${sn}`},ls="X-Supabase-Api-Version",nn={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},So=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,vt="sb_flow_id",xo=5,To=600*1e3;class rr extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function T(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class Eo extends rr{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}}function an(t){return T(t)&&t.name==="AuthApiError"}class Ve extends rr{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class et extends rr{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}}class be extends et{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Er(t){return T(t)&&t.name==="AuthSessionMissingError"}class $t extends et{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class jr extends et{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Ar 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 jo(t){return T(t)&&t.name==="AuthImplicitGrantRedirectError"}class on 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 Ao 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 Pr extends et{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function Rr(t){return T(t)&&t.name==="AuthRetryableFetchError"}class ln extends et{constructor(e="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(e,"AuthRefreshDiscardedError",409,void 0)}}function Po(t){return T(t)&&t.name==="AuthRefreshDiscardedError"}class cn 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 Or extends et{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Cr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),un=`
|
|
26
|
-
\r=`.split(""),Ro=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<un.length;e+=1)t[un[e].charCodeAt(0)]=-2;for(let e=0;e<Cr.length;e+=1)t[Cr[e].charCodeAt(0)]=e;return t})();function dn(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(Cr[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(Cr[s]),e.queuedBits-=6}}function hn(t,e,r){const s=Ro[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 fn(t){const e=[],r=a=>{e.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=a=>{No(a,s,r)};for(let a=0;a<t.length;a+=1)hn(t.charCodeAt(a),n,i);return e.join("")}function Oo(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 Co(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}Oo(s,e)}}function No(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 Lt(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)hn(t.charCodeAt(n),r,s);return new Uint8Array(e)}function Io(t){const e=[];return Co(t,r=>e.push(r)),new Uint8Array(e)}function wt(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>dn(n,r,s)),dn(null,r,s),e.join("")}function Do(t){return Math.round(Date.now()/1e3)+t}function $o(){return Symbol("auth-callback")}const we=()=>typeof window<"u"&&typeof document<"u",_t={tested:!1,writable:!1},mn=()=>{if(!we())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(_t.tested)return _t.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),_t.tested=!0,_t.writable=!0}catch{_t.tested=!0,_t.writable=!1}return _t.writable};function pn(t){const e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,i)=>{e[i]=n})}catch{}return r.searchParams.forEach((s,n)=>{e[n]=s}),e}const gn=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Lo=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",at=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},ke=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return null}},Re=async(t,e)=>{await t.removeItem(e)};class Nr{constructor(){this.promise=new Nr.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}Nr.promiseConstructor=Promise;function Ir(t){const e=t.split(".");if(e.length!==3)throw new Or("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!So.test(e[s]))throw new Or("JWT not in base64url format");return{header:JSON.parse(fn(e[0])),payload:JSON.parse(fn(e[1])),signature:Lt(e[2]),raw:{header:e[0],payload:e[1]}}}async function Mo(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Uo(t,e){return new Promise((s,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{const a=await t(i);if(!e(i,null,a)){s(a);return}}catch(a){if(!e(i,a)){n(a);return}}})()})}function yn(t){return("0"+t.toString(16)).substr(-2)}function Bo(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=r.length;let n="";for(let i=0;i<56;i++)n+=r.charAt(Math.floor(Math.random()*s));return n}return crypto.getRandomValues(e),Array.from(e,yn).join("")}async function Fo(t){const r=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(s);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}async function Ko(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 Fo(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}const qo=/^[a-zA-Z0-9_-]{8,64}$/;function Dr(t){return typeof t=="string"&&qo.test(t)?t:null}function Wo(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,yn).join("")}let t="";for(let e=0;e<32;e++)t+=Math.floor(Math.random()*16).toString(16);return t}const Mt=(t,e)=>`${t}-flow-${e}-code-verifier`,sr=t=>`${t}-flows-code-verifier`;async function cs(t,e){const r=await ke(t,sr(e));return Array.isArray(r)?r.filter(s=>Dr(s)!==null):[]}async function Ho(t,e,r,s,n){await at(t,Mt(e,r),s);const i=(await cs(t,e)).filter(a=>a!==r);for(i.push(r);i.length>xo;){const a=i.shift();await Re(t,Mt(e,a)),n?.(a)}await at(t,sr(e),i),await at(t,`${e}-code-verifier`,s)}async function Go(t,e,r){if(r){const n=await ke(t,Mt(e,r));return{verifier:typeof n=="string"?n:null,flowId:r}}const s=await ke(t,`${e}-code-verifier`);return{verifier:typeof s=="string"?s:null,flowId:null}}async function Je(t,e,r){const s=`${e}-code-verifier`;if(!r){await Re(t,s);return}const n=Mt(e,r),i=await ke(t,n);await Re(t,n);const a=await cs(t,e),o=a.filter(l=>l!==r);o.length!==a.length&&(o.length>0?await at(t,sr(e),o):await Re(t,sr(e))),i!=null&&i===await ke(t,s)&&await Re(t,s)}async function zo(t,e){const r=await cs(t,e);for(const s of r)await Re(t,Mt(e,s));await Re(t,sr(e)),await Re(t,`${e}-code-verifier`)}function Vo(t,e){const r=t.indexOf("#");let s=r===-1?t:t.slice(0,r);const n=r===-1?"":t.slice(r),i=s.indexOf("?");if(i!==-1){const o=s.slice(0,i),l=s.slice(i+1).split("&").filter(u=>u!==""&&u!==vt&&!u.startsWith(`${vt}=`));s=l.length>0?`${o}?${l.join("&")}`:o}const a=s.includes("?")?"&":"?";return`${s}${a}${vt}=${encodeURIComponent(e)}${n}`}async function Jo(t,e,r=!1,s){const n=Bo();let i=n;r&&(i+="/recovery");const a=Wo();await Ho(t,e,a,i,s);const o=await Ko(n);return[o,n===o?"plain":"s256",a]}const Yo=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Qo(t){const e=t.headers.get(ls);if(!e||!e.match(Yo))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Xo(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 Zo(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 el=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ot(t){if(!el.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ye(t){if(!t.passkey)throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function us(){const t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){const s=r.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function tl(t,e){return new Proxy(t,{get:(r,s,n)=>{if(s==="__isInsecureUserWarningProxy")return!0;if(typeof s=="symbol"){const i=s.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,s,n)}return!e.value&&typeof s=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,s,n)}})}function bn(t){return JSON.parse(JSON.stringify(t))}const kt=t=>{if(typeof t=="object"&&t!==null){const e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(t)},vn=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function wn(t){var e;if(!Lo(t))throw new Pr(kt(t),0);let r;try{r=await t.json()}catch(i){throw vn.includes(t.status)?new Pr(t.statusText||`HTTP ${t.status}`,t.status):new Ve(kt(i),i)}if(vn.includes(t.status))throw new Pr(kt(r),t.status);let s;const n=Qo(t);if(n&&n.getTime()>=nn["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 cn(kt(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new be}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,a)=>i&&typeof a=="string",!0))throw new cn(kt(r),t.status,r.weak_password.reasons);throw new Eo(kt(r),t.status||500,s)}const rl=(t,e,r,s)=>{const n={method:t,headers:e?.headers||{}};return t==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))};async function P(t,e,r,s){var n;const i=Object.assign({},s?.headers);i[ls]||(i[ls]=nn["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);const a=(n=s?.query)!==null&&n!==void 0?n:{};s?.redirectTo&&(a.redirect_to=s.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await sl(t,e,r+o,{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function sl(t,e,r,s,n,i){const a=rl(e,s,n,i);let o;try{o=await t(r,Object.assign({},a))}catch(l){throw new Pr(kt(l),0)}if(o.ok||await wn(o),s?.noResolveJson)return o;try{return await o.json()}catch(l){await wn(l)}}function Ue(t){var e;let r=null;al(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Do(t.expires_in)));const s=(e=t.user)!==null&&e!==void 0?e:typeof t?.id=="string"?t:null;return{data:{session:r,user:s},error:null}}function _n(t){const e=Ue(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,s)=>r&&typeof s=="string",!0)&&(e.data.weak_password=t.weak_password),e}function dt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function nl(t){return{data:t,error:null}}function il(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=t,a=yr(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},l=Object.assign({},a);return{data:{properties:o,user:l},error:null}}function kn(t){return t}function al(t){return!!t.access_token&&!!t.refresh_token&&!!t.expires_in}const ds=["global","local","others"];class ol{constructor({url:e="",headers:r={},fetch:s,experimental:n}){this.url=e,this.headers=r,this.fetch=gn(s),this.experimental=n??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,r=ds[0]){if(ds.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ds.join(", ")}`);try{return await P(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(T(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await P(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:dt})}catch(s){if(T(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:r}=e,s=yr(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:il,redirectTo:r?.redirectTo})}catch(r){if(T(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await P(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:dt})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,s,n,i,a,o,l;try{const u={nextPage:null,lastPage:0,total:0},d=await P(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:kn});if(d.error)throw d.error;const h=await d.json(),p=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,m=(l=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(g.split(";")[1].split("=")[1]);u[`${_}Page`]=y}),u.total=parseInt(p)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(T(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){ot(e);try{return await P(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:dt})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){ot(e);try{return await P(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:dt})}catch(s){if(T(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){ot(e);try{return await P(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:dt})}catch(s){if(T(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){ot(e.userId);try{const{data:r,error:s}=await P(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:s}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _deleteFactor(e){ot(e.userId),ot(e.id);try{return{data:await P(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,s,n,i,a,o,l;try{const u={nextPage:null,lastPage:0,total:0},d=await P(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:kn});if(d.error)throw d.error;const h=await d.json(),p=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,m=(l=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(g.split(";")[1].split("=")[1]);u[`${_}Page`]=y}),u.total=parseInt(p)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(T(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await P(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await P(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await P(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(T(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await P(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await P(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{const r={};return e?.type&&(r.type=e.type),await P(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:s=>{var n;return{data:{providers:(n=s?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(T(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await P(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await P(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await P(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(T(s))return{data:null,error:s};throw s}}async _deleteCustomProvider(e){try{return await P(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _adminListPasskeys(e){Ye(this.experimental),ot(e.userId);try{return await P(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _adminDeletePasskey(e){Ye(this.experimental),ot(e.userId),ot(e.passkeyId);try{return await P(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}}function Sn(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}globalThis&&mn()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug");class ll extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}function cl(){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 xn(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function ul(t){return parseInt(t,16)}function dl(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function hl(t){var e;const{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:l,resources:u,scheme:d,uri:h,version:p}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!h)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(p!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${p}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
|
|
27
|
-
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}const m=
|
|
28
|
-
`:"",
|
|
25
|
+
});`;class La{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var s;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new ra,this._manuallySetToken=!1,this._authPromise=null,this._authGeneration=0,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=i=>i?(...a)=>i(...a):(...a)=>fetch(...a),!(!((s=r?.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;const n=this._initializeOptions(r);this.socketAdapter=new Oa(e,n),this.httpEndpoint=Bs(e),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){const r=e.message;throw new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return r==="ok"&&e.teardown(),r}async removeAllChannels(){const e=this.channels.map(async s=>{const n=await s.unsubscribe();return s.teardown(),n}),r=await Promise.all(e);return await this.disconnect(),r}log(e,r,s){this.socketAdapter.log(e,r,s)}hasLogger(){return this.socketAdapter.hasLogger()}connectionState(){return this.socketAdapter.connectionState()||Zr.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){const s=`realtime:${e}`,n=this.getChannels().find(i=>i.topic===s);if(n)return n;{const i=new nt(`realtime:${e}`,r,this);return this._cancelPendingDisconnect(),this.channels.push(i),i}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){const r=++this._authGeneration,s=this._performAuth(e,r);r===this._authGeneration&&(this._authPromise=s);try{await s}finally{this._authPromise===s&&(this._authPromise=null)}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic),this.channels.length===0&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e,r){let s,n=!1;if(e)s=e,n=!0;else if(this.accessToken)try{s=await this.accessToken()}catch(i){this.log("error","Error fetching access token from callback",i),s=this.accessTokenValue}else s=this.accessTokenValue;r===this._authGeneration&&(this.accessToken?this._manuallySetToken=!1:n&&(this._manuallySetToken=!0),this.accessTokenValue!=s&&(this.accessTokenValue=s,this.channels.forEach(i=>{const a={access_token:s,version:Qi};i.updateJoinPayload(a),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push(Ls.access_token,{access_token:s})})))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,s)=>{r!=="disconnected"&&(r=="sent"&&this._setAuthSafely(),e&&e(r,s))}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{const s=new Blob([$a],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_initializeOptions(e){var r,s,n,i,a,o,l,u,d,h,p,m;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(s=e?.accessToken)!==null&&s!==void 0?s:null;const g={};g.timeout=(n=e?.timeout)!==null&&n!==void 0?n:ea,g.heartbeatIntervalMs=(i=e?.heartbeatIntervalMs)!==null&&i!==void 0?i:Gs.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(a=e?.disconnectOnEmptyChannelsAfterMs)!==null&&a!==void 0?a:2*((o=e?.heartbeatIntervalMs)!==null&&o!==void 0?o:Gs.HEARTBEAT_INTERVAL),g.transport=(l=e?.transport)!==null&&l!==void 0?l:Yi.getWebSocketConstructor(),g.params=e?.params,g.logger=e?.logger,g.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),g.sessionStorage=(u=e?.sessionStorage)!==null&&u!==void 0?u:Da(),g.reconnectAfterMs=(d=e?.reconnectAfterMs)!==null&&d!==void 0?d:(_=>Ca[_-1]||Na);let y,x;const v=(h=e?.vsn)!==null&&h!==void 0?h:Zi;switch(v){case Xi:y=(_,k)=>k(JSON.stringify(_)),x=(_,k)=>k(JSON.parse(_));break;case $s:y=this.serializer.encode.bind(this.serializer),x=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${g.vsn}`)}if(g.vsn=v,g.encode=(p=e?.encode)!==null&&p!==void 0?p:y,g.decode=(m=e?.decode)!==null&&m!==void 0?m:x,g.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,g.params=Object.assign(Object.assign({},g.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,g.autoSendHeartbeat=!this.worker}return g}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var Vt=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Ma(t,e,r){const s=new URL(e,t);if(r)for(const[n,i]of Object.entries(r))i!==void 0&&s.searchParams.set(n,i);return s.toString()}async function Ua(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function Ba(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:a}){const o=Ma(t.baseUrl,s,n),l=await Ua(t.auth),u=await e(o,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...a},body:i?JSON.stringify(i):void 0}),d=await u.text(),h=(u.headers.get("content-type")||"").includes("application/json"),p=h&&d?JSON.parse(d):d;if(!u.ok){const m=h?p:void 0,g=m?.error;throw new Vt(g?.message??`Request failed with status ${u.status}`,{status:u.status,icebergType:g?.type,icebergCode:g?.code,details:m})}return{status:u.status,headers:u.headers,data:p}}}}function _r(t){return t.join("")}var Fa=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:_r(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(s=>({namespace:s}))}async createNamespace(t,e){const r={namespace:t.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${_r(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${_r(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${_r(t.namespace)}`}),!0}catch(e){if(e instanceof Vt&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof Vt&&r.status===409)return;throw r}}};function Nt(t){return t.join("")}var Ka=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Nt(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){const r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Nt(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Nt(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Nt(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(t){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Nt(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Nt(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof Vt&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof Vt&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},qa=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Ba({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new Fa(this.client,e),this.tableOps=new Ka(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};function Jt(t){"@babel/helpers - typeof";return Jt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Jt(t)}function Wa(t,e){if(Jt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(Jt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ha(t){var e=Wa(t,"string");return Jt(e)=="symbol"?e:e+""}function Ga(t,e,r){return(e=Ha(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function zs(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function C(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?zs(Object(r),!0).forEach(function(s){Ga(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):zs(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var kr=class extends Error{constructor(t,e="storage",r,s){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function Sr(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var ss=class extends kr{constructor(t,e,r,s="storage",n){super(t,s,e,r),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r,this.code=n}toJSON(){return C(C({},super.toJSON()),{},{code:this.code})}},Vs=class extends kr{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};function xr(t,e,r){const s=C({},t),n=e.toLowerCase();for(const i of Object.keys(s))i.toLowerCase()===n&&delete s[i];return s[n]=r,s}function za(t){const e={};for(const[r,s]of Object.entries(t))e[r.toLowerCase()]=s;return e}const Va=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ja=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},ns=t=>{if(Array.isArray(t))return t.map(r=>ns(r));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([r,s])=>{const n=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[n]=ns(s)}),e},Ya=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),Js=t=>t.split("/").map(encodeURIComponent).join("/"),Ys=t=>{if(typeof t=="object"&&t!==null){const e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){const r=e.error;if(typeof r.message=="string")return r.message}}return JSON.stringify(t)},Qa=async(t,e,r,s)=>{if(t!==null&&typeof t=="object"&&"json"in t&&typeof t.json=="function"){const n=t;let i=parseInt(String(n.status),10);Number.isFinite(i)||(i=500),n.json().then(a=>{const o=a?.statusCode||a?.code||i+"";e(new ss(Ys(a),i,o,s,a?.code))}).catch(()=>{const a=i+"";e(new ss(n.statusText||`HTTP ${i} error`,i,a,s))})}else e(new Vs(Ys(t),t,s))},Xa=(t,e,r,s)=>{const n={method:t,headers:e?.headers||{}};if(t==="GET"||t==="HEAD"||!s)return C(C({},n),r);if(Ja(s)){var i;const a=e?.headers||{};let o;for(const[l,u]of Object.entries(a))l.toLowerCase()==="content-type"&&(o=u);n.headers=xr(a,"Content-Type",(i=o)!==null&&i!==void 0?i:"application/json"),n.body=JSON.stringify(s)}else n.body=s;return e?.duplex&&(n.duplex=e.duplex),C(C({},n),r)};async function Yt(t,e,r,s,n,i,a){return new Promise((o,l)=>{t(r,Xa(e,s,n,i)).then(u=>{if(!u.ok)throw u;if(s?.noResolveJson)return u;if(a==="vectors"){const d=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!d||!d.includes("application/json"))return{}}return u.json()}).then(u=>o(u)).catch(u=>Qa(u,l,s,a))})}function Qs(t="storage"){return{get:async(e,r,s,n)=>Yt(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,i)=>Yt(e,"POST",r,n,i,s,t),put:async(e,r,s,n,i)=>Yt(e,"PUT",r,n,i,s,t),head:async(e,r,s,n)=>Yt(e,"HEAD",r,C(C({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,i)=>Yt(e,"DELETE",r,n,i,s,t)}}const Za=Qs("storage"),{get:Qt,post:ze,put:is,head:eo,remove:Xt}=Za,De=Qs("vectors");var It=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=za(e),this.fetch=Va(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=xr(this.headers,t,e),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(Sr(r))return{data:null,error:r};throw r}}};let Xs;Xs=Symbol.toStringTag;var to=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Xs]="StreamDownloadBuilder",this.promise=null}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Sr(e))return{data:null,error:e};throw e}}};let Zs;Zs=Symbol.toStringTag;var ro=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Zs]="BlobDownloadBuilder",this.promise=null}asStream(){return new to(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Sr(e))return{data:null,error:e};throw e}}};const as={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},en={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var so=class extends It{constructor(t,e={},r,s){super(t,e,s,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,s){var n=this;return n.handleOperation(async()=>{let i;const a=C(C({},en),s);let o=C(C({},n.headers),t==="POST"&&{"x-upsert":String(a.upsert)});const l=a.metadata;if(typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),l&&i.append("metadata",n.encodeMetadata(l)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",a.cacheControl),l&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(l))):(i=r,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!a.duplex&&(a.duplex="half")),s?.headers)for(const[p,m]of Object.entries(s.headers))o=xr(o,p,m);const u=n._removeEmptyFolders(e),d=n._getFinalPath(u),h=await(t=="PUT"?is:ze)(n.fetch,`${n.url}/object/${d}`,i,C({headers:o},a?.duplex?{duplex:a.duplex}:{}));return{path:u,id:h.Id,fullPath:h.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,s){var n=this;const i=n._removeEmptyFolders(t),a=n._getFinalPath(i),o=new URL(n.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",e),n.handleOperation(async()=>{let l;const u=C(C({},en),s);let d=C(C({},n.headers),{"x-upsert":String(u.upsert)});const h=u.metadata;if(typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),h&&l.append("metadata",n.encodeMetadata(h)),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.has("cacheControl")||l.append("cacheControl",u.cacheControl),h&&!l.has("metadata")&&l.append("metadata",n.encodeMetadata(h))):(l=r,d["cache-control"]=`max-age=${u.cacheControl}`,d["content-type"]=u.contentType,h&&(d["x-metadata"]=n.toBase64(n.encodeMetadata(h))),(typeof ReadableStream<"u"&&l instanceof ReadableStream||l&&typeof l=="object"&&"pipe"in l&&typeof l.pipe=="function")&&!u.duplex&&(u.duplex="half")),s?.headers)for(const[p,m]of Object.entries(s.headers))d=xr(d,p,m);return{path:i,fullPath:(await is(n.fetch,o.toString(),l,C({headers:d},u?.duplex?{duplex:u.duplex}:{}))).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t);const n=C({},r.headers);e?.upsert&&(n["x-upsert"]="true");const i=await ze(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),a=new URL(r.url+i.url),o=a.searchParams.get("token");if(!o)throw new kr("No token returned by API");return{signedUrl:a.toString(),path:t,token:o}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var s=this;return s.handleOperation(async()=>await ze(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:s.headers}))}async copy(t,e,r){var s=this;return s.handleOperation(async()=>({path:(await ze(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(t,e,r){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(t);const i=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0;let a=await ze(s.fetch,`${s.url}/object/sign/${n}`,C({expiresIn:e},i?{transform:r.transform}:{}),{headers:s.headers});const o=new URLSearchParams;r?.download&&o.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&o.set("cacheNonce",String(r.cacheNonce));const l=o.toString();return{signedUrl:encodeURI(`${s.url}${a.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{const n=await ze(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:t},{headers:s.headers}),i=new URLSearchParams;r?.download&&i.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&i.set("cacheNonce",String(r.cacheNonce));const a=i.toString();return n.map(o=>C(C({},o),{},{signedUrl:o.signedURL?encodeURI(`${s.url}${o.signedURL}${a?`&${a}`:""}`):null}))})}download(t,e,r){const s=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",n=new URLSearchParams;e?.transform&&this.applyTransformOptsToQuery(n,e.transform),e?.cacheNonce!=null&&n.set("cacheNonce",String(e.cacheNonce));const i=n.toString(),a=this._getFinalPath(t),o=()=>Qt(this.fetch,`${this.url}/${s}/${a}${i?`?${i}`:""}`,{headers:this.headers,noResolveJson:!0},r);return new ro(o,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>ns(await Qt(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await eo(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(Sr(n)){var s;const i=n instanceof ss?n.status:n instanceof Vs?(s=n.originalError)===null||s===void 0?void 0:s.status:void 0;if(i!==void 0&&[400,404].includes(i))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){const r=this._getFinalPath(t),s=new URLSearchParams;e?.download&&s.set("download",e.download===!0?"":e.download),e?.transform&&this.applyTransformOptsToQuery(s,e.transform),e?.cacheNonce!=null&&s.set("cacheNonce",String(e.cacheNonce));const n=s.toString(),i=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}`)+(n?`?${n}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await Xt(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async purgeCache(t,e,r){var s=this;return s.handleOperation(async()=>{const n=Js(s._getFinalPath(t)),i=new URLSearchParams;e?.transformations&&i.set("transformations","true");const a=i.toString();return await Xt(s.fetch,`${s.url}/cdn/${n}${a?`?${a}`:""}`,{},{headers:s.headers},r)})}async list(t,e,r){var s=this;return s.handleOperation(async()=>{const n=e?.sortBy?C(C({},as.sortBy),e.sortBy):as.sortBy,i=C(C(C({},as),e),{},{sortBy:n,prefix:t||""});return await ze(s.fetch,`${s.url}/object/list/${s.bucketId}`,i,{headers:s.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{const s=C({},t);return await ze(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("quality",e.quality.toString()),t}};const Zt={"X-Client-Info":"storage-js/2.112.4"};var no=class extends It{constructor(t,e={},r,s){const n=new URL(t);s?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));const i=n.href.replace(/\/$/,""),a=C(C({},Zt),e);super(i,a,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await Qt(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Qt(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await ze(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await is(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await ze(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Xt(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}async purgeBucketCache(t,e,r){var s=this;return s.handleOperation(async()=>{const n=new URLSearchParams;e?.transformations&&n.set("transformations","true");const i=n.toString();return await Xt(s.fetch,`${s.url}/cdn/${Js(t)}${i?`?${i}`:""}`,{},{headers:s.headers},r)})}listBucketOptionsToQueryString(t){const e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},io=class extends It{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},Zt),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await ze(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);const s=r.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await Qt(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Xt(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!Ya(t))throw new kr("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new qa({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(n,i){const a=n[i];return typeof a!="function"?a:async(...o)=>{try{return{data:await a.apply(n,o),error:null}}catch(l){if(s)throw l;return{data:null,error:l}}}}})}},ao=class extends It{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},Zt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await De.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await De.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},oo=class extends It{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},Zt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},lo=class extends It{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=C(C({},Zt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},co=class extends lo{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new uo(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},uo=class extends ao{constructor(t,e,r,s){super(t,e,s),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new ho(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},ho=class extends oo{constructor(t,e,r,s,n){super(t,e,n),this.vectorBucketName=r,this.indexName=s}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},fo=class extends no{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new so(this.url,this.headers,t,this.fetch)}get vectors(){return new co(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new io(this.url+"/iceberg",this.headers,this.fetch)}};const tn="2.112.4",it=30*1e3,er=3,os=er*it,mo=2*it,po="http://localhost:9999",go="supabase.auth.token",yo={"X-Client-Info":`gotrue-js/${tn}`},ls="X-Supabase-Api-Version",rn={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},bo=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,bt="sb_flow_id",vo=5,wo=600*1e3;class tr extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function T(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class _o extends tr{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}}function sn(t){return T(t)&&t.name==="AuthApiError"}class Ve extends tr{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class et extends tr{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}}class be extends et{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Tr(t){return T(t)&&t.name==="AuthSessionMissingError"}class Dt extends et{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Er extends et{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class jr extends et{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}function ko(t){return T(t)&&t.name==="AuthImplicitGrantRedirectError"}class nn extends et{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class So extends et{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class Ar extends et{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function Pr(t){return T(t)&&t.name==="AuthRetryableFetchError"}class an extends et{constructor(e="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(e,"AuthRefreshDiscardedError",409,void 0)}}function xo(t){return T(t)&&t.name==="AuthRefreshDiscardedError"}class on extends et{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class Rr extends et{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Or="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),ln=`
|
|
26
|
+
\r=`.split(""),To=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<ln.length;e+=1)t[ln[e].charCodeAt(0)]=-2;for(let e=0;e<Or.length;e+=1)t[Or[e].charCodeAt(0)]=e;return t})();function cn(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(Or[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(Or[s]),e.queuedBits-=6}}function un(t,e,r){const s=To[t];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function dn(t){const e=[],r=a=>{e.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=a=>{Ao(a,s,r)};for(let a=0;a<t.length;a+=1)un(t.charCodeAt(a),n,i);return e.join("")}function Eo(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function jo(t,e){for(let r=0;r<t.length;r+=1){let s=t.charCodeAt(r);if(s>55295&&s<=56319){const n=(s-55296)*1024&65535;s=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}Eo(s,e)}}function Ao(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let s=1;s<6;s+=1)if((t>>7-s&1)===0){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function $t(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)un(t.charCodeAt(n),r,s);return new Uint8Array(e)}function Po(t){const e=[];return jo(t,r=>e.push(r)),new Uint8Array(e)}function vt(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>cn(n,r,s)),cn(null,r,s),e.join("")}function Ro(t){return Math.round(Date.now()/1e3)+t}function Oo(){return Symbol("auth-callback")}const we=()=>typeof window<"u"&&typeof document<"u",wt={tested:!1,writable:!1},hn=()=>{if(!we())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(wt.tested)return wt.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),wt.tested=!0,wt.writable=!0}catch{wt.tested=!0,wt.writable=!1}return wt.writable};function fn(t){const e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,i)=>{e[i]=n})}catch{}return r.searchParams.forEach((s,n)=>{e[n]=s}),e}const mn=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Co=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",at=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},ke=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return null}},Re=async(t,e)=>{await t.removeItem(e)};class Cr{constructor(){this.promise=new Cr.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}Cr.promiseConstructor=Promise;function Nr(t){const e=t.split(".");if(e.length!==3)throw new Rr("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!bo.test(e[s]))throw new Rr("JWT not in base64url format");return{header:JSON.parse(dn(e[0])),payload:JSON.parse(dn(e[1])),signature:$t(e[2]),raw:{header:e[0],payload:e[1]}}}async function No(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Io(t,e){return new Promise((s,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{const a=await t(i);if(!e(i,null,a)){s(a);return}}catch(a){if(!e(i,a)){n(a);return}}})()})}function pn(t){return("0"+t.toString(16)).substr(-2)}function Do(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=r.length;let n="";for(let i=0;i<56;i++)n+=r.charAt(Math.floor(Math.random()*s));return n}return crypto.getRandomValues(e),Array.from(e,pn).join("")}async function $o(t){const r=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(s);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}async function Lo(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;const r=await $o(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}const Mo=/^[a-zA-Z0-9_-]{8,64}$/;function Ir(t){return typeof t=="string"&&Mo.test(t)?t:null}function Uo(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,pn).join("")}let t="";for(let e=0;e<32;e++)t+=Math.floor(Math.random()*16).toString(16);return t}const Lt=(t,e)=>`${t}-flow-${e}-code-verifier`,rr=t=>`${t}-flows-code-verifier`;async function cs(t,e){const r=await ke(t,rr(e));return Array.isArray(r)?r.filter(s=>Ir(s)!==null):[]}async function Bo(t,e,r,s,n){await at(t,Lt(e,r),s);const i=(await cs(t,e)).filter(a=>a!==r);for(i.push(r);i.length>vo;){const a=i.shift();await Re(t,Lt(e,a)),n?.(a)}await at(t,rr(e),i),await at(t,`${e}-code-verifier`,s)}async function Fo(t,e,r){if(r){const n=await ke(t,Lt(e,r));return{verifier:typeof n=="string"?n:null,flowId:r}}const s=await ke(t,`${e}-code-verifier`);return{verifier:typeof s=="string"?s:null,flowId:null}}async function Je(t,e,r){const s=`${e}-code-verifier`;if(!r){await Re(t,s);return}const n=Lt(e,r),i=await ke(t,n);await Re(t,n);const a=await cs(t,e),o=a.filter(l=>l!==r);o.length!==a.length&&(o.length>0?await at(t,rr(e),o):await Re(t,rr(e))),i!=null&&i===await ke(t,s)&&await Re(t,s)}async function Ko(t,e){const r=await cs(t,e);for(const s of r)await Re(t,Lt(e,s));await Re(t,rr(e)),await Re(t,`${e}-code-verifier`)}function qo(t,e){const r=t.indexOf("#");let s=r===-1?t:t.slice(0,r);const n=r===-1?"":t.slice(r),i=s.indexOf("?");if(i!==-1){const o=s.slice(0,i),l=s.slice(i+1).split("&").filter(u=>u!==""&&u!==bt&&!u.startsWith(`${bt}=`));s=l.length>0?`${o}?${l.join("&")}`:o}const a=s.includes("?")?"&":"?";return`${s}${a}${bt}=${encodeURIComponent(e)}${n}`}async function Wo(t,e,r=!1,s){const n=Do();let i=n;r&&(i+="/recovery");const a=Uo();await Bo(t,e,a,i,s);const o=await Lo(n);return[o,n===o?"plain":"s256",a]}const Ho=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Go(t){const e=t.headers.get(ls);if(!e||!e.match(Ho))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function zo(t){if(!t)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function Vo(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const Jo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ot(t){if(!Jo.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ye(t){if(!t.passkey)throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function us(){const t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){const s=r.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Yo(t,e){return new Proxy(t,{get:(r,s,n)=>{if(s==="__isInsecureUserWarningProxy")return!0;if(typeof s=="symbol"){const i=s.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,s,n)}return!e.value&&typeof s=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,s,n)}})}function gn(t){return JSON.parse(JSON.stringify(t))}const _t=t=>{if(typeof t=="object"&&t!==null){const e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(t)},yn=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function bn(t){var e;if(!Co(t))throw new Ar(_t(t),0);let r;try{r=await t.json()}catch(i){throw yn.includes(t.status)?new Ar(t.statusText||`HTTP ${t.status}`,t.status):new Ve(_t(i),i)}if(yn.includes(t.status))throw new Ar(_t(r),t.status);let s;const n=Go(t);if(n&&n.getTime()>=rn["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?s=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(s=r.error_code),s){if(s==="weak_password")throw new on(_t(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new be}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,a)=>i&&typeof a=="string",!0))throw new on(_t(r),t.status,r.weak_password.reasons);throw new _o(_t(r),t.status||500,s)}const Qo=(t,e,r,s)=>{const n={method:t,headers:e?.headers||{}};return t==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))};async function P(t,e,r,s){var n;const i=Object.assign({},s?.headers);i[ls]||(i[ls]=rn["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);const a=(n=s?.query)!==null&&n!==void 0?n:{};s?.redirectTo&&(a.redirect_to=s.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await Xo(t,e,r+o,{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function Xo(t,e,r,s,n,i){const a=Qo(e,s,n,i);let o;try{o=await t(r,Object.assign({},a))}catch(l){throw new Ar(_t(l),0)}if(o.ok||await bn(o),s?.noResolveJson)return o;try{return await o.json()}catch(l){await bn(l)}}function Ue(t){var e;let r=null;tl(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Ro(t.expires_in)));const s=(e=t.user)!==null&&e!==void 0?e:typeof t?.id=="string"?t:null;return{data:{session:r,user:s},error:null}}function vn(t){const e=Ue(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,s)=>r&&typeof s=="string",!0)&&(e.data.weak_password=t.weak_password),e}function dt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Zo(t){return{data:t,error:null}}function el(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=t,a=gr(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},l=Object.assign({},a);return{data:{properties:o,user:l},error:null}}function wn(t){return t}function tl(t){return!!t.access_token&&!!t.refresh_token&&!!t.expires_in}const ds=["global","local","others"];class rl{constructor({url:e="",headers:r={},fetch:s,experimental:n}){this.url=e,this.headers=r,this.fetch=mn(s),this.experimental=n??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,r=ds[0]){if(ds.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ds.join(", ")}`);try{return await P(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(T(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await P(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:dt})}catch(s){if(T(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:r}=e,s=gr(e,["options"]),n=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(n.new_email=s?.newEmail,delete n.newEmail),await P(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:el,redirectTo:r?.redirectTo})}catch(r){if(T(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await P(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:dt})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,s,n,i,a,o,l;try{const u={nextPage:null,lastPage:0,total:0},d=await P(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:wn});if(d.error)throw d.error;const h=await d.json(),p=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,m=(l=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),x=JSON.parse(g.split(";")[1].split("=")[1]);u[`${x}Page`]=y}),u.total=parseInt(p)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(T(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){ot(e);try{return await P(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:dt})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){ot(e);try{return await P(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:dt})}catch(s){if(T(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){ot(e);try{return await P(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:dt})}catch(s){if(T(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){ot(e.userId);try{const{data:r,error:s}=await P(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:s}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _deleteFactor(e){ot(e.userId),ot(e.id);try{return{data:await P(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,s,n,i,a,o,l;try{const u={nextPage:null,lastPage:0,total:0},d=await P(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:wn});if(d.error)throw d.error;const h=await d.json(),p=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,m=(l=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),x=JSON.parse(g.split(";")[1].split("=")[1]);u[`${x}Page`]=y}),u.total=parseInt(p)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(T(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await P(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await P(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await P(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(T(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await P(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await P(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{const r={};return e?.type&&(r.type=e.type),await P(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:s=>{var n;return{data:{providers:(n=s?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(T(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await P(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await P(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await P(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(T(s))return{data:null,error:s};throw s}}async _deleteCustomProvider(e){try{return await P(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _adminListPasskeys(e){Ye(this.experimental),ot(e.userId);try{return await P(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _adminDeletePasskey(e){Ye(this.experimental),ot(e.userId),ot(e.passkeyId);try{return await P(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}}function _n(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}globalThis&&hn()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug");class sl extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}function nl(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function kn(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function il(t){return parseInt(t,16)}function al(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function ol(t){var e;const{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:l,resources:u,scheme:d,uri:h,version:p}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!h)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(p!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${p}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
|
|
27
|
+
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}const m=kn(t.address),g=d?`${d}://${s}`:s,y=t.statement?`${t.statement}
|
|
28
|
+
`:"",x=`${g} wants you to sign in with your Ethereum account:
|
|
29
29
|
${m}
|
|
30
30
|
|
|
31
|
-
${y}`;let
|
|
31
|
+
${y}`;let v=`URI: ${h}
|
|
32
32
|
Version: ${p}
|
|
33
33
|
Chain ID: ${r}${a?`
|
|
34
34
|
Nonce: ${a}`:""}
|
|
35
|
-
Issued At: ${i.toISOString()}`;if(n&&(
|
|
36
|
-
Expiration Time: ${n.toISOString()}`),o&&(
|
|
37
|
-
Not Before: ${o.toISOString()}`),l&&(
|
|
38
|
-
Request ID: ${l}`),u){let
|
|
39
|
-
Resources:`;for(const
|
|
40
|
-
- ${
|
|
41
|
-
${b}`}class de extends Error{constructor({message:e,code:r,cause:s,name:n}){var i;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(i=n??(s instanceof Error?s.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class $r extends de{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function fl({error:t,options:e}){var r,s,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new de({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new de({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new de({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new de({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new de({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new de({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new de({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new de({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const a=window.location.hostname;if(Pn(a)){if(i.rp.id!==a)return new de({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new de({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new de({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new de({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new de({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function ml({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(Pn(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 pl{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const hs=new pl;function Tn(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=yr(t,["challenge","user","excludeCredentials"]),i=Lt(e).buffer,a=Object.assign(Object.assign({},r),{id:Lt(r.id).buffer}),o=Object.assign(Object.assign({},n),{challenge:i,user:a});if(s&&s.length>0){o.excludeCredentials=new Array(s.length);for(let l=0;l<s.length;l++){const u=s[l];o.excludeCredentials[l]=Object.assign(Object.assign({},u),{id:Lt(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return o}function En(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=yr(t,["challenge","allowCredentials"]),n=Lt(e).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let a=0;a<r.length;a++){const o=r[a];i.allowCredentials[a]=Object.assign(Object.assign({},o),{id:Lt(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return i}function jn(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:wt(new Uint8Array(t.response.attestationObject)),clientDataJSON:wt(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function An(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:wt(new Uint8Array(n.authenticatorData)),clientDataJSON:wt(new Uint8Array(n.clientDataJSON)),signature:wt(new Uint8Array(n.signature)),userHandle:n.userHandle?wt(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Pn(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Lr(){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 Rn(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new $r("Browser returned unexpected credential type",e)}:{data:null,error:new $r("Empty credential response",e)}}catch(e){return{data:null,error:fl({error:e,options:t})}}}async function On(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new $r("Browser returned unexpected credential type",e)}:{data:null,error:new $r("Empty credential response",e)}}catch(e){return{data:null,error:ml({error:e,options:t})}}}const gl={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},yl={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Mr(...t){const e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(const n of t)if(n)for(const i in n){const a=n[i];if(a!==void 0)if(Array.isArray(a))s[i]=a;else if(r(a))s[i]=a;else if(e(a)){const o=s[i];e(o)?s[i]=Mr(o,a):s[i]=Mr(a)}else s[i]=a}return s}function bl(t,e){return Mr(gl,t,e||{})}function vl(t,e){return Mr(yl,t,e||{})}class wl{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:s,signal:n},i){var a;try{const{data:o,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!o)return{data:null,error:l};const u=n??hs.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:d}=o.webauthn.credential_options.publicKey;if(!d.name){const h=s;if(h)d.name=`${d.id}:${h}`;else{const m=(await this.client.getUser()).data.user,g=((a=m?.user_metadata)===null||a===void 0?void 0:a.name)||m?.email||m?.id||"User";d.name=`${d.id}:${g}`}}d.displayName||(d.displayName=d.name)}switch(o.webauthn.type){case"create":{const d=bl(o.webauthn.credential_options.publicKey,i?.create),{data:h,error:p}=await Rn({publicKey:d,signal:u});return h?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:h}},error:null}:{data:null,error:p}}case"request":{const d=vl(o.webauthn.credential_options.publicKey,i?.request),{data:h,error:p}=await On(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:d,signal:u}));return h?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:h}},error:null}:{data:null,error:p}}}}catch(o){return T(o)?{data:null,error:o}:{data:null,error:new Ve("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new rr("rpId is required for WebAuthn authentication")};try{if(!Lr())return{data:null,error:new Ve("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{request:i});if(!a)return{data:null,error:o};const{webauthn:l}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:s,credential_response:l.credential_response}})}catch(a){return T(a)?{data:null,error:a}:{data:null,error:new Ve("Unexpected error in authenticate",a)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new rr("rpId is required for WebAuthn registration")};try{if(!Lr())return{data:null,error:new Ve("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this._enroll({friendlyName:e});if(!a)return await this.client.mfa.listFactors().then(d=>{var h;return(h=d.data)===null||h===void 0?void 0:h.all.find(p=>p.factor_type==="webauthn"&&p.friendly_name===e&&p.status==="unverified")}).then(d=>d?this.client.mfa.unenroll({factorId:d?.id}):void 0),{data:null,error:o};const{data:l,error:u}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:i});return l?this._verify({factorId:a.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:s,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(a){return T(a)?{data:null,error:a}:{data:null,error:new Ve("Unexpected error in register",a)}}}}cl();const _l={url:wo,storageKey:_o,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ko,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},Ut={};let Cn=!1;class nr{get jwks(){var e,r;return(r=(e=Ut[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Ut[this.storageKey]=Object.assign(Object.assign({},Ut[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Ut[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Ut[this.storageKey]=Object.assign(Object.assign({},Ut[this.storageKey]),{cachedAt:e})}constructor(e){var r,s,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},_l),e);if(this.storageKey=i.storageKey,this.instanceID=(r=nr.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,nr.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&we()){const a=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(a),this.logDebugMessages&&console.trace(a)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(s=i.experimental)!==null&&s!==void 0?s:{},this.admin=new ol({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=gn(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock!=null&&(this.lock=i.lock,Cn||(Cn=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new wl(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:mn()?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(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a),(a.data.event==="TOKEN_REFRESHED"||a.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(o){this._debug("#broadcastChannel","error",o)}})}i.skipAutoInitialize||this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${sn}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();const r=await this.initializePromise,s=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(const n of s)await this._notifyAllSubscribers(n.event,n.session,n.broadcast);return r}async _initialize(){var e;try{let r={},s="none";if(we()&&(r=pn(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),we()&&this.detectSessionInUrl&&s!=="none"){const{data:n,error:i}=await this._getSessionFromURL(r,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),jo(i)){const l=(e=i.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:a,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",a,"redirect type",o),await this._saveSession(a),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return T(r)?this._returnResult({error:r}):this._returnResult({error:new Ve("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const i=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:Ue}),{data:a,error:o}=i;if(o||!a)return this._returnResult({data:{user:null,session:null},error:o});const l=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(i){if(T(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,s,n;let i=null;try{let a;if("email"in e){const{email:h,password:p,options:m}=e;let g=null,y=null;this.flowType==="pkce"&&([g,y,i]=await this._getCodeChallengeAndMethod()),a=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(m?.emailRedirectTo,i),body:{email:h,password:p,data:(r=m?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:m?.captchaToken},code_challenge:g,code_challenge_method:y},xform:Ue})}else if("phone"in e){const{phone:h,password:p,options:m}=e;a=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:p,data:(s=m?.data)!==null&&s!==void 0?s:{},channel:(n=m?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:m?.captchaToken}},xform:Ue})}else throw new jr("You must provide either an email or phone number and a password");const{data:o,error:l}=a;if(l||!o)return await Je(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:l});const u=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:d,session:u},error:null})}catch(a){if(await Je(this.storage,this.storageKey,i),T(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithPassword(e){try{let r;if("email"in e){const{email:i,password:a,options:o}=e;r=await P(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:_n})}else if("phone"in e){const{phone:i,password:a,options:o}=e;r=await P(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:_n})}else throw new jr("You must provide either an email or phone number and a password");const{data:s,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){const i=new $t;return this._returnResult({data:{user:null,session:null},error:i})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,r){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,r)):this._exchangeCodeForSession(e,r)}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,s,n,i,a,o,l,u,d,h,p;let m,g;if("message"in e)m=e.message,g=e.signature;else{const{chain:y,wallet:_,statement:b,options:k}=e;let S;if(we())if(typeof _=="object")S=_;else{const L=window;if("ethereum"in L&&typeof L.ethereum=="object"&&"request"in L.ethereum&&typeof L.ethereum.request=="function")S=L.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof _!="object"||!k?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");S=_}const O=new URL((r=k?.url)!==null&&r!==void 0?r:window.location.href),R=await S.request({method:"eth_requestAccounts"}).then(L=>L).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!R||R.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const M=xn(R[0]);let E=(s=k?.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!E){const L=await S.request({method:"eth_chainId"});E=ul(L)}const $={domain:O.host,address:M,statement:b,uri:O.href,version:"1",chainId:E,nonce:(n=k?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(a=(i=k?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(o=k?.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(l=k?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=k?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(d=k?.signInWithEthereum)===null||d===void 0?void 0:d.resources};m=hl($),g=await S.request({method:"personal_sign",params:[dl(m),M]})}try{const{data:y,error:_}=await P(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:g},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:Ue});if(_)throw _;if(!y||!y.session||!y.user){const b=new $t;return this._returnResult({data:{user:null,session:null},error:b})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:_})}catch(y){if(T(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async signInWithSolana(e){var r,s,n,i,a,o,l,u,d,h,p,m;let g,y;if("message"in e)g=e.message,y=e.signature;else{const{chain:_,wallet:b,statement:k,options:S}=e;let O;if(we())if(typeof b=="object")O=b;else{const M=window;if("solana"in M&&typeof M.solana=="object"&&("signIn"in M.solana&&typeof M.solana.signIn=="function"||"signMessage"in M.solana&&typeof M.solana.signMessage=="function"))O=M.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof b!="object"||!S?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");O=b}const R=new URL((r=S?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in O&&O.signIn){const M=await O.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},S?.signInWithSolana),{version:"1",domain:R.host,uri:R.href}),k?{statement:k}:null));let E;if(Array.isArray(M)&&M[0]&&typeof M[0]=="object")E=M[0];else if(M&&typeof M=="object"&&"signedMessage"in M&&"signature"in M)E=M;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in E&&"signature"in E&&(typeof E.signedMessage=="string"||E.signedMessage instanceof Uint8Array)&&E.signature instanceof Uint8Array)g=typeof E.signedMessage=="string"?E.signedMessage:new TextDecoder().decode(E.signedMessage),y=E.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in O)||typeof O.signMessage!="function"||!("publicKey"in O)||typeof O!="object"||!O.publicKey||!("toBase58"in O.publicKey)||typeof O.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${R.host} wants you to sign in with your Solana account:`,O.publicKey.toBase58(),...k?["",k,""]:[""],"Version: 1",`URI: ${R.href}`,`Issued At: ${(n=(s=S?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=S?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${S.signInWithSolana.notBefore}`]:[],...!((a=S?.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${S.signInWithSolana.expirationTime}`]:[],...!((o=S?.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${S.signInWithSolana.chainId}`]:[],...!((l=S?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${S.signInWithSolana.nonce}`]:[],...!((u=S?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${S.signInWithSolana.requestId}`]:[],...!((h=(d=S?.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||h===void 0)&&h.length?["Resources",...S.signInWithSolana.resources.map(E=>`- ${E}`)]:[]].join(`
|
|
42
|
-
`);const M=await O.signMessage(new TextEncoder().encode(g),"utf8");if(!M||!(M instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");y=M}}try{const{data:_,error:b}=await P(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:wt(y)},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:Ue});if(b)throw b;if(!_||!_.session||!_.user){const k=new $t;return this._returnResult({data:{user:null,session:null},error:k})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:b})}catch(_){if(T(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e,r){const s=r?.flowId!=null,n=s?Dr(r?.flowId):we()?Dr(pn(window.location.href)[vt]):null;s&&!n&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",r?.flowId);const{verifier:i,flowId:a}=s&&!n?{verifier:null,flowId:null}:await Go(this.storage,this.storageKey,n),[o,l]=(i??"").split("/");try{if(!o&&this.flowType==="pkce")throw new Ao;const{data:u,error:d}=await P(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:o},xform:Ue});if(await Je(this.storage,this.storageKey,a),d)throw d;if(!u||!u.session||!u.user){const h=new $t;return this._returnResult({data:{user:null,session:null,redirectType:null},error:h})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers(l==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:l??null}),error:d})}catch(u){if(await Je(this.storage,this.storageKey,a),T(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:i,nonce:a}=e,o=await P(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:Ue}),{data:l,error:u}=o;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){const d=new $t;return this._returnResult({data:{user:null,session:null},error:d})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,a;let o=null;try{if("email"in e){const{email:l,options:u}=e;let d=null,h=null;this.flowType==="pkce"&&([d,h,o]=await this._getCodeChallengeAndMethod());const{error:p}=await P(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(r=u?.data)!==null&&r!==void 0?r:{},create_user:(s=u?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},code_challenge:d,code_challenge_method:h},redirectTo:this._maybeAppendFlowIdToRedirect(u?.emailRedirectTo,o)});return this._returnResult({data:{user:null,session:null},error:p})}if("phone"in e){const{phone:l,options:u}=e,{data:d,error:h}=await P(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(n=u?.data)!==null&&n!==void 0?n:{},create_user:(i=u?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},channel:(a=u?.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:d?.message_id},error:h})}throw new jr("You must provide either an email or phone number.")}catch(l){if(await Je(this.storage,this.storageKey,o),T(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:a,error:o}=await P(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:Ue});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");const l=a.session,u=a.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(T(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i;let a=null;try{let o=null,l=null;this.flowType==="pkce"&&([o,l,a]=await this._getCodeChallengeAndMethod());const u=await P(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:this._maybeAppendFlowIdToRedirect((r=e.options)===null||r===void 0?void 0:r.redirectTo,a)}),!((s=e?.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:l}),headers:this.headers,xform:nl});return!((n=u.data)===null||n===void 0)&&n.url&&we()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(o){if(await Je(this.storage,this.storageKey,a),T(o))return this._returnResult({data:null,error:o});throw o}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new be;const{error:n}=await P(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(T(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let r=null;try{const s=`${this.url}/resend`;if("email"in e){const{email:n,type:i,options:a}=e;let o=null,l=null;this.flowType==="pkce"&&([o,l,r]=await this._getCodeChallengeAndMethod());const{error:u}=await P(this.fetch,"POST",s,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:a?.captchaToken},code_challenge:o,code_challenge_method:l},redirectTo:this._maybeAppendFlowIdToRedirect(a?.emailRedirectTo,r)});return u&&await Je(this.storage,this.storageKey,r),this._returnResult({data:{user:null,session:null},error:u})}else if("phone"in e){const{phone:n,type:i,options:a}=e,{data:o,error:l}=await P(this.fetch,"POST",s,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:a?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:l})}throw new jr("You must provide either an email or phone number and a type")}catch(s){if(await Je(this.storage,this.storageKey,r),T(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await ke(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<os:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await ke(this.userStorage,this.storageKey+"-user");a?.user?e.user=a.user:e.user=us()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=tl(e.user,a),a.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);if(i){if(!!(e.expires_at&&e.expires_at*1e3>Date.now())){const o=await ke(this.storage,this.storageKey);if(o&&o.refresh_token===e.refresh_token)return this._returnResult({data:{session:e},error:null})}return this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r;return this.lock!=null?r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):r=await this._getUser(),r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await P(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:dt}):await this._useSession(async r=>{var s,n,i;const{data:a,error:o}=r;if(o)throw o;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new be}:await P(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:dt})})}catch(r){if(T(r))return Er(r)&&await this._removeSession(),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r)):await this._updateUser(e,r)}async _updateUser(e,r={}){let s=null;try{return await this._useSession(async n=>{const{data:i,error:a}=n;if(a)throw a;if(!i.session)throw new be;const o=i.session;let l=null,u=null;this.flowType==="pkce"&&e.email!=null&&([l,u,s]=await this._getCodeChallengeAndMethod());const{data:d,error:h}=await P(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(r?.emailRedirectTo,s),body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:u}),jwt:o.access_token,xform:dt});if(h)throw h;return o.user=d.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await Je(this.storage,this.storageKey,s),T(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new be;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:a}=Ir(e.access_token);if(a.exp&&(s=a.exp,n=s<=r),n){const{data:o,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o)return{data:{user:null,session:null},error:null};i=o}else{const{data:o,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(T(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){const{data:a,error:o}=r;if(o)throw o;e=(s=a.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new be;const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var s;try{if(!we())throw new Ar("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ar(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 on("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ar("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 on("No code detected.");const{data:S,error:O}=await this._exchangeCodeForSession(e.code,{flowId:e[vt]});if(O)throw O;const R=new URL(window.location.href);return R.searchParams.delete("code"),R.searchParams.delete(vt),window.history.replaceState(window.history.state,"",R.toString()),{data:{session:S.session,redirectType:(s=S.redirectType)!==null&&s!==void 0?s:null},error:null}}const{provider_token:n,provider_refresh_token:i,access_token:a,refresh_token:o,expires_in:l,expires_at:u,token_type:d}=e;if(!a||!l||!o||!d)throw new Ar("No session defined in URL");const h=Math.round(Date.now()/1e3),p=parseInt(l);let m=h+p;u&&(m=parseInt(u));const g=m-h;g*1e3<=it&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${p}s`);const y=m-p;h-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,m,h):h-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",y,m,h);const{data:_,error:b}=await this._getUser(a);if(b)throw b;const k={provider_token:n,provider_refresh_token:i,access_token:a,expires_in:p,expires_at:m,refresh_token:o,token_type:d,user:_.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:k,redirectType:e.type},error:null})}catch(n){if(T(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;const r=Dr(e[vt]);return r&&await ke(this.storage,Mt(this.storageKey,r))?!0:!!await ke(this.storage,`${this.storageKey}-code-verifier`)}async signOut(e={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;const n=async()=>{await this._removeSession()},{data:i,error:a}=r;if(a&&!Er(a))return this._returnResult({error:a});const o=(s=i.session)===null||s===void 0?void 0:s.access_token;if(o){const{error:l}=await this.admin.signOut(o,e);if(l&&!(an(l)&&(l.status===404||l.status===401||l.status===403)||Er(l)))return e!=="others"&&await n(),this._returnResult({error:l})}return e!=="others"&&await n(),this._returnResult({error:null})})}onAuthStateChange(e){const r=$o(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)}):await this._emitInitialSession(r)))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{const{data:{session:i},error:a}=r;if(a)throw a;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),Er(i)||Rr(i)||an(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null,i=null;this.flowType==="pkce"&&([s,n,i]=await this._getCodeChallengeAndMethod(!0));try{return await P(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(r.redirectTo,i)})}catch(a){if(await Je(this.storage,this.storageKey,i),T(a))return this._returnResult({data:null,error:a});throw a}}async getUserIdentities(){var e;try{const{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;let s=null;try{const{data:n,error:i}=await this._useSession(async a=>{var o,l,u,d,h;const{data:p,error:m}=a;if(m)throw m;const{url:g,flowId:y}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(l=e.options)===null||l===void 0?void 0:l.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return s=y,await P(this.fetch,"GET",g,{headers:this.headers,jwt:(h=(d=p.session)===null||d===void 0?void 0:d.access_token)!==null&&h!==void 0?h:void 0})});if(i)throw i;return we()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url,flowId:s},error:null})}catch(n){if(T(n))return this._returnResult({data:{provider:e.provider,url:null,flowId:s},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{const{error:n,data:{session:i}}=r;if(n)throw n;const{options:a,provider:o,token:l,access_token:u,nonce:d}=e,h=await P(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i?.access_token)!==null&&s!==void 0?s:void 0,body:{provider:o,id_token:l,access_token:u,nonce:d,link_identity:!0,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ue}),{data:p,error:m}=h;return m?this._returnResult({data:{user:null,session:null},error:m}):!p||!p.session||!p.user?this._returnResult({data:{user:null,session:null},error:new $t}):(p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("USER_UPDATED",p.session)),this._returnResult({data:p,error:m}))}catch(n){if(await Je(this.storage,this.storageKey,null),T(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:a}=r;if(a)throw a;return await P(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r="#_refreshAccessToken()";this._debug(r,"begin");try{const s=Date.now();return await Uo(async n=>(n>0&&await Mo(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await P(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Ue})),(n,i)=>{const a=200*Math.pow(2,n);return i&&Rr(i)&&Date.now()+a-s<it})}catch(s){if(this._debug(r,"error",s),T(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const{url:s,flowId:n}=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),we()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s,flowId:n},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await ke(this.storage,this.storageKey);if(n&&this.userStorage){let a=await ke(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:n.user},await at(this.userStorage,this.storageKey+"-user",a)),n.user=(e=a?.user)!==null&&e!==void 0?e:us()}else if(n&&!n.user&&!n.user){const a=await ke(this.storage,this.storageKey+"-user");a&&a?.user?(n.user=a.user,await Re(this.storage,this.storageKey+"-user"),await at(this.storage,this.storageKey,n)):n.user=us()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}const i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<os;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${os}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:a}=await this._callRefreshToken(n.refresh_token);a&&(Po(a)?this._debug(s,"refresh discarded by commit guard",a):this._debug(s,"refresh failed",a))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:o}=await this._getUser(n.access_token);!o&&a?.user?(n.user=a.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(s,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),Rr(n)?console.warn(n):console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new be;if(this.refreshingDeferred)return this.refreshingDeferred.promise;if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===e&&Date.now()<this.lastRefreshFailure.expiresAt)return this._debug("#_callRefreshToken()","returning cached failure (cooldown active)"),this.lastRefreshFailure.result;const n="#_callRefreshToken()";this._debug(n,"begin");try{this.refreshingDeferred=new Nr,this.refreshingDeferred.promise.then(void 0,()=>{});const i=await ke(this.storage,this.storageKey),{data:a,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!a.session)throw new be;const l=await ke(this.storage,this.storageKey);if(i!==null&&(l===null||l.refresh_token!==i.refresh_token)){this._debug(n,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:l?"replaced":"cleared"});const p={data:null,error:new ln};return this.refreshingDeferred.resolve(p),p}const d=this._sessionRemovalEpoch;if(await this._saveSession(a.session),this._sessionRemovalEpoch!==d){this._debug(n,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await Re(this.storage,this.storageKey),this.userStorage&&await Re(this.userStorage,this.storageKey+"-user");const p={data:null,error:new ln};return this.refreshingDeferred.resolve(p),p}await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const h={data:a.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(h),h}catch(i){if(this._debug(n,"error",i),T(i)){const a={data:null,error:i};if(!Rr(i)){const o=await ke(this.storage,this.storageKey);!!(o?.expires_at&&o.expires_at*1e3>Date.now())?this._debug(n,"proactive refresh failed, access token still valid — preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:a,expiresAt:Date.now()+vo},(r=this.refreshingDeferred)===null||r===void 0||r.resolve(a),a}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){if(this._pendingInitNotifications!==null&&s){this._pendingInitNotifications.push({event:e,session:r,broadcast:s});return}const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const i=[],a=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,r)}catch(l){i.push(l)}});if(await Promise.all(a),i.length>0){for(let o=0;o<i.length;o+=1)console.error(i[o]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await at(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=bn(n);await at(this.storage,this.storageKey,i)}else{const n=bn(r);await at(this.storage,this.storageKey,n)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.lastRefreshFailure=null,this.suppressGetSessionWarning=!1,await Re(this.storage,this.storageKey),await zo(this.storage,this.storageKey),await Re(this.storage,this.storageKey+"-user"),this.userStorage&&await Re(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&we()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),it);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/it);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${it}ms, refresh threshold is ${tr} ticks`),n<=tr&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof ll)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{const e=Date.now();try{await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/it);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${it}ms, refresh threshold is ${tr} ticks`),n<=tr&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!we()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;if(this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(r,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){let n=s?.redirectTo,i=null,a=null,o=null;this.flowType==="pkce"&&([i,a,o]=await this._getCodeChallengeAndMethod(),n=this._maybeAppendFlowIdToRedirect(n,o));const l=[`provider=${encodeURIComponent(r)}`];if(n&&l.push(`redirect_to=${encodeURIComponent(n)}`),s?.scopes&&l.push(`scopes=${encodeURIComponent(s.scopes)}`),i!=null&&a!=null){const u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});l.push(u.toString())}if(s?.queryParams){const u=new URLSearchParams(s.queryParams);l.push(u.toString())}return s?.skipBrowserRedirect&&l.push(`skip_http_redirect=${s.skipBrowserRedirect}`),{url:`${e}?${l.join("&")}`,flowId:o}}_maybeAppendFlowIdToRedirect(e,r){return!e||!r||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:Vo(e,r)}async _getCodeChallengeAndMethod(e=!1){return Jo(this.storage,this.storageKey,e,r=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",r))}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await P(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:u}=await P(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&l.type==="totp"&&(!((n=l?.totp)===null||n===void 0)&&n.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){const r=async()=>{try{return await this._useSession(async s=>{var n;const{data:i,error:a}=s;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?jn(e.webauthn.credential_response):An(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:u}=await P(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:u}))})}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challenge(e){const r=async()=>{try{return await this._useSession(async s=>{var n;const{data:i,error:a}=s;if(a)return this._returnResult({data:null,error:a});const o=await P(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;const{data:l}=o;if(l.type!=="webauthn")return{data:l,error:null};switch(l.webauthn.type){case"create":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:Tn(l.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:En(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challengeAndVerify(e){const{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{const{payload:m}=Ir(e);let g=null;m.aal&&(g=m.aal);let y=g;const{data:{user:_},error:b}=await this.getUser(e);if(b)return this._returnResult({data:null,error:b});((s=(r=_?.factors)===null||r===void 0?void 0:r.filter(O=>O.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(y="aal2");const S=m.amr||[];return{data:{currentLevel:g,nextLevel:y,currentAuthenticationMethods:S},error:null}}catch(m){if(T(m))return this._returnResult({data:null,error:m});throw m}const{data:{session:a},error:o}=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=Ir(a.access_token);let u=null;l.aal&&(u=l.aal);let d=u;((i=(n=a.user.factors)===null||n===void 0?void 0:n.filter(m=>m.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(d="aal2");const p=l.amr||[];return{data:{currentLevel:u,nextLevel:d,currentAuthenticationMethods:p},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await P(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new be})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new be});const a=await P(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&we()&&!r?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new be});const a=await P(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&we()&&!r?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await P(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new be})})}catch(e){if(T(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await P(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new be})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(o=>o.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+To>n)return s;const{data:i,error:a}=await P(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,s=i.keys.find(o=>o.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:m,error:g}=await this.getSession();if(g||!m.session)return this._returnResult({data:null,error:g});s=m.session.access_token}const{header:n,payload:i,signature:a,raw:{header:o,payload:l}}=Ir(s);if(!r?.allowExpired)try{Xo(i.exp)}catch(m){throw new Or(m instanceof Error?m.message:"JWT validation failed")}const u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!u){const{error:m}=await this.getUser(s);if(m)throw m;return{data:{claims:i,header:n,signature:a},error:null}}const d=Zo(n.alg),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,a,Io(`${o}.${l}`)))throw new Or("Invalid JWT signature");return{data:{claims:i,header:n,signature:a},error:null}}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}}async signInWithPasskey(e){var r,s,n;Ye(this.experimental);try{if(!Lr())return this._returnResult({data:null,error:new Ve("Browser does not support WebAuthn",null)});const{data:i,error:a}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}});if(a||!i)return this._returnResult({data:null,error:a});const o=En(i.options),l=(n=(s=e?.options)===null||s===void 0?void 0:s.signal)!==null&&n!==void 0?n:hs.createNewAbortSignal(),{data:u,error:d}=await On({publicKey:o,signal:l});if(d||!u)return this._returnResult({data:null,error:d??new Ve("WebAuthn ceremony failed",null)});const h=An(u);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:h})}catch(i){if(T(i))return this._returnResult({data:null,error:i});throw i}}async registerPasskey(e){var r,s;Ye(this.experimental);try{if(!Lr())return this._returnResult({data:null,error:new Ve("Browser does not support WebAuthn",null)});const{data:n,error:i}=await this._startPasskeyRegistration();if(i||!n)return this._returnResult({data:null,error:i});const a=Tn(n.options),o=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:hs.createNewAbortSignal(),{data:l,error:u}=await Rn({publicKey:a,signal:o});if(u||!l)return this._returnResult({data:null,error:u??new Ve("WebAuthn ceremony failed",null)});const d=jn(l);return this._verifyPasskeyRegistration({challengeId:n.challenge_id,credential:d})}catch(n){if(T(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyRegistration(){Ye(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new be});const{data:n,error:i}=await P(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(T(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){Ye(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new be});const{data:i,error:a}=await P(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:s.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;Ye(this.experimental);try{const{data:s,error:n}=await P(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:s,error:null})}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}}async _verifyPasskeyAuthentication(e){Ye(this.experimental);try{const{data:r,error:s}=await P(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:Ue});return s?this._returnResult({data:null,error:s}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){Ye(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new be});const{data:n,error:i}=await P(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:a=>({data:a,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(T(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){Ye(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new be});const{data:i,error:a}=await P(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,body:{friendly_name:e.friendlyName}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){Ye(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new be});const{error:i}=await P(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}}nr.nextInstanceID={};const kl=nr,Sl="2.115.0";let ir="",Ur;if(typeof Deno<"u"){var fs;ir="deno",Ur=(fs=Deno.version)===null||fs===void 0?void 0:fs.deno}else if(typeof document<"u")ir="web";else if(typeof navigator<"u"&&navigator.product==="ReactNative")ir="react-native";else{var ms;ir="node";const t=globalThis.process;Ur=t==null||(ms=t.version)===null||ms===void 0?void 0:ms.replace(/^v/,"")}const Nn=[`runtime=${ir}`];Ur&&Nn.push(`runtime-version=${Ur}`);const xl={headers:{"X-Client-Info":`supabase-js/${Sl}; ${Nn.join("; ")}`}},Tl={schema:"public"},El={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},jl={},Al={enabled:!1,respectSamplingDecision:!0};function Pl(t){if(!t||typeof t!="string")return null;const e=t.split("-");if(e.length!==4)return null;const[r,s,n,i]=e;if(r.length!==2||s.length!==32||n.length!==16||i.length!==2)return null;const a=/^[0-9a-f]+$/i;return!a.test(r)||!a.test(s)||!a.test(n)||!a.test(i)||s==="00000000000000000000000000000000"||n==="0000000000000000"?null:{version:r,traceId:s,parentId:n,traceFlags:i,isSampled:(parseInt(i,16)&1)===1}}function Rl(t,e){if(!t||!e||e.length===0)return!1;let r;if(t instanceof URL)r=t;else try{r=new URL(t)}catch{return!1}for(const s of e)try{if(typeof s=="string"){if(Ol(r.hostname,s))return!0}else if(s instanceof RegExp){if(s.test(r.hostname))return!0}else if(typeof s=="function"&&s(r))return!0}catch{continue}return!1}function Ol(t,e){if(e===t)return!0;if(e.startsWith("*.")){const r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function Cl(t){const e=[];try{const r=new URL(t);e.push(r.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function ar(t){"@babel/helpers - typeof";return ar=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},ar(t)}function Nl(t,e){if(ar(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(ar(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Il(t){var e=Nl(t,"string");return ar(e)=="symbol"?e:e+""}function Dl(t,e,r){return(e=Il(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function In(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function ie(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?In(Object(r),!0).forEach(function(s){Dl(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):In(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const $l=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ll=()=>Headers,Dn=t=>t.startsWith("sb_publishable_")||t.startsWith("sb_secret_"),Ml="sb_temp_",$n=new Set,Ul=t=>{var e,r;if(!t.startsWith("sb_")||Dn(t)||t.startsWith(Ml))return;const s=(e=(r=t.match(/^sb_[a-zA-Z0-9]+_/))===null||r===void 0?void 0:r[0])!==null&&e!==void 0?e:"unknown";$n.has(s)||($n.add(s),console.warn("@supabase/supabase-js: Unrecognized Supabase API key format. The client will proceed and send this key as-is; if you see authentication errors you may need to upgrade @supabase/supabase-js to a version that recognizes this key type."))},Ln=(t,e,r,s,n,i)=>{const a=$l(s),o=Ll(),l=n?.enabled===!0,u=n?.respectSamplingDecision!==!1,d=l?Cl(e):null,h=!(i?.omitApiKeyAsBearer&&Dn(t));return async(p,m)=>{const g=await r();let y=new o(m?.headers);if(y.has("apikey")||y.set("apikey",t),!y.has("Authorization")){const _=g??(h?t:null);_&&y.set("Authorization",`Bearer ${_}`)}if(d){const _=Bl(p,d,u);_&&(_.traceparent&&!y.has("traceparent")&&y.set("traceparent",_.traceparent),_.tracestate&&!y.has("tracestate")&&y.set("tracestate",_.tracestate),_.baggage&&!y.has("baggage")&&y.set("baggage",_.baggage))}return a(p,ie(ie({},m),{},{headers:y}))}};let Mn=!1,Un=!1;function Bl(t,e,r){const s=Mi();if(!s)return Mn||(Mn=!0,console.warn("@supabase/supabase-js: tracePropagation is enabled but the tracing runtime is not loaded, so trace headers will not be attached. Add `import '@supabase/supabase-js/tracing'` at your application entry point (requires the OpenTelemetry API package to be installed). The CDN/UMD build does not support trace propagation.")),null;if(!Rl(typeof t=="string"||t instanceof URL?t:t.url,e))return null;const n=s();if(!n||!n.traceparent){var i;if(!(n==null||(i=n.carrierKeys)===null||i===void 0)&&i.length&&!Un){Un=!0;const a=n.carrierKeys.includes("sentry-trace")?" Sentry detected: set `propagateTraceparent: true` in Sentry.init() to emit it.":" Configure your tracing SDK to emit W3C trace context on outgoing requests.";console.warn(`@supabase/supabase-js: tracePropagation is enabled and a tracing SDK is active, but its propagator wrote [${n.carrierKeys.join(", ")}] and no W3C traceparent header, so trace headers will not be attached.`+a)}return null}if(r){const a=Pl(n.traceparent);if(a&&!a.isSampled)return{traceparent:n.traceparent}}return n}function Bn(t){return typeof t=="boolean"?{enabled:t}:t}function Fl(t){return t.endsWith("/")?t:t+"/"}function Kl(t,e){var r,s,n,i,a,o;const{db:l,auth:u,realtime:d,global:h}=t,{db:p,auth:m,realtime:g,global:y}=e,_=Bn(t.tracePropagation),b=Bn(e.tracePropagation),k={db:ie(ie({},p),l),auth:ie(ie({},m),u),realtime:ie(ie({},g),d),storage:{},global:ie(ie(ie({},y),h),{},{headers:ie(ie({},(r=y?.headers)!==null&&r!==void 0?r:{}),(s=h?.headers)!==null&&s!==void 0?s:{})}),tracePropagation:{enabled:(n=(i=_?.enabled)!==null&&i!==void 0?i:b?.enabled)!==null&&n!==void 0?n:!1,respectSamplingDecision:(a=(o=_?.respectSamplingDecision)!==null&&o!==void 0?o:b?.respectSamplingDecision)!==null&&a!==void 0?a:!0},accessToken:async()=>""};return t.accessToken?k.accessToken=t.accessToken:delete k.accessToken,k}function ql(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(Fl(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Wl=class extends kl{constructor(t){super(t)}},Hl=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=ql(t);if(!e)throw new Error("supabaseKey is required.");Ul(e),this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const a=`sb-${i.hostname.split(".")[0]}-auth-token`,o={db:Tl,realtime:jl,auth:ie(ie({},El),{},{storageKey:a}),global:xl,tracePropagation:Al},l=Kl(r??{},o);if(this.settings=l,this.storageKey=(s=l.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(d,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=Ln(e,t,this._getSessionToken.bind(this),l.global.fetch,l.tracePropagation),this.functionsFetch=Ln(e,t,this._getSessionToken.bind(this),l.global.fetch,l.tracePropagation,{omitApiKeyAsBearer:!0}),this.realtime=this._initRealtimeClient(ie({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(d=>this.realtime.setAuth(d)).catch(d=>console.warn("Failed to set initial Realtime auth token:",d)),this.rest=new Xi(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit,retry:l.db.retry}),this.storage=new bo(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new Ki(this.functionsUrl.href,{headers:this.headers,customFetch:this.functionsFetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}getOpenApiSpec(){return this.rest.getOpenApiSpec()}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getSessionToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:null}async _getAccessToken(){var t=this,e;return(e=await t._getSessionToken())!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:a,lock:o,debug:l,throwOnError:u,experimental:d,lockAcquireTimeout:h,skipAutoInitialize:p},m,g){const y={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Wl({url:this.authUrl.href,headers:ie(ie({},y),m),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:o,debug:l,throwOnError:u,experimental:d,fetch:g,lockAcquireTimeout:h,skipAutoInitialize:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(_=>_.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Ka(this.realtimeUrl.href,ie(ie({},t),{},{params:ie(ie({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN"||t==="INITIAL_SESSION")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const Gl=(t,e,r)=>new Hl(t,e,r);function zl(){if(typeof window<"u"||globalThis.Deno!==void 0)return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=20:!1}zl()&&console.warn("⚠️ Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715");function Fn(t,e){if(!t||!e)throw new Error("Supabase URL and anon key are required");return Gl(t,e)}function Kn(t){const e=[];let r="",s=!1;for(let n=0;n<t.length;n++){const i=t[n];i==='"'?s&&t[n+1]==='"'?(r+='"',n++):s=!s:i===","&&!s?(e.push(r),r=""):r+=i}return e.push(r),e.map(n=>n.trim().replace(/^"|"$/g,""))}function Be(t,...e){const r=n=>n.trim().toLowerCase().replace(/[_\s]+/g," ").trim(),s=new Map;Object.entries(t).forEach(([n,i])=>s.set(r(n),i));for(const n of e){const i=s.get(r(n));if(i!==void 0&&i.trim())return i.trim()}return""}function Vl(t){const r=t.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
|
|
35
|
+
Issued At: ${i.toISOString()}`;if(n&&(v+=`
|
|
36
|
+
Expiration Time: ${n.toISOString()}`),o&&(v+=`
|
|
37
|
+
Not Before: ${o.toISOString()}`),l&&(v+=`
|
|
38
|
+
Request ID: ${l}`),u){let _=`
|
|
39
|
+
Resources:`;for(const k of u){if(!k||typeof k!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${k}`);_+=`
|
|
40
|
+
- ${k}`}v+=_}return`${x}
|
|
41
|
+
${v}`}class de extends Error{constructor({message:e,code:r,cause:s,name:n}){var i;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(i=n??(s instanceof Error?s.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class Dr extends de{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function ll({error:t,options:e}){var r,s,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new de({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new de({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new de({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new de({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new de({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new de({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new de({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new de({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const a=window.location.hostname;if(jn(a)){if(i.rp.id!==a)return new de({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new de({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new de({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new de({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new de({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function cl({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new de({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new de({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(jn(s)){if(r.rpId!==s)return new de({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new de({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new de({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new de({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class ul{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const hs=new ul;function Sn(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);const{challenge:e,user:r,excludeCredentials:s}=t,n=gr(t,["challenge","user","excludeCredentials"]),i=$t(e).buffer,a=Object.assign(Object.assign({},r),{id:$t(r.id).buffer}),o=Object.assign(Object.assign({},n),{challenge:i,user:a});if(s&&s.length>0){o.excludeCredentials=new Array(s.length);for(let l=0;l<s.length;l++){const u=s[l];o.excludeCredentials[l]=Object.assign(Object.assign({},u),{id:$t(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return o}function xn(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);const{challenge:e,allowCredentials:r}=t,s=gr(t,["challenge","allowCredentials"]),n=$t(e).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let a=0;a<r.length;a++){const o=r[a];i.allowCredentials[a]=Object.assign(Object.assign({},o),{id:$t(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return i}function Tn(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t;return{id:t.id,rawId:t.id,response:{attestationObject:vt(new Uint8Array(t.response.attestationObject)),clientDataJSON:vt(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function En(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t,s=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:vt(new Uint8Array(n.authenticatorData)),clientDataJSON:vt(new Uint8Array(n.clientDataJSON)),signature:vt(new Uint8Array(n.signature)),userHandle:n.userHandle?vt(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function jn(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function $r(){var t,e;return!!(we()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function An(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Dr("Browser returned unexpected credential type",e)}:{data:null,error:new Dr("Empty credential response",e)}}catch(e){return{data:null,error:ll({error:e,options:t})}}}async function Pn(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Dr("Browser returned unexpected credential type",e)}:{data:null,error:new Dr("Empty credential response",e)}}catch(e){return{data:null,error:cl({error:e,options:t})}}}const dl={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},hl={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Lr(...t){const e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(const n of t)if(n)for(const i in n){const a=n[i];if(a!==void 0)if(Array.isArray(a))s[i]=a;else if(r(a))s[i]=a;else if(e(a)){const o=s[i];e(o)?s[i]=Lr(o,a):s[i]=Lr(a)}else s[i]=a}return s}function fl(t,e){return Lr(dl,t,e||{})}function ml(t,e){return Lr(hl,t,e||{})}class pl{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:s,signal:n},i){var a;try{const{data:o,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!o)return{data:null,error:l};const u=n??hs.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:d}=o.webauthn.credential_options.publicKey;if(!d.name){const h=s;if(h)d.name=`${d.id}:${h}`;else{const m=(await this.client.getUser()).data.user,g=((a=m?.user_metadata)===null||a===void 0?void 0:a.name)||m?.email||m?.id||"User";d.name=`${d.id}:${g}`}}d.displayName||(d.displayName=d.name)}switch(o.webauthn.type){case"create":{const d=fl(o.webauthn.credential_options.publicKey,i?.create),{data:h,error:p}=await An({publicKey:d,signal:u});return h?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:h}},error:null}:{data:null,error:p}}case"request":{const d=ml(o.webauthn.credential_options.publicKey,i?.request),{data:h,error:p}=await Pn(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:d,signal:u}));return h?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:h}},error:null}:{data:null,error:p}}}}catch(o){return T(o)?{data:null,error:o}:{data:null,error:new Ve("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new tr("rpId is required for WebAuthn authentication")};try{if(!$r())return{data:null,error:new Ve("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{request:i});if(!a)return{data:null,error:o};const{webauthn:l}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:s,credential_response:l.credential_response}})}catch(a){return T(a)?{data:null,error:a}:{data:null,error:new Ve("Unexpected error in authenticate",a)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new tr("rpId is required for WebAuthn registration")};try{if(!$r())return{data:null,error:new Ve("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this._enroll({friendlyName:e});if(!a)return await this.client.mfa.listFactors().then(d=>{var h;return(h=d.data)===null||h===void 0?void 0:h.all.find(p=>p.factor_type==="webauthn"&&p.friendly_name===e&&p.status!=="unverified")}).then(d=>d?this.client.mfa.unenroll({factorId:d?.id}):void 0),{data:null,error:o};const{data:l,error:u}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:i});return l?this._verify({factorId:a.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:s,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(a){return T(a)?{data:null,error:a}:{data:null,error:new Ve("Unexpected error in register",a)}}}}nl();const gl={url:po,storageKey:go,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:yo,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},Mt={};let Rn=!1;class sr{get jwks(){var e,r;return(r=(e=Mt[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Mt[this.storageKey]=Object.assign(Object.assign({},Mt[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Mt[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Mt[this.storageKey]=Object.assign(Object.assign({},Mt[this.storageKey]),{cachedAt:e})}constructor(e){var r,s,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},gl),e);if(this.storageKey=i.storageKey,this.instanceID=(r=sr.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,sr.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&we()){const a=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(a),this.logDebugMessages&&console.trace(a)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(s=i.experimental)!==null&&s!==void 0?s:{},this.admin=new rl({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=mn(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock!=null&&(this.lock=i.lock,Rn||(Rn=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new pl(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:hn()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=_n(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=_n(this.memoryStorage)),we()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a),(a.data.event==="TOKEN_REFRESHED"||a.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(o){this._debug("#broadcastChannel","error",o)}})}i.skipAutoInitialize||this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${tn}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();const r=await this.initializePromise,s=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(const n of s)await this._notifyAllSubscribers(n.event,n.session,n.broadcast);return r}async _initialize(){var e;try{let r={},s="none";if(we()&&(r=fn(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),we()&&this.detectSessionInUrl&&s!=="none"){const{data:n,error:i}=await this._getSessionFromURL(r,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),ko(i)){const l=(e=i.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:a,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",a,"redirect type",o),await this._saveSession(a),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return T(r)?this._returnResult({error:r}):this._returnResult({error:new Ve("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const i=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:Ue}),{data:a,error:o}=i;if(o||!a)return this._returnResult({data:{user:null,session:null},error:o});const l=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(i){if(T(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,s,n;let i=null;try{let a;if("email"in e){const{email:h,password:p,options:m}=e;let g=null,y=null;this.flowType==="pkce"&&([g,y,i]=await this._getCodeChallengeAndMethod()),a=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(m?.emailRedirectTo,i),body:{email:h,password:p,data:(r=m?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:m?.captchaToken},code_challenge:g,code_challenge_method:y},xform:Ue})}else if("phone"in e){const{phone:h,password:p,options:m}=e;a=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:p,data:(s=m?.data)!==null&&s!==void 0?s:{},channel:(n=m?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:m?.captchaToken}},xform:Ue})}else throw new Er("You must provide either an email or phone number and a password");const{data:o,error:l}=a;if(l||!o)return await Je(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:l});const u=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:d,session:u},error:null})}catch(a){if(await Je(this.storage,this.storageKey,i),T(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithPassword(e){try{let r;if("email"in e){const{email:i,password:a,options:o}=e;r=await P(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:vn})}else if("phone"in e){const{phone:i,password:a,options:o}=e;r=await P(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:vn})}else throw new Er("You must provide either an email or phone number and a password");const{data:s,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){const i=new Dt;return this._returnResult({data:{user:null,session:null},error:i})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,r){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,r)):this._exchangeCodeForSession(e,r)}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,s,n,i,a,o,l,u,d,h,p;let m,g;if("message"in e)m=e.message,g=e.signature;else{const{chain:y,wallet:x,statement:v,options:_}=e;let k;if(we())if(typeof x=="object")k=x;else{const L=window;if("ethereum"in L&&typeof L.ethereum=="object"&&"request"in L.ethereum&&typeof L.ethereum.request=="function")k=L.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof x!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");k=x}const O=new URL((r=_?.url)!==null&&r!==void 0?r:window.location.href),R=await k.request({method:"eth_requestAccounts"}).then(L=>L).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!R||R.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const M=kn(R[0]);let E=(s=_?.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!E){const L=await k.request({method:"eth_chainId"});E=il(L)}const $={domain:O.host,address:M,statement:v,uri:O.href,version:"1",chainId:E,nonce:(n=_?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(a=(i=_?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(o=_?.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(l=_?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=_?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(d=_?.signInWithEthereum)===null||d===void 0?void 0:d.resources};m=ol($),g=await k.request({method:"personal_sign",params:[al(m),M]})}try{const{data:y,error:x}=await P(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:g},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:Ue});if(x)throw x;if(!y||!y.session||!y.user){const v=new Dt;return this._returnResult({data:{user:null,session:null},error:v})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:x})}catch(y){if(T(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async signInWithSolana(e){var r,s,n,i,a,o,l,u,d,h,p,m;let g,y;if("message"in e)g=e.message,y=e.signature;else{const{chain:x,wallet:v,statement:_,options:k}=e;let O;if(we())if(typeof v=="object")O=v;else{const M=window;if("solana"in M&&typeof M.solana=="object"&&("signIn"in M.solana&&typeof M.solana.signIn=="function"||"signMessage"in M.solana&&typeof M.solana.signMessage=="function"))O=M.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof v!="object"||!k?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");O=v}const R=new URL((r=k?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in O&&O.signIn){const M=await O.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},k?.signInWithSolana),{version:"1",domain:R.host,uri:R.href}),_?{statement:_}:null));let E;if(Array.isArray(M)&&M[0]&&typeof M[0]=="object")E=M[0];else if(M&&typeof M=="object"&&"signedMessage"in M&&"signature"in M)E=M;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in E&&"signature"in E&&(typeof E.signedMessage=="string"||E.signedMessage instanceof Uint8Array)&&E.signature instanceof Uint8Array)g=typeof E.signedMessage=="string"?E.signedMessage:new TextDecoder().decode(E.signedMessage),y=E.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in O)||typeof O.signMessage!="function"||!("publicKey"in O)||typeof O!="object"||!O.publicKey||!("toBase58"in O.publicKey)||typeof O.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${R.host} wants you to sign in with your Solana account:`,O.publicKey.toBase58(),..._?["",_,""]:[""],"Version: 1",`URI: ${R.href}`,`Issued At: ${(n=(s=k?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=k?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${k.signInWithSolana.notBefore}`]:[],...!((a=k?.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${k.signInWithSolana.expirationTime}`]:[],...!((o=k?.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${k.signInWithSolana.chainId}`]:[],...!((l=k?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${k.signInWithSolana.nonce}`]:[],...!((u=k?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${k.signInWithSolana.requestId}`]:[],...!((h=(d=k?.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||h===void 0)&&h.length?["Resources",...k.signInWithSolana.resources.map(E=>`- ${E}`)]:[]].join(`
|
|
42
|
+
`);const M=await O.signMessage(new TextEncoder().encode(g),"utf8");if(!M||!(M instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");y=M}}try{const{data:x,error:v}=await P(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:vt(y)},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:Ue});if(v)throw v;if(!x||!x.session||!x.user){const _=new Dt;return this._returnResult({data:{user:null,session:null},error:_})}return x.session&&(await this._saveSession(x.session),await this._notifyAllSubscribers("SIGNED_IN",x.session)),this._returnResult({data:Object.assign({},x),error:v})}catch(x){if(T(x))return this._returnResult({data:{user:null,session:null},error:x});throw x}}async _exchangeCodeForSession(e,r){const s=r?.flowId!=null,n=s?Ir(r?.flowId):we()?Ir(fn(window.location.href)[bt]):null;s&&!n&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",r?.flowId);const{verifier:i,flowId:a}=s&&!n?{verifier:null,flowId:null}:await Fo(this.storage,this.storageKey,n),[o,l]=(i??"").split("/");try{if(!o&&this.flowType==="pkce")throw new So;const{data:u,error:d}=await P(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:o},xform:Ue});if(await Je(this.storage,this.storageKey,a),d)throw d;if(!u||!u.session||!u.user){const h=new Dt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:h})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers(l==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:l??null}),error:d})}catch(u){if(await Je(this.storage,this.storageKey,a),T(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:i,nonce:a}=e,o=await P(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:Ue}),{data:l,error:u}=o;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){const d=new Dt;return this._returnResult({data:{user:null,session:null},error:d})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,a;let o=null;try{if("email"in e){const{email:l,options:u}=e;let d=null,h=null;this.flowType==="pkce"&&([d,h,o]=await this._getCodeChallengeAndMethod());const{error:p}=await P(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(r=u?.data)!==null&&r!==void 0?r:{},create_user:(s=u?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},code_challenge:d,code_challenge_method:h},redirectTo:this._maybeAppendFlowIdToRedirect(u?.emailRedirectTo,o)});return this._returnResult({data:{user:null,session:null},error:p})}if("phone"in e){const{phone:l,options:u}=e,{data:d,error:h}=await P(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(n=u?.data)!==null&&n!==void 0?n:{},create_user:(i=u?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},channel:(a=u?.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:d?.message_id},error:h})}throw new Er("You must provide either an email or phone number.")}catch(l){if(await Je(this.storage,this.storageKey,o),T(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:a,error:o}=await P(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:Ue});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");const l=a.session,u=a.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(T(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i;let a=null;try{let o=null,l=null;this.flowType==="pkce"&&([o,l,a]=await this._getCodeChallengeAndMethod());const u=await P(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:this._maybeAppendFlowIdToRedirect((r=e.options)===null||r===void 0?void 0:r.redirectTo,a)}),!((s=e?.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:l}),headers:this.headers,xform:Zo});return!((n=u.data)===null||n===void 0)&&n.url&&we()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(o){if(await Je(this.storage,this.storageKey,a),T(o))return this._returnResult({data:null,error:o});throw o}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new be;const{error:n}=await P(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(T(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let r=null;try{const s=`${this.url}/resend`;if("email"in e){const{email:n,type:i,options:a}=e;let o=null,l=null;this.flowType==="pkce"&&([o,l,r]=await this._getCodeChallengeAndMethod());const{error:u}=await P(this.fetch,"POST",s,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:a?.captchaToken},code_challenge:o,code_challenge_method:l},redirectTo:this._maybeAppendFlowIdToRedirect(a?.emailRedirectTo,r)});return u&&await Je(this.storage,this.storageKey,r),this._returnResult({data:{user:null,session:null},error:u})}else if("phone"in e){const{phone:n,type:i,options:a}=e,{data:o,error:l}=await P(this.fetch,"POST",s,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:a?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:l})}throw new Er("You must provide either an email or phone number and a type")}catch(s){if(await Je(this.storage,this.storageKey,r),T(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await ke(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<os:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await ke(this.userStorage,this.storageKey+"-user");a?.user?e.user=a.user:e.user=us()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=Yo(e.user,a),a.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);if(i){if(!!(e.expires_at&&e.expires_at*1e3>Date.now())){const o=await ke(this.storage,this.storageKey);if(o&&o.refresh_token===e.refresh_token)return this._returnResult({data:{session:e},error:null})}return this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r;return this.lock!=null?r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):r=await this._getUser(),r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await P(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:dt}):await this._useSession(async r=>{var s,n,i;const{data:a,error:o}=r;if(o)throw o;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new be}:await P(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:dt})})}catch(r){if(T(r))return Tr(r)&&await this._removeSession(),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r)):await this._updateUser(e,r)}async _updateUser(e,r={}){let s=null;try{return await this._useSession(async n=>{const{data:i,error:a}=n;if(a)throw a;if(!i.session)throw new be;const o=i.session;let l=null,u=null;this.flowType==="pkce"&&e.email!=null&&([l,u,s]=await this._getCodeChallengeAndMethod());const{data:d,error:h}=await P(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(r?.emailRedirectTo,s),body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:u}),jwt:o.access_token,xform:dt});if(h)throw h;return o.user=d.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await Je(this.storage,this.storageKey,s),T(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new be;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:a}=Nr(e.access_token);if(a.exp&&(s=a.exp,n=s<=r),n){const{data:o,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o)return{data:{user:null,session:null},error:null};i=o}else{const{data:o,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(T(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){const{data:a,error:o}=r;if(o)throw o;e=(s=a.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new be;const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var s;try{if(!we())throw new jr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new jr(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new nn("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new jr("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new nn("No code detected.");const{data:k,error:O}=await this._exchangeCodeForSession(e.code,{flowId:e[bt]});if(O)throw O;const R=new URL(window.location.href);return R.searchParams.delete("code"),R.searchParams.delete(bt),window.history.replaceState(window.history.state,"",R.toString()),{data:{session:k.session,redirectType:(s=k.redirectType)!==null&&s!==void 0?s:null},error:null}}const{provider_token:n,provider_refresh_token:i,access_token:a,refresh_token:o,expires_in:l,expires_at:u,token_type:d}=e;if(!a||!l||!o||!d)throw new jr("No session defined in URL");const h=Math.round(Date.now()/1e3),p=parseInt(l);let m=h+p;u&&(m=parseInt(u));const g=m-h;g*1e3<=it&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${p}s`);const y=m-p;h-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,m,h):h-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",y,m,h);const{data:x,error:v}=await this._getUser(a);if(v)throw v;const _={provider_token:n,provider_refresh_token:i,access_token:a,expires_in:p,expires_at:m,refresh_token:o,token_type:d,user:x.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:_,redirectType:e.type},error:null})}catch(n){if(T(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;const r=Ir(e[bt]);return r&&await ke(this.storage,Lt(this.storageKey,r))?!0:!!await ke(this.storage,`${this.storageKey}-code-verifier`)}async signOut(e={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;const n=async()=>{await this._removeSession()},{data:i,error:a}=r;if(a&&!Tr(a))return this._returnResult({error:a});const o=(s=i.session)===null||s===void 0?void 0:s.access_token;if(o){const{error:l}=await this.admin.signOut(o,e);if(l&&!(sn(l)&&(l.status===404||l.status===401||l.status===403)||Tr(l)))return e!=="others"&&await n(),this._returnResult({error:l})}return e!=="others"&&await n(),this._returnResult({error:null})})}onAuthStateChange(e){const r=Oo(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)}):await this._emitInitialSession(r)))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{const{data:{session:i},error:a}=r;if(a)throw a;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),Tr(i)||Pr(i)||sn(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null,i=null;this.flowType==="pkce"&&([s,n,i]=await this._getCodeChallengeAndMethod(!0));try{return await P(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(r.redirectTo,i)})}catch(a){if(await Je(this.storage,this.storageKey,i),T(a))return this._returnResult({data:null,error:a});throw a}}async getUserIdentities(){var e;try{const{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;let s=null;try{const{data:n,error:i}=await this._useSession(async a=>{var o,l,u,d,h;const{data:p,error:m}=a;if(m)throw m;const{url:g,flowId:y}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(l=e.options)===null||l===void 0?void 0:l.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return s=y,await P(this.fetch,"GET",g,{headers:this.headers,jwt:(h=(d=p.session)===null||d===void 0?void 0:d.access_token)!==null&&h!==void 0?h:void 0})});if(i)throw i;return we()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url,flowId:s},error:null})}catch(n){if(T(n))return this._returnResult({data:{provider:e.provider,url:null,flowId:s},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{const{error:n,data:{session:i}}=r;if(n)throw n;const{options:a,provider:o,token:l,access_token:u,nonce:d}=e,h=await P(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i?.access_token)!==null&&s!==void 0?s:void 0,body:{provider:o,id_token:l,access_token:u,nonce:d,link_identity:!0,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ue}),{data:p,error:m}=h;return m?this._returnResult({data:{user:null,session:null},error:m}):!p||!p.session||!p.user?this._returnResult({data:{user:null,session:null},error:new Dt}):(p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("USER_UPDATED",p.session)),this._returnResult({data:p,error:m}))}catch(n){if(await Je(this.storage,this.storageKey,null),T(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:a}=r;if(a)throw a;return await P(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r="#_refreshAccessToken()";this._debug(r,"begin");try{const s=Date.now();return await Io(async n=>(n>0&&await No(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await P(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Ue})),(n,i)=>{const a=200*Math.pow(2,n);return i&&Pr(i)&&Date.now()+a-s<it})}catch(s){if(this._debug(r,"error",s),T(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const{url:s,flowId:n}=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),we()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s,flowId:n},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await ke(this.storage,this.storageKey);if(n&&this.userStorage){let a=await ke(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:n.user},await at(this.userStorage,this.storageKey+"-user",a)),n.user=(e=a?.user)!==null&&e!==void 0?e:us()}else if(n&&!n.user&&!n.user){const a=await ke(this.storage,this.storageKey+"-user");a&&a?.user?(n.user=a.user,await Re(this.storage,this.storageKey+"-user"),await at(this.storage,this.storageKey,n)):n.user=us()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}const i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<os;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${os}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:a}=await this._callRefreshToken(n.refresh_token);a&&(xo(a)?this._debug(s,"refresh discarded by commit guard",a):this._debug(s,"refresh failed",a))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:o}=await this._getUser(n.access_token);!o&&a?.user?(n.user=a.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(s,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),Pr(n)?console.warn(n):console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new be;if(this.refreshingDeferred)return this.refreshingDeferred.promise;if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===e&&Date.now()<this.lastRefreshFailure.expiresAt)return this._debug("#_callRefreshToken()","returning cached failure (cooldown active)"),this.lastRefreshFailure.result;const n="#_callRefreshToken()";this._debug(n,"begin");try{this.refreshingDeferred=new Cr,this.refreshingDeferred.promise.then(void 0,()=>{});const i=await ke(this.storage,this.storageKey),{data:a,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!a.session)throw new be;const l=await ke(this.storage,this.storageKey);if(i!==null&&(l===null||l.refresh_token!==i.refresh_token)){this._debug(n,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:l?"replaced":"cleared"});const p={data:null,error:new an};return this.refreshingDeferred.resolve(p),p}const d=this._sessionRemovalEpoch;if(await this._saveSession(a.session),this._sessionRemovalEpoch!==d){this._debug(n,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await Re(this.storage,this.storageKey),this.userStorage&&await Re(this.userStorage,this.storageKey+"-user");const p={data:null,error:new an};return this.refreshingDeferred.resolve(p),p}await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const h={data:a.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(h),h}catch(i){if(this._debug(n,"error",i),T(i)){const a={data:null,error:i};if(!Pr(i)){const o=await ke(this.storage,this.storageKey);!!(o?.expires_at&&o.expires_at*1e3>Date.now())?this._debug(n,"proactive refresh failed, access token still valid — preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:a,expiresAt:Date.now()+mo},(r=this.refreshingDeferred)===null||r===void 0||r.resolve(a),a}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){if(this._pendingInitNotifications!==null&&s){this._pendingInitNotifications.push({event:e,session:r,broadcast:s});return}const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const i=[],a=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,r)}catch(l){i.push(l)}});if(await Promise.all(a),i.length>0){for(let o=0;o<i.length;o+=1)console.error(i[o]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await at(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=gn(n);await at(this.storage,this.storageKey,i)}else{const n=gn(r);await at(this.storage,this.storageKey,n)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.lastRefreshFailure=null,this.suppressGetSessionWarning=!1,await Re(this.storage,this.storageKey),await Ko(this.storage,this.storageKey),await Re(this.storage,this.storageKey+"-user"),this.userStorage&&await Re(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&we()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),it);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/it);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${it}ms, refresh threshold is ${er} ticks`),n<=er&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof sl)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{const e=Date.now();try{await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/it);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${it}ms, refresh threshold is ${er} ticks`),n<=er&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!we()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;if(this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(r,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){let n=s?.redirectTo,i=null,a=null,o=null;this.flowType==="pkce"&&([i,a,o]=await this._getCodeChallengeAndMethod(),n=this._maybeAppendFlowIdToRedirect(n,o));const l=[`provider=${encodeURIComponent(r)}`];if(n&&l.push(`redirect_to=${encodeURIComponent(n)}`),s?.scopes&&l.push(`scopes=${encodeURIComponent(s.scopes)}`),i!=null&&a!=null){const u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});l.push(u.toString())}if(s?.queryParams){const u=new URLSearchParams(s.queryParams);l.push(u.toString())}return s?.skipBrowserRedirect&&l.push(`skip_http_redirect=${s.skipBrowserRedirect}`),{url:`${e}?${l.join("&")}`,flowId:o}}_maybeAppendFlowIdToRedirect(e,r){return!e||!r||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:qo(e,r)}async _getCodeChallengeAndMethod(e=!1){return Wo(this.storage,this.storageKey,e,r=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",r))}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await P(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:u}=await P(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&l.type==="totp"&&(!((n=l?.totp)===null||n===void 0)&&n.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){const r=async()=>{try{return await this._useSession(async s=>{var n;const{data:i,error:a}=s;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Tn(e.webauthn.credential_response):En(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:u}=await P(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:u}))})}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challenge(e){const r=async()=>{try{return await this._useSession(async s=>{var n;const{data:i,error:a}=s;if(a)return this._returnResult({data:null,error:a});const o=await P(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;const{data:l}=o;if(l.type!=="webauthn")return{data:l,error:null};switch(l.webauthn.type){case"create":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:Sn(l.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:xn(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challengeAndVerify(e){const{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{const{payload:m}=Nr(e);let g=null;m.aal&&(g=m.aal);let y=g;const{data:{user:x},error:v}=await this.getUser(e);if(v)return this._returnResult({data:null,error:v});((s=(r=x?.factors)===null||r===void 0?void 0:r.filter(O=>O.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(y="aal2");const k=m.amr||[];return{data:{currentLevel:g,nextLevel:y,currentAuthenticationMethods:k},error:null}}catch(m){if(T(m))return this._returnResult({data:null,error:m});throw m}const{data:{session:a},error:o}=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=Nr(a.access_token);let u=null;l.aal&&(u=l.aal);let d=u;((i=(n=a.user.factors)===null||n===void 0?void 0:n.filter(m=>m.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(d="aal2");const p=l.amr||[];return{data:{currentLevel:u,nextLevel:d,currentAuthenticationMethods:p},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await P(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new be})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new be});const a=await P(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&we()&&!r?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new be});const a=await P(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&we()&&!r?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await P(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new be})})}catch(e){if(T(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await P(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new be})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(o=>o.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+wo>n)return s;const{data:i,error:a}=await P(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,s=i.keys.find(o=>o.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:m,error:g}=await this.getSession();if(g||!m.session)return this._returnResult({data:null,error:g});s=m.session.access_token}const{header:n,payload:i,signature:a,raw:{header:o,payload:l}}=Nr(s);if(!r?.allowExpired)try{zo(i.exp)}catch(m){throw new Rr(m instanceof Error?m.message:"JWT validation failed")}const u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!u){const{error:m}=await this.getUser(s);if(m)throw m;return{data:{claims:i,header:n,signature:a},error:null}}const d=Vo(n.alg),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,a,Po(`${o}.${l}`)))throw new Rr("Invalid JWT signature");return{data:{claims:i,header:n,signature:a},error:null}}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}}async signInWithPasskey(e){var r,s,n;Ye(this.experimental);try{if(!$r())return this._returnResult({data:null,error:new Ve("Browser does not support WebAuthn",null)});const{data:i,error:a}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}});if(a||!i)return this._returnResult({data:null,error:a});const o=xn(i.options),l=(n=(s=e?.options)===null||s===void 0?void 0:s.signal)!==null&&n!==void 0?n:hs.createNewAbortSignal(),{data:u,error:d}=await Pn({publicKey:o,signal:l});if(d||!u)return this._returnResult({data:null,error:d??new Ve("WebAuthn ceremony failed",null)});const h=En(u);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:h})}catch(i){if(T(i))return this._returnResult({data:null,error:i});throw i}}async registerPasskey(e){var r,s;Ye(this.experimental);try{if(!$r())return this._returnResult({data:null,error:new Ve("Browser does not support WebAuthn",null)});const{data:n,error:i}=await this._startPasskeyRegistration();if(i||!n)return this._returnResult({data:null,error:i});const a=Sn(n.options),o=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:hs.createNewAbortSignal(),{data:l,error:u}=await An({publicKey:a,signal:o});if(u||!l)return this._returnResult({data:null,error:u??new Ve("WebAuthn ceremony failed",null)});const d=Tn(l);return this._verifyPasskeyRegistration({challengeId:n.challenge_id,credential:d})}catch(n){if(T(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyRegistration(){Ye(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new be});const{data:n,error:i}=await P(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(T(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){Ye(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new be});const{data:i,error:a}=await P(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:s.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;Ye(this.experimental);try{const{data:s,error:n}=await P(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:s,error:null})}catch(s){if(T(s))return this._returnResult({data:null,error:s});throw s}}async _verifyPasskeyAuthentication(e){Ye(this.experimental);try{const{data:r,error:s}=await P(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:Ue});return s?this._returnResult({data:null,error:s}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){Ye(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new be});const{data:n,error:i}=await P(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:a=>({data:a,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(T(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){Ye(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new be});const{data:i,error:a}=await P(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,body:{friendly_name:e.friendlyName}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){Ye(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new be});const{error:i}=await P(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}}sr.nextInstanceID={};const yl=sr,bl="2.112.4";let nr="",Mr;if(typeof Deno<"u"){var fs;nr="deno",Mr=(fs=Deno.version)===null||fs===void 0?void 0:fs.deno}else if(typeof document<"u")nr="web";else if(typeof navigator<"u"&&navigator.product==="ReactNative")nr="react-native";else{var ms;nr="node";const t=globalThis.process;Mr=t==null||(ms=t.version)===null||ms===void 0?void 0:ms.replace(/^v/,"")}const On=[`runtime=${nr}`];Mr&&On.push(`runtime-version=${Mr}`);const vl={headers:{"X-Client-Info":`supabase-js/${bl}; ${On.join("; ")}`}},wl={schema:"public"},_l={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},kl={},Sl={enabled:!1,respectSamplingDecision:!0};function xl(t){if(!t||typeof t!="string")return null;const e=t.split("-");if(e.length!==4)return null;const[r,s,n,i]=e;if(r.length!==2||s.length!==32||n.length!==16||i.length!==2)return null;const a=/^[0-9a-f]+$/i;return!a.test(r)||!a.test(s)||!a.test(n)||!a.test(i)||s==="00000000000000000000000000000000"||n==="0000000000000000"?null:{version:r,traceId:s,parentId:n,traceFlags:i,isSampled:(parseInt(i,16)&1)===1}}function Tl(t,e){if(!t||!e||e.length===0)return!1;let r;if(t instanceof URL)r=t;else try{r=new URL(t)}catch{return!1}for(const s of e)try{if(typeof s=="string"){if(El(r.hostname,s))return!0}else if(s instanceof RegExp){if(s.test(r.hostname))return!0}else if(typeof s=="function"&&s(r))return!0}catch{continue}return!1}function El(t,e){if(e===t)return!0;if(e.startsWith("*.")){const r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function jl(t){const e=[];try{const r=new URL(t);e.push(r.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function ir(t){"@babel/helpers - typeof";return ir=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ir(t)}function Al(t,e){if(ir(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(ir(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Pl(t){var e=Al(t,"string");return ir(e)=="symbol"?e:e+""}function Rl(t,e,r){return(e=Pl(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Cn(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function ie(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Cn(Object(r),!0).forEach(function(s){Rl(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Cn(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const Ol=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Cl=()=>Headers,Nn=t=>t.startsWith("sb_publishable_")||t.startsWith("sb_secret_"),Nl="sb_temp_",In=new Set,Il=t=>{var e,r;if(!t.startsWith("sb_")||Nn(t)||t.startsWith(Nl))return;const s=(e=(r=t.match(/^sb_[a-zA-Z0-9]+_/))===null||r===void 0?void 0:r[0])!==null&&e!==void 0?e:"unknown";In.has(s)||(In.add(s),console.warn("@supabase/supabase-js: Unrecognized Supabase API key format. The client will proceed and send this key as-is; if you see authentication errors you may need to upgrade @supabase/supabase-js to a version that recognizes this key type."))},Dn=(t,e,r,s,n,i)=>{const a=Ol(s),o=Cl(),l=n?.enabled===!0,u=n?.respectSamplingDecision!==!1,d=l?jl(e):null,h=!(i?.omitApiKeyAsBearer&&Nn(t));return async(p,m)=>{const g=await r();let y=new o(m?.headers);if(y.has("apikey")||y.set("apikey",t),!y.has("Authorization")){const x=g??(h?t:null);x&&y.set("Authorization",`Bearer ${x}`)}if(d){const x=Dl(p,d,u);x&&(x.traceparent&&!y.has("traceparent")&&y.set("traceparent",x.traceparent),x.tracestate&&!y.has("tracestate")&&y.set("tracestate",x.tracestate),x.baggage&&!y.has("baggage")&&y.set("baggage",x.baggage))}return a(p,ie(ie({},m),{},{headers:y}))}};let $n=!1,Ln=!1;function Dl(t,e,r){const s=$i();if(!s)return $n||($n=!0,console.warn("@supabase/supabase-js: tracePropagation is enabled but the tracing runtime is not loaded, so trace headers will not be attached. Add `import '@supabase/supabase-js/tracing'` at your application entry point (requires the OpenTelemetry API package to be installed). The CDN/UMD build does not support trace propagation.")),null;if(!Tl(typeof t=="string"||t instanceof URL?t:t.url,e))return null;const n=s();if(!n||!n.traceparent){var i;if(!(n==null||(i=n.carrierKeys)===null||i===void 0)&&i.length&&!Ln){Ln=!0;const a=n.carrierKeys.includes("sentry-trace")?" Sentry detected: set `propagateTraceparent: true` in Sentry.init() to emit it.":" Configure your tracing SDK to emit W3C trace context on outgoing requests.";console.warn(`@supabase/supabase-js: tracePropagation is enabled and a tracing SDK is active, but its propagator wrote [${n.carrierKeys.join(", ")}] and no W3C traceparent header, so trace headers will not be attached.`+a)}return null}if(r){const a=xl(n.traceparent);if(a&&!a.isSampled)return{traceparent:n.traceparent}}return n}function Mn(t){return typeof t=="boolean"?{enabled:t}:t}function $l(t){return t.endsWith("/")?t:t+"/"}function Ll(t,e){var r,s,n,i,a,o;const{db:l,auth:u,realtime:d,global:h}=t,{db:p,auth:m,realtime:g,global:y}=e,x=Mn(t.tracePropagation),v=Mn(e.tracePropagation),_={db:ie(ie({},p),l),auth:ie(ie({},m),u),realtime:ie(ie({},g),d),storage:{},global:ie(ie(ie({},y),h),{},{headers:ie(ie({},(r=y?.headers)!==null&&r!==void 0?r:{}),(s=h?.headers)!==null&&s!==void 0?s:{})}),tracePropagation:{enabled:(n=(i=x?.enabled)!==null&&i!==void 0?i:v?.enabled)!==null&&n!==void 0?n:!1,respectSamplingDecision:(a=(o=x?.respectSamplingDecision)!==null&&o!==void 0?o:v?.respectSamplingDecision)!==null&&a!==void 0?a:!0},accessToken:async()=>""};return t.accessToken?_.accessToken=t.accessToken:delete _.accessToken,_}function Ml(t){const e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL($l(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Ul=class extends yl{constructor(t){super(t)}},Bl=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=Ml(t);if(!e)throw new Error("supabaseKey is required.");Il(e),this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const a=`sb-${i.hostname.split(".")[0]}-auth-token`,o={db:wl,realtime:kl,auth:ie(ie({},_l),{},{storageKey:a}),global:vl,tracePropagation:Sl},l=Ll(r??{},o);if(this.settings=l,this.storageKey=(s=l.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(d,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=Dn(e,t,this._getSessionToken.bind(this),l.global.fetch,l.tracePropagation),this.functionsFetch=Dn(e,t,this._getSessionToken.bind(this),l.global.fetch,l.tracePropagation,{omitApiKeyAsBearer:!0}),this.realtime=this._initRealtimeClient(ie({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(d=>this.realtime.setAuth(d)).catch(d=>console.warn("Failed to set initial Realtime auth token:",d)),this.rest=new Ji(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit,retry:l.db.retry}),this.storage=new fo(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new Bi(this.functionsUrl.href,{headers:this.headers,customFetch:this.functionsFetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getSessionToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:null}async _getAccessToken(){var t=this,e;return(e=await t._getSessionToken())!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:a,lock:o,debug:l,throwOnError:u,experimental:d,lockAcquireTimeout:h,skipAutoInitialize:p},m,g){const y={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Ul({url:this.authUrl.href,headers:ie(ie({},y),m),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:o,debug:l,throwOnError:u,experimental:d,fetch:g,lockAcquireTimeout:h,skipAutoInitialize:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(x=>x.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new La(this.realtimeUrl.href,ie(ie({},t),{},{params:ie(ie({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN"||t==="INITIAL_SESSION")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const Fl=(t,e,r)=>new Bl(t,e,r);function Kl(){if(typeof window<"u"||globalThis.Deno!==void 0)return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=20:!1}Kl()&&console.warn("⚠️ Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715");function Un(t,e){if(!t||!e)throw new Error("Supabase URL and anon key are required");return Fl(t,e)}function Bn(t){const e=[];let r="",s=!1;for(let n=0;n<t.length;n++){const i=t[n];i==='"'?s&&t[n+1]==='"'?(r+='"',n++):s=!s:i===","&&!s?(e.push(r),r=""):r+=i}return e.push(r),e.map(n=>n.trim().replace(/^"|"$/g,""))}function Be(t,...e){const r=n=>n.trim().toLowerCase().replace(/[_\s]+/g," ").trim(),s=new Map;Object.entries(t).forEach(([n,i])=>s.set(r(n),i));for(const n of e){const i=s.get(r(n));if(i!==void 0&&i.trim())return i.trim()}return""}function ql(t){const r=t.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
|
|
43
43
|
`).trim().split(`
|
|
44
|
-
`);if(r.length<2)return[];const s=Kn(r[0]),n=[];for(let i=1;i<r.length;i++){const a=Kn(r[i]);if(a.length<s.length)continue;const o={};s.forEach((p,m)=>{o[p]=a[m]??""});const l=Be(o,"store_id","store id"),u=Be(o,"pooja_title","pooja title","puja title");if(!l||!u)continue;const d=Be(o,"cover_media_url","cover media url","cover image"),h=Be(o,"cover_media_url_english","cover media url english","cover image english");n.push({store_id:l,pooja_title:u,temple_name:Be(o,"temple_name","temple name")||"",pooja_title_english:Be(o,"pooja_title_english","pooja title english","puja title english")||void 0,temple_name_english:Be(o,"temple_name_english","temple name english")||void 0,cover_media_url:d||void 0,cover_media_url_english:h||void 0,puja_link:Be(o,"puja_link","puja link","pooja link")||Be(o,"puja link","pooja link")||"",puja_link_hindi:Be(o,"puja_link_hindi","puja link hindi","pooja link hindi")||void 0,individual_pack_price_inr:parseFloat(Be(o,"individual_pack_price_inr","individual pack price inr","price"))||0,schedule_date_ist:Be(o,"schedule_date_ist","schedule date ist","schedule date")||""})}return n}const qn={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 Jl(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=qn[e]||qn[e.toLowerCase()];if(!r||r.length===0)return null;const s=t.filter(a=>{const o=(a.pooja_title||"").toLowerCase(),l=(a.pooja_title_english||"").toLowerCase();return o.includes("rashi")||l.includes("rashi")?!1:r.some(u=>o.includes(u.toLowerCase())||l.includes(u.toLowerCase()))});if(s.length===0)return null;const n=new Date;return n.setHours(0,0,0,0),(s.filter(a=>{const o=Jl(a.schedule_date_ist);return o?o.getTime()>=n.getTime():!0})[0]??s[0])||null}let Bt=[],Hn=0;const Yl=3600*1e3;async function Ql(t){const e=Date.now();if(Bt.length>0&&e-Hn<Yl)return Bt;try{const{data:r,error:s}=await t.functions.invoke("fetch-pujas");if(s)return console.warn("[DoshaCalculator] fetch-pujas error:",s),Bt;const n=typeof r=="string"?r:"";if(!n)return Bt;const i=Vl(n);return Bt=i,Hn=e,i}catch(r){return console.warn("[DoshaCalculator] fetchPujas error:",r),Bt}}const Gn={"पितृ दोष निवारण महायज्ञ एवं काशी गंगा महाआरती":"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"},Xl={पूजा:"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"},zn={"काशी विश्वनाथ मंदिर":"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 Zl(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 Vn(t){let e=t;return Object.entries(Xl).sort((s,n)=>n[0].length-s[0].length).forEach(([s,n])=>{const i=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi");e=e.replace(i,n)}),e.replace(/\s+/g," ").trim()}function ps(t,e){const r=e?.toLowerCase().startsWith("hi"),s=typeof t=="string"?t:t.pooja_title,n=typeof t=="string"?void 0:t.pooja_title_english;if(r)return s;if(n?.trim())return n;if(Gn[s])return Gn[s];const i=Vn(s);return i!==s?i:s}function Jn(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(zn[s])return zn[s];const i=Vn(s);return i!==s?i:s}function Yn(t,e="en"){const r=Zl(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 ec(t){if(!t||typeof window>"u")return t;try{const e=new URLSearchParams(window.location.search),r=e.get("utm_source"),s=e.get("utm_medium"),n=e.get("utm_content");if(!r&&!s&&!n)return t;const i=new URL(t);return r&&i.searchParams.set("utm_source",r),s&&i.searchParams.set("utm_medium",s),n&&i.searchParams.set("utm_content",n),i.toString()}catch{return t}}function gs(t,e){const s=e?.toLowerCase().startsWith("hi")?t.puja_link_hindi||t.puja_link:t.puja_link||t.puja_link_hindi;return ec(s||"")}function Qn(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 tc={container:"_container_m8vst_1"},rc=["en","hi"],sc={en:"English",hi:"हिन्दी"},Xn={en:{language:"Language",guest:"Guest",sriMandir:"Sri Mandir",ratingText:"3 Crore+ app downloads",feedbackTitle:"What Others Discovered Through Their Dosha Analysis",feedbackTrust:"Trusted by over 5 crore users worldwide",feedbackRating:"4.9",feedbackTestimonial1:"I was facing delay in marriage and also tension in career. After checking my kundli I understood the problems clearly. I followed the remedies with faith and slowly things started improving. Now my marriage is fixed and job situation is also better. Feeling very thankful.",feedbackTestimonial2:"My health was not good from long time and money problems also coming again and again. The report explained everything in simple way. After doing small remedies I feel more positive and health is improving. Very good experience.",feedbackTestimonial3:"Career was fully stuck and no promotion from 3 years. I created my kundli here and got to know about some dosha affecting work life. After remedies within few months I changed job with better salary. Really happy.",feedbackTestimonial4:"I checked kundli for marriage but it also told about finance issues. Remedies were easy to follow. Slowly money stability came and good rishta also came in family. Feeling peaceful now.",feedbackTestimonial5:"Simple and clear guidance. Problems in job and health both reduced after remedies. Good service.",feedbackTestimonial6:"Too much stress in life related to marriage and future. Kundli reading was very detailed but easy to understand. After doing puja and mantra I feel calm and recently got good marriage proposal. Thank you so much.",feedbackTestimonial7:"Finance loss was happening again and again in business. They told reason from kundli and suggested remedy. I followed for few weeks and situation slowly became stable. Good support.",feedbackTestimonial8:"I almost lost hope for marriage and career both. But this kundli analysis gave me new confidence. Within 2 months I got interview call and also one good match from relatives. Things are moving finally.",feedbackTestimonial9:"Very genuine report not copy paste. Health issue reason also explained. After remedies I feel more energy and mind peace. Satisfied.",feedbackTestimonial10:"Marriage delay, money tension, family stress everything was going wrong. Remedies were small but powerful. Now engagement done and finance also improving slowly. Feeling blessed.",feedbackTestimonial11:"I was not believing before but result surprised me. Career growth started after long time and new opportunities coming. Good guidance and honest prediction.",feedbackTestimonial12:"Health problems and negative thoughts were too much. After following remedies I feel mentally strong and peaceful. Family also noticing the change. Very grateful.",feedbackTestimonial13:"Short review. Career better now and money flow also improved after remedy. Thank you.",feedbackTestimonial14:"Kundli reading helped me understand many hidden issues in life like marriage delay and job confusion. Remedies were simple daily things. Slowly life becoming stable. Nice experience overall.",feedbackTestimonial15:"Good for anyone facing problems in marriage career or finance. Simple language and true guidance. I saw positive change in few months only. Highly recommended.",feedbackAuthor1:"Abhishek Mishra",feedbackAuthor2:"Pooja Verma",feedbackAuthor3:"Amit Patel",feedbackAuthor4:"Sneha Gupta",feedbackAuthor5:"Vikas Yadav",feedbackAuthor6:"Neha Singh",feedbackAuthor7:"Rahul Jain",feedbackAuthor8:"Kavita Mishra",feedbackAuthor9:"Sandeep Kumar",feedbackAuthor10:"Anjali Mehta",feedbackAuthor11:"Deepak Arora",feedbackAuthor12:"Ritu Saxena",feedbackAuthor13:"Manoj Tiwari",feedbackAuthor14:"Priya Nair",feedbackAuthor15:"Karan Malhotra",feedbackAuthor1AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639330970.png",feedbackAuthor2AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639293055.png",feedbackAuthor3AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639358174.png",feedbackAuthor4AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639427379.png",feedbackAuthor5AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639381899.png",feedbackAuthor6AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639416587.png",feedbackAuthor7AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639454626.png",feedbackAuthor8AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639319028.png",feedbackAuthor9AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639271096.png",feedbackAuthor10AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639254172.png",feedbackAuthor11AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639345411.png",feedbackAuthor12AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639306698.png",feedbackAuthor13AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639330970.png",feedbackAuthor14AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639402894.png",feedbackAuthor15AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639358174.png",readMoreReviews:"Read More Reviews",readLess:"Read Less",feedbackTitleMarriage:"What others facing marriage delay discovered",feedbackTestimonialMarriage1:"My marriage was getting delayed again and again and we were very worried. After creating my kundli here I came to know about Mangal dosh and some other issues. The remedies suggested were simple and within few months things started moving. Now my engagement is fixed. Feeling very thankful.",feedbackTestimonialMarriage2:"I was honestly not believing in kundli much but my parents forced me to try. They found a marriage dosha in my chart and gave puja guidance. After doing it I met a very good person through relatives. Sometimes these things really work.",feedbackTestimonialMarriage3:"Got my kundli checked because nothing was working for my wedding. Every match was breaking. The report clearly explained the doshas and what to do. Followed the remedy for 40 days and suddenly one perfect match came. Married now and happy.",feedbackTestimonialMarriage4:"Very helpful service. Found reason for delay in marriage and solution also given. Things improved slowly.",feedbackTestimonialMarriage5:"I was 32 and tension in home was too much. Kundli showed Shani related problem affecting marriage. Did the suggested donation and mantra. Within 3 months alliance got finalised. Still feels like miracle honestly.",feedbackTestimonialMarriage6:"The explanation was simple and easy to understand. I liked that they did not scare me but gave practical remedies. After doing them my long pending relationship got approval from both families and we are getting married soon.",feedbackTestimonialMarriage7:"Short review but true. Marriage dosh removed after remedies and now wedding date fixed. Thank you so much.",feedbackTestimonialMarriage8:"Many astrologers told different things and I was confused. Here the kundli analysis felt genuine and detailed. They pointed out exact dosha causing breakups. After remedies my partner came back and families agreed. Feeling peaceful now.",feedbackTestimonialMarriage9:"I created my kundli just casually but result shocked me. There was strong manglik issue. Followed puja on Tuesday as told. Within few months I got good proposal from same city. Everything went smooth after that.",feedbackTestimonialMarriage10:"Service is good and fast. Report is clear. My marriage problem solved after remedy. Satisfied.",feedbackTestimonialMarriage11:"For 5 years nothing was happening in my life regarding marriage. After kundli matching they told to wait few months and do certain prayers. Exactly in that time I met my husband through office. Now happily married for 1 year.",feedbackTestimonialMarriage12:"Very emotional moment for me writing this. I had almost lost hope. The dosha remedies gave me confidence and positivity also. Slowly situations changed and today my roka ceremony is done. Truly grateful.",feedbackTestimonialMarriage13:"Nice guidance and honest prediction. No false promises. Remedies worked for my delayed marriage issue.",feedbackTestimonialMarriage14:"My daughter kundli was checked here. They found dosha and suggested simple temple visit and fasting. We followed sincerely. Within short time good proposal came from nice family. As parents we are very relieved.",feedbackTestimonialMarriage15:"I recommend this to anyone facing marriage delay. Kundli analysis felt real not copy paste. Small small remedies but big change in life. Thank you from heart.",faqTitle:"Frequently Asked Questions",faqQ1:"Is this really free?",faqA1:"Yes, the Dosha Calculator is completely free to use. You can check your kundli for doshas and get detailed analysis at no cost.",faqQ2:"What if I don't know birth time?",faqA2:"You can enter an approximate birth time or use 12:00 PM as default. Some doshas like Mangal Dosha and Kaal Sarp Dosha can still be detected with approximate time.",faqQ3:"Is this a generic report?",faqA3:"No, your report is personalized based on your exact date, time, and place of birth. Each kundli analysis is unique and the dosha detection is specific to your birth chart.",faqQ1Marriage:"Is this really free?",faqA1Marriage:"Yes, the Dosha Calculator is completely free to use. You can check your kundli for doshas and get detailed analysis at no cost.",faqQ2Marriage:"What if I don't know birth time?",faqA2Marriage:"You can enter an approximate birth time or use 12:00 PM as default. Some doshas like Mangal Dosha and Kaal Sarp Dosha can still be detected with approximate time.",faqQ3Marriage:"Is this a generic report?",faqA3Marriage:"No, your report is personalized based on your exact date, time, and place of birth. Each kundli analysis is unique and the dosha detection is specific to your birth chart.",faqQ4Marriage:"Will this fix my marriage delay?",faqA4Marriage:"The calculator identifies doshas that may be causing marriage delay. Once detected, we recommend specific pujas and remedies that have helped thousands of users overcome marriage obstacles.",formPrivacyBanner:"100% Private & Secure",formTitle:"Enter your details",formSubtitle:"We'll generate your kundli to know your doshas",formNameLabel:"Enter Your Name",formNamePlaceholder:"Your Name",formGenderLabel:"Your Gender",formGenderMale:"Male",formGenderFemale:"Female",formProblemLabel:"What problem is bothering you?",formProblemMarriage:"Marriage",formProblemMoney:"Money",formProblemOther:"Others",formProblemHealth:"Health",formProblemEducation:"Education",formProblemCareer:"Career",formProblemOtherPlaceholder:"Please describe your problem",formProblemOtherHint:"Max 100 characters",formDobLabel:"Select Date of Birth",formDobInfo:"Your date of birth is used to calculate your dosha balance.",formTimeLabel:"Exact Time of Birth",formTimeInfo:"Birth time helps improve accuracy of the analysis.",formTimeUnknown:"I don't know my birth time",formTimeUnknownHelp:"Note - Without exact birth time, accuracy will be reduced. We'll run Moon-based checks only.",formPlaceLabel:"Enter your birth place",formPlaceInfo:"City and state/country help us refine your result.",formPlacePlaceholder:"City, State",formFooterNote:"Analysis Takes Only 60 seconds",formFooterNoteBefore:"Analysis Takes Only ",formFooterNoteBold:"60 seconds",formFooterNoteAfter:"",formCta:"Check My Dosha for FREE",formCtaCalculate:"Calculate my Dosha",calculating:"Calculating...",bookPuja:"Book Puja",resultPageTitle:"Find Puja Remedy for Free",resultPageSubtitle:"Analyse your kundli to find out which doshas (if any) appear in your Vedic chart—and see devotional remedies.",calculationSuccess:"Your dosha analysis is ready.",calculationError:"Something went wrong. Please try again.",formError:"Please correct the highlighted fields.",formNameRequired:"Name is required.",formGenderRequired:"Gender is required.",formDobRequired:"Date of birth is required.",formTimeRequired:"Time is required when birth time is known.",formPlaceRequired:"Birth place is required.",formPlaceSelectFromDropdown:"Please select a place from the dropdown list.",formAgeMarriageRestriction:"Please select appropriate problem areas. Marriage, financial, career, and business-related issues are applicable for users above 18 years.",locationError:"Could not get location coordinates. Please try again.",calculationResolvingPlace:"Resolving place…",info:"Info",resultTitle:"Your Dosha Analysis",resultSomeDoshas:"Some Doshas Have Been Detected",resultNoDoshas:"No Major Doshas Found",resultNoDoshasDesc:"Your birth chart shows no major doshas.",resultMangal:"Mangal Dosha",resultKaalSarp:"Kaal Sarp Dosha",resultPitra:"Pitra Dosha",resultSadeSati:"Shani Sade Sati",resultStatusPresent:"Present",resultStatusAbsent:"Absent",resultStatusInactive:"Inactive",resultExplanation:"Explanation",resultRemedies:"Remedies",resultEditForm:"Edit details",drStatus:"Status",drSeverity:"Severity",drType:"Type",drPhase:"Phase",drExplanation:"Explanation",drWhyPresent:"Why Present",drWhyAbsent:"Why Absent",drImpact:"Impact",drPlanetaryPositions:"Planetary Positions",drTraditionalRemedies:"Traditional Remedies",drDetailedAnalysis:"Detailed Analysis & Remedies",drBasedOnChart:"Based on your birth chart calculations",drDisclaimer:"While we follow established astrological rules, dosha interpretation can vary among astrologers. We recommend consulting an astrologer you trust if you wish to explore additional viewpoints.",drStatusPresent:"Present",drStatusAbsent:"Absent",drStatusInactive:"Inactive",drStatusActive:"Active",drStatusSuggested:"Suggested",drStatusNullified:"Present (Nullified)",drMangalName:"Mangal Dosha (Manglik)",drMangalDesc:"Mangal (Manglik/Kuja) Dosha — Linked with Mars in certain houses; traditionally associated with friction in relationships and decisiveness.",drMangalImpact:"Greater likelihood of friction in close relationships, impatience/anger spikes, or delays and stops/starts in marriage or partnerships.",drMangalRemedies:`Recite Hanuman Chalisa daily
|
|
44
|
+
`);if(r.length<2)return[];const s=Bn(r[0]),n=[];for(let i=1;i<r.length;i++){const a=Bn(r[i]);if(a.length<s.length)continue;const o={};s.forEach((p,m)=>{o[p]=a[m]??""});const l=Be(o,"store_id","store id"),u=Be(o,"pooja_title","pooja title","puja title");if(!l||!u)continue;const d=Be(o,"cover_media_url","cover media url","cover image"),h=Be(o,"cover_media_url_english","cover media url english","cover image english");n.push({store_id:l,pooja_title:u,temple_name:Be(o,"temple_name","temple name")||"",pooja_title_english:Be(o,"pooja_title_english","pooja title english","puja title english")||void 0,temple_name_english:Be(o,"temple_name_english","temple name english")||void 0,cover_media_url:d||void 0,cover_media_url_english:h||void 0,puja_link:Be(o,"puja_link","puja link","pooja link")||Be(o,"puja link","pooja link")||"",puja_link_hindi:Be(o,"puja_link_hindi","puja link hindi","pooja link hindi")||void 0,individual_pack_price_inr:parseFloat(Be(o,"individual_pack_price_inr","individual pack price inr","price"))||0,schedule_date_ist:Be(o,"schedule_date_ist","schedule date ist","schedule date")||""})}return n}const Fn={mangal:["mangal","manglik","kuja","मंगल","मांगलिक","30 day","30-day","30 din"],"kaal-sarp":["kaal sarp","kaal-sarp","kaalsarp","काल सर्प","कालसर्प","sarp"],kaalSarp:["kaal sarp","kaal-sarp","kaalsarp","काल सर्प","कालसर्प","sarp"],pitra:["pitru","pitra","पितृ","पितर","pitra dosha","pitru dosha"],shani:["shani","saturn","शनि","sade sati","साढ़े साती","साढ़ेसाती","sade saati"],sadeSati:["shani","saturn","शनि","sade sati","साढ़े साती","साढ़ेसाती","sade saati"]};function Wl(t){const e=t.split("/");if(e.length!==3)return null;const r=parseInt(e[0],10),s=parseInt(e[1],10)-1,n=parseInt(e[2],10);return new Date(n,s,r)}function Kn(t,e){const r=Fn[e]||Fn[e.toLowerCase()];if(!r||r.length===0)return null;const s=t.filter(a=>{const o=(a.pooja_title||"").toLowerCase(),l=(a.pooja_title_english||"").toLowerCase();return o.includes("rashi")||l.includes("rashi")?!1:r.some(u=>o.includes(u.toLowerCase())||l.includes(u.toLowerCase()))});if(s.length===0)return null;const n=new Date;return n.setHours(0,0,0,0),(s.filter(a=>{const o=Wl(a.schedule_date_ist);return o?o.getTime()>=n.getTime():!0})[0]??s[0])||null}let Ut=[],qn=0;const Hl=3600*1e3;async function Gl(t){const e=Date.now();if(Ut.length>0&&e-qn<Hl)return Ut;try{const{data:r,error:s}=await t.functions.invoke("fetch-pujas");if(s)return console.warn("[DoshaCalculator] fetch-pujas error:",s),Ut;const n=typeof r=="string"?r:"";if(!n)return Ut;const i=ql(n);return Ut=i,qn=e,i}catch(r){return console.warn("[DoshaCalculator] fetchPujas error:",r),Ut}}const Wn={"पितृ दोष निवारण महायज्ञ एवं काशी गंगा महाआरती":"Pitru Dosha Nivaran Mahayagya & Kashi Ganga Maha Aarti","पितृ दोष शांति महापूजा एवं काशी गंगा आरती":"Pitra Dosha Shanti Mahapuja & Kashi Ganga Aarti","पितृ दोष निवारण पूजा एवं काशी गंगा आरती":"Pitra Dosha Nivaran Puja & Kashi Ganga Aarti","त्र्यंबकेश्वर ज्योतिर्लिंग रुद्राभिषेक और काल सर्प दोष निवारण पूजा":"Trimbakeshwar Jyotirlinga Rudrabhishek & Kaal Sarp Dosha Nivaran Puja","काल सर्प दोष निवारण पूजा एवं त्र्यंबकेश्वर ज्योतिर्लिंग रुद्राभिषेक":"Kaal Sarp Dosha Nivaran Puja & Trimbakeshwar Jyotirlinga Rudrabhishek","राहु-सूर्य दोष निवारण पूजा":"Rahu-Surya Dosha Nivaran Puja","मंगल दोष निवारण पूजा":"Mangal Dosha Nivaran Puja","शनि शांति पूजा":"Shani Shanti Puja","शनि साढ़े साती शांति पूजा":"Shani Sade Sati Shanti Puja","नवग्रह शांति पूजा":"Navagraha Shanti Puja","गुरु चांडाल दोष निवारण पूजा":"Guru Chandal Dosha Nivaran Puja","श्रापित दोष निवारण पूजा":"Shrapit Dosha Nivaran Puja","काल सर्प दोष पूजा":"Kaal Sarp Dosha Puja","मंगल पूजा":"Mangal Puja","शनि पूजा":"Shani Puja","राहु पूजा":"Rahu Puja","केतु पूजा":"Ketu Puja","नवग्रह शांति पूजा, शनि तिल तेल अभिषेक और पाप ग्रह शांति यज्ञ":"Navagraha Shanti Puja, Shani Til Tel Abhishek and Paap Graha Shanti Yagya","30 दिन मंगल दोष निवारण पूजा":"30-Day Mangal Dosha Nivaran Puja","30 दिनों में मंगल दोष निवारण पूजा":"30-Day Mangal Dosha Nivaran Puja","30 दिन मंगल पूजा":"30-Day Mangal Puja","30 लाख मंगल जाप":"30 Lakh Mangal Jaap","शनि साढ़ेसाती शांति पूजा":"Shani Sade Sati Shanti Puja","शनि महादशा शांति पूजा":"Shani Mahadasha Shanti Puja","शनि दोष निवारण पूजा":"Shani Dosha Nivaran Puja","काल सर्प दोष निवारण महापूजा":"Kaal Sarp Dosha Nivaran Mahapuja","पिशाच मोचन कुंड पूजा":"Pishach Mochan Kund Puja","पितृ तर्पण पूजा":"Pitru Tarpan Puja"},zl={पूजा:"Puja",महापूजा:"Mahapuja",दोष:"Dosha",निवारण:"Nivaran",शांति:"Shanti",महायज्ञ:"Mahayagya",यज्ञ:"Yagya",अभिषेक:"Abhishek",रुद्राभिषेक:"Rudrabhishek",आरती:"Aarti",महाआरती:"Maha Aarti",महादशा:"Mahadasha",मंदिर:"Temple",ज्योतिर्लिंग:"Jyotirlinga",देव:"Dev",एवं:"&",और:"and",तिल:"Til",तेल:"Tel",गंगा:"Ganga",पाप:"Paap",ग्रह:"Graha",नवग्रह:"Navagraha",मंगल:"Mangal",शनि:"Shani","साढ़े साती":"Sade Sati",साढ़ेसाती:"Sade Sati",राहु:"Rahu",केतु:"Ketu",गुरु:"Guru",सूर्य:"Surya",चंद्र:"Chandra",चन्द्र:"Chandra",बुध:"Budh",शुक्र:"Shukra","काल सर्प":"Kaal Sarp",कालसर्प:"Kaal Sarp",पितृ:"Pitru",पितर:"Pitra",श्रापित:"Shrapit",चांडाल:"Chandal",काशी:"Kashi",त्र्यंबकेश्वर:"Trimbakeshwar",हथला:"Hathla"},Hn={"काशी विश्वनाथ मंदिर":"Kashi Vishwanath Temple","त्र्यंबकेश्वर मंदिर":"Trimbakeshwar Temple","त्र्यंबकेश्वर ज्योतिर्लिंग":"Trimbakeshwar Jyotirlinga","महाकालेश्वर मंदिर":"Mahakaleshwar Temple","सोमनाथ मंदिर":"Somnath Temple","केदारनाथ मंदिर":"Kedarnath Temple","बद्रीनाथ मंदिर":"Badrinath Temple","रामेश्वरम मंदिर":"Rameshwaram Temple","द्वारकाधीश मंदिर":"Dwarkadhish Temple","जगन्नाथ पुरी मंदिर":"Jagannath Puri Temple","हथला शनि देव मंदिर":"Hathla Shani Dev Temple"};function Vl(t){const e=t.split("/");if(e.length!==3)return null;const r=parseInt(e[0],10),s=parseInt(e[1],10)-1,n=parseInt(e[2],10);return new Date(n,s,r)}function Gn(t){let e=t;return Object.entries(zl).sort((s,n)=>n[0].length-s[0].length).forEach(([s,n])=>{const i=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi");e=e.replace(i,n)}),e.replace(/\s+/g," ").trim()}function ps(t,e){const r=e?.toLowerCase().startsWith("hi"),s=typeof t=="string"?t:t.pooja_title,n=typeof t=="string"?void 0:t.pooja_title_english;if(r)return s;if(n?.trim())return n;if(Wn[s])return Wn[s];const i=Gn(s);return i!==s?i:s}function zn(t,e){const r=e?.toLowerCase().startsWith("hi"),s=typeof t=="string"?t:t.temple_name,n=typeof t=="string"?void 0:t.temple_name_english;if(r)return s;if(n?.trim())return n;if(Hn[s])return Hn[s];const i=Gn(s);return i!==s?i:s}function Vn(t,e="en"){const r=Vl(t);if(!r)return t;const n=e?.toLowerCase().startsWith("hi")?"hi-IN":"en-GB";return new Intl.DateTimeFormat(n,{day:"numeric",month:"short",year:"numeric"}).format(r)}function Jl(t){if(!t||typeof window>"u")return t;try{const e=new URLSearchParams(window.location.search),r=e.get("utm_source"),s=e.get("utm_medium"),n=e.get("utm_content");if(!r&&!s&&!n)return t;const i=new URL(t);return r&&i.searchParams.set("utm_source",r),s&&i.searchParams.set("utm_medium",s),n&&i.searchParams.set("utm_content",n),i.toString()}catch{return t}}function gs(t,e){const s=e?.toLowerCase().startsWith("hi")?t.puja_link_hindi||t.puja_link:t.puja_link||t.puja_link_hindi;return Jl(s||"")}function Jn(t,e){return e?.toLowerCase().startsWith("hi")?t.cover_media_url||t.cover_media_url_english||"":t.cover_media_url_english||t.cover_media_url||""}const Yl={container:"_container_m8vst_1"},Ql=["en","hi"],Xl={en:"English",hi:"हिन्दी"},Yn={en:{language:"Language",guest:"Guest",sriMandir:"Sri Mandir",ratingText:"3 Crore+ app downloads",feedbackTitle:"What Others Discovered Through Their Dosha Analysis",feedbackTrust:"Trusted by over 5 crore users worldwide",feedbackRating:"4.9",feedbackTestimonial1:"I was facing delay in marriage and also tension in career. After checking my kundli I understood the problems clearly. I followed the remedies with faith and slowly things started improving. Now my marriage is fixed and job situation is also better. Feeling very thankful.",feedbackTestimonial2:"My health was not good from long time and money problems also coming again and again. The report explained everything in simple way. After doing small remedies I feel more positive and health is improving. Very good experience.",feedbackTestimonial3:"Career was fully stuck and no promotion from 3 years. I created my kundli here and got to know about some dosha affecting work life. After remedies within few months I changed job with better salary. Really happy.",feedbackTestimonial4:"I checked kundli for marriage but it also told about finance issues. Remedies were easy to follow. Slowly money stability came and good rishta also came in family. Feeling peaceful now.",feedbackTestimonial5:"Simple and clear guidance. Problems in job and health both reduced after remedies. Good service.",feedbackTestimonial6:"Too much stress in life related to marriage and future. Kundli reading was very detailed but easy to understand. After doing puja and mantra I feel calm and recently got good marriage proposal. Thank you so much.",feedbackTestimonial7:"Finance loss was happening again and again in business. They told reason from kundli and suggested remedy. I followed for few weeks and situation slowly became stable. Good support.",feedbackTestimonial8:"I almost lost hope for marriage and career both. But this kundli analysis gave me new confidence. Within 2 months I got interview call and also one good match from relatives. Things are moving finally.",feedbackTestimonial9:"Very genuine report not copy paste. Health issue reason also explained. After remedies I feel more energy and mind peace. Satisfied.",feedbackTestimonial10:"Marriage delay, money tension, family stress everything was going wrong. Remedies were small but powerful. Now engagement done and finance also improving slowly. Feeling blessed.",feedbackTestimonial11:"I was not believing before but result surprised me. Career growth started after long time and new opportunities coming. Good guidance and honest prediction.",feedbackTestimonial12:"Health problems and negative thoughts were too much. After following remedies I feel mentally strong and peaceful. Family also noticing the change. Very grateful.",feedbackTestimonial13:"Short review. Career better now and money flow also improved after remedy. Thank you.",feedbackTestimonial14:"Kundli reading helped me understand many hidden issues in life like marriage delay and job confusion. Remedies were simple daily things. Slowly life becoming stable. Nice experience overall.",feedbackTestimonial15:"Good for anyone facing problems in marriage career or finance. Simple language and true guidance. I saw positive change in few months only. Highly recommended.",feedbackAuthor1:"Abhishek Mishra",feedbackAuthor2:"Pooja Verma",feedbackAuthor3:"Amit Patel",feedbackAuthor4:"Sneha Gupta",feedbackAuthor5:"Vikas Yadav",feedbackAuthor6:"Neha Singh",feedbackAuthor7:"Rahul Jain",feedbackAuthor8:"Kavita Mishra",feedbackAuthor9:"Sandeep Kumar",feedbackAuthor10:"Anjali Mehta",feedbackAuthor11:"Deepak Arora",feedbackAuthor12:"Ritu Saxena",feedbackAuthor13:"Manoj Tiwari",feedbackAuthor14:"Priya Nair",feedbackAuthor15:"Karan Malhotra",feedbackAuthor1AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639330970.png",feedbackAuthor2AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639293055.png",feedbackAuthor3AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639358174.png",feedbackAuthor4AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639427379.png",feedbackAuthor5AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639381899.png",feedbackAuthor6AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639416587.png",feedbackAuthor7AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639454626.png",feedbackAuthor8AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639319028.png",feedbackAuthor9AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639271096.png",feedbackAuthor10AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639254172.png",feedbackAuthor11AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639345411.png",feedbackAuthor12AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639306698.png",feedbackAuthor13AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639330970.png",feedbackAuthor14AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639402894.png",feedbackAuthor15AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639358174.png",readMoreReviews:"Read More Reviews",readLess:"Read Less",feedbackTitleMarriage:"What others facing marriage delay discovered",feedbackTestimonialMarriage1:"My marriage was getting delayed again and again and we were very worried. After creating my kundli here I came to know about Mangal dosh and some other issues. The remedies suggested were simple and within few months things started moving. Now my engagement is fixed. Feeling very thankful.",feedbackTestimonialMarriage2:"I was honestly not believing in kundli much but my parents forced me to try. They found a marriage dosha in my chart and gave puja guidance. After doing it I met a very good person through relatives. Sometimes these things really work.",feedbackTestimonialMarriage3:"Got my kundli checked because nothing was working for my wedding. Every match was breaking. The report clearly explained the doshas and what to do. Followed the remedy for 40 days and suddenly one perfect match came. Married now and happy.",feedbackTestimonialMarriage4:"Very helpful service. Found reason for delay in marriage and solution also given. Things improved slowly.",feedbackTestimonialMarriage5:"I was 32 and tension in home was too much. Kundli showed Shani related problem affecting marriage. Did the suggested donation and mantra. Within 3 months alliance got finalised. Still feels like miracle honestly.",feedbackTestimonialMarriage6:"The explanation was simple and easy to understand. I liked that they did not scare me but gave practical remedies. After doing them my long pending relationship got approval from both families and we are getting married soon.",feedbackTestimonialMarriage7:"Short review but true. Marriage dosh removed after remedies and now wedding date fixed. Thank you so much.",feedbackTestimonialMarriage8:"Many astrologers told different things and I was confused. Here the kundli analysis felt genuine and detailed. They pointed out exact dosha causing breakups. After remedies my partner came back and families agreed. Feeling peaceful now.",feedbackTestimonialMarriage9:"I created my kundli just casually but result shocked me. There was strong manglik issue. Followed puja on Tuesday as told. Within few months I got good proposal from same city. Everything went smooth after that.",feedbackTestimonialMarriage10:"Service is good and fast. Report is clear. My marriage problem solved after remedy. Satisfied.",feedbackTestimonialMarriage11:"For 5 years nothing was happening in my life regarding marriage. After kundli matching they told to wait few months and do certain prayers. Exactly in that time I met my husband through office. Now happily married for 1 year.",feedbackTestimonialMarriage12:"Very emotional moment for me writing this. I had almost lost hope. The dosha remedies gave me confidence and positivity also. Slowly situations changed and today my roka ceremony is done. Truly grateful.",feedbackTestimonialMarriage13:"Nice guidance and honest prediction. No false promises. Remedies worked for my delayed marriage issue.",feedbackTestimonialMarriage14:"My daughter kundli was checked here. They found dosha and suggested simple temple visit and fasting. We followed sincerely. Within short time good proposal came from nice family. As parents we are very relieved.",feedbackTestimonialMarriage15:"I recommend this to anyone facing marriage delay. Kundli analysis felt real not copy paste. Small small remedies but big change in life. Thank you from heart.",faqTitle:"Frequently Asked Questions",faqQ1:"Is this really free?",faqA1:"Yes, the Dosha Calculator is completely free to use. You can check your kundli for doshas and get detailed analysis at no cost.",faqQ2:"What if I don't know birth time?",faqA2:"You can enter an approximate birth time or use 12:00 PM as default. Some doshas like Mangal Dosha and Kaal Sarp Dosha can still be detected with approximate time.",faqQ3:"Is this a generic report?",faqA3:"No, your report is personalized based on your exact date, time, and place of birth. Each kundli analysis is unique and the dosha detection is specific to your birth chart.",faqQ1Marriage:"Is this really free?",faqA1Marriage:"Yes, the Dosha Calculator is completely free to use. You can check your kundli for doshas and get detailed analysis at no cost.",faqQ2Marriage:"What if I don't know birth time?",faqA2Marriage:"You can enter an approximate birth time or use 12:00 PM as default. Some doshas like Mangal Dosha and Kaal Sarp Dosha can still be detected with approximate time.",faqQ3Marriage:"Is this a generic report?",faqA3Marriage:"No, your report is personalized based on your exact date, time, and place of birth. Each kundli analysis is unique and the dosha detection is specific to your birth chart.",faqQ4Marriage:"Will this fix my marriage delay?",faqA4Marriage:"The calculator identifies doshas that may be causing marriage delay. Once detected, we recommend specific pujas and remedies that have helped thousands of users overcome marriage obstacles.",formPrivacyBanner:"100% Private & Secure",formTitle:"Enter your details",formSubtitle:"We'll generate your kundli to know your doshas",formNameLabel:"Enter Your Name",formNamePlaceholder:"Your Name",formGenderLabel:"Your Gender",formGenderMale:"Male",formGenderFemale:"Female",formProblemLabel:"What problem is bothering you?",formProblemMarriage:"Marriage",formProblemMoney:"Money",formProblemOther:"Others",formProblemHealth:"Health",formProblemEducation:"Education",formProblemCareer:"Career",formProblemOtherPlaceholder:"Please describe your problem",formProblemOtherHint:"Max 100 characters",formDobLabel:"Select Date of Birth",formDobInfo:"Your date of birth is used to calculate your dosha balance.",formTimeLabel:"Exact Time of Birth",formTimeInfo:"Birth time helps improve accuracy of the analysis.",formTimeUnknown:"I don't know my birth time",formTimeUnknownHelp:"Note - Without exact birth time, accuracy will be reduced. We'll run Moon-based checks only.",formPlaceLabel:"Enter your birth place",formPlaceInfo:"City and state/country help us refine your result.",formPlacePlaceholder:"City, State",formFooterNote:"Analysis Takes Only 60 seconds",formFooterNoteBefore:"Analysis Takes Only ",formFooterNoteBold:"60 seconds",formFooterNoteAfter:"",formCta:"Check My Dosha for FREE",formCtaCalculate:"Calculate my Dosha",calculating:"Calculating...",bookPuja:"Book Puja",resultPageTitle:"Find Puja Remedy for Free",resultPageSubtitle:"Analyse your kundli to find out which doshas (if any) appear in your Vedic chart—and see devotional remedies.",calculationSuccess:"Your dosha analysis is ready.",calculationError:"Something went wrong. Please try again.",formError:"Please correct the highlighted fields.",formNameRequired:"Name is required.",formGenderRequired:"Gender is required.",formDobRequired:"Date of birth is required.",formTimeRequired:"Time is required when birth time is known.",formPlaceRequired:"Birth place is required.",formPlaceSelectFromDropdown:"Please select a place from the dropdown list.",formAgeMarriageRestriction:"Please select appropriate problem areas. Marriage, financial, career, and business-related issues are applicable for users above 18 years.",locationError:"Could not get location coordinates. Please try again.",calculationResolvingPlace:"Resolving place…",info:"Info",resultTitle:"Your Dosha Analysis",resultSomeDoshas:"Some Doshas Have Been Detected",resultNoDoshas:"No Major Doshas Found",resultNoDoshasDesc:"Your birth chart shows no major doshas.",resultMangal:"Mangal Dosha",resultKaalSarp:"Kaal Sarp Dosha",resultPitra:"Pitra Dosha",resultSadeSati:"Shani Sade Sati",resultStatusPresent:"Present",resultStatusAbsent:"Absent",resultStatusInactive:"Inactive",resultExplanation:"Explanation",resultRemedies:"Remedies",resultEditForm:"Edit details",drStatus:"Status",drSeverity:"Severity",drType:"Type",drPhase:"Phase",drExplanation:"Explanation",drWhyPresent:"Why Present",drWhyAbsent:"Why Absent",drImpact:"Impact",drPlanetaryPositions:"Planetary Positions",drTraditionalRemedies:"Traditional Remedies",drDetailedAnalysis:"Detailed Analysis & Remedies",drBasedOnChart:"Based on your birth chart calculations",drDisclaimer:"While we follow established astrological rules, dosha interpretation can vary among astrologers. We recommend consulting an astrologer you trust if you wish to explore additional viewpoints.",drStatusPresent:"Present",drStatusAbsent:"Absent",drStatusInactive:"Inactive",drStatusActive:"Active",drStatusSuggested:"Suggested",drStatusNullified:"Present (Nullified)",drMangalName:"Mangal Dosha (Manglik)",drMangalDesc:"Mangal (Manglik/Kuja) Dosha — Linked with Mars in certain houses; traditionally associated with friction in relationships and decisiveness.",drMangalImpact:"Greater likelihood of friction in close relationships, impatience/anger spikes, or delays and stops/starts in marriage or partnerships.",drMangalRemedies:`Recite Hanuman Chalisa daily
|
|
45
45
|
Fast on Tuesdays
|
|
46
46
|
Donate red items like lentils or cloth
|
|
47
47
|
Wear a coral gemstone after consultation`,drKaalSarpName:"Kaal Sarp Dosha",drKaalSarpDesc:"Kaal Sarp Dosha — All planets hemmed between Rahu and Ketu; often framed as a pattern indicating inner tension and transformation.",drKaalSarpImpact:"A pattern of inner restlessness and periodic setbacks; plans may feel blocked or get delayed despite effort, requiring extra persistence.",drKaalSarpRemedies:`Recite Maha Mrityunjaya Mantra 108 times daily
|
|
@@ -149,12 +149,12 @@ Visit Navagraha temples`,ctaKundliCreated:"3L+ Kundli Reports Created.",ctaCerti
|
|
|
149
149
|
परामर्श के बाद लहसुनिया पहनें`,drOtherNavagrahaRemedies:`व्यापक नवग्रह शांति पूजा करें
|
|
150
150
|
नवग्रह मंत्र का पाठ करें
|
|
151
151
|
सभी नौ ग्रहों के लिए वस्तुओं का दान करें
|
|
152
|
-
नवग्रह मंदिरों में जाएं`,ctaKundliCreated:"3L+ कुंडली रिपोर्ट बनाई।",ctaCertified:"BHU प्रमाणित ज्योतिषी।",ctaSecurePayment:"सुरक्षित भुगतान।",contactTitle:"संपर्क करें",contactBrandName:"श्री मंदिर",contactWhatsAppGlobal:"व्हाट्सएप: 8296947757",contactWhatsAppDomestic:"व्हाट्सएप: 08071174417",contactEmail:"ईमेल: pujaseva@appsforbharat.com",whatFromAnalysisTitle:"इस विश्लेषण से आपको क्या मिलेगा",whatFromAnalysisMarriage1Title:"शादी पर प्रभाव जानें",whatFromAnalysisMarriage1Desc:"क्या शादी में देरी होगी, कोई समस्या आएगी या मैच सही रहेगा।",whatFromAnalysisMarriage2Title:"मंगल दोष की पुष्टि",whatFromAnalysisMarriage2Desc:"जानें कि मंगल दोष है या नहीं और वह कितना मजबूत है।",whatFromAnalysisMarriage3Title:"उपाय और पूजा की जानकारी",whatFromAnalysisMarriage3Desc:"कौन सा उपाय या पूजा आपके लिए सही रहेगा।",whatFromAnalysisGeneric1Title:"जीवन पर प्रभाव का संक्षेप",whatFromAnalysisGeneric1Desc:"शादी, करियर, पैसे, सेहत और पढ़ाई में होने वाली देरी, परेशानी या अवसरों को समझें",whatFromAnalysisGeneric2Title:"दोष की पुष्टि",whatFromAnalysisGeneric2Desc:"जानें कि कोई दोष या ग्रहों का असंतुलन आपकी प्रगति को प्रभावित कर रहा है या नहीं",whatFromAnalysisGeneric3Title:"उपाय की दिशा",whatFromAnalysisGeneric3Desc:"कौन सा उपाय या पूजा आपके लिए सही रहेगा।"}},Zn=w.createContext(null);function ei(){return typeof window>"u"?"en":window.location.pathname.split("/").filter(Boolean)[0]==="hi"?"hi":"en"}function nc(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 ic({locale:t,onLocaleChange:e,children:r}){const[s,n]=w.useState(()=>t||ei());w.useEffect(()=>{if(t)n(t);else{const o=()=>n(ei());return window.addEventListener("popstate",o),()=>window.removeEventListener("popstate",o)}},[t]);const i=o=>{e?e(o):nc(o)},a=w.useMemo(()=>o=>Xn[s]?.[o]??o,[s]);return c.jsx(Zn.Provider,{value:{locale:s,setLocale:i,t:a},children:r})}function ys(){return w.useContext(Zn)}function ac(){const e=ys()?.locale==="hi";return c.jsx("div",{className:tc.container,children:e?"100% सटीक • सुरक्षित • 30 लाख+ परिवारों द्वारा विश्वसनीय":"100% Accurate • Secure • Trusted by 30L+ families"})}const Fe=t=>({width:t,height:t});function bs(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"}),c.jsx("path",{d:"M12 9v4"}),c.jsx("path",{d:"M12 17h.01"})]})}function ti(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),c.jsx("path",{d:"m9 11 3 3L22 4"})]})}function Br(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("path",{d:"M12 16v-4"}),c.jsx("path",{d:"M12 8h.01"})]})}function oc(t){const{size:e=24,...r}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:c.jsx("path",{d:"M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"})})}function lc(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"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 cc(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function uc(t){const{size:e=24,...r}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:c.jsx("path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"})})}function dc(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"m5 12 7-7 7 7"}),c.jsx("path",{d:"M12 19V5"})]})}function ri(t){const{size:e=24,...r}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:c.jsx("path",{d:"m6 9 6 6 6-6"})})}function vs(t){const{size:e=24,className:r="",...s}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`animate-spin ${r}`,style:{animation:"spin 1s linear infinite"},...Fe(e),...s,children:c.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})}function hc(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("line",{x1:"10",x2:"21",y1:"14",y2:"3"})]})}function fc(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),c.jsx("path",{d:"M3 3v5h5"})]})}const Ke={ctaFilled:"_ctaFilled_8nukz_2",ctaFilledContent:"_ctaFilledContent_8nukz_7",chevronRight:"_chevronRight_8nukz_14",bookPujaButton:"_bookPujaButton_8nukz_21",bookPujaContent:"_bookPujaContent_8nukz_27",pujaInfo:"_pujaInfo_8nukz_36",pujaName:"_pujaName_8nukz_44",pujaPrice:"_pujaPrice_8nukz_57",priceLabel:"_priceLabel_8nukz_64",priceAmount:"_priceAmount_8nukz_68",bookButton:"_bookButton_8nukz_74"},lt=t=>{const{priority:e,fetchPriority:r,width:s,height:n,...i}=t;return w.createElement("img",{...i,width:s??1,height:n??1,decoding:"async",loading:i.loading??(e?"eager":"lazy"),...r&&{fetchPriority:r}})},mc="https://srm-cdn.a4b.io/yoda/1771588545907.svg";function pc({isFormComplete:t,onPress:e,labelDefault:r,labelFilled:s,isLoading:n=!1,mode:i="form",firstPuja:a,showingResults:o=!1,bookPujaLabel:l="Book Puja",loadingLabel:u="Calculating..."}){return i==="book-puja"&&a&&o?c.jsx(q.FooterCTAButton,{onClick:e,disabled:n,className:Ke.bookPujaButton,children:c.jsxs("div",{className:Ke.bookPujaContent,children:[c.jsxs("div",{className:Ke.pujaInfo,children:[c.jsx("span",{className:Ke.pujaName,children:a.name}),a.price>0&&c.jsxs("div",{className:Ke.pujaPrice,children:[c.jsx("span",{className:Ke.priceLabel,children:"Starting from "}),c.jsxs("span",{className:Ke.priceAmount,children:["₹",a.price]})]})]}),c.jsxs("span",{className:Ke.bookButton,children:[l," →"]})]})}):c.jsx(q.FooterCTAButton,{onClick:e,disabled:n,className:t?Ke.ctaFilled:void 0,children:n?c.jsxs("span",{className:Ke.ctaFilledContent,children:[c.jsx(vs,{className:"w-5 h-5 animate-spin"}),u]}):t?c.jsxs("span",{className:Ke.ctaFilledContent,children:[s,c.jsx(lt,{src:mc,alt:"",className:Ke.chevronRight,width:20,height:20,loading:"lazy"})]}):r})}const Fr={bannerContainer:"_bannerContainer_1s29r_1",bannerImage:"_bannerImage_1s29r_13",ticker:"_ticker_1s29r_20",tickerContent:"_tickerContent_1s29r_30"};function gc({bannerConfig:t,className:e="",imageComponent:r=lt}){const s=r;return c.jsxs("section",{className:`${Fr.bannerContainer} ${e}`,children:[c.jsx(s,{src:t.imageUrl,alt:t.alt,className:Fr.bannerImage,loading:"eager",priority:!0,fetchPriority:"high"}),c.jsx("div",{className:Fr.ticker,children:c.jsx("div",{className:Fr.tickerContent,children:t.tickerText})})]})}const yc=112;function ht({section:t,children:e,onImpression:r}){const s=w.useRef(null),n=w.useRef(!1);return w.useEffect(()=>{const i=s.current;if(!i)return;const a=new IntersectionObserver(([o])=>{!o?.isIntersecting||n.current||(n.current=!0,r(t))},{threshold:.1,rootMargin:`0px 0px -${yc}px 0px`});return a.observe(i),()=>a.disconnect()},[t,r]),c.jsx("div",{ref:s,children:e})}const Ft={wrap:"_wrap_1mrzx_1",input:"_input_1mrzx_6",iconBtn:"_iconBtn_1mrzx_35",iconImg:"_iconImg_1mrzx_49",placeholder:"_placeholder_1mrzx_53",dateDisplay:"_dateDisplay_1mrzx_65"},bc="https://srm-cdn.a4b.io/yoda/1770372045894.svg",vc=t=>{if(!t)return"";const[e,r,s]=t.split("-");return`${s}/${r}/${e}`};function wc({id:t,value:e,onChange:r,onOpen:s,className:n=""}){const i=w.useRef(null),a=w.useMemo(()=>{const l=new Date,u=d=>String(d).padStart(2,"0");return`${l.getFullYear()}-${u(l.getMonth()+1)}-${u(l.getDate())}`},[]),o=()=>{s?.();const l=i.current;if(l&&typeof l.showPicker=="function")try{l.showPicker()}catch{l?.focus()}else l?.focus()};return c.jsxs("div",{className:`${Ft.wrap} ${n}`,children:[!e&&c.jsx("span",{className:Ft.placeholder,children:"Select Date of Birth"}),e&&c.jsx("div",{className:Ft.dateDisplay,children:vc(e)}),c.jsx("input",{ref:i,id:t,type:"date",className:Ft.input,value:e,max:a,onChange:l=>{const u=l.target.value,d=new Date,h=m=>String(m).padStart(2,"0"),p=`${d.getFullYear()}-${h(d.getMonth()+1)}-${h(d.getDate())}`;u&&u>p||r(u)},onClick:o,onFocus:o}),c.jsx("button",{type:"button",className:Ft.iconBtn,"aria-label":"Open date picker",onMouseDown:l=>l.preventDefault(),onClick:l=>{l.preventDefault(),l.stopPropagation(),o()},children:c.jsx(lt,{className:Ft.iconImg,src:bc,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"},_c="https://srm-cdn.a4b.io/yoda/1770372014782.svg",si=t=>String(t).padStart(2,"0");function kc(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 Sc(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 xc(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),`${si(s)}:${r}`}function Tc({id:t,value:e,onChange:r,onOpen:s,placeholder:n="Exact Time of Birth",disabled:i=!1,className:a=""}){const o=w.useRef(null),[l,u]=w.useState(!1),[d,h]=w.useState({hour12:12,minute:"00",meridiem:"AM"});w.useEffect(()=>{const g=y=>{o.current&&(o.current.contains(y.target)||u(!1))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[]);const p=()=>{i||(s?.(),h(Sc(e||"12:00")),u(g=>!g))},m=()=>{const g=xc(d);r(g),u(!1)};return c.jsxs("div",{className:`${ve.wrap} ${a}`,ref:o,children:[c.jsx("input",{id:t,className:ve.input,type:"text",value:e?kc(e):"",readOnly:!0,disabled:i,placeholder:n,onClick:p}),c.jsx("button",{type:"button",className:ve.iconBtn,"aria-label":"Open time picker",disabled:i,onMouseDown:g=>g.preventDefault(),onClick:g=>{g.preventDefault(),g.stopPropagation(),p()},children:c.jsx(lt,{className:ve.iconImg,src:_c,alt:"",width:22,height:22,loading:"lazy"})}),l&&!i&&c.jsxs("div",{className:ve.timePopover,role:"dialog","aria-label":"Select time",children:[c.jsxs("div",{className:ve.timePickerRow,children:[c.jsx("select",{className:ve.timePickerSelect,value:d.hour12,onChange:g=>h(y=>({...y,hour12:Number(g.target.value)})),"aria-label":"Hour",children:Array.from({length:12},(g,y)=>y+1).map(g=>c.jsx("option",{value:g,children:g},g))}),c.jsx("span",{className:ve.timePickerColon,children:":"}),c.jsx("select",{className:ve.timePickerSelect,value:d.minute,onChange:g=>h(y=>({...y,minute:g.target.value})),"aria-label":"Minute",children:Array.from({length:60},(g,y)=>si(y)).map(g=>c.jsx("option",{value:g,children:g},g))}),c.jsxs("div",{className:ve.meridiemToggle,"aria-label":"AM/PM",children:[c.jsx("button",{type:"button",className:`${ve.meridiemBtn} ${d.meridiem==="AM"?ve.meridiemActive:""}`,onClick:()=>h(g=>({...g,meridiem:"AM"})),children:"AM"}),c.jsx("button",{type:"button",className:`${ve.meridiemBtn} ${d.meridiem==="PM"?ve.meridiemActive:""}`,onClick:()=>h(g=>({...g,meridiem:"PM"})),children:"PM"})]})]}),c.jsxs("div",{className:ve.timePopoverActions,children:[c.jsx("button",{type:"button",className:ve.timePopoverBtn,onClick:()=>u(!1),children:"Cancel"}),c.jsx("button",{type:"button",className:`${ve.timePopoverBtn} ${ve.timePopoverOk}`,onClick:m,"aria-label":"OK",children:c.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:c.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})]})}async function ni(t,e){const{visitorId:r,sessionId:s,problemStatements:n,language:i}=e;if(n.length!==0)try{await t.from("session_problem_statements").insert({visitor_id:r,session_id:s,problem_statements:n,language:i??"en"})}catch{}}async function ii(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 ai(t,e,r={}){const{visitorId:s="unknown",sessionId:n="unknown",trackProblemStatements:i=!0,problemStatements:a=[],language:o="en"}=r;return i&&a.length>0&&await ni(t,{visitorId:s,sessionId:n,problemStatements:a,language:o}),ii(t,e,{"x-visitor-id":s,"x-session-id":n})}let Kr=null;const Ec=(t,e)=>typeof window>"u"||window.google?.maps?.places?Promise.resolve():Kr||(Kr=new Promise((r,s)=>{const n=document.querySelector('script[data-google-maps-places="true"]');if(n){const o=Date.now(),l=()=>{if(window.google?.maps?.places){r();return}if(Date.now()-o>5e3){s(new Error("Google Maps script present but Places library did not become available."));return}window.setTimeout(l,50)};n.getAttribute("src")?l():(n.addEventListener("load",()=>l()),n.addEventListener("error",()=>s(new Error("Failed to load Google Maps API"))));return}const i=document.createElement("script"),a=new URL("https://maps.googleapis.com/maps/api/js");a.searchParams.set("key",t),a.searchParams.set("libraries","places"),a.searchParams.set("loading","async"),e&&a.searchParams.set("language",e),i.src=a.toString(),i.async=!0,i.defer=!0,i.setAttribute("data-google-maps-places","true"),i.onload=()=>{const o=Date.now(),l=()=>{if(window.google?.maps?.places){r();return}if(Date.now()-o>2e3){s(new Error("Google Maps loaded but Places library is unavailable. Check API key restrictions / enabled APIs."));return}window.setTimeout(l,50)};l()},i.onerror=()=>s(new Error("Failed to load Google Maps API")),document.head.appendChild(i)}),Kr),oi=(t={})=>{const{apiKey:e,language:r="en",restrictCountry:s}=t,[n,i]=w.useState(!1),[a,o]=w.useState([]),[l,u]=w.useState(!1),[d,h]=w.useState(null),p=w.useRef(null),m=w.useRef(null),g=w.useRef(null);w.useEffect(()=>{if(!e){i(!1),h(null);return}Ec(e,r).then(()=>{try{p.current=new google.maps.places.AutocompleteService;const k=document.createElement("div");m.current=new google.maps.places.PlacesService(k),g.current=new google.maps.places.AutocompleteSessionToken,i(!0),h(null)}catch(k){i(!1),h(k instanceof Error?k.message:"Failed to create Places services")}}).catch(k=>{i(!1),h(k instanceof Error?k.message:"Failed to load location service")})},[e,r]);const y=w.useCallback(async k=>{if(!k||k.length<2||!p.current){o([]);return}u(!0);try{const S={input:k,types:["(cities)"],sessionToken:g.current??void 0};s&&(S.componentRestrictions={country:s});const O=await new Promise((R,M)=>{p.current.getPlacePredictions(S,(E,$)=>{$===google.maps.places.PlacesServiceStatus.OK&&E?R(E):$===google.maps.places.PlacesServiceStatus.ZERO_RESULTS?R([]):M(new Error(`Places API error: ${$}`))})});o(O.map(R=>({place_id:R.place_id,description:R.description,structured_formatting:{main_text:R.structured_formatting?.main_text||R.description,secondary_text:R.structured_formatting?.secondary_text||""}})))}catch{o([])}finally{u(!1)}},[s]),_=w.useCallback(async k=>{if(!m.current)return null;try{const S=await new Promise((L,$e)=>{m.current.getDetails({placeId:k,fields:["geometry","address_components","formatted_address"],sessionToken:g.current??void 0},(ge,Oe)=>{Oe===google.maps.places.PlacesServiceStatus.OK&&ge?L(ge):$e(new Error(`Place details error: ${Oe}`))})});g.current=new google.maps.places.AutocompleteSessionToken;const O=S.geometry?.location?.lat()||0,R=S.geometry?.location?.lng()||0;let M="",E="",$="";return S.address_components?.forEach(L=>{L.types.includes("locality")&&(M=L.long_name),L.types.includes("administrative_area_level_1")&&(E=L.long_name),L.types.includes("country")&&($=L.long_name)}),{display_name:S.formatted_address||"",lat:O,lng:R,city:M,state:E,country:$}}catch{return null}},[]),b=w.useCallback(()=>o([]),[]);return{isLoaded:n,predictions:a,isSearching:l,loadError:d,searchPlaces:y,getPlaceDetails:_,clearPredictions:b}},jc=["formProblemMarriage","formProblemMoney","formProblemHealth","formProblemEducation","formProblemCareer","formProblemOther"];function Ac(){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 Pc(){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 Rc(t){if(!t)return 0;const e=new Date(t);if(Number.isNaN(e.getTime()))return 0;const r=new Date;let s=r.getFullYear()-e.getFullYear();const n=r.getMonth()-e.getMonth();return(n<0||n===0&&r.getDate()<e.getDate())&&s--,s}const ws=w.forwardRef(function({t:e,className:r="",initialValues:s,onValuesChange:n,onFormValidityChange:i,supabase:a,resolvePlace:o,onResult:l,onError:u,onLoadingChange:d,analytics:h,googleMapsApiKey:p},m){const g=A=>A.replace(/[^a-zA-Z\u0900-\u097F\s]/g,"").replace(/\s{2,}/g," "),[y,_]=w.useState(s?.name??""),[b,k]=w.useState(s?.gender??""),[S,O]=w.useState(s?.problems??[]),[R,M]=w.useState(s?.dateOfBirth??""),[E,$]=w.useState(s?.birthTime??""),[L,$e]=w.useState(s?.birthTimeUnknown??!1),[ge,Oe]=w.useState(s?.birthPlace??""),[ee,te]=w.useState(s?.otherProblemText??""),[he,tt]=w.useState(null),[Ce,re]=w.useState(!1),[fe,Se]=w.useState(null),[Q,v]=w.useState({}),F=w.useCallback(A=>{const I=ae=>{const Qe=document.getElementById(ae);return Qe?(Qe.focus(),Qe.scrollIntoView({behavior:"smooth",block:"center"}),!0):!1};if(A==="name"){I("dosha-name");return}if(A==="gender"){const ae=document.querySelector('[role="group"][aria-labelledby="dosha-gender-label"] button');ae&&(ae.focus(),ae.scrollIntoView({behavior:"smooth",block:"center"}));return}if(A==="dateOfBirth"){I("dosha-dob");return}if(A==="birthTime"){I("dosha-time");return}A==="birthPlace"&&I("dosha-place")},[]),z=w.useRef(!1),H=w.useRef(!1),V=w.useRef(!1),B=w.useRef(!1),U=w.useRef(!1),J=w.useRef(null),{predictions:se,isSearching:me,loadError:le,searchPlaces:Ee,getPlaceDetails:qt,clearPredictions:We}=oi({apiKey:p,language:"en"}),Le=w.useCallback(()=>{z.current||(z.current=!0,h?.trackFormFillInitiated?.())},[h]);w.useEffect(()=>{const A=I=>{J.current&&(J.current.contains(I.target)||re(!1))};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[]),w.useEffect(()=>{if(!Ce)return;if(ge.length<2){We();return}const A=window.setTimeout(async()=>{await Ee(ge)},300);return()=>window.clearTimeout(A)},[ge,We,Ce,Ee]);const Et=y.trim()!==""&&(b==="male"||b==="female")&&R!==""&&(E!==""||L)&&ge.trim()!=="";w.useEffect(()=>{i?.(Et)},[Et,i]),w.useEffect(()=>{n?.({name:y,gender:b,problems:S,otherProblemText:ee,dateOfBirth:R,birthTime:E,birthTimeUnknown:L,birthPlace:ge})},[y,b,S,ee,R,E,L,ge,n]),w.useEffect(()=>{!S.includes("formProblemOther")&&ee&&te("")},[S,ee]);const jt=w.useCallback(async(A,I)=>{if(!p)return"UTC";try{const ae=Math.floor(Date.now()/1e3),Qe=`https://maps.googleapis.com/maps/api/timezone/json?location=${A},${I}×tamp=${ae}&key=${p}`,_e=await(await fetch(Qe)).json();return _e.status==="OK"&&_e.timeZoneId?_e.timeZoneId:"UTC"}catch{return"UTC"}},[p]),ct=w.useCallback(async()=>{const A=(ce,je,He=!1)=>{je&&(v(Me=>({...Me,[je]:ce})),F(je)),Se(He?ce:null),u?.(ce)};if(v({}),Se(null),!a){A(e("calculationError"));return}if(!y.trim()){A(e("formNameRequired"),"name");return}if(b!=="male"&&b!=="female"){A(e("formGenderRequired"),"gender");return}if(!R){A(e("formDobRequired"),"dateOfBirth");return}if(!L&&!E){A(e("formTimeRequired"),"birthTime");return}const I=ge.trim();if(!I){A(e("formPlaceRequired"),"birthPlace");return}const ae=g(I).trim();if(!ae){A(e("formPlaceRequired"),"birthPlace");return}const Qe=Rc(R),pt=new Set(["formProblemMarriage","formProblemMoney","formProblemCareer","formProblemBusiness","marriage","financial","career","business"]),_e=S.some(ce=>pt.has(ce));if(Qe<18&&_e){A(e("formAgeMarriageRestriction"),void 0,!0);return}if(!he&&!o){A(e("formPlaceSelectFromDropdown"),"birthPlace");return}d?.(!0);try{let ce,je,He;if(he)ce=he.lat,je=he.lon,he.tz?He=he.tz:(He=await jt(ce,je),tt({...he,tz:He}));else if(o){const ye=await o(I);if(!ye){A(e("locationError")),d?.(!1);return}ce=ye.lat,je=ye.lon,He=ye.tz}else{A(e("formPlaceSelectFromDropdown"),"birthPlace"),d?.(!1);return}const Me={problemAreaValues:[...S.filter(ye=>ye!=="formProblemOther").map(ye=>e(ye)).filter(Boolean),...S.includes("formProblemOther")&&ee.trim()?[ee.trim()]:[]],name:y.trim(),gender:b==="male"?"M":"F",date:R,time:L?"":E||"12:00",unknownTime:L,tz:He||"UTC",lat:ce,lon:je,place:ae,problemArea:void 0};Me.problemArea=Me.problemAreaValues.length>0?Me.problemAreaValues.join(", "):void 0;const ur=Ac(),N=Pc(),ne=Me.problemAreaValues,xe=typeof navigator<"u"&&navigator.language?.toLowerCase().startsWith("hi")?"hi":"en",Te=await ai(a,Me,{visitorId:ur,sessionId:N,trackProblemStatements:!0,problemStatements:ne,language:xe});if(Te.success){Se(null);const[ye,dr,hr]=(Me.date||"").split("-").map(Number),Vr=Me.time||"12:00",[gt,fr]=Vr.split(":").map(Yr=>parseInt(Yr,10)||0);l?.(Te,{day:hr||1,month:dr||1,year:ye||2e3,hour:gt,minute:fr,lat:ce,lon:je,tzone:5.5})}else{let ye=Te.error??e("calculationError");(ye.includes("Expected 'M' | 'F'")||ye.includes("gender"))&&(ye=e("formGenderRequired")),A(ye)}}catch(ce){const je=ce instanceof Error?ce.message:String(ce);A(je)}finally{d?.(!1)}},[a,o,he,ge,y,b,R,E,L,S,e,u,d,h,l,jt,F]);w.useImperativeHandle(m,()=>({submit:ct}),[ct]);const cr=jc.map(A=>({key:A,label:e(A)}));return c.jsxs(q.FormContainer,{className:r,"aria-label":e("formTitle"),children:[c.jsx(q.PrivacyBanner,{text:e("formPrivacyBanner")}),c.jsx(q.FormSectionHeader,{title:e("formTitle"),subtitle:e("formSubtitle")}),c.jsx("div",{onFocusCapture:()=>{Le(),h?.trackNameSectionClicked?.()},children:c.jsxs(q.FormField,{id:"dosha-name",label:e("formNameLabel"),required:!0,children:[c.jsx(q.FormTextInput,{id:"dosha-name",value:y,onChange:A=>{const I=A.target.value;I&&!H.current&&(H.current=!0,h?.trackNameSectionFilled?.()),_(I),Q.name&&v(ae=>({...ae,name:void 0})),fe&&Se(null)},placeholder:e("formNamePlaceholder"),autoComplete:"name"}),Q.name&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.name})]})}),c.jsxs(q.FormField,{id:"dosha-gender",label:e("formGenderLabel"),required:!0,children:[c.jsx(q.FormSegmentedControl,{id:"dosha-gender",options:[{value:"male",label:e("formGenderMale")},{value:"female",label:e("formGenderFemale")}],value:b,onChange:A=>{k(A),Q.gender&&v(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:cr,selected:S,onChange:A=>{O(A),A.includes("formProblemOther")||te("")}}),S.includes("formProblemOther")&&c.jsxs("div",{style:{marginTop:"8px"},children:[c.jsx(q.FormTextInput,{id:"dosha-problem-other",value:ee,onChange:A=>{const I=A.target.value.slice(0,100);te(I)},placeholder:e("formProblemOtherPlaceholder")}),c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#8f6e56"},children:e("formProblemOtherHint")})]})]}),c.jsx(q.FormField,{id:"dosha-dob",label:e("formDobLabel"),required:!0,children:c.jsxs("div",{style:{minHeight:Q.dateOfBirth?"72px":"48px",transition:"min-height 0.2s"},children:[c.jsx(wc,{id:"dosha-dob",value:R,onOpen:()=>{Le(),h?.trackDobClicked?.()},onChange:A=>{A&&!V.current&&(V.current=!0,h?.trackDobFilled?.()),M(A),Q.dateOfBirth&&v(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(Tc,{id:"dosha-time",value:E,onOpen:()=>{Le(),h?.trackTimeClicked?.()},onChange:A=>{A&&!B.current&&(B.current=!0,h?.trackTimeFilled?.()),$(A),Q.birthTime&&v(I=>({...I,birthTime:void 0})),fe&&Se(null)},disabled:L}),Q.birthTime&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.birthTime})]})}),c.jsx(q.FormCheckboxWithHelp,{id:"dosha-time-unknown",checked:L,onChange:A=>{Le(),h?.trackTimeCheckboxClicked?.(),$e(A),A&&Q.birthTime&&v(I=>({...I,birthTime:void 0}))},primaryText:e("formTimeUnknown"),helpText:e("formTimeUnknownHelp")}),c.jsx("div",{onFocusCapture:()=>{Le(),h?.trackPlaceOfBirthClicked?.()},children:c.jsx(q.FormField,{id:"dosha-place",label:e("formPlaceLabel"),required:!0,children:c.jsxs("div",{ref:J,style:{position:"relative"},children:[c.jsx(q.FormLocationInput,{id:"dosha-place",value:ge,onChange:A=>{const I=g(A.target.value);Oe(I),tt(null),re(!0),I&&!U.current&&(U.current=!0,h?.trackPlaceOfBirthChosen?.(I)),Q.birthPlace&&v(ae=>({...ae,birthPlace:void 0})),fe&&Se(null)},onFocus:()=>re(!0),placeholder:e("formPlacePlaceholder")}),Q.birthPlace&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.birthPlace}),Ce&&se.length>0&&c.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",maxHeight:"240px",overflowY:"auto",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},role:"listbox",children:se.slice(0,8).map(A=>c.jsxs("button",{type:"button",onClick:async()=>{if(Oe(g(A.description)),qt){const I=await qt(A.place_id);I&&(tt({lat:I.lat,lon:I.lng}),Q.birthPlace&&v(ae=>({...ae,birthPlace:void 0})),fe&&Se(null))}We(),re(!1),U.current||(U.current=!0,h?.trackPlaceOfBirthChosen?.(A.description))},style:{width:"100%",padding:"10px 12px",textAlign:"left",border:"none",backgroundColor:"transparent",cursor:"pointer",display:"flex",flexDirection:"column",gap:"2px",outline:"none"},onMouseEnter:I=>{I.currentTarget.style.backgroundColor="rgba(247, 94, 34, 0.06)"},onMouseLeave:I=>{I.currentTarget.style.backgroundColor="transparent"},onFocus:I=>{I.currentTarget.style.backgroundColor="rgba(247, 94, 34, 0.06)"},onBlur:I=>{I.currentTarget.style.backgroundColor="transparent"},children:[c.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:"#111827"},children:A.structured_formatting?.main_text??A.description}),A.structured_formatting?.secondary_text&&c.jsx("span",{style:{fontSize:"12px",color:"#6b7280"},children:A.structured_formatting.secondary_text})]},A.place_id))}),Ce&&p&&me&&c.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,padding:"10px 12px",backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",fontSize:"12px",color:"#6b7280",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},children:"Loading…"}),Ce&&p&&!me&&le&&c.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,padding:"10px 12px",backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",fontSize:"12px",color:"#dc2626",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},children:le})]})})}),c.jsxs(q.FormFooterNote,{children:["⚡ ",e("formFooterNoteBefore"),c.jsx("strong",{children:e("formFooterNoteBold")}),e("formFooterNoteAfter")]}),fe&&c.jsxs("div",{style:{marginTop:"4px",width:"100%",borderRadius:"14px",border:"1px solid #FCA5A5",background:"#FEF2F2",padding:"16px",display:"flex",alignItems:"flex-start",gap:"10px"},role:"alert","aria-live":"assertive",children:[c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{width:"16px",height:"16px",marginTop:"2px",flexShrink:0},"aria-hidden":"true",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),c.jsx("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]}),c.jsx("p",{style:{margin:0,fontSize:"14px",lineHeight:"1.5",color:"#EF4444"},children:fe})]})]})}),Kt=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`animate-pulse rounded-md bg-muted ${t}`,...e}));Kt.displayName="Skeleton";const ft=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`rounded-lg border border-border bg-card text-card-foreground shadow-sm ${t}`,...e}));ft.displayName="Card";const St=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`flex flex-col space-y-1.5 p-6 ${t}`,...e}));St.displayName="CardHeader";const xt=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("h3",{ref:r,className:`text-2xl font-semibold leading-none tracking-tight ${t}`,...e}));xt.displayName="CardTitle";const qr=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("p",{ref:r,className:`text-sm text-muted-foreground ${t}`,...e}));qr.displayName="CardDescription";const Tt=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`p-6 pt-0 ${t}`,...e}));Tt.displayName="CardContent";const or=Ie.forwardRef(({className:t="",size:e="default",variant:r="default",...s},n)=>{const i={default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8"},a={default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"};return c.jsx("button",{ref:n,type:"button",className:`inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 ${i[e]} ${a[r]} ${t}`,...s})});or.displayName="Button";function li({puja:t,doshaType:e,language:r,onBookClick:s,imageComponent:n=lt,analytics:i}){const a=n,o=r?.toLowerCase().startsWith("hi"),l=ps(t,r),u=Jn(t,r),d=Yn(t.schedule_date_ist,r),h=gs(t,r),p=Qn(t,r),m=async()=>{if(i?.trackDoshaCalculatorResultBookCtaClicked?.({position:"puja_card",url:h,isOldDosha:!1}),s)try{await s()}catch(g){console.error("Error in onBookClick:",g)}window.open(h,"_blank","noopener,noreferrer")};return c.jsx(ft,{className:"overflow-hidden hover:shadow-lg transition-shadow relative",children:c.jsxs("div",{className:"relative",children:[c.jsx("div",{className:"absolute -top-1 -left-1 z-10",children:c.jsx("span",{className:"inline-flex items-center px-2 py-1 text-[10px] font-medium bg-destructive/90 text-destructive-foreground rounded-br-md shadow-sm",children:o?"सीमित सीटें":"Limited Seats"})}),p&&c.jsx("div",{className:"relative aspect-[16/10] w-full overflow-hidden bg-muted",children:c.jsx(a,{src:p,alt:l,className:"w-full h-full object-contain",loading:"lazy"})}),c.jsxs("div",{className:"p-3 space-y-2",children:[c.jsx("h4",{className:"font-semibold text-sm line-clamp-2 text-card-foreground",children:l}),t.temple_name&&c.jsx("p",{className:"text-sm text-muted-foreground",children:u}),t.schedule_date_ist&&c.jsx("p",{className:"text-sm font-medium text-card-foreground",children:d}),t.individual_pack_price_inr>0&&c.jsx("p",{className:"text-base font-bold text-primary",children:o?`₹${t.individual_pack_price_inr} से शुरू`:`Starting from ₹${t.individual_pack_price_inr}`}),c.jsxs(or,{size:"lg",className:"book-puja-cta w-full h-14 text-lg font-bold",onClick:async g=>{g.preventDefault(),await m()},children:[o?"पूजा बुक करें":"Book Puja",c.jsx(hc,{className:"ml-1.5 h-3.5 w-3.5",size:14})]}),c.jsx("p",{className:"text-[10px] text-center text-muted-foreground",children:o?"श्री मंदिर द्वारा संचालित":"Powered by Sri Mandir"})]})]})})}const mt={section:"_section_15ygl_1",heading:"_heading_15ygl_5",list:"_list_15ygl_16",item:"_item_15ygl_20",stepNumber:"_stepNumber_15ygl_24",itemContent:"_itemContent_15ygl_30",itemTitle:"_itemTitle_15ygl_34",itemDesc:"_itemDesc_15ygl_39"};function ci({t,className:e="",bannerType:r="generic"}){const s=t("whatFromAnalysisTitle"),n=r==="marriage"?"whatFromAnalysisMarriage":"whatFromAnalysisGeneric",i=[{titleKey:`${n}1Title`,descKey:`${n}1Desc`},{titleKey:`${n}2Title`,descKey:`${n}2Desc`},{titleKey:`${n}3Title`,descKey:`${n}3Desc`}];return c.jsxs("section",{className:`${mt.section} ${e}`,"aria-labelledby":"what-from-analysis-heading",children:[c.jsx("h2",{id:"what-from-analysis-heading",className:mt.heading,children:s}),c.jsx("ol",{className:mt.list,children:i.map(({titleKey:a,descKey:o},l)=>c.jsxs("li",{className:mt.item,children:[c.jsx("span",{className:mt.stepNumber,"aria-hidden":"true",children:l+1}),c.jsxs("div",{className:mt.itemContent,children:[c.jsx("span",{className:mt.itemTitle,children:t(a)}),c.jsx("span",{className:mt.itemDesc,children:t(o)})]})]},a))})]})}const Oc={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 रेटिंग अपने दोषा को जानने वाले यूज़र्स ने दी"}}},Cc={"marriage-what-you'll-get-first":"marriage","marriage-form-first":"marriage","generic-what-you'll-get-first":"generic","generic-form-first":"generic"};function ui(t,e){let r="generic";if(t){for(const[s,n]of Object.entries(Cc))if(t.includes(s)){r=n;break}}return Oc[r][e]}function Nc(t){return typeof window>"u"?null:new URLSearchParams(window.location.search).get(t)}function Wr(){return Nc("utm_term")}const Ic=w.lazy(()=>Promise.resolve().then(()=>tu).then(t=>({default:t.DoshaResultsFull}))),Dc="https://srm-cdn.a4b.io/yoda/1770362904947.svg",$c="https://srm-cdn.a4b.io/yoda/1770375694934.svg",Lc="https://srm-cdn.a4b.io/yoda/1770375720933.svg",Mc="https://srm-cdn.a4b.io/yoda/1770707793537.svg",Uc="https://srm-cdn.a4b.io/yoda/1770362713543.svg";function di(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 Hr(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function hi(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 fi(t){if(!t||typeof window>"u")return t;try{const e=new URLSearchParams(window.location.search);if(Array.from(e.keys()).length===0)return t;const r=new URL(t,window.location.href);return e.forEach((s,n)=>{r.searchParams.set(n,s)}),r.toString()}catch{return t}}function _s(t){const e=[];return Hr(t.kaalSarp)&&e.push({type:"kaal-sarp",severity:typeof t.kaalSarpSeverity=="string"?t.kaalSarpSeverity:void 0}),Hr(t.pitra)&&e.push({type:"pitra",severity:typeof t.pitraSeverity=="string"?t.pitraSeverity:void 0}),Hr(t.shaniSadeSati||t.sadeSati)&&e.push({type:"shani",severity:typeof t.sadeSatiSeverity=="string"?t.sadeSatiSeverity:void 0}),Hr(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)=>hi(s.severity)-hi(r.severity)),e[0]?.type??null)}function Bc({t}){return c.jsxs("div",{className:q.footerShellStyles.marqueeContent,children:[c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(lt,{src:$c,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaKundliCreated")]}),c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(lt,{src:Lc,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaCertified")]}),c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(lt,{src:Mc,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaSecurePayment")]})]})}const Fc=[{qKey:"faqQ1",aKey:"faqA1"},{qKey:"faqQ2",aKey:"faqA2"},{qKey:"faqQ3",aKey:"faqA3"}],Kc=[{qKey:"faqQ1Marriage",aKey:"faqA1Marriage"},{qKey:"faqQ2Marriage",aKey:"faqA2Marriage"},{qKey:"faqQ3Marriage",aKey:"faqA3Marriage"},{qKey:"faqQ4Marriage",aKey:"faqA4Marriage"}];function qc({className:t="",logoUrl:e=Dc,languageSelector:r,showLanguageSelector:s=!0,isGlobal:n=!1,readMoreReviewsHref:i,supabaseUrl:a,supabaseAnonKey:o,googleMapsApiKey:l,supabase:u,resolvePlace:d,onResult:h,onError:p,renderPujaCard:m,isLoadingPujas:g=!1,renderKundali:y,kundaliSectionId:_="kundali-chart-section",analytics:b,getFirstPujaInfo:k,onBookPujaClick:S,imageComponent:O=lt}){const R=w.useMemo(()=>{if(u)return u;if(a&&o)try{return Fn(a,o)}catch{return null}return null},[u,a,o]),M=O,E=ys(),$=E?.t??(N=>N),L=E?.locale??"en",$e=E?.setLocale,ge=L.toLowerCase().startsWith("hi"),Oe=w.useRef(null),ee=w.useRef(null),[te,he]=w.useState(!1),[tt,Ce]=w.useState(!1),[re,fe]=w.useState(null),[Se,Q]=w.useState(null),[v,F]=w.useState(void 0),[z,H]=w.useState(!1),[V,B]=w.useState([]),[U,J]=w.useState(!1),[se,me]=w.useState(null),le=w.useRef(!1);w.useEffect(()=>{le.current||(le.current=!0,b?.trackDoshaCalculatorWebView?.())},[]);const Ee=!m||!k;w.useEffect(()=>{if(!Ee||!R)return;let N=!0;return J(!0),Ql(R).then(ne=>{N&&B(ne)}).finally(()=>{N&&J(!1)}),()=>{N=!1}},[Ee,R]);const qt=w.useCallback(N=>{const ne=Wn(V,N);return ne?c.jsx(li,{puja:ne,doshaType:N,language:L,imageComponent:O,analytics:b}):null},[V,L,O,b]),We=w.useCallback(N=>{const ne=Wn(V,N);return ne?{name:ps(ne,L),price:ne.individual_pack_price_inr,link:gs(ne,L)}:null},[V,L]),Le=m??qt,Et=k??We,jt=g||!m&&U,[ct,cr]=w.useState(()=>{const N=typeof window<"u"?Wr():null;return ui(N,L)}),[A,I]=w.useState(()=>{if(typeof window>"u")return"generic";const N=Wr();return N&&N.toLowerCase().includes("marriage")?"marriage":"generic"});w.useEffect(()=>{const N=Wr(),ne=ui(N,L);cr(ne);let xe="generic";N&&N.toLowerCase().includes("marriage")&&(xe="marriage"),I(xe)},[L]);const[ae,Qe]=w.useState(!1);w.useEffect(()=>{const N=Wr();N&&N.toLowerCase().includes("what-you")&&Qe(!0)},[]);const pt=()=>{Oe.current?.scrollIntoView({behavior:"smooth"})},_e=w.useCallback(N=>{b?.trackDoshaSectionImpression?.({section:N,timestamp:new Date().toISOString()})},[b]),ce=(N,ne)=>{if(fe(N),Q(ne??null),H(!1),N.summary){const xe=N.summary,Te=_s(xe);if(Te){const ye=di(Te).map(dr=>Et(dr)).find(Boolean)??null;me(ye)}else me(null)}else me(null);h?.(N,ne)};w.useEffect(()=>{if(k||!re?.summary)return;const N=_s(re.summary);if(!N){me(null);return}const ne=di(N).map(xe=>We(xe)).find(Boolean)??null;me(ne)},[We,k,re]);const je=()=>{H(!0),window.scrollTo({top:0,behavior:"smooth"})},He=()=>{if(re&&!z&&se){if(se.link){const N=fi(se.link);b?.trackDoshaCalculatorResultBookCtaClicked?.({position:"floating_cta",url:N,isOldDosha:!1})}if(S)S();else if(se.link){const N=fi(se.link);window.open(N,"_blank","noopener,noreferrer")}return}console.log("supabase",R),console.log("resolvePlaceProp",d),console.log("isFormComplete",te),console.log("formSubmitRef.current",ee.current),R&&ee.current?(b?.trackFloatingCtaClicked?.(te?gr.all_fields_filled:gr.fields_not_filled),te||pt(),ee.current.submit()):(b?.trackFloatingCtaClicked?.(gr.fields_not_filled),pt())},ur=s&&!n?c.jsxs("button",{type:"button",onClick:()=>{$e&&$e(ge?"en":"hi")},"aria-label":ge?"Switch to English":"हिंदी में बदलें",className:"flex items-center justify-center gap-1.5 py-2 rounded-lg text-white text-sm font-medium hover:opacity-90 transition-colors",style:{backgroundColor:"#E13A44",borderRadius:"8px",width:"100px"},disabled:!$e,children:[c.jsx(M,{src:Uc,alt:"",className:"w-5 h-5 brightness-0 invert",width:20,height:20,loading:"lazy"}),c.jsx("span",{children:ge?"English":"हिंदी"})]}):null;return c.jsxs("div",{className:t,children:[c.jsx(q.PageHeader,{t:$,logoUrl:e,languageSelector:ur,showLanguageSelector:s}),c.jsx(q.MarqueeStrip,{children:c.jsx(Bc,{t:$})}),!re&&c.jsx(ht,{section:"banner",onImpression:_e,children:c.jsx(gc,{bannerConfig:ct,imageComponent:O})}),c.jsx("main",{className:"pb-28",children:re?c.jsx(ht,{section:"result",onImpression:_e,children:c.jsx(w.Suspense,{fallback:c.jsxs("div",{className:"container mx-auto px-4 py-8 space-y-4",children:[c.jsx(Kt,{className:"h-12 w-3/4 mx-auto"}),c.jsx(Kt,{className:"h-32 w-full"}),c.jsx(Kt,{className:"h-48 w-full"}),c.jsx(Kt,{className:"h-48 w-full"})]}),children:c.jsx(Ic,{result:re,t:$,onEdit:z?void 0:je,inlineEditForm:z?c.jsx(ws,{ref:ee,t:$,initialValues:v,onValuesChange:F,onFormValidityChange:he,supabase:R??void 0,resolvePlace:d,googleMapsApiKey:l,onResult:ce,onError:p,onLoadingChange:Ce,analytics:b}):void 0,renderPujaCard:Le,isLoadingPujas:jt,renderKundali:y,kundaliSectionId:_,birthDetails:Se,supabase:R,language:E?.locale??"en",readMoreReviewsHref:i,analytics:b,problemArea:(()=>{const N=v?.problems||[],ne=N.filter(Te=>Te!=="formProblemOther").map(Te=>$(Te)).filter(Boolean),xe=v?.otherProblemText?.trim();return N.includes("formProblemOther")&&xe&&ne.push(xe),ne.join(", ")})(),problemAreaIds:v?.problems||[],customProblemText:v?.otherProblemText||""})})}):c.jsxs(c.Fragment,{children:[ae&&c.jsx(ht,{section:"what_from_analysis",onImpression:_e,children:c.jsx(ci,{t:$,bannerType:A})}),c.jsx(ht,{section:"form",onImpression:_e,children:c.jsx("div",{ref:Oe,children:c.jsx(ws,{ref:ee,t:$,initialValues:v,onValuesChange:F,onFormValidityChange:he,supabase:R??void 0,resolvePlace:d,googleMapsApiKey:l,onResult:ce,onError:p,onLoadingChange:Ce,analytics:b})})}),!ae&&c.jsx(ht,{section:"what_from_analysis",onImpression:_e,children:c.jsx(ci,{t:$,bannerType:A})}),c.jsx(ht,{section:"user_reviews",onImpression:_e,children:c.jsx(q.UserReviewsSection,{t:N=>{if(A==="marriage"){if(N==="feedbackTitle")return $("feedbackTitleMarriage");if(N.startsWith("feedbackTestimonial")){const xe=`feedbackTestimonialMarriage${N.replace("feedbackTestimonial","")}`,Te=$(xe);return Te===xe?$(N):Te}}return $(N)},readMoreHref:i,onReadMore:b?.trackReadMoreReviewsClicked?()=>b.trackReadMoreReviewsClicked():void 0})}),c.jsx(ht,{section:"faq",onImpression:_e,children:c.jsx(q.FAQAccordion,{t:$,items:A==="marriage"?Kc:Fc,defaultOpenIndex:0,onItemOpen:N=>b?.trackFaqQuestionClicked?.(N)})}),c.jsx(ht,{section:"contact",onImpression:_e,children:c.jsx(q.ContactUsSection,{title:$("contactTitle"),brandName:$("contactBrandName"),whatsAppLine:$("contactWhatsAppDomestic"),emailLine:$("contactEmail")})})]})}),!(re&&!z&&_s(re.summary)===null)&&c.jsxs(q.FooterShell,{children:[!(re&&!z&&se)&&c.jsx(ac,{}),c.jsx(pc,{isFormComplete:te,onPress:He,labelDefault:$("formCta"),labelFilled:$("formCtaCalculate"),loadingLabel:$("calculating"),isLoading:tt,mode:re&&!z&&se?"book-puja":"form",firstPuja:se||void 0,showingResults:!!re&&!z,bookPujaLabel:$("bookPuja")})]})]})}const oe={section:"_section_ji9so_1",heading:"_heading_ji9so_6",headingSuccess:"_headingSuccess_ji9so_13",card:"_card_ji9so_17",cardPresent:"_cardPresent_ji9so_25",cardAbsent:"_cardAbsent_ji9so_29",cardHeader:"_cardHeader_ji9so_33",doshaName:"_doshaName_ji9so_41",badge:"_badge_ji9so_46",badgePresent:"_badgePresent_ji9so_53",badgeAbsent:"_badgeAbsent_ji9so_58",badgeInactive:"_badgeInactive_ji9so_63",body:"_body_ji9so_68",bodyLabel:"_bodyLabel_ji9so_75",noDoshas:"_noDoshas_ji9so_81",noDoshasDesc:"_noDoshasDesc_ji9so_88",editBtn:"_editBtn_ji9so_94",accordionContent:"_accordionContent_ji9so_128"},Wc=[{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 lr(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function Hc(t,e){if(Array.isArray(t))return t.find(s=>(s.name??s.type)===e);if(t&&typeof t=="object"&&e in t){const r=t[e];if(!r)return;const s=typeof r.remedies=="string"?r.remedies:Array.isArray(r.remedies)?r.remedies.join(`
|
|
153
|
-
`):void 0;return{explanation:r.explanation,remedies:s}}}function
|
|
152
|
+
नवग्रह मंदिरों में जाएं`,ctaKundliCreated:"3L+ कुंडली रिपोर्ट बनाई।",ctaCertified:"BHU प्रमाणित ज्योतिषी।",ctaSecurePayment:"सुरक्षित भुगतान।",contactTitle:"संपर्क करें",contactBrandName:"श्री मंदिर",contactWhatsAppGlobal:"व्हाट्सएप: 8296947757",contactWhatsAppDomestic:"व्हाट्सएप: 08071174417",contactEmail:"ईमेल: pujaseva@appsforbharat.com",whatFromAnalysisTitle:"इस विश्लेषण से आपको क्या मिलेगा",whatFromAnalysisMarriage1Title:"शादी पर प्रभाव जानें",whatFromAnalysisMarriage1Desc:"क्या शादी में देरी होगी, कोई समस्या आएगी या मैच सही रहेगा।",whatFromAnalysisMarriage2Title:"मंगल दोष की पुष्टि",whatFromAnalysisMarriage2Desc:"जानें कि मंगल दोष है या नहीं और वह कितना मजबूत है।",whatFromAnalysisMarriage3Title:"उपाय और पूजा की जानकारी",whatFromAnalysisMarriage3Desc:"कौन सा उपाय या पूजा आपके लिए सही रहेगा।",whatFromAnalysisGeneric1Title:"जीवन पर प्रभाव का संक्षेप",whatFromAnalysisGeneric1Desc:"शादी, करियर, पैसे, सेहत और पढ़ाई में होने वाली देरी, परेशानी या अवसरों को समझें",whatFromAnalysisGeneric2Title:"दोष की पुष्टि",whatFromAnalysisGeneric2Desc:"जानें कि कोई दोष या ग्रहों का असंतुलन आपकी प्रगति को प्रभावित कर रहा है या नहीं",whatFromAnalysisGeneric3Title:"उपाय की दिशा",whatFromAnalysisGeneric3Desc:"कौन सा उपाय या पूजा आपके लिए सही रहेगा।"}},Qn=w.createContext(null);function Xn(){return typeof window>"u"?"en":window.location.pathname.split("/").filter(Boolean)[0]==="hi"?"hi":"en"}function Zl(t){const{pathname:e,search:r,hash:s}=window.location,n=e.split("/").filter(Boolean);n[0]==="en"||n[0]==="hi"?n[0]=t:n.unshift(t),window.location.href="/"+n.join("/")+r+s}function ec({locale:t,onLocaleChange:e,children:r}){const[s,n]=w.useState(()=>t||Xn());w.useEffect(()=>{if(t)n(t);else{const o=()=>n(Xn());return window.addEventListener("popstate",o),()=>window.removeEventListener("popstate",o)}},[t]);const i=o=>{e?e(o):Zl(o)},a=w.useMemo(()=>o=>Yn[s]?.[o]??o,[s]);return c.jsx(Qn.Provider,{value:{locale:s,setLocale:i,t:a},children:r})}function ys(){return w.useContext(Qn)}function tc(){const e=ys()?.locale==="hi";return c.jsx("div",{className:Yl.container,children:e?"100% सटीक • सुरक्षित • 30 लाख+ परिवारों द्वारा विश्वसनीय":"100% Accurate • Secure • Trusted by 30L+ families"})}const Fe=t=>({width:t,height:t});function bs(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"}),c.jsx("path",{d:"M12 9v4"}),c.jsx("path",{d:"M12 17h.01"})]})}function Zn(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),c.jsx("path",{d:"m9 11 3 3L22 4"})]})}function Ur(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("path",{d:"M12 16v-4"}),c.jsx("path",{d:"M12 8h.01"})]})}function rc(t){const{size:e=24,...r}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:c.jsx("path",{d:"M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"})})}function sc(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"M2 6c.6.5 1.2 1 2.5 1C7 7 7 5 9.5 5c2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"}),c.jsx("path",{d:"M2 12c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"}),c.jsx("path",{d:"M2 18c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"})]})}function nc(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function ic(t){const{size:e=24,...r}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:c.jsx("path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"})})}function ac(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"m5 12 7-7 7 7"}),c.jsx("path",{d:"M12 19V5"})]})}function ei(t){const{size:e=24,...r}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:c.jsx("path",{d:"m6 9 6 6 6-6"})})}function vs(t){const{size:e=24,className:r="",...s}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`animate-spin ${r}`,style:{animation:"spin 1s linear infinite"},...Fe(e),...s,children:c.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})}function oc(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("line",{x1:"10",x2:"21",y1:"14",y2:"3"})]})}function lc(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Fe(e),...r,children:[c.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),c.jsx("path",{d:"M3 3v5h5"})]})}const Ke={ctaFilled:"_ctaFilled_8nukz_2",ctaFilledContent:"_ctaFilledContent_8nukz_7",chevronRight:"_chevronRight_8nukz_14",bookPujaButton:"_bookPujaButton_8nukz_21",bookPujaContent:"_bookPujaContent_8nukz_27",pujaInfo:"_pujaInfo_8nukz_36",pujaName:"_pujaName_8nukz_44",pujaPrice:"_pujaPrice_8nukz_57",priceLabel:"_priceLabel_8nukz_64",priceAmount:"_priceAmount_8nukz_68",bookButton:"_bookButton_8nukz_74"},lt=t=>{const{priority:e,fetchPriority:r,width:s,height:n,...i}=t;return w.createElement("img",{...i,width:s??1,height:n??1,decoding:"async",loading:i.loading??(e?"eager":"lazy"),...r&&{fetchPriority:r}})},cc="https://srm-cdn.a4b.io/yoda/1771588545907.svg";function uc({isFormComplete:t,onPress:e,labelDefault:r,labelFilled:s,isLoading:n=!1,mode:i="form",firstPuja:a,showingResults:o=!1,bookPujaLabel:l="Book Puja",loadingLabel:u="Calculating..."}){return i==="book-puja"&&a&&o?c.jsx(q.FooterCTAButton,{onClick:e,disabled:n,className:Ke.bookPujaButton,children:c.jsxs("div",{className:Ke.bookPujaContent,children:[c.jsxs("div",{className:Ke.pujaInfo,children:[c.jsx("span",{className:Ke.pujaName,children:a.name}),a.price>0&&c.jsxs("div",{className:Ke.pujaPrice,children:[c.jsx("span",{className:Ke.priceLabel,children:"Starting from "}),c.jsxs("span",{className:Ke.priceAmount,children:["₹",a.price]})]})]}),c.jsxs("span",{className:Ke.bookButton,children:[l," →"]})]})}):c.jsx(q.FooterCTAButton,{onClick:e,disabled:n,className:t?Ke.ctaFilled:void 0,children:n?c.jsxs("span",{className:Ke.ctaFilledContent,children:[c.jsx(vs,{className:"w-5 h-5 animate-spin"}),u]}):t?c.jsxs("span",{className:Ke.ctaFilledContent,children:[s,c.jsx(lt,{src:cc,alt:"",className:Ke.chevronRight,width:20,height:20,loading:"lazy"})]}):r})}const Br={bannerContainer:"_bannerContainer_1s29r_1",bannerImage:"_bannerImage_1s29r_13",ticker:"_ticker_1s29r_20",tickerContent:"_tickerContent_1s29r_30"};function dc({bannerConfig:t,className:e="",imageComponent:r=lt}){const s=r;return c.jsxs("section",{className:`${Br.bannerContainer} ${e}`,children:[c.jsx(s,{src:t.imageUrl,alt:t.alt,className:Br.bannerImage,loading:"eager",priority:!0,fetchPriority:"high"}),c.jsx("div",{className:Br.ticker,children:c.jsx("div",{className:Br.tickerContent,children:t.tickerText})})]})}const hc=112;function ht({section:t,children:e,onImpression:r}){const s=w.useRef(null),n=w.useRef(!1);return w.useEffect(()=>{const i=s.current;if(!i)return;const a=new IntersectionObserver(([o])=>{!o?.isIntersecting||n.current||(n.current=!0,r(t))},{threshold:.1,rootMargin:`0px 0px -${hc}px 0px`});return a.observe(i),()=>a.disconnect()},[t,r]),c.jsx("div",{ref:s,children:e})}const Bt={wrap:"_wrap_1mrzx_1",input:"_input_1mrzx_6",iconBtn:"_iconBtn_1mrzx_35",iconImg:"_iconImg_1mrzx_49",placeholder:"_placeholder_1mrzx_53",dateDisplay:"_dateDisplay_1mrzx_65"},fc="https://srm-cdn.a4b.io/yoda/1770372045894.svg",mc=t=>{if(!t)return"";const[e,r,s]=t.split("-");return`${s}/${r}/${e}`};function pc({id:t,value:e,onChange:r,onOpen:s,className:n=""}){const i=w.useRef(null),a=w.useMemo(()=>{const l=new Date,u=d=>String(d).padStart(2,"0");return`${l.getFullYear()}-${u(l.getMonth()+1)}-${u(l.getDate())}`},[]),o=()=>{s?.();const l=i.current;if(l&&typeof l.showPicker=="function")try{l.showPicker()}catch{l?.focus()}else l?.focus()};return c.jsxs("div",{className:`${Bt.wrap} ${n}`,children:[!e&&c.jsx("span",{className:Bt.placeholder,children:"Select Date of Birth"}),e&&c.jsx("div",{className:Bt.dateDisplay,children:mc(e)}),c.jsx("input",{ref:i,id:t,type:"date",className:Bt.input,value:e,max:a,onChange:l=>{const u=l.target.value,d=new Date,h=m=>String(m).padStart(2,"0"),p=`${d.getFullYear()}-${h(d.getMonth()+1)}-${h(d.getDate())}`;u&&u>p||r(u)},onClick:o,onFocus:o}),c.jsx("button",{type:"button",className:Bt.iconBtn,"aria-label":"Open date picker",onMouseDown:l=>l.preventDefault(),onClick:l=>{l.preventDefault(),l.stopPropagation(),o()},children:c.jsx(lt,{className:Bt.iconImg,src:fc,alt:"",width:22,height:22,loading:"lazy"})})]})}const ve={wrap:"_wrap_spo2g_1",input:"_input_spo2g_6",iconBtn:"_iconBtn_spo2g_24",iconImg:"_iconImg_spo2g_38",timePopover:"_timePopover_spo2g_42",timePickerRow:"_timePickerRow_spo2g_58",timePickerSelect:"_timePickerSelect_spo2g_64",timePickerColon:"_timePickerColon_spo2g_80",meridiemToggle:"_meridiemToggle_spo2g_88",meridiemBtn:"_meridiemBtn_spo2g_97",meridiemActive:"_meridiemActive_spo2g_112",timePopoverActions:"_timePopoverActions_spo2g_117",timePopoverBtn:"_timePopoverBtn_spo2g_123",timePopoverOk:"_timePopoverOk_spo2g_142"},gc="https://srm-cdn.a4b.io/yoda/1770372014782.svg",ti=t=>String(t).padStart(2,"0");function yc(t){const e=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(t);if(!e)return t;const r=Number(e[1]),s=e[2],n=r>=12?"PM":"AM";return`${r%12===0?12:r%12}:${s} ${n}`}function bc(t){const e=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(t);if(!e)return{hour12:12,minute:"00",meridiem:"AM"};const r=Number(e[1]),s=e[2],n=r>=12?"PM":"AM";return{hour12:r%12===0?12:r%12,minute:s,meridiem:n}}function vc(t){const e=Math.min(12,Math.max(1,t.hour12)),r=/^([0-5]\d)$/.test(t.minute)?t.minute:"00";let s=e%12;return t.meridiem==="PM"&&(s+=12),`${ti(s)}:${r}`}function wc({id:t,value:e,onChange:r,onOpen:s,placeholder:n="Exact Time of Birth",disabled:i=!1,className:a=""}){const o=w.useRef(null),[l,u]=w.useState(!1),[d,h]=w.useState({hour12:12,minute:"00",meridiem:"AM"});w.useEffect(()=>{const g=y=>{o.current&&(o.current.contains(y.target)||u(!1))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[]);const p=()=>{i||(s?.(),h(bc(e||"12:00")),u(g=>!g))},m=()=>{const g=vc(d);r(g),u(!1)};return c.jsxs("div",{className:`${ve.wrap} ${a}`,ref:o,children:[c.jsx("input",{id:t,className:ve.input,type:"text",value:e?yc(e):"",readOnly:!0,disabled:i,placeholder:n,onClick:p}),c.jsx("button",{type:"button",className:ve.iconBtn,"aria-label":"Open time picker",disabled:i,onMouseDown:g=>g.preventDefault(),onClick:g=>{g.preventDefault(),g.stopPropagation(),p()},children:c.jsx(lt,{className:ve.iconImg,src:gc,alt:"",width:22,height:22,loading:"lazy"})}),l&&!i&&c.jsxs("div",{className:ve.timePopover,role:"dialog","aria-label":"Select time",children:[c.jsxs("div",{className:ve.timePickerRow,children:[c.jsx("select",{className:ve.timePickerSelect,value:d.hour12,onChange:g=>h(y=>({...y,hour12:Number(g.target.value)})),"aria-label":"Hour",children:Array.from({length:12},(g,y)=>y+1).map(g=>c.jsx("option",{value:g,children:g},g))}),c.jsx("span",{className:ve.timePickerColon,children:":"}),c.jsx("select",{className:ve.timePickerSelect,value:d.minute,onChange:g=>h(y=>({...y,minute:g.target.value})),"aria-label":"Minute",children:Array.from({length:60},(g,y)=>ti(y)).map(g=>c.jsx("option",{value:g,children:g},g))}),c.jsxs("div",{className:ve.meridiemToggle,"aria-label":"AM/PM",children:[c.jsx("button",{type:"button",className:`${ve.meridiemBtn} ${d.meridiem==="AM"?ve.meridiemActive:""}`,onClick:()=>h(g=>({...g,meridiem:"AM"})),children:"AM"}),c.jsx("button",{type:"button",className:`${ve.meridiemBtn} ${d.meridiem==="PM"?ve.meridiemActive:""}`,onClick:()=>h(g=>({...g,meridiem:"PM"})),children:"PM"})]})]}),c.jsxs("div",{className:ve.timePopoverActions,children:[c.jsx("button",{type:"button",className:ve.timePopoverBtn,onClick:()=>u(!1),children:"Cancel"}),c.jsx("button",{type:"button",className:`${ve.timePopoverBtn} ${ve.timePopoverOk}`,onClick:m,"aria-label":"OK",children:c.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:c.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})]})}async function ri(t,e){const{visitorId:r,sessionId:s,problemStatements:n,language:i}=e;if(n.length!==0)try{await t.from("session_problem_statements").insert({visitor_id:r,session_id:s,problem_statements:n,language:i??"en"})}catch{}}async function si(t,e,r){const{data:s,error:n}=await t.functions.invoke("calculate-dosha",{body:e,headers:r??{}});return n?{success:!1,error:n.message||"Calculation failed"}:s&&typeof s=="object"&&"success"in s?s.success===!0?s:{success:!1,error:s.error??"Unknown error",details:s.details}:{success:!1,error:"Invalid response from server"}}async function ni(t,e,r={}){const{visitorId:s="unknown",sessionId:n="unknown",trackProblemStatements:i=!0,problemStatements:a=[],language:o="en"}=r;return i&&a.length>0&&await ri(t,{visitorId:s,sessionId:n,problemStatements:a,language:o}),si(t,e,{"x-visitor-id":s,"x-session-id":n})}let Fr=null;const _c=(t,e)=>typeof window>"u"||window.google?.maps?.places?Promise.resolve():Fr||(Fr=new Promise((r,s)=>{const n=document.querySelector('script[data-google-maps-places="true"]');if(n){const o=Date.now(),l=()=>{if(window.google?.maps?.places){r();return}if(Date.now()-o>5e3){s(new Error("Google Maps script present but Places library did not become available."));return}window.setTimeout(l,50)};n.getAttribute("src")?l():(n.addEventListener("load",()=>l()),n.addEventListener("error",()=>s(new Error("Failed to load Google Maps API"))));return}const i=document.createElement("script"),a=new URL("https://maps.googleapis.com/maps/api/js");a.searchParams.set("key",t),a.searchParams.set("libraries","places"),a.searchParams.set("loading","async"),e&&a.searchParams.set("language",e),i.src=a.toString(),i.async=!0,i.defer=!0,i.setAttribute("data-google-maps-places","true"),i.onload=()=>{const o=Date.now(),l=()=>{if(window.google?.maps?.places){r();return}if(Date.now()-o>2e3){s(new Error("Google Maps loaded but Places library is unavailable. Check API key restrictions / enabled APIs."));return}window.setTimeout(l,50)};l()},i.onerror=()=>s(new Error("Failed to load Google Maps API")),document.head.appendChild(i)}),Fr),ii=(t={})=>{const{apiKey:e,language:r="en",restrictCountry:s}=t,[n,i]=w.useState(!1),[a,o]=w.useState([]),[l,u]=w.useState(!1),[d,h]=w.useState(null),p=w.useRef(null),m=w.useRef(null),g=w.useRef(null);w.useEffect(()=>{if(!e){i(!1),h(null);return}_c(e,r).then(()=>{try{p.current=new google.maps.places.AutocompleteService;const _=document.createElement("div");m.current=new google.maps.places.PlacesService(_),g.current=new google.maps.places.AutocompleteSessionToken,i(!0),h(null)}catch(_){i(!1),h(_ instanceof Error?_.message:"Failed to create Places services")}}).catch(_=>{i(!1),h(_ instanceof Error?_.message:"Failed to load location service")})},[e,r]);const y=w.useCallback(async _=>{if(!_||_.length<2||!p.current){o([]);return}u(!0);try{const k={input:_,types:["(cities)"],sessionToken:g.current??void 0};s&&(k.componentRestrictions={country:s});const O=await new Promise((R,M)=>{p.current.getPlacePredictions(k,(E,$)=>{$===google.maps.places.PlacesServiceStatus.OK&&E?R(E):$===google.maps.places.PlacesServiceStatus.ZERO_RESULTS?R([]):M(new Error(`Places API error: ${$}`))})});o(O.map(R=>({place_id:R.place_id,description:R.description,structured_formatting:{main_text:R.structured_formatting?.main_text||R.description,secondary_text:R.structured_formatting?.secondary_text||""}})))}catch{o([])}finally{u(!1)}},[s]),x=w.useCallback(async _=>{if(!m.current)return null;try{const k=await new Promise((L,$e)=>{m.current.getDetails({placeId:_,fields:["geometry","address_components","formatted_address"],sessionToken:g.current??void 0},(ge,Oe)=>{Oe===google.maps.places.PlacesServiceStatus.OK&&ge?L(ge):$e(new Error(`Place details error: ${Oe}`))})});g.current=new google.maps.places.AutocompleteSessionToken;const O=k.geometry?.location?.lat()||0,R=k.geometry?.location?.lng()||0;let M="",E="",$="";return k.address_components?.forEach(L=>{L.types.includes("locality")&&(M=L.long_name),L.types.includes("administrative_area_level_1")&&(E=L.long_name),L.types.includes("country")&&($=L.long_name)}),{display_name:k.formatted_address||"",lat:O,lng:R,city:M,state:E,country:$}}catch{return null}},[]),v=w.useCallback(()=>o([]),[]);return{isLoaded:n,predictions:a,isSearching:l,loadError:d,searchPlaces:y,getPlaceDetails:x,clearPredictions:v}},kc=["formProblemMarriage","formProblemMoney","formProblemHealth","formProblemEducation","formProblemCareer","formProblemOther"];function Sc(){try{const t="analytics_visitor_id";let e=typeof localStorage<"u"?localStorage.getItem(t):null;if(!e){e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`;try{localStorage.setItem(t,e)}catch{}}return e??"unknown"}catch{return"unknown"}}function xc(){try{const t="analytics_session_id";let e=typeof localStorage<"u"?localStorage.getItem(t):null;if(!e){e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`;try{localStorage.setItem(t,e)}catch{}}return e??"unknown"}catch{return"unknown"}}function Tc(t){if(!t)return 0;const e=new Date(t);if(Number.isNaN(e.getTime()))return 0;const r=new Date;let s=r.getFullYear()-e.getFullYear();const n=r.getMonth()-e.getMonth();return(n<0||n===0&&r.getDate()<e.getDate())&&s--,s}const ws=w.forwardRef(function({t:e,className:r="",initialValues:s,onValuesChange:n,onFormValidityChange:i,supabase:a,resolvePlace:o,onResult:l,onError:u,onLoadingChange:d,analytics:h,googleMapsApiKey:p},m){const g=A=>A.replace(/[^a-zA-Z\u0900-\u097F\s]/g,"").replace(/\s{2,}/g," "),[y,x]=w.useState(s?.name??""),[v,_]=w.useState(s?.gender??""),[k,O]=w.useState(s?.problems??[]),[R,M]=w.useState(s?.dateOfBirth??""),[E,$]=w.useState(s?.birthTime??""),[L,$e]=w.useState(s?.birthTimeUnknown??!1),[ge,Oe]=w.useState(s?.birthPlace??""),[ee,te]=w.useState(s?.otherProblemText??""),[he,tt]=w.useState(null),[Ce,re]=w.useState(!1),[fe,Se]=w.useState(null),[Q,b]=w.useState({}),F=w.useCallback(A=>{const I=ae=>{const Qe=document.getElementById(ae);return Qe?(Qe.focus(),Qe.scrollIntoView({behavior:"smooth",block:"center"}),!0):!1};if(A==="name"){I("dosha-name");return}if(A==="gender"){const ae=document.querySelector('[role="group"][aria-labelledby="dosha-gender-label"] button');ae&&(ae.focus(),ae.scrollIntoView({behavior:"smooth",block:"center"}));return}if(A==="dateOfBirth"){I("dosha-dob");return}if(A==="birthTime"){I("dosha-time");return}A==="birthPlace"&&I("dosha-place")},[]),z=w.useRef(!1),H=w.useRef(!1),V=w.useRef(!1),B=w.useRef(!1),U=w.useRef(!1),J=w.useRef(null),{predictions:se,isSearching:me,loadError:le,searchPlaces:Ee,getPlaceDetails:Kt,clearPredictions:We}=ii({apiKey:p,language:"en"}),Le=w.useCallback(()=>{z.current||(z.current=!0,h?.trackFormFillInitiated?.())},[h]);w.useEffect(()=>{const A=I=>{J.current&&(J.current.contains(I.target)||re(!1))};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[]),w.useEffect(()=>{if(!Ce)return;if(ge.length<2){We();return}const A=window.setTimeout(async()=>{await Ee(ge)},300);return()=>window.clearTimeout(A)},[ge,We,Ce,Ee]);const Tt=y.trim()!==""&&(v==="male"||v==="female")&&R!==""&&(E!==""||L)&&ge.trim()!=="";w.useEffect(()=>{i?.(Tt)},[Tt,i]),w.useEffect(()=>{n?.({name:y,gender:v,problems:k,otherProblemText:ee,dateOfBirth:R,birthTime:E,birthTimeUnknown:L,birthPlace:ge})},[y,v,k,ee,R,E,L,ge,n]),w.useEffect(()=>{!k.includes("formProblemOther")&&ee&&te("")},[k,ee]);const Et=w.useCallback(async(A,I)=>{if(!p)return"UTC";try{const ae=Math.floor(Date.now()/1e3),Qe=`https://maps.googleapis.com/maps/api/timezone/json?location=${A},${I}×tamp=${ae}&key=${p}`,_e=await(await fetch(Qe)).json();return _e.status==="OK"&&_e.timeZoneId?_e.timeZoneId:"UTC"}catch{return"UTC"}},[p]),ct=w.useCallback(async()=>{const A=(ce,je,He=!1)=>{je&&(b(Me=>({...Me,[je]:ce})),F(je)),Se(He?ce:null),u?.(ce)};if(b({}),Se(null),!a){A(e("calculationError"));return}if(!y.trim()){A(e("formNameRequired"),"name");return}if(v!=="male"&&v!=="female"){A(e("formGenderRequired"),"gender");return}if(!R){A(e("formDobRequired"),"dateOfBirth");return}if(!L&&!E){A(e("formTimeRequired"),"birthTime");return}const I=ge.trim();if(!I){A(e("formPlaceRequired"),"birthPlace");return}const ae=g(I).trim();if(!ae){A(e("formPlaceRequired"),"birthPlace");return}const Qe=Tc(R),pt=new Set(["formProblemMarriage","formProblemMoney","formProblemCareer","formProblemBusiness","marriage","financial","career","business"]),_e=k.some(ce=>pt.has(ce));if(Qe<18&&_e){A(e("formAgeMarriageRestriction"),void 0,!0);return}if(!he&&!o){A(e("formPlaceSelectFromDropdown"),"birthPlace");return}d?.(!0);try{let ce,je,He;if(he)ce=he.lat,je=he.lon,he.tz?He=he.tz:(He=await Et(ce,je),tt({...he,tz:He}));else if(o){const ye=await o(I);if(!ye){A(e("locationError")),d?.(!1);return}ce=ye.lat,je=ye.lon,He=ye.tz}else{A(e("formPlaceSelectFromDropdown"),"birthPlace"),d?.(!1);return}const Me={problemAreaValues:[...k.filter(ye=>ye!=="formProblemOther").map(ye=>e(ye)).filter(Boolean),...k.includes("formProblemOther")&&ee.trim()?[ee.trim()]:[]],name:y.trim(),gender:v==="male"?"M":"F",date:R,time:L?"":E||"12:00",unknownTime:L,tz:He||"UTC",lat:ce,lon:je,place:ae,problemArea:void 0};Me.problemArea=Me.problemAreaValues.length>0?Me.problemAreaValues.join(", "):void 0;const cr=Sc(),N=xc(),ne=Me.problemAreaValues,xe=typeof navigator<"u"&&navigator.language?.toLowerCase().startsWith("hi")?"hi":"en",Te=await ni(a,Me,{visitorId:cr,sessionId:N,trackProblemStatements:!0,problemStatements:ne,language:xe});if(Te.success){Se(null);const[ye,ur,dr]=(Me.date||"").split("-").map(Number),zr=Me.time||"12:00",[gt,hr]=zr.split(":").map(Jr=>parseInt(Jr,10)||0);l?.(Te,{day:dr||1,month:ur||1,year:ye||2e3,hour:gt,minute:hr,lat:ce,lon:je,tzone:5.5})}else{let ye=Te.error??e("calculationError");(ye.includes("Expected 'M' | 'F'")||ye.includes("gender"))&&(ye=e("formGenderRequired")),A(ye)}}catch(ce){const je=ce instanceof Error?ce.message:String(ce);A(je)}finally{d?.(!1)}},[a,o,he,ge,y,v,R,E,L,k,e,u,d,h,l,Et,F]);w.useImperativeHandle(m,()=>({submit:ct}),[ct]);const lr=kc.map(A=>({key:A,label:e(A)}));return c.jsxs(q.FormContainer,{className:r,"aria-label":e("formTitle"),children:[c.jsx(q.PrivacyBanner,{text:e("formPrivacyBanner")}),c.jsx(q.FormSectionHeader,{title:e("formTitle"),subtitle:e("formSubtitle")}),c.jsx("div",{onFocusCapture:()=>{Le(),h?.trackNameSectionClicked?.()},children:c.jsxs(q.FormField,{id:"dosha-name",label:e("formNameLabel"),required:!0,children:[c.jsx(q.FormTextInput,{id:"dosha-name",value:y,onChange:A=>{const I=A.target.value;I&&!H.current&&(H.current=!0,h?.trackNameSectionFilled?.()),x(I),Q.name&&b(ae=>({...ae,name:void 0})),fe&&Se(null)},placeholder:e("formNamePlaceholder"),autoComplete:"name"}),Q.name&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.name})]})}),c.jsxs(q.FormField,{id:"dosha-gender",label:e("formGenderLabel"),required:!0,children:[c.jsx(q.FormSegmentedControl,{id:"dosha-gender",options:[{value:"male",label:e("formGenderMale")},{value:"female",label:e("formGenderFemale")}],value:v,onChange:A=>{_(A),Q.gender&&b(I=>({...I,gender:void 0})),fe&&Se(null)}}),Q.gender&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.gender})]}),c.jsxs(q.FormField,{id:"dosha-problems",label:e("formProblemLabel"),children:[c.jsx(q.FormTagPills,{id:"dosha-problems",options:lr,selected:k,onChange:A=>{O(A),A.includes("formProblemOther")||te("")}}),k.includes("formProblemOther")&&c.jsxs("div",{style:{marginTop:"8px"},children:[c.jsx(q.FormTextInput,{id:"dosha-problem-other",value:ee,onChange:A=>{const I=A.target.value.slice(0,100);te(I)},placeholder:e("formProblemOtherPlaceholder")}),c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#8f6e56"},children:e("formProblemOtherHint")})]})]}),c.jsx(q.FormField,{id:"dosha-dob",label:e("formDobLabel"),required:!0,children:c.jsxs("div",{style:{minHeight:Q.dateOfBirth?"72px":"48px",transition:"min-height 0.2s"},children:[c.jsx(pc,{id:"dosha-dob",value:R,onOpen:()=>{Le(),h?.trackDobClicked?.()},onChange:A=>{A&&!V.current&&(V.current=!0,h?.trackDobFilled?.()),M(A),Q.dateOfBirth&&b(I=>({...I,dateOfBirth:void 0})),fe&&Se(null)}}),Q.dateOfBirth&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.dateOfBirth})]})}),c.jsx(q.FormField,{id:"dosha-time",label:e("formTimeLabel"),required:!0,children:c.jsxs("div",{style:{minHeight:Q.birthTime?"72px":"48px",transition:"min-height 0.2s"},children:[c.jsx(wc,{id:"dosha-time",value:E,onOpen:()=>{Le(),h?.trackTimeClicked?.()},onChange:A=>{A&&!B.current&&(B.current=!0,h?.trackTimeFilled?.()),$(A),Q.birthTime&&b(I=>({...I,birthTime:void 0})),fe&&Se(null)},disabled:L}),Q.birthTime&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.birthTime})]})}),c.jsx(q.FormCheckboxWithHelp,{id:"dosha-time-unknown",checked:L,onChange:A=>{Le(),h?.trackTimeCheckboxClicked?.(),$e(A),A&&Q.birthTime&&b(I=>({...I,birthTime:void 0}))},primaryText:e("formTimeUnknown"),helpText:e("formTimeUnknownHelp")}),c.jsx("div",{onFocusCapture:()=>{Le(),h?.trackPlaceOfBirthClicked?.()},children:c.jsx(q.FormField,{id:"dosha-place",label:e("formPlaceLabel"),required:!0,children:c.jsxs("div",{ref:J,style:{position:"relative"},children:[c.jsx(q.FormLocationInput,{id:"dosha-place",value:ge,onChange:A=>{const I=g(A.target.value);Oe(I),tt(null),re(!0),I&&!U.current&&(U.current=!0,h?.trackPlaceOfBirthChosen?.(I)),Q.birthPlace&&b(ae=>({...ae,birthPlace:void 0})),fe&&Se(null)},onFocus:()=>re(!0),placeholder:e("formPlacePlaceholder")}),Q.birthPlace&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.birthPlace}),Ce&&se.length>0&&c.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",maxHeight:"240px",overflowY:"auto",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},role:"listbox",children:se.slice(0,8).map(A=>c.jsxs("button",{type:"button",onClick:async()=>{if(Oe(g(A.description)),Kt){const I=await Kt(A.place_id);I&&(tt({lat:I.lat,lon:I.lng}),Q.birthPlace&&b(ae=>({...ae,birthPlace:void 0})),fe&&Se(null))}We(),re(!1),U.current||(U.current=!0,h?.trackPlaceOfBirthChosen?.(A.description))},style:{width:"100%",padding:"10px 12px",textAlign:"left",border:"none",backgroundColor:"transparent",cursor:"pointer",display:"flex",flexDirection:"column",gap:"2px",outline:"none"},onMouseEnter:I=>{I.currentTarget.style.backgroundColor="rgba(247, 94, 34, 0.06)"},onMouseLeave:I=>{I.currentTarget.style.backgroundColor="transparent"},onFocus:I=>{I.currentTarget.style.backgroundColor="rgba(247, 94, 34, 0.06)"},onBlur:I=>{I.currentTarget.style.backgroundColor="transparent"},children:[c.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:"#111827"},children:A.structured_formatting?.main_text??A.description}),A.structured_formatting?.secondary_text&&c.jsx("span",{style:{fontSize:"12px",color:"#6b7280"},children:A.structured_formatting.secondary_text})]},A.place_id))}),Ce&&p&&me&&c.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,padding:"10px 12px",backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",fontSize:"12px",color:"#6b7280",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},children:"Loading…"}),Ce&&p&&!me&&le&&c.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,padding:"10px 12px",backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",fontSize:"12px",color:"#dc2626",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},children:le})]})})}),c.jsxs(q.FormFooterNote,{children:["⚡ ",e("formFooterNoteBefore"),c.jsx("strong",{children:e("formFooterNoteBold")}),e("formFooterNoteAfter")]}),fe&&c.jsxs("div",{style:{marginTop:"4px",width:"100%",borderRadius:"14px",border:"1px solid #FCA5A5",background:"#FEF2F2",padding:"16px",display:"flex",alignItems:"flex-start",gap:"10px"},role:"alert","aria-live":"assertive",children:[c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{width:"16px",height:"16px",marginTop:"2px",flexShrink:0},"aria-hidden":"true",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),c.jsx("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]}),c.jsx("p",{style:{margin:0,fontSize:"14px",lineHeight:"1.5",color:"#EF4444"},children:fe})]})]})}),Ft=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`animate-pulse rounded-md bg-muted ${t}`,...e}));Ft.displayName="Skeleton";const ft=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`rounded-lg border border-border bg-card text-card-foreground shadow-sm ${t}`,...e}));ft.displayName="Card";const kt=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`flex flex-col space-y-1.5 p-6 ${t}`,...e}));kt.displayName="CardHeader";const St=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("h3",{ref:r,className:`text-2xl font-semibold leading-none tracking-tight ${t}`,...e}));St.displayName="CardTitle";const Kr=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("p",{ref:r,className:`text-sm text-muted-foreground ${t}`,...e}));Kr.displayName="CardDescription";const xt=Ie.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`p-6 pt-0 ${t}`,...e}));xt.displayName="CardContent";const ar=Ie.forwardRef(({className:t="",size:e="default",variant:r="default",...s},n)=>{const i={default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8"},a={default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"};return c.jsx("button",{ref:n,type:"button",className:`inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 ${i[e]} ${a[r]} ${t}`,...s})});ar.displayName="Button";function ai({puja:t,doshaType:e,language:r,onBookClick:s,imageComponent:n=lt,analytics:i}){const a=n,o=r?.toLowerCase().startsWith("hi"),l=ps(t,r),u=zn(t,r),d=Vn(t.schedule_date_ist,r),h=gs(t,r),p=Jn(t,r),m=async()=>{if(i?.trackDoshaCalculatorResultBookCtaClicked?.({position:"puja_card",url:h,isOldDosha:!1}),s)try{await s()}catch(g){console.error("Error in onBookClick:",g)}window.open(h,"_blank","noopener,noreferrer")};return c.jsx(ft,{className:"overflow-hidden hover:shadow-lg transition-shadow relative",children:c.jsxs("div",{className:"relative",children:[c.jsx("div",{className:"absolute -top-1 -left-1 z-10",children:c.jsx("span",{className:"inline-flex items-center px-2 py-1 text-[10px] font-medium bg-destructive/90 text-destructive-foreground rounded-br-md shadow-sm",children:o?"सीमित सीटें":"Limited Seats"})}),p&&c.jsx("div",{className:"relative aspect-[16/10] w-full overflow-hidden bg-muted",children:c.jsx(a,{src:p,alt:l,className:"w-full h-full object-contain",loading:"lazy"})}),c.jsxs("div",{className:"p-3 space-y-2",children:[c.jsx("h4",{className:"font-semibold text-sm line-clamp-2 text-card-foreground",children:l}),t.temple_name&&c.jsx("p",{className:"text-sm text-muted-foreground",children:u}),t.schedule_date_ist&&c.jsx("p",{className:"text-sm font-medium text-card-foreground",children:d}),t.individual_pack_price_inr>0&&c.jsx("p",{className:"text-base font-bold text-primary",children:o?`₹${t.individual_pack_price_inr} से शुरू`:`Starting from ₹${t.individual_pack_price_inr}`}),c.jsxs(ar,{size:"lg",className:"book-puja-cta w-full h-14 text-lg font-bold",onClick:async g=>{g.preventDefault(),await m()},children:[o?"पूजा बुक करें":"Book Puja",c.jsx(oc,{className:"ml-1.5 h-3.5 w-3.5",size:14})]}),c.jsx("p",{className:"text-[10px] text-center text-muted-foreground",children:o?"श्री मंदिर द्वारा संचालित":"Powered by Sri Mandir"})]})]})})}const mt={section:"_section_15ygl_1",heading:"_heading_15ygl_5",list:"_list_15ygl_16",item:"_item_15ygl_20",stepNumber:"_stepNumber_15ygl_24",itemContent:"_itemContent_15ygl_30",itemTitle:"_itemTitle_15ygl_34",itemDesc:"_itemDesc_15ygl_39"};function oi({t,className:e="",bannerType:r="generic"}){const s=t("whatFromAnalysisTitle"),n=r==="marriage"?"whatFromAnalysisMarriage":"whatFromAnalysisGeneric",i=[{titleKey:`${n}1Title`,descKey:`${n}1Desc`},{titleKey:`${n}2Title`,descKey:`${n}2Desc`},{titleKey:`${n}3Title`,descKey:`${n}3Desc`}];return c.jsxs("section",{className:`${mt.section} ${e}`,"aria-labelledby":"what-from-analysis-heading",children:[c.jsx("h2",{id:"what-from-analysis-heading",className:mt.heading,children:s}),c.jsx("ol",{className:mt.list,children:i.map(({titleKey:a,descKey:o},l)=>c.jsxs("li",{className:mt.item,children:[c.jsx("span",{className:mt.stepNumber,"aria-hidden":"true",children:l+1}),c.jsxs("div",{className:mt.itemContent,children:[c.jsx("span",{className:mt.itemTitle,children:t(a)}),c.jsx("span",{className:mt.itemDesc,children:t(o)})]})]},a))})]})}const Ec={marriage:{en:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137437775.webp",alt:"Marriage dosha analysis banner",tickerText:"★ 4.9 Rated By Users Facing Marriage Delay"},hi:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137493287.webp",alt:"विवाह दोष विश्लेषण बैनर",tickerText:"★ 4.9 शादी में देरी का सामना कर रहे उपयोगकर्ताओं द्वारा रेटेड"}},generic:{en:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137415503.webp",alt:"Dosha analysis banner",tickerText:"★ 4.9 Rated By Users Seeking Clarity"},hi:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137476046.webp",alt:"दोष विश्लेषण बैनर",tickerText:"★ 4.9 रेटिंग अपने दोषा को जानने वाले यूज़र्स ने दी"}}},jc={"marriage-what-you'll-get-first":"marriage","marriage-form-first":"marriage","generic-what-you'll-get-first":"generic","generic-form-first":"generic"};function li(t,e){let r="generic";if(t){for(const[s,n]of Object.entries(jc))if(t.includes(s)){r=n;break}}return Ec[r][e]}function Ac(t){return typeof window>"u"?null:new URLSearchParams(window.location.search).get(t)}function qr(){return Ac("utm_term")}const Pc=w.lazy(()=>Promise.resolve().then(()=>Yc).then(t=>({default:t.DoshaResultsFull}))),Rc="https://srm-cdn.a4b.io/yoda/1770362904947.svg",Oc="https://srm-cdn.a4b.io/yoda/1770375694934.svg",Cc="https://srm-cdn.a4b.io/yoda/1770375720933.svg",Nc="https://srm-cdn.a4b.io/yoda/1770707793537.svg",Ic="https://srm-cdn.a4b.io/yoda/1770362713543.svg";function ci(t){const e=new Set([t]);switch(t){case"kaal-sarp":e.add("kaalSarp"),e.add("kaalsarp"),e.add("kaal_sarp");break;case"shani":e.add("sadeSati"),e.add("shaniSadeSati"),e.add("sade-sati");break;case"mangal":e.add("mangalDosha"),e.add("manglik");break;case"pitra":e.add("pitru"),e.add("pitraDosha");break}return Array.from(e)}function Wr(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function ui(t){if(!t)return 2;const e=t.toLowerCase();return e==="severe"||e==="high"?3:e==="moderate"||e==="medium"?2:e==="mild"||e==="low"?1:2}function di(t){if(!t||typeof window>"u")return t;try{const e=new URLSearchParams(window.location.search);if(Array.from(e.keys()).length===0)return t;const r=new URL(t,window.location.href);return e.forEach((s,n)=>{r.searchParams.set(n,s)}),r.toString()}catch{return t}}function _s(t){const e=[];return Wr(t.kaalSarp)&&e.push({type:"kaal-sarp",severity:typeof t.kaalSarpSeverity=="string"?t.kaalSarpSeverity:void 0}),Wr(t.pitra)&&e.push({type:"pitra",severity:typeof t.pitraSeverity=="string"?t.pitraSeverity:void 0}),Wr(t.shaniSadeSati||t.sadeSati)&&e.push({type:"shani",severity:typeof t.sadeSatiSeverity=="string"?t.sadeSatiSeverity:void 0}),Wr(t.mangal)&&!t.mangal?.toLowerCase().includes("nullified")&&e.push({type:"mangal",severity:typeof t.mangalSeverity=="string"?t.mangalSeverity:void 0}),e.length===0?null:(e.sort((r,s)=>ui(s.severity)-ui(r.severity)),e[0]?.type??null)}function Dc({t}){return c.jsxs("div",{className:q.footerShellStyles.marqueeContent,children:[c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(lt,{src:Oc,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaKundliCreated")]}),c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(lt,{src:Cc,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaCertified")]}),c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(lt,{src:Nc,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaSecurePayment")]})]})}const $c=[{qKey:"faqQ1",aKey:"faqA1"},{qKey:"faqQ2",aKey:"faqA2"},{qKey:"faqQ3",aKey:"faqA3"}],Lc=[{qKey:"faqQ1Marriage",aKey:"faqA1Marriage"},{qKey:"faqQ2Marriage",aKey:"faqA2Marriage"},{qKey:"faqQ3Marriage",aKey:"faqA3Marriage"},{qKey:"faqQ4Marriage",aKey:"faqA4Marriage"}];function Mc({className:t="",logoUrl:e=Rc,languageSelector:r,showLanguageSelector:s=!0,isGlobal:n=!1,readMoreReviewsHref:i,supabaseUrl:a,supabaseAnonKey:o,googleMapsApiKey:l,supabase:u,resolvePlace:d,onResult:h,onError:p,renderPujaCard:m,isLoadingPujas:g=!1,renderKundali:y,kundaliSectionId:x="kundali-chart-section",analytics:v,getFirstPujaInfo:_,onBookPujaClick:k,imageComponent:O=lt}){const R=w.useMemo(()=>{if(u)return u;if(a&&o)try{return Un(a,o)}catch{return null}return null},[u,a,o]),M=O,E=ys(),$=E?.t??(N=>N),L=E?.locale??"en",$e=E?.setLocale,ge=L.toLowerCase().startsWith("hi"),Oe=w.useRef(null),ee=w.useRef(null),[te,he]=w.useState(!1),[tt,Ce]=w.useState(!1),[re,fe]=w.useState(null),[Se,Q]=w.useState(null),[b,F]=w.useState(void 0),[z,H]=w.useState(!1),[V,B]=w.useState([]),[U,J]=w.useState(!1),[se,me]=w.useState(null),le=w.useRef(!1);w.useEffect(()=>{le.current||(le.current=!0,v?.trackDoshaCalculatorWebView?.())},[]);const Ee=!m||!_;w.useEffect(()=>{if(!Ee||!R)return;let N=!0;return J(!0),Gl(R).then(ne=>{N&&B(ne)}).finally(()=>{N&&J(!1)}),()=>{N=!1}},[Ee,R]);const Kt=w.useCallback(N=>{const ne=Kn(V,N);return ne?c.jsx(ai,{puja:ne,doshaType:N,language:L,imageComponent:O,analytics:v}):null},[V,L,O,v]),We=w.useCallback(N=>{const ne=Kn(V,N);return ne?{name:ps(ne,L),price:ne.individual_pack_price_inr,link:gs(ne,L)}:null},[V,L]),Le=m??Kt,Tt=_??We,Et=g||!m&&U,[ct,lr]=w.useState(()=>{const N=typeof window<"u"?qr():null;return li(N,L)}),[A,I]=w.useState(()=>{if(typeof window>"u")return"generic";const N=qr();return N&&N.toLowerCase().includes("marriage")?"marriage":"generic"});w.useEffect(()=>{const N=qr(),ne=li(N,L);lr(ne);let xe="generic";N&&N.toLowerCase().includes("marriage")&&(xe="marriage"),I(xe)},[L]);const[ae,Qe]=w.useState(!1);w.useEffect(()=>{const N=qr();N&&N.toLowerCase().includes("what-you")&&Qe(!0)},[]);const pt=()=>{Oe.current?.scrollIntoView({behavior:"smooth"})},_e=w.useCallback(N=>{v?.trackDoshaSectionImpression?.({section:N,timestamp:new Date().toISOString()})},[v]),ce=(N,ne)=>{if(fe(N),Q(ne??null),H(!1),N.summary){const xe=N.summary,Te=_s(xe);if(Te){const ye=ci(Te).map(ur=>Tt(ur)).find(Boolean)??null;me(ye)}else me(null)}else me(null);h?.(N,ne)};w.useEffect(()=>{if(_||!re?.summary)return;const N=_s(re.summary);if(!N){me(null);return}const ne=ci(N).map(xe=>We(xe)).find(Boolean)??null;me(ne)},[We,_,re]);const je=()=>{H(!0),window.scrollTo({top:0,behavior:"smooth"})},He=()=>{if(re&&!z&&se){if(se.link){const N=di(se.link);v?.trackDoshaCalculatorResultBookCtaClicked?.({position:"floating_cta",url:N,isOldDosha:!1})}if(k)k();else if(se.link){const N=di(se.link);window.open(N,"_blank","noopener,noreferrer")}return}console.log("supabase",R),console.log("resolvePlaceProp",d),console.log("isFormComplete",te),console.log("formSubmitRef.current",ee.current),R&&ee.current?(v?.trackFloatingCtaClicked?.(te?pr.all_fields_filled:pr.fields_not_filled),te||pt(),ee.current.submit()):(v?.trackFloatingCtaClicked?.(pr.fields_not_filled),pt())},cr=s&&!n?c.jsxs("button",{type:"button",onClick:()=>{$e&&$e(ge?"en":"hi")},"aria-label":ge?"Switch to English":"हिंदी में बदलें",className:"flex items-center justify-center gap-1.5 py-2 rounded-lg text-white text-sm font-medium hover:opacity-90 transition-colors",style:{backgroundColor:"#E13A44",borderRadius:"8px",width:"100px"},disabled:!$e,children:[c.jsx(M,{src:Ic,alt:"",className:"w-5 h-5 brightness-0 invert",width:20,height:20,loading:"lazy"}),c.jsx("span",{children:ge?"English":"हिंदी"})]}):null;return c.jsxs("div",{className:t,children:[c.jsx(q.PageHeader,{t:$,logoUrl:e,languageSelector:cr,showLanguageSelector:s}),c.jsx(q.MarqueeStrip,{children:c.jsx(Dc,{t:$})}),!re&&c.jsx(ht,{section:"banner",onImpression:_e,children:c.jsx(dc,{bannerConfig:ct,imageComponent:O})}),c.jsx("main",{className:"pb-28",children:re?c.jsx(ht,{section:"result",onImpression:_e,children:c.jsx(w.Suspense,{fallback:c.jsxs("div",{className:"container mx-auto px-4 py-8 space-y-4",children:[c.jsx(Ft,{className:"h-12 w-3/4 mx-auto"}),c.jsx(Ft,{className:"h-32 w-full"}),c.jsx(Ft,{className:"h-48 w-full"}),c.jsx(Ft,{className:"h-48 w-full"})]}),children:c.jsx(Pc,{result:re,t:$,onEdit:z?void 0:je,inlineEditForm:z?c.jsx(ws,{ref:ee,t:$,initialValues:b,onValuesChange:F,onFormValidityChange:he,supabase:R??void 0,resolvePlace:d,googleMapsApiKey:l,onResult:ce,onError:p,onLoadingChange:Ce,analytics:v}):void 0,renderPujaCard:Le,isLoadingPujas:Et,renderKundali:y,kundaliSectionId:x,birthDetails:Se,supabase:R,language:E?.locale??"en",readMoreReviewsHref:i,analytics:v,problemArea:(()=>{const N=b?.problems||[],ne=N.filter(Te=>Te!=="formProblemOther").map(Te=>$(Te)).filter(Boolean),xe=b?.otherProblemText?.trim();return N.includes("formProblemOther")&&xe&&ne.push(xe),ne.join(", ")})(),problemAreaIds:b?.problems||[],customProblemText:b?.otherProblemText||""})})}):c.jsxs(c.Fragment,{children:[ae&&c.jsx(ht,{section:"what_from_analysis",onImpression:_e,children:c.jsx(oi,{t:$,bannerType:A})}),c.jsx(ht,{section:"form",onImpression:_e,children:c.jsx("div",{ref:Oe,children:c.jsx(ws,{ref:ee,t:$,initialValues:b,onValuesChange:F,onFormValidityChange:he,supabase:R??void 0,resolvePlace:d,googleMapsApiKey:l,onResult:ce,onError:p,onLoadingChange:Ce,analytics:v})})}),!ae&&c.jsx(ht,{section:"what_from_analysis",onImpression:_e,children:c.jsx(oi,{t:$,bannerType:A})}),c.jsx(ht,{section:"user_reviews",onImpression:_e,children:c.jsx(q.UserReviewsSection,{t:N=>{if(A==="marriage"){if(N==="feedbackTitle")return $("feedbackTitleMarriage");if(N.startsWith("feedbackTestimonial")){const xe=`feedbackTestimonialMarriage${N.replace("feedbackTestimonial","")}`,Te=$(xe);return Te===xe?$(N):Te}}return $(N)},readMoreHref:i,onReadMore:v?.trackReadMoreReviewsClicked?()=>v.trackReadMoreReviewsClicked():void 0})}),c.jsx(ht,{section:"faq",onImpression:_e,children:c.jsx(q.FAQAccordion,{t:$,items:A==="marriage"?Lc:$c,defaultOpenIndex:0,onItemOpen:N=>v?.trackFaqQuestionClicked?.(N)})}),c.jsx(ht,{section:"contact",onImpression:_e,children:c.jsx(q.ContactUsSection,{title:$("contactTitle"),brandName:$("contactBrandName"),whatsAppLine:$("contactWhatsAppDomestic"),emailLine:$("contactEmail")})})]})}),!(re&&!z&&_s(re.summary)===null)&&c.jsxs(q.FooterShell,{children:[!(re&&!z&&se)&&c.jsx(tc,{}),c.jsx(uc,{isFormComplete:te,onPress:He,labelDefault:$("formCta"),labelFilled:$("formCtaCalculate"),loadingLabel:$("calculating"),isLoading:tt,mode:re&&!z&&se?"book-puja":"form",firstPuja:se||void 0,showingResults:!!re&&!z,bookPujaLabel:$("bookPuja")})]})]})}const oe={section:"_section_ji9so_1",heading:"_heading_ji9so_6",headingSuccess:"_headingSuccess_ji9so_13",card:"_card_ji9so_17",cardPresent:"_cardPresent_ji9so_25",cardAbsent:"_cardAbsent_ji9so_29",cardHeader:"_cardHeader_ji9so_33",doshaName:"_doshaName_ji9so_41",badge:"_badge_ji9so_46",badgePresent:"_badgePresent_ji9so_53",badgeAbsent:"_badgeAbsent_ji9so_58",badgeInactive:"_badgeInactive_ji9so_63",body:"_body_ji9so_68",bodyLabel:"_bodyLabel_ji9so_75",noDoshas:"_noDoshas_ji9so_81",noDoshasDesc:"_noDoshasDesc_ji9so_88",editBtn:"_editBtn_ji9so_94",accordionContent:"_accordionContent_ji9so_128"},Uc=[{key:"mangal",labelKey:"resultMangal",summaryKey:"mangal"},{key:"kaalSarp",labelKey:"resultKaalSarp",summaryKey:"kaalSarp"},{key:"pitra",labelKey:"resultPitra",summaryKey:"pitra"},{key:"sadeSati",labelKey:"resultSadeSati",summaryKey:"shaniSadeSati"}];function or(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function Bc(t,e){if(Array.isArray(t))return t.find(s=>(s.name??s.type)===e);if(t&&typeof t=="object"&&e in t){const r=t[e];if(!r)return;const s=typeof r.remedies=="string"?r.remedies:Array.isArray(r.remedies)?r.remedies.join(`
|
|
153
|
+
`):void 0;return{explanation:r.explanation,remedies:s}}}function Fc(t,e){if(!t)return"";const r=t.toLowerCase();return r.includes("nullified")||r==="present"||r==="active"||r==="partial"||r==="suggested"?e("resultStatusPresent"):r==="absent"?e("resultStatusAbsent"):r==="inactive"?e("resultStatusInactive"):t}function Kc({result:t,t:e,onEdit:r,className:s=""}){const n=t.summary??{},i=t.details??{},a=n.shaniSadeSati??n.sadeSati,o=or(n.mangal)||or(n.kaalSarp)||or(n.pitra)||or(a);return c.jsxs("section",{className:`${oe.section} ${s}`,"aria-labelledby":"dosha-results-heading",children:[c.jsx("h2",{id:"dosha-results-heading",className:o?`${oe.heading} ${oe.headingSuccess}`:oe.heading,children:e(o?"resultSomeDoshas":"resultNoDoshas")}),o?c.jsx("div",{children:Uc.map(({key:l,labelKey:u,summaryKey:d})=>{const h=d==="shaniSadeSati"?a:n[d],p=or(h),m=Bc(i,l==="sadeSati"?"sadeSati":l),g=m?.explanation,y=typeof m?.remedies=="string"?m.remedies:void 0;return c.jsxs("div",{className:`${oe.card} ${p?oe.cardPresent:oe.cardAbsent}`,children:[c.jsxs("div",{className:oe.cardHeader,children:[c.jsx("span",{className:oe.doshaName,children:e(u)}),c.jsx("span",{className:`${oe.badge} ${p?oe.badgePresent:h==="inactive"?oe.badgeInactive:oe.badgeAbsent}`,children:Fc(h,e)})]}),(g||y)&&c.jsxs("div",{className:oe.body,children:[g&&c.jsxs("div",{children:[c.jsx("div",{className:oe.bodyLabel,children:e("resultExplanation")}),c.jsx("p",{className:oe.accordionContent,children:g})]}),y&&c.jsxs("div",{style:{marginTop:g?"0.75rem":0},children:[c.jsx("div",{className:oe.bodyLabel,children:e("resultRemedies")}),c.jsx("p",{className:oe.accordionContent,children:y})]})]})]},l)})}):c.jsxs("div",{className:oe.noDoshas,children:[c.jsx("p",{children:e("resultNoDoshas")}),c.jsx("p",{className:oe.noDoshasDesc,children:e("resultNoDoshasDesc")})]}),r&&c.jsx("button",{type:"button",className:oe.editBtn,onClick:r,"aria-label":e("resultEditForm"),children:e("resultEditForm")})]})}const Hr=Ie.forwardRef(({className:t="",variant:e="default",...r},s)=>{const n={default:"border-transparent bg-primary text-primary-foreground",secondary:"border-transparent bg-secondary text-secondary-foreground",destructive:"border-transparent bg-destructive/10 text-destructive",outline:"border-border text-muted-foreground bg-transparent"};return c.jsx("div",{ref:s,className:`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors ${n[e]} ${t}`,...r})});Hr.displayName="Badge";const ks=Ie.createContext(null);function hi({type:t="single",collapsible:e=!0,className:r="",children:s,onValueChange:n}){const[i,a]=Ie.useState(null),o=Ie.useCallback(l=>{a(u=>{const d=u===l?e?null:u:l;return n?.(d),d})},[e,n]);return c.jsx(ks.Provider,{value:{value:i,onToggle:o},children:c.jsx("div",{className:r,children:s})})}function fi({value:t,className:e="",children:r}){return c.jsx("div",{"data-state":t,className:`border-b border-border ${e}`,children:r})}function mi({className:t="",children:e,value:r}){const s=Ie.useContext(ks),n=s?.value===r;return c.jsxs("button",{type:"button",onClick:()=>s?.onToggle(r),className:`flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline w-full text-left ${t}`,"aria-expanded":n,children:[e,c.jsx(ei,{className:`h-4 w-4 shrink-0 transition-transform duration-200 ${n?"rotate-180":""}`})]})}function pi({className:t="",children:e,value:r}){return Ie.useContext(ks)?.value===r?c.jsx("div",{className:`overflow-hidden text-sm pb-4 pt-0 ${t}`,children:e}):null}const Ss=new Map,gi=1800*1e3;function qc(t,e,r){return`D1|${e}|svg|${t.day}-${t.month}-${t.year}-${t.hour}-${t.minute}-${t.lat}-${t.lon}-${t.tzone}|${r}`}function Wc(t){const e=Ss.get(t);if(e&&Date.now()-e.timestamp<gi)return e.svg;try{const r=sessionStorage.getItem(`kundali_${t}`);if(r){const s=JSON.parse(r);if(Date.now()-s.timestamp<gi)return Ss.set(t,s),s.svg;sessionStorage.removeItem(`kundali_${t}`)}}catch{}return null}function Hc(t,e){const r={svg:e,timestamp:Date.now()};Ss.set(t,r);try{sessionStorage.setItem(`kundali_${t}`,JSON.stringify(r))}catch{}}function Gc(t){try{const r=new DOMParser().parseFromString(t,"image/svg+xml"),s=r.querySelector("svg");return s?(s.removeAttribute("width"),s.removeAttribute("height"),s.getAttribute("viewBox")||s.setAttribute("viewBox","0 0 350 350"),s.setAttribute("preserveAspectRatio","xMidYMid meet"),s.setAttribute("style","width:100%;height:auto;display:block;"),new XMLSerializer().serializeToString(r)):t}catch(e){return console.error("[kundaliChart] SVG transform error:",e),t}}async function yi(t,e){const{birthDetails:r,chartType:s,language:n,signal:i}=e,a=qc(r,s,n),o=Wc(a);if(o)return o;const l=await t.functions.invoke("get-kundali-chart",{body:{...r,chartType:s,language:n}});if(i?.aborted)throw new DOMException("Aborted","AbortError");if(l.error)throw new Error(l.error.message||"Failed to fetch kundali chart");const u=l.data?.data?.svg;if(!u)throw new Error("No SVG data in response");const d=Gc(u);return Hc(a,d),d}function bi({birthDetails:t,supabase:e,language:r,t:s}){const[n,i]=w.useState("North"),[a,o]=w.useState("idle"),[l,u]=w.useState(""),[d,h]=w.useState(""),p=w.useRef(null),m=w.useRef(null),y=(r||"").toLowerCase().startsWith("hi")?"hi":"en",x=w.useCallback(async k=>{p.current&&p.current.abort();const O=new AbortController;p.current=O,o("loading"),h("");try{const R=await yi(e,{birthDetails:t,chartType:k,language:y,signal:O.signal});O.signal.aborted||(u(R),o("success"))}catch(R){if(R instanceof Error&&R.name==="AbortError")return;console.error("[KundaliCard] Fetch error:",R),O.signal.aborted||(h(R instanceof Error?R.message:"Failed to load chart"),o("error"))}},[t,e,y]);w.useEffect(()=>(x(n),()=>{p.current&&p.current.abort()}),[n,x]);const v=k=>{k!==n&&i(k)},_=()=>{x(n)};return c.jsxs(ft,{ref:m,className:"spiritual-glow border border-primary/10",children:[c.jsxs(kt,{className:"pb-3",children:[c.jsx(St,{className:"text-xl font-bold",children:s("drYourKundali")}),c.jsxs("div",{className:"flex gap-2 mt-3 pt-2",children:[c.jsx(ar,{type:"button",size:"sm",variant:n==="North"?"default":"outline",className:"rounded-full px-4",onClick:()=>v("North"),children:s("kundaliChartNorth")}),c.jsx(ar,{type:"button",size:"sm",variant:n==="South"?"default":"outline",className:"rounded-full px-4",onClick:()=>v("South"),children:s("kundaliChartSouth")})]})]}),c.jsx(xt,{children:c.jsxs("div",{className:"w-full max-w-[360px] mx-auto",children:[a==="loading"&&c.jsx(Ft,{className:"w-full aspect-square rounded-lg"}),a==="success"&&l&&c.jsx("div",{className:"w-full aspect-square",dangerouslySetInnerHTML:{__html:l}}),a==="error"&&c.jsxs("div",{className:"w-full aspect-square flex flex-col items-center justify-center bg-muted/30 rounded-lg border border-border",children:[c.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:s("kundaliChartLoadError")}),c.jsxs(ar,{type:"button",variant:"outline",size:"sm",onClick:_,className:"gap-2",children:[c.jsx(lc,{className:"w-4 h-4"}),s("kundaliChartRetry")]})]})]})})]})}const zc=[{qKey:"faqQ1",aKey:"faqA1"},{qKey:"faqQ2",aKey:"faqA2"},{qKey:"faqQ3",aKey:"faqA3"}],vi=[{type:"kaal-sarp",detailKey:"kaalSarp",nameKey:"drKaalSarpName",descKey:"drKaalSarpDesc",impactKey:"drKaalSarpImpact",remediesKey:"drKaalSarpRemedies",benefitsKey:"drPujaBenefitsKaalSarp",icon:sc,summaryKey:"kaalSarp",severityKey:"kaalSarpSeverity"},{type:"pitra",detailKey:"pitra",nameKey:"drPitraName",descKey:"drPitraDesc",impactKey:"drPitraImpact",remediesKey:"drPitraRemedies",benefitsKey:"drPujaBenefitsPitra",icon:nc,summaryKey:"pitra",severityKey:"pitraSeverity"},{type:"shani",detailKey:"sadeSati",nameKey:"drSadeSatiName",descKey:"drSadeSatiDesc",impactKey:"drSadeSatiImpact",remediesKey:"drSadeSatiRemedies",benefitsKey:"drPujaBenefitsShani",icon:ic,summaryKey:"shaniSadeSati",severityKey:"sadeSatiSeverity"},{type:"mangal",detailKey:"mangal",nameKey:"drMangalName",descKey:"drMangalDesc",impactKey:"drMangalImpact",remediesKey:"drMangalRemedies",benefitsKey:"drPujaBenefitsMangal",icon:rc,summaryKey:"mangal",severityKey:"mangalSeverity"}];function Vc(t,e){const r=new Set([t]);switch(e&&r.add(e),t){case"kaal-sarp":r.add("kaalSarp"),r.add("kaalsarp"),r.add("kaal_sarp");break;case"shani":r.add("sadeSati"),r.add("shaniSadeSati"),r.add("sade-sati");break;case"mangal":r.add("mangalDosha"),r.add("manglik");break;case"pitra":r.add("pitru"),r.add("pitraDosha");break}return Array.from(r)}function qe(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function Gr(t){return t?t.toLowerCase().includes("nullified"):!1}function wi(t,e){if(Array.isArray(t)){const r=t.find(i=>(i.name??i.type)===e);if(!r)return;const s=typeof r.remedies=="string"?r.remedies:Array.isArray(r.remedies)?r.remedies.join(`
|
|
154
154
|
`):void 0,n=Array.isArray(r.placements)?r.placements:void 0;return{explanation:r.explanation,remedies:s,placements:n}}if(t&&typeof t=="object"&&e in t){const r=t[e];if(!r)return;const s=typeof r.remedies=="string"?r.remedies:Array.isArray(r.remedies)?r.remedies.join(`
|
|
155
|
-
`):void 0;return{explanation:r.explanation,remedies:s,placements:r.placements}}}function
|
|
156
|
-
`).map(Ee=>Ee.trim()).filter(Boolean),le=e(
|
|
157
|
-
`).map(Ee=>Ee.trim()).filter(Boolean);te.push({type:
|
|
158
|
-
`).map(le=>le.trim()).filter(Boolean);return c.jsxs(
|
|
159
|
-
`).map((U,J)=>c.jsx("li",{children:U},J))})]})]})]},
|
|
155
|
+
`):void 0;return{explanation:r.explanation,remedies:s,placements:r.placements}}}function _i(t,e){if(!t)return"";const r=t.toLowerCase();return r.includes("nullified")?e("drStatusNullified"):r==="present"||r==="active"||r==="partial"||r==="suggested"?e("drStatusPresent"):r==="absent"?e("drStatusAbsent"):r==="inactive"?e("drStatusInactive"):t}function ki(t){if(!t)return 2;const e=t.toLowerCase();return e==="severe"||e==="high"?3:e==="moderate"||e==="medium"?2:e==="mild"||e==="low"?1:2}function Si(t,e){if(!t)return e("drSeverityMedium");const r=t.toLowerCase();return e(r==="severe"||r==="high"?"drSeverityHigh":r==="moderate"||r==="medium"?"drSeverityMedium":r==="mild"||r==="low"?"drSeverityLow":"drSeverityMedium")}function Jc(t){return!t||/[\u0900-\u097F]/.test(t)?!1:/[A-Za-z]/.test(t)}function xi({result:t,t:e,onEdit:r,className:s="",kundaliSectionId:n,feedbackEmail:i="pujaseva@appsforbharat.com",renderPujaCard:a,isLoadingPujas:o=!1,renderKundali:l,birthDetails:u,supabase:d,language:h="en",readMoreReviewsHref:p,inlineEditForm:m,analytics:g,problemArea:y,problemAreaIds:x,customProblemText:v}){const[_,k]=w.useState({}),[O,R]=w.useState(!1),M=!l&&u&&d,E=t.summary??{},$=t.details??{};w.useEffect(()=>{if(!y||!y.trim()||!d){R(!1);return}R(!0),k({}),(async()=>{const F={},H=["mangal","kaal-sarp","pitra","shani"].filter(B=>B==="mangal"?qe(E.mangal)&&!Gr(E.mangal):B==="kaal-sarp"?qe(E.kaalSarp):B==="pitra"?qe(E.pitra):B==="shani"?qe(E.shaniSadeSati??E.sadeSati):!1);console.log("[DoshaResultsFull] Generating impacts for:",H,"problemArea:",y);const V=H.map(async B=>{try{const U={formProblemMarriage:"marriage",formProblemMoney:"financial",formProblemHealth:"health",formProblemEducation:"education",formProblemCareer:"career",formProblemBusiness:"business",formProblemFamily:"family",formProblemFinancial:"financial",formProblemOther:"other"},J=x?.filter(le=>le!=="formProblemOther").map(le=>U[le]||le.toLowerCase()).filter(Boolean)||[];x?.includes("formProblemOther")&&v?.trim()&&J.push("other");const se=J[0]||void 0;console.log(`[DoshaResultsFull] Calling generate-impact for ${B}`,{originalProblemAreaIds:x,mappedProblemAreaIds:J,problemArea:y,problemAreaId:se,customProblemText:v,language:h?.toLowerCase().startsWith("hi")?"hi":"en"});const me=await d.functions.invoke("generate-impact",{body:{doshaType:B,problemArea:y,problemAreaId:se,problemAreaIds:J,customProblemText:v,language:h?.toLowerCase().startsWith("hi")?"hi":"en"}});if(console.log(`[DoshaResultsFull] Impact response for ${B}:`,me.data),me.error){console.error(`[DoshaResultsFull] Error generating impact for ${B}:`,me.error);return}me.data?.impactText&&(F[B]={title:me.data.impactTitle||e("drImpactIfPresent"),text:me.data.impactText})}catch(U){console.error(`[DoshaResultsFull] Failed to generate impact for ${B}:`,U)}});await Promise.all(V),console.log("[DoshaResultsFull] Final personalized impacts:",F),k(F),R(!1)})()},[y,x,v,h,d,E]),w.useEffect(()=>{g?.trackDoshaCalculatorResultPageView?.()},[g]);const L=E.shaniSadeSati??E.sadeSati,$e=[{summaryKey:"grahan",detailKey:"grahan",labelKey:"drOtherGrahan",descKey:"drOtherGrahanDesc",impactKey:"drOtherGrahanImpact",remediesKey:"drOtherGrahanRemedies"},{summaryKey:"shrapit",detailKey:"shrapit",labelKey:"drOtherShrapit",descKey:"drOtherShrapitDesc",impactKey:"drOtherShrapitImpact",remediesKey:"drOtherShrapitRemedies"},{summaryKey:"guruChandal",detailKey:"guruChandal",labelKey:"drOtherGuruChandal",descKey:"drOtherGuruChandalDesc",impactKey:"drOtherGuruChandalImpact",remediesKey:"drOtherGuruChandalRemedies"},{summaryKey:"punarphoo",detailKey:"punarphoo",labelKey:"drOtherPunarphoo",descKey:"drOtherPunarphooDesc",impactKey:"drOtherPunarphooImpact",remediesKey:"drOtherPunarphooRemedies"},{summaryKey:"kemadruma",detailKey:"kemadruma",labelKey:"drOtherKemadruma",descKey:"drOtherKemadrumaDesc",impactKey:"drOtherKemadrumaImpact",remediesKey:"drOtherKemadrumaRemedies"},{summaryKey:"gandmool",detailKey:"gandmool",labelKey:"drOtherGandmool",descKey:"drOtherGandmoolDesc",impactKey:"drOtherGandmoolImpact",remediesKey:"drOtherGandmoolRemedies"},{summaryKey:"kalathra",detailKey:"kalathra",labelKey:"drOtherKalathra",descKey:"drOtherKalathraDec",impactKey:"drOtherKalathraImpact",remediesKey:"drOtherKalathraRemedies"},{summaryKey:"vishDaridra",detailKey:"vishDaridra",labelKey:"drOtherVishDaridra",descKey:"drOtherVishDaridraDesc",impactKey:"drOtherVishDaridraImpact",remediesKey:"drOtherVishDaridraRemedies"},{summaryKey:"ketuNaga",detailKey:"ketuNaga",labelKey:"drOtherKetuNaga",descKey:"drOtherKetuNagaDesc",impactKey:"drOtherKetuNagaImpact",remediesKey:"drOtherKetuNagaRemedies"},{summaryKey:"navagrahaUmbrella",detailKey:"navagraha",labelKey:"drOtherNavagraha",descKey:"drOtherNavagrahaDesc",impactKey:"drOtherNavagrahaImpact",remediesKey:"drOtherNavagrahaRemedies"}],Oe=$e.filter(b=>qe(E[b.summaryKey])).length>0,ee=qe(E.mangal)&&!Gr(E.mangal)||qe(E.kaalSarp)||qe(E.pitra)||qe(L)||Oe,te=[];for(const b of vi){const F=b.summaryKey==="shaniSadeSati"?L:E[b.summaryKey];if(!qe(F)||b.type==="mangal"&&Gr(F))continue;const z=E[b.severityKey],H=b.type==="shani"?E.shaniPhase??E.shaniPhase:void 0,V=wi($,b.detailKey==="sadeSati"?"sadeSati":b.detailKey),B=V?.explanation,U=B&&!(h.toLowerCase().startsWith("hi")&&Jc(B))?B:e(b.descKey),se=(V?.remedies??e(b.remediesKey)).split(`
|
|
156
|
+
`).map(Ee=>Ee.trim()).filter(Boolean),le=e(b.benefitsKey).split(`
|
|
157
|
+
`).map(Ee=>Ee.trim()).filter(Boolean);te.push({type:b.type,detailKey:b.detailKey,label:e(b.nameKey),icon:b.icon,status:F??"",severity:z||"moderate",phase:H??void 0,explanation:U,placements:V?.placements,impact:e(b.impactKey),remedies:se,benefits:le})}te.sort((b,F)=>ki(F.severity)-ki(b.severity));const[he,tt]=w.useState(!1),Ce=/\b(house|lagna|ascendant|moon|mars|saturn|rahu|ketu|sun|jupiter|venus|mercury|sign|degree|H\d+|conjunction|aspect)\b|भाव|लग्न|चंद्र|मंगल|शनि|राहु|केतु|सूर्य|बृहस्पति|शुक्र|बुध/i,re=$&&typeof $=="object"&&!Array.isArray($)?$:{},fe=[];te.forEach(b=>{const F=re[b.detailKey==="sadeSati"?"sadeSati":b.detailKey]||{},z=[...F.placements||[],...F.triggeredBy||[],...F.notes||[]].map(U=>String(U||"").trim()).filter(Boolean),H=Array.from(new Set(z)),V=H.filter(U=>Ce.test(U)),B=V.length>0?V:H;B.length>0&&fe.push({label:b.label,evidence:B})}),$e.forEach(b=>{if(!qe(E[b.summaryKey]))return;const F=re[b.detailKey]||{},z=[...F.placements||[],...F.triggeredBy||[],...F.notes||[]].map(U=>String(U||"").trim()).filter(Boolean),H=Array.from(new Set(z)),V=H.filter(U=>Ce.test(U)),B=V.length>0?V:H;if(B.length>0){const U=e(b.labelKey);fe.some(J=>J.label===U)||fe.push({label:U,evidence:B})}});const Se=b=>b===1?e("drPhaseRising"):b===2?e("drPhasePeak"):b===3?e("drPhaseSetting"):"",Q=["bg-orange-50/50 border-l-4 border-l-orange-400","bg-blue-50/50 border-l-4 border-l-blue-400","bg-purple-50/50 border-l-4 border-l-purple-400","bg-amber-50/50 border-l-4 border-l-amber-400"];return c.jsxs("div",{className:`w-full max-w-2xl mx-auto space-y-6 ${s}`,children:[c.jsxs("div",{className:"px-4 pt-4 pb-2 mb-6",children:[c.jsxs("div",{className:"text-center",children:[c.jsx("h1",{className:"text-2xl font-bold mb-2",style:{color:"#1F2937",fontFamily:'"Plus Jakarta Sans", sans-serif'},children:e("resultPageTitle")}),c.jsx("p",{className:"text-sm leading-relaxed",style:{color:"#6B7280",fontFamily:'"Plus Jakarta Sans", sans-serif'},children:e("resultPageSubtitle")})]}),m?c.jsx("div",{className:"mt-4",children:m}):r?c.jsxs("button",{type:"button",onClick:r,className:"mt-4 inline-flex items-center gap-2 min-h-[44px] px-4 text-sm font-medium border border-gray-300 bg-white rounded-md hover:bg-gray-50 transition-colors text-gray-700",style:{fontFamily:'"Plus Jakarta Sans", sans-serif'},children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[c.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),c.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),e("resultEditForm")]}):null]}),c.jsxs(ft,{className:"spiritual-glow border-2 border-primary/20 mx-4",children:[c.jsx(kt,{children:c.jsx(St,{id:"dosha-results-heading",className:`text-2xl sm:text-3xl font-bold break-words ${ee?"text-primary":"text-success"}`,children:ee?e("resultSomeDoshas"):`✓ ${e("resultNoDoshas")}`})}),c.jsx(xt,{children:ee?c.jsx("div",{className:"flex flex-wrap gap-2",children:te.map(b=>c.jsxs("div",{className:"inline-flex items-center gap-2 bg-accent/20 border border-accent/30 px-4 py-2 rounded-full",children:[c.jsx(bs,{className:"w-4 h-4 text-primary"}),c.jsxs("span",{className:"font-medium text-sm text-foreground",children:[b.label,": ",_i(b.status,e)]})]},b.type))}):c.jsxs("div",{className:"text-center py-8",children:[c.jsx(Zn,{className:"w-12 h-12 mx-auto mb-4 text-success"}),c.jsx("p",{className:"text-lg font-medium text-foreground",children:e("resultNoDoshas")}),c.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:e("resultNoDoshasDesc")})]})})]}),te.map((b,F)=>{const z=b.icon,H=b.type==="shani"&&b.phase?Se(b.phase):"",V=Q[F%Q.length],B=e("drDoshaOf").replace("{{index}}",String(F+1)).replace("{{total}}",String(te.length));return c.jsxs(ft,{className:`spiritual-glow border border-primary/10 mx-4 ${V}`,children:[c.jsx("div",{className:"px-4 pt-3",children:c.jsx(Hr,{variant:"outline",className:"text-xs font-normal text-muted-foreground",children:B})}),c.jsxs(kt,{className:"pb-3 pt-2",children:[c.jsxs(St,{className:"flex items-center gap-3 text-xl",children:[c.jsx(z,{className:"w-6 h-6 text-primary"}),b.label]}),c.jsxs(Kr,{children:[e("drSeverity"),": ",Si(b.severity,e),b.phase!=null&&` • ${e("drPhase")}: ${b.phase}`]})]}),c.jsxs(xt,{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsxs("h4",{className:"font-semibold text-base flex items-center gap-2",children:[c.jsx(Ur,{className:"w-4 h-4 text-primary"}),e("drWhyMarked"),n&&c.jsxs("button",{type:"button",onClick:()=>{g?.trackDoshaCalculatorResultViewKundliClick?.();const U=document.getElementById(n);U&&U.scrollIntoView({behavior:"smooth",block:"center"})},className:"text-xs text-primary hover:underline ml-auto whitespace-nowrap",children:[e("drViewKundli")," ↓"]})]}),c.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:b.explanation}),H&&c.jsxs("div",{className:"mt-3 p-3 bg-warning/10 rounded-md border border-warning/20",children:[c.jsx("h5",{className:"font-medium text-sm mb-2",children:e("drPhaseMeaning")}),c.jsx("p",{className:"text-sm text-muted-foreground",children:H})]}),b.type!=="pitra"&&b.placements&&b.placements.length>0&&c.jsxs("div",{className:"mt-3 p-3 bg-accent/10 rounded-md border border-accent/20",children:[c.jsx("h5",{className:"font-medium text-sm mb-2",children:e("drPlanetaryPositions")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:b.placements.map((U,J)=>c.jsx("li",{children:U},J))})]})]}),c.jsxs("div",{className:"p-4 bg-destructive/10 border border-destructive/20 rounded-lg",children:[c.jsx("h4",{className:"font-semibold text-sm mb-2 text-destructive",children:_[b.type]?.title||e("drImpactIfPresent")}),O?c.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[c.jsx(vs,{className:"w-4 h-4 animate-spin"}),c.jsx("span",{children:h==="hi"?"प्रभाव विश्लेषण हो रहा है...":"Analyzing impact..."})]}):c.jsx("p",{className:"text-sm text-muted-foreground",children:_[b.type]?.text||b.impact})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("h4",{className:"font-semibold text-base",children:e("drPujaRecommendation")}),a?o?c.jsx("div",{className:"flex items-center justify-center py-6",children:c.jsx(vs,{className:"w-6 h-6 text-primary animate-spin",size:24})}):(()=>{const U=Vc(b.type,b.detailKey),J=U.map(se=>a(se)).find(Boolean);return!J&&typeof window<"u"&&console.warn(`[DoshaCalculator] renderPujaCard returned null/undefined for dosha type: ${b.type} (tried: ${U.join(", ")})`),J||c.jsx("p",{className:"text-sm text-muted-foreground italic",children:e("drNoPujaAvailable")})})():c.jsxs("p",{className:"text-sm text-muted-foreground italic",children:[e("drNoPujaAvailable"),typeof window<"u"&&(console.warn("[DoshaCalculator] renderPujaCard prop not provided. Pass renderPujaCard to show puja recommendations."),null)]})]}),b.benefits.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsx("h4",{className:"font-semibold text-base flex items-center gap-2",children:e("drHowPujaHelps")}),c.jsx("ul",{className:"text-sm text-muted-foreground space-y-3 ml-1",children:b.benefits.map((U,J)=>c.jsxs("li",{className:"flex items-start gap-3",children:[c.jsx("span",{className:"text-primary mt-1.5 flex-shrink-0",children:"•"}),c.jsx("span",{children:U})]},J))})]})]})]},b.type)}),te.length>0&&c.jsx("p",{className:"text-xs text-muted-foreground text-center italic px-4",children:e("drFomoLine")}),c.jsxs("div",{className:"mx-4 p-4 bg-muted/30 rounded-lg border border-border/50 text-center",children:[c.jsx("p",{className:"text-sm text-foreground/80 font-medium",children:e("drFeedbackContact")}),c.jsx("a",{href:`mailto:${i}`,className:"text-primary hover:underline font-semibold text-base mt-1 inline-block",children:i})]}),c.jsxs(ft,{className:"spiritual-glow mx-4",children:[c.jsxs(kt,{children:[c.jsx(St,{className:"text-2xl font-bold text-center gradient-spiritual bg-clip-text text-transparent",children:e("drDetailedAnalysis")}),c.jsx(Kr,{className:"text-center",children:e("drBasedOnChart")})]}),c.jsx(xt,{className:"space-y-4",children:c.jsx(hi,{type:"single",collapsible:!0,className:"w-full space-y-4",children:vi.map(b=>{const F=b.detailKey==="sadeSati"?"sadeSati":b.detailKey,z=b.summaryKey==="shaniSadeSati"?L:E[b.summaryKey],H=wi($,b.detailKey==="sadeSati"?"sadeSati":b.detailKey),V=E[b.severityKey],B=b.type==="shani"?E.shaniPhase:void 0,U=b.icon,me=(H?.remedies?.trim()||e(b.remediesKey)).split(`
|
|
158
|
+
`).map(le=>le.trim()).filter(Boolean);return c.jsxs(fi,{value:F,className:"border border-border rounded-lg px-4",children:[c.jsx(mi,{value:F,className:"hover:no-underline",children:c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(U,{className:"w-5 h-5 text-destructive"}),c.jsxs("div",{className:"text-left",children:[c.jsx("h3",{className:"font-semibold text-lg",children:e(b.nameKey)}),c.jsxs("p",{className:"text-sm text-muted-foreground",children:[e("drStatus"),": ",_i(z,e),V&&!Gr(z)&&` • ${e("drSeverity")}: ${Si(V,e)}`,b.type==="shani"&&B!=null&&` • ${e("drPhase")}: ${B}`]})]})]})}),c.jsxs(pi,{value:F,className:"pt-4 space-y-4",children:[c.jsx("p",{className:"text-sm text-muted-foreground italic",children:e(b.descKey)}),H?.explanation&&c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium mb-2",children:e("drExplanation")}),c.jsx("p",{className:"text-sm text-muted-foreground",children:H.explanation})]}),H?.placements&&H.placements.length>0&&c.jsxs("div",{className:"p-3 bg-accent/10 rounded-md",children:[c.jsx("h4",{className:"font-medium mb-2",children:e("drPlanetaryPositions")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:H.placements.map((le,Ee)=>c.jsx("li",{children:le},Ee))})]}),c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium mb-2",children:e("drTraditionalRemedies")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:me.map((le,Ee)=>c.jsx("li",{children:le},Ee))})]})]})]},F)})})})]}),c.jsxs(ft,{className:"mx-4",children:[c.jsx(kt,{className:"cursor-pointer hover:bg-accent/5 transition-colors",onClick:()=>tt(b=>!b),children:c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"text-left flex-1 min-w-0",children:[c.jsx(St,{className:"text-xl font-semibold",children:e("drOtherDoshas")}),c.jsx(Kr,{children:e(Oe?"drOtherDoshasStatusActive":"drOtherDoshasStatusNone")})]}),c.jsx(ei,{className:`h-5 w-5 flex-shrink-0 text-muted-foreground transition-transform duration-200 ${he?"rotate-180":""}`})]})}),he&&c.jsx(xt,{children:c.jsx(hi,{type:"single",collapsible:!0,className:"w-full space-y-2",children:$e.map(b=>{const F=E[b.summaryKey],z=qe(F),H=re[b.detailKey]??{},V=H.explanation,B=H.placements;return c.jsxs(fi,{value:b.summaryKey,className:"border border-border rounded-lg px-3",children:[c.jsx(mi,{value:b.summaryKey,className:"hover:no-underline py-3",children:c.jsxs("div",{className:"flex items-center justify-between gap-2 flex-1 min-w-0 mr-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"font-semibold text-sm text-left leading-tight",children:e(b.labelKey)}),c.jsx(Ur,{size:14,className:"text-muted-foreground flex-shrink-0"})]}),z?c.jsxs(Hr,{variant:"destructive",className:"flex-shrink-0 text-xs flex items-center gap-1 pointer-events-none",children:[c.jsx(bs,{size:10}),e("drStatusPresent")]}):c.jsxs(Hr,{variant:"secondary",className:"flex-shrink-0 text-xs flex items-center gap-1 bg-white border pointer-events-none",style:{borderColor:"#e4decd",color:"#000000"},children:[c.jsx(Zn,{size:10,color:"#000000"}),e("drStatusAbsent")]})]})}),c.jsxs(pi,{value:b.summaryKey,className:"space-y-3 pt-0 pb-3",children:[c.jsx("div",{className:"border-l-4 border-orange-500 bg-orange-50 rounded-lg pl-3 py-2",children:c.jsx("p",{className:"text-sm text-muted-foreground italic",children:e(b.descKey)})}),B&&B.length>0&&c.jsxs("div",{className:"p-3 bg-accent/10 rounded-md border border-accent/20",children:[c.jsxs("h5",{className:"font-medium mb-2 flex items-center gap-2 text-sm",children:[c.jsx(Ur,{size:14}),e("drPlanetaryPositions")]}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1 leading-relaxed",children:B.map((U,J)=>c.jsx("li",{children:U},J))})]}),V&&c.jsxs("div",{className:"border-l-4 border-orange-500 bg-orange-50 rounded-lg pl-3 py-2",children:[c.jsxs("h5",{className:"font-medium mb-2 text-sm flex items-center gap-2",children:[c.jsx(Ur,{size:14}),e(z?"drWhyPresent":"drWhyAbsent")]}),c.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:V})]}),z&&c.jsxs("div",{className:"border-l-4 border-red-500 bg-red-50 rounded-lg pl-3 py-2",children:[c.jsxs("h5",{className:"font-medium mb-2 text-sm flex items-center gap-2 text-red-600",children:[c.jsx(bs,{size:14}),e("drImpact")]}),c.jsx("p",{className:"text-sm text-muted-foreground",children:e(b.impactKey)})]}),z&&c.jsxs("div",{children:[c.jsx("h5",{className:"font-medium mb-2 text-sm",children:e("drTraditionalRemedies")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:e(b.remediesKey).split(`
|
|
159
|
+
`).map((U,J)=>c.jsx("li",{children:U},J))})]})]})]},b.summaryKey)})})})]}),c.jsx("div",{id:n||"kundali-chart-section",className:"px-4",children:(l||M||fe.length>0)&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"flex justify-end mb-2",children:c.jsxs("button",{type:"button",onClick:()=>document.getElementById("dosha-results-heading")?.scrollIntoView({behavior:"smooth",block:"start"}),className:"inline-flex items-center gap-1.5 text-sm text-primary hover:text-primary/80 transition-colors font-medium",children:[c.jsx(ac,{className:"w-4 h-4"}),e("drGoBack")]})}),l?c.jsxs("div",{className:"mt-2",children:[c.jsx("h2",{className:"text-xl font-semibold text-foreground mb-3",children:e("drYourKundali")}),l()]}):M&&u&&d?c.jsx("div",{className:"mt-2",children:c.jsx(bi,{birthDetails:u,supabase:d,language:h,t:e})}):null,fe.length>0&&c.jsxs(ft,{className:"mt-4 bg-accent/10 border border-accent/30",children:[c.jsx(kt,{className:"pb-2",children:c.jsx(St,{className:"text-base font-semibold",children:e("drPlanetaryPositionsCausing")})}),c.jsx(xt,{className:"pt-0",children:c.jsx("ul",{className:"space-y-3 text-sm text-muted-foreground",children:fe.map((b,F)=>c.jsxs("li",{children:[c.jsxs("div",{className:"font-semibold text-foreground mb-1",children:[b.label,":"]}),c.jsx("ul",{className:"ml-4 space-y-1",children:b.evidence.map((z,H)=>c.jsxs("li",{className:"flex items-start gap-2",children:[c.jsx("span",{className:"text-primary flex-shrink-0",children:"→"}),c.jsx("span",{children:z})]},H))})]},F))})})]})]})}),c.jsx("p",{className:"text-xs text-muted-foreground/70 text-center px-4",children:e("drDisclaimer")}),c.jsx(q.UserReviewsSection,{t:e,readMoreHref:p,onReadMore:g?.trackReadMoreReviewsClicked?()=>g.trackReadMoreReviewsClicked():void 0}),c.jsx(q.FAQAccordion,{t:e,items:zc,defaultOpenIndex:0}),c.jsx(q.ContactUsSection,{title:e("contactTitle"),brandName:e("contactBrandName"),whatsAppLine:e("contactWhatsAppDomestic"),emailLine:e("contactEmail")})]})}const Yc=Object.freeze(Object.defineProperty({__proto__:null,DoshaResultsFull:xi},Symbol.toStringTag,{value:"Module"}));function Qc(t){return!t||t.trim()===""?async()=>null:async e=>{try{if(!e?.trim())return null;const r=`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(e)}&key=${t}`,n=await(await fetch(r)).json();if(n.status!=="OK"||!n.results?.[0])return null;const{lat:i,lng:a}=n.results[0].geometry.location,o=Math.floor(Date.now()/1e3),l=`https://maps.googleapis.com/maps/api/timezone/json?location=${i},${a}×tamp=${o}&key=${t}`,d=await(await fetch(l)).json();if(d.status!=="OK")return null;const h=d.timeZoneId,p=(d.rawOffset+d.dstOffset)/3600;return{lat:i,lon:a,tz:h,tzoneOffset:p}}catch{return null}}}G.DoshaCalculator=Mc,G.DoshaFormSection=ws,G.DoshaResultsFull=xi,G.DoshaResultsView=Kc,G.FLOATING_CTA_STATUS=pr,G.I18nProvider=ec,G.KundaliCard=bi,G.LOCALE_LABELS=Xl,G.SUPPORTED_LOCALES=Ql,G.SriMandirPujaVerticalCard=ai,G.createGoogleMapsResolver=Qc,G.createSupabaseClient=Un,G.fetchKundaliSvg=yi,G.formatScheduleDate=Vn,G.getCoverImageUrl=Jn,G.getPujaLink=gs,G.getPujaTitle=ps,G.getTempleName=zn,G.insertSessionProblemStatements=ri,G.invokeCalculateDosha=si,G.submitDoshaCalculation=ni,G.translations=Yn,G.useGooglePlacesAutocomplete=ii,G.useI18n=ys,Object.defineProperty(G,Symbol.toStringTag,{value:"Module"})}));
|
|
160
160
|
//# sourceMappingURL=dosha-calculator.umd.cjs.map
|