@gymmymac/bob-widget 3.2.17 → 3.2.18

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/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var si=t=>{throw TypeError(t)};var rn=(t,e,r)=>e.has(t)||si("Cannot "+r);var w=(t,e,r)=>(rn(t,e,"read from private field"),r?r.call(t):e.get(t)),se=(t,e,r)=>e.has(t)?si("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),H=(t,e,r,s)=>(rn(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),pe=(t,e,r)=>(rn(t,e,"access private method"),r);var Is=(t,e,r,s)=>({set _(n){H(t,e,n,r)},get _(){return w(t,e,s)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react");function fo(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 pt=fo(p),It="3.2.17",po=()=>It;var pn={exports:{}},Xr={};/**
1
+ "use strict";var di=t=>{throw TypeError(t)};var hn=(t,e,r)=>e.has(t)||di("Cannot "+r);var w=(t,e,r)=>(hn(t,e,"read from private field"),r?r.call(t):e.get(t)),se=(t,e,r)=>e.has(t)?di("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),z=(t,e,r,s)=>(hn(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),fe=(t,e,r)=>(hn(t,e,"access private method"),r);var $s=(t,e,r,s)=>({set _(n){z(t,e,n,r)},get _(){return w(t,e,s)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react");function To(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 pt=To(p),Bt="3.2.18",Ro=()=>Bt;var xn={exports:{}},es={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.min.js
4
4
  *
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */var ni;function go(){if(ni)return Xr;ni=1;var t=p,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(l,c,u){var d,h={},g=null,f=null;u!==void 0&&(g=""+u),c.key!==void 0&&(g=""+c.key),c.ref!==void 0&&(f=c.ref);for(d in c)s.call(c,d)&&!i.hasOwnProperty(d)&&(h[d]=c[d]);if(l&&l.defaultProps)for(d in c=l.defaultProps,c)h[d]===void 0&&(h[d]=c[d]);return{$$typeof:e,type:l,key:g,ref:f,props:h,_owner:n.current}}return Xr.Fragment=r,Xr.jsx=a,Xr.jsxs=a,Xr}var Zr={};/**
9
+ */var hi;function Ao(){if(hi)return es;hi=1;var t=p,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,c,u){var d,h={},g=null,f=null;u!==void 0&&(g=""+u),c.key!==void 0&&(g=""+c.key),c.ref!==void 0&&(f=c.ref);for(d in c)s.call(c,d)&&!i.hasOwnProperty(d)&&(h[d]=c[d]);if(o&&o.defaultProps)for(d in c=o.defaultProps,c)h[d]===void 0&&(h[d]=c[d]);return{$$typeof:e,type:o,key:g,ref:f,props:h,_owner:n.current}}return es.Fragment=r,es.jsx=a,es.jsxs=a,es}var ts={};/**
10
10
  * @license React
11
11
  * react-jsx-runtime.development.js
12
12
  *
@@ -14,32 +14,33 @@
14
14
  *
15
15
  * This source code is licensed under the MIT license found in the
16
16
  * LICENSE file in the root directory of this source tree.
17
- */var ii;function bo(){return ii||(ii=1,process.env.NODE_ENV!=="production"&&function(){var t=p,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"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),g=Symbol.for("react.lazy"),f=Symbol.for("react.offscreen"),m=Symbol.iterator,b="@@iterator";function _(v){if(v===null||typeof v!="object")return null;var I=m&&v[m]||v[b];return typeof I=="function"?I:null}var y=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function k(v){{for(var I=arguments.length,q=new Array(I>1?I-1:0),X=1;X<I;X++)q[X-1]=arguments[X];j("error",v,q)}}function j(v,I,q){{var X=y.ReactDebugCurrentFrame,de=X.getStackAddendum();de!==""&&(I+="%s",q=q.concat([de]));var _e=q.map(function(fe){return String(fe)});_e.unshift("Warning: "+I),Function.prototype.apply.call(console[v],console,_e)}}var x=!1,T=!1,S=!1,F=!1,E=!1,P;P=Symbol.for("react.module.reference");function C(v){return!!(typeof v=="string"||typeof v=="function"||v===s||v===i||E||v===n||v===u||v===d||F||v===f||x||T||S||typeof v=="object"&&v!==null&&(v.$$typeof===g||v.$$typeof===h||v.$$typeof===a||v.$$typeof===l||v.$$typeof===c||v.$$typeof===P||v.getModuleId!==void 0))}function R(v,I,q){var X=v.displayName;if(X)return X;var de=I.displayName||I.name||"";return de!==""?q+"("+de+")":q}function O(v){return v.displayName||"Context"}function A(v){if(v==null)return null;if(typeof v.tag=="number"&&k("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof v=="function")return v.displayName||v.name||null;if(typeof v=="string")return v;switch(v){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 v=="object")switch(v.$$typeof){case l:var I=v;return O(I)+".Consumer";case a:var q=v;return O(q._context)+".Provider";case c:return R(v,v.render,"ForwardRef");case h:var X=v.displayName||null;return X!==null?X:A(v.type)||"Memo";case g:{var de=v,_e=de._payload,fe=de._init;try{return A(fe(_e))}catch{return null}}}return null}var $=Object.assign,V=0,z,ie,Y,U,K,he,Z;function re(){}re.__reactDisabledLog=!0;function ve(){{if(V===0){z=console.log,ie=console.info,Y=console.warn,U=console.error,K=console.group,he=console.groupCollapsed,Z=console.groupEnd;var v={configurable:!0,enumerable:!0,value:re,writable:!0};Object.defineProperties(console,{info:v,log:v,warn:v,error:v,group:v,groupCollapsed:v,groupEnd:v})}V++}}function D(){{if(V--,V===0){var v={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:$({},v,{value:z}),info:$({},v,{value:ie}),warn:$({},v,{value:Y}),error:$({},v,{value:U}),group:$({},v,{value:K}),groupCollapsed:$({},v,{value:he}),groupEnd:$({},v,{value:Z})})}V<0&&k("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var ae=y.ReactCurrentDispatcher,J;function B(v,I,q){{if(J===void 0)try{throw Error()}catch(de){var X=de.stack.trim().match(/\n( *(at )?)/);J=X&&X[1]||""}return`
18
- `+J+v}}var Se=!1,ke;{var we=typeof WeakMap=="function"?WeakMap:Map;ke=new we}function je(v,I){if(!v||Se)return"";{var q=ke.get(v);if(q!==void 0)return q}var X;Se=!0;var de=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var _e;_e=ae.current,ae.current=null,ve();try{if(I){var fe=function(){throw Error()};if(Object.defineProperty(fe.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(fe,[])}catch(Oe){X=Oe}Reflect.construct(v,[],fe)}else{try{fe.call()}catch(Oe){X=Oe}v.call(fe.prototype)}}else{try{throw Error()}catch(Oe){X=Oe}v()}}catch(Oe){if(Oe&&X&&typeof Oe.stack=="string"){for(var le=Oe.stack.split(`
19
- `),We=X.stack.split(`
20
- `),Ee=le.length-1,Re=We.length-1;Ee>=1&&Re>=0&&le[Ee]!==We[Re];)Re--;for(;Ee>=1&&Re>=0;Ee--,Re--)if(le[Ee]!==We[Re]){if(Ee!==1||Re!==1)do if(Ee--,Re--,Re<0||le[Ee]!==We[Re]){var Je=`
21
- `+le[Ee].replace(" at new "," at ");return v.displayName&&Je.includes("<anonymous>")&&(Je=Je.replace("<anonymous>",v.displayName)),typeof v=="function"&&ke.set(v,Je),Je}while(Ee>=1&&Re>=0);break}}}finally{Se=!1,ae.current=_e,D(),Error.prepareStackTrace=de}var Tt=v?v.displayName||v.name:"",Qe=Tt?B(Tt):"";return typeof v=="function"&&ke.set(v,Qe),Qe}function Fe(v,I,q){return je(v,!1)}function Le(v){var I=v.prototype;return!!(I&&I.isReactComponent)}function Xe(v,I,q){if(v==null)return"";if(typeof v=="function")return je(v,Le(v));if(typeof v=="string")return B(v);switch(v){case u:return B("Suspense");case d:return B("SuspenseList")}if(typeof v=="object")switch(v.$$typeof){case c:return Fe(v.render);case h:return Xe(v.type,I,q);case g:{var X=v,de=X._payload,_e=X._init;try{return Xe(_e(de),I,q)}catch{}}}return""}var ze=Object.prototype.hasOwnProperty,tt={},it=y.ReactDebugCurrentFrame;function Ue(v){if(v){var I=v._owner,q=Xe(v.type,v._source,I?I.type:null);it.setExtraStackFrame(q)}else it.setExtraStackFrame(null)}function N(v,I,q,X,de){{var _e=Function.call.bind(ze);for(var fe in v)if(_e(v,fe)){var le=void 0;try{if(typeof v[fe]!="function"){var We=Error((X||"React class")+": "+q+" type `"+fe+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof v[fe]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw We.name="Invariant Violation",We}le=v[fe](I,fe,X,q,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(Ee){le=Ee}le&&!(le instanceof Error)&&(Ue(de),k("%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).",X||"React class",q,fe,typeof le),Ue(null)),le instanceof Error&&!(le.message in tt)&&(tt[le.message]=!0,Ue(de),k("Failed %s type: %s",q,le.message),Ue(null))}}}var oe=Array.isArray;function Ce(v){return oe(v)}function W(v){{var I=typeof Symbol=="function"&&Symbol.toStringTag,q=I&&v[Symbol.toStringTag]||v.constructor.name||"Object";return q}}function ce(v){try{return Ae(v),!1}catch{return!0}}function Ae(v){return""+v}function Ze(v){if(ce(v))return k("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",W(v)),Ae(v)}var be=y.ReactCurrentOwner,er={key:!0,ref:!0,__self:!0,__source:!0},Me,Qr;function ei(v){if(ze.call(v,"ref")){var I=Object.getOwnPropertyDescriptor(v,"ref").get;if(I&&I.isReactWarning)return!1}return v.ref!==void 0}function ti(v){if(ze.call(v,"key")){var I=Object.getOwnPropertyDescriptor(v,"key").get;if(I&&I.isReactWarning)return!1}return v.key!==void 0}function ri(v,I){typeof v.ref=="string"&&be.current}function Rs(v,I){{var q=function(){Me||(Me=!0,k("%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)",I))};q.isReactWarning=!0,Object.defineProperty(v,"key",{get:q,configurable:!0})}}function Cs(v,I){{var q=function(){Qr||(Qr=!0,k("%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)",I))};q.isReactWarning=!0,Object.defineProperty(v,"ref",{get:q,configurable:!0})}}var As=function(v,I,q,X,de,_e,fe){var le={$$typeof:e,type:v,key:I,ref:q,props:fe,_owner:_e};return le._store={},Object.defineProperty(le._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(le,"_self",{configurable:!1,enumerable:!1,writable:!1,value:X}),Object.defineProperty(le,"_source",{configurable:!1,enumerable:!1,writable:!1,value:de}),Object.freeze&&(Object.freeze(le.props),Object.freeze(le)),le};function Os(v,I,q,X,de){{var _e,fe={},le=null,We=null;q!==void 0&&(Ze(q),le=""+q),ti(I)&&(Ze(I.key),le=""+I.key),ei(I)&&(We=I.ref,ri(I,de));for(_e in I)ze.call(I,_e)&&!er.hasOwnProperty(_e)&&(fe[_e]=I[_e]);if(v&&v.defaultProps){var Ee=v.defaultProps;for(_e in Ee)fe[_e]===void 0&&(fe[_e]=Ee[_e])}if(le||We){var Re=typeof v=="function"?v.displayName||v.name||"Unknown":v;le&&Rs(fe,Re),We&&Cs(fe,Re)}return As(v,le,We,de,X,be.current,fe)}}var M=y.ReactCurrentOwner,te=y.ReactDebugCurrentFrame;function ue(v){if(v){var I=v._owner,q=Xe(v.type,v._source,I?I.type:null);te.setExtraStackFrame(q)}else te.setExtraStackFrame(null)}var me;me=!1;function Ge(v){return typeof v=="object"&&v!==null&&v.$$typeof===e}function Ft(){{if(M.current){var v=A(M.current.type);if(v)return`
17
+ */var fi;function Co(){return fi||(fi=1,process.env.NODE_ENV!=="production"&&function(){var t=p,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"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),g=Symbol.for("react.lazy"),f=Symbol.for("react.offscreen"),y=Symbol.iterator,b="@@iterator";function _(m){if(m===null||typeof m!="object")return null;var P=y&&m[y]||m[b];return typeof P=="function"?P:null}var v=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function S(m){{for(var P=arguments.length,q=new Array(P>1?P-1:0),X=1;X<P;X++)q[X-1]=arguments[X];j("error",m,q)}}function j(m,P,q){{var X=v.ReactDebugCurrentFrame,de=X.getStackAddendum();de!==""&&(P+="%s",q=q.concat([de]));var _e=q.map(function(he){return String(he)});_e.unshift("Warning: "+P),Function.prototype.apply.call(console[m],console,_e)}}var x=!1,A=!1,k=!1,F=!1,E=!1,O;O=Symbol.for("react.module.reference");function T(m){return!!(typeof m=="string"||typeof m=="function"||m===s||m===i||E||m===n||m===u||m===d||F||m===f||x||A||k||typeof m=="object"&&m!==null&&(m.$$typeof===g||m.$$typeof===h||m.$$typeof===a||m.$$typeof===o||m.$$typeof===c||m.$$typeof===O||m.getModuleId!==void 0))}function R(m,P,q){var X=m.displayName;if(X)return X;var de=P.displayName||P.name||"";return de!==""?q+"("+de+")":q}function N(m){return m.displayName||"Context"}function C(m){if(m==null)return null;if(typeof m.tag=="number"&&S("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof m=="function")return m.displayName||m.name||null;if(typeof m=="string")return m;switch(m){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 m=="object")switch(m.$$typeof){case o:var P=m;return N(P)+".Consumer";case a:var q=m;return N(q._context)+".Provider";case c:return R(m,m.render,"ForwardRef");case h:var X=m.displayName||null;return X!==null?X:C(m.type)||"Memo";case g:{var de=m,_e=de._payload,he=de._init;try{return C(he(_e))}catch{return null}}}return null}var L=Object.assign,K=0,H,Y,Z,W,V,ge,te;function ie(){}ie.__reactDisabledLog=!0;function ve(){{if(K===0){H=console.log,Y=console.info,Z=console.warn,W=console.error,V=console.group,ge=console.groupCollapsed,te=console.groupEnd;var m={configurable:!0,enumerable:!0,value:ie,writable:!0};Object.defineProperties(console,{info:m,log:m,warn:m,error:m,group:m,groupCollapsed:m,groupEnd:m})}K++}}function $(){{if(K--,K===0){var m={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:L({},m,{value:H}),info:L({},m,{value:Y}),warn:L({},m,{value:Z}),error:L({},m,{value:W}),group:L({},m,{value:V}),groupCollapsed:L({},m,{value:ge}),groupEnd:L({},m,{value:te})})}K<0&&S("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var ae=v.ReactCurrentDispatcher,J;function B(m,P,q){{if(J===void 0)try{throw Error()}catch(de){var X=de.stack.trim().match(/\n( *(at )?)/);J=X&&X[1]||""}return`
18
+ `+J+m}}var Se=!1,ke;{var we=typeof WeakMap=="function"?WeakMap:Map;ke=new we}function je(m,P){if(!m||Se)return"";{var q=ke.get(m);if(q!==void 0)return q}var X;Se=!0;var de=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var _e;_e=ae.current,ae.current=null,ve();try{if(P){var he=function(){throw Error()};if(Object.defineProperty(he.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(he,[])}catch(Oe){X=Oe}Reflect.construct(m,[],he)}else{try{he.call()}catch(Oe){X=Oe}m.call(he.prototype)}}else{try{throw Error()}catch(Oe){X=Oe}m()}}catch(Oe){if(Oe&&X&&typeof Oe.stack=="string"){for(var le=Oe.stack.split(`
19
+ `),Me=X.stack.split(`
20
+ `),Ee=le.length-1,Re=Me.length-1;Ee>=1&&Re>=0&&le[Ee]!==Me[Re];)Re--;for(;Ee>=1&&Re>=0;Ee--,Re--)if(le[Ee]!==Me[Re]){if(Ee!==1||Re!==1)do if(Ee--,Re--,Re<0||le[Ee]!==Me[Re]){var Ge=`
21
+ `+le[Ee].replace(" at new "," at ");return m.displayName&&Ge.includes("<anonymous>")&&(Ge=Ge.replace("<anonymous>",m.displayName)),typeof m=="function"&&ke.set(m,Ge),Ge}while(Ee>=1&&Re>=0);break}}}finally{Se=!1,ae.current=_e,$(),Error.prepareStackTrace=de}var Rt=m?m.displayName||m.name:"",Je=Rt?B(Rt):"";return typeof m=="function"&&ke.set(m,Je),Je}function Fe(m,P,q){return je(m,!1)}function $e(m){var P=m.prototype;return!!(P&&P.isReactComponent)}function Ye(m,P,q){if(m==null)return"";if(typeof m=="function")return je(m,$e(m));if(typeof m=="string")return B(m);switch(m){case u:return B("Suspense");case d:return B("SuspenseList")}if(typeof m=="object")switch(m.$$typeof){case c:return Fe(m.render);case h:return Ye(m.type,P,q);case g:{var X=m,de=X._payload,_e=X._init;try{return Ye(_e(de),P,q)}catch{}}}return""}var qe=Object.prototype.hasOwnProperty,et={},it=v.ReactDebugCurrentFrame;function De(m){if(m){var P=m._owner,q=Ye(m.type,m._source,P?P.type:null);it.setExtraStackFrame(q)}else it.setExtraStackFrame(null)}function I(m,P,q,X,de){{var _e=Function.call.bind(qe);for(var he in m)if(_e(m,he)){var le=void 0;try{if(typeof m[he]!="function"){var Me=Error((X||"React class")+": "+q+" type `"+he+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof m[he]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw Me.name="Invariant Violation",Me}le=m[he](P,he,X,q,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(Ee){le=Ee}le&&!(le instanceof Error)&&(De(de),S("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",X||"React class",q,he,typeof le),De(null)),le instanceof Error&&!(le.message in et)&&(et[le.message]=!0,De(de),S("Failed %s type: %s",q,le.message),De(null))}}}var oe=Array.isArray;function Ae(m){return oe(m)}function M(m){{var P=typeof Symbol=="function"&&Symbol.toStringTag,q=P&&m[Symbol.toStringTag]||m.constructor.name||"Object";return q}}function ce(m){try{return Ce(m),!1}catch{return!0}}function Ce(m){return""+m}function Xe(m){if(ce(m))return S("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",M(m)),Ce(m)}var be=v.ReactCurrentOwner,rr={key:!0,ref:!0,__self:!0,__source:!0},Ue,Xr;function li(m){if(qe.call(m,"ref")){var P=Object.getOwnPropertyDescriptor(m,"ref").get;if(P&&P.isReactWarning)return!1}return m.ref!==void 0}function ci(m){if(qe.call(m,"key")){var P=Object.getOwnPropertyDescriptor(m,"key").get;if(P&&P.isReactWarning)return!1}return m.key!==void 0}function ui(m,P){typeof m.ref=="string"&&be.current}function Ns(m,P){{var q=function(){Ue||(Ue=!0,S("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",P))};q.isReactWarning=!0,Object.defineProperty(m,"key",{get:q,configurable:!0})}}function Is(m,P){{var q=function(){Xr||(Xr=!0,S("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",P))};q.isReactWarning=!0,Object.defineProperty(m,"ref",{get:q,configurable:!0})}}var Bs=function(m,P,q,X,de,_e,he){var le={$$typeof:e,type:m,key:P,ref:q,props:he,_owner:_e};return le._store={},Object.defineProperty(le._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(le,"_self",{configurable:!1,enumerable:!1,writable:!1,value:X}),Object.defineProperty(le,"_source",{configurable:!1,enumerable:!1,writable:!1,value:de}),Object.freeze&&(Object.freeze(le.props),Object.freeze(le)),le};function Fs(m,P,q,X,de){{var _e,he={},le=null,Me=null;q!==void 0&&(Xe(q),le=""+q),ci(P)&&(Xe(P.key),le=""+P.key),li(P)&&(Me=P.ref,ui(P,de));for(_e in P)qe.call(P,_e)&&!rr.hasOwnProperty(_e)&&(he[_e]=P[_e]);if(m&&m.defaultProps){var Ee=m.defaultProps;for(_e in Ee)he[_e]===void 0&&(he[_e]=Ee[_e])}if(le||Me){var Re=typeof m=="function"?m.displayName||m.name||"Unknown":m;le&&Ns(he,Re),Me&&Is(he,Re)}return Bs(m,le,Me,de,X,be.current,he)}}var U=v.ReactCurrentOwner,re=v.ReactDebugCurrentFrame;function ue(m){if(m){var P=m._owner,q=Ye(m.type,m._source,P?P.type:null);re.setExtraStackFrame(q)}else re.setExtraStackFrame(null)}var me;me=!1;function Ve(m){return typeof m=="object"&&m!==null&&m.$$typeof===e}function $t(){{if(U.current){var m=C(U.current.type);if(m)return`
22
22
 
23
- Check the render method of \``+v+"`."}return""}}function tr(v){return""}var $t={};function _r(v){{var I=Ft();if(!I){var q=typeof v=="string"?v:v.displayName||v.name;q&&(I=`
23
+ Check the render method of \``+m+"`."}return""}}function sr(m){return""}var Dt={};function kr(m){{var P=$t();if(!P){var q=typeof m=="string"?m:m.displayName||m.name;q&&(P=`
24
24
 
25
- Check the top-level render call using <`+q+">.")}return I}}function Dt(v,I){{if(!v._store||v._store.validated||v.key!=null)return;v._store.validated=!0;var q=_r(I);if($t[q])return;$t[q]=!0;var X="";v&&v._owner&&v._owner!==M.current&&(X=" It was passed a child from "+A(v._owner.type)+"."),ue(v),k('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',q,X),ue(null)}}function Lt(v,I){{if(typeof v!="object")return;if(Ce(v))for(var q=0;q<v.length;q++){var X=v[q];Ge(X)&&Dt(X,I)}else if(Ge(v))v._store&&(v._store.validated=!0);else if(v){var de=_(v);if(typeof de=="function"&&de!==v.entries)for(var _e=de.call(v),fe;!(fe=_e.next()).done;)Ge(fe.value)&&Dt(fe.value,I)}}}function gt(v){{var I=v.type;if(I==null||typeof I=="string")return;var q;if(typeof I=="function")q=I.propTypes;else if(typeof I=="object"&&(I.$$typeof===c||I.$$typeof===h))q=I.propTypes;else return;if(q){var X=A(I);N(q,v.props,"prop",X,v)}else if(I.PropTypes!==void 0&&!me){me=!0;var de=A(I);k("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",de||"Unknown")}typeof I.getDefaultProps=="function"&&!I.getDefaultProps.isReactClassApproved&&k("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function kr(v){{for(var I=Object.keys(v.props),q=0;q<I.length;q++){var X=I[q];if(X!=="children"&&X!=="key"){ue(v),k("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",X),ue(null);break}}v.ref!==null&&(ue(v),k("Invalid attribute `ref` supplied to `React.Fragment`."),ue(null))}}var rr={};function bt(v,I,q,X,de,_e){{var fe=C(v);if(!fe){var le="";(v===void 0||typeof v=="object"&&v!==null&&Object.keys(v).length===0)&&(le+=" 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 We=tr();We?le+=We:le+=Ft();var Ee;v===null?Ee="null":Ce(v)?Ee="array":v!==void 0&&v.$$typeof===e?(Ee="<"+(A(v.type)||"Unknown")+" />",le=" Did you accidentally export a JSX literal instead of a component?"):Ee=typeof v,k("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",Ee,le)}var Re=Os(v,I,q,de,_e);if(Re==null)return Re;if(fe){var Je=I.children;if(Je!==void 0)if(X)if(Ce(Je)){for(var Tt=0;Tt<Je.length;Tt++)Lt(Je[Tt],v);Object.freeze&&Object.freeze(Je)}else k("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 Lt(Je,v)}if(ze.call(I,"key")){var Qe=A(v),Oe=Object.keys(I).filter(function(at){return at!=="key"}),dt=Oe.length>0?"{key: someKey, "+Oe.join(": ..., ")+": ...}":"{key: someKey}";if(!rr[Qe+dt]){var Rt=Oe.length>0?"{"+Oe.join(": ..., ")+": ...}":"{}";k(`A props object containing a "key" prop is being spread into JSX:
25
+ Check the top-level render call using <`+q+">.")}return P}}function Ut(m,P){{if(!m._store||m._store.validated||m.key!=null)return;m._store.validated=!0;var q=kr(P);if(Dt[q])return;Dt[q]=!0;var X="";m&&m._owner&&m._owner!==U.current&&(X=" It was passed a child from "+C(m._owner.type)+"."),ue(m),S('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',q,X),ue(null)}}function Mt(m,P){{if(typeof m!="object")return;if(Ae(m))for(var q=0;q<m.length;q++){var X=m[q];Ve(X)&&Ut(X,P)}else if(Ve(m))m._store&&(m._store.validated=!0);else if(m){var de=_(m);if(typeof de=="function"&&de!==m.entries)for(var _e=de.call(m),he;!(he=_e.next()).done;)Ve(he.value)&&Ut(he.value,P)}}}function gt(m){{var P=m.type;if(P==null||typeof P=="string")return;var q;if(typeof P=="function")q=P.propTypes;else if(typeof P=="object"&&(P.$$typeof===c||P.$$typeof===h))q=P.propTypes;else return;if(q){var X=C(P);I(q,m.props,"prop",X,m)}else if(P.PropTypes!==void 0&&!me){me=!0;var de=C(P);S("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",de||"Unknown")}typeof P.getDefaultProps=="function"&&!P.getDefaultProps.isReactClassApproved&&S("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Sr(m){{for(var P=Object.keys(m.props),q=0;q<P.length;q++){var X=P[q];if(X!=="children"&&X!=="key"){ue(m),S("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",X),ue(null);break}}m.ref!==null&&(ue(m),S("Invalid attribute `ref` supplied to `React.Fragment`."),ue(null))}}var nr={};function bt(m,P,q,X,de,_e){{var he=T(m);if(!he){var le="";(m===void 0||typeof m=="object"&&m!==null&&Object.keys(m).length===0)&&(le+=" 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 Me=sr();Me?le+=Me:le+=$t();var Ee;m===null?Ee="null":Ae(m)?Ee="array":m!==void 0&&m.$$typeof===e?(Ee="<"+(C(m.type)||"Unknown")+" />",le=" Did you accidentally export a JSX literal instead of a component?"):Ee=typeof m,S("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",Ee,le)}var Re=Fs(m,P,q,de,_e);if(Re==null)return Re;if(he){var Ge=P.children;if(Ge!==void 0)if(X)if(Ae(Ge)){for(var Rt=0;Rt<Ge.length;Rt++)Mt(Ge[Rt],m);Object.freeze&&Object.freeze(Ge)}else S("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Mt(Ge,m)}if(qe.call(P,"key")){var Je=C(m),Oe=Object.keys(P).filter(function(at){return at!=="key"}),dt=Oe.length>0?"{key: someKey, "+Oe.join(": ..., ")+": ...}":"{key: someKey}";if(!nr[Je+dt]){var At=Oe.length>0?"{"+Oe.join(": ..., ")+": ...}":"{}";S(`A props object containing a "key" prop is being spread into JSX:
26
26
  let props = %s;
27
27
  <%s {...props} />
28
28
  React keys must be passed directly to JSX without using spread:
29
29
  let props = %s;
30
- <%s key={someKey} {...props} />`,dt,Qe,Rt,Qe),rr[Qe+dt]=!0}}return v===s?kr(Re):gt(Re),Re}}function Sr(v,I,q){return bt(v,I,q,!0)}function Er(v,I,q){return bt(v,I,q,!1)}var Ut=Er,ut=Sr;Zr.Fragment=s,Zr.jsx=Ut,Zr.jsxs=ut}()),Zr}process.env.NODE_ENV==="production"?pn.exports=go():pn.exports=bo();var o=pn.exports;function Vs(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 mo(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 l(d){try{u(s.next(d))}catch(h){a(h)}}function c(d){try{u(s.throw(d))}catch(h){a(h)}}function u(d){d.done?i(d.value):n(d.value).then(l,c)}u((s=s.apply(t,e||[])).next())})}const yo=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class qn extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}}class vo extends qn{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class ai extends qn{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class oi extends qn{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var gn;(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"})(gn||(gn={}));class wo{constructor(e,{headers:r={},customFetch:s,region:n=gn.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=yo(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return mo(this,arguments,void 0,function*(r,s={}){var n;let i,a;try{const{headers:l,method:c,body:u,signal:d,timeout:h}=s;let g={},{region:f}=s;f||(f=this.region);const m=new URL(`${this.url}/${r}`);f&&f!=="any"&&(g["x-region"]=f,m.searchParams.set("forceFunctionRegion",f));let b;u&&(l&&!Object.prototype.hasOwnProperty.call(l,"Content-Type")||!l)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(g["Content-Type"]="application/octet-stream",b=u):typeof u=="string"?(g["Content-Type"]="text/plain",b=u):typeof FormData<"u"&&u instanceof FormData?b=u:(g["Content-Type"]="application/json",b=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?b=JSON.stringify(u):b=u;let _=d;h&&(a=new AbortController,i=setTimeout(()=>a.abort(),h),d?(_=a.signal,d.addEventListener("abort",()=>a.abort())):_=a.signal);const y=yield this.fetch(m.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},g),this.headers),l),body:b,signal:_}).catch(T=>{throw new vo(T)}),k=y.headers.get("x-relay-error");if(k&&k==="true")throw new ai(y);if(!y.ok)throw new oi(y);let j=((n=y.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),x;return j==="application/json"?x=yield y.json():j==="application/octet-stream"||j==="application/pdf"?x=yield y.blob():j==="text/event-stream"?x=y:j==="multipart/form-data"?x=yield y.formData():x=yield y.text(),{data:x,error:null,response:y}}catch(l){return{data:null,error:l,response:l instanceof oi||l instanceof ai?l.context:void 0}}finally{i&&clearTimeout(i)}})}}var xo=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},_o=class{constructor(t){var e,r,s;this.shouldThrowOnError=!1,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.urlLengthLimit=(s=t.urlLengthLimit)!==null&&s!==void 0?s:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;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");const s=this.fetch;let n=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let a=null,l=null,c=null,u=i.status,d=i.statusText;if(i.ok){var h,g;if(r.method!=="HEAD"){var f;const y=await i.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((f=r.headers.get("Accept"))===null||f===void 0)&&f.includes("application/vnd.pgrst.plan+text"))?l=y:l=JSON.parse(y))}const b=(h=r.headers.get("Prefer"))===null||h===void 0?void 0:h.match(/count=(exact|planned|estimated)/),_=(g=i.headers.get("content-range"))===null||g===void 0?void 0:g.split("/");b&&_&&_.length>1&&(c=parseInt(_[1])),r.isMaybeSingle&&r.method==="GET"&&Array.isArray(l)&&(l.length>1?(a={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,c=null,u=406,d="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{var m;const b=await i.text();try{a=JSON.parse(b),Array.isArray(a)&&i.status===404&&(l=[],a=null,u=200,d="OK")}catch{i.status===404&&b===""?(u=204,d="No Content"):a={message:b}}if(a&&r.isMaybeSingle&&(!(a==null||(m=a.details)===null||m===void 0)&&m.includes("0 rows"))&&(a=null,u=200,d="OK"),a&&r.shouldThrowOnError)throw new xo(a)}return{error:a,data:l,count:c,status:u,statusText:d}});return this.shouldThrowOnError||(n=n.catch(i=>{var a;let l="",c="",u="";const d=i==null?void 0:i.cause;if(d){var h,g,f,m;const y=(h=d==null?void 0:d.message)!==null&&h!==void 0?h:"",k=(g=d==null?void 0:d.code)!==null&&g!==void 0?g:"";l=`${(f=i==null?void 0:i.name)!==null&&f!==void 0?f:"FetchError"}: ${i==null?void 0:i.message}`,l+=`
30
+ <%s key={someKey} {...props} />`,dt,Je,At,Je),nr[Je+dt]=!0}}return m===s?Sr(Re):gt(Re),Re}}function Er(m,P,q){return bt(m,P,q,!0)}function jr(m,P,q){return bt(m,P,q,!1)}var Wt=jr,ut=Er;ts.Fragment=s,ts.jsx=Wt,ts.jsxs=ut}()),ts}process.env.NODE_ENV==="production"?xn.exports=Ao():xn.exports=Co();var l=xn.exports;function rn(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 Oo(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 c(d){try{u(s.throw(d))}catch(h){a(h)}}function u(d){d.done?i(d.value):n(d.value).then(o,c)}u((s=s.apply(t,e||[])).next())})}const Po=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class Yn extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}}class No extends Yn{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class pi extends Yn{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class gi extends Yn{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var _n;(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"})(_n||(_n={}));class Io{constructor(e,{headers:r={},customFetch:s,region:n=_n.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=Po(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Oo(this,arguments,void 0,function*(r,s={}){var n;let i,a;try{const{headers:o,method:c,body:u,signal:d,timeout:h}=s;let g={},{region:f}=s;f||(f=this.region);const y=new URL(`${this.url}/${r}`);f&&f!=="any"&&(g["x-region"]=f,y.searchParams.set("forceFunctionRegion",f));let b;u&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(g["Content-Type"]="application/octet-stream",b=u):typeof u=="string"?(g["Content-Type"]="text/plain",b=u):typeof FormData<"u"&&u instanceof FormData?b=u:(g["Content-Type"]="application/json",b=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?b=JSON.stringify(u):b=u;let _=d;h&&(a=new AbortController,i=setTimeout(()=>a.abort(),h),d?(_=a.signal,d.addEventListener("abort",()=>a.abort())):_=a.signal);const v=yield this.fetch(y.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},g),this.headers),o),body:b,signal:_}).catch(A=>{throw new No(A)}),S=v.headers.get("x-relay-error");if(S&&S==="true")throw new pi(v);if(!v.ok)throw new gi(v);let j=((n=v.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),x;return j==="application/json"?x=yield v.json():j==="application/octet-stream"||j==="application/pdf"?x=yield v.blob():j==="text/event-stream"?x=v:j==="multipart/form-data"?x=yield v.formData():x=yield v.text(),{data:x,error:null,response:v}}catch(o){return{data:null,error:o,response:o instanceof gi||o instanceof pi?o.context:void 0}}finally{i&&clearTimeout(i)}})}}var Bo=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Fo=class{constructor(t){var e,r,s;this.shouldThrowOnError=!1,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.urlLengthLimit=(s=t.urlLengthLimit)!==null&&s!==void 0?s:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;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");const s=this.fetch;let n=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let a=null,o=null,c=null,u=i.status,d=i.statusText;if(i.ok){var h,g;if(r.method!=="HEAD"){var f;const v=await i.text();v===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((f=r.headers.get("Accept"))===null||f===void 0)&&f.includes("application/vnd.pgrst.plan+text"))?o=v:o=JSON.parse(v))}const b=(h=r.headers.get("Prefer"))===null||h===void 0?void 0:h.match(/count=(exact|planned|estimated)/),_=(g=i.headers.get("content-range"))===null||g===void 0?void 0:g.split("/");b&&_&&_.length>1&&(c=parseInt(_[1])),r.isMaybeSingle&&r.method==="GET"&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,c=null,u=406,d="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{var y;const b=await i.text();try{a=JSON.parse(b),Array.isArray(a)&&i.status===404&&(o=[],a=null,u=200,d="OK")}catch{i.status===404&&b===""?(u=204,d="No Content"):a={message:b}}if(a&&r.isMaybeSingle&&(!(a==null||(y=a.details)===null||y===void 0)&&y.includes("0 rows"))&&(a=null,u=200,d="OK"),a&&r.shouldThrowOnError)throw new Bo(a)}return{error:a,data:o,count:c,status:u,statusText:d}});return this.shouldThrowOnError||(n=n.catch(i=>{var a;let o="",c="",u="";const d=i==null?void 0:i.cause;if(d){var h,g,f,y;const v=(h=d==null?void 0:d.message)!==null&&h!==void 0?h:"",S=(g=d==null?void 0:d.code)!==null&&g!==void 0?g:"";o=`${(f=i==null?void 0:i.name)!==null&&f!==void 0?f:"FetchError"}: ${i==null?void 0:i.message}`,o+=`
31
31
 
32
- Caused by: ${(m=d==null?void 0:d.name)!==null&&m!==void 0?m:"Error"}: ${y}`,k&&(l+=` (${k})`),d!=null&&d.stack&&(l+=`
33
- ${d.stack}`)}else{var b;l=(b=i==null?void 0:i.stack)!==null&&b!==void 0?b:""}const _=this.url.toString().length;return(i==null?void 0:i.name)==="AbortError"||(i==null?void 0:i.code)==="ABORT_ERR"?(u="",c="Request was aborted (timeout or manual cancellation)",_>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${_} 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.`)):((d==null?void 0:d.name)==="HeadersOverflowError"||(d==null?void 0:d.code)==="UND_ERR_HEADERS_OVERFLOW")&&(u="",c="HTTP headers exceeded server limits (typically 16KB)",_>this.urlLengthLimit&&(c+=`. Your request URL is ${_} 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.`)),{error:{message:`${(a=i==null?void 0:i.name)!==null&&a!==void 0?a:"FetchError"}: ${i==null?void 0:i.message}`,details:l,hint:c,code:u},data:null,count:null,status:0,statusText:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},ko=class extends _o{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.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),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 l=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${c}"; options=${l};`),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 li=new RegExp("[,()]");var Pr=class extends ko{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"&&li.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"&&li.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}},So=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:n=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=s,this.urlLengthLimit=n}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:l,headers:c}=this.cloneRequestState();return l.searchParams.set("select",a),s&&c.append("Prefer",`count=${s}`),new Pr({method:n,url:l,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}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 l=t.reduce((c,u)=>c.concat(Object.keys(u)),[]);if(l.length>0){const c=[...new Set(l)].map(u=>`"${u}"`);i.searchParams.set("columns",c.join(","))}}return new Pr({method:n,url:i,headers:a,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var i;const a="POST",{url:l,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&l.searchParams.set("on_conflict",e),s&&c.append("Prefer",`count=${s}`),n||c.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}"`);l.searchParams.set("columns",d.join(","))}}return new Pr({method:a,url:l,headers:c,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;const s="PATCH",{url:n,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Pr({method:s,url:n,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;const r="DELETE",{url:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new Pr({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function cs(t){"@babel/helpers - typeof";return cs=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},cs(t)}function Eo(t,e){if(cs(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(cs(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function jo(t){var e=Eo(t,"string");return cs(e)=="symbol"?e:e+""}function To(t,e,r){return(e=jo(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function ci(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 Ns(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?ci(Object(r),!0).forEach(function(s){To(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):ci(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Ro=class ia{constructor(e,{headers:r={},schema:s,fetch:n,timeout:i,urlLengthLimit:a=8e3}={}){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=(c,u)=>{const d=new AbortController,h=setTimeout(()=>d.abort(),i),g=u==null?void 0:u.signal;if(g){if(g.aborted)return clearTimeout(h),l(c,u);const f=()=>{clearTimeout(h),d.abort()};return g.addEventListener("abort",f,{once:!0}),l(c,Ns(Ns({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(h),g.removeEventListener("abort",f)})}return l(c,Ns(Ns({},u),{},{signal:d.signal})).finally(()=>clearTimeout(h))}:this.fetch=l}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new So(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new ia(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:s=!1,get:n=!1,count:i}={}){var a;let l;const c=new URL(`${this.url}/rpc/${e}`);let u;const d=f=>f!==null&&typeof f=="object"&&(!Array.isArray(f)||f.some(d)),h=s&&Object.values(r).some(d);h?(l="POST",u=r):s||n?(l=s?"HEAD":"GET",Object.entries(r).filter(([f,m])=>m!==void 0).map(([f,m])=>[f,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([f,m])=>{c.searchParams.append(f,m)})):(l="POST",u=r);const g=new Headers(this.headers);return h?g.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&g.set("Prefer",`count=${i}`),new Pr({method:l,url:c,headers:g,schema:this.schemaName,body:u,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};class Co{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const r=globalThis.process;if(r){const s=r.versions;if(s&&s.node){const n=s.node,i=parseInt(n.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
32
+ Caused by: ${(y=d==null?void 0:d.name)!==null&&y!==void 0?y:"Error"}: ${v}`,S&&(o+=` (${S})`),d!=null&&d.stack&&(o+=`
33
+ ${d.stack}`)}else{var b;o=(b=i==null?void 0:i.stack)!==null&&b!==void 0?b:""}const _=this.url.toString().length;return(i==null?void 0:i.name)==="AbortError"||(i==null?void 0:i.code)==="ABORT_ERR"?(u="",c="Request was aborted (timeout or manual cancellation)",_>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${_} 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.`)):((d==null?void 0:d.name)==="HeadersOverflowError"||(d==null?void 0:d.code)==="UND_ERR_HEADERS_OVERFLOW")&&(u="",c="HTTP headers exceeded server limits (typically 16KB)",_>this.urlLengthLimit&&(c+=`. Your request URL is ${_} 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.`)),{error:{message:`${(a=i==null?void 0:i.name)!==null&&a!==void 0?a:"FetchError"}: ${i==null?void 0:i.message}`,details:o,hint:c,code:u},data:null,count:null,status:0,statusText:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},Lo=class extends Fo{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.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),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("|"),c=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${c}"; 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 bi=new RegExp("[,()]");var Ir=class extends Lo{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"&&bi.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"&&bi.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}},$o=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:n=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=s,this.urlLengthLimit=n}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:c}=this.cloneRequestState();return o.searchParams.set("select",a),s&&c.append("Prefer",`count=${s}`),new Ir({method:n,url:o,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}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((c,u)=>c.concat(Object.keys(u)),[]);if(o.length>0){const c=[...new Set(o)].map(u=>`"${u}"`);i.searchParams.set("columns",c.join(","))}}return new Ir({method:n,url:i,headers:a,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var i;const a="POST",{url:o,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&c.append("Prefer",`count=${s}`),n||c.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 Ir({method:a,url:o,headers:c,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;const s="PATCH",{url:n,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Ir({method:s,url:n,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;const r="DELETE",{url:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new Ir({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function ps(t){"@babel/helpers - typeof";return ps=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},ps(t)}function Do(t,e){if(ps(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(ps(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Uo(t){var e=Do(t,"string");return ps(e)=="symbol"?e:e+""}function Mo(t,e,r){return(e=Uo(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function mi(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 Ds(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?mi(Object(r),!0).forEach(function(s){Mo(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):mi(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Wo=class ga{constructor(e,{headers:r={},schema:s,fetch:n,timeout:i,urlLengthLimit:a=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.urlLengthLimit=a;const o=n??globalThis.fetch;i!==void 0&&i>0?this.fetch=(c,u)=>{const d=new AbortController,h=setTimeout(()=>d.abort(),i),g=u==null?void 0:u.signal;if(g){if(g.aborted)return clearTimeout(h),o(c,u);const f=()=>{clearTimeout(h),d.abort()};return g.addEventListener("abort",f,{once:!0}),o(c,Ds(Ds({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(h),g.removeEventListener("abort",f)})}return o(c,Ds(Ds({},u),{},{signal:d.signal})).finally(()=>clearTimeout(h))}:this.fetch=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 $o(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new ga(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:s=!1,get:n=!1,count:i}={}){var a;let o;const c=new URL(`${this.url}/rpc/${e}`);let u;const d=f=>f!==null&&typeof f=="object"&&(!Array.isArray(f)||f.some(d)),h=s&&Object.values(r).some(d);h?(o="POST",u=r):s||n?(o=s?"HEAD":"GET",Object.entries(r).filter(([f,y])=>y!==void 0).map(([f,y])=>[f,Array.isArray(y)?`{${y.join(",")}}`:`${y}`]).forEach(([f,y])=>{c.searchParams.append(f,y)})):(o="POST",u=r);const g=new Headers(this.headers);return h?g.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&g.set("Prefer",`count=${i}`),new Ir({method:o,url:c,headers:g,schema:this.schemaName,body:u,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};class qo{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const r=globalThis.process;if(r){const s=r.versions;if(s&&s.node){const n=s.node,i=parseInt(n.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
34
34
  import ws from "ws"
35
35
  new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
36
36
 
37
- Suggested solution: ${e.workaround}`),new Error(r)}static createWebSocket(e,r){const s=this.getWebSocketConstructor();return new s(e,r)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const Ao="2.99.3",Oo=`realtime-js/${Ao}`,Po="1.0.0",aa="2.0.0",ui=aa,bn=1e4,Io=1e3,No=100;var zt;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(zt||(zt={}));var De;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(De||(De={}));var xt;(function(t){t.close="phx_close",t.error="phx_error",t.join="phx_join",t.reply="phx_reply",t.leave="phx_leave",t.access_token="access_token"})(xt||(xt={}));var mn;(function(t){t.websocket="websocket"})(mn||(mn={}));var or;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(or||(or={}));class Bo{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=e.topic,l=(n=e.ref)!==null&&n!==void 0?n:"",c=(i=e.join_ref)!==null&&i!==void 0?i:"",u=e.payload.event,d=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=Object.keys(d).length===0?"":JSON.stringify(d);if(c.length>255)throw new Error(`joinRef length ${c.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`ref length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`topic length ${a.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const g=this.USER_BROADCAST_PUSH_META_LENGTH+c.length+l.length+a.length+u.length+h.length,f=new ArrayBuffer(this.HEADER_LENGTH+g);let m=new DataView(f),b=0;m.setUint8(b++,this.KINDS.userBroadcastPush),m.setUint8(b++,c.length),m.setUint8(b++,l.length),m.setUint8(b++,a.length),m.setUint8(b++,u.length),m.setUint8(b++,h.length),m.setUint8(b++,r),Array.from(c,y=>m.setUint8(b++,y.charCodeAt(0))),Array.from(l,y=>m.setUint8(b++,y.charCodeAt(0))),Array.from(a,y=>m.setUint8(b++,y.charCodeAt(0))),Array.from(u,y=>m.setUint8(b++,y.charCodeAt(0))),Array.from(h,y=>m.setUint8(b++,y.charCodeAt(0)));var _=new Uint8Array(f.byteLength+s.byteLength);return _.set(new Uint8Array(f),0),_.set(new Uint8Array(s),f.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,l,c]=s;return r({join_ref:n,ref:i,topic:a,event:l,payload:c})}return r({})}_binaryDecode(e){const r=new DataView(e),s=r.getUint8(0),n=new TextDecoder;switch(s){case 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),l=r.getUint8(4);let c=this.HEADER_LENGTH+4;const u=s.decode(e.slice(c,c+n));c=c+n;const d=s.decode(e.slice(c,c+i));c=c+i;const h=s.decode(e.slice(c,c+a));c=c+a;const g=e.slice(c,e.byteLength),f=l===this.JSON_ENCODING?JSON.parse(s.decode(g)):g,m={type:this.BROADCAST_EVENT,event:d,payload:f};return a>0&&(m.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:m}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e==null?void 0: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)))}}class oa{constructor(e,r){this.callback=e,this.timerCalc=r,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=r}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var Te;(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"})(Te||(Te={}));const di=(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]=Fo(a,t,e,n),i),{}):{}},Fo=(t,e,r,s)=>{const n=e.find(l=>l.name===t),i=n==null?void 0:n.type,a=r[t];return i&&!s.includes(i)?la(i,a):yn(a)},la=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return Uo(e,r)}switch(t){case Te.bool:return $o(e);case Te.float4:case Te.float8:case Te.int2:case Te.int4:case Te.int8:case Te.numeric:case Te.oid:return Do(e);case Te.json:case Te.jsonb:return Lo(e);case Te.timestamp:return Mo(e);case Te.abstime:case Te.date:case Te.daterange:case Te.int4range:case Te.int8range:case Te.money:case Te.reltime:case Te.text:case Te.time:case Te.timestamptz:case Te.timetz:case Te.tsrange:case Te.tstzrange:return yn(e);default:return yn(e)}},yn=t=>t,$o=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},Do=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},Lo=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Uo=(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(l=>la(e,l))}return t},Mo=t=>typeof t=="string"?t.replace(" ","T"):t,ca=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};class sn{constructor(e,r,s={},n=bn){this.channel=e,this.event=r,this.payload=s,this.timeout=n,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,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()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,r){var s;return this._hasReceived(e)&&r((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:r})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:r}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(r))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var hi;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(hi||(hi={}));class as{constructor(e,r){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const s=(r==null?void 0:r.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},n=>{const{onJoin:i,onLeave:a,onSync:l}=this.caller;this.joinRef=this.channel._joinRef(),this.state=as.syncState(this.state,n,i,a),this.pendingDiffs.forEach(c=>{this.state=as.syncDiff(this.state,c,i,a)}),this.pendingDiffs=[],l()}),this.channel._on(s.diff,{},n=>{const{onJoin:i,onLeave:a,onSync:l}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=as.syncDiff(this.state,n,i,a),l())}),this.onJoin((n,i,a)=>{this.channel._trigger("presence",{event:"join",key:n,currentPresences:i,newPresences:a})}),this.onLeave((n,i,a)=>{this.channel._trigger("presence",{event:"leave",key:n,currentPresences:i,leftPresences:a})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,r,s,n){const i=this.cloneDeep(e),a=this.transformState(r),l={},c={};return this.map(i,(u,d)=>{a[u]||(c[u]=d)}),this.map(a,(u,d)=>{const h=i[u];if(h){const g=d.map(_=>_.presence_ref),f=h.map(_=>_.presence_ref),m=d.filter(_=>f.indexOf(_.presence_ref)<0),b=h.filter(_=>g.indexOf(_.presence_ref)<0);m.length>0&&(l[u]=m),b.length>0&&(c[u]=b)}else l[u]=d}),this.syncDiff(i,{joins:l,leaves:c},s,n)}static syncDiff(e,r,s,n){const{joins:i,leaves:a}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return s||(s=()=>{}),n||(n=()=>{}),this.map(i,(l,c)=>{var u;const d=(u=e[l])!==null&&u!==void 0?u:[];if(e[l]=this.cloneDeep(c),d.length>0){const h=e[l].map(f=>f.presence_ref),g=d.filter(f=>h.indexOf(f.presence_ref)<0);e[l].unshift(...g)}s(l,d,c)}),this.map(a,(l,c)=>{let u=e[l];if(!u)return;const d=c.map(h=>h.presence_ref);u=u.filter(h=>d.indexOf(h.presence_ref)<0),e[l]=u,n(l,u,c),u.length===0&&delete e[l]}),e}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{const n=e[s];return"metas"in n?r[s]=n.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):r[s]=n,r},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var fi;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(fi||(fi={}));var os;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(os||(os={}));var At;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(At||(At={}));class Br{constructor(e,r={config:{}},s){var n,i;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.state=De.closed,this.joinedOnce=!1,this.pushBuffer=[],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.timeout=this.socket.timeout,this.joinPush=new sn(this,xt.join,this.params,this.timeout),this.rejoinTimer=new oa(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=De.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(a=>a.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=De.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=De.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=De.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=De.errored,this.rejoinTimer.scheduleTimeout())}),this._on(xt.reply,{},(a,l)=>{this._trigger(this._replyEventName(l),a)}),this.presence=new as(this),this.broadcastEndpointURL=ca(this.socket.endPoint),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`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.state==De.closed){const{config:{broadcast:a,presence:l,private:c}}=this.params,u=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(f=>f.filter))!==null&&n!==void 0?n:[],d=!!this.bindings[os.PRESENCE]&&this.bindings[os.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,h={},g={broadcast:a,presence:Object.assign(Object.assign({},l),{enabled:d}),postgres_changes:u,private:c};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(f=>e==null?void 0:e(At.CHANNEL_ERROR,f)),this._onClose(()=>e==null?void 0:e(At.CLOSED)),this.updateJoinPayload(Object.assign({config:g},h)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:f})=>{var m;if(this.socket._isManualToken()||this.socket.setAuth(),f===void 0){e==null||e(At.SUBSCRIBED);return}else{const b=this.bindings.postgres_changes,_=(m=b==null?void 0:b.length)!==null&&m!==void 0?m:0,y=[];for(let k=0;k<_;k++){const j=b[k],{filter:{event:x,schema:T,table:S,filter:F}}=j,E=f&&f[k];if(E&&E.event===x&&Br.isFilterValueEqual(E.schema,T)&&Br.isFilterValueEqual(E.table,S)&&Br.isFilterValueEqual(E.filter,F))y.push(Object.assign(Object.assign({},j),{id:E.id}));else{this.unsubscribe(),this.state=De.errored,e==null||e(At.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=y,e&&e(At.SUBSCRIBED);return}}).receive("error",f=>{this.state=De.errored,e==null||e(At.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(At.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,s){return this.state===De.joined&&e===os.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,r,s)}async httpSend(e,r,s={}){var n;if(r==null)return Promise.reject("Payload is required for httpSend()");const i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);const a={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);if(l.status===202)return{success:!0};let c=l.statusText;try{const u=await l.json();c=u.error||u.message||c}catch{}return Promise.reject(new Error(c))}async send(e,r={}){var s,n;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:a}=e,l={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(l.Authorization=`Bearer ${this.socket.accessTokenValue}`);const c={method:"POST",headers:l,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:a,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var a,l,c;const u=this._push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(l=(a=this.params)===null||a===void 0?void 0:a.config)===null||l===void 0?void 0:l.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),u.receive("ok",()=>i("ok")),u.receive("error",()=>i("error")),u.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=De.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(xt.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(n=>{s=new sn(this,xt.leave,{},e),s.receive("ok",()=>{r(),n("ok")}).receive("timeout",()=>{r(),n("timed out")}).receive("error",()=>{n("error")}),s.send(),this._canPush()||s.trigger("ok",{})}).finally(()=>{s==null||s.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=De.closed,this.bindings={}}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}_push(e,r,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let n=new sn(this,e,r,s);return this._canPush()?n.send():this._addToPushBuffer(n),n}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>No){const r=this.pushBuffer.shift();r&&(r.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${r.event}`,r.payload))}}_onMessage(e,r,s){return r}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,r,s){var n,i;const a=e.toLocaleLowerCase(),{close:l,error:c,leave:u,join:d}=xt;if(s&&[l,c,u,d].indexOf(a)>=0&&s!==this._joinRef())return;let g=this._onMessage(a,r,s);if(r&&!g)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(a)?(n=this.bindings.postgres_changes)===null||n===void 0||n.filter(f=>{var m,b,_;return((m=f.filter)===null||m===void 0?void 0:m.event)==="*"||((_=(b=f.filter)===null||b===void 0?void 0:b.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===a}).map(f=>f.callback(g,s)):(i=this.bindings[a])===null||i===void 0||i.filter(f=>{var m,b,_,y,k,j;if(["broadcast","presence","postgres_changes"].includes(a))if("id"in f){const x=f.id,T=(m=f.filter)===null||m===void 0?void 0:m.event;return x&&((b=r.ids)===null||b===void 0?void 0:b.includes(x))&&(T==="*"||(T==null?void 0:T.toLocaleLowerCase())===((_=r.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else{const x=(k=(y=f==null?void 0:f.filter)===null||y===void 0?void 0:y.event)===null||k===void 0?void 0:k.toLocaleLowerCase();return x==="*"||x===((j=r==null?void 0:r.event)===null||j===void 0?void 0:j.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===a}).map(f=>{if(typeof g=="object"&&"ids"in g){const m=g.data,{schema:b,table:_,commit_timestamp:y,type:k,errors:j}=m;g=Object.assign(Object.assign({},{schema:b,table:_,commit_timestamp:y,eventType:k,new:{},old:{},errors:j}),this._getPayloadRecords(m))}f.callback(g,s)})}_isClosed(){return this.state===De.closed}_isJoined(){return this.state===De.joined}_isJoining(){return this.state===De.joining}_isLeaving(){return this.state===De.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,r,s){const n=e.toLocaleLowerCase(),i={type:n,filter:r,callback:s};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this}_off(e,r){const s=e.toLocaleLowerCase();return this.bindings[s]&&(this.bindings[s]=this.bindings[s].filter(n=>{var i;return!(((i=n.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===s&&Br.isEqual(n.filter,r))})),this}static isEqual(e,r){if(Object.keys(e).length!==Object.keys(r).length)return!1;for(const s in e)if(e[s]!==r[s])return!1;return!0}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(xt.close,{},e)}_onError(e){this._on(xt.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=De.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=di(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=di(e.columns,e.old_record)),r}}const nn=()=>{},Bs={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Wo=[1e3,2e3,5e3,1e4],qo=1e4,zo=`
37
+ Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const Ho="2.100.0",zo=`realtime-js/${Ho}`,Ko="1.0.0",ba="2.0.0",Vo=ba,Go=1e4,Jo=100,Kt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},ma={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},kn={connecting:"connecting",closing:"closing",closed:"closed"};class Qo{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=e.topic,o=(n=e.ref)!==null&&n!==void 0?n:"",c=(i=e.join_ref)!==null&&i!==void 0?i:"",u=e.payload.event,d=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=Object.keys(d).length===0?"":JSON.stringify(d);if(c.length>255)throw new Error(`joinRef length ${c.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`topic length ${a.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const g=this.USER_BROADCAST_PUSH_META_LENGTH+c.length+o.length+a.length+u.length+h.length,f=new ArrayBuffer(this.HEADER_LENGTH+g);let y=new DataView(f),b=0;y.setUint8(b++,this.KINDS.userBroadcastPush),y.setUint8(b++,c.length),y.setUint8(b++,o.length),y.setUint8(b++,a.length),y.setUint8(b++,u.length),y.setUint8(b++,h.length),y.setUint8(b++,r),Array.from(c,v=>y.setUint8(b++,v.charCodeAt(0))),Array.from(o,v=>y.setUint8(b++,v.charCodeAt(0))),Array.from(a,v=>y.setUint8(b++,v.charCodeAt(0))),Array.from(u,v=>y.setUint8(b++,v.charCodeAt(0))),Array.from(h,v=>y.setUint8(b++,v.charCodeAt(0)));var _=new Uint8Array(f.byteLength+s.byteLength);return _.set(new Uint8Array(f),0),_.set(new Uint8Array(s),f.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,c]=s;return r({join_ref:n,ref:i,topic:a,event:o,payload:c})}return r({})}_binaryDecode(e){const r=new DataView(e),s=r.getUint8(0),n=new TextDecoder;switch(s){case 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 c=this.HEADER_LENGTH+4;const u=s.decode(e.slice(c,c+n));c=c+n;const d=s.decode(e.slice(c,c+i));c=c+i;const h=s.decode(e.slice(c,c+a));c=c+a;const g=e.slice(c,e.byteLength),f=o===this.JSON_ENCODING?JSON.parse(s.decode(g)):g,y={type:this.BROADCAST_EVENT,event:d,payload:f};return a>0&&(y.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:y}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e==null?void 0: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 Te;(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"})(Te||(Te={}));const yi=(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]=Yo(a,t,e,n),i),{}):{}},Yo=(t,e,r,s)=>{const n=e.find(o=>o.name===t),i=n==null?void 0:n.type,a=r[t];return i&&!s.includes(i)?ya(i,a):Sn(a)},ya=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return tl(e,r)}switch(t){case Te.bool:return Xo(e);case Te.float4:case Te.float8:case Te.int2:case Te.int4:case Te.int8:case Te.numeric:case Te.oid:return Zo(e);case Te.json:case Te.jsonb:return el(e);case Te.timestamp:return rl(e);case Te.abstime:case Te.date:case Te.daterange:case Te.int4range:case Te.int8range:case Te.money:case Te.reltime:case Te.text:case Te.time:case Te.timestamptz:case Te.timetz:case Te.tsrange:case Te.tstzrange:return Sn(e);default:return Sn(e)}},Sn=t=>t,Xo=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},Zo=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},el=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},tl=(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=>ya(e,o))}return t},rl=t=>typeof t=="string"?t.replace(" ","T"):t,va=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 cs=t=>typeof t=="function"?t:function(){return t},sl=typeof self<"u"?self:null,Br=typeof window<"u"?window:null,_t=sl||Br||globalThis,nl="2.0.0",il=1e4,al=1e3,Tt={connecting:0,open:1,closing:2,closed:3},tt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Ot={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},En={longpoll:"longpoll",websocket:"websocket"},ol={complete:4},jn="base64url.bearer.phx.",Us=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})}},wa=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))}},ll=class{constructor(t,e,r){this.state=tt.closed,this.topic=t,this.params=cs(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Us(this,Ot.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new wa(()=>{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=tt.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",s=>{this.state=tt.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=tt.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=tt.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 Us(this,Ot.leave,cs({}),this.timeout).send(),this.state=tt.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(Ot.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=tt.closed,this.bindings=[]}onClose(t){this.on(Ot.close,t)}onError(t){return this.on(Ot.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 Us(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=tt.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Ot.close,"leave")},r=new Us(this,Ot.leave,cs({}),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=tt.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===tt.closed}isErrored(){return this.state===tt.errored}isJoined(){return this.state===tt.joined}isJoining(){return this.state===tt.joining}isLeaving(){return this.state===tt.leaving}},Js=class{static request(t,e,r,s,n,i,a){if(_t.XDomainRequest){let o=new _t.XDomainRequest;return this.xdomainRequest(o,t,e,s,n,i,a)}else if(_t.XMLHttpRequest){let o=new _t.XMLHttpRequest;return this.xhrRequest(o,t,e,r,s,n,i,a)}else{if(_t.fetch&&_t.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},c=null;return n&&(c=new AbortController,setTimeout(()=>c.abort(),n),o.signal=c.signal),_t.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)}),c}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[c,u]of Object.entries(s))t.setRequestHeader(c,u);return t.onerror=()=>o&&o(null),t.onreadystatechange=()=>{if(t.readyState===ol.complete&&o){let c=this.parseJSON(t.responseText);o(c)}},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)}`}},cl=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)},Tr=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(jn)&&(this.authToken=atob(e[1].slice(jn.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=Tt.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+En.websocket),"$1/"+En.longpoll)}endpointURL(){return Js.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=Tt.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Tt.open||this.readyState===Tt.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=Tt.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=cl(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
38
+ `),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,r){for(let n of this.reqs)n.abort();this.readyState=Tt.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=Js.request(t,this.endpointURL(),e,r,this.timeout,a,o=>{this.reqs.delete(i),this.isActive()&&n(o)}),this.reqs.add(i)}},ul=class is{constructor(e,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,n=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.joinRef=this.channel.joinRef(),this.state=is.syncState(this.state,n,i,a),this.pendingDiffs.forEach(c=>{this.state=is.syncDiff(this.state,c,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=is.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 is.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,s,n){let i=this.clone(e),a={},o={};return this.map(i,(c,u)=>{r[c]||(o[c]=u)}),this.map(r,(c,u)=>{let d=i[c];if(d){let h=u.metas.map(b=>b.phx_ref),g=d.metas.map(b=>b.phx_ref),f=u.metas.filter(b=>g.indexOf(b.phx_ref)<0),y=d.metas.filter(b=>h.indexOf(b.phx_ref)<0);f.length>0&&(a[c]=u,a[c].metas=f),y.length>0&&(o[c]=this.clone(d),o[c].metas=y)}else a[c]=u}),this.syncDiff(i,{joins:a,leaves:o},s,n)}static syncDiff(e,r,s,n){let{joins:i,leaves:a}=this.clone(r);return s||(s=function(){}),n||(n=function(){}),this.map(i,(o,c)=>{let u=e[o];if(e[o]=this.clone(c),u){let d=e[o].metas.map(g=>g.phx_ref),h=u.metas.filter(g=>d.indexOf(g.phx_ref)<0);e[o].metas.unshift(...h)}s(o,u,c)}),this.map(a,(o,c)=>{let u=e[o];if(!u)return;let d=c.metas.map(h=>h.phx_ref);u.metas=u.metas.filter(h=>d.indexOf(h.phx_ref)<0),n(o,u,c),u.metas.length===0&&delete e[o]}),e}static list(e,r){return r||(r=function(s,n){return n}),this.map(e,(s,n)=>r(s,n))}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static clone(e){return JSON.parse(JSON.stringify(e))}},Ms={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=this.META_LENGTH+e.length+r.length+n.length+s.length,o=new ArrayBuffer(this.HEADER_LENGTH+a),c=new DataView(o),u=0;c.setUint8(u++,this.KINDS.push),c.setUint8(u++,e.length),c.setUint8(u++,r.length),c.setUint8(u++,n.length),c.setUint8(u++,s.length),Array.from(e,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(r,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(n,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(s,h=>c.setUint8(u++,h.charCodeAt(0)));var d=new Uint8Array(o.byteLength+i.byteLength);return d.set(new Uint8Array(o),0),d.set(new Uint8Array(i),o.byteLength),d.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,s);case this.KINDS.reply:return this.decodeReply(t,e,s);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,s)}},decodePush(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(t.slice(a,a+s));a=a+s;let c=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:c,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,c=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 g=t.slice(o,t.byteLength),f={status:h,response:g};return{join_ref:c,ref:u,topic:d,event:Ot.reply,payload:f}},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 c=t.slice(i,t.byteLength);return{join_ref:null,ref:null,topic:a,event:o,payload:c}}},dl=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||il,this.transport=e.transport||_t.WebSocket||Tr,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||_t&&_t.sessionStorage,this.establishedConnections=0,this.defaultEncoder=Ms.encode.bind(Ms),this.defaultDecoder=Ms.decode.bind(Ms),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!==Tr?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;Br&&Br.addEventListener&&(Br.addEventListener("pagehide",s=>{this.conn&&(this.disconnect(),r=this.connectClock)}),Br.addEventListener("pageshow",s=>{r===this.connectClock&&(r=null,this.connect())}),Br.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=s=>e.rejoinAfterMs?e.rejoinAfterMs(s):[1e3,2e3,5e3][s-1]||1e4,this.reconnectAfterMs=s=>e.reconnectAfterMs?e.reconnectAfterMs(s):[10,50,100,150,200,250,500,1e3,2e3][s-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(s,n,i)=>{console.log(`${s}: ${n}`,i)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=cs(e.params||{}),this.endPoint=`${t}/${En.websocket}`,this.vsn=e.vsn||nl,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new wa(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return Tr}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=Js.appendParams(Js.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=cs(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Tr?this.connectWithFallback(Tr,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){switch(t){case Tr:return"LongPoll";default:return t.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${jn}${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=c=>{this.log("transport",`falling back to ${a}...`,c),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(c=>{this.log("transport","error",c),s&&!r&&(clearTimeout(this.fallbackTimer),o(c))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!s){let c=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${c}`,"true"),this.log("transport",`established ${c} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,e),this.ping(c=>{this.log("transport","connected to primary after",c),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),al,"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===Tt.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(Ot.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case Tt.connecting:return"connecting";case Tt.open:return"open";case Tt.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 ll(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(c){this.log("error","error in heartbeat callback",c)}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 c=this.channels[o];c.isMember(r,s,n,a)&&c.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 us{constructor(e,r){const s=fl(r);this.presence=new ul(e.getChannel(),s),this.presence.onJoin((n,i,a)=>{const o=us.onJoinPayload(n,i,a);e.getChannel().trigger("presence",o)}),this.presence.onLeave((n,i,a)=>{const o=us.onLeavePayload(n,i,a);e.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return us.transformState(this.presence.state)}static transformState(e){return e=hl(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{const n=e[s];return r[s]=Gs(n),r},{})}static onJoinPayload(e,r,s){const n=vi(r),i=Gs(s);return{event:"join",key:e,currentPresences:n,newPresences:i}}static onLeavePayload(e,r,s){const n=vi(r),i=Gs(s);return{event:"leave",key:e,currentPresences:n,leftPresences:i}}}function Gs(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function hl(t){return JSON.parse(JSON.stringify(t))}function fl(t){return(t==null?void 0:t.events)&&{events:t.events}}function vi(t){return t!=null&&t.metas?Gs(t):[]}var wi;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(wi||(wi={}));class pl{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new us(this.channel.channelAdapter,r)}}class gl{constructor(e,r,s){const n=bl(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`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>Jo){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===Kt.joined}isJoined(){return this.state===Kt.joined}isJoining(){return this.state===Kt.joining}isClosed(){return this.state===Kt.closed}isLeaving(){return this.state===Kt.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function bl(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var xi;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(xi||(xi={}));var ds;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(ds||(ds={}));var Pt;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Pt||(Pt={}));class hs{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 gl(this.socket.socketAdapter,e,this.params),this.presence=new pl(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=va(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`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:c}}=this.params,u=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(f=>f.filter))!==null&&n!==void 0?n:[],d=!!this.bindings[ds.PRESENCE]&&this.bindings[ds.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,h={},g={broadcast:a,presence:Object.assign(Object.assign({},o),{enabled:d}),postgres_changes:u,private:c};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(f=>{e==null||e(Pt.CHANNEL_ERROR,f)}),this._onClose(()=>e==null?void 0:e(Pt.CLOSED)),this.updateJoinPayload(Object.assign({config:g},h)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:f})=>{if(this.socket._isManualToken()||this.socket.setAuth(),f===void 0){e==null||e(Pt.SUBSCRIBED);return}this._updatePostgresBindings(f,e)}).receive("error",f=>{this.state=Kt.errored,e==null||e(Pt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(Pt.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var s;const n=this.bindings.postgres_changes,i=(s=n==null?void 0:n.length)!==null&&s!==void 0?s:0,a=[];for(let o=0;o<i;o++){const c=n[o],{filter:{event:u,schema:d,table:h,filter:g}}=c,f=e&&e[o];if(f&&f.event===u&&hs.isFilterValueEqual(f.schema,d)&&hs.isFilterValueEqual(f.table,h)&&hs.isFilterValueEqual(f.filter,g))a.push(Object.assign(Object.assign({},c),{id:f.id}));else{this.unsubscribe(),this.state=Kt.errored,r==null||r(Pt.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=a,this.state!=Kt.errored&&r&&r(Pt.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,s){if(this.channelAdapter.isJoined()&&e===ds.PRESENCE)throw this.socket.log("channel",`cannot add presence callbacks for ${this.topic} after joining.`),new Error("cannot add presence callbacks after joining a channel");return this._on(e,r,s)}async httpSend(e,r,s={}){var n;if(r==null)return Promise.reject("Payload is required for httpSend()");const i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);const a={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);if(o.status===202)return{success:!0};let c=o.statusText;try{const u=await o.json();c=u.error||u.message||c}catch{}return Promise.reject(new Error(c))}async send(e,r={}){var s,n;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:a}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const c={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:a,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var a,o,c;const u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(o=(a=this.params)===null||a===void 0?void 0:a.config)===null||o===void 0?void 0:o.broadcast)===null||c===void 0)&&c.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){const n=e.toLocaleLowerCase(),i=this.channelAdapter.on(e,s),a={type:n,filter:r,callback:s,ref:i};return this.bindings[n]?this.bindings[n].push(a):this.bindings[n]=[a],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,c,u,d;const h=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(h,s))return!1;const g=(n=this.bindings[h])===null||n===void 0?void 0:n.find(f=>f.ref===e.ref);if(!g)return!0;if(["broadcast","presence","postgres_changes"].includes(h))if("id"in g){const f=g.id,y=(i=g.filter)===null||i===void 0?void 0:i.event;return f&&((a=r.ids)===null||a===void 0?void 0:a.includes(f))&&(y==="*"||(y==null?void 0:y.toLocaleLowerCase())===((o=r.data)===null||o===void 0?void 0:o.type.toLocaleLowerCase()))}else{const f=(u=(c=g==null?void 0:g.filter)===null||c===void 0?void 0:c.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return f==="*"||f===((d=r==null?void 0:r.event)===null||d===void 0?void 0:d.toLocaleLowerCase())}else return g.type.toLocaleLowerCase()===h})}_notThisChannelEvent(e,r){const{close:s,error:n,leave:i,join:a}=ma;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:c,errors:u}=n;return Object.assign(Object.assign({},{schema:i,table:a,commit_timestamp:o,eventType:c,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=yi(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=yi(e.columns,e.old_record)),r}}class ml{constructor(e,r){this.socket=new dl(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)}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()==kn.connecting}isDisconnecting(){return this.socket.connectionState()==kn.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const yl={HEARTBEAT_INTERVAL:25e3},vl=[1e3,2e3,5e3,1e4],wl=1e4,xl=`
38
39
  addEventListener("message", (e) => {
39
40
  if (e.data.event === "start") {
40
41
  setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
41
42
  }
42
- });`;class Ho{constructor(e,r){var s;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=bn,this.transport=null,this.heartbeatIntervalMs=Bs.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=nn,this.ref=0,this.reconnectTimer=null,this.vsn=ui,this.logger=nn,this.conn=null,this.sendBuffer=[],this.serializer=new Bo,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=n=>n?(...i)=>n(...i):(...i)=>fetch(...i),!(!((s=r==null?void 0:r.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey,this.endPoint=`${e}/${mn.websocket}`,this.httpEndpoint=ca(e),this._initializeOptions(r),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(r==null?void 0:r.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=Co.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const r=e.message;throw r.includes("Node.js")?new Error(`${r}
43
+ });`;class _l{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 Qo,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=i=>i?(...a)=>i(...a):(...a)=>fetch(...a),!(!((s=r==null?void 0: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 ml(e,n),this.httpEndpoint=va(e),this.fetch=this._resolveFetch(r==null?void 0:r.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){const r=e.message;throw r.includes("Node.js")?new Error(`${r}
43
44
 
44
45
  To use Realtime in Node.js, you need to provide a WebSocket implementation:
45
46
 
@@ -52,31 +53,31 @@ Option 2: Install and provide the "ws" package:
52
53
  const client = new RealtimeClient(url, {
53
54
  ...options,
54
55
  transport: ws
55
- })`):new Error(`WebSocket not available: ${r}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,r){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const s=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(s),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(e?this.conn.close(e,r??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const e=await Promise.all(this.channels.map(r=>r.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,r,s){this.logger(e,r,s)}connectionState(){switch(this.conn&&this.conn.readyState){case zt.connecting:return or.Connecting;case zt.open:return or.Open;case zt.closing:return or.Closing;default:return or.Closed}}isConnected(){return this.connectionState()===or.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,r={config:{}}){const s=`realtime:${e}`,n=this.getChannels().find(i=>i.topic===s);if(n)return n;{const i=new Br(`realtime:${e}`,r,this);return this.channels.push(i),i}}push(e){const{topic:r,event:s,payload:n,ref:i}=e,a=()=>{this.encode(e,l=>{var c;(c=this.conn)===null||c===void 0||c.send(l)})};this.log("push",`${r} ${s} (${i})`,n),this.isConnected()?a():this.sendBuffer.push(a)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(r){this.log("error","error in heartbeat callback",r)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(r){this.log("error","error in heartbeat callback",r)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(Io,"heartbeat timeout"),setTimeout(()=>{var r;this.isConnected()||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout()},Bs.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(r){this.log("error","error in heartbeat callback",r)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let r=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));r&&(this.log("transport",`leaving duplicate topic "${e}"`),r.unsubscribe())}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,r=>{if(r.topic==="phoenix"&&r.event==="phx_reply"&&r.ref&&r.ref===this.pendingHeartbeatRef){const u=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(r.payload.status==="ok"?"ok":"error",u)}catch(d){this.log("error","error in heartbeat callback",d)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:s,event:n,payload:i,ref:a}=r,l=a?`(${a})`:"",c=i.status||"";this.log("receive",`${c} ${s} ${n} ${l}`.trim(),i),this.channels.filter(u=>u._isMember(s)).forEach(u=>u._trigger(n,i,a)),this._triggerStateCallbacks("message",r)})}_clearTimer(e){var r;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((r=this.reconnectTimer)===null||r===void 0||r.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),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),this.conn.readyState===zt.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===zt.open||this.conn.readyState===zt.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.accessTokenValue&&(this.channels.forEach(r=>{r.updateJoinPayload({access_token:this.accessTokenValue})}),this.sendBuffer=[],this.channels.forEach(r=>{r._isJoining()&&(r.joinPush.sent=!1,r.joinPush.send())})),this.flushSendBuffer()}).catch(r=>{this.log("error","error waiting for auth on connect",r),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_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.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)}_onConnClose(e){var r;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e);try{this.heartbeatCallback("error")}catch(r){this.log("error","error in heartbeat callback",r)}}_triggerChanError(){this.channels.forEach(e=>e._trigger(xt.error))}_appendParams(e,r){if(Object.keys(r).length===0)return e;const s=e.match(/\?/)?"&":"?",n=new URLSearchParams(r);return`${e}${s}${n}`}_workerObjectUrl(e){let r;if(e)r=e;else{const s=new Blob([zo],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_setConnectionState(e,r=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=r)}async _performAuth(e=null){let r,s=!1;if(e)r=e,s=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),r=this.accessTokenValue}else r=this.accessTokenValue;s?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{const i={access_token:r,version:Oo};r&&n.updateJoinPayload(i),n.joinedOnce&&n._isJoined()&&n._push(xt.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_triggerStateCallbacks(e,r){try{this.stateChangeCallbacks[e].forEach(s=>{try{s(r)}catch(n){this.log("error",`error in ${e} callback`,n)}})}catch(s){this.log("error",`error triggering ${e} callbacks`,s)}}_setupReconnectionTimer(){this.reconnectTimer=new oa(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Bs.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var r,s,n,i,a,l,c,u,d,h,g,f;switch(this.transport=(r=e==null?void 0:e.transport)!==null&&r!==void 0?r:null,this.timeout=(s=e==null?void 0:e.timeout)!==null&&s!==void 0?s:bn,this.heartbeatIntervalMs=(n=e==null?void 0:e.heartbeatIntervalMs)!==null&&n!==void 0?n:Bs.HEARTBEAT_INTERVAL,this.worker=(i=e==null?void 0:e.worker)!==null&&i!==void 0?i:!1,this.accessToken=(a=e==null?void 0:e.accessToken)!==null&&a!==void 0?a:null,this.heartbeatCallback=(l=e==null?void 0:e.heartbeatCallback)!==null&&l!==void 0?l:nn,this.vsn=(c=e==null?void 0:e.vsn)!==null&&c!==void 0?c:ui,e!=null&&e.params&&(this.params=e.params),e!=null&&e.logger&&(this.logger=e.logger),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(u=e==null?void 0:e.reconnectAfterMs)!==null&&u!==void 0?u:m=>Wo[m-1]||qo,this.vsn){case Po:this.encode=(d=e==null?void 0:e.encode)!==null&&d!==void 0?d:(m,b)=>b(JSON.stringify(m)),this.decode=(h=e==null?void 0:e.decode)!==null&&h!==void 0?h:(m,b)=>b(JSON.parse(m));break;case aa:this.encode=(g=e==null?void 0:e.encode)!==null&&g!==void 0?g:this.serializer.encode.bind(this.serializer),this.decode=(f=e==null?void 0:e.decode)!==null&&f!==void 0?f:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl}}}var us=class extends Error{constructor(t,e){var r;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)&&((r=e.icebergType)==null?void 0:r.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Ko(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 Vo(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 Go(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:a}){const l=Ko(t.baseUrl,s,n),c=await Vo(t.auth),u=await e(l,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...c,...a},body:i?JSON.stringify(i):void 0}),d=await u.text(),h=(u.headers.get("content-type")||"").includes("application/json"),g=h&&d?JSON.parse(d):d;if(!u.ok){const f=h?g:void 0,m=f==null?void 0:f.error;throw new us((m==null?void 0:m.message)??`Request failed with status ${u.status}`,{status:u.status,icebergType:m==null?void 0:m.type,icebergCode:m==null?void 0:m.code,details:f})}return{status:u.status,headers:u.headers,data:g}}}}function Fs(t){return t.join("")}var Jo=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:Fs(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==null?void 0: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/${Fs(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Fs(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Fs(t.namespace)}`}),!0}catch(e){if(e instanceof us&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof us&&r.status===409)return;throw r}}};function jr(t){return t.join("")}var Qo=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/${jr(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/${jr(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/${jr(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/${jr(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String((e==null?void 0: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/${jr(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/${jr(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof us&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof us&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},Yo=class{constructor(t){var s;let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Go({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=(s=t.accessDelegation)==null?void 0:s.join(","),this.namespaceOps=new Jo(this.client,e),this.tableOps=new Qo(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)}},Gs=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}};function Js(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var vn=class extends Gs{constructor(t,e,r,s="storage"){super(t,s,e,r),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},ua=class extends Gs{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};const Xo=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Zo=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)},wn=t=>{if(Array.isArray(t))return t.map(r=>wn(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]=wn(s)}),e},el=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function ds(t){"@babel/helpers - typeof";return ds=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},ds(t)}function tl(t,e){if(ds(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(ds(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function rl(t){var e=tl(t,"string");return ds(e)=="symbol"?e:e+""}function sl(t,e,r){return(e=rl(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function pi(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 ne(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?pi(Object(r),!0).forEach(function(s){sl(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):pi(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const gi=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},nl=async(t,e,r,s)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){const n=t;let i=parseInt(n.status,10);Number.isFinite(i)||(i=500),n.json().then(a=>{const l=(a==null?void 0:a.statusCode)||(a==null?void 0:a.code)||i+"";e(new vn(gi(a),i,l,s))}).catch(()=>{const a=i+"";e(new vn(n.statusText||`HTTP ${i} error`,i,a,s))})}else e(new ua(gi(t),t,s))},il=(t,e,r,s)=>{const n={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"||t==="HEAD"||!s?ne(ne({},n),r):(Zo(s)?(n.headers=ne({"Content-Type":"application/json"},e==null?void 0:e.headers),n.body=JSON.stringify(s)):n.body=s,e!=null&&e.duplex&&(n.duplex=e.duplex),ne(ne({},n),r))};async function es(t,e,r,s,n,i,a){return new Promise((l,c)=>{t(r,il(e,s,n,i)).then(u=>{if(!u.ok)throw u;if(s!=null&&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=>l(u)).catch(u=>nl(u,c,s,a))})}function da(t="storage"){return{get:async(e,r,s,n)=>es(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,i)=>es(e,"POST",r,n,i,s,t),put:async(e,r,s,n,i)=>es(e,"PUT",r,n,i,s,t),head:async(e,r,s,n)=>es(e,"HEAD",r,ne(ne({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,i)=>es(e,"DELETE",r,n,i,s,t)}}const al=da("storage"),{get:hs,post:yt,put:xn,head:ol,remove:zn}=al,ct=da("vectors");var Jr=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=Xo(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=ne(ne({},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(Js(r))return{data:null,error:r};throw r}}},ll=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Js(e))return{data:null,error:e};throw e}}};let ha;ha=Symbol.toStringTag;var cl=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[ha]="BlobDownloadBuilder",this.promise=null}asStream(){return new ll(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(Js(e))return{data:null,error:e};throw e}}};const ul={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},bi={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var dl=class extends Jr{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=ne(ne({},bi),s);let l=ne(ne({},n.headers),t==="POST"&&{"x-upsert":String(a.upsert)});const c=a.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),c&&i.append("metadata",n.encodeMetadata(c)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",a.cacheControl),c&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(c))):(i=r,l["cache-control"]=`max-age=${a.cacheControl}`,l["content-type"]=a.contentType,c&&(l["x-metadata"]=n.toBase64(n.encodeMetadata(c))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!a.duplex&&(a.duplex="half")),s!=null&&s.headers&&(l=ne(ne({},l),s.headers));const u=n._removeEmptyFolders(e),d=n._getFinalPath(u),h=await(t=="PUT"?xn:yt)(n.fetch,`${n.url}/object/${d}`,i,ne({headers:l},a!=null&&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),l=new URL(n.url+`/object/upload/sign/${a}`);return l.searchParams.set("token",e),n.handleOperation(async()=>{let c;const u=ne({upsert:bi.upsert},s),d=ne(ne({},n.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",u.cacheControl)):(c=r,d["cache-control"]=`max-age=${u.cacheControl}`,d["content-type"]=u.contentType),{path:i,fullPath:(await xn(n.fetch,l.toString(),c,{headers:d})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t);const n=ne({},r.headers);e!=null&&e.upsert&&(n["x-upsert"]="true");const i=await yt(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),a=new URL(r.url+i.url),l=a.searchParams.get("token");if(!l)throw new Gs("No token returned by API");return{signedUrl:a.toString(),path:t,token:l}})}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 yt(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0:r.destinationBucket},{headers:s.headers}))}async copy(t,e,r){var s=this;return s.handleOperation(async()=>({path:(await yt(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0: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==null?void 0:r.transform)=="object"&&r.transform!==null&&Object.keys(r.transform).length>0;let a=await yt(s.fetch,`${s.url}/object/sign/${n}`,ne({expiresIn:e},i?{transform:r.transform}:{}),{headers:s.headers});const l=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"",c=i&&a.signedURL.includes("/object/sign/")?a.signedURL.replace("/object/sign/","/render/image/sign/"):a.signedURL;return{signedUrl:encodeURI(`${s.url}${c}${l}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{const n=await yt(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:t},{headers:s.headers}),i=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return n.map(a=>ne(ne({},a),{},{signedUrl:a.signedURL?encodeURI(`${s.url}${a.signedURL}${i}`):null}))})}download(t,e,r){const s=typeof(e==null?void 0:e.transform)<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString((e==null?void 0:e.transform)||{}),i=n?`?${n}`:"",a=this._getFinalPath(t),l=()=>hs(this.fetch,`${this.url}/${s}/${a}${i}`,{headers:this.headers,noResolveJson:!0},r);return new cl(l,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>wn(await hs(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await ol(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(Js(n)){var s;const i=n instanceof vn?n.status:n instanceof ua?(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=[],n=e!=null&&e.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&s.push(n);const i=typeof(e==null?void 0:e.transform)<"u"?"render/image":"object",a=this.transformOptsToQueryString((e==null?void 0:e.transform)||{});a!==""&&s.push(a);let l=s.join("&");return l!==""&&(l=`?${l}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${l}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await zn(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var s=this;return s.handleOperation(async()=>{const n=ne(ne(ne({},ul),e),{},{prefix:t||""});return await yt(s.fetch,`${s.url}/object/list/${s.bucketId}`,n,{headers:s.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{const s=ne({},t);return await yt(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,"/")}transformOptsToQueryString(t){const e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}};const hl="2.99.3",Es={"X-Client-Info":`storage-js/${hl}`};var fl=class extends Jr{constructor(t,e={},r,s){const n=new URL(t);s!=null&&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=ne(ne({},Es),e);super(i,a,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await hs(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await hs(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await yt(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 xn(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 yt(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await zn(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){const e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},pl=class extends Jr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ne(ne({},Es),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await yt(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==null?void 0:t.limit)!==void 0&&r.set("limit",t.limit.toString()),(t==null?void 0:t.offset)!==void 0&&r.set("offset",t.offset.toString()),t!=null&&t.sortColumn&&r.set("sortColumn",t.sortColumn),t!=null&&t.sortOrder&&r.set("sortOrder",t.sortOrder),t!=null&&t.search&&r.set("search",t.search);const s=r.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await hs(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await zn(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!el(t))throw new Gs("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 Yo({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(...l)=>{try{return{data:await a.apply(n,l),error:null}}catch(c){if(s)throw c;return{data:null,error:c}}}}})}},gl=class extends Jr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ne(ne({},Es),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await ct.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await ct.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await ct.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await ct.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},bl=class extends Jr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ne(ne({},Es),{},{"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 ct.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await ct.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 ct.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await ct.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 ct.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},ml=class extends Jr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ne(ne({},Es),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await ct.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await ct.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await ct.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await ct.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},yl=class extends ml{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new vl(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)}},vl=class extends gl{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,ne(ne({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,ne(ne({},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 wl(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},wl=class extends bl{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,ne(ne({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,ne(ne({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,ne(ne({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,ne(ne({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,ne(ne({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},xl=class extends fl{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new dl(this.url,this.headers,t,this.fetch)}get vectors(){return new yl(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new pl(this.url+"/iceberg",this.headers,this.fetch)}};const fa="2.99.3",Ir=30*1e3,_n=3,an=_n*Ir,_l="http://localhost:9999",kl="supabase.auth.token",Sl={"X-Client-Info":`gotrue-js/${fa}`},kn="X-Supabase-Api-Version",pa={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},El=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,jl=10*60*1e3;class fs extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}}function Q(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class Tl extends fs{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}}function Rl(t){return Q(t)&&t.name==="AuthApiError"}class lr extends fs{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class Nt extends fs{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}}class ot extends Nt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function on(t){return Q(t)&&t.name==="AuthSessionMissingError"}class Tr extends Nt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class $s extends Nt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Ds extends Nt{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function Cl(t){return Q(t)&&t.name==="AuthImplicitGrantRedirectError"}class mi extends Nt{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Al extends Nt{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 Sn extends Nt{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function ln(t){return Q(t)&&t.name==="AuthRetryableFetchError"}class yi extends Nt{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}}class En extends Nt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Ms="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),vi=`
56
- \r=`.split(""),Ol=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<vi.length;e+=1)t[vi[e].charCodeAt(0)]=-2;for(let e=0;e<Ms.length;e+=1)t[Ms[e].charCodeAt(0)]=e;return t})();function wi(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(Ms[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(Ms[s]),e.queuedBits-=6}}function ga(t,e,r){const s=Ol[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 xi(t){const e=[],r=a=>{e.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=a=>{Nl(a,s,r)};for(let a=0;a<t.length;a+=1)ga(t.charCodeAt(a),n,i);return e.join("")}function Pl(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 Il(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}Pl(s,e)}}function Nl(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)){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 Fr(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)ga(t.charCodeAt(n),r,s);return new Uint8Array(e)}function Bl(t){const e=[];return Il(t,r=>e.push(r)),new Uint8Array(e)}function cr(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>wi(n,r,s)),wi(null,r,s),e.join("")}function Fl(t){return Math.round(Date.now()/1e3)+t}function $l(){return Symbol("auth-callback")}const Ke=()=>typeof window<"u"&&typeof document<"u",nr={tested:!1,writable:!1},ba=()=>{if(!Ke())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(nr.tested)return nr.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),nr.tested=!0,nr.writable=!0}catch{nr.tested=!0,nr.writable=!1}return nr.writable};function Dl(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 ma=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ll=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Nr=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},ir=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},He=async(t,e)=>{await t.removeItem(e)};class Qs{constructor(){this.promise=new Qs.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}Qs.promiseConstructor=Promise;function Ls(t){const e=t.split(".");if(e.length!==3)throw new En("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!El.test(e[s]))throw new En("JWT not in base64url format");return{header:JSON.parse(xi(e[0])),payload:JSON.parse(xi(e[1])),signature:Fr(e[2]),raw:{header:e[0],payload:e[1]}}}async function Ul(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Ml(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 Wl(t){return("0"+t.toString(16)).substr(-2)}function ql(){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,Wl).join("")}async function zl(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 Hl(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 zl(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Rr(t,e,r=!1){const s=ql();let n=s;r&&(n+="/PASSWORD_RECOVERY"),await Nr(t,`${e}-code-verifier`,n);const i=await Hl(s);return[i,s===i?"plain":"s256"]}const Kl=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Vl(t){const e=t.headers.get(kn);if(!e||!e.match(Kl))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Gl(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 Jl(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 Ql=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Cr(t){if(!Ql.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function cn(){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 Yl(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 _i(t){return JSON.parse(JSON.stringify(t))}const ar=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Xl=[502,503,504];async function ki(t){var e;if(!Ll(t))throw new Sn(ar(t),0);if(Xl.includes(t.status))throw new Sn(ar(t),t.status);let r;try{r=await t.json()}catch(i){throw new lr(ar(i),i)}let s;const n=Vl(t);if(n&&n.getTime()>=pa["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 yi(ar(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new ot}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 yi(ar(r),t.status,r.weak_password.reasons);throw new Tl(ar(r),t.status||500,s)}const Zl=(t,e,r,s)=>{const n={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))};async function ee(t,e,r,s){var n;const i=Object.assign({},s==null?void 0:s.headers);i[kn]||(i[kn]=pa["2024-01-01"].name),s!=null&&s.jwt&&(i.Authorization=`Bearer ${s.jwt}`);const a=(n=s==null?void 0:s.query)!==null&&n!==void 0?n:{};s!=null&&s.redirectTo&&(a.redirect_to=s.redirectTo);const l=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",c=await ec(t,e,r+l,{headers:i,noResolveJson:s==null?void 0:s.noResolveJson},{},s==null?void 0:s.body);return s!=null&&s.xform?s==null?void 0:s.xform(c):{data:Object.assign({},c),error:null}}async function ec(t,e,r,s,n,i){const a=Zl(e,s,n,i);let l;try{l=await t(r,Object.assign({},a))}catch(c){throw console.error(c),new Sn(ar(c),0)}if(l.ok||await ki(l),s!=null&&s.noResolveJson)return l;try{return await l.json()}catch(c){await ki(c)}}function mt(t){var e;let r=null;sc(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Fl(t.expires_in)));const s=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:s},error:null}}function Si(t){const e=mt(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 Ht(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function tc(t){return{data:t,error:null}}function rc(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=t,a=Vs(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},c=Object.assign({},a);return{data:{properties:l,user:c},error:null}}function Ei(t){return t}function sc(t){return t.access_token&&t.refresh_token&&t.expires_in}const un=["global","local","others"];class nc{constructor({url:e="",headers:r={},fetch:s}){this.url=e,this.headers=r,this.fetch=ma(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,r=un[0]){if(un.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${un.join(", ")}`);try{return await ee(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(Q(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await ee(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Ht})}catch(s){if(Q(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:r}=e,s=Vs(e,["options"]),n=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(n.new_email=s==null?void 0:s.newEmail,delete n.newEmail),await ee(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:rc,redirectTo:r==null?void 0:r.redirectTo})}catch(r){if(Q(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await ee(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Ht})}catch(r){if(Q(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,s,n,i,a,l,c;try{const u={nextPage:null,lastPage:0,total:0},d=await ee(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e==null?void 0:e.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:Ei});if(d.error)throw d.error;const h=await d.json(),g=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,f=(c=(l=d.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(m=>{const b=parseInt(m.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(m.split(";")[1].split("=")[1]);u[`${_}Page`]=b}),u.total=parseInt(g)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(Q(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Cr(e);try{return await ee(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Ht})}catch(r){if(Q(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Cr(e);try{return await ee(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Ht})}catch(s){if(Q(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){Cr(e);try{return await ee(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Ht})}catch(s){if(Q(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){Cr(e.userId);try{const{data:r,error:s}=await ee(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(Q(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Cr(e.userId),Cr(e.id);try{return{data:await ee(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(Q(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,s,n,i,a,l,c;try{const u={nextPage:null,lastPage:0,total:0},d=await ee(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e==null?void 0:e.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:Ei});if(d.error)throw d.error;const h=await d.json(),g=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,f=(c=(l=d.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(m=>{const b=parseInt(m.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(m.split(";")[1].split("=")[1]);u[`${_}Page`]=b}),u.total=parseInt(g)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(Q(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await ee(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Q(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await ee(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Q(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await ee(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(Q(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await ee(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(Q(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await ee(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Q(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{const r={};return e!=null&&e.type&&(r.type=e.type),await ee(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:s=>{var n;return{data:{providers:(n=s==null?void 0:s.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(Q(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await ee(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Q(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await ee(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Q(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await ee(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(Q(s))return{data:null,error:s};throw s}}async _deleteCustomProvider(e){try{return await ee(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(Q(r))return{data:null,error:r};throw r}}}function ji(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}const _t={debug:!!(globalThis&&ba()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class ya extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Ti extends ya{}async function ic(t,e,r){_t.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const s=new globalThis.AbortController;let n;e>0&&(n=setTimeout(()=>{s.abort(),_t.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){clearTimeout(n),_t.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,i.name);try{return await r()}finally{_t.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,i.name)}}else{if(e===0)throw _t.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Ti(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(_t.debug)try{const a=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(a,null," "))}catch(a){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",a)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(n),await r()}})}catch(i){if(e>0&&clearTimeout(n),(i==null?void 0:i.name)==="AbortError"&&e>0){if(s.signal.aborted)return _t.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:!0},async a=>{if(a){_t.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,a.name);try{return await r()}finally{_t.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,a.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw _t.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new Ti(`Lock "${t}" was released because another request stole it`)}throw i}}function ac(){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 va(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function oc(t){return parseInt(t,16)}function lc(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function cc(t){var e;const{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:a,notBefore:l,requestId:c,resources:u,scheme:d,uri:h,version:g}=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(g!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${g}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
57
- `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}const f=va(t.address),m=d?`${d}://${s}`:s,b=t.statement?`${t.statement}
58
- `:"",_=`${m} wants you to sign in with your Ethereum account:
56
+ })`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const e=this.channels.map(async s=>{const n=await s.unsubscribe();return s.teardown(),n}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,s){this.socketAdapter.log(e,r,s)}connectionState(){return this.socketAdapter.connectionState()||kn.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 hs(`realtime:${e}`,r,this);return this.channels.push(i),i}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}async _performAuth(e=null){let r,s=!1;if(e)r=e,s=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),r=this.accessTokenValue}else r=this.accessTokenValue;s?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{const i={access_token:r,version:zo};r&&n.updateJoinPayload(i),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(ma.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,s)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,s)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{const s=new Blob([xl],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_initializeOptions(e){var r,s,n,i,a,o,c,u,d;this.worker=(r=e==null?void 0:e.worker)!==null&&r!==void 0?r:!1,this.accessToken=(s=e==null?void 0:e.accessToken)!==null&&s!==void 0?s:null;const h={};h.timeout=(n=e==null?void 0:e.timeout)!==null&&n!==void 0?n:Go,h.heartbeatIntervalMs=(i=e==null?void 0:e.heartbeatIntervalMs)!==null&&i!==void 0?i:yl.HEARTBEAT_INTERVAL,h.transport=(a=e==null?void 0:e.transport)!==null&&a!==void 0?a:qo.getWebSocketConstructor(),h.params=e==null?void 0:e.params,h.logger=e==null?void 0:e.logger,h.heartbeatCallback=this._wrapHeartbeatCallback(e==null?void 0:e.heartbeatCallback),h.reconnectAfterMs=(o=e==null?void 0:e.reconnectAfterMs)!==null&&o!==void 0?o:b=>vl[b-1]||wl;let g,f;const y=(c=e==null?void 0:e.vsn)!==null&&c!==void 0?c:Vo;switch(y){case Ko:g=(b,_)=>_(JSON.stringify(b)),f=(b,_)=>_(JSON.parse(b));break;case ba:g=this.serializer.encode.bind(this.serializer),f=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${h.vsn}`)}if(h.vsn=y,h.encode=(u=e==null?void 0:e.encode)!==null&&u!==void 0?u:g,h.decode=(d=e==null?void 0:e.decode)!==null&&d!==void 0?d:f,h.beforeReconnect=this._reconnectAuth.bind(this),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,h.params=Object.assign(Object.assign({},h.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl,h.autoSendHeartbeat=!this.worker}return h}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var gs=class extends Error{constructor(t,e){var r;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)&&((r=e.icebergType)==null?void 0:r.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function kl(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 Sl(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 El(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:a}){const o=kl(t.baseUrl,s,n),c=await Sl(t.auth),u=await e(o,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...c,...a},body:i?JSON.stringify(i):void 0}),d=await u.text(),h=(u.headers.get("content-type")||"").includes("application/json"),g=h&&d?JSON.parse(d):d;if(!u.ok){const f=h?g:void 0,y=f==null?void 0:f.error;throw new gs((y==null?void 0:y.message)??`Request failed with status ${u.status}`,{status:u.status,icebergType:y==null?void 0:y.type,icebergCode:y==null?void 0:y.code,details:f})}return{status:u.status,headers:u.headers,data:g}}}}function Ws(t){return t.join("")}var jl=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:Ws(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==null?void 0: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/${Ws(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ws(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Ws(t.namespace)}`}),!0}catch(e){if(e instanceof gs&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof gs&&r.status===409)return;throw r}}};function Rr(t){return t.join("")}var Tl=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/${Rr(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/${Rr(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/${Rr(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/${Rr(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String((e==null?void 0: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/${Rr(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/${Rr(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof gs&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof gs&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},Rl=class{constructor(t){var s;let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=El({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=(s=t.accessDelegation)==null?void 0:s.join(","),this.namespaceOps=new jl(this.client,e),this.tableOps=new Tl(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)}},sn=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}};function nn(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var Tn=class extends sn{constructor(t,e,r,s="storage"){super(t,s,e,r),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},xa=class extends sn{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};const Al=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Cl=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)},Rn=t=>{if(Array.isArray(t))return t.map(r=>Rn(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]=Rn(s)}),e},Ol=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function bs(t){"@babel/helpers - typeof";return bs=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},bs(t)}function Pl(t,e){if(bs(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(bs(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Nl(t){var e=Pl(t,"string");return bs(e)=="symbol"?e:e+""}function Il(t,e,r){return(e=Nl(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function _i(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 ne(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?_i(Object(r),!0).forEach(function(s){Il(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):_i(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const ki=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},Bl=async(t,e,r,s)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){const n=t;let i=parseInt(n.status,10);Number.isFinite(i)||(i=500),n.json().then(a=>{const o=(a==null?void 0:a.statusCode)||(a==null?void 0:a.code)||i+"";e(new Tn(ki(a),i,o,s))}).catch(()=>{const a=i+"";e(new Tn(n.statusText||`HTTP ${i} error`,i,a,s))})}else e(new xa(ki(t),t,s))},Fl=(t,e,r,s)=>{const n={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"||t==="HEAD"||!s?ne(ne({},n),r):(Cl(s)?(n.headers=ne({"Content-Type":"application/json"},e==null?void 0:e.headers),n.body=JSON.stringify(s)):n.body=s,e!=null&&e.duplex&&(n.duplex=e.duplex),ne(ne({},n),r))};async function rs(t,e,r,s,n,i,a){return new Promise((o,c)=>{t(r,Fl(e,s,n,i)).then(u=>{if(!u.ok)throw u;if(s!=null&&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=>Bl(u,c,s,a))})}function _a(t="storage"){return{get:async(e,r,s,n)=>rs(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,i)=>rs(e,"POST",r,n,i,s,t),put:async(e,r,s,n,i)=>rs(e,"PUT",r,n,i,s,t),head:async(e,r,s,n)=>rs(e,"HEAD",r,ne(ne({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,i)=>rs(e,"DELETE",r,n,i,s,t)}}const Ll=_a("storage"),{get:ms,post:yt,put:An,head:$l,remove:Xn}=Ll,ct=_a("vectors");var Yr=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=Al(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=ne(ne({},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(nn(r))return{data:null,error:r};throw r}}},Dl=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(nn(e))return{data:null,error:e};throw e}}};let ka;ka=Symbol.toStringTag;var Ul=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[ka]="BlobDownloadBuilder",this.promise=null}asStream(){return new Dl(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(nn(e))return{data:null,error:e};throw e}}};const Ml={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Si={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Wl=class extends Yr{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=ne(ne({},Si),s);let o=ne(ne({},n.headers),t==="POST"&&{"x-upsert":String(a.upsert)});const c=a.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),c&&i.append("metadata",n.encodeMetadata(c)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",a.cacheControl),c&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(c))):(i=r,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,c&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(c))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!a.duplex&&(a.duplex="half")),s!=null&&s.headers&&(o=ne(ne({},o),s.headers));const u=n._removeEmptyFolders(e),d=n._getFinalPath(u),h=await(t=="PUT"?An:yt)(n.fetch,`${n.url}/object/${d}`,i,ne({headers:o},a!=null&&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 c;const u=ne({upsert:Si.upsert},s),d=ne(ne({},n.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",u.cacheControl)):(c=r,d["cache-control"]=`max-age=${u.cacheControl}`,d["content-type"]=u.contentType),{path:i,fullPath:(await An(n.fetch,o.toString(),c,{headers:d})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t);const n=ne({},r.headers);e!=null&&e.upsert&&(n["x-upsert"]="true");const i=await yt(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 sn("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 yt(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0:r.destinationBucket},{headers:s.headers}))}async copy(t,e,r){var s=this;return s.handleOperation(async()=>({path:(await yt(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0: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==null?void 0:r.transform)=="object"&&r.transform!==null&&Object.keys(r.transform).length>0;let a=await yt(s.fetch,`${s.url}/object/sign/${n}`,ne({expiresIn:e},i?{transform:r.transform}:{}),{headers:s.headers});const o=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"",c=i&&a.signedURL.includes("/object/sign/")?a.signedURL.replace("/object/sign/","/render/image/sign/"):a.signedURL;return{signedUrl:encodeURI(`${s.url}${c}${o}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{const n=await yt(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:t},{headers:s.headers}),i=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return n.map(a=>ne(ne({},a),{},{signedUrl:a.signedURL?encodeURI(`${s.url}${a.signedURL}${i}`):null}))})}download(t,e,r){const s=typeof(e==null?void 0:e.transform)<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString((e==null?void 0:e.transform)||{}),i=n?`?${n}`:"",a=this._getFinalPath(t),o=()=>ms(this.fetch,`${this.url}/${s}/${a}${i}`,{headers:this.headers,noResolveJson:!0},r);return new Ul(o,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>Rn(await ms(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await $l(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(nn(n)){var s;const i=n instanceof Tn?n.status:n instanceof xa?(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=[],n=e!=null&&e.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&s.push(n);const i=typeof(e==null?void 0:e.transform)<"u"?"render/image":"object",a=this.transformOptsToQueryString((e==null?void 0:e.transform)||{});a!==""&&s.push(a);let o=s.join("&");return o!==""&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${o}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await Xn(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var s=this;return s.handleOperation(async()=>{const n=ne(ne(ne({},Ml),e),{},{prefix:t||""});return await yt(s.fetch,`${s.url}/object/list/${s.bucketId}`,n,{headers:s.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{const s=ne({},t);return await yt(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,"/")}transformOptsToQueryString(t){const e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}};const ql="2.100.0",Cs={"X-Client-Info":`storage-js/${ql}`};var Hl=class extends Yr{constructor(t,e={},r,s){const n=new URL(t);s!=null&&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=ne(ne({},Cs),e);super(i,a,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await ms(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await ms(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await yt(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 An(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 yt(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Xn(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){const e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},zl=class extends Yr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ne(ne({},Cs),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await yt(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==null?void 0:t.limit)!==void 0&&r.set("limit",t.limit.toString()),(t==null?void 0:t.offset)!==void 0&&r.set("offset",t.offset.toString()),t!=null&&t.sortColumn&&r.set("sortColumn",t.sortColumn),t!=null&&t.sortOrder&&r.set("sortOrder",t.sortOrder),t!=null&&t.search&&r.set("search",t.search);const s=r.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await ms(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Xn(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!Ol(t))throw new sn("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 Rl({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(c){if(s)throw c;return{data:null,error:c}}}}})}},Kl=class extends Yr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ne(ne({},Cs),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await ct.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await ct.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await ct.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await ct.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},Vl=class extends Yr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ne(ne({},Cs),{},{"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 ct.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await ct.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 ct.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await ct.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 ct.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},Gl=class extends Yr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ne(ne({},Cs),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await ct.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await ct.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await ct.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await ct.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Jl=class extends Gl{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Ql(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)}},Ql=class extends Kl{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,ne(ne({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,ne(ne({},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 Yl(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Yl=class extends Vl{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,ne(ne({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,ne(ne({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,ne(ne({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,ne(ne({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,ne(ne({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},Xl=class extends Hl{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new Wl(this.url,this.headers,t,this.fetch)}get vectors(){return new Jl(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new zl(this.url+"/iceberg",this.headers,this.fetch)}};const Sa="2.100.0",Fr=30*1e3,Cn=3,fn=Cn*Fr,Zl="http://localhost:9999",ec="supabase.auth.token",tc={"X-Client-Info":`gotrue-js/${Sa}`},On="X-Supabase-Api-Version",Ea={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},rc=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,sc=10*60*1e3;class ys extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}}function Q(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class nc extends ys{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}}function ic(t){return Q(t)&&t.name==="AuthApiError"}class cr extends ys{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class Ft extends ys{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}}class ot extends Ft{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function pn(t){return Q(t)&&t.name==="AuthSessionMissingError"}class Ar extends Ft{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class qs extends Ft{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Hs extends Ft{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function ac(t){return Q(t)&&t.name==="AuthImplicitGrantRedirectError"}class Ei extends Ft{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class oc extends Ft{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 Pn extends Ft{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function gn(t){return Q(t)&&t.name==="AuthRetryableFetchError"}class ji extends Ft{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}}class Nn extends Ft{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Qs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Ti=`
57
+ \r=`.split(""),lc=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Ti.length;e+=1)t[Ti[e].charCodeAt(0)]=-2;for(let e=0;e<Qs.length;e+=1)t[Qs[e].charCodeAt(0)]=e;return t})();function Ri(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(Qs[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(Qs[s]),e.queuedBits-=6}}function ja(t,e,r){const s=lc[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 Ai(t){const e=[],r=a=>{e.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=a=>{dc(a,s,r)};for(let a=0;a<t.length;a+=1)ja(t.charCodeAt(a),n,i);return e.join("")}function cc(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 uc(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}cc(s,e)}}function dc(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)){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 $r(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)ja(t.charCodeAt(n),r,s);return new Uint8Array(e)}function hc(t){const e=[];return uc(t,r=>e.push(r)),new Uint8Array(e)}function ur(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>Ri(n,r,s)),Ri(null,r,s),e.join("")}function fc(t){return Math.round(Date.now()/1e3)+t}function pc(){return Symbol("auth-callback")}const ze=()=>typeof window<"u"&&typeof document<"u",ar={tested:!1,writable:!1},Ta=()=>{if(!ze())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ar.tested)return ar.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),ar.tested=!0,ar.writable=!0}catch{ar.tested=!0,ar.writable=!1}return ar.writable};function gc(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 Ra=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),bc=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Lr=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},or=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},He=async(t,e)=>{await t.removeItem(e)};class an{constructor(){this.promise=new an.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}an.promiseConstructor=Promise;function zs(t){const e=t.split(".");if(e.length!==3)throw new Nn("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!rc.test(e[s]))throw new Nn("JWT not in base64url format");return{header:JSON.parse(Ai(e[0])),payload:JSON.parse(Ai(e[1])),signature:$r(e[2]),raw:{header:e[0],payload:e[1]}}}async function mc(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function yc(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 vc(t){return("0"+t.toString(16)).substr(-2)}function wc(){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,vc).join("")}async function xc(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 _c(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 xc(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Cr(t,e,r=!1){const s=wc();let n=s;r&&(n+="/PASSWORD_RECOVERY"),await Lr(t,`${e}-code-verifier`,n);const i=await _c(s);return[i,s===i?"plain":"s256"]}const kc=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Sc(t){const e=t.headers.get(On);if(!e||!e.match(kc))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Ec(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 jc(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 Tc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Or(t){if(!Tc.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function bn(){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 Rc(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 Ci(t){return JSON.parse(JSON.stringify(t))}const lr=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Ac=[502,503,504];async function Oi(t){var e;if(!bc(t))throw new Pn(lr(t),0);if(Ac.includes(t.status))throw new Pn(lr(t),t.status);let r;try{r=await t.json()}catch(i){throw new cr(lr(i),i)}let s;const n=Sc(t);if(n&&n.getTime()>=Ea["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 ji(lr(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new ot}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 ji(lr(r),t.status,r.weak_password.reasons);throw new nc(lr(r),t.status||500,s)}const Cc=(t,e,r,s)=>{const n={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))};async function ee(t,e,r,s){var n;const i=Object.assign({},s==null?void 0:s.headers);i[On]||(i[On]=Ea["2024-01-01"].name),s!=null&&s.jwt&&(i.Authorization=`Bearer ${s.jwt}`);const a=(n=s==null?void 0:s.query)!==null&&n!==void 0?n:{};s!=null&&s.redirectTo&&(a.redirect_to=s.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",c=await Oc(t,e,r+o,{headers:i,noResolveJson:s==null?void 0:s.noResolveJson},{},s==null?void 0:s.body);return s!=null&&s.xform?s==null?void 0:s.xform(c):{data:Object.assign({},c),error:null}}async function Oc(t,e,r,s,n,i){const a=Cc(e,s,n,i);let o;try{o=await t(r,Object.assign({},a))}catch(c){throw console.error(c),new Pn(lr(c),0)}if(o.ok||await Oi(o),s!=null&&s.noResolveJson)return o;try{return await o.json()}catch(c){await Oi(c)}}function mt(t){var e;let r=null;Ic(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=fc(t.expires_in)));const s=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:s},error:null}}function Pi(t){const e=mt(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 Vt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Pc(t){return{data:t,error:null}}function Nc(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=t,a=rn(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},c=Object.assign({},a);return{data:{properties:o,user:c},error:null}}function Ni(t){return t}function Ic(t){return t.access_token&&t.refresh_token&&t.expires_in}const mn=["global","local","others"];class Bc{constructor({url:e="",headers:r={},fetch:s}){this.url=e,this.headers=r,this.fetch=Ra(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,r=mn[0]){if(mn.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${mn.join(", ")}`);try{return await ee(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(Q(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await ee(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Vt})}catch(s){if(Q(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:r}=e,s=rn(e,["options"]),n=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(n.new_email=s==null?void 0:s.newEmail,delete n.newEmail),await ee(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Nc,redirectTo:r==null?void 0:r.redirectTo})}catch(r){if(Q(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await ee(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Vt})}catch(r){if(Q(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,s,n,i,a,o,c;try{const u={nextPage:null,lastPage:0,total:0},d=await ee(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e==null?void 0:e.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:Ni});if(d.error)throw d.error;const h=await d.json(),g=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,f=(c=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(y=>{const b=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(y.split(";")[1].split("=")[1]);u[`${_}Page`]=b}),u.total=parseInt(g)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(Q(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Or(e);try{return await ee(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Vt})}catch(r){if(Q(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Or(e);try{return await ee(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Vt})}catch(s){if(Q(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){Or(e);try{return await ee(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Vt})}catch(s){if(Q(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){Or(e.userId);try{const{data:r,error:s}=await ee(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(Q(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Or(e.userId),Or(e.id);try{return{data:await ee(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(Q(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,s,n,i,a,o,c;try{const u={nextPage:null,lastPage:0,total:0},d=await ee(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e==null?void 0:e.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:Ni});if(d.error)throw d.error;const h=await d.json(),g=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,f=(c=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(y=>{const b=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(y.split(";")[1].split("=")[1]);u[`${_}Page`]=b}),u.total=parseInt(g)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(Q(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await ee(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Q(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await ee(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Q(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await ee(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(Q(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await ee(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(Q(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await ee(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Q(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{const r={};return e!=null&&e.type&&(r.type=e.type),await ee(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:s=>{var n;return{data:{providers:(n=s==null?void 0:s.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(Q(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await ee(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Q(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await ee(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Q(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await ee(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(Q(s))return{data:null,error:s};throw s}}async _deleteCustomProvider(e){try{return await ee(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(Q(r))return{data:null,error:r};throw r}}}function Ii(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}const xt={debug:!!(globalThis&&Ta()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Aa extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Bi extends Aa{}async function Fc(t,e,r){xt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const s=new globalThis.AbortController;let n;e>0&&(n=setTimeout(()=>{s.abort(),xt.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){clearTimeout(n),xt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,i.name);try{return await r()}finally{xt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,i.name)}}else{if(e===0)throw xt.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Bi(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(xt.debug)try{const a=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(a,null," "))}catch(a){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",a)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(n),await r()}})}catch(i){if(e>0&&clearTimeout(n),(i==null?void 0:i.name)==="AbortError"&&e>0){if(s.signal.aborted)return xt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:!0},async a=>{if(a){xt.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,a.name);try{return await r()}finally{xt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,a.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw xt.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new Bi(`Lock "${t}" was released because another request stole it`)}throw i}}function Lc(){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 Ca(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function $c(t){return parseInt(t,16)}function Dc(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function Uc(t){var e;const{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:c,resources:u,scheme:d,uri:h,version:g}=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(g!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${g}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
58
+ `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}const f=Ca(t.address),y=d?`${d}://${s}`:s,b=t.statement?`${t.statement}
59
+ `:"",_=`${y} wants you to sign in with your Ethereum account:
59
60
  ${f}
60
61
 
61
- ${b}`;let y=`URI: ${h}
62
+ ${b}`;let v=`URI: ${h}
62
63
  Version: ${g}
63
64
  Chain ID: ${r}${a?`
64
65
  Nonce: ${a}`:""}
65
- Issued At: ${i.toISOString()}`;if(n&&(y+=`
66
- Expiration Time: ${n.toISOString()}`),l&&(y+=`
67
- Not Before: ${l.toISOString()}`),c&&(y+=`
68
- Request ID: ${c}`),u){let k=`
69
- Resources:`;for(const j of u){if(!j||typeof j!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${j}`);k+=`
70
- - ${j}`}y+=k}return`${_}
71
- ${y}`}class $e 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}}class Ws extends $e{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function uc({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 $e({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 $e({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 $e({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 $e({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 $e({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new $e({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new $e({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new $e({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(wa(a)){if(i.rp.id!==a)return new $e({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new $e({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 $e({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 $e({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 $e({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function dc({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 $e({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new $e({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(wa(s)){if(r.rpId!==s)return new $e({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new $e({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new $e({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 $e({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class hc{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 fc=new hc;function pc(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=Vs(t,["challenge","user","excludeCredentials"]),i=Fr(e).buffer,a=Object.assign(Object.assign({},r),{id:Fr(r.id).buffer}),l=Object.assign(Object.assign({},n),{challenge:i,user:a});if(s&&s.length>0){l.excludeCredentials=new Array(s.length);for(let c=0;c<s.length;c++){const u=s[c];l.excludeCredentials[c]=Object.assign(Object.assign({},u),{id:Fr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return l}function gc(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=Vs(t,["challenge","allowCredentials"]),n=Fr(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 l=r[a];i.allowCredentials[a]=Object.assign(Object.assign({},l),{id:Fr(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return i}function bc(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:cr(new Uint8Array(t.response.attestationObject)),clientDataJSON:cr(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function mc(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:cr(new Uint8Array(n.authenticatorData)),clientDataJSON:cr(new Uint8Array(n.clientDataJSON)),signature:cr(new Uint8Array(n.signature)),userHandle:n.userHandle?cr(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function wa(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Ri(){var t,e;return!!(Ke()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator==null?void 0:navigator.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function yc(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ws("Browser returned unexpected credential type",e)}:{data:null,error:new Ws("Empty credential response",e)}}catch(e){return{data:null,error:uc({error:e,options:t})}}}async function vc(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ws("Browser returned unexpected credential type",e)}:{data:null,error:new Ws("Empty credential response",e)}}catch(e){return{data:null,error:dc({error:e,options:t})}}}const wc={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},xc={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function qs(...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 l=s[i];e(l)?s[i]=qs(l,a):s[i]=qs(a)}else s[i]=a}return s}function _c(t,e){return qs(wc,t,e||{})}function kc(t,e){return qs(xc,t,e||{})}class Sc{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:l,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!l)return{data:null,error:c};const u=n??fc.createNewAbortSignal();if(l.webauthn.type==="create"){const{user:d}=l.webauthn.credential_options.publicKey;if(!d.name){const h=s;if(h)d.name=`${d.id}:${h}`;else{const f=(await this.client.getUser()).data.user,m=((a=f==null?void 0:f.user_metadata)===null||a===void 0?void 0:a.name)||(f==null?void 0:f.email)||(f==null?void 0:f.id)||"User";d.name=`${d.id}:${m}`}}d.displayName||(d.displayName=d.name)}switch(l.webauthn.type){case"create":{const d=_c(l.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:h,error:g}=await yc({publicKey:d,signal:u});return h?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:h}},error:null}:{data:null,error:g}}case"request":{const d=kc(l.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:h,error:g}=await vc(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:d,signal:u}));return h?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:h}},error:null}:{data:null,error:g}}}}catch(l){return Q(l)?{data:null,error:l}:{data:null,error:new lr("Unexpected error in challenge",l)}}}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 fs("rpId is required for WebAuthn authentication")};try{if(!Ri())return{data:null,error:new lr("Browser does not support WebAuthn",null)};const{data:a,error:l}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{request:i});if(!a)return{data:null,error:l};const{webauthn:c}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:c.type,rpId:r,rpOrigins:s,credential_response:c.credential_response}})}catch(a){return Q(a)?{data:null,error:a}:{data:null,error:new lr("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 fs("rpId is required for WebAuthn registration")};try{if(!Ri())return{data:null,error:new lr("Browser does not support WebAuthn",null)};const{data:a,error:l}=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(g=>g.factor_type==="webauthn"&&g.friendly_name===e&&g.status!=="unverified")}).then(d=>d?this.client.mfa.unenroll({factorId:d==null?void 0:d.id}):void 0),{data:null,error:l};const{data:c,error:u}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:i});return c?this._verify({factorId:a.id,challengeId:c.challengeId,webauthn:{rpId:r,rpOrigins:s,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(a){return Q(a)?{data:null,error:a}:{data:null,error:new lr("Unexpected error in register",a)}}}}ac();const Ec={url:_l,storageKey:kl,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Sl,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function Ci(t,e,r){return await r()}const Ar={};class ps{get jwks(){var e,r;return(r=(e=Ar[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Ar[this.storageKey]=Object.assign(Object.assign({},Ar[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Ar[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Ar[this.storageKey]=Object.assign(Object.assign({},Ar[this.storageKey]),{cachedAt:e})}constructor(e){var r,s,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},Ec),e);if(this.storageKey=i.storageKey,this.instanceID=(r=ps.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,ps.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&Ke()){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.admin=new nc({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=ma(i.fetch),this.lock=i.lock||Ci,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&Ke()&&(!((s=globalThis==null?void 0:globalThis.navigator)===null||s===void 0)&&s.locks)?this.lock=ic:this.lock=Ci,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 Sc(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:ba()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=ji(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=ji(this.memoryStorage)),Ke()&&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);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}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} (${fa}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},s="none";if(Ke()&&(r=Dl(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),Ke()&&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),Cl(i)){const c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:a,redirectType:l}=n;return this._debug("#_initialize()","detected session in URL",a,"redirect type",l),await this._saveSession(a),setTimeout(async()=>{l==="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 Q(r)?this._returnResult({error:r}):this._returnResult({error:new lr("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const i=await ee(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.captchaToken}},xform:mt}),{data:a,error:l}=i;if(l||!a)return this._returnResult({data:{user:null,session:null},error:l});const c=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(Q(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,s,n;try{let i;if("email"in e){const{email:d,password:h,options:g}=e;let f=null,m=null;this.flowType==="pkce"&&([f,m]=await Rr(this.storage,this.storageKey)),i=await ee(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:g==null?void 0:g.emailRedirectTo,body:{email:d,password:h,data:(r=g==null?void 0:g.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken},code_challenge:f,code_challenge_method:m},xform:mt})}else if("phone"in e){const{phone:d,password:h,options:g}=e;i=await ee(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:h,data:(s=g==null?void 0:g.data)!==null&&s!==void 0?s:{},channel:(n=g==null?void 0:g.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken}},xform:mt})}else throw new $s("You must provide either an email or phone number and a password");const{data:a,error:l}=i;if(l||!a)return await He(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:l});const c=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(await He(this.storage,`${this.storageKey}-code-verifier`),Q(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let r;if("email"in e){const{email:i,password:a,options:l}=e;r=await ee(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Si})}else if("phone"in e){const{phone:i,password:a,options:l}=e;r=await ee(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Si})}else throw new $s("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 Tr;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(Q(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){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,s,n,i,a,l,c,u,d,h,g;let f,m;if("message"in e)f=e.message,m=e.signature;else{const{chain:b,wallet:_,statement:y,options:k}=e;let j;if(Ke())if(typeof _=="object")j=_;else{const P=window;if("ethereum"in P&&typeof P.ethereum=="object"&&"request"in P.ethereum&&typeof P.ethereum.request=="function")j=P.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!=null&&k.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");j=_}const x=new URL((r=k==null?void 0:k.url)!==null&&r!==void 0?r:window.location.href),T=await j.request({method:"eth_requestAccounts"}).then(P=>P).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!T||T.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const S=va(T[0]);let F=(s=k==null?void 0:k.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!F){const P=await j.request({method:"eth_chainId"});F=oc(P)}const E={domain:x.host,address:S,statement:y,uri:x.href,version:"1",chainId:F,nonce:(n=k==null?void 0:k.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(a=(i=k==null?void 0:k.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(l=k==null?void 0:k.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=k==null?void 0:k.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=k==null?void 0:k.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(d=k==null?void 0:k.signInWithEthereum)===null||d===void 0?void 0:d.resources};f=cc(E),m=await j.request({method:"personal_sign",params:[lc(f),S]})}try{const{data:b,error:_}=await ee(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:m},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:mt});if(_)throw _;if(!b||!b.session||!b.user){const y=new Tr;return this._returnResult({data:{user:null,session:null},error:y})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:_})}catch(b){if(Q(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async signInWithSolana(e){var r,s,n,i,a,l,c,u,d,h,g,f;let m,b;if("message"in e)m=e.message,b=e.signature;else{const{chain:_,wallet:y,statement:k,options:j}=e;let x;if(Ke())if(typeof y=="object")x=y;else{const S=window;if("solana"in S&&typeof S.solana=="object"&&("signIn"in S.solana&&typeof S.solana.signIn=="function"||"signMessage"in S.solana&&typeof S.solana.signMessage=="function"))x=S.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 y!="object"||!(j!=null&&j.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");x=y}const T=new URL((r=j==null?void 0:j.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in x&&x.signIn){const S=await x.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},j==null?void 0:j.signInWithSolana),{version:"1",domain:T.host,uri:T.href}),k?{statement:k}:null));let F;if(Array.isArray(S)&&S[0]&&typeof S[0]=="object")F=S[0];else if(S&&typeof S=="object"&&"signedMessage"in S&&"signature"in S)F=S;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in F&&"signature"in F&&(typeof F.signedMessage=="string"||F.signedMessage instanceof Uint8Array)&&F.signature instanceof Uint8Array)m=typeof F.signedMessage=="string"?F.signedMessage:new TextDecoder().decode(F.signedMessage),b=F.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in x)||typeof x.signMessage!="function"||!("publicKey"in x)||typeof x!="object"||!x.publicKey||!("toBase58"in x.publicKey)||typeof x.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");m=[`${T.host} wants you to sign in with your Solana account:`,x.publicKey.toBase58(),...k?["",k,""]:[""],"Version: 1",`URI: ${T.href}`,`Issued At: ${(n=(s=j==null?void 0:j.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=j==null?void 0:j.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${j.signInWithSolana.notBefore}`]:[],...!((a=j==null?void 0:j.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${j.signInWithSolana.expirationTime}`]:[],...!((l=j==null?void 0:j.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${j.signInWithSolana.chainId}`]:[],...!((c=j==null?void 0:j.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${j.signInWithSolana.nonce}`]:[],...!((u=j==null?void 0:j.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${j.signInWithSolana.requestId}`]:[],...!((h=(d=j==null?void 0:j.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||h===void 0)&&h.length?["Resources",...j.signInWithSolana.resources.map(F=>`- ${F}`)]:[]].join(`
72
- `);const S=await x.signMessage(new TextEncoder().encode(m),"utf8");if(!S||!(S instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");b=S}}try{const{data:_,error:y}=await ee(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:m,signature:cr(b)},!((g=e.options)===null||g===void 0)&&g.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:mt});if(y)throw y;if(!_||!_.session||!_.user){const k=new Tr;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:y})}catch(_){if(Q(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){const r=await ir(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new Al;const{data:i,error:a}=await ee(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:mt});if(await He(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!i||!i.session||!i.user){const l=new Tr;return this._returnResult({data:{user:null,session:null,redirectType:null},error:l})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:a})}catch(i){if(await He(this.storage,`${this.storageKey}-code-verifier`),Q(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:i,nonce:a}=e,l=await ee(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==null?void 0:r.captchaToken}},xform:mt}),{data:c,error:u}=l;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){const d=new Tr;return this._returnResult({data:{user:null,session:null},error:d})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(r){if(Q(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,a;try{if("email"in e){const{email:l,options:c}=e;let u=null,d=null;this.flowType==="pkce"&&([u,d]=await Rr(this.storage,this.storageKey));const{error:h}=await ee(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(r=c==null?void 0:c.data)!==null&&r!==void 0?r:{},create_user:(s=c==null?void 0:c.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:u,code_challenge_method:d},redirectTo:c==null?void 0:c.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in e){const{phone:l,options:c}=e,{data:u,error:d}=await ee(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(n=c==null?void 0:c.data)!==null&&n!==void 0?n:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(a=c==null?void 0:c.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:d})}throw new $s("You must provide either an email or phone number.")}catch(l){if(await He(this.storage,`${this.storageKey}-code-verifier`),Q(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:l}=await ee(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:mt});if(l)throw l;if(!a)throw new Error("An error occurred on token verification.");const c=a.session,u=a.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(n){if(Q(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i,a;try{let l=null,c=null;this.flowType==="pkce"&&([l,c]=await Rr(this.storage,this.storageKey));const u=await ee(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e==null?void 0:e.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:tc});return!((i=u.data)===null||i===void 0)&&i.url&&Ke()&&!(!((a=e.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await He(this.storage,`${this.storageKey}-code-verifier`),Q(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new ot;const{error:n}=await ee(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(Q(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:s,type:n,options:i}=e,{error:a}=await ee(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if("phone"in e){const{phone:s,type:n,options:i}=e,{data:a,error:l}=await ee(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:l})}throw new $s("You must provide either an email or phone number and a type")}catch(r){if(Q(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await ir(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()<an:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await ir(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=cn()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=Yl(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);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await ee(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Ht}):await this._useSession(async r=>{var s,n,i;const{data:a,error:l}=r;if(l)throw l;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ot}:await ee(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:Ht})})}catch(r){if(Q(r))return on(r)&&(await this._removeSession(),await He(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async s=>{const{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new ot;const a=n.session;let l=null,c=null;this.flowType==="pkce"&&e.email!=null&&([l,c]=await Rr(this.storage,this.storageKey));const{data:u,error:d}=await ee(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:c}),jwt:a.access_token,xform:Ht});if(d)throw d;return a.user=u.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(s){if(await He(this.storage,`${this.storageKey}-code-verifier`),Q(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ot;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:a}=Ls(e.access_token);if(a.exp&&(s=a.exp,n=s<=r),n){const{data:l,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};i=l}else{const{data:l,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.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(Q(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){const{data:a,error:l}=r;if(l)throw l;e=(s=a.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new ot;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(Q(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!Ke())throw new Ds("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ds(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 mi("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ds("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 mi("No code detected.");const{data:k,error:j}=await this._exchangeCodeForSession(e.code);if(j)throw j;const x=new URL(window.location.href);return x.searchParams.delete("code"),window.history.replaceState(window.history.state,"",x.toString()),{data:{session:k.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:n,access_token:i,refresh_token:a,expires_in:l,expires_at:c,token_type:u}=e;if(!i||!l||!a||!u)throw new Ds("No session defined in URL");const d=Math.round(Date.now()/1e3),h=parseInt(l);let g=d+h;c&&(g=parseInt(c));const f=g-d;f*1e3<=Ir&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${h}s`);const m=g-h;d-m>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",m,g,d):d-m<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",m,g,d);const{data:b,error:_}=await this._getUser(i);if(_)throw _;const y={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:h,expires_at:g,refresh_token:a,token_type:u,user:b.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:y,redirectType:e.type},error:null})}catch(s){if(Q(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await ir(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i&&!on(i))return this._returnResult({error:i});const a=(s=n.session)===null||s===void 0?void 0:s.access_token;if(a){const{error:l}=await this.admin.signOut(a,e);if(l&&!(Rl(l)&&(l.status===404||l.status===401||l.status===403)||on(l)))return this._returnResult({error:l})}return e!=="others"&&(await this._removeSession(),await He(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=$l(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{const{data:{session: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),console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await Rr(this.storage,this.storageKey,!0));try{return await ee(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await He(this.storage,`${this.storageKey}-code-verifier`),Q(i))return this._returnResult({data:null,error:i});throw i}}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(Q(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:s,error:n}=await this._useSession(async i=>{var a,l,c,u,d;const{data:h,error:g}=i;if(g)throw g;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(l=e.options)===null||l===void 0?void 0:l.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await ee(this.fetch,"GET",f,{headers:this.headers,jwt:(d=(u=h.session)===null||u===void 0?void 0:u.access_token)!==null&&d!==void 0?d:void 0})});if(n)throw n;return Ke()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),this._returnResult({data:{provider:e.provider,url:s==null?void 0:s.url},error:null})}catch(s){if(Q(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{const{error:n,data:{session:i}}=r;if(n)throw n;const{options:a,provider:l,token:c,access_token:u,nonce:d}=e,h=await ee(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i==null?void 0:i.access_token)!==null&&s!==void 0?s:void 0,body:{provider:l,id_token:c,access_token:u,nonce:d,link_identity:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:mt}),{data:g,error:f}=h;return f?this._returnResult({data:{user:null,session:null},error:f}):!g||!g.session||!g.user?this._returnResult({data:{user:null,session:null},error:new Tr}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:f}))}catch(n){if(await He(this.storage,`${this.storageKey}-code-verifier`),Q(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 ee(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(Q(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const s=Date.now();return await Ml(async n=>(n>0&&await Ul(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await ee(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:mt})),(n,i)=>{const a=200*Math.pow(2,n);return i&&ln(i)&&Date.now()+a-s<Ir})}catch(s){if(this._debug(r,"error",s),Q(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),Ke()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await ir(this.storage,this.storageKey);if(n&&this.userStorage){let a=await ir(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:n.user},await Nr(this.userStorage,this.storageKey+"-user",a)),n.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:cn()}else if(n&&!n.user&&!n.user){const a=await ir(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(n.user=a.user,await He(this.storage,this.storageKey+"-user"),await Nr(this.storage,this.storageKey,n)):n.user=cn()}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()<an;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${an}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:a}=await this._callRefreshToken(n.refresh_token);a&&(console.error(a),ln(a)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:l}=await this._getUser(n.access_token);!l&&(a!=null&&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),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new ot;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Qs;const{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new ot;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const l={data:i.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(i){if(this._debug(n,"error",i),Q(i)){const a={data:null,error:i};return ln(i)||await this._removeSession(),(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){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 l=>{try{await l.callback(e,r)}catch(c){i.push(c)}});if(await Promise.all(a),i.length>0){for(let l=0;l<i.length;l+=1)console.error(i[l]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await He(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await Nr(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=_i(n);await Nr(this.storage,this.storageKey,i)}else{const n=_i(r);await Nr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await He(this.storage,this.storageKey),await He(this.storage,this.storageKey+"-code-verifier"),await He(this.storage,this.storageKey+"-user"),this.userStorage&&await He(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Ke()&&(window!=null&&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(),Ir);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/Ir);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Ir}ms, refresh threshold is ${_n} ticks`),n<=_n&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof ya)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ke()||!(window!=null&&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==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){const n=[`provider=${encodeURIComponent(r)}`];if(s!=null&&s.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s!=null&&s.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[i,a]=await Rr(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});n.push(l.toString())}if(s!=null&&s.queryParams){const i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s!=null&&s.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await ee(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(Q(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 l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await ee(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((n=c==null?void 0:c.totp)===null||n===void 0)&&n.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(r){if(Q(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?bc(e.webauthn.credential_response):mc(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:c}=await ee(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(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:c}))})}catch(r){if(Q(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const a=await ee(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});if(a.error)return a;const{data:l}=a;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:pc(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:gc(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(Q(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=r==null?void 0: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:f}=Ls(e);let m=null;f.aal&&(m=f.aal);let b=m;const{data:{user:_},error:y}=await this.getUser(e);if(y)return this._returnResult({data:null,error:y});((s=(r=_==null?void 0:_.factors)===null||r===void 0?void 0:r.filter(x=>x.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(b="aal2");const j=f.amr||[];return{data:{currentLevel:m,nextLevel:b,currentAuthenticationMethods:j},error:null}}catch(f){if(Q(f))return this._returnResult({data:null,error:f});throw f}const{data:{session:a},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:c}=Ls(a.access_token);let u=null;c.aal&&(u=c.aal);let d=u;((i=(n=a.user.factors)===null||n===void 0?void 0:n.filter(f=>f.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(d="aal2");const g=c.amr||[];return{data:{currentLevel:u,nextLevel:d,currentAuthenticationMethods:g},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 ee(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 ot})})}catch(r){if(Q(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 ot});const a=await ee(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return a.data&&a.data.redirect_url&&Ke()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(Q(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 ot});const a=await ee(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return a.data&&a.data.redirect_url&&Ke()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(Q(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 ee(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 ot})})}catch(e){if(Q(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 ee(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 ot})})}catch(r){if(Q(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(l=>l.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(l=>l.kid===e),s&&this.jwks_cached_at+jl>n)return s;const{data:i,error:a}=await ee(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(l=>l.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:f,error:m}=await this.getSession();if(m||!f.session)return this._returnResult({data:null,error:m});s=f.session.access_token}const{header:n,payload:i,signature:a,raw:{header:l,payload:c}}=Ls(s);r!=null&&r.allowExpired||Gl(i.exp);const u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!u){const{error:f}=await this.getUser(s);if(f)throw f;return{data:{claims:i,header:n,signature:a},error:null}}const d=Jl(n.alg),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,a,Bl(`${l}.${c}`)))throw new En("Invalid JWT signature");return{data:{claims:i,header:n,signature:a},error:null}}catch(s){if(Q(s))return this._returnResult({data:null,error:s});throw s}}}ps.nextInstanceID={};const jc=ps,Tc="2.99.3";let ss="";typeof Deno<"u"?ss="deno":typeof document<"u"?ss="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ss="react-native":ss="node";const Rc={"X-Client-Info":`supabase-js-${ss}/${Tc}`},Cc={headers:Rc},Ac={schema:"public"},Oc={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Pc={};function gs(t){"@babel/helpers - typeof";return gs=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},gs(t)}function Ic(t,e){if(gs(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(gs(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Nc(t){var e=Ic(t,"string");return gs(e)=="symbol"?e:e+""}function Bc(t,e,r){return(e=Nc(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Ai(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 Be(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Ai(Object(r),!0).forEach(function(s){Bc(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Ai(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const Fc=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),$c=()=>Headers,Dc=(t,e,r)=>{const s=Fc(r),n=$c();return async(i,a)=>{var l;const c=(l=await e())!==null&&l!==void 0?l:t;let u=new n(a==null?void 0:a.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),s(i,Be(Be({},a),{},{headers:u}))}};function Lc(t){return t.endsWith("/")?t:t+"/"}function Uc(t,e){var r,s;const{db:n,auth:i,realtime:a,global:l}=t,{db:c,auth:u,realtime:d,global:h}=e,g={db:Be(Be({},c),n),auth:Be(Be({},u),i),realtime:Be(Be({},d),a),storage:{},global:Be(Be(Be({},h),l),{},{headers:Be(Be({},(r=h==null?void 0:h.headers)!==null&&r!==void 0?r:{}),(s=l==null?void 0:l.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return t.accessToken?g.accessToken=t.accessToken:delete g.accessToken,g}function Mc(t){const e=t==null?void 0: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(Lc(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Wc=class extends jc{constructor(t){super(t)}},qc=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=Mc(t);if(!e)throw new Error("supabaseKey is required.");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`,l={db:Ac,realtime:Pc,auth:Be(Be({},Oc),{},{storageKey:a}),global:Cc},c=Uc(r??{},l);if(this.storageKey=(s=c.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},c.accessToken)this.accessToken=c.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=c.auth)!==null&&u!==void 0?u:{},this.headers,c.global.fetch)}this.fetch=Dc(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Be({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.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 Ro(new URL("rest/v1",i).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit}),this.storage=new xl(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new wo(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:a,lock:l,debug:c,throwOnError:u},d,h){const g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Wc({url:this.authUrl.href,headers:Be(Be({},g),d),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:l,debug:c,throwOnError:u,fetch:h,hasCustomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Ho(this.realtimeUrl.href,Be(Be({},t),{},{params:Be(Be({},{apikey:this.supabaseKey}),t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const jn=(t,e,r)=>new qc(t,e,r);function zc(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}zc()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");var js=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},dr,Kt,$r,Ji,Hc=(Ji=class extends js{constructor(){super();se(this,dr);se(this,Kt);se(this,$r);H(this,$r,e=>{if(typeof window<"u"&&window.addEventListener){const r=()=>e();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){w(this,Kt)||this.setEventListener(w(this,$r))}onUnsubscribe(){var e;this.hasListeners()||((e=w(this,Kt))==null||e.call(this),H(this,Kt,void 0))}setEventListener(e){var r;H(this,$r,e),(r=w(this,Kt))==null||r.call(this),H(this,Kt,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){w(this,dr)!==e&&(H(this,dr,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(r=>{r(e)})}isFocused(){var e;return typeof w(this,dr)=="boolean"?w(this,dr):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},dr=new WeakMap,Kt=new WeakMap,$r=new WeakMap,Ji),Hn=new Hc,Kc={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},kt,hr,Qi,Vc=(Qi=class{constructor(){se(this,kt,Kc);se(this,hr,!1)}setTimeoutProvider(t){process.env.NODE_ENV!=="production"&&w(this,hr)&&t!==w(this,kt)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:w(this,kt),provider:t}),H(this,kt,t),process.env.NODE_ENV!=="production"&&H(this,hr,!1)}setTimeout(t,e){return process.env.NODE_ENV!=="production"&&H(this,hr,!0),w(this,kt).setTimeout(t,e)}clearTimeout(t){w(this,kt).clearTimeout(t)}setInterval(t,e){return process.env.NODE_ENV!=="production"&&H(this,hr,!0),w(this,kt).setInterval(t,e)}clearInterval(t){w(this,kt).clearInterval(t)}},kt=new WeakMap,hr=new WeakMap,Qi),ur=new Vc;function Gc(t){setTimeout(t,0)}var Jc=typeof window>"u"||"Deno"in globalThis;function st(){}function Qc(t,e){return typeof t=="function"?t(e):t}function Tn(t){return typeof t=="number"&&t>=0&&t!==1/0}function xa(t,e){return Math.max(t+(e||0)-Date.now(),0)}function Zt(t,e){return typeof t=="function"?t(e):t}function ft(t,e){return typeof t=="function"?t(e):t}function Oi(t,e){const{type:r="all",exact:s,fetchStatus:n,predicate:i,queryKey:a,stale:l}=t;if(a){if(s){if(e.queryHash!==Kn(a,e.options))return!1}else if(!ms(e.queryKey,a))return!1}if(r!=="all"){const c=e.isActive();if(r==="active"&&!c||r==="inactive"&&c)return!1}return!(typeof l=="boolean"&&e.isStale()!==l||n&&n!==e.state.fetchStatus||i&&!i(e))}function Pi(t,e){const{exact:r,status:s,predicate:n,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(r){if(bs(e.options.mutationKey)!==bs(i))return!1}else if(!ms(e.options.mutationKey,i))return!1}return!(s&&e.state.status!==s||n&&!n(e))}function Kn(t,e){return((e==null?void 0:e.queryKeyHashFn)||bs)(t)}function bs(t){return JSON.stringify(t,(e,r)=>An(r)?Object.keys(r).sort().reduce((s,n)=>(s[n]=r[n],s),{}):r)}function ms(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(r=>ms(t[r],e[r])):!1}var Yc=Object.prototype.hasOwnProperty;function Rn(t,e,r=0){if(t===e)return t;if(r>500)return e;const s=Ii(t)&&Ii(e);if(!s&&!(An(t)&&An(e)))return e;const i=(s?t:Object.keys(t)).length,a=s?e:Object.keys(e),l=a.length,c=s?new Array(l):{};let u=0;for(let d=0;d<l;d++){const h=s?d:a[d],g=t[h],f=e[h];if(g===f){c[h]=g,(s?d<i:Yc.call(t,h))&&u++;continue}if(g===null||f===null||typeof g!="object"||typeof f!="object"){c[h]=f;continue}const m=Rn(g,f,r+1);c[h]=m,m===g&&u++}return i===l&&u===i?t:c}function Cn(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(const r in t)if(t[r]!==e[r])return!1;return!0}function Ii(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function An(t){if(!Ni(t))return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(!Ni(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function Ni(t){return Object.prototype.toString.call(t)==="[object Object]"}function Xc(t){return new Promise(e=>{ur.setTimeout(e,t)})}function On(t,e,r){if(typeof r.structuralSharing=="function")return r.structuralSharing(t,e);if(r.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return Rn(t,e)}catch(s){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${r.queryHash}]: ${s}`),s}return Rn(t,e)}return e}function Zc(t,e,r=0){const s=[...t,e];return r&&s.length>r?s.slice(1):s}function eu(t,e,r=0){const s=[e,...t];return r&&s.length>r?s.slice(0,-1):s}var zs=Symbol();function _a(t,e){return process.env.NODE_ENV!=="production"&&t.queryFn===zs&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${t.queryHash}'`),!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===zs?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function ka(t,e){return typeof t=="function"?t(...e):!!t}function tu(t,e,r){let s=!1,n;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(n??(n=e()),s||(s=!0,n.aborted?r():n.addEventListener("abort",r,{once:!0})),n)}),t}var ys=(()=>{let t=()=>Jc;return{isServer(){return t()},setIsServer(e){t=e}}})();function Pn(){let t,e;const r=new Promise((n,i)=>{t=n,e=i});r.status="pending",r.catch(()=>{});function s(n){Object.assign(r,n),delete r.resolve,delete r.reject}return r.resolve=n=>{s({status:"fulfilled",value:n}),t(n)},r.reject=n=>{s({status:"rejected",reason:n}),e(n)},r}var ru=Gc;function su(){let t=[],e=0,r=l=>{l()},s=l=>{l()},n=ru;const i=l=>{e?t.push(l):n(()=>{r(l)})},a=()=>{const l=t;t=[],l.length&&n(()=>{s(()=>{l.forEach(c=>{r(c)})})})};return{batch:l=>{let c;e++;try{c=l()}finally{e--,e||a()}return c},batchCalls:l=>(...c)=>{i(()=>{l(...c)})},schedule:i,setNotifyFunction:l=>{r=l},setBatchNotifyFunction:l=>{s=l},setScheduler:l=>{n=l}}}var Ve=su(),Dr,Vt,Lr,Yi,nu=(Yi=class extends js{constructor(){super();se(this,Dr,!0);se(this,Vt);se(this,Lr);H(this,Lr,e=>{if(typeof window<"u"&&window.addEventListener){const r=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",s)}}})}onSubscribe(){w(this,Vt)||this.setEventListener(w(this,Lr))}onUnsubscribe(){var e;this.hasListeners()||((e=w(this,Vt))==null||e.call(this),H(this,Vt,void 0))}setEventListener(e){var r;H(this,Lr,e),(r=w(this,Vt))==null||r.call(this),H(this,Vt,e(this.setOnline.bind(this)))}setOnline(e){w(this,Dr)!==e&&(H(this,Dr,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return w(this,Dr)}},Dr=new WeakMap,Vt=new WeakMap,Lr=new WeakMap,Yi),Hs=new nu;function iu(t){return Math.min(1e3*2**t,3e4)}function Sa(t){return(t??"online")==="online"?Hs.isOnline():!0}var In=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function Ea(t){let e=!1,r=0,s;const n=Pn(),i=()=>n.status!=="pending",a=b=>{var _;if(!i()){const y=new In(b);g(y),(_=t.onCancel)==null||_.call(t,y)}},l=()=>{e=!0},c=()=>{e=!1},u=()=>Hn.isFocused()&&(t.networkMode==="always"||Hs.isOnline())&&t.canRun(),d=()=>Sa(t.networkMode)&&t.canRun(),h=b=>{i()||(s==null||s(),n.resolve(b))},g=b=>{i()||(s==null||s(),n.reject(b))},f=()=>new Promise(b=>{var _;s=y=>{(i()||u())&&b(y)},(_=t.onPause)==null||_.call(t)}).then(()=>{var b;s=void 0,i()||(b=t.onContinue)==null||b.call(t)}),m=()=>{if(i())return;let b;const _=r===0?t.initialPromise:void 0;try{b=_??t.fn()}catch(y){b=Promise.reject(y)}Promise.resolve(b).then(h).catch(y=>{var S;if(i())return;const k=t.retry??(ys.isServer()?0:3),j=t.retryDelay??iu,x=typeof j=="function"?j(r,y):j,T=k===!0||typeof k=="number"&&r<k||typeof k=="function"&&k(r,y);if(e||!T){g(y);return}r++,(S=t.onFail)==null||S.call(t,r,y),Xc(x).then(()=>u()?void 0:f()).then(()=>{e?g(y):m()})})};return{promise:n,status:()=>n.status,cancel:a,continue:()=>(s==null||s(),n),cancelRetry:l,continueRetry:c,canStart:d,start:()=>(d()?m():f().then(m),n)}}var fr,Xi,ja=(Xi=class{constructor(){se(this,fr)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Tn(this.gcTime)&&H(this,fr,ur.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(ys.isServer()?1/0:5*60*1e3))}clearGcTimeout(){w(this,fr)&&(ur.clearTimeout(w(this,fr)),H(this,fr,void 0))}},fr=new WeakMap,Xi),pr,Ur,ht,gr,qe,ws,br,lt,Ta,Ct,Zi,au=(Zi=class extends ja{constructor(e){super();se(this,lt);se(this,pr);se(this,Ur);se(this,ht);se(this,gr);se(this,qe);se(this,ws);se(this,br);H(this,br,!1),H(this,ws,e.defaultOptions),this.setOptions(e.options),this.observers=[],H(this,gr,e.client),H(this,ht,w(this,gr).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,H(this,pr,Fi(this.options)),this.state=e.state??w(this,pr),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=w(this,qe))==null?void 0:e.promise}setOptions(e){if(this.options={...w(this,ws),...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const r=Fi(this.options);r.data!==void 0&&(this.setState(Bi(r.data,r.dataUpdatedAt)),H(this,pr,r))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&w(this,ht).remove(this)}setData(e,r){const s=On(this.state.data,e,this.options);return pe(this,lt,Ct).call(this,{data:s,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),s}setState(e,r){pe(this,lt,Ct).call(this,{type:"setState",state:e,setStateOptions:r})}cancel(e){var s,n;const r=(s=w(this,qe))==null?void 0:s.promise;return(n=w(this,qe))==null||n.cancel(e),r?r.then(st).catch(st):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return w(this,pr)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>ft(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===zs||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Zt(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!xa(this.state.dataUpdatedAt,e)}onFocus(){var r;const e=this.observers.find(s=>s.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(r=w(this,qe))==null||r.continue()}onOnline(){var r;const e=this.observers.find(s=>s.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(r=w(this,qe))==null||r.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),w(this,ht).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(r=>r!==e),this.observers.length||(w(this,qe)&&(w(this,br)||pe(this,lt,Ta).call(this)?w(this,qe).cancel({revert:!0}):w(this,qe).cancelRetry()),this.scheduleGc()),w(this,ht).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||pe(this,lt,Ct).call(this,{type:"invalidate"})}async fetch(e,r){var c,u,d,h,g,f,m,b,_,y,k,j;if(this.state.fetchStatus!=="idle"&&((c=w(this,qe))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(w(this,qe))return w(this,qe).continueRetry(),w(this,qe).promise}if(e&&this.setOptions(e),!this.options.queryFn){const x=this.observers.find(T=>T.options.queryFn);x&&this.setOptions(x.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const s=new AbortController,n=x=>{Object.defineProperty(x,"signal",{enumerable:!0,get:()=>(H(this,br,!0),s.signal)})},i=()=>{const x=_a(this.options,r),S=(()=>{const F={client:w(this,gr),queryKey:this.queryKey,meta:this.meta};return n(F),F})();return H(this,br,!1),this.options.persister?this.options.persister(x,S,this):x(S)},l=(()=>{const x={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:w(this,gr),state:this.state,fetchFn:i};return n(x),x})();(u=this.options.behavior)==null||u.onFetch(l,this),H(this,Ur,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((d=l.fetchOptions)==null?void 0:d.meta))&&pe(this,lt,Ct).call(this,{type:"fetch",meta:(h=l.fetchOptions)==null?void 0:h.meta}),H(this,qe,Ea({initialPromise:r==null?void 0:r.initialPromise,fn:l.fetchFn,onCancel:x=>{x instanceof In&&x.revert&&this.setState({...w(this,Ur),fetchStatus:"idle"}),s.abort()},onFail:(x,T)=>{pe(this,lt,Ct).call(this,{type:"failed",failureCount:x,error:T})},onPause:()=>{pe(this,lt,Ct).call(this,{type:"pause"})},onContinue:()=>{pe(this,lt,Ct).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode,canRun:()=>!0}));try{const x=await w(this,qe).start();if(x===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(x),(f=(g=w(this,ht).config).onSuccess)==null||f.call(g,x,this),(b=(m=w(this,ht).config).onSettled)==null||b.call(m,x,this.state.error,this),x}catch(x){if(x instanceof In){if(x.silent)return w(this,qe).promise;if(x.revert){if(this.state.data===void 0)throw x;return this.state.data}}throw pe(this,lt,Ct).call(this,{type:"error",error:x}),(y=(_=w(this,ht).config).onError)==null||y.call(_,x,this),(j=(k=w(this,ht).config).onSettled)==null||j.call(k,this.state.data,x,this),x}finally{this.scheduleGc()}}},pr=new WeakMap,Ur=new WeakMap,ht=new WeakMap,gr=new WeakMap,qe=new WeakMap,ws=new WeakMap,br=new WeakMap,lt=new WeakSet,Ta=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ct=function(e){const r=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...Ra(s.data,this.options),fetchMeta:e.meta??null};case"success":const n={...s,...Bi(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return H(this,Ur,e.manual?n:void 0),n;case"error":const i=e.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=r(this.state),Ve.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),w(this,ht).notify({query:this,type:"updated",action:e})})},Zi);function Ra(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Sa(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function Bi(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Fi(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,r=e!==void 0,s=r?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:r?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var rt,ge,xs,et,mr,Mr,Ot,Gt,_s,Wr,qr,yr,vr,Jt,zr,xe,ns,Nn,Bn,Fn,$n,Dn,Ln,Un,Ca,ea,ou=(ea=class extends js{constructor(e,r){super();se(this,xe);se(this,rt);se(this,ge);se(this,xs);se(this,et);se(this,mr);se(this,Mr);se(this,Ot);se(this,Gt);se(this,_s);se(this,Wr);se(this,qr);se(this,yr);se(this,vr);se(this,Jt);se(this,zr,new Set);this.options=r,H(this,rt,e),H(this,Gt,null),H(this,Ot,Pn()),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(w(this,ge).addObserver(this),$i(w(this,ge),this.options)?pe(this,xe,ns).call(this):this.updateResult(),pe(this,xe,$n).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Mn(w(this,ge),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Mn(w(this,ge),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,pe(this,xe,Dn).call(this),pe(this,xe,Ln).call(this),w(this,ge).removeObserver(this)}setOptions(e){const r=this.options,s=w(this,ge);if(this.options=w(this,rt).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ft(this.options.enabled,w(this,ge))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");pe(this,xe,Un).call(this),w(this,ge).setOptions(this.options),r._defaulted&&!Cn(this.options,r)&&w(this,rt).getQueryCache().notify({type:"observerOptionsUpdated",query:w(this,ge),observer:this});const n=this.hasListeners();n&&Di(w(this,ge),s,this.options,r)&&pe(this,xe,ns).call(this),this.updateResult(),n&&(w(this,ge)!==s||ft(this.options.enabled,w(this,ge))!==ft(r.enabled,w(this,ge))||Zt(this.options.staleTime,w(this,ge))!==Zt(r.staleTime,w(this,ge)))&&pe(this,xe,Nn).call(this);const i=pe(this,xe,Bn).call(this);n&&(w(this,ge)!==s||ft(this.options.enabled,w(this,ge))!==ft(r.enabled,w(this,ge))||i!==w(this,Jt))&&pe(this,xe,Fn).call(this,i)}getOptimisticResult(e){const r=w(this,rt).getQueryCache().build(w(this,rt),e),s=this.createResult(r,e);return cu(this,s)&&(H(this,et,s),H(this,Mr,this.options),H(this,mr,w(this,ge).state)),s}getCurrentResult(){return w(this,et)}trackResult(e,r){return new Proxy(e,{get:(s,n)=>(this.trackProp(n),r==null||r(n),n==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&w(this,Ot).status==="pending"&&w(this,Ot).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,n))})}trackProp(e){w(this,zr).add(e)}getCurrentQuery(){return w(this,ge)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const r=w(this,rt).defaultQueryOptions(e),s=w(this,rt).getQueryCache().build(w(this,rt),r);return s.fetch().then(()=>this.createResult(s,r))}fetch(e){return pe(this,xe,ns).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),w(this,et)))}createResult(e,r){var P;const s=w(this,ge),n=this.options,i=w(this,et),a=w(this,mr),l=w(this,Mr),u=e!==s?e.state:w(this,xs),{state:d}=e;let h={...d},g=!1,f;if(r._optimisticResults){const C=this.hasListeners(),R=!C&&$i(e,r),O=C&&Di(e,s,r,n);(R||O)&&(h={...h,...Ra(d.data,e.options)}),r._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:m,errorUpdatedAt:b,status:_}=h;f=h.data;let y=!1;if(r.placeholderData!==void 0&&f===void 0&&_==="pending"){let C;i!=null&&i.isPlaceholderData&&r.placeholderData===(l==null?void 0:l.placeholderData)?(C=i.data,y=!0):C=typeof r.placeholderData=="function"?r.placeholderData((P=w(this,qr))==null?void 0:P.state.data,w(this,qr)):r.placeholderData,C!==void 0&&(_="success",f=On(i==null?void 0:i.data,C,r),g=!0)}if(r.select&&f!==void 0&&!y)if(i&&f===(a==null?void 0:a.data)&&r.select===w(this,_s))f=w(this,Wr);else try{H(this,_s,r.select),f=r.select(f),f=On(i==null?void 0:i.data,f,r),H(this,Wr,f),H(this,Gt,null)}catch(C){H(this,Gt,C)}w(this,Gt)&&(m=w(this,Gt),f=w(this,Wr),b=Date.now(),_="error");const k=h.fetchStatus==="fetching",j=_==="pending",x=_==="error",T=j&&k,S=f!==void 0,E={status:_,fetchStatus:h.fetchStatus,isPending:j,isSuccess:_==="success",isError:x,isInitialLoading:T,isLoading:T,data:f,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:b,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:k,isRefetching:k&&!j,isLoadingError:x&&!S,isPaused:h.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:x&&S,isStale:Vn(e,r),refetch:this.refetch,promise:w(this,Ot),isEnabled:ft(r.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const C=E.data!==void 0,R=E.status==="error"&&!C,O=V=>{R?V.reject(E.error):C&&V.resolve(E.data)},A=()=>{const V=H(this,Ot,E.promise=Pn());O(V)},$=w(this,Ot);switch($.status){case"pending":e.queryHash===s.queryHash&&O($);break;case"fulfilled":(R||E.data!==$.value)&&A();break;case"rejected":(!R||E.error!==$.reason)&&A();break}}return E}updateResult(){const e=w(this,et),r=this.createResult(w(this,ge),this.options);if(H(this,mr,w(this,ge).state),H(this,Mr,this.options),w(this,mr).data!==void 0&&H(this,qr,w(this,ge)),Cn(r,e))return;H(this,et,r);const s=()=>{if(!e)return!0;const{notifyOnChangeProps:n}=this.options,i=typeof n=="function"?n():n;if(i==="all"||!i&&!w(this,zr).size)return!0;const a=new Set(i??w(this,zr));return this.options.throwOnError&&a.add("error"),Object.keys(w(this,et)).some(l=>{const c=l;return w(this,et)[c]!==e[c]&&a.has(c)})};pe(this,xe,Ca).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&pe(this,xe,$n).call(this)}},rt=new WeakMap,ge=new WeakMap,xs=new WeakMap,et=new WeakMap,mr=new WeakMap,Mr=new WeakMap,Ot=new WeakMap,Gt=new WeakMap,_s=new WeakMap,Wr=new WeakMap,qr=new WeakMap,yr=new WeakMap,vr=new WeakMap,Jt=new WeakMap,zr=new WeakMap,xe=new WeakSet,ns=function(e){pe(this,xe,Un).call(this);let r=w(this,ge).fetch(this.options,e);return e!=null&&e.throwOnError||(r=r.catch(st)),r},Nn=function(){pe(this,xe,Dn).call(this);const e=Zt(this.options.staleTime,w(this,ge));if(ys.isServer()||w(this,et).isStale||!Tn(e))return;const s=xa(w(this,et).dataUpdatedAt,e)+1;H(this,yr,ur.setTimeout(()=>{w(this,et).isStale||this.updateResult()},s))},Bn=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(w(this,ge)):this.options.refetchInterval)??!1},Fn=function(e){pe(this,xe,Ln).call(this),H(this,Jt,e),!(ys.isServer()||ft(this.options.enabled,w(this,ge))===!1||!Tn(w(this,Jt))||w(this,Jt)===0)&&H(this,vr,ur.setInterval(()=>{(this.options.refetchIntervalInBackground||Hn.isFocused())&&pe(this,xe,ns).call(this)},w(this,Jt)))},$n=function(){pe(this,xe,Nn).call(this),pe(this,xe,Fn).call(this,pe(this,xe,Bn).call(this))},Dn=function(){w(this,yr)&&(ur.clearTimeout(w(this,yr)),H(this,yr,void 0))},Ln=function(){w(this,vr)&&(ur.clearInterval(w(this,vr)),H(this,vr,void 0))},Un=function(){const e=w(this,rt).getQueryCache().build(w(this,rt),this.options);if(e===w(this,ge))return;const r=w(this,ge);H(this,ge,e),H(this,xs,e.state),this.hasListeners()&&(r==null||r.removeObserver(this),e.addObserver(this))},Ca=function(e){Ve.batch(()=>{e.listeners&&this.listeners.forEach(r=>{r(w(this,et))}),w(this,rt).getQueryCache().notify({query:w(this,ge),type:"observerResultsUpdated"})})},ea);function lu(t,e){return ft(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function $i(t,e){return lu(t,e)||t.state.data!==void 0&&Mn(t,e,e.refetchOnMount)}function Mn(t,e,r){if(ft(e.enabled,t)!==!1&&Zt(e.staleTime,t)!=="static"){const s=typeof r=="function"?r(t):r;return s==="always"||s!==!1&&Vn(t,e)}return!1}function Di(t,e,r,s){return(t!==e||ft(s.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&Vn(t,r)}function Vn(t,e){return ft(e.enabled,t)!==!1&&t.isStaleByTime(Zt(e.staleTime,t))}function cu(t,e){return!Cn(t.getCurrentResult(),e)}function Li(t){return{onFetch:(e,r)=>{var d,h,g,f,m;const s=e.options,n=(g=(h=(d=e.fetchOptions)==null?void 0:d.meta)==null?void 0:h.fetchMore)==null?void 0:g.direction,i=((f=e.state.data)==null?void 0:f.pages)||[],a=((m=e.state.data)==null?void 0:m.pageParams)||[];let l={pages:[],pageParams:[]},c=0;const u=async()=>{let b=!1;const _=j=>{tu(j,()=>e.signal,()=>b=!0)},y=_a(e.options,e.fetchOptions),k=async(j,x,T)=>{if(b)return Promise.reject();if(x==null&&j.pages.length)return Promise.resolve(j);const F=(()=>{const R={client:e.client,queryKey:e.queryKey,pageParam:x,direction:T?"backward":"forward",meta:e.options.meta};return _(R),R})(),E=await y(F),{maxPages:P}=e.options,C=T?eu:Zc;return{pages:C(j.pages,E,P),pageParams:C(j.pageParams,x,P)}};if(n&&i.length){const j=n==="backward",x=j?uu:Ui,T={pages:i,pageParams:a},S=x(s,T);l=await k(T,S,j)}else{const j=t??i.length;do{const x=c===0?a[0]??s.initialPageParam:Ui(s,l);if(c>0&&x==null)break;l=await k(l,x),c++}while(c<j)}return l};e.options.persister?e.fetchFn=()=>{var b,_;return(_=(b=e.options).persister)==null?void 0:_.call(b,u,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r)}:e.fetchFn=u}}}function Ui(t,{pages:e,pageParams:r}){const s=e.length-1;return e.length>0?t.getNextPageParam(e[s],e,r[s],r):void 0}function uu(t,{pages:e,pageParams:r}){var s;return e.length>0?(s=t.getPreviousPageParam)==null?void 0:s.call(t,e[0],e,r[0],r):void 0}var ks,St,Ye,wr,Et,qt,ta,du=(ta=class extends ja{constructor(e){super();se(this,Et);se(this,ks);se(this,St);se(this,Ye);se(this,wr);H(this,ks,e.client),this.mutationId=e.mutationId,H(this,Ye,e.mutationCache),H(this,St,[]),this.state=e.state||hu(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){w(this,St).includes(e)||(w(this,St).push(e),this.clearGcTimeout(),w(this,Ye).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){H(this,St,w(this,St).filter(r=>r!==e)),this.scheduleGc(),w(this,Ye).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){w(this,St).length||(this.state.status==="pending"?this.scheduleGc():w(this,Ye).remove(this))}continue(){var e;return((e=w(this,wr))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var a,l,c,u,d,h,g,f,m,b,_,y,k,j,x,T,S,F;const r=()=>{pe(this,Et,qt).call(this,{type:"continue"})},s={client:w(this,ks),meta:this.options.meta,mutationKey:this.options.mutationKey};H(this,wr,Ea({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(E,P)=>{pe(this,Et,qt).call(this,{type:"failed",failureCount:E,error:P})},onPause:()=>{pe(this,Et,qt).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>w(this,Ye).canRun(this)}));const n=this.state.status==="pending",i=!w(this,wr).canStart();try{if(n)r();else{pe(this,Et,qt).call(this,{type:"pending",variables:e,isPaused:i}),w(this,Ye).config.onMutate&&await w(this,Ye).config.onMutate(e,this,s);const P=await((l=(a=this.options).onMutate)==null?void 0:l.call(a,e,s));P!==this.state.context&&pe(this,Et,qt).call(this,{type:"pending",context:P,variables:e,isPaused:i})}const E=await w(this,wr).start();return await((u=(c=w(this,Ye).config).onSuccess)==null?void 0:u.call(c,E,e,this.state.context,this,s)),await((h=(d=this.options).onSuccess)==null?void 0:h.call(d,E,e,this.state.context,s)),await((f=(g=w(this,Ye).config).onSettled)==null?void 0:f.call(g,E,null,this.state.variables,this.state.context,this,s)),await((b=(m=this.options).onSettled)==null?void 0:b.call(m,E,null,e,this.state.context,s)),pe(this,Et,qt).call(this,{type:"success",data:E}),E}catch(E){try{await((y=(_=w(this,Ye).config).onError)==null?void 0:y.call(_,E,e,this.state.context,this,s))}catch(P){Promise.reject(P)}try{await((j=(k=this.options).onError)==null?void 0:j.call(k,E,e,this.state.context,s))}catch(P){Promise.reject(P)}try{await((T=(x=w(this,Ye).config).onSettled)==null?void 0:T.call(x,void 0,E,this.state.variables,this.state.context,this,s))}catch(P){Promise.reject(P)}try{await((F=(S=this.options).onSettled)==null?void 0:F.call(S,void 0,E,e,this.state.context,s))}catch(P){Promise.reject(P)}throw pe(this,Et,qt).call(this,{type:"error",error:E}),E}finally{w(this,Ye).runNext(this)}}},ks=new WeakMap,St=new WeakMap,Ye=new WeakMap,wr=new WeakMap,Et=new WeakSet,qt=function(e){const r=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=r(this.state),Ve.batch(()=>{w(this,St).forEach(s=>{s.onMutationUpdate(e)}),w(this,Ye).notify({mutation:this,type:"updated",action:e})})},ta);function hu(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Pt,wt,Ss,ra,fu=(ra=class extends js{constructor(e={}){super();se(this,Pt);se(this,wt);se(this,Ss);this.config=e,H(this,Pt,new Set),H(this,wt,new Map),H(this,Ss,0)}build(e,r,s){const n=new du({client:e,mutationCache:this,mutationId:++Is(this,Ss)._,options:e.defaultMutationOptions(r),state:s});return this.add(n),n}add(e){w(this,Pt).add(e);const r=Us(e);if(typeof r=="string"){const s=w(this,wt).get(r);s?s.push(e):w(this,wt).set(r,[e])}this.notify({type:"added",mutation:e})}remove(e){if(w(this,Pt).delete(e)){const r=Us(e);if(typeof r=="string"){const s=w(this,wt).get(r);if(s)if(s.length>1){const n=s.indexOf(e);n!==-1&&s.splice(n,1)}else s[0]===e&&w(this,wt).delete(r)}}this.notify({type:"removed",mutation:e})}canRun(e){const r=Us(e);if(typeof r=="string"){const s=w(this,wt).get(r),n=s==null?void 0:s.find(i=>i.state.status==="pending");return!n||n===e}else return!0}runNext(e){var s;const r=Us(e);if(typeof r=="string"){const n=(s=w(this,wt).get(r))==null?void 0:s.find(i=>i!==e&&i.state.isPaused);return(n==null?void 0:n.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Ve.batch(()=>{w(this,Pt).forEach(e=>{this.notify({type:"removed",mutation:e})}),w(this,Pt).clear(),w(this,wt).clear()})}getAll(){return Array.from(w(this,Pt))}find(e){const r={exact:!0,...e};return this.getAll().find(s=>Pi(r,s))}findAll(e={}){return this.getAll().filter(r=>Pi(e,r))}notify(e){Ve.batch(()=>{this.listeners.forEach(r=>{r(e)})})}resumePausedMutations(){const e=this.getAll().filter(r=>r.state.isPaused);return Ve.batch(()=>Promise.all(e.map(r=>r.continue().catch(st))))}},Pt=new WeakMap,wt=new WeakMap,Ss=new WeakMap,ra);function Us(t){var e;return(e=t.options.scope)==null?void 0:e.id}var jt,sa,pu=(sa=class extends js{constructor(e={}){super();se(this,jt);this.config=e,H(this,jt,new Map)}build(e,r,s){const n=r.queryKey,i=r.queryHash??Kn(n,r);let a=this.get(i);return a||(a=new au({client:e,queryKey:n,queryHash:i,options:e.defaultQueryOptions(r),state:s,defaultOptions:e.getQueryDefaults(n)}),this.add(a)),a}add(e){w(this,jt).has(e.queryHash)||(w(this,jt).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const r=w(this,jt).get(e.queryHash);r&&(e.destroy(),r===e&&w(this,jt).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Ve.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return w(this,jt).get(e)}getAll(){return[...w(this,jt).values()]}find(e){const r={exact:!0,...e};return this.getAll().find(s=>Oi(r,s))}findAll(e={}){const r=this.getAll();return Object.keys(e).length>0?r.filter(s=>Oi(e,s)):r}notify(e){Ve.batch(()=>{this.listeners.forEach(r=>{r(e)})})}onFocus(){Ve.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Ve.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},jt=new WeakMap,sa),Ne,Qt,Yt,Hr,Kr,Xt,Vr,Gr,na,gu=(na=class{constructor(t={}){se(this,Ne);se(this,Qt);se(this,Yt);se(this,Hr);se(this,Kr);se(this,Xt);se(this,Vr);se(this,Gr);H(this,Ne,t.queryCache||new pu),H(this,Qt,t.mutationCache||new fu),H(this,Yt,t.defaultOptions||{}),H(this,Hr,new Map),H(this,Kr,new Map),H(this,Xt,0)}mount(){Is(this,Xt)._++,w(this,Xt)===1&&(H(this,Vr,Hn.subscribe(async t=>{t&&(await this.resumePausedMutations(),w(this,Ne).onFocus())})),H(this,Gr,Hs.subscribe(async t=>{t&&(await this.resumePausedMutations(),w(this,Ne).onOnline())})))}unmount(){var t,e;Is(this,Xt)._--,w(this,Xt)===0&&((t=w(this,Vr))==null||t.call(this),H(this,Vr,void 0),(e=w(this,Gr))==null||e.call(this),H(this,Gr,void 0))}isFetching(t){return w(this,Ne).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return w(this,Qt).findAll({...t,status:"pending"}).length}getQueryData(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=w(this,Ne).get(e.queryHash))==null?void 0:r.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),r=w(this,Ne).build(this,e),s=r.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(Zt(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return w(this,Ne).findAll(t).map(({queryKey:e,state:r})=>{const s=r.data;return[e,s]})}setQueryData(t,e,r){const s=this.defaultQueryOptions({queryKey:t}),n=w(this,Ne).get(s.queryHash),i=n==null?void 0:n.state.data,a=Qc(e,i);if(a!==void 0)return w(this,Ne).build(this,s).setData(a,{...r,manual:!0})}setQueriesData(t,e,r){return Ve.batch(()=>w(this,Ne).findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,r)]))}getQueryState(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=w(this,Ne).get(e.queryHash))==null?void 0:r.state}removeQueries(t){const e=w(this,Ne);Ve.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){const r=w(this,Ne);return Ve.batch(()=>(r.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const r={revert:!0,...e},s=Ve.batch(()=>w(this,Ne).findAll(t).map(n=>n.cancel(r)));return Promise.all(s).then(st).catch(st)}invalidateQueries(t,e={}){return Ve.batch(()=>(w(this,Ne).findAll(t).forEach(r=>{r.invalidate()}),(t==null?void 0:t.refetchType)==="none"?Promise.resolve():this.refetchQueries({...t,type:(t==null?void 0:t.refetchType)??(t==null?void 0:t.type)??"active"},e)))}refetchQueries(t,e={}){const r={...e,cancelRefetch:e.cancelRefetch??!0},s=Ve.batch(()=>w(this,Ne).findAll(t).filter(n=>!n.isDisabled()&&!n.isStatic()).map(n=>{let i=n.fetch(void 0,r);return r.throwOnError||(i=i.catch(st)),n.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(s).then(st)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=w(this,Ne).build(this,e);return r.isStaleByTime(Zt(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(st).catch(st)}fetchInfiniteQuery(t){return t.behavior=Li(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(st).catch(st)}ensureInfiniteQueryData(t){return t.behavior=Li(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return Hs.isOnline()?w(this,Qt).resumePausedMutations():Promise.resolve()}getQueryCache(){return w(this,Ne)}getMutationCache(){return w(this,Qt)}getDefaultOptions(){return w(this,Yt)}setDefaultOptions(t){H(this,Yt,t)}setQueryDefaults(t,e){w(this,Hr).set(bs(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...w(this,Hr).values()],r={};return e.forEach(s=>{ms(t,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(t,e){w(this,Kr).set(bs(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...w(this,Kr).values()],r={};return e.forEach(s=>{ms(t,s.mutationKey)&&Object.assign(r,s.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;const e={...w(this,Yt).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=Kn(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===zs&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...w(this,Yt).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){w(this,Ne).clear(),w(this,Qt).clear()}},Ne=new WeakMap,Qt=new WeakMap,Yt=new WeakMap,Hr=new WeakMap,Kr=new WeakMap,Xt=new WeakMap,Vr=new WeakMap,Gr=new WeakMap,na),Aa=pt.createContext(void 0),Oa=t=>{const e=pt.useContext(Aa);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},bu=({client:t,children:e})=>(pt.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),o.jsx(Aa.Provider,{value:t,children:e})),Pa=pt.createContext(!1),mu=()=>pt.useContext(Pa);Pa.Provider;function yu(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var vu=pt.createContext(yu()),wu=()=>pt.useContext(vu),xu=(t,e,r)=>{const s=r!=null&&r.state.error&&typeof t.throwOnError=="function"?ka(t.throwOnError,[r.state.error,r]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},_u=t=>{pt.useEffect(()=>{t.clearReset()},[t])},ku=({result:t,errorResetBoundary:e,throwOnError:r,query:s,suspense:n})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(n&&t.data===void 0||ka(r,[t.error,s])),Su=t=>{if(t.suspense){const r=n=>n==="static"?n:Math.max(n??1e3,1e3),s=t.staleTime;t.staleTime=typeof s=="function"?(...n)=>r(s(...n)):r(s),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},Eu=(t,e)=>t.isLoading&&t.isFetching&&!e,ju=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,Mi=(t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()});function Tu(t,e,r){var g,f,m,b;if(process.env.NODE_ENV!=="production"&&(typeof t!="object"||Array.isArray(t)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const s=mu(),n=wu(),i=Oa(),a=i.defaultQueryOptions(t);(f=(g=i.getDefaultOptions().queries)==null?void 0:g._experimental_beforeQuery)==null||f.call(g,a);const l=i.getQueryCache().get(a.queryHash);process.env.NODE_ENV!=="production"&&(a.queryFn||console.error(`[${a.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),a._optimisticResults=s?"isRestoring":"optimistic",Su(a),xu(a,n,l),_u(n);const c=!i.getQueryCache().get(a.queryHash),[u]=pt.useState(()=>new e(i,a)),d=u.getOptimisticResult(a),h=!s&&t.subscribed!==!1;if(pt.useSyncExternalStore(pt.useCallback(_=>{const y=h?u.subscribe(Ve.batchCalls(_)):st;return u.updateResult(),y},[u,h]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),pt.useEffect(()=>{u.setOptions(a)},[a,u]),ju(a,d))throw Mi(a,u,n);if(ku({result:d,errorResetBoundary:n,throwOnError:a.throwOnError,query:l,suspense:a.suspense}))throw d.error;if((b=(m=i.getDefaultOptions().queries)==null?void 0:m._experimental_afterQuery)==null||b.call(m,a,d),a.experimental_prefetchInRender&&!ys.isServer()&&Eu(d,s)){const _=c?Mi(a,u,n):l==null?void 0:l.promise;_==null||_.catch(st).finally(()=>{u.updateResult()})}return a.notifyOnChangeProps?d:u.trackResult(d)}function Ts(t,e){return Tu(t,ou)}const Ru=5e3,Cu=()=>`bob_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;function Ia({ga4Config:t,hostContext:e,callbacks:r,enabled:s=!0,bobSupabaseUrl:n,bobSupabaseKey:i}){const a=p.useRef(Cu()),l=p.useRef(!1),c=p.useRef(null),u=p.useRef(!1),d=p.useCallback((E,P)=>{if(!(!(t!=null&&t.measurementId)||typeof window>"u")&&window.gtag){const C={...P,send_to:t.measurementId};t.debug&&console.log("[BobAnalytics] GA4 event:",E,C),window.gtag("event",E,C)}},[t]),h=p.useCallback((E,P={})=>{var R,O,A,$,V,z,ie,Y;if(!s)return;const C={event_name:E,timestamp:new Date().toISOString(),session_id:a.current,user_email:(R=e==null?void 0:e.user)==null?void 0:R.email,user_id:(O=e==null?void 0:e.user)==null?void 0:O.id,vehicle_id:(V=($=(A=e==null?void 0:e.vehicle)==null?void 0:A.selectedVehicle)==null?void 0:$.vehicle_id)==null?void 0:V.toString(),rego:(ie=(z=e==null?void 0:e.vehicle)==null?void 0:z.selectedVehicle)==null?void 0:ie.rego,parameters:P};d(E,{session_id:C.session_id,user_email:C.user_email,vehicle_id:C.vehicle_id,...P}),(Y=r==null?void 0:r.onAnalyticsEvent)==null||Y.call(r,C),t!=null&&t.debug&&console.log("[BobAnalytics] Event tracked:",C)},[s,e,r,d,t==null?void 0:t.debug]),g=p.useCallback(()=>{var E,P,C;l.current||(l.current=!0,h("bob_session_start",{widget_version:It,has_vehicle:!!((E=e==null?void 0:e.vehicle)!=null&&E.selectedVehicle),has_user:!!((P=e==null?void 0:e.user)!=null&&P.id)||!!((C=e==null?void 0:e.user)!=null&&C.email)}))},[h,e]),f=p.useCallback((E,P)=>{h("bob_message_sent",{message_length:E,has_vehicle:P})},[h]),m=p.useCallback(E=>{h("bob_vehicle_identified",{vehicle_make:E.make||"unknown",vehicle_model:E.model||"unknown",vehicle_year:E.year||"unknown",rego:E.rego})},[h]),b=p.useCallback((E,P)=>{h("bob_parts_viewed",{part_count:E,vehicle_id:P})},[h]),_=p.useCallback(E=>{h("bob_product_clicked",{sku:E.sku,product_name:E.product_name,price:E.price,brand:E.brand})},[h]),y=p.useCallback(E=>{h("bob_product_viewed",{sku:E.sku,product_name:E.product_name,price:E.price,brand:E.brand})},[h]),k=p.useCallback(E=>{h("bob_add_to_cart",{sku:E.sku,product_name:E.product_name,price:E.price,brand:E.brand,quantity:E.quantity??1})},[h]),j=p.useCallback((E,P)=>{h("bob_checkout_started",{cart_value:E,item_count:P})},[h]),x=p.useCallback(E=>{const P=Math.ceil(E/5/150*60);h("bob_speech_played",{text_length:E,duration_estimate:P})},[h]),T=p.useCallback(E=>{h("bob_speech_failed",{text_length:E})},[h]),S=p.useCallback((E,P)=>{h("bob_error",{error_type:E,error_message:P})},[h]),F=p.useCallback(E=>{if(!s||!n||!i)return;const P=(E==null?void 0:E.led_to_cart)||(E==null?void 0:E.had_product_match),C=()=>{var O,A,$,V,z,ie;u.current=!1;const R={session_id:a.current,user_id:((O=e==null?void 0:e.user)==null?void 0:O.id)||null,channel:"web",vehicle_id:(E==null?void 0:E.vehicle_id)||((V=($=(A=e==null?void 0:e.vehicle)==null?void 0:A.selectedVehicle)==null?void 0:$.vehicle_id)==null?void 0:V.toString())||null,rego:(E==null?void 0:E.rego)||((ie=(z=e==null?void 0:e.vehicle)==null?void 0:z.selectedVehicle)==null?void 0:ie.rego)||null,had_product_match:(E==null?void 0:E.had_product_match)||!1,led_to_cart:(E==null?void 0:E.led_to_cart)||!1};fetch(`${n}/functions/v1/bob-conversation-track`,{method:"POST",headers:{"Content-Type":"application/json",apikey:i},body:JSON.stringify(R)}).catch(Y=>{console.warn("[BobAnalytics] Conversation track failed:",Y)})};if(P){c.current&&(clearTimeout(c.current),c.current=null),C();return}u.current||(u.current=!0,c.current=setTimeout(C,Ru))},[s,n,i,e]);return p.useEffect(()=>{g()},[g]),p.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[]),{trackEvent:h,sessionId:a.current,trackSessionStart:g,trackMessageSent:f,trackVehicleIdentified:m,trackPartsViewed:b,trackProductClicked:_,trackProductViewed:y,trackAddToCart:k,trackCheckoutStarted:j,trackSpeechPlayed:x,trackSpeechFailed:T,trackError:S,trackConversationActivity:F}}const Ys=p.createContext(null);function Gn({children:t,bobConfig:e,hostApiConfig:r,hostContext:s={},callbacks:n={},queryClient:i,ga4Config:a,analyticsEnabled:l=!0,bottomOffset:c=0,zIndexBase:u=50}){const d=p.useMemo(()=>new gu({defaultOptions:{queries:{retry:1,staleTime:3e5}}}),[]),h=i||d,g=!!i;p.useEffect(()=>{console.log(`[BobWidget] v${It} initialized`),console.log(`[BobWidget] QueryClient: ${g?"external (shared)":"internal"}`),console.log(`[BobWidget] Analytics: ${l?"enabled":"disabled"}`),a!=null&&a.measurementId&&console.log(`[BobWidget] GA4: ${a.measurementId}`)},[g,l,a==null?void 0:a.measurementId]);const f=p.useMemo(()=>jn(e.supabaseUrl,e.supabaseKey),[e.supabaseUrl,e.supabaseKey]),[m,b]=p.useState(s);p.useEffect(()=>{b(s)},[s]);const _=p.useCallback(k=>{b(j=>({...j,...k}))},[]),y=p.useMemo(()=>({bobSupabase:f,bobConfig:e,hostApiConfig:r,hostContext:m,callbacks:n,updateHostContext:_,ga4Config:a,analyticsEnabled:l,bottomOffset:c,zIndexBase:u}),[f,e,r,m,n,_,a,l,c,u]);return o.jsx(bu,{client:h,children:o.jsx(Ys.Provider,{value:y,children:t})})}function Bt(){const t=p.useContext(Ys);if(!t)throw new Error("useBobContext must be used within a BobProvider");return t}function Au(){const{bobSupabase:t}=Bt();return t}function xr(){const t=p.useContext(Ys);return(t==null?void 0:t.bobSupabase)||null}function Ou(){const{hostContext:t}=Bt();return t}function Pu(){const{hostApiConfig:t}=Bt();return t}function Iu(){const{callbacks:t}=Bt();return t}function Nu(){const{ga4Config:t,analyticsEnabled:e}=Bt();return{ga4Config:t,enabled:e}}function Jn(){const t=p.useContext(Ys);return t?{bottomOffset:t.bottomOffset,zIndexBase:t.zIndexBase}:{bottomOffset:0,zIndexBase:50}}const Bu=15e3,Fu={greeting_returning:/ah hey|you again|what you after this time/i,greeting_welcome:/g'?day|welcome.*carfix|bob.*here/i,ask_rego:/need your rego|rego.*get cracking|what('?s| is) your rego/i,vehicle_not_found:/couldn'?t find that|double.?check.*plate/i,no_parts_found:/nothing came up|no results|sorry.*search/i,checkout_ready:/ready to checkout|checkout.*ready|choice.*checkout/i,rego_searching:/let('?s| us) see what car|sweet.*searching|searching for/i},ts=new Map,$u=t=>t.replace(/\bya\b/gi,"you"),Na=({onStart:t,onEnd:e,onFailed:r}={})=>{const{bobConfig:s,bobSupabase:n}=Bt(),[i,a]=p.useState(!1),l=p.useRef(null),c=p.useRef(null),u=p.useRef(!1),d=p.useRef([]),h=p.useRef(!1),g=p.useRef(!1),f=p.useRef(null),m=p.useRef(null),b=p.useRef(t),_=p.useRef(e),y=p.useRef(r);p.useEffect(()=>{b.current=t,_.current=e,y.current=r},[t,e,r]);const k=p.useCallback(()=>{c.current&&(clearTimeout(c.current),c.current=null)},[]),j=p.useCallback(()=>{var O;u.current||(u.current=!0,console.log("[BobWidget TTS] Fallback: triggering onStart without audio"),(O=b.current)==null||O.call(b))},[]),x=p.useCallback(async O=>{if(ts.has(O)){const A=ts.get(O);return console.log(`[BobWidget TTS] Cache hit for clip: ${O}`,A?"found":"null"),A||null}try{console.log(`[BobWidget TTS] Fetching clip from DB: ${O}`);const{data:A,error:$}=await n.from("bob_audio_clips").select("audio_url").eq("clip_key",O).eq("is_active",!0).single();return $||!A?(console.log(`[BobWidget TTS] No clip found for: ${O}`),ts.set(O,null),null):(console.log(`[BobWidget TTS] Clip found: ${O} -> ${A.audio_url}`),ts.set(O,A),A)}catch(A){return console.warn(`[BobWidget TTS] Clip lookup failed for ${O}:`,A),ts.set(O,null),null}},[n]),T=p.useCallback(async O=>{for(const[A,$]of Object.entries(Fu))if($.test(O)){console.log(`[BobWidget TTS] Pattern matched: ${A}`);const V=await x(A);if(V!=null&&V.audio_url)return V.audio_url}return null},[x]),S=p.useCallback(async()=>{var V,z,ie;if(h.current||d.current.length===0)return;h.current=!0;const O=d.current.shift();if(!O){h.current=!1;return}const{text:A,isGreeting:$}=O;$&&(g.current=!0),u.current=!1,k(),l.current&&(l.current.pause(),l.current=null),c.current=setTimeout(()=>{var Y,U;console.warn("[BobWidget TTS] Timeout - triggering fallback callbacks"),j(),a(!1),g.current=!1,(Y=_.current)==null||Y.call(_),(U=y.current)==null||U.call(y),l.current=null,h.current=!1,S()},Bu);try{let Y=null;if(Y=await T(A),Y)console.log("[BobWidget TTS] Using pre-recorded audio (fast path)");else{console.log("[BobWidget TTS] No pre-recorded clip, using ElevenLabs TTS");const K=$u(A),he=await fetch(`${s.supabaseUrl}/functions/v1/bob-tts-elevenlabs`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.supabaseKey}`},body:JSON.stringify({text:K})});if(!he.ok){const re=await he.json().catch(()=>({}));throw console.error("[BobWidget TTS] Request failed:",re),new Error("TTS request failed")}const Z=await he.blob();Y=URL.createObjectURL(Z)}const U=new Audio(Y);l.current=U,U.onplay=()=>{var K;k(),f.current=null,u.current||(u.current=!0,a(!0),console.log("[BobWidget TTS] Audio playing, triggering onStart (animation: TALKING)"),(K=b.current)==null||K.call(b))},U.onended=()=>{var K;k(),a(!1),g.current=!1,console.log("[BobWidget TTS] Audio ended, triggering onEnd (animation: COMPLETE/IDLE)"),(K=_.current)==null||K.call(_),l.current=null,h.current=!1,S()},U.onerror=K=>{var he,Z;k(),console.warn("[BobWidget TTS] Audio playback error:",K),j(),a(!1),g.current=!1,(he=_.current)==null||he.call(_),(Z=y.current)==null||Z.call(y),l.current=null,h.current=!1,S()};try{await U.play()}catch(K){console.warn("[BobWidget TTS] Audio play() failed (autoplay policy):",K),k(),$&&(f.current=A,console.log("[BobWidget TTS] Greeting stored for retry on user interaction")),j(),a(!1),g.current=!1,(V=_.current)==null||V.call(_),h.current=!1,S()}}catch(Y){k(),console.error("[BobWidget TTS] Speech synthesis error:",Y),j(),a(!1),g.current=!1,(z=_.current)==null||z.call(_),(ie=y.current)==null||ie.call(y),h.current=!1,S()}},[s.supabaseUrl,s.supabaseKey,k,j,T]),F=p.useCallback((O,A=!1)=>{if(O.trim()){if(A){if(m.current===O){console.log(`[BobWidget TTS] Ignoring duplicate greeting: "${O.substring(0,30)}..."`);return}m.current=O,f.current=null}if(g.current&&!A){console.log("[BobWidget TTS] Greeting playing - queueing message"),d.current.push({text:O,isGreeting:A});return}A?d.current.unshift({text:O,isGreeting:A}):d.current.push({text:O,isGreeting:A}),S()}},[S]),E=p.useCallback(()=>{if(f.current&&!l.current&&!h.current){console.log("[BobWidget TTS] Retrying pending greeting on user interaction");const O=f.current;f.current=null,F(O,!0)}},[F]),P=p.useCallback((O=!1)=>{var A;k(),d.current=[],l.current&&(l.current.onended=null,l.current.onerror=null,l.current.pause(),l.current=null),a(!1),g.current=!1,h.current=!1,O||(A=_.current)==null||A.call(_)},[k]),C=p.useCallback(()=>{var O;(O=l.current)==null||O.pause()},[]),R=p.useCallback(()=>{var O;(O=l.current)==null||O.play()},[]);return p.useEffect(()=>()=>{k(),d.current=[],l.current&&(l.current.pause(),l.current=null)},[k]),{speak:F,stop:P,pause:C,resume:R,isSpeaking:i,isSupported:!0,retryPendingGreeting:E}},Wi="bob_last_visit",Du=30;function Ba(t=Du){const[e,r]=p.useState(!1),[s,n]=p.useState(null);return p.useEffect(()=>{try{const i=localStorage.getItem(Wi),a=Date.now();if(i){const l=parseInt(i,10),c=(a-l)/(1e3*60*60*24);c<=t?(r(!0),n(new Date(l)),console.log(`[BobWidget] Returning user detected - last visit ${Math.round(c)} days ago`)):console.log(`[BobWidget] Previous visit was ${Math.round(c)} days ago - treating as new user`)}else console.log("[BobWidget] First time visitor detected");localStorage.setItem(Wi,String(a))}catch(i){console.warn("[BobWidget] Could not access localStorage for returning user detection:",i)}},[t]),{isReturningUser:e,lastVisitDate:s,daysSinceLastVisit:s?Math.round((Date.now()-s.getTime())/(1e3*60*60*24)):null}}const Wn=t=>{if(!t)return t;let e=t;return e=e.replace(/\b(retrieve_parts|lookup_vehicle|search_general_products|retrieve_service_packages|add_to_cart|get_cart|create_checkout|get_customer_context|get_product_details|search_products|check_vehicle_fitment|search_web)\s*\([^)]*\)/gi,""),e=e.replace(/\(\s*(vehicleid|vehicle_id|part_type|query|plate|user_email|sku)\s*=\s*[^)]+\)/gi,""),e=e.replace(/\b(retrieve_parts|lookup_vehicle|search_general_products|retrieve_service_packages|add_to_cart|get_cart|create_checkout|get_customer_context|get_product_details|search_products|check_vehicle_fitment|search_web)\s*\(/gi,""),e=e.replace(/\b(vehicleid|vehicle_id|part_type)\s*=\s*(['"]?[\w\s]+['"]?)\s*,?\s*/gi,""),e=e.replace(/```[\s\S]*?```/g,""),e=e.replace(/\(\s*\)/g,""),e=e.replace(/\s{2,}/g," "),e=e.trim(),e},Lu=t=>{let e=Wn(t);return e=e.replace(/[\[\]{}]/g,""),e=e.replace(/https?:\/\/[^\s]+/g,""),e=e.replace(/\bSKU\s*:?\s*\w+/gi,""),e},Uu=["what version","which version","software version","bob version","your version","current version","running version","version number","what ver","which ver"],qi=["recommend","suggest","need","part","filter","brake","rotor","oil","price","$","stock","available","pads","disc","spark plug","battery","clutch","alternator","starter","muffler","exhaust","service pack","add-on","tyre shine","windscreen wash"],Fa=({setAnimationState:t,manualMode:e=!1,talkingState:r="talking",thinkingState:s="researching",completeState:n="idle",idleState:i="idle",listenState:a="listening",onStreamStart:l,onStreamComplete:c,onShowingProduct:u,onResearchStart:d,onReadyToSpeak:h,onHighlightPart:g,onHighlightProduct:f,onNoPartsFound:m,onAutoFetchComplete:b,onVariantSelectionRequired:_,shelfCategoriesRef:y,initialVehicle:k})=>{var Rs,Cs,As,Os;const{bobConfig:j,hostApiConfig:x,hostContext:T,callbacks:S,ga4Config:F,analyticsEnabled:E}=Bt(),P=Ia({ga4Config:F,hostContext:T,callbacks:S,enabled:E}),{isReturningUser:C}=Ba(),[R,O]=p.useState([]),[A,$]=p.useState(""),[V,z]=p.useState(!1),[ie,Y]=p.useState(!1),[U,K]=p.useState(null),he=p.useRef(null),Z=p.useRef(!1),re=p.useRef(!1),ve=p.useRef(""),D=p.useRef(!1),ae=p.useRef(null);p.useRef(null);const J="carfix_bob_session",B=4*60*60*1e3,Se=p.useRef(!1),ke=(M,te)=>{try{const ue={messages:M??R,vehicleCandidates:je.current,conversationState:Fe.current,identifiedVehicle:te!==void 0?te:U,savedAt:Date.now()};sessionStorage.setItem(J,JSON.stringify(ue))}catch(ue){console.warn("[BobWidget] Failed to save session:",ue)}},we=p.useRef({source:"none",isPlaying:!1,hasCannedAudio:!1,cannedUrl:null,currentAudio:null,searchingQueue:[]}),je=p.useRef([]),Fe=p.useRef("AWAITING_REGO");p.useEffect(()=>{if(!Se.current){Se.current=!0;try{const M=sessionStorage.getItem(J);if(M){const te=JSON.parse(M);if(Date.now()-(te.savedAt||0)<B&&Array.isArray(te.messages)&&te.messages.length>0){console.log("[BobWidget] Restoring session:",te.messages.length,"messages, state:",te.conversationState),O(te.messages),re.current=!0,Array.isArray(te.vehicleCandidates)&&(je.current=te.vehicleCandidates),te.conversationState&&(Fe.current=te.conversationState),te.identifiedVehicle&&(K(te.identifiedVehicle),console.log("[BobWidget] Restored identifiedVehicle:",te.identifiedVehicle.make,te.identifiedVehicle.model));return}else console.log("[BobWidget] Session expired, clearing"),sessionStorage.removeItem(J)}}catch(M){console.warn("[BobWidget] Failed to restore session:",M),sessionStorage.removeItem(J)}k&&(console.log("[BobWidget] Applying initialVehicle:",k.make,k.model),je.current=[k],Fe.current="VEHICLE_CONFIRMED",K(k))}},[]),p.useEffect(()=>{R.length>0&&ke(R)},[R]);const[Le,Xe]=p.useState(!1),ze=()=>{const M=we.current;if(M.currentAudio){try{M.currentAudio.pause(),M.currentAudio.currentTime=0}catch(te){console.warn("[BobWidget] Error stopping audio:",te)}M.currentAudio=null}M.isPlaying=!1,M.source="none",M.searchingQueue=[],Xe(!1),oe()},tt=(M,te,ue)=>{const me=we.current;if(me.isPlaying){if(te==="canned"||te==="searching"&&me.source==="tts")ze();else if(me.source==="canned"){console.log("[BobWidget Audio] Skipping lower priority audio while canned is playing");return}}const Ge=new Audio(M);me.currentAudio=Ge,me.source=te,me.isPlaying=!0,Ge.onplay=()=>{console.log(`[BobWidget Audio] ${te} STARTED:`,M.split("/").pop()),Xe(!0),e||ce(r)},Ge.onended=()=>{console.log(`[BobWidget Audio] ${te} ENDED`),me.currentAudio=null,me.isPlaying=!1,me.source="none",Xe(!1),ue==null||ue()},Ge.onerror=()=>{console.warn(`[BobWidget Audio] ${te} FAILED:`,M),me.currentAudio=null,me.isPlaying=!1,me.source="none",Xe(!1),ue==null||ue()},Ge.play().catch(Ft=>{console.warn(`[BobWidget Audio] ${te} autoplay blocked:`,Ft),me.currentAudio=null,me.isPlaying=!1,me.source="none",ue==null||ue()})},it=()=>{const M=we.current;if(M.hasCannedAudio||M.source==="canned"){console.log("[BobWidget Audio] Skipping searching audio - canned audio takes priority"),M.searchingQueue=[];return}if(M.searchingQueue.length===0){!e&&M.source==="searching"&&ce(s);return}const te=M.searchingQueue.shift();tt(te,"searching",()=>{it()})},Ue=()=>{ae.current&&(clearTimeout(ae.current),ae.current=null)},{speak:N,stop:oe,isSpeaking:Ce,retryPendingGreeting:W}=Na({onStart:()=>{Ue(),D.current=!0,console.log("[BobWidget STATE] Speech STARTED - transitioning to TALK state"),P.trackSpeechPlayed(ve.current.length),h==null||h(),e||(console.log("[BobWidget STATE] Setting state to:",r),ce(r))},onEnd:()=>{Ue(),console.log("[BobWidget STATE] Speech ENDED - transitioning out of TALK state");const M=qi.some(te=>ve.current.toLowerCase().includes(te.toLowerCase()));e||(M&&u?(console.log("[BobWidget STATE] Has products - calling onShowingProduct"),u()):c?(console.log("[BobWidget STATE] Calling onStreamComplete"),c()):(console.log("[BobWidget STATE] Setting state to:",n),ce(n),setTimeout(()=>{console.log("[BobWidget STATE] Post-complete transition to:",a),ce(a)},2e3)))},onFailed:()=>{console.warn("[BobWidget] Speech synthesis failed - fallback triggered"),P.trackSpeechFailed(ve.current.length)}});p.useEffect(()=>{var M;(M=S.onStopSpeechReady)==null||M.call(S,ze)},[]),p.useEffect(()=>{var M;(M=he.current)==null||M.scrollIntoView({behavior:"smooth"})},[R]),p.useEffect(()=>{var te,ue;const M=(te=T.vehicle)==null?void 0:te.selectedVehicle;M&&!U&&(console.log("[BobWidget] Setting vehicle from host context:",M),K(M),(ue=S.onVehicleIdentified)==null||ue.call(S,M),P.trackVehicleIdentified({make:M.make,model:M.model,year:M.year,rego:M.rego}))},[(Rs=T.vehicle)==null?void 0:Rs.selectedVehicle]),p.useEffect(()=>{var M;if(R.length===0&&!re.current){re.current=!0;const te=(M=T.vehicle)==null?void 0:M.selectedVehicle;let ue;C?(ue="Ah hey... you again! What you after this time?",console.log("[BobWidget] Using returning user greeting")):te?ue=`G'day! Saw you've got the ${`${te.year} ${te.make} ${te.model}`} - choice wagon! What can I help you find for it today?`:ue="G'day! Bob from CARFIX here. How can I help ya today?",O([{role:"assistant",content:ue}]),ie||setTimeout(()=>{console.log("[BobWidget] Speaking initial greeting (priority)"),N(ue,!0)},500)}},[(Cs=T.vehicle)==null?void 0:Cs.selectedVehicle,R.length,ie,N]),p.useEffect(()=>{const M=()=>{console.log("[BobWidget] User interaction detected - retrying pending greeting"),W(),document.removeEventListener("click",M),document.removeEventListener("touchstart",M)};return document.addEventListener("click",M,{once:!0}),document.addEventListener("touchstart",M,{once:!0}),()=>{document.removeEventListener("click",M),document.removeEventListener("touchstart",M)}},[W]),p.useEffect(()=>{var tr,$t;const M=(tr=T.vehicle)==null?void 0:tr.selectedVehicle;if(!M||Z.current)return;const te=M.vehicle_id??M.id,ue=Number.parseInt(String(te),10);if(!Number.isFinite(ue)){console.warn("[BobWidget] Vehicle has invalid vehicle_id, cannot auto-fetch:",M);return}Z.current=!0;const me={...M,vehicle_id:String(ue)},Ge=($t=T.user)==null?void 0:$t.email;(async()=>{var Dt,Lt;const _r=`${j.supabaseUrl}/functions/v1/bob-chat`;try{const gt=await fetch(_r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${j.supabaseKey}`},body:JSON.stringify({messages:[],vehicleContext:me,customerEmail:Ge,autoFetchParts:!0,hostConfig:x,hostContext:T})});if(!gt.ok||!gt.body){console.error("[BobWidget] Auto-fetch failed:",gt.status);return}const kr=gt.body.getReader(),rr=new TextDecoder;let bt="";for(;;){const{done:Sr,value:Er}=await kr.read();if(Sr)break;bt+=rr.decode(Er,{stream:!0});let Ut;for(;(Ut=bt.indexOf(`
73
- `))!==-1;){let ut=bt.slice(0,Ut);if(bt=bt.slice(Ut+1),ut.endsWith("\r")&&(ut=ut.slice(0,-1)),ut.startsWith(":")||ut.trim()===""||!ut.startsWith("data: "))continue;const v=ut.slice(6).trim();if(v==="[DONE]")break;try{const I=JSON.parse(v);I.type==="service_packages_found"&&I.packages&&(console.log("[useBobChat autoFetch] Received service_packages_found:",I.packages.length,"packages"),(Dt=S.onServicePackagesFound)==null||Dt.call(S,I.packages),y!=null&&y.current&&I.packages.forEach(q=>{q.title&&y.current.add(q.title)})),I.type==="parts_found"&&I.parts&&(console.log("[useBobChat autoFetch] Received parts_found:",I.parts.length,"parts"),(Lt=S.onPartsFound)==null||Lt.call(S,I.parts),P.trackPartsViewed(Array.isArray(I.parts)?I.parts.length:0,String(ue)))}catch{}}}b==null||b()}catch(gt){console.error("[BobWidget] Auto-fetch error:",gt)}})()},[(As=T.vehicle)==null?void 0:As.selectedVehicle,(Os=T.user)==null?void 0:Os.email]);const ce=M=>{try{t(M)}catch{console.warn(`[BobWidget] State "${M}" not available`)}},Ae=async M=>{var Ge,Ft,tr,$t,_r,Dt,Lt,gt,kr,rr,bt,Sr,Er,Ut,ut,v,I,q;const te=`${j.supabaseUrl}/functions/v1/bob-chat`,ue=(Ge=T.user)==null?void 0:Ge.email;let me=!1;try{const X={messages:[...R,M],hostConfig:x,hostContext:T};y!=null&&y.current&&y.current.size>0&&(X.shelfContext=Array.from(y.current).join(", ")),U&&(X.vehicleContext=U),ue&&(X.customerEmail=ue),console.log("[useBobChat DEBUG] vehicleCandidatesRef.current:",JSON.stringify((Ft=je.current)==null?void 0:Ft.slice(0,2))),console.log("[useBobChat DEBUG] vehicleCandidatesRef.current.length:",(tr=je.current)==null?void 0:tr.length),console.log("[useBobChat DEBUG] conversationStateRef.current:",Fe.current),je.current&&je.current.length>0?(X.vehicleCandidates=je.current,console.log("[useBobChat] ✅ Including",je.current.length,"vehicle candidates in request")):console.log("[useBobChat] ⚠️ No vehicle candidates to include - ref is empty");const de=await fetch(te,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${j.supabaseKey}`},body:JSON.stringify(X)});if(!de.ok){if(de.status===429){($t=S.onError)==null||$t.call(S,new Error("Rate limit exceeded"));return}if(de.status===402){(_r=S.onError)==null||_r.call(S,new Error("Payment required"));return}throw new Error("Failed to start stream")}if(!de.body)throw new Error("No response body");const _e=de.body.getReader(),fe=new TextDecoder;let le="",We=!1,Ee="";for(;!We;){const{done:Oe,value:dt}=await _e.read();if(Oe)break;le+=fe.decode(dt,{stream:!0});let Rt;for(;(Rt=le.indexOf(`
74
- `))!==-1;){let at=le.slice(0,Rt);if(le=le.slice(Rt+1),at.endsWith("\r")&&(at=at.slice(0,-1)),at.startsWith(":")||at.trim()===""||!at.startsWith("data: "))continue;const Yr=at.slice(6).trim();if(Yr==="[DONE]"){We=!0;break}try{const L=JSON.parse(Yr);if(L.type==="conversation_state"){console.log("[useBobChat] 🔄 conversation_state event received:",L.state),Fe.current=L.state,L.candidates&&Array.isArray(L.candidates)?(je.current=L.candidates,console.log("[useBobChat] ✅ Stored",L.candidates.length,"vehicle candidates from state event"),console.log("[useBobChat] First candidate:",JSON.stringify(L.candidates[0]))):console.log("[useBobChat] ⚠️ conversation_state had no candidates array"),ke();continue}if(L.type==="variant_selection_required"){const ye=Array.isArray(L.candidates)?L.candidates.length:0;console.log("[useBobChat] 🎴 variant_selection_required event received:",ye,"cards"),Array.isArray(L.candidates)?_==null||_(L.candidates,typeof L.make=="string"?L.make:"",typeof L.model=="string"?L.model:""):console.warn("[useBobChat] ⚠️ variant_selection_required had no candidates array");continue}if(L.type==="vehicle_identified"&&L.vehicle){K(L.vehicle),je.current=[],Fe.current="VEHICLE_CONFIRMED",ke(void 0,L.vehicle),(Dt=S.onVehicleIdentified)==null||Dt.call(S,L.vehicle),P.trackVehicleIdentified({make:L.vehicle.make,model:L.vehicle.model,year:L.vehicle.year,rego:L.vehicle.rego});continue}if(L.type==="vehicle_candidates_found"&&L.candidates){console.log("[useBobChat] 📦 vehicle_candidates_found event received:",L.candidates.length,"candidates"),je.current=L.candidates,console.log("[useBobChat] ✅ Candidates stored in ref. First:",JSON.stringify(L.candidates[0])),ke();continue}if(L.type==="service_packages_found"&&L.packages){(Lt=S.onServicePackagesFound)==null||Lt.call(S,L.packages),y!=null&&y.current&&(L.packages.forEach(ye=>{ye.title&&y.current.add(ye.title)}),console.log("[useBobChat] Eagerly added service package titles to shelfCategories:",Array.from(y.current)));continue}if(L.type==="parts_found"&&L.parts){console.log("[useBobChat] Received parts_found event:",L.parts.length,"parts"),(gt=S.onPartsFound)==null||gt.call(S,L.parts),y!=null&&y.current&&Array.isArray(L.parts)&&L.parts.forEach(ye=>{const Pe=ye.partslot_description||"Other Parts";Pe&&y.current.add(Pe)}),P.trackPartsViewed(Array.isArray(L.parts)?L.parts.length:0,(kr=U==null?void 0:U.vehicle_id)==null?void 0:kr.toString());continue}if(L.type==="bob_suggestions"&&L.products){console.log("[useBobChat] Received bob_suggestions:",L.products.length,"products",L.title),O(ye=>{var Mt;const Pe=[...ye],Ie=Pe[Pe.length-1];return console.log("[useBobChat] Attaching to message:",Ie==null?void 0:Ie.role,(Mt=Ie==null?void 0:Ie.content)==null?void 0:Mt.slice(0,40)),(Ie==null?void 0:Ie.role)==="assistant"?Pe.map((sr,tn)=>tn===Pe.length-1?{...sr,suggestedProducts:L.products,suggestionsTitle:L.title}:sr):Pe}),console.log("[useBobChat] bob_suggestions processed for inline display only");continue}if(L.type==="no_parts_found"){(rr=S.onPartsFound)==null||rr.call(S,[]),(bt=S.onServicePackagesFound)==null||bt.call(S,[]),m==null||m();continue}if(L.type==="highlight_category"&&L.category){console.log("[useBobChat] highlight_category event:",L.category),me=!0,g==null||g(L.category);continue}if(L.type==="navigate_url"&&L.url){console.log("[useBobChat] navigate_url event:",L.url),oe(),(Sr=S.onNavigateToProductPage)==null||Sr.call(S,{sku:L.sku,url:L.url});continue}if(L.type==="quick_replies"&&Array.isArray(L.replies)){console.log("[useBobChat] quick_replies event:",L.replies.length,"buttons"),O(ye=>{var Mt;const Pe=[...ye],Ie=Pe.length-1;return((Mt=Pe[Ie])==null?void 0:Mt.role)==="assistant"?Pe.map((sr,tn)=>tn===Ie?{...sr,quickReplies:L.replies}:sr):Pe});continue}if(L.type==="audio_hint"&&L.audio_url){console.log("[useBobChat] Audio hint received:",L.clip_key,L.audio_url);const ye=we.current;ye.hasCannedAudio=!0,ye.cannedUrl=L.audio_url,ze();continue}if(L.type==="bob_searching"&&L.audio_url){console.log("[useBobChat] Bob searching:",L.search_type,L.clip_key),L.transcript&&O(Pe=>{const Ie=Pe[Pe.length-1];return(Ie==null?void 0:Ie.role)!=="assistant"||(Ie==null?void 0:Ie.content)!==L.transcript?[...Pe,{role:"assistant",content:L.transcript}]:Pe});const ye=we.current;ye.searchingQueue.push(L.audio_url),!ye.isPlaying&&!ye.hasCannedAudio&&!ie&&it();continue}if(L.type==="cart_updated"&&L.items){if((Er=S.onCartUpdated)==null||Er.call(S,L.items),S.onAddToCart)for(const ye of L.items)S.onAddToCart({product_id:ye.product_id||ye.productName||"",product_name:ye.product_name||ye.productName||"",quantity:ye.quantity||1,unit_price:ye.unit_price||0,vehicle_id:ye.vehicle_id,sku:ye.sku,brand:ye.brand});continue}const Ps=(v=(ut=(Ut=L.choices)==null?void 0:Ut[0])==null?void 0:ut.delta)==null?void 0:v.content;if(Ps){Ee+=Ps;let ye=Ee.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");ye=Wn(ye),O(Pe=>{const Ie=Pe[Pe.length-1];return(Ie==null?void 0:Ie.role)==="assistant"?Pe.map((Mt,sr)=>sr===Pe.length-1?{...Mt,content:ye}:Mt):[...Pe,{role:"assistant",content:ye}]}),(I=S.onBobMessage)==null||I.call(S,ye)}}catch{le=at+`
75
- `+le;break}}}let Re=Ee.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");Re=Wn(Re),ve.current=Re;const Je=qi.some(Oe=>Ee.toLowerCase().includes(Oe.toLowerCase()));if(console.log("[useBobChat] v3.2.10 scroll debug: highlightCategoryReceived=",me,"shelfCategories=",y!=null&&y.current?Array.from(y.current):"none"),!me&&(y!=null&&y.current)&&y.current.size>0){const Oe=Re.toLowerCase();let dt=null,Rt=0;for(const at of y.current){const Yr=at.toLowerCase().split(/\s+/).filter(Boolean),L=Yr.filter(Ps=>Oe.includes(Ps)).length;L===Yr.length&&L>Rt&&(Rt=L,dt=at)}dt&&(console.log("[useBobChat] v3.2.10 shelf category match:",dt,`(${Rt} words)`),g==null||g(dt))}const Tt=Ee.match(/(?:go with|recommend|suggest|grab|try)\s+(?:the\s+)?(\w+)\s+(?:at|for)\s+\$(\d+(?:\.\d{2})?)/i);if(Tt){const[,Oe,dt]=Tt;f==null||f({brand:Oe,price:parseFloat(dt)})}const Qe=we.current;if(!ie&&ve.current.trim()){if(D.current=!1,Ue(),Qe.hasCannedAudio&&Qe.cannedUrl)console.log("[BobWidget] Playing canned audio (priority):",Qe.cannedUrl),ze(),tt(Qe.cannedUrl,"canned",()=>{Qe.hasCannedAudio=!1,Qe.cannedUrl=null,Ue(),e||(Je&&u?u():c?c():(ce(n),setTimeout(()=>ce(a),3e3)))}),D.current=!0,h==null||h();else if(Qe.isPlaying)console.log("[BobWidget] Skipping TTS - audio already playing:",Qe.source);else{const Oe=Lu(ve.current);console.log("[BobWidget] Playing TTS (no canned audio)"),N(Oe)}ae.current=setTimeout(()=>{D.current||(console.warn("[BobWidget] Speech fallback after 5s"),h==null||h(),e||(Je&&u?u():c?c():(ce(n),setTimeout(()=>ce(a),3e3))))},5e3)}else h==null||h(),e||(Je&&u?u():c?c():(ce(n),setTimeout(()=>ce(a),3e3)))}catch(X){console.error("[BobWidget] Chat error:",X);const de=X instanceof Error?X:new Error("Unknown error");(q=S.onError)==null||q.call(S,de),P.trackError(de.name||"ChatError",de.message||"Unknown chat error"),e||ce(i)}},Ze=async()=>{if(!A.trim()||V)return;W(),oe();const M={role:"user",content:A};O(me=>[...me,M]),$(""),P.trackMessageSent(A.length,!!U);const te=A.toLowerCase();if(Uu.some(me=>te.includes(me))){const me=`G'day mate! I'm running Bob v${It} - she's running sweet as! Anything else I can help ya with?`;O(Ge=>[...Ge,{role:"assistant",content:me}]),ie||N(me);return}z(!0),console.log("[BobWidget STATE] User sent message - switching to RESEARCH state:",s),d==null||d(),e||ce(s),await Ae(M),z(!1)};return{messages:R,input:A,setInput:$,isLoading:V,handleSend:Ze,handleKeyPress:M=>{M.key==="Enter"&&!M.shiftKey&&(M.preventDefault(),Ze())},handleInputFocus:()=>{W()},handleInputBlur:()=>{},chatEndRef:he,clearMessages:()=>{sessionStorage.removeItem(J),je.current=[],Fe.current="AWAITING_REGO",O([{role:"assistant",content:"G'day! Bob from CARFIX here. How can I help ya today?"}])},isMuted:ie,toggleMute:()=>{Y(M=>!M),ie||oe()},isSpeaking:Ce||Le,identifiedVehicle:U,clearVehicle:()=>{K(null)},sendDirectMessage:M=>{if(!M.trim())return;console.log("[BobWidget] sendDirectMessage:",M),oe(),z(!1),$("");const te={role:"user",content:M};O(ue=>[...ue,te]),d==null||d(),e||ce(s),z(!0),Ae(te).finally(()=>z(!1))},stopAllAudio:ze}},Mu={states:[],configs:[],uploadedImages:[],looks:[],activeLookId:null},$a=t=>{const e=Oa(),r=xr();return p.useEffect(()=>{if(!r)return;const s=r.channel("animation-states-changes").on("postgres_changes",{event:"*",schema:"public",table:"animation_states"},()=>{e.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe(),n=r.channel("bob-animations-changes").on("postgres_changes",{event:"*",schema:"public",table:"bob_animations"},()=>{e.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe();return()=>{r.removeChannel(s),r.removeChannel(n)}},[e,r]),Ts({queryKey:["bob-animation-data",t],queryFn:async()=>{var j;if(!r)return console.log("[BobAnimation] No supabase client, returning empty data"),Mu;const{data:s,error:n}=await r.from("bob_looks").select("*").order("display_order");if(n)throw n;const i=(s||[]).find(x=>x.is_active),a=t||(i==null?void 0:i.id)||s&&((j=s[0])==null?void 0:j.id)||null;if(!a)return console.warn("[BobAnimation] No looks configured in database"),{states:[],configs:[],uploadedImages:[],looks:s||[],activeLookId:null};console.log(`[BobAnimation] Loading animations for look: ${(i==null?void 0:i.name)||a}`);const{data:l,error:c}=await r.from("animation_states").select("*").eq("is_active",!0).eq("look_id",a).order("display_order");if(c)throw c;const{data:u,error:d}=await r.from("bob_animations").select("*").eq("is_active",!0).eq("look_id",a).order("animation_state").order("sequence_order");if(d)throw d;const h=(l||[]).map(x=>x.state_key);console.log(`[BobAnimation] Loaded ${h.length} states: ${h.join(", ")}`);const f=["idle","talking","listening"].filter(x=>{const T=[x,x.replace("ing",""),x+"ing"];return!h.some(S=>T.includes(S))});f.length>0&&console.warn(`[BobAnimation] ⚠️ Missing critical states: ${f.join(", ")}`);const m=new Set(h),b=(u||[]).filter(x=>m.has(x.animation_state));console.log(`[BobAnimation] Loaded ${b.length} animation frames`);const{data:_,error:y}=await r.storage.from("bob-images").list();if(y)throw y;const k=(_||[]).map(x=>{const{data:T}=r.storage.from("bob-images").getPublicUrl(x.name);return T.publicUrl});return b.forEach(x=>{const T=new Image;T.src=x.image_url}),{states:l||[],configs:b,uploadedImages:k,looks:s||[],activeLookId:a}},staleTime:30*1e3,gcTime:5*60*1e3})},Da=(t={})=>{const{isSpeaking:e=!1}=t,[r,s]=p.useState(""),[n,i]=p.useState(0),[a,l]=p.useState(400),[c,u]=p.useState(!1),d=p.useRef(null),h=p.useRef(0),g=p.useRef(e),f=p.useRef(0),m=p.useRef(0),b=p.useRef(!1),_=p.useRef(0),{data:y,isLoading:k}=$a(),j=p.useRef({}),{imageUrlsMap:x,alternateImages:T,offsetsMap:S,scalesMap:F,availableStates:E}=p.useMemo(()=>{if(!y)return{imageUrlsMap:{},alternateImages:{},offsetsMap:{},scalesMap:{},availableStates:[]};const A={},$={},V={},z={},ie=y.states.map(Y=>Y.state_key);return ie.forEach(Y=>{const U=y.configs.filter(re=>re.animation_state===Y),K=U.map(re=>re.image_url),he=U.map(re=>re.vertical_offset||0),Z=U.map(re=>re.scale||100);if(K.length>0){const re=y.states.find(ve=>ve.state_key===Y);A[Y]={url:K[0],animation_speed:(re==null?void 0:re.animation_speed)||400,pause_duration:(re==null?void 0:re.pause_duration)||0,loop_count:(re==null?void 0:re.loop_count)||0},$[Y]=K,V[Y]=he,z[Y]=Z}}),{imageUrlsMap:A,alternateImages:$,offsetsMap:V,scalesMap:z,availableStates:ie}},[y]);p.useEffect(()=>{j.current=x},[x]),p.useEffect(()=>{const A=g.current;if(g.current=e,A&&!e){const $=r.toLowerCase();($.includes("talk")||$==="talking")&&(console.log("[useBobAnimation] Speech ended while in talk state - forcing loop completion"),m.current=999)}},[e,r]);const P=p.useCallback(A=>{s($=>$===A?$:(f.current=0,m.current=0,b.current=!1,i(0),A))},[]);p.useEffect(()=>{E.length>0&&!r&&s(E[0])},[E,r]),p.useEffect(()=>{const A=T[r];if(d.current!==null&&(cancelAnimationFrame(d.current),d.current=null),f.current=0,m.current=0,b.current=!1,h.current=0,i(0),!A||A.length<=1)return;const $=j.current[r],V=($==null?void 0:$.animation_speed)||a||400,z=($==null?void 0:$.loop_count)||0,ie=($==null?void 0:$.pause_duration)||0,Y=r.toLowerCase().includes("talk"),U=K=>{if(h.current===0&&(h.current=K),b.current){K-_.current>=ie&&(b.current=!1,m.current=0,h.current=K),d.current=requestAnimationFrame(U);return}if(K-h.current>=V){h.current=K;const Z=(f.current+1)%A.length;Z===0?(m.current++,Y&&g.current?(f.current=Z,i(Z)):z>0&&m.current>=z?ie>0&&(b.current=!0,_.current=K):(f.current=Z,i(Z))):(f.current=Z,i(Z))}d.current=requestAnimationFrame(U)};return d.current=requestAnimationFrame(U),()=>{d.current!==null&&(cancelAnimationFrame(d.current),d.current=null)}},[r,T,a]);const C=p.useCallback(()=>{const A=T[r];if(!A||A.length===0){const $=E.find(V=>{var z;return((z=T[V])==null?void 0:z.length)>0});return $?(console.warn(`[useBobAnimation] No images for "${r}", using fallback: ${$}`),T[$][0]):(console.error("[useBobAnimation] No valid images found for any state!"),"")}return A[n]||A[0]},[T,r,E,n]),R=p.useCallback(()=>{const A=S[r];if(!A||A.length===0){const $=E.find(V=>{var z;return((z=S[V])==null?void 0:z.length)>0});return $?S[$][0]:0}return A[n]||A[0]},[S,r,E,n]),O=p.useCallback(()=>{const A=F[r];if(!A||A.length===0){const $=E.find(V=>{var z;return((z=F[V])==null?void 0:z.length)>0});return $?F[$][0]:100}return A[n]||A[0]},[F,r,E,n]);return{animationState:r,setAnimationState:P,getCurrentImage:C,getCurrentOffset:R,getCurrentScale:O,imageUrls:x,availableStates:E,setTalkSpeed:l,manualMode:c,setManualMode:u,isLoading:k}},La=()=>{const t=xr(),{data:e=[],isLoading:r}=Ts({queryKey:["bob-backdrops"],queryFn:async()=>{if(!t)return console.log("[useBobBackdrop] No supabase client, returning empty"),[];const{data:n,error:i}=await t.from("bob_backdrops").select("*").order("display_order",{ascending:!0});if(i)throw i;return n},staleTime:5*60*1e3,gcTime:10*60*1e3}),s=e.find(n=>n.is_active);return{backdrops:e,activeBackdrop:s,isLoading:r}},Ua=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=12,className:i="",verticalOffset:a=0,scale:l=100})=>{const c=a+n,u=55*(l/100);return o.jsx("div",{className:`flex flex-col items-center justify-center gap-6 w-full ${i}`,children:o.jsxs("div",{className:"relative w-full max-w-[600px] mx-auto aspect-[16/10] overflow-hidden",children:[r&&o.jsx("img",{src:r,alt:"Backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-bottom"}),o.jsx("img",{src:t,alt:`Bob ${e}`,className:"absolute z-10 h-auto object-contain left-1/2 -translate-x-1/2",style:{bottom:`${c}%`,width:`${u}%`,maxWidth:`${220*(l/100)}px`,transformOrigin:"center bottom"}}),s&&o.jsx("img",{src:s,alt:"Counter",className:"absolute z-20 bottom-0 left-0 w-full object-cover object-bottom",style:{height:`${n}%`}})]})})},G={primary:"#0052CC",primaryHover:"#0047B3",secondary:"#38BDF8",foreground:"#0F172A",accent:"#FF8C00",success:"#22C55E",destructive:"#EF4444",performanceRed:"#DC2626",mutedForeground:"#64748B",background:"#FAFAFA",card:"#FFFFFF",border:"#E2E8F0",slateEconomy:"#475569"},Ks={Economy:{icon:"DollarSign",emoji:"💰",textColor:"#475569",background:"#F1F5F9",border:"#CBD5E1",description:"Smart savings"},Standard:{icon:"Star",emoji:"⭐",textColor:"#0052CC",background:"rgba(0,82,204,0.1)",border:"rgba(0,82,204,0.3)",description:"Best value",isRecommended:!0},Premium:{icon:"Award",emoji:"🏆",textColor:"#D97706",background:"#FEF3C7",border:"#FCD34D",description:"Superior quality"},Performance:{icon:"Zap",emoji:"⚡",textColor:"#DC2626",background:"#FEE2E2",border:"#FCA5A5",description:"Maximum power"}},dn={"Oil Change":"Neglecting oil changes leads to engine wear, overheating, and catastrophic failure costing thousands. Quality oil and filters keep your engine running smoothly. Each CARFIX Oil Change Service Pack includes premium oil and filter matched to your engine specifications.","Front Brake Service":"Your front brakes handle 70% of stopping power. Worn pads dangerously increase stopping distance. Quality brake components ensure confident, safe stops. Each CARFIX Front Brake Service Pack includes pads and rotors to restore your braking performance.","Rear Brake Service":"Rear brakes provide stability and balance during emergency stops. Worn components cause instability and longer stopping distances. Each CARFIX Rear Brake Service Pack includes quality pads/shoes and rotors/drums for complete rear brake renewal.","Timing Belt Service":"A snapped timing belt destroys engines instantly, causing $8,000+ in damage. Preventive replacement is essential for peace of mind. Each CARFIX Timing Belt Service Pack includes the belt, tensioner, and related components.",Wipers:"Worn wipers reduce visibility in rain, compromising safety. Quality blades provide streak-free, clear vision. Each CARFIX Wipers Service Pack includes the gear you need to change all of your vehicle's wiper blades to restore your driving vision.","Coolant Service":"Old coolant causes overheating, warped cylinder heads, and engine seizure. Fresh coolant protects your entire cooling system. Each CARFIX Coolant Service Pack includes quality coolant matched to your vehicle's requirements.","Air Filter Service":"Clogged air filters reduce engine performance by 10% and increase fuel consumption. Clean filters improve power and economy. Each CARFIX Air Filter Service Pack includes a precision-fit filter for optimal airflow.","Spark Plug Service":"Worn spark plugs cause misfires, poor fuel economy, and catalytic converter damage. Fresh plugs restore smooth, efficient running. Each CARFIX Spark Plug Service Pack includes quality plugs matched to your engine.","Battery Service":"A failing battery leaves you stranded without warning. Reliable power is essential for starting and electronics. Each CARFIX Battery Service Pack includes a quality battery sized for your vehicle's demands.","Cabin Filter":"Cabin filters clean the air you and your passengers breathe. Replace regularly to remove pollen, dust, and odours. Each CARFIX Cabin Filter Service Pack includes a quality filter for fresh, clean cabin air.","Fuel Filter Service":"Clogged fuel filters restrict flow, causing poor performance and potential engine damage. Clean fuel is critical for efficiency. Each CARFIX Fuel Filter Service Pack includes a quality filter for optimal fuel delivery.","Transmission Service":"Old transmission fluid causes rough shifting, slipping, and premature wear. Fresh fluid extends transmission life. Each CARFIX Transmission Service Pack includes quality fluid matched to your transmission type."},Wu="Keep your vehicle running safely and efficiently with quality parts matched to your specific make and model. Each CARFIX Service Pack includes everything you need for this essential maintenance.",vs={storageBase:"https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public",productImage:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/product_images/${t}.jpg`,brandLogo:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${t.replace(/\s+/g,"")}.jpg`,carfixImage:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/carfix_images/${t}_1.jpg`},Ma={fitsVehicle:{background:"rgba(34,197,94,0.1)",text:"#22C55E",border:"rgba(34,197,94,0.2)",icon:"Check",label:"Fits Your Vehicle"},viscosity:{background:"#EFF6FF",text:"#1D4ED8",border:"#BFDBFE",icon:"Gauge"},volume:{background:"#ECFEFF",text:"#0E7490",border:"#A5F3FC",icon:"Droplets"},quantity:{background:"#F1F5F9",text:"#475569",border:"#CBD5E1"},partNumber:{background:"transparent",text:"#64748B",border:"transparent"},carfixValue:{background:"rgba(0,82,204,0.1)",text:"#0052CC",border:"rgba(0,82,204,0.2)",icon:"Sparkles",label:"CARFIX Value"},rotorPair:{background:"#EFF6FF",text:"#1D4ED8",border:"#BFDBFE",label:"Pair"}},vt={packageTitle:{fontSize:"20px",fontWeight:700},partslotName:{fontSize:"14px",fontWeight:600},productName:{fontSize:"14px",fontWeight:500},description:{fontSize:"14px",fontWeight:400},priceMain:{fontSize:"20px",fontWeight:700},priceSecondary:{fontSize:"12px",fontWeight:400},tierLabel:{fontSize:"14px",fontWeight:500},badgeText:{fontSize:"12px",fontWeight:500}};function Wa(t){var s;const e=((s=t.name)==null?void 0:s.toLowerCase())||"",r=(t.partslotDescription||t.partslot_description||"").toLowerCase();return e.includes("rotor")||r.includes("disc rotor")||r.includes("brake rotor")||t.per_car_qty===2}function qa(t,e){return e?{displayPrice:t*2,unitPriceLabel:`$${t.toFixed(2)} each`}:{displayPrice:t}}function nt(t){return`$${t.toFixed(2)}`}function za(t){if(dn[t])return dn[t];const e=t.toLowerCase();for(const[r,s]of Object.entries(dn))if(e.includes(r.toLowerCase())||r.toLowerCase().includes(e))return s;return Wu}const is=({type:t,value:e,className:r=""})=>{const s=Ma[t],n=e||("label"in s?s.label:""),i=()=>{if(!("icon"in s))return null;const a={width:12,height:12};switch(s.icon){case"Check":return o.jsx("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",children:o.jsx("polyline",{points:"20 6 9 17 4 12"})});case"Sparkles":return o.jsxs("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("path",{d:"M12 3l1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5L12 3z"}),o.jsx("path",{d:"M5 19l1 3 1-3 3-1-3-1-1-3-1 3-3 1 3 1z"})]});case"Gauge":return o.jsxs("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[o.jsx("circle",{cx:"12",cy:"12",r:"10"}),o.jsx("path",{d:"M12 6v6l4 2"})]});case"Droplets":return o.jsx("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:o.jsx("path",{d:"M12 2.69l5.66 5.66a8 8 0 11-11.31 0z"})});default:return null}};return o.jsxs("span",{className:r,style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",fontSize:"12px",fontWeight:500,background:s.background,color:s.text,border:`1px solid ${s.border}`,whiteSpace:"nowrap"},children:[i(),n]})},Qn=({products:t,title:e,onProductClick:r,onAddToCart:s})=>!t||t.length===0?null:o.jsxs("div",{style:{marginTop:"16px",width:"100%"},children:[e&&o.jsxs("div",{style:{marginBottom:"12px",fontSize:vt.partslotName.fontSize,fontWeight:vt.partslotName.fontWeight,color:G.foreground,display:"flex",alignItems:"center",gap:"8px"},children:[o.jsx("span",{style:{fontSize:"18px"},children:"🚗"}),e]}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:t.slice(0,6).map((n,i)=>o.jsx(qu,{product:n,onProductClick:r,onAddToCart:s,isRecommended:i===0},n.id||n.sku||i))}),t.length>6&&o.jsxs("div",{style:{marginTop:"12px",fontSize:"13px",color:G.mutedForeground,textAlign:"center"},children:["+ ",t.length-6," more options available"]})]}),qu=({product:t,onProductClick:e,onAddToCart:r,isRecommended:s=!1})=>{const[n,i]=p.useState(!1),[a,l]=p.useState(!1),c=t.image_url||t.image||(t.sku?vs.productImage(t.sku):null),u=t.brand?vs.brandLogo(t.brand):null,d=t.brand||"Quality Part",h=t.name||"Product",g=t.price??0,f=t.partNumber||t.part_number,m=Wa({name:t.name,partslotDescription:t.partslotDescription,per_car_qty:t.quantity}),{displayPrice:b,unitPriceLabel:_}=qa(g,m);return o.jsxs("div",{style:{background:G.card,borderRadius:"12px",border:`2px solid ${G.border}`,overflow:"hidden",cursor:e?"pointer":"default",transition:"all 0.2s ease"},onClick:()=>e==null?void 0:e(t),onMouseEnter:y=>{y.currentTarget.style.borderColor=`${G.primary}80`,y.currentTarget.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)"},onMouseLeave:y=>{y.currentTarget.style.borderColor=G.border,y.currentTarget.style.boxShadow="none"},children:[t.partslotDescription&&o.jsxs("div",{style:{background:"rgba(0,0,0,0.03)",borderBottom:`1px solid ${G.border}`,padding:"10px 16px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsx("span",{style:{fontSize:vt.partslotName.fontSize,fontWeight:vt.partslotName.fontWeight,color:G.foreground},children:t.partslotDescription}),s&&o.jsx(is,{type:"carfixValue"})]}),o.jsxs("div",{style:{padding:"16px",display:"flex",gap:"16px"},children:[o.jsx("div",{style:{width:"96px",minWidth:"96px",height:"96px",borderRadius:"8px",background:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",border:`1px solid ${G.border}`},children:c&&!n?o.jsx("img",{src:c,alt:h,style:{width:"100%",height:"100%",objectFit:"contain",padding:"4px"},onError:()=>i(!0)}):o.jsx("span",{style:{fontSize:"32px",opacity:.5},children:"🔧"})}),o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:[u&&!a&&o.jsx("img",{src:u,alt:d,style:{height:"16px",width:"auto",objectFit:"contain"},onError:()=>l(!0)}),o.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:G.foreground,textTransform:"uppercase"},children:d})]}),o.jsx("div",{style:{fontSize:vt.productName.fontSize,fontWeight:vt.productName.fontWeight,color:G.foreground,overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",lineHeight:"1.4",marginBottom:"8px"},children:h}),o.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px",marginBottom:"12px"},children:[o.jsx(is,{type:"fitsVehicle"}),m&&o.jsx(is,{type:"rotorPair"}),t.quantity&&t.quantity>1&&!m&&o.jsx(is,{type:"quantity",value:`Qty: ${t.quantity}`}),f&&o.jsxs("span",{style:{fontSize:"12px",color:G.mutedForeground},children:["#",f]})]})]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",justifyContent:"space-between",minWidth:"100px"},children:[o.jsxs("div",{style:{textAlign:"right"},children:[o.jsx("div",{style:{fontSize:vt.priceMain.fontSize,fontWeight:vt.priceMain.fontWeight,color:G.foreground},children:nt(b)}),_&&o.jsx("div",{style:{fontSize:vt.priceSecondary.fontSize,color:G.mutedForeground},children:_}),o.jsx("div",{style:{fontSize:vt.priceSecondary.fontSize,color:G.mutedForeground},children:"inc GST"})]}),r&&o.jsx("button",{onClick:y=>{y.stopPropagation(),r(t)},style:{background:G.primary,color:"#FFFFFF",border:"none",borderRadius:"8px",padding:"8px 16px",fontSize:"13px",fontWeight:600,cursor:"pointer",transition:"all 0.2s ease",whiteSpace:"nowrap"},onMouseEnter:y=>{y.currentTarget.style.background=G.primaryHover},onMouseLeave:y=>{y.currentTarget.style.background=G.primary},onMouseDown:y=>{y.currentTarget.style.transform="scale(0.98)"},onMouseUp:y=>{y.currentTarget.style.transform="scale(1)"},children:"Add to Cart"})]})]})]})},Ha=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:l,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,className:g="",onAddToCart:f,onProductClick:m})=>o.jsx("div",{className:g,style:{width:"100%",maxWidth:"72rem",margin:"0 auto",padding:"0 16px 32px 16px"},children:o.jsxs("div",{style:{backgroundColor:"rgba(20, 30, 50, 0.85)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"16px",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.3)",overflow:"hidden"},children:[o.jsx("div",{style:{padding:"16px",borderBottom:"1px solid rgba(255,255,255,0.1)",backgroundColor:"rgba(0,0,0,0.2)"},children:o.jsxs("div",{style:{display:"flex",gap:"8px"},children:[o.jsx("input",{value:e,onChange:b=>r(b.target.value),onKeyPress:i,onFocus:a,onBlur:l,placeholder:"Ask Bob about car parts...",disabled:s,style:{flex:1,padding:"12px 16px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",color:"white",fontSize:"16px",outline:"none"}}),d&&o.jsx("button",{onClick:d,style:{flexShrink:0,padding:"12px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",cursor:"pointer",minHeight:"unset",minWidth:"unset"},title:u?"Unmute Bob's voice":"Mute Bob's voice",children:u?"🔇":"🔊"}),o.jsx("button",{onClick:n,disabled:s||!e.trim(),style:{flexShrink:0,padding:"12px 20px",background:s||!e.trim()?"rgba(0, 102, 204, 0.3)":"linear-gradient(135deg, rgba(0, 102, 204, 0.95), rgba(0, 73, 153, 1))",color:"white",borderRadius:"12px",border:"1px solid rgba(255,255,255,0.2)",cursor:s||!e.trim()?"not-allowed":"pointer",opacity:s||!e.trim()?.5:1,minHeight:"unset",minWidth:"unset",fontWeight:600},children:"Send"})]})}),o.jsxs("div",{style:{overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"12px",height:"400px",background:"rgba(0,0,0,0.1)"},children:[[...t].reverse().map((b,_)=>{var y;return o.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:b.role==="user"?"flex-end":"flex-start"},children:o.jsxs("div",{style:{maxWidth:(y=b.suggestedProducts)!=null&&y.length?"100%":"80%",borderRadius:"16px",padding:"12px 16px",fontSize:"14px",backgroundColor:b.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9), rgba(0, 73, 153, 1))":"rgba(255,255,255,0.1)",background:b.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9), rgba(0, 73, 153, 1))":"rgba(255,255,255,0.08)",color:"white",border:"1px solid rgba(255,255,255,0.15)",boxShadow:"0 2px 8px rgba(0,0,0,0.2)"},children:[b.content,b.role==="assistant"&&b.suggestedProducts&&b.suggestedProducts.length>0&&o.jsx(Qn,{products:b.suggestedProducts,title:b.suggestionsTitle,onAddToCart:f,onProductClick:m})]})},_)}),o.jsx("div",{ref:c})]})]})}),zu=768,Hu=1024;function Xs(){const[t,e]=p.useState("mobile");return p.useEffect(()=>{const r=()=>{const s=window.innerWidth;s>=Hu?e("desktop"):s>=zu?e("tablet"):e("mobile")};return r(),window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),t}function Yn(){const t=Xs();return Ku(t)}function Ku(t){switch(t){case"mobile":return{bobOffset:1,productWidth:1,uiScale:1,partialLeftPosition:-30,hiddenPosition:-100};case"tablet":return{bobOffset:.7,productWidth:.85,uiScale:1.1,partialLeftPosition:-25,hiddenPosition:-80};case"desktop":return{bobOffset:.5,productWidth:.7,uiScale:1.2,partialLeftPosition:-5,hiddenPosition:-60};default:return{bobOffset:1,productWidth:1,uiScale:1,partialLeftPosition:-20,hiddenPosition:-100}}}const Zs=({currentImage:t,animationState:e,counterOverlayUrl:r,counterHeightPercent:s=15,scale:n=100,position:i="center",verticalOffset:a=0,hasArrived:l=!0})=>{const c=Yn(),d=95*n/100,h=550*n/100,g=()=>{switch(i){case"center":return"50%";case"partial-left":return`${c.partialLeftPosition}%`;case"hidden":return`${c.hiddenPosition}%`;default:return"50%"}},f=()=>i==="center"?"translateX(-50%)":"translateX(0)",m=s+a,b=()=>i==="hidden"?"all 0.35s cubic-bezier(0.4, 0, 0.2, 1)":"all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1)";return o.jsxs("div",{className:"absolute inset-0 pointer-events-none",style:{overflow:"visible"},children:[o.jsx("div",{className:"absolute z-[60]",style:{bottom:`${m}%`,left:g(),maxHeight:`${100-s-2}%`,transform:f(),width:`${d}%`,maxWidth:`${h}px`,transition:b()+", opacity 0.6s ease-out",willChange:"transform, left, opacity",opacity:l?1:0},children:o.jsx("img",{src:t,alt:`Bob ${e}`,className:"w-full h-auto object-contain",style:{display:"block",maxHeight:"100%",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1})}),r&&o.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-[70]",style:{height:`${s}%`,pointerEvents:"none"},children:o.jsx("img",{src:r,alt:"Shop counter",className:"w-full h-full",style:{objectFit:"fill",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1})})]})},Vu={background:"rgba(20, 30, 50, 0.92)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"28px",boxShadow:"0 10px 40px rgba(0, 0, 0, 0.35), inset 0 0 0 1px rgba(255,255,255,0.1)"},Gu={background:"linear-gradient(135deg, rgba(40, 60, 100, 0.95) 0%, rgba(20, 40, 80, 0.98) 100%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(0, 0, 0, 0.35), 0 0 0 1px rgba(255,255,255,0.15), inset 0 1px 0 rgba(255,255,255,0.2)"},Ka={background:"rgba(255, 255, 255, 0.08)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"28px",boxShadow:"0 10px 40px rgba(0, 0, 0, 0.3)"},ls={primary:{color:"rgba(255, 255, 255, 1)",textShadow:"0 1px 3px rgba(0,0,0,0.5)"}},Ju={background:"rgba(255, 255, 255, 0.12)",borderRadius:"20px",border:"1px solid rgba(255, 255, 255, 0.15)"},zi={background:"rgba(255, 255, 255, 0.15)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"12px"},Qu={width:"4px",height:"4px",borderRadius:"50%",background:"rgba(255, 255, 255, 0.6)",boxShadow:"0 0 8px rgba(255, 255, 255, 0.4)"},Va=({product:t,isSpotlighted:e=!1,onProductClick:r,onAddToCart:s})=>{const[n,i]=p.useState(!1),[a,l]=p.useState(0),c=()=>{r==null||r(t)},u=m=>{m.stopPropagation(),s==null||s(t)},d=()=>{a===0&&t.brandImageUrl?l(1):l(2)},h=a===0?t.image_url:a===1?t.brandImageUrl:void 0,g=e?Gu:Vu,f=t.webDescription||t.name;return o.jsxs("div",{onClick:c,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),className:"relative w-full cursor-pointer glass-card",style:{...g,padding:"16px",paddingBottom:"60px",position:"relative",transform:n?"scale(1.04) translateY(-4px)":"scale(1) translateY(0)",boxShadow:n?"0 16px 56px rgba(0, 0, 0, 0.4), 0 0 24px rgba(255,255,255,0.08)":g.boxShadow,transition:"transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.3s ease-out"},children:[e&&o.jsxs("div",{className:"absolute -top-2.5 -right-2.5 z-10 flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.95) 0%, rgba(0, 73, 153, 1) 100%)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.3)",borderRadius:"20px",boxShadow:"0 8px 24px rgba(0, 102, 204, 0.5)",color:"white"},children:[o.jsx("svg",{className:"w-3.5 h-3.5",fill:"currentColor",viewBox:"0 0 20 20",children:o.jsx("path",{d:"M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"})}),"Bob's Pick"]}),o.jsxs("div",{className:"flex items-start gap-4",children:[o.jsx("div",{className:"flex-shrink-0 flex items-center justify-center overflow-hidden",style:{...Ju,width:"92px",height:"92px",backgroundColor:"#ffffff"},children:h&&a<2?o.jsx("img",{src:h,alt:t.name,className:"w-full h-full object-contain p-2",loading:"lazy",onError:d}):o.jsx("div",{className:"flex flex-col items-center justify-center",style:{color:"rgba(255,255,255,0.4)"},children:o.jsx("svg",{className:"w-8 h-8",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"font-bold leading-tight",style:{fontSize:"15px",letterSpacing:"-0.01em",...ls.primary},children:f}),t.partNumber&&o.jsx("p",{className:"mt-0.5 text-xs",style:{color:"rgba(255,255,255,0.5)"},children:t.partNumber}),o.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 flex-wrap",children:[t.brand&&o.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5",style:{...zi,color:"rgba(255, 255, 255, 0.9)"},children:[o.jsx("svg",{className:"w-2.5 h-2.5",fill:"currentColor",viewBox:"0 0 20 20",children:o.jsx("path",{fillRule:"evenodd",d:"M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),t.brand]}),t.perCarQty&&t.perCarQty>1&&o.jsxs("span",{className:"inline-flex items-center text-xs font-semibold px-2 py-0.5",style:{...zi,color:"rgba(255, 200, 50, 0.95)"},children:["Qty: ",t.perCarQty]})]}),(t.viscosity||t.volume)&&o.jsx("p",{className:"mt-1 text-xs font-medium",style:{color:"rgba(255, 255, 255, 0.7)"},children:[t.viscosity,t.volume].filter(Boolean).join(" / ")}),o.jsx("p",{className:"font-extrabold mt-2",style:{fontSize:"22px",letterSpacing:"-0.02em",color:"#FFD700",textShadow:"0 2px 6px rgba(0, 0, 0, 0.5), 0 0 12px rgba(255, 215, 0, 0.3)"},children:t.price>0?`$${t.price.toFixed(2)}`:"POA"})]})]}),o.jsx("button",{onClick:u,className:"absolute flex items-center justify-center cursor-pointer",style:{bottom:"12px",right:"12px",background:"linear-gradient(135deg, #22C55E 0%, #16A34A 100%)",border:"1px solid rgba(255, 255, 255, 0.35)",borderRadius:"22px",boxShadow:"0 10px 40px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)",width:"44px",height:"44px",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease-out"},onMouseEnter:m=>{m.currentTarget.style.transform="scale(1.08) translateY(-2px)",m.currentTarget.style.boxShadow="0 14px 48px rgba(34, 197, 94, 0.5), inset 0 1px 0 rgba(255,255,255,0.4)"},onMouseLeave:m=>{m.currentTarget.style.transform="scale(1) translateY(0)",m.currentTarget.style.boxShadow="0 10px 40px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},children:o.jsx("svg",{className:"w-5 h-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M12 4v16m8-8H4"})})}),t.partslotDescription&&o.jsx("div",{className:"mt-3 pt-3",style:{borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:o.jsx("span",{className:"text-xs font-medium",style:{color:"rgba(255, 255, 255, 0.6)"},children:t.partslotDescription})})]})},Ga=["SHOE","DRUM"],Ja=["PAD","ROTOR"];function Qa(t){var s,n;const e=((s=t.id)==null?void 0:s.toLowerCase())||"",r=((n=t.title)==null?void 0:n.toLowerCase())||"";return e.includes("rear-brake")||r.includes("rear brake")}function Ya(t,e){const r=e==="disc"?Ga:Ja;return t.filter(s=>{const n=s.partslotName.toUpperCase();return!r.some(i=>n.includes(i))})}function Xa(t){return t.reduce((e,r)=>e+r.displayPrice,0)}function Za(t){const e=t.flatMap(n=>n.products),r=e.some(n=>{const i=n.partslotName.toUpperCase();return n.displayPrice>0&&Ja.some(a=>i.includes(a))}),s=e.some(n=>{const i=n.partslotName.toUpperCase();return n.displayPrice>0&&Ga.some(a=>i.includes(a))});return{hasDisc:r,hasDrum:s}}const hn=(t,e)=>{if(!t||!e)return!1;const r=t.toLowerCase();return e.toLowerCase().replace(/s\b/g,"").split(/\s+/).filter(Boolean).every(n=>r.includes(n))},Yu=(t,e)=>{var n;const r=((n=t.brand)==null?void 0:n.toLowerCase())===e.brand.toLowerCase(),s=Math.abs(t.price-e.price)<1;return r&&s},Xu=({product:t,isSpotlighted:e,spotlightedRef:r,onProductClick:s,onAddToCart:n})=>o.jsx("div",{ref:e?r:void 0,children:o.jsx(Va,{product:t,isSpotlighted:e,onProductClick:s,onAddToCart:n})}),en=({products:t,servicePackages:e,highlightedPartType:r,highlightedProduct:s,scrollToCategory:n,onScrollToCategoryComplete:i,onProductClick:a,onPackageSelect:l,isResearching:c,visible:u=!0,counterHeightPercent:d=22,hasVehicle:h=!1,onAddToCart:g,vehicleMakeModel:f,pendingVariants:m,pendingVariantMake:b,pendingVariantModel:_,onVariantSelect:y})=>{const k=f||"Bob's Shelf",j=Xs();Yn();const x=p.useRef(null),T=p.useRef({}),S=p.useRef(null),[F,E]=p.useState(null),[P,C]=p.useState({}),[R,O]=p.useState({}),A=p.useMemo(()=>{const D={};return t.forEach(J=>{const B=J.partslotDescription||"Other Parts";D[B]||(D[B]=[]),D[B].push(J)}),Object.keys(D).sort((J,B)=>J.localeCompare(B)).map(J=>({name:J,products:D[J]}))},[t]);p.useEffect(()=>{if(!r)return;const D=setTimeout(()=>{const ae=Object.entries(T.current);for(const[J,B]of ae)if(B&&hn(J,r)){B.scrollIntoView({behavior:"smooth",block:"start"});break}},300);return()=>clearTimeout(D)},[r]),p.useEffect(()=>{if(!n)return;const D=setTimeout(()=>{const ae=Object.entries(T.current);for(const[J,B]of ae)if(B&&hn(J,n)){B.scrollIntoView({behavior:"smooth",block:"start"});break}i==null||i()},300);return()=>clearTimeout(D)},[n]);const[$,V]=p.useState(0),z=D=>{const ae=D.currentTarget,J=ae.scrollHeight-ae.clientHeight;if(J>0){const B=ae.scrollTop/J;V(Math.max(0,Math.min(1,B)))}},ie=((m==null?void 0:m.length)??0)>0,Y=t.length>0||e.length>0||ie,U=c&&!Y,K=Y&&!U,he=u||Y,Z=j==="mobile"?92:j==="tablet"?65:70,re=j==="desktop"?"900px":j==="tablet"?"500px":"100%",ve=j==="mobile"?"calc(8px + env(safe-area-inset-top, 4px))":"6px";return o.jsxs(o.Fragment,{children:[Y&&u&&o.jsx("div",{style:{position:"fixed",right:"2px",top:`calc(${$*65+18}%)`,...Qu,opacity:.8,transition:"top 0.1s ease-out",zIndex:100,pointerEvents:"none"}}),o.jsxs("div",{ref:x,onScroll:z,className:`absolute overflow-y-auto overflow-x-hidden flex flex-col gap-3 md:gap-4 transition-all duration-400 ease-out product-scroll ${he?"opacity-100 translate-x-0":"opacity-0 translate-x-12 pointer-events-none"}`,style:{width:`${Z}%`,maxWidth:re,right:"0",left:"auto",top:ve,bottom:j==="mobile"?"calc(100px + env(safe-area-inset-bottom, 0px))":"52px",paddingTop:"4px",paddingRight:"16px",paddingLeft:"16px",paddingBottom:"8px",zIndex:55,pointerEvents:"auto",touchAction:"pan-y",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none"},children:[o.jsx("div",{className:"sticky top-0 z-10 -mx-1 px-3 py-2.5",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.85) 0%, rgba(0, 73, 153, 0.9) 100%)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",borderRadius:"24px",boxShadow:"0 10px 40px rgba(0, 102, 204, 0.4)",border:"1px solid rgba(255, 255, 255, 0.25)"},children:o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[c&&Y?o.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:o.jsx("div",{className:"w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin"})}):o.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:o.jsx("svg",{className:"w-3.5 h-3.5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),o.jsx("span",{style:{...ls.primary,fontWeight:700,fontSize:"14px",letterSpacing:"0.025em"},children:c&&Y?"Updating...":k})]}),o.jsxs("span",{style:{color:"rgba(255,255,255,0.8)",fontSize:"12px",fontWeight:500},children:[t.length+e.length," ",t.length+e.length===1?"item":"items"]})]})}),U&&o.jsx("div",{className:"p-5",children:o.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[o.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(0, 102, 204, 0.3)"},children:o.jsx("div",{className:"w-6 h-6 border-2 border-t-transparent rounded-full animate-spin",style:{borderColor:"rgba(255,255,255,0.8)",borderTopColor:"transparent"}})}),o.jsxs("div",{children:[o.jsx("p",{style:{...ls.primary,fontWeight:600,fontSize:"14px"},children:"Searching shelves..."}),o.jsx("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:"Finding the best parts for you"})]})]})}),ie&&m&&y&&o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsx("div",{className:"sticky top-0 z-10 px-4 py-3",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",borderRadius:"20px",boxShadow:"0 8px 32px rgba(0, 102, 204, 0.35)",border:"1px solid rgba(255, 255, 255, 0.2)"},children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:o.jsx("svg",{className:"w-4 h-4 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),o.jsxs("div",{children:[o.jsxs("span",{className:"text-white font-semibold text-sm",children:["Which ",b," ",_,"?"]}),o.jsx("span",{className:"text-white/70 text-xs block",children:"Tap your variant to continue"})]})]})}),o.jsx("div",{className:"flex flex-col gap-2 px-1",children:(()=>{const D=(m||[]).map(J=>[J.engineCode,J.kw?`${J.kw}kW`:null,J.ccDisplay||(J.cc?`${J.cc}cc`:null),J.fuelType].filter(Boolean).join(" · ")||J.displayTitle),ae=D.reduce((J,B)=>(J[B]=(J[B]||0)+1,J),{});return(m||[]).map((J,B)=>{const Se=D[B],we=ae[Se]>1&&J.displaySubtitle?J.displaySubtitle:Se;return o.jsx("button",{type:"button",onClick:()=>y(J),className:"w-full text-left transition-all duration-200 cursor-pointer rounded-2xl overflow-hidden focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 active:scale-[0.98]",style:{background:"linear-gradient(135deg, rgba(255, 255, 255, 0.92) 0%, rgba(255, 255, 255, 0.85) 100%)",backdropFilter:"blur(12px) saturate(150%)",WebkitBackdropFilter:"blur(12px) saturate(150%)",boxShadow:"0 4px 24px rgba(0, 0, 0, 0.12)",border:"1px solid rgba(255, 255, 255, 0.4)",minHeight:"72px"},children:o.jsxs("div",{className:"flex items-center gap-3 p-4",children:[o.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center shrink-0 font-bold text-lg text-white",style:{background:"linear-gradient(135deg, #0066CC 0%, #0052A3 100%)",boxShadow:"0 2px 8px rgba(0, 102, 204, 0.4)"},children:J.optionNumber}),o.jsx("div",{className:"flex-1 min-w-0",children:o.jsx("p",{className:"font-semibold text-gray-900 text-base leading-tight",children:we})}),o.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{background:"rgba(0, 102, 204, 0.1)"},children:o.jsx("svg",{className:"w-4 h-4 text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M9 5l7 7-7 7"})})})]})},J.vehicle_id)})})()})]}),!U&&!Y&&o.jsx("div",{className:"p-5",children:o.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[o.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(255, 149, 0, 0.3)"},children:o.jsx("svg",{className:"w-5 h-5",style:{color:"#FF9500"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),o.jsxs("div",{children:[o.jsx("p",{style:{...ls.primary,fontWeight:600,fontSize:"14px"},children:"No products to display"}),o.jsxs("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:["Products: ",t.length," | Packages: ",e.length]})]})]})}),K&&e.length>0&&o.jsx("div",{className:"space-y-4",children:e.map(D=>{var it,Ue;const ae=Qa(D),J=(D.preparedTiers||[]).filter(N=>!N.isHidden),{hasDisc:B,hasDrum:Se}=ae?Za(J):{hasDisc:!1,hasDrum:!1},ke=ae&&B&&!Se?"disc":ae&&Se&&!B?"drum":R[D.id]||"disc";let we=J;ae&&(we=J.map(N=>{const oe=Ya(N.products,ke);return{...N,products:oe,totalPrice:Xa(oe),productCount:oe.length}}));const je=((it=we.find(N=>N.isRecommended))==null?void 0:it.tierName)||((Ue=we[0])==null?void 0:Ue.tierName)||"",Fe=P[D.id]||je,Le=we.find(N=>N.tierName===Fe),ze=za(D.title).split(".")[0]+".",tt=F===D.id;return o.jsxs("div",{ref:N=>{T.current[D.title]=N},className:"overflow-hidden transition-all duration-300",style:{background:G.card,borderRadius:"16px",border:`1px solid ${G.border}`,boxShadow:"0 4px 20px rgba(0,0,0,0.08)"},children:[o.jsx("div",{className:"px-4 py-3",style:{background:`linear-gradient(135deg, ${G.primary} 0%, ${G.primaryHover} 100%)`},children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 flex items-center justify-center flex-shrink-0",children:o.jsx("svg",{className:"h-5 w-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("h3",{className:"text-white font-bold text-base leading-tight truncate",children:D.title}),D.estimated_time&&o.jsx("div",{className:"flex items-center gap-3 mt-0.5",children:o.jsxs("span",{className:"text-white/70 text-xs flex items-center gap-1",children:[o.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),D.estimated_time]})})]})]})}),o.jsxs("div",{className:"px-4 py-3 border-b",style:{borderColor:G.border},children:[o.jsx("p",{className:"text-sm leading-relaxed",style:{color:G.mutedForeground},children:ze}),ae&&B&&Se&&o.jsxs("div",{className:"mt-2 mb-1",children:[o.jsx("p",{className:"text-[11px] mb-1.5",style:{color:G.mutedForeground},children:"Select your vehicle's rear brake type"}),o.jsxs("div",{className:"flex rounded-xl overflow-hidden border",style:{borderColor:G.border},children:[o.jsx("button",{onClick:()=>O(N=>({...N,[D.id]:"disc"})),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:ke==="disc"?G.primary:"transparent",color:ke==="disc"?"#FFFFFF":G.mutedForeground},children:"Disc Brakes (Pads + Rotors)"}),o.jsx("button",{onClick:()=>O(N=>({...N,[D.id]:"drum"})),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:ke==="drum"?G.primary:"transparent",color:ke==="drum"?"#FFFFFF":G.mutedForeground},children:"Drum Brakes (Shoes + Drums)"})]})]})]}),we.length>0&&o.jsxs("div",{className:"p-3",children:[o.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide mb-2 px-1",style:{color:G.mutedForeground},children:"Choose Your Value Level"}),o.jsx("div",{className:"grid gap-2",style:{gridTemplateColumns:`repeat(${Math.min(we.length,4)}, 1fr)`},children:we.map(N=>{const oe=Ks[N.tierName],Ce=N.tierName===Fe;return o.jsxs("div",{onClick:()=>C(W=>({...W,[D.id]:N.tierName})),className:"relative rounded-xl text-center transition-all cursor-pointer",style:{padding:we.length>=4?"6px 4px":"8px",background:N.isRecommended?`${G.primary}10`:Ce?`${G.primary}05`:G.background,border:`2px solid ${N.isRecommended?G.primary:Ce?G.primary+"80":G.border}`},children:[N.isRecommended&&o.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wide whitespace-nowrap",style:{background:G.primary,color:"white"},children:"Carfix Value"}),o.jsxs("p",{className:"text-sm font-bold mt-1",style:{color:(oe==null?void 0:oe.textColor)||G.foreground},children:[oe==null?void 0:oe.emoji," ",N.displayName]}),o.jsx("div",{className:"flex flex-col items-center gap-1 mt-2",style:{minHeight:we.length>=4?"40px":"48px"},children:N.brands.slice(0,1).map((W,ce)=>{const Ae=`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${W.fullName.replace(/\s+/g,"")}.jpg`;return o.jsx("div",{className:"w-full bg-white rounded-lg flex items-center justify-center overflow-hidden",style:{height:we.length>=4?"36px":"44px",maxWidth:we.length>=4?"64px":"80px",boxShadow:"0 2px 8px rgba(0,0,0,0.1)",border:"1px solid #F1F5F9"},children:o.jsx("img",{src:W.imageUrl,alt:W.fullName,className:"w-auto object-contain",style:{height:we.length>=4?"26px":"32px"},onError:Ze=>{const be=Ze.target;be.src!==Ae?be.src=Ae:(be.style.display="none",be.parentElement.innerHTML=`<span class="text-[10px] font-semibold text-gray-600 truncate px-1">${W.fullName}</span>`)}})},ce)})}),o.jsxs("p",{className:"text-[10px] mt-2",style:{color:G.mutedForeground},children:[N.productCount," ",N.productCount===1?"part":"parts"]}),N.savingsAmount&&N.savingsAmount>0?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-[11px] line-through",style:{color:G.mutedForeground},children:nt(N.originalTotalPrice)}),o.jsx("p",{className:"text-base font-bold",style:{color:G.success},children:nt(N.totalPrice)}),o.jsxs("p",{className:"text-[9px] font-semibold px-1.5 py-0.5 rounded-full mt-0.5",style:{background:`${G.success}15`,color:G.success},children:["SAVE ",nt(N.savingsAmount)," — ",N.bundleDiscountPercentage,"% Bundle Deal"]})]}):o.jsx("p",{className:"text-base font-bold mt-1",style:{color:G.foreground},children:nt(N.totalPrice)}),o.jsx("p",{className:"text-[10px]",style:{color:G.mutedForeground},children:"inc GST"}),o.jsx("button",{onClick:W=>{W.stopPropagation();const ce=N.bundleDiscountPercentage||0,Ae=1-ce/100,Ze=N.products.map(be=>({id:be.sku,name:be.name,brand:be.brand,price:ce>0?Math.round(be.displayPrice*Ae*100)/100:be.displayPrice,sku:be.sku,partNumber:be.partNumber||void 0,image_url:be.productImageUrl,partslotDescription:be.partslotName,quantity:1,_bundleMeta:{is_bundle_item:!0,bundle_discount_percentage:ce,service_package_name:D.title,service_package_id:D.id,quality_tier:N.tierName}}));g==null||g(Ze)},className:"w-full mt-2 py-1.5 rounded-lg text-[10px] font-semibold transition-all",style:{background:N.isRecommended?G.success:"#F1F5F9",color:N.isRecommended?"white":G.success,border:N.isRecommended?"none":"1px solid #E2E8F0",textAlign:"center"},children:"Add"})]},N.tierName)})})]}),o.jsxs("div",{onClick:()=>E(tt?null:D.id),className:"flex items-center justify-center gap-1.5 py-2 cursor-pointer hover:bg-gray-50 transition-colors border-t",style:{borderColor:G.border},children:[o.jsx("span",{className:"text-xs",style:{color:G.mutedForeground},children:tt?"Hide details":"Show details"}),o.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${tt?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",style:{color:G.mutedForeground},children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),tt&&Le&&o.jsx("div",{className:"px-4 pb-4 border-t animate-in slide-in-from-top-2 duration-200",style:{borderColor:G.border},children:o.jsxs("div",{className:"pt-3",children:[o.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide mb-3",style:{color:G.mutedForeground},children:[Le.displayName," Tier Products"]}),o.jsx("div",{className:"space-y-2",children:Le.products.map(N=>o.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg",style:{background:G.background,border:`1px solid ${G.border}`},children:[o.jsx("div",{className:"flex-shrink-0 bg-white rounded-lg overflow-hidden flex items-center justify-center",style:{width:"56px",height:"56px",minWidth:"56px",maxWidth:"56px"},children:N.productImageUrl?o.jsx("img",{src:N.productImageUrl,alt:N.name,className:"object-contain",style:{width:"100%",height:"100%",maxWidth:"56px",maxHeight:"56px",padding:"4px"}}):o.jsx("svg",{className:"w-6 h-6 text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-xs font-medium truncate",style:{color:G.foreground},children:N.name}),o.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[o.jsx("span",{className:"text-[10px]",style:{color:G.mutedForeground},children:N.brand}),N.isRotor&&o.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 font-medium",children:"Pair"})]}),o.jsx("p",{className:"text-[10px] mt-0.5",style:{color:G.mutedForeground},children:N.partslotName})]}),o.jsxs("div",{className:"text-right flex-shrink-0",children:[o.jsx("p",{className:"text-sm font-bold",style:{color:G.primary},children:nt(N.displayPrice)}),N.isRotor&&o.jsxs("p",{className:"text-[9px]",style:{color:G.mutedForeground},children:["$",N.price.toFixed(2)," ea"]})]})]},N.sku))})]})})]},D.id)})}),K&&A.map(({name:D,products:ae})=>{const J=r&&hn(D,r);return o.jsxs("section",{ref:B=>{T.current[D]=B},className:"transition-all duration-300",style:{background:"transparent",borderRadius:"24px"},children:[o.jsxs("div",{"data-testid":"partslot-header","data-partslot-name":D,className:"px-3 py-2.5 flex items-center justify-between",style:{background:J?"rgba(0, 102, 204, 0.95)":"rgba(0, 51, 102, 0.9)",borderRadius:"16px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",marginBottom:"8px"},children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("div",{className:"w-5 h-5 rounded-md flex items-center justify-center flex-shrink-0",style:{background:J?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 1) 100%)":"rgba(255,255,255,0.2)"},children:o.jsx("svg",{className:"h-3 w-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),o.jsx("span",{className:"text-xs font-bold truncate uppercase tracking-wide",style:{color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)"},children:D})]}),o.jsx("span",{className:"text-[10px] font-bold px-2.5 py-1 rounded-full flex-shrink-0",style:{background:"rgba(255, 149, 0, 0.9)",color:"white",boxShadow:"0 2px 8px rgba(255, 149, 0, 0.4)"},children:ae.length})]}),o.jsx("div",{className:"flex flex-col gap-3",children:ae.map((B,Se)=>{const ke=!!(s&&Yu(B,s));return o.jsx("div",{"data-testid":"partslot-product",children:o.jsx(Xu,{product:B,isSpotlighted:ke,spotlightedRef:S,onProductClick:a,onAddToCart:g,viewportSize:j})},`${B.id}-${Se}`)})})]},D)}),o.jsx("div",{className:"h-4"})]})]})},Xn=({onTranscript:t,onSpeechEnd:e,language:r="en-NZ",mode:s="toggle"}={})=>{const[n,i]=p.useState(!1),[a,l]=p.useState(""),[c,u]=p.useState(""),[d,h]=p.useState(null),[g,f]=p.useState(!1),m=p.useRef(null),b=p.useRef(""),_=p.useRef(t),y=p.useRef(e),k=p.useRef(null),j=15e3;p.useEffect(()=>{_.current=t,y.current=e},[t,e]),p.useEffect(()=>{if(typeof window<"u"&&window.location.protocol!=="https:"&&window.location.hostname!=="localhost"&&window.location.hostname!=="127.0.0.1"){console.warn("[BobWidget] Speech recognition requires HTTPS. PTT will not work on HTTP."),h("Voice input requires a secure connection (HTTPS)"),f(!1);return}const F=window.SpeechRecognition||window.webkitSpeechRecognition;if(F){f(!0);const E=new F;E.continuous=s==="ptt",E.interimResults=!0,E.lang=r,E.maxAlternatives=1,E.onstart=()=>{i(!0),h(null)},E.onresult=P=>{let C="",R="";for(let O=P.resultIndex;O<P.results.length;O++){const A=P.results[O][0].transcript;P.results[O].isFinal?R+=A:C+=A}R&&(b.current=R,l(R),_.current&&_.current(R)),u(C)},E.onerror=P=>{switch(i(!1),P.error){case"no-speech":h("No speech detected. Please try again.");break;case"audio-capture":h("No microphone found. Please check your device.");break;case"not-allowed":h("Microphone permission denied. Please allow access.");break;default:h("Speech recognition error. Please try again.")}},E.onend=()=>{k.current&&(clearTimeout(k.current),k.current=null),i(!1),u(""),b.current&&y.current&&y.current(b.current),b.current=""},m.current=E}return()=>{m.current&&m.current.stop()}},[r,s]);const x=()=>{if(m.current&&!n){l(""),u(""),h(null),k.current=setTimeout(()=>{console.warn("[SpeechRecognition] Safety timeout - forcing stop after 15s"),m.current&&m.current.abort(),i(!1),u("")},j);try{m.current.start()}catch(F){console.warn("[SpeechRecognition] start() failed (already running):",F),k.current&&(clearTimeout(k.current),k.current=null)}}},T=()=>{k.current&&(clearTimeout(k.current),k.current=null),m.current&&n&&m.current.stop()};return{isListening:n,transcript:a,interimTranscript:c,error:d,isSupported:g,startListening:x,stopListening:T,toggleListening:()=>{n?T():x()}}},eo=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:l,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,onAddToCart:g,onProductClick:f,onQuickReply:m,onInterrupt:b,counterHeightPercent:_=22})=>{var ve;const[y,k]=p.useState(!1),j=p.useRef(null),x=p.useRef(!1),{bottomOffset:T,zIndexBase:S}=Jn(),{isListening:F,interimTranscript:E,error:P,isSupported:C,startListening:R,stopListening:O}=Xn({onTranscript:D=>r(D),language:"en-NZ",mode:"ptt"});p.useEffect(()=>{E&&r(E)},[E,r]);const A=h?"speaking":s?"processing":F?"listening":"idle",$=p.useCallback(D=>{if(D.preventDefault(),A==="speaking"){b==null||b();return}s||x.current||(x.current=!0,navigator.vibrate&&navigator.vibrate(30),R())},[A,s,R,b]),V=p.useCallback(()=>{x.current&&(x.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),O(),setTimeout(()=>{n()},150))},[O,n]),z=[...t].reverse().find(D=>D.role==="assistant"),ie=((ve=z==null?void 0:z.suggestedProducts)==null?void 0:ve.length)||0,Y=z!=null&&z.content?z.content.length>50?z.content.slice(0,50)+"...":z.content:"Ask Bob about car parts...",U=ie>0?` (${ie} products)`:"",K={idle:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.9) 0%, rgba(22, 163, 74, 0.95) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 8px 32px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},active:{background:"linear-gradient(135deg, rgba(255, 149, 0, 0.95) 0%, rgba(230, 134, 0, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(255, 149, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.3)"},disabled:{background:"rgba(156, 163, 175, 0.5)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"32px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)"}},Z={idle:K.idle,listening:K.active,processing:K.disabled,speaking:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.95) 0%, rgba(22, 163, 74, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"}}[A],re={idle:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-breathe 2s ease-in-out infinite"},listening:null,processing:{border:"2px solid rgba(156, 163, 175, 0.6)",animation:"ring-processing 1.5s ease-in-out infinite"},speaking:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-speaking 1.8s ease-in-out infinite"}};return o.jsxs("div",{ref:j,style:{position:"fixed",bottom:T,left:0,right:0,...Ka,background:"rgba(15, 23, 42, 0.92)",borderRadius:"28px 28px 0 0",borderBottom:"none",transition:"all 0.3s ease-out",boxShadow:"0 -10px 40px rgba(0, 0, 0, 0.3)",height:y?"55vh":"90px",zIndex:S+80,paddingBottom:"env(safe-area-inset-bottom, 8px)"},children:[o.jsx("button",{onClick:()=>k(!y),style:{position:"absolute",top:"-20px",left:"50%",transform:"translateX(-50%)",background:"rgba(255, 255, 255, 0.15)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"9999px",padding:"6px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)",zIndex:S+90,cursor:"pointer",minHeight:"unset",minWidth:"unset"},"aria-label":y?"Collapse chat":"Expand chat",children:y?o.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}):o.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 15l7-7 7 7"})})}),!y&&o.jsx("div",{onClick:()=>k(!0),style:{padding:"8px 12px 2px 12px",cursor:"pointer"},children:o.jsxs("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Y,U&&o.jsx("span",{style:{color:"rgba(255,200,0,0.9)",fontWeight:600},children:U})]})}),y&&o.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px"},className:"glass-scroll",children:[[...t].reverse().map((D,ae)=>{var J;return o.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:D.role==="user"?"flex-end":"flex-start"},children:o.jsxs("div",{style:{maxWidth:(J=D.suggestedProducts)!=null&&J.length?"100%":"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:D.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)":"rgba(255, 255, 255, 0.12)",backdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",color:"rgba(255, 255, 255, 0.95)",textShadow:"0 1px 2px rgba(0,0,0,0.2)"},children:[D.content,D.role==="assistant"&&D.suggestedProducts&&D.suggestedProducts.length>0&&o.jsx(Qn,{products:D.suggestedProducts,title:D.suggestionsTitle,onAddToCart:g,onProductClick:f}),D.role==="assistant"&&D.quickReplies&&D.quickReplies.length>0&&o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"8px"},children:D.quickReplies.map((B,Se)=>o.jsx("button",{onClick:ke=>{ke.stopPropagation(),b==null||b(),m==null||m(B.url)},style:{padding:"6px 14px",borderRadius:"20px",border:"1px solid rgba(0,102,204,0.6)",background:"rgba(0,102,204,0.15)",color:"white",fontSize:"13px",fontWeight:600,cursor:"pointer",backdropFilter:"blur(8px)",WebkitBackdropFilter:"blur(8px)",minHeight:"unset",minWidth:"unset"},children:B.label},Se))})]})},ae)}),o.jsx("div",{ref:c})]}),C&&o.jsxs("div",{style:{display:"flex",justifyContent:"center",padding:"12px 16px 8px 16px",position:"relative"},children:[A==="listening"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite",opacity:0,pointerEvents:"none"}}),o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite 0.5s",opacity:0,pointerEvents:"none"}})]}),A!=="listening"&&re[A]&&o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:re[A].border,transform:"translate(-50%, -50%)",animation:re[A].animation,pointerEvents:"none"}}),o.jsx("button",{onTouchStart:$,onTouchEnd:V,onTouchCancel:V,onMouseDown:$,onMouseUp:V,onMouseLeave:V,onClick:F?V:void 0,disabled:A==="processing","aria-label":"Hold to talk to Bob",className:"glass-button bob-ptt-btn",style:{width:"200px",height:"64px",minHeight:"unset",minWidth:"unset",display:"flex",alignItems:"center",justifyContent:"center",userSelect:"none",touchAction:"none",cursor:A==="processing"?"not-allowed":"pointer",opacity:A==="processing"?.6:1,transform:A==="listening"?"scale(1.04)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease, background 0.3s ease",backdropFilter:Z.backdropFilter,WebkitBackdropFilter:Z.WebkitBackdropFilter,"--bob-ptt-bg":Z.background,"--bob-ptt-shadow":Z.boxShadow,"--bob-ptt-border":Z.border,"--bob-ptt-radius":"32px"},title:"Hold to talk",children:o.jsx("span",{style:{fontSize:"22px",fontWeight:800,letterSpacing:"0.15em",...ls.primary,textTransform:"uppercase",fontFamily:"system-ui, -apple-system, sans-serif"},children:A==="listening"?"LISTENING":A==="processing"?"THINKING":A==="speaking"?"TAP TO STOP":"TALK"})})]}),o.jsxs("div",{style:{padding:"4px 12px 8px 12px",borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:[P&&o.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:P}),o.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[d&&o.jsx("button",{onClick:d,style:{flexShrink:0,height:"40px",width:"40px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"12px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:h?"#0066CC":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:u?"Unmute":"Mute",children:u?o.jsxs("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):o.jsx("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),o.jsxs("div",{style:{flex:1,position:"relative",height:"40px"},children:[o.jsx("input",{type:"text",value:e,onChange:D=>r(D.target.value),onKeyPress:i,onFocus:a,onBlur:l,placeholder:"Message Bob...",disabled:A!=="idle",className:"high-contrast-input bob-chat-input",style:{width:"100%",height:"40px",fontSize:"16px",padding:"0 14px",background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",color:"#0F172A",outline:"none",opacity:A!=="idle"?0:1,transition:"opacity 0.15s ease"}}),A!=="idle"&&o.jsxs("div",{className:"bob-state-overlay",style:{position:"absolute",inset:0,background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",display:"flex",alignItems:"center",padding:"0 14px",gap:"8px"},children:[A==="listening"&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{width:"10px",height:"10px",borderRadius:"50%",backgroundColor:"#FF8C00",animation:"dot-pulse 1s ease-in-out infinite",flexShrink:0}}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Listening..."})]}),A==="processing"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{width:"18px",height:"18px",flexShrink:0,border:"2px solid rgba(15, 23, 42, 0.15)",borderTop:"2px solid #0F172A",borderRadius:"50%",animation:"processing-spin 0.8s linear infinite"}}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is researching your input."})]}),A==="speaking"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{display:"flex",alignItems:"center",gap:"2px",height:"20px",flexShrink:0},children:[0,.15,.3,.45,.6].map((D,ae)=>o.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${D}s infinite`}},ae))}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is talking..."}),u&&o.jsxs("svg",{style:{height:"16px",width:"16px",color:"#ef4444",marginLeft:"auto",flexShrink:0},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]})]})]})]})]})]})]})},to=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:g,chatEndRef:f,isMuted:m,onToggleMute:b,isSpeaking:_,products:y,servicePackages:k,highlightedPartType:j,highlightedProduct:x,scrollToCategory:T,onScrollToCategoryComplete:S,onProductClick:F,onPackageSelect:E,isResearching:P,onAddToCart:C,onQuickReply:R,onInterrupt:O,vehicle:A,onChangeVehicle:$,pendingVariants:V,pendingVariantMake:z,pendingVariantModel:ie,onVariantSelect:Y,bobOffset:U=0,bobScale:K=100,embedded:he=!1})=>{console.log("[MobileBobLayout] Rendering with:",{currentImage:(t==null?void 0:t.substring(0,50))||"EMPTY",backdropUrl:(r==null?void 0:r.substring(0,50))||"NONE",counterOverlayUrl:(s==null?void 0:s.substring(0,50))||"NONE"});const Z=Xs(),[re,ve]=p.useState("center"),[D,ae]=p.useState("hidden"),J=y.length>0||k.length>0,B=((V==null?void 0:V.length)??0)>0,Se=J||B,je=(()=>{switch(Z){case"desktop":return 70;case"tablet":return 80;case"mobile":return 140;default:return 140}})()*K/100;p.useEffect(()=>{if(P&&D!=="loading"&&D!=="visible")ae("loading"),re==="center"&&ve("partial-left");else if(Se&&D!=="visible")if(re==="center"){ve("partial-left"),ae("transitioning");const Le=setTimeout(()=>{ae("visible")},400);return()=>clearTimeout(Le)}else ae("visible");else!Se&&!P&&D!=="hidden"&&(ae("hidden"),ve("center"))},[Se,P,D,re]);const Fe=D!=="hidden";return o.jsxs("div",{className:he?"absolute inset-0 overflow-hidden":"fixed inset-0 overflow-hidden",style:{height:he?"100%":"100dvh",touchAction:"manipulation"},children:[r&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"absolute inset-0 z-0",style:{backgroundImage:`url(${r})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:"blur(var(--bob-blur-intensity, 0px)) brightness(0.95)",transform:"scale(1.02)"}}),o.jsx("div",{className:"absolute inset-0 z-[1]",style:{background:"rgba(0, 0, 0, var(--bob-overlay-opacity, 0.1))"}})]}),o.jsx(Zs,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:je,position:re,verticalOffset:U}),o.jsx(en,{products:y,servicePackages:k,highlightedPartType:j,highlightedProduct:x,scrollToCategory:T,onScrollToCategoryComplete:S,onProductClick:F,onPackageSelect:E,isResearching:P,visible:Fe,counterHeightPercent:n,hasVehicle:!!A,onAddToCart:C,pendingVariants:V,pendingVariantMake:z,pendingVariantModel:ie,onVariantSelect:Y}),o.jsx(eo,{messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:g,chatEndRef:f,isMuted:m,onToggleMute:b,isSpeaking:_,onAddToCart:C,onProductClick:F,onQuickReply:R,onInterrupt:O,counterHeightPercent:n})]})},ro=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:l,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,onQuickReply:g,onInterrupt:f,counterHeightPercent:m=22})=>{const[b,_]=p.useState(!1),y=p.useRef(null),k=p.useRef(!1),{bottomOffset:j,zIndexBase:x}=Jn(),{isListening:T,interimTranscript:S,error:F,isSupported:E,startListening:P,stopListening:C}=Xn({onTranscript:K=>r(K),language:"en-NZ",mode:"ptt"});p.useEffect(()=>{S&&r(S)},[S,r]);const R=h?"speaking":s?"processing":T?"listening":"idle",O=p.useCallback(K=>{if(K.preventDefault(),R==="speaking"){f==null||f();return}s||k.current||(k.current=!0,navigator.vibrate&&navigator.vibrate(30),P())},[R,s,P,f]),A=p.useCallback(()=>{k.current&&(k.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),C(),setTimeout(()=>{n()},150))},[C,n]),$=[...t].reverse().find(K=>K.role==="assistant"),V=$!=null&&$.content?$.content.length>50?$.content.slice(0,50)+"...":$.content:"Ask Bob about car parts...",z={idle:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.9) 0%, rgba(22, 163, 74, 0.95) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 8px 32px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},active:{background:"linear-gradient(135deg, rgba(255, 149, 0, 0.95) 0%, rgba(230, 134, 0, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 12px 48px rgba(255, 149, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.3)"},disabled:{background:"rgba(156, 163, 175, 0.5)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"50%",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)"}},Y={idle:z.idle,listening:z.active,processing:z.disabled,speaking:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.9) 0%, rgba(22, 163, 74, 0.95) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 12px 48px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"}}[R],U={idle:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-breathe 2s ease-in-out infinite"},listening:null,processing:{border:"2px solid rgba(156, 163, 175, 0.6)",animation:"ring-processing 1.5s ease-in-out infinite"},speaking:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-speaking 1.8s ease-in-out infinite"}};return o.jsxs("div",{ref:y,style:{position:"absolute",bottom:0,left:0,right:0,top:"auto",contain:"layout",transform:"translateZ(0)",WebkitTransform:"translateZ(0)",backfaceVisibility:"hidden",WebkitBackfaceVisibility:"hidden",isolation:"isolate",...Ka,background:"rgba(15, 23, 42, 0.92)",borderRadius:"28px 28px 0 0",borderBottom:"none",transition:"height 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 -10px 40px rgba(0, 0, 0, 0.3)",height:b?"55%":"110px",overflow:"visible",zIndex:x+30,paddingBottom:"calc(8px + env(safe-area-inset-bottom, 0px))",pointerEvents:"none"},children:[o.jsx("button",{onClick:()=>_(!b),style:{position:"absolute",top:"-24px",left:"50%",transform:"translateX(-50%)",background:"rgba(0, 102, 204, 0.9)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"2px solid rgba(255, 255, 255, 0.35)",borderRadius:"9999px",padding:"8px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.3)",zIndex:x+40,cursor:"pointer",minHeight:"32px",minWidth:"32px",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto"},"aria-label":b?"Collapse chat":"Expand chat",children:b?o.jsx("svg",{style:{height:"16px",width:"16px",color:"white"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M19 9l-7 7-7-7"})}):o.jsx("svg",{style:{height:"16px",width:"16px",color:"white"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M5 15l7-7 7 7"})})}),!b&&o.jsx("div",{onClick:()=>_(!0),style:{padding:"6px 12px 4px 12px",height:"26px",overflow:"hidden",cursor:"pointer",pointerEvents:"auto"},children:o.jsx("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:V})}),b&&o.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px",pointerEvents:"auto"},className:"glass-scroll",children:[[...t].reverse().map((K,he)=>o.jsx("div",{style:{display:"flex",justifyContent:K.role==="user"?"flex-end":"flex-start"},children:o.jsxs("div",{style:{maxWidth:"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:K.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)":"rgba(255, 255, 255, 0.12)",backdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",color:"rgba(255, 255, 255, 0.95)",textShadow:"0 1px 2px rgba(0,0,0,0.2)"},children:[K.content,K.role==="assistant"&&K.quickReplies&&K.quickReplies.length>0&&o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"8px"},children:K.quickReplies.map((Z,re)=>o.jsx("button",{onClick:ve=>{ve.stopPropagation(),f==null||f(),g==null||g(Z.url)},style:{padding:"6px 14px",borderRadius:"20px",border:"1px solid rgba(0,102,204,0.6)",background:"rgba(0,102,204,0.15)",color:"white",fontSize:"13px",fontWeight:600,cursor:"pointer",backdropFilter:"blur(8px)",WebkitBackdropFilter:"blur(8px)",minHeight:"unset",minWidth:"unset"},children:Z.label},re))})]})},he)),o.jsx("div",{ref:c})]}),o.jsxs("div",{style:{padding:b?"8px 12px 4px 12px":"4px 12px 4px 12px",borderTop:b?"1px solid rgba(255, 255, 255, 0.15)":"none",pointerEvents:"auto"},children:[F&&o.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:F}),o.jsxs("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[d&&b&&o.jsx("button",{onClick:d,style:{flexShrink:0,height:"36px",width:"36px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"10px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:h?"#22c55e":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:u?"Unmute":"Mute",children:u?o.jsxs("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):o.jsx("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),o.jsxs("div",{style:{flex:1,position:"relative",height:"40px"},children:[o.jsx("input",{type:"text",value:e,onChange:K=>r(K.target.value),onKeyPress:i,onFocus:a,onBlur:l,placeholder:"Message Bob...",disabled:R!=="idle",className:"high-contrast-input bob-chat-input",style:{width:"100%",height:"40px",fontSize:"16px",padding:"0 14px",background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",color:"#0F172A",outline:"none",opacity:R!=="idle"?0:1,transition:"opacity 0.15s ease"}}),R!=="idle"&&o.jsxs("div",{className:"bob-state-overlay",style:{position:"absolute",inset:0,background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",display:"flex",alignItems:"center",padding:"0 14px",gap:"8px"},children:[R==="listening"&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{width:"10px",height:"10px",borderRadius:"50%",backgroundColor:"#FF8C00",animation:"dot-pulse 1s ease-in-out infinite",flexShrink:0}}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Listening..."})]}),R==="processing"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{width:"18px",height:"18px",flexShrink:0,border:"2px solid rgba(15, 23, 42, 0.15)",borderTop:"2px solid #0F172A",borderRadius:"50%",animation:"processing-spin 0.8s linear infinite"}}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is researching your input."})]}),R==="speaking"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{display:"flex",alignItems:"center",gap:"2px",height:"20px",flexShrink:0},children:[0,.15,.3,.45,.6].map((K,he)=>o.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${K}s infinite`}},he))}),o.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is talking..."}),u&&o.jsxs("svg",{style:{height:"16px",width:"16px",color:"#ef4444",marginLeft:"auto",flexShrink:0},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]})]})]})]}),E&&o.jsxs("div",{style:{position:"relative",marginLeft:"4px"},children:[R==="listening"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite",opacity:0,pointerEvents:"none"}}),o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite 0.5s",opacity:0,pointerEvents:"none"}})]}),R!=="listening"&&U[R]&&o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:U[R].border,transform:"translate(-50%, -50%)",animation:U[R].animation,pointerEvents:"none"}}),o.jsxs("button",{onTouchStart:O,onTouchEnd:A,onTouchCancel:A,onMouseDown:O,onMouseUp:A,onMouseLeave:A,disabled:R==="processing","aria-label":"Hold to talk to Bob",className:"glass-button bob-ptt-btn",style:{position:"relative",flexShrink:0,height:"72px",width:"72px",minHeight:"unset",minWidth:"unset",display:"flex",alignItems:"center",justifyContent:"center",userSelect:"none",touchAction:"none",color:"white",cursor:R==="processing"?"not-allowed":"pointer",opacity:R==="processing"?.6:1,transform:R==="listening"?"scale(1.08)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease, background 0.3s ease",zIndex:x+45,backdropFilter:Y.backdropFilter,WebkitBackdropFilter:Y.WebkitBackdropFilter,"--bob-ptt-bg":Y.background,"--bob-ptt-shadow":Y.boxShadow,"--bob-ptt-border":Y.border,"--bob-ptt-radius":"50%"},title:"Hold to talk",children:[o.jsx("svg",{style:{height:"28px",width:"28px",filter:"drop-shadow(0 1px 2px rgba(0, 0, 0, 0.2))"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"})}),R==="listening"&&o.jsx("div",{style:{position:"absolute",top:"8px",right:"8px",width:"12px",height:"12px",borderRadius:"50%",backgroundColor:"#fef3c7",animation:"ptt-dot 0.6s ease-in-out infinite alternate"}})]})]})]})]})]})},Zu=({product:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{const n=t.productUrl||t.product_url,i=t.partNumber||t.part_number,a=!!n||!!s;return o.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-white/95 backdrop-blur-md overflow-hidden",children:[o.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-gray-200 bg-white/80 backdrop-blur-sm",children:o.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-blue-600 font-medium text-sm hover:text-blue-700 active:scale-95 transition-all",children:[o.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back to Products"]})}),o.jsxs("div",{className:"flex-1 overflow-y-auto",children:[o.jsx("div",{className:"aspect-square bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center",children:t.image_url?o.jsx("img",{src:t.image_url,alt:t.name,className:"w-full h-full object-contain p-4"}):o.jsxs("div",{className:"flex flex-col items-center justify-center text-gray-400",children:[o.jsx("svg",{className:"h-16 w-16 mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})}),o.jsx("span",{className:"text-sm font-medium uppercase tracking-wide",children:"No Image Available"})]})}),o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsxs("div",{children:[o.jsx("h1",{className:"text-xl font-bold text-gray-900 mb-1",children:t.name}),t.brand&&o.jsx("p",{className:"text-sm text-gray-600 font-medium",children:t.brand})]}),o.jsxs("div",{className:"bg-blue-50 rounded-xl p-4",children:[o.jsx("p",{className:"text-sm text-gray-600 mb-1",children:"Price"}),o.jsx("p",{className:"text-2xl font-bold text-blue-600",children:t.price>0?`$${t.price.toFixed(2)}`:"Price on Request"}),t.price>0&&o.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Inc. GST"})]}),o.jsxs("div",{className:"space-y-3",children:[t.partslotDescription&&o.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[o.jsx("span",{className:"text-sm text-gray-500",children:"Category"}),o.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.partslotDescription})]}),t.sku&&o.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[o.jsx("span",{className:"text-sm text-gray-500",children:"SKU"}),o.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.sku})]}),i&&o.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[o.jsx("span",{className:"text-sm text-gray-500",children:"Part Number"}),o.jsx("span",{className:"text-sm font-medium text-gray-900",children:i})]})]}),a&&o.jsx("a",{href:n||"#",onClick:l=>{s&&(l.preventDefault(),s(t))},target:n&&!s?"_blank":void 0,rel:n&&!s?"noopener noreferrer":void 0,className:"block text-center text-blue-600 text-sm font-medium hover:underline py-2",children:"View Full Details on CARFIX →"})]})]}),o.jsx("div",{className:"p-4 border-t border-gray-200 bg-white/95 backdrop-blur-sm",children:o.jsx("button",{onClick:()=>r==null?void 0:r(t),className:"w-full bg-blue-600 text-white text-base font-semibold py-3 rounded-xl hover:bg-blue-700 active:bg-blue-800 transition-colors shadow-lg",children:"Add to Cart"})})]})},so=({package:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{var j;const[n,i]=p.useState(!1),a=p.useMemo(()=>Qa(t),[t.id,t.title]),{hasDisc:l,hasDrum:c}=p.useMemo(()=>{if(!a||!t.preparedTiers)return{hasDisc:!1,hasDrum:!1};const x=t.preparedTiers.filter(T=>!T.isHidden);return Za(x)},[a,t.preparedTiers]),[u,d]=p.useState("disc"),h=p.useMemo(()=>!a||l&&!c?"disc":c&&!l?"drum":u,[a,l,c,u]),g=a&&l&&c,f=p.useMemo(()=>{if(!t.preparedTiers||t.preparedTiers.length===0)return[];const x=t.preparedTiers.filter(T=>!T.isHidden);return a?x.map(T=>{const S=Ya(T.products,h);return{...T,products:S,totalPrice:Xa(S),productCount:S.length}}):x},[t.preparedTiers,a,h]),m=f.length>0,b=x=>{const T=x.bundleDiscountPercentage||0,S=1-T/100,F=x.products.map(E=>({...E,displayPrice:T>0?Math.round(E.displayPrice*S*100)/100:E.displayPrice,_bundleMeta:{is_bundle_item:!0,bundle_discount_percentage:T,service_package_name:t.title,service_package_id:t.id,quality_tier:x.tierName}}));r==null||r(F)},_=x=>x===2?"grid-cols-2":x===3?"grid-cols-3":"grid-cols-2",y=za(t.title),k=((j=f[0])==null?void 0:j.productCount)||0;return o.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-[#FAFAFA] overflow-hidden",children:[o.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[#E2E8F0] bg-white shadow-sm",children:o.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-[#0052CC] font-medium text-sm hover:text-[#0047B3] active:scale-95 transition-all",children:[o.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back"]})}),o.jsxs("div",{className:"flex-1 overflow-y-auto",children:[o.jsxs("div",{className:"px-4 pt-4 pb-4",style:{background:"linear-gradient(135deg, rgba(0,82,204,0.05) 0%, rgba(56,189,248,0.05) 100%)"},children:[o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center flex-shrink-0 bg-white shadow-md",children:t.icon_url?o.jsx("img",{src:t.icon_url,alt:"",className:"w-8 h-8 object-contain"}):o.jsx("svg",{className:"w-7 h-7 text-[#0052CC]",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("h1",{className:"text-xl font-bold text-[#0F172A]",children:t.title}),o.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-[#64748B]",children:[t.estimated_time&&o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),t.estimated_time]}),t.difficulty_level&&o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11.42 15.17L17.25 21A2.652 2.652 0 0021 17.25l-5.877-5.877M11.42 15.17l2.496-3.03c.317-.384.74-.626 1.208-.766M11.42 15.17l-4.655 5.653a2.548 2.548 0 11-3.586-3.586l6.837-5.63m5.108-.233c.55-.164 1.163-.188 1.743-.14a4.5 4.5 0 004.486-6.336l-3.276 3.277a3.004 3.004 0 01-2.25-2.25l3.276-3.276a4.5 4.5 0 00-6.336 4.486c.091 1.076-.071 2.264-.904 2.95l-.102.085"})}),t.difficulty_level]})]})]})]}),o.jsx("p",{className:"text-sm text-[#64748B] mt-3 leading-relaxed",children:y}),g&&o.jsxs("div",{className:"mt-3",children:[o.jsx("p",{className:"text-[11px] text-[#94A3B8] mb-1.5",children:"Select your vehicle's rear brake type"}),o.jsxs("div",{className:"flex rounded-xl overflow-hidden border border-[#E2E8F0] bg-white",children:[o.jsx("button",{onClick:()=>d("disc"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:u==="disc"?G.primary:"transparent",color:u==="disc"?"#FFFFFF":"#64748B"},children:"Disc Brakes (Pads + Rotors)"}),o.jsx("button",{onClick:()=>d("drum"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:u==="drum"?G.primary:"transparent",color:u==="drum"?"#FFFFFF":"#64748B"},children:"Drum Brakes (Shoes + Drums)"})]})]})]}),o.jsxs("div",{className:"px-4 py-3 flex items-center justify-center gap-2 border-b border-[#E2E8F0] bg-white",children:[o.jsx("span",{className:"font-semibold text-[#0F172A] text-sm",children:"Choose Your Value Level"}),o.jsx("span",{className:"text-[#64748B] text-xs cursor-help",title:"Select the quality tier that suits your needs",children:"ⓘ"})]}),o.jsx("div",{className:"p-4",children:m?o.jsx("div",{className:`grid ${_(f.length)} gap-3`,children:f.map(x=>{const T=Ks[x.tierName];return o.jsxs("div",{className:"relative rounded-2xl overflow-hidden bg-white shadow-md flex flex-col",style:{border:x.isRecommended?"2px solid #0052CC":"1px solid #E2E8F0"},children:[x.isRecommended&&o.jsx("div",{className:"absolute top-0 left-0 right-0 px-2 py-1 text-[9px] font-bold text-white text-center",style:{background:G.primary},children:"★ CARFIX VALUE"}),o.jsxs("div",{className:`p-3 flex-1 flex flex-col ${x.isRecommended?"pt-7":""}`,children:[o.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[o.jsx("span",{className:"text-lg",children:T==null?void 0:T.emoji}),o.jsxs("div",{children:[o.jsx("span",{className:"font-bold text-sm block",style:{color:(T==null?void 0:T.textColor)||G.foreground},children:x.displayName}),o.jsx("span",{className:"text-[10px] text-[#64748B] hidden md:block",children:x.description||(T==null?void 0:T.description)})]})]}),o.jsx("div",{className:"flex items-center gap-1.5 mb-3 min-h-[42px] flex-wrap",children:x.brands.slice(0,3).map(S=>o.jsx("div",{className:"h-10 px-2 bg-white rounded-xl flex items-center justify-center shadow-md border border-[#F1F5F9]",children:o.jsx("img",{src:S.imageUrl,alt:S.fullName,className:"h-6 w-auto object-contain",onError:F=>{const E=F.target,P=`${vs.storageBase}/brand_images/${S.fullName.replace(/\s+/g,"")}.jpg`;if(E.src!==P)E.src=P;else{const C=E.parentElement;C&&(C.innerHTML=`<span class="text-[10px] font-medium text-slate-700 px-1 truncate max-w-[60px]">${S.name}</span>`)}}})},S.name))}),o.jsxs("p",{className:"text-xs text-[#64748B] hidden md:block mb-2",children:[x.productCount," part",x.productCount!==1?"s":""," included"]}),o.jsx("div",{className:"mt-auto",children:x.savingsAmount&&x.savingsAmount>0?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-xs line-through text-[#94A3B8]",children:nt(x.originalTotalPrice)}),o.jsx("p",{className:"text-xl font-bold",style:{color:"#22C55E"},children:nt(x.totalPrice)}),o.jsxs("p",{className:"text-[10px] font-semibold text-[#22C55E] bg-[#22C55E]/10 inline-block px-1.5 py-0.5 rounded-full mt-0.5",children:["SAVE ",nt(x.savingsAmount)," — ",x.bundleDiscountPercentage,"% Bundle Deal"]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-xl font-bold",style:{color:x.isRecommended?"#0052CC":"#0F172A"},children:nt(x.totalPrice)}),o.jsx("p",{className:"text-[10px] text-[#64748B] hidden md:block",children:"inc GST"})]})}),o.jsx("button",{onClick:()=>b(x),className:`mt-3 w-full px-3 py-2.5 rounded-xl text-xs font-semibold transition-all hover:scale-[1.02] active:scale-95 flex items-center justify-center ${x.isRecommended?"bg-[#22C55E] text-white shadow-md hover:bg-[#16A34A]":"bg-slate-100 text-[#22C55E] border border-slate-200 hover:bg-slate-200"}`,children:"Add to Cart"})]})]},x.tierName)})}):o.jsxs("div",{className:"rounded-2xl p-6 bg-white border border-[#E2E8F0] shadow-md text-center",children:[o.jsx("svg",{className:"w-12 h-12 mx-auto text-[#94A3B8] mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),o.jsx("p",{className:"text-sm font-medium text-[#64748B]",children:"Package details not available for this vehicle"}),o.jsx("p",{className:"text-xs text-[#94A3B8] mt-1",children:"Please try refreshing or contact support"})]})}),m&&o.jsxs("div",{className:"px-4 pb-4",children:[o.jsxs("button",{onClick:()=>i(!n),className:"w-full flex items-center justify-between p-3 rounded-xl bg-white border border-[#E2E8F0] hover:bg-slate-50 transition-all shadow-sm",children:[o.jsxs("span",{className:"text-sm font-medium text-[#0F172A]",children:[n?"▼":"▶"," View Product Details"]}),o.jsxs("span",{className:"text-xs text-[#64748B]",children:[k," product",k!==1?"s":""]})]}),n&&o.jsx("div",{className:"mt-3 space-y-4 bg-white rounded-xl border border-[#E2E8F0] p-3",children:f.map(x=>{if(x.products.length===0)return null;const T=Ks[x.tierName];return o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2 pb-1 border-b border-[#E2E8F0]",children:[o.jsx("span",{className:"text-lg",children:T==null?void 0:T.emoji}),o.jsx("span",{className:"font-semibold text-sm",style:{color:T==null?void 0:T.textColor},children:x.displayName}),o.jsxs("span",{className:"text-xs text-[#64748B]",children:["(",x.products.length," parts)"]})]}),o.jsx("div",{className:"space-y-2",children:x.products.map((S,F)=>{var C;const E=(C=t.carfixValueProducts)==null?void 0:C.includes(S.sku),P=S.unitPrice??S.price;return o.jsxs("div",{className:"flex items-center gap-3 p-2.5 rounded-xl transition-all hover:bg-slate-50 cursor-pointer border border-[#E2E8F0]",onClick:()=>s==null?void 0:s(S.sku),children:[o.jsx("div",{className:"flex-shrink-0 rounded-lg bg-white overflow-hidden border border-[#E2E8F0]",style:{width:"56px",height:"56px",minWidth:"56px",maxWidth:"56px"},children:o.jsx("img",{src:S.productImageUrl||vs.productImage(S.sku),alt:S.name,className:"object-contain",style:{width:"100%",height:"100%",maxWidth:"56px",maxHeight:"56px",padding:"6px"},onError:R=>{R.target.src="/placeholder.svg"}})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[o.jsx("span",{className:"text-xs font-semibold text-[#0F172A]",children:S.brandFullName||S.brand}),E&&o.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"rgba(0, 82, 204, 0.1)",color:"#0052CC"},children:"CFX VALUE"}),S.isMultiQty&&S.perCarQty>1&&o.jsxs("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#F0FDF4",color:"#15803D"},children:["×",S.perCarQty]}),S.isRotor&&o.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#EFF6FF",color:"#1D4ED8"},children:"Pair"})]}),o.jsx("p",{className:"text-xs text-[#64748B] line-clamp-1",children:S.name})]}),o.jsxs("div",{className:"text-right flex-shrink-0",children:[o.jsx("p",{className:"text-sm font-bold text-[#0F172A]",children:nt(S.displayPrice)}),S.isMultiQty&&S.perCarQty>1&&o.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[S.perCarQty,"× ",nt(P)," each"]}),S.isRotor&&!S.isMultiQty&&o.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[nt(P)," each"]})]})]},`${S.sku}-${F}`)})})]},x.tierName)})})]}),t.bundle_discount_percentage&&t.bundle_discount_percentage>0&&o.jsx("div",{className:"px-4 pb-4",children:o.jsx("div",{className:"rounded-xl p-3 text-center",style:{background:"rgba(34,197,94,0.1)",border:"1px solid rgba(34,197,94,0.2)"},children:o.jsxs("span",{className:"text-sm font-semibold text-[#22C55E]",children:["Bundle saves you ",t.bundle_discount_percentage,"%"]})})})]})]})},no=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:g,chatEndRef:f,isMuted:m,onToggleMute:b,isSpeaking:_,products:y,servicePackages:k,highlightedPartType:j,highlightedProduct:x,scrollToCategory:T,onScrollToCategoryComplete:S,onProductClick:F,onPackageSelect:E,isResearching:P,onAddToCart:C,onNavigateToProductPage:R,onQuickReply:O,onInterrupt:A,vehicle:$,onChangeVehicle:V,pendingVariants:z,pendingVariantMake:ie,pendingVariantModel:Y,onVariantSelect:U,bobOffset:K=0,bobScale:he=100})=>{const[Z,re]=p.useState("center"),[ve,D]=p.useState("hidden"),[ae,J]=p.useState("products"),[B,Se]=p.useState(null),[ke,we]=p.useState(null),je=y.length>0||k.length>0,Fe=((z==null?void 0:z.length)??0)>0,Le=je||Fe,tt=(ae==="productDetail"?70:Z==="center"&&!Le?140:98)*he/100;p.useEffect(()=>{if(P&&ve!=="loading"&&ve!=="visible")D("loading"),Z==="center"&&re("partial-left");else if(Le&&ve!=="visible")if(Z==="center"){re("partial-left"),D("transitioning");const W=setTimeout(()=>{D("visible")},400);return()=>clearTimeout(W)}else D("visible");else!Le&&!P&&ve!=="hidden"&&(D("hidden"),re("center"))},[Le,P,ve,Z]);const it=W=>{if(R){R(W),F==null||F(W);return}Se(W),J("productDetail"),F==null||F(W)},Ue=()=>{Se(null),we(null),J("products")},N=W=>{console.log("[ContainedMobileBobLayout] Package selected:",W.title),we(W),J("packageDetail"),E==null||E(W)},oe=ve!=="hidden"&&ae==="products",Ce=ve!=="hidden";return o.jsxs("div",{className:"absolute inset-0",style:{overflow:"clip",isolation:"isolate"},onContextMenu:W=>W.preventDefault(),children:[r&&o.jsx("div",{className:"absolute inset-0 z-0 transition-all duration-500 ease-out",style:{backgroundImage:`url(${r})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:Ce?"blur(var(--bob-blur-intensity, 0px)) brightness(0.95)":"none",transform:Ce?"scale(1.02)":"scale(1)",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"}}),o.jsx(Zs,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:tt,position:Z,verticalOffset:K}),o.jsx(en,{products:y,servicePackages:k,highlightedPartType:j,highlightedProduct:x,scrollToCategory:T,onScrollToCategoryComplete:S,onProductClick:it,onPackageSelect:N,isResearching:P,visible:oe,counterHeightPercent:n,hasVehicle:!!$,onAddToCart:C,vehicleMakeModel:$?`${$.make||""} ${$.model||""}`.trim():void 0,pendingVariants:z,pendingVariantMake:ie,pendingVariantModel:Y,onVariantSelect:U}),ae==="productDetail"&&B&&o.jsx(Zu,{product:B,onBack:Ue,onAddToCart:C,onNavigateToProductPage:R}),ae==="packageDetail"&&ke&&o.jsx(so,{package:ke,onBack:Ue,onAddToCart:W=>{W.forEach(ce=>{var Ae;C==null||C({id:ce.sku||((Ae=ce.partslotId)==null?void 0:Ae.toString())||"unknown",name:ce.name||ce.partslotName||"Unknown Part",brand:ce.brand,price:ce.displayPrice,sku:ce.sku,partNumber:ce.partNumber,image_url:ce.productImageUrl,partslotDescription:ce.partslotName})})},onNavigateToProductPage:W=>{const ce=y.find(Ae=>Ae.sku===W);ce&&R&&R(ce)}}),ae==="products"&&o.jsx(ro,{messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:g,chatEndRef:f,isMuted:m,onToggleMute:b,isSpeaking:_,onQuickReply:O,onInterrupt:A,counterHeightPercent:n})]})},Zn=({variant:t="inline",initialState:e="idle",showChat:r=!0,className:s="",backdropUrl:n,counterOverlayUrl:i,counterHeightPercent:a,defaultBobImage:l,verticalOffset:c=0,scale:u=100,sessionToken:d,embedded:h=!1,initialVehicle:g})=>{var it,Ue;const{callbacks:f}=Bt(),[m,b]=p.useState(!1),{animationState:_,setAnimationState:y,getCurrentImage:k,getCurrentOffset:j,getCurrentScale:x,availableStates:T}=Da({isSpeaking:m}),{activeBackdrop:S}=La(),[F,E]=p.useState([]),[P,C]=p.useState([]),[R,O]=p.useState(null),[A,$]=p.useState(null),[V,z]=p.useState(!1),[ie,Y]=p.useState(null),U=p.useRef(new Set);p.useEffect(()=>{const N=new Set(F.map(oe=>oe.partslotDescription||"Other Parts").filter(Boolean));U.current=N},[F]),p.useEffect(()=>{if(P.length>0){const N=new Set(U.current);P.forEach(oe=>{oe.title&&N.add(oe.title)}),U.current=N}},[P]);const[K,he]=p.useState([]),[Z,re]=p.useState(""),[ve,D]=p.useState(""),ae=p.useRef(null),J=p.useRef(null);p.useEffect(()=>{ae.current=N=>{if(z(!1),!N||N.length===0){console.log("[Bob] Clearing products (empty array received)"),E([]);return}const oe=N[0];console.log("[Bob] First part raw keys:",Object.keys(oe));const Ce=N.map((W,ce)=>{const Ae=W.Brand||W.brand||"";return{id:W.SKU||W.sku||`part-${ce}`,name:W["Part Product Type"]||W.partslot_description||W.name||"Unknown Part",brand:Ae,price:W["Metro Retail Price"]||W.price||0,sku:W.SKU||W.sku,partNumber:W["Part Number"]||W.part_number||null,partslotDescription:W["Part Product Type"]||W.partslot_description||W.partslotDescription||W.part_type||W.category||"General Parts",image_url:W.image_url||(W.SKU||W.sku?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/product_images/${W.SKU||W.sku}.jpg`:void 0),webDescription:W["Web Part Description"]||W.web_description||null,brandDescription:W["Brand Description"]||W.brand_description||null,perCarQty:W["Per Car Qty"]||W.per_car_qty||1,volume:W.volume||null,viscosity:W.viscosity||null,brandImageUrl:Ae?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${Ae.replace(/\s+/g,"")}.jpg`:void 0}});E(W=>{var er;const ce=new Set(W.map(Me=>Me.sku).filter(Boolean)),Ae=new Set(W.map(Me=>Me.partslotDescription||"Other Parts")),Ze=new Set,be=Ce.filter(Me=>!Me.sku||Ze.has(Me.sku)||ce.has(Me.sku)?!1:(Ze.add(Me.sku),!0));if(console.log("[Bob] Products mapped:",Ce.length,"-> new unique:",be.length,"-> existing:",W.length),be.length>0&&W.length>0){const Me=(er=be.find(Qr=>!Ae.has(Qr.partslotDescription||"Other Parts")))==null?void 0:er.partslotDescription;Me&&setTimeout(()=>Y(Me),100)}return[...W,...be]})},J.current=N=>{if(!N||N.length===0){console.log("[Bob] Clearing service packages (empty array received)"),C([]);return}console.log("[Bob] Service packages received via stable ref:",N.length),C(N)}},[]);const B=Fa({setAnimationState:y,manualMode:!1,onReadyToSpeak:()=>{console.log("[BobWidget] Ready to speak")},onStreamComplete:()=>{y(T.find(N=>N.includes("idle"))||"idle")},onResearchStart:()=>{z(!0)},onVariantSelectionRequired:(N,oe,Ce)=>{z(!1),he(N),re(oe),D(Ce)},onHighlightPart:N=>{O(N),setTimeout(()=>O(null),8e3)},onHighlightProduct:N=>{$(N),setTimeout(()=>$(null),8e3)},onAutoFetchComplete:()=>{z(!1)},shelfCategoriesRef:U,initialVehicle:g});p.useEffect(()=>{B.identifiedVehicle&&(he([]),re(""),D(""))},[(it=B.identifiedVehicle)==null?void 0:it.vehicle_id,(Ue=B.identifiedVehicle)==null?void 0:Ue.id]);const Se=N=>{B.sendDirectMessage(`Option ${N.optionNumber}`)};p.useEffect(()=>{b(B.isSpeaking)},[B.isSpeaking]),p.useEffect(()=>{const N=f.onPartsFound,oe=f.onServicePackagesFound;return f.onPartsFound=Ce=>{var W;(W=ae.current)==null||W.call(ae,Ce),N==null||N(Ce)},f.onServicePackagesFound=Ce=>{var W;(W=J.current)==null||W.call(J,Ce),oe==null||oe(Ce)},()=>{f.onPartsFound=N,f.onServicePackagesFound=oe}},[f]);const ke=n||(S==null?void 0:S.image_url),we=i||(S==null?void 0:S.counter_overlay_url)||void 0,je=a||(S==null?void 0:S.counter_height_percent)||12,Fe=k()||l||"",Le=j(),Xe=x(),ze=p.useCallback(N=>{var W,ce,Ae,Ze;const oe=Array.isArray(N)?N:[N],Ce=((ce=(W=B.identifiedVehicle)==null?void 0:W.vehicle_id)==null?void 0:ce.toString())||((Ze=(Ae=B.identifiedVehicle)==null?void 0:Ae.id)==null?void 0:Ze.toString());oe.forEach(be=>{var Me;const er={product_id:be.id||be.sku||"",product_name:be.name,quantity:be.quantity||1,unit_price:be.price,sku:be.sku,brand:be.brand,image_url:be.image_url,vehicle_id:Ce,...be._bundleMeta||{}};(Me=f.onAddToCart)==null||Me.call(f,er)})},[B.identifiedVehicle,f]);if(t==="mobile"||t==="fullscreen")return o.jsx(to,{currentImage:Fe,animationState:_,backdropUrl:ke,counterOverlayUrl:we,counterHeightPercent:je,bobOffset:Le,bobScale:Xe,embedded:h,messages:B.messages,input:B.input,setInput:B.setInput,isLoading:B.isLoading,onSend:B.handleSend,onKeyPress:B.handleKeyPress,onInputFocus:B.handleInputFocus,onInputBlur:B.handleInputBlur,chatEndRef:B.chatEndRef,isMuted:B.isMuted,onToggleMute:B.toggleMute,isSpeaking:B.isSpeaking,products:F,servicePackages:P,highlightedPartType:R,highlightedProduct:A,scrollToCategory:ie,onScrollToCategoryComplete:()=>Y(null),onAddToCart:ze,onNavigateToProductPage:N=>{var oe;return(oe=f.onNavigateToProductPage)==null?void 0:oe.call(f,N)},onQuickReply:N=>{var oe;return(oe=f.onNavigateToProductPage)==null?void 0:oe.call(f,{url:N})},onPackageSelect:N=>console.log("[BobWidget] Package selected:",N),isResearching:V,vehicle:B.identifiedVehicle,pendingVariants:K,pendingVariantMake:Z,pendingVariantModel:ve,onVariantSelect:Se,onInterrupt:B.stopAllAudio});if(t==="inline"&&r)return o.jsx("div",{className:`relative w-full h-full ${s}`,children:o.jsx(no,{currentImage:Fe,animationState:_,backdropUrl:ke,counterOverlayUrl:we,counterHeightPercent:je,bobOffset:Le,bobScale:Xe,messages:B.messages,input:B.input,setInput:B.setInput,isLoading:B.isLoading,onSend:B.handleSend,onKeyPress:B.handleKeyPress,onInputFocus:B.handleInputFocus,onInputBlur:B.handleInputBlur,chatEndRef:B.chatEndRef,isMuted:B.isMuted,onToggleMute:B.toggleMute,isSpeaking:B.isSpeaking,products:F,servicePackages:P,highlightedPartType:R,highlightedProduct:A,scrollToCategory:ie,onScrollToCategoryComplete:()=>Y(null),onAddToCart:ze,onNavigateToProductPage:N=>{var oe;return(oe=f.onNavigateToProductPage)==null?void 0:oe.call(f,N)},onQuickReply:N=>{var oe;return(oe=f.onNavigateToProductPage)==null?void 0:oe.call(f,{url:N})},onPackageSelect:N=>console.log("[BobWidget] Package selected:",N),isResearching:V,vehicle:B.identifiedVehicle,pendingVariants:K,pendingVariantMake:Z,pendingVariantModel:ve,onVariantSelect:Se,onInterrupt:B.stopAllAudio})});const tt={inline:"",floating:"fixed bottom-4 right-4 w-96 z-50 shadow-2xl rounded-lg overflow-hidden"};return o.jsxs("div",{className:`${tt[t]||""} ${s}`,children:[Fe&&o.jsx(Ua,{currentImage:Fe,animationState:_,backdropUrl:ke,counterOverlayUrl:we,counterHeightPercent:je,verticalOffset:Le,scale:Xe}),r&&o.jsx(Ha,{messages:B.messages,input:B.input,setInput:B.setInput,isLoading:B.isLoading,onSend:B.handleSend,onKeyPress:B.handleKeyPress,onInputFocus:B.handleInputFocus,onInputBlur:B.handleInputBlur,chatEndRef:B.chatEndRef,isMuted:B.isMuted,onToggleMute:B.toggleMute,isSpeaking:B.isSpeaking})]})},io=(t=!0)=>{const[e,r]=p.useState("prompt"),s=p.useRef(!1);return p.useEffect(()=>{if(!t)return;navigator.permissions?navigator.permissions.query({name:"microphone"}).then(i=>{r(i.state),i.state!=="granted"&&(i.state==="prompt"&&!s.current&&(s.current=!0,navigator.mediaDevices.getUserMedia({audio:!0}).then(a=>{a.getTracks().forEach(l=>l.stop()),r("granted")}).catch(()=>r("denied"))),i.addEventListener("change",()=>{r(i.state)}))}).catch(()=>{n()}):n();function n(){var i;if(!s.current){if(!((i=navigator.mediaDevices)!=null&&i.getUserMedia)){r("unsupported");return}s.current=!0,navigator.mediaDevices.getUserMedia({audio:!0}).then(a=>{a.getTracks().forEach(l=>l.stop()),r("granted")}).catch(()=>r("denied"))}}},[t]),{micPermission:e}},ed=({bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,variant:n="mobile",initialState:i,showChat:a,className:l,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:h,verticalOffset:g,scale:f,ga4Config:m,analyticsEnabled:b=!0,bottomOffset:_=0,zIndexBase:y=50,embedded:k=!1})=>{const{micPermission:j}=io(!0);return p.useEffect(()=>{console.log("[BobWidget] Initialized",{version:It,variant:n,bottomOffset:_,zIndexBase:y,bobConfigUrl:t.supabaseUrl,hostApiBaseUrl:e.baseUrl,analyticsEnabled:b,micPermission:j})},[n,_,y,t.supabaseUrl,e.baseUrl,b,j]),o.jsx("div",{className:"bob-widget-root",style:{width:"100%",height:"100%"},children:o.jsx(Gn,{bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,ga4Config:m,analyticsEnabled:b,bottomOffset:_,zIndexBase:y,children:o.jsx(Zn,{variant:n,initialState:i,showChat:a,className:l,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:h,verticalOffset:g,scale:f,embedded:k})})})};function td(t){return t<640?"mobile":t<1024?"tablet":"desktop"}function rd(){const t=[];if(typeof window>"u")return t;const e=document.querySelector(".bob-widget-root");if(!e)return t.push("bob-widget-root not found in DOM"),t;const r=window.getComputedStyle(e),s=e.parentElement;return s&&window.getComputedStyle(s).overflow==="hidden"&&t.push("Parent has overflow:hidden - may clip Bob"),r.transform!=="none"&&r.transform!=="matrix(1, 0, 0, 1, 0, 0)"&&t.push(`Unexpected transform on root: ${r.transform}`),r.isolation!=="isolate"&&t.push("Isolation not properly set"),t}const ao=({partnerConfig:t,sessionToken:e})=>{const[r,s]=p.useState(null),[n,i]=p.useState([]),[a,l]=p.useState(!1);if(p.useEffect(()=>{const u=()=>{var g;const d=window.innerWidth,h=window.innerHeight;s({viewport:{width:d,height:h,deviceType:td(d)},origin:window.location.origin,originAllowed:((g=t==null?void 0:t.allowed_origins)==null?void 0:g.some(f=>f===window.location.origin||f.includes("*")))??!1,userAgent:navigator.userAgent.slice(0,50)+"...",timestamp:new Date().toISOString()}),i(rd())};return u(),window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[t]),!r)return null;const c=({ok:u,label:d})=>o.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"4px",fontSize:"11px",fontWeight:500,background:u?"rgba(34, 197, 94, 0.2)":"rgba(239, 68, 68, 0.2)",color:u?"#22c55e":"#ef4444"},children:[u?"✓":"✗"," ",d]});return o.jsxs("div",{style:{position:"fixed",top:"8px",right:"8px",zIndex:99999,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace',fontSize:"11px",lineHeight:1.4},children:[o.jsx("button",{onClick:()=>l(!a),style:{position:"absolute",top:0,right:0,width:"24px",height:"24px",background:"rgba(0, 0, 0, 0.8)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"4px",color:"#fff",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1},children:a?"🔍":"✕"}),!a&&o.jsxs("div",{style:{background:"rgba(0, 0, 0, 0.9)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"8px",padding:"12px",color:"#fff",maxWidth:"320px",backdropFilter:"blur(8px)"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"12px",paddingBottom:"8px",borderBottom:"1px solid rgba(255,255,255,0.1)"},children:[o.jsx("span",{style:{fontSize:"14px"},children:"🔧"}),o.jsxs("span",{style:{fontWeight:600},children:["Bob Debug v",It]})]}),o.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px",marginBottom:"12px"},children:[o.jsx(c,{ok:!!t,label:`Partner: ${(t==null?void 0:t.partner_code)||"none"}`}),o.jsx(c,{ok:!!e,label:e?"Session":"No Session"}),o.jsx(c,{ok:r.originAllowed,label:"Origin"})]}),o.jsxs("div",{style:{display:"grid",gap:"6px"},children:[o.jsx(Or,{label:"Viewport",value:`${r.viewport.width}×${r.viewport.height} (${r.viewport.deviceType})`}),o.jsx(Or,{label:"Origin",value:r.origin}),o.jsx(Or,{label:"Bottom Offset",value:`${(t==null?void 0:t.default_bottom_offset)??0}px`}),o.jsx(Or,{label:"Z-Index Base",value:`${(t==null?void 0:t.default_z_index_base)??50}`}),o.jsx(Or,{label:"Blur",value:`${(t==null?void 0:t.backdrop_blur_intensity)??8}px`}),o.jsx(Or,{label:"Overlay",value:`${(((t==null?void 0:t.backdrop_overlay_opacity)??.15)*100).toFixed(0)}%`})]}),(t==null?void 0:t.feature_flags)&&o.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[o.jsx("div",{style:{color:"rgba(255,255,255,0.5)",marginBottom:"4px"},children:"Features:"}),o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px"},children:Object.entries(t.feature_flags).map(([u,d])=>o.jsx(c,{ok:!!d,label:u.replace(/([A-Z])/g," $1").trim()},u))})]}),n.length>0&&o.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[o.jsx("div",{style:{color:"#ef4444",marginBottom:"4px"},children:"⚠️ CSS Conflicts:"}),n.map((u,d)=>o.jsxs("div",{style:{color:"#fca5a5",fontSize:"10px"},children:["• ",u]},d))]}),o.jsx("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",color:"rgba(255,255,255,0.4)",fontSize:"10px"},children:r.timestamp})]})]})},Or=({label:t,value:e})=>o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:"8px"},children:[o.jsxs("span",{style:{color:"rgba(255,255,255,0.5)"},children:[t,":"]}),o.jsx("span",{style:{color:"#fff",textAlign:"right",wordBreak:"break-all"},children:e})]}),Hi="https://gjoguxzstsihhxvdgpto.supabase.co",Ki="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imdqb2d1eHpzdHNpaGh4dmRncHRvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjM5MzgyODEsImV4cCI6MjA3OTUxNDI4MX0.detu4TKB7RjC6l6CrVaPYoi0Hhz2asDt6zxNx1cdzq8";function sd(t,e){return t.some(r=>{if(r.includes("*")){const s=r.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${s}$`).test(e)}return r===e})}function oo(t){const[e,r]=p.useState(null),[s,n]=p.useState(!0),[i,a]=p.useState(null),[l,c]=p.useState(!1),[u,d]=p.useState(null),h=p.useCallback(async()=>{if(!t){n(!1),a(new Error("Partner code is required"));return}n(!0),a(null);try{const g=jn(Hi,Ki);console.log(`[BobWidget] Loading partner config for: ${t}`);const{data:f,error:m}=await g.from("bob_partners").select("*").eq("partner_code",t).eq("is_active",!0).maybeSingle();if(m)throw new Error(`Failed to load partner config: ${m.message}`);if(!f)throw new Error(`Partner "${t}" not found or inactive`);const b=f,_=typeof window<"u"?window.location.origin:"",y=sd(b.allowed_origins||[],_);!y&&_&&(console.warn(`[BobWidget] Origin "${_}" not in allowed origins for ${t}`),console.warn("[BobWidget] Allowed origins:",b.allowed_origins));const k=jn(b.bob_supabase_url||Hi,b.bob_supabase_key||Ki,{auth:{storageKey:`bobwidget_${b.partner_code.toLowerCase()}`,persistSession:!1,autoRefreshToken:!1}});console.log("[BobWidget] Partner config loaded:",{partner:b.partner_code,displayName:b.display_name,bottomOffset:b.default_bottom_offset,blurIntensity:b.backdrop_blur_intensity,features:b.feature_flags,originAllowed:y}),r(b),c(y),d(k)}catch(g){const f=g instanceof Error?g:new Error("Unknown error loading partner config");console.error("[BobWidget] Partner config error:",f),a(f)}finally{n(!1)}},[t]);return p.useEffect(()=>{h()},[h]),{config:e,isLoading:s,error:i,isOriginAllowed:l,supabaseClient:u,reload:h}}function lo(t,e,r){return t!=null&&t.feature_flags?t.feature_flags[e]??r:r}const nd=()=>o.jsxs("div",{className:"bob-widget-root",style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",background:"linear-gradient(180deg, #0a1628 0%, #0f2137 100%)"},children:[o.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[o.jsx("div",{style:{width:"48px",height:"48px",border:"4px solid rgba(0, 102, 204, 0.3)",borderTopColor:"#0066cc",borderRadius:"50%",animation:"spin 1s linear infinite"}}),o.jsx("span",{style:{color:"rgba(255,255,255,0.7)",fontSize:"14px"},children:"Loading Bob..."})]}),o.jsx("style",{children:`
66
+ Issued At: ${i.toISOString()}`;if(n&&(v+=`
67
+ Expiration Time: ${n.toISOString()}`),o&&(v+=`
68
+ Not Before: ${o.toISOString()}`),c&&(v+=`
69
+ Request ID: ${c}`),u){let S=`
70
+ Resources:`;for(const j of u){if(!j||typeof j!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${j}`);S+=`
71
+ - ${j}`}v+=S}return`${_}
72
+ ${v}`}class Le 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}}class Ys extends Le{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function Mc({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 Le({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 Le({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 Le({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 Le({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 Le({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new Le({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 Le({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new Le({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(Oa(a)){if(i.rp.id!==a)return new Le({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Le({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 Le({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 Le({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 Le({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Wc({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 Le({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new Le({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(Oa(s)){if(r.rpId!==s)return new Le({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Le({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new Le({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 Le({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class qc{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 Hc=new qc;function zc(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=rn(t,["challenge","user","excludeCredentials"]),i=$r(e).buffer,a=Object.assign(Object.assign({},r),{id:$r(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 c=0;c<s.length;c++){const u=s[c];o.excludeCredentials[c]=Object.assign(Object.assign({},u),{id:$r(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return o}function Kc(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=rn(t,["challenge","allowCredentials"]),n=$r(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:$r(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return i}function Vc(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:ur(new Uint8Array(t.response.attestationObject)),clientDataJSON:ur(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Gc(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:ur(new Uint8Array(n.authenticatorData)),clientDataJSON:ur(new Uint8Array(n.clientDataJSON)),signature:ur(new Uint8Array(n.signature)),userHandle:n.userHandle?ur(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Oa(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Fi(){var t,e;return!!(ze()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator==null?void 0:navigator.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Jc(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ys("Browser returned unexpected credential type",e)}:{data:null,error:new Ys("Empty credential response",e)}}catch(e){return{data:null,error:Mc({error:e,options:t})}}}async function Qc(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ys("Browser returned unexpected credential type",e)}:{data:null,error:new Ys("Empty credential response",e)}}catch(e){return{data:null,error:Wc({error:e,options:t})}}}const Yc={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Xc={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Xs(...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]=Xs(o,a):s[i]=Xs(a)}else s[i]=a}return s}function Zc(t,e){return Xs(Yc,t,e||{})}function eu(t,e){return Xs(Xc,t,e||{})}class tu{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:c}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!o)return{data:null,error:c};const u=n??Hc.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 f=(await this.client.getUser()).data.user,y=((a=f==null?void 0:f.user_metadata)===null||a===void 0?void 0:a.name)||(f==null?void 0:f.email)||(f==null?void 0:f.id)||"User";d.name=`${d.id}:${y}`}}d.displayName||(d.displayName=d.name)}switch(o.webauthn.type){case"create":{const d=Zc(o.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:h,error:g}=await Jc({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:g}}case"request":{const d=eu(o.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:h,error:g}=await Qc(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:g}}}}catch(o){return Q(o)?{data:null,error:o}:{data:null,error:new cr("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 ys("rpId is required for WebAuthn authentication")};try{if(!Fi())return{data:null,error:new cr("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:c}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:c.type,rpId:r,rpOrigins:s,credential_response:c.credential_response}})}catch(a){return Q(a)?{data:null,error:a}:{data:null,error:new cr("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 ys("rpId is required for WebAuthn registration")};try{if(!Fi())return{data:null,error:new cr("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(g=>g.factor_type==="webauthn"&&g.friendly_name===e&&g.status!=="unverified")}).then(d=>d?this.client.mfa.unenroll({factorId:d==null?void 0:d.id}):void 0),{data:null,error:o};const{data:c,error:u}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:i});return c?this._verify({factorId:a.id,challengeId:c.challengeId,webauthn:{rpId:r,rpOrigins:s,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(a){return Q(a)?{data:null,error:a}:{data:null,error:new cr("Unexpected error in register",a)}}}}Lc();const ru={url:Zl,storageKey:ec,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:tc,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function Li(t,e,r){return await r()}const Pr={};class vs{get jwks(){var e,r;return(r=(e=Pr[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Pr[this.storageKey]=Object.assign(Object.assign({},Pr[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Pr[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Pr[this.storageKey]=Object.assign(Object.assign({},Pr[this.storageKey]),{cachedAt:e})}constructor(e){var r,s,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},ru),e);if(this.storageKey=i.storageKey,this.instanceID=(r=vs.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,vs.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&ze()){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.admin=new Bc({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Ra(i.fetch),this.lock=i.lock||Li,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&ze()&&(!((s=globalThis==null?void 0:globalThis.navigator)===null||s===void 0)&&s.locks)?this.lock=Fc:this.lock=Li,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 tu(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:Ta()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Ii(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Ii(this.memoryStorage)),ze()&&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);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} (${Sa}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},s="none";if(ze()&&(r=gc(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),ze()&&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),ac(i)){const c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="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 Q(r)?this._returnResult({error:r}):this._returnResult({error:new cr("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const i=await ee(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.captchaToken}},xform:mt}),{data:a,error:o}=i;if(o||!a)return this._returnResult({data:{user:null,session:null},error:o});const c=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(Q(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,s,n;try{let i;if("email"in e){const{email:d,password:h,options:g}=e;let f=null,y=null;this.flowType==="pkce"&&([f,y]=await Cr(this.storage,this.storageKey)),i=await ee(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:g==null?void 0:g.emailRedirectTo,body:{email:d,password:h,data:(r=g==null?void 0:g.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken},code_challenge:f,code_challenge_method:y},xform:mt})}else if("phone"in e){const{phone:d,password:h,options:g}=e;i=await ee(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:h,data:(s=g==null?void 0:g.data)!==null&&s!==void 0?s:{},channel:(n=g==null?void 0:g.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken}},xform:mt})}else throw new qs("You must provide either an email or phone number and a password");const{data:a,error:o}=i;if(o||!a)return await He(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});const c=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(await He(this.storage,`${this.storageKey}-code-verifier`),Q(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let r;if("email"in e){const{email:i,password:a,options:o}=e;r=await ee(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Pi})}else if("phone"in e){const{phone:i,password:a,options:o}=e;r=await ee(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Pi})}else throw new qs("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 Ar;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(Q(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){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,s,n,i,a,o,c,u,d,h,g;let f,y;if("message"in e)f=e.message,y=e.signature;else{const{chain:b,wallet:_,statement:v,options:S}=e;let j;if(ze())if(typeof _=="object")j=_;else{const O=window;if("ethereum"in O&&typeof O.ethereum=="object"&&"request"in O.ethereum&&typeof O.ethereum.request=="function")j=O.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"||!(S!=null&&S.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");j=_}const x=new URL((r=S==null?void 0:S.url)!==null&&r!==void 0?r:window.location.href),A=await j.request({method:"eth_requestAccounts"}).then(O=>O).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!A||A.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const k=Ca(A[0]);let F=(s=S==null?void 0:S.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!F){const O=await j.request({method:"eth_chainId"});F=$c(O)}const E={domain:x.host,address:k,statement:v,uri:x.href,version:"1",chainId:F,nonce:(n=S==null?void 0:S.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(a=(i=S==null?void 0:S.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(o=S==null?void 0:S.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(c=S==null?void 0:S.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=S==null?void 0:S.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(d=S==null?void 0:S.signInWithEthereum)===null||d===void 0?void 0:d.resources};f=Uc(E),y=await j.request({method:"personal_sign",params:[Dc(f),k]})}try{const{data:b,error:_}=await ee(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:y},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:mt});if(_)throw _;if(!b||!b.session||!b.user){const v=new Ar;return this._returnResult({data:{user:null,session:null},error:v})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:_})}catch(b){if(Q(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async signInWithSolana(e){var r,s,n,i,a,o,c,u,d,h,g,f;let y,b;if("message"in e)y=e.message,b=e.signature;else{const{chain:_,wallet:v,statement:S,options:j}=e;let x;if(ze())if(typeof v=="object")x=v;else{const k=window;if("solana"in k&&typeof k.solana=="object"&&("signIn"in k.solana&&typeof k.solana.signIn=="function"||"signMessage"in k.solana&&typeof k.solana.signMessage=="function"))x=k.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"||!(j!=null&&j.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");x=v}const A=new URL((r=j==null?void 0:j.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in x&&x.signIn){const k=await x.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},j==null?void 0:j.signInWithSolana),{version:"1",domain:A.host,uri:A.href}),S?{statement:S}:null));let F;if(Array.isArray(k)&&k[0]&&typeof k[0]=="object")F=k[0];else if(k&&typeof k=="object"&&"signedMessage"in k&&"signature"in k)F=k;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in F&&"signature"in F&&(typeof F.signedMessage=="string"||F.signedMessage instanceof Uint8Array)&&F.signature instanceof Uint8Array)y=typeof F.signedMessage=="string"?F.signedMessage:new TextDecoder().decode(F.signedMessage),b=F.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in x)||typeof x.signMessage!="function"||!("publicKey"in x)||typeof x!="object"||!x.publicKey||!("toBase58"in x.publicKey)||typeof x.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");y=[`${A.host} wants you to sign in with your Solana account:`,x.publicKey.toBase58(),...S?["",S,""]:[""],"Version: 1",`URI: ${A.href}`,`Issued At: ${(n=(s=j==null?void 0:j.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=j==null?void 0:j.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${j.signInWithSolana.notBefore}`]:[],...!((a=j==null?void 0:j.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${j.signInWithSolana.expirationTime}`]:[],...!((o=j==null?void 0:j.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${j.signInWithSolana.chainId}`]:[],...!((c=j==null?void 0:j.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${j.signInWithSolana.nonce}`]:[],...!((u=j==null?void 0:j.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${j.signInWithSolana.requestId}`]:[],...!((h=(d=j==null?void 0:j.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||h===void 0)&&h.length?["Resources",...j.signInWithSolana.resources.map(F=>`- ${F}`)]:[]].join(`
73
+ `);const k=await x.signMessage(new TextEncoder().encode(y),"utf8");if(!k||!(k instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");b=k}}try{const{data:_,error:v}=await ee(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:y,signature:ur(b)},!((g=e.options)===null||g===void 0)&&g.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:mt});if(v)throw v;if(!_||!_.session||!_.user){const S=new Ar;return this._returnResult({data:{user:null,session:null},error:S})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:v})}catch(_){if(Q(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){const r=await or(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new oc;const{data:i,error:a}=await ee(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:mt});if(await He(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!i||!i.session||!i.user){const o=new Ar;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:a})}catch(i){if(await He(this.storage,`${this.storageKey}-code-verifier`),Q(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:i,nonce:a}=e,o=await ee(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==null?void 0:r.captchaToken}},xform:mt}),{data:c,error:u}=o;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){const d=new Ar;return this._returnResult({data:{user:null,session:null},error:d})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(r){if(Q(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,a;try{if("email"in e){const{email:o,options:c}=e;let u=null,d=null;this.flowType==="pkce"&&([u,d]=await Cr(this.storage,this.storageKey));const{error:h}=await ee(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(r=c==null?void 0:c.data)!==null&&r!==void 0?r:{},create_user:(s=c==null?void 0:c.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:u,code_challenge_method:d},redirectTo:c==null?void 0:c.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in e){const{phone:o,options:c}=e,{data:u,error:d}=await ee(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(n=c==null?void 0:c.data)!==null&&n!==void 0?n:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(a=c==null?void 0:c.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:d})}throw new qs("You must provide either an email or phone number.")}catch(o){if(await He(this.storage,`${this.storageKey}-code-verifier`),Q(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}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 ee(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:mt});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");const c=a.session,u=a.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(n){if(Q(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i,a;try{let o=null,c=null;this.flowType==="pkce"&&([o,c]=await Cr(this.storage,this.storageKey));const u=await ee(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e==null?void 0:e.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:c}),headers:this.headers,xform:Pc});return!((i=u.data)===null||i===void 0)&&i.url&&ze()&&!(!((a=e.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(o){if(await He(this.storage,`${this.storageKey}-code-verifier`),Q(o))return this._returnResult({data:null,error:o});throw o}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new ot;const{error:n}=await ee(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(Q(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:s,type:n,options:i}=e,{error:a}=await ee(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if("phone"in e){const{phone:s,type:n,options:i}=e,{data:a,error:o}=await ee(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:o})}throw new qs("You must provide either an email or phone number and a type")}catch(r){if(Q(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await or(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()<fn:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await or(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=bn()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=Rc(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);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await ee(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Vt}):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 ot}:await ee(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:Vt})})}catch(r){if(Q(r))return pn(r)&&(await this._removeSession(),await He(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async s=>{const{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new ot;const a=n.session;let o=null,c=null;this.flowType==="pkce"&&e.email!=null&&([o,c]=await Cr(this.storage,this.storageKey));const{data:u,error:d}=await ee(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:c}),jwt:a.access_token,xform:Vt});if(d)throw d;return a.user=u.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(s){if(await He(this.storage,`${this.storageKey}-code-verifier`),Q(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ot;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:a}=zs(e.access_token);if(a.exp&&(s=a.exp,n=s<=r),n){const{data:o,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!o)return{data:{user:null,session:null},error:null};i=o}else{const{data:o,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});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(Q(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){const{data:a,error:o}=r;if(o)throw o;e=(s=a.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new ot;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(Q(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!ze())throw new Hs("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Hs(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 Ei("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Hs("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 Ei("No code detected.");const{data:S,error:j}=await this._exchangeCodeForSession(e.code);if(j)throw j;const x=new URL(window.location.href);return x.searchParams.delete("code"),window.history.replaceState(window.history.state,"",x.toString()),{data:{session:S.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:n,access_token:i,refresh_token:a,expires_in:o,expires_at:c,token_type:u}=e;if(!i||!o||!a||!u)throw new Hs("No session defined in URL");const d=Math.round(Date.now()/1e3),h=parseInt(o);let g=d+h;c&&(g=parseInt(c));const f=g-d;f*1e3<=Fr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${h}s`);const y=g-h;d-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,g,d):d-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",y,g,d);const{data:b,error:_}=await this._getUser(i);if(_)throw _;const v={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:h,expires_at:g,refresh_token:a,token_type:u,user:b.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:v,redirectType:e.type},error:null})}catch(s){if(Q(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await or(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i&&!pn(i))return this._returnResult({error:i});const a=(s=n.session)===null||s===void 0?void 0:s.access_token;if(a){const{error:o}=await this.admin.signOut(a,e);if(o&&!(ic(o)&&(o.status===404||o.status===401||o.status===403)||pn(o)))return this._returnResult({error:o})}return e!=="others"&&(await this._removeSession(),await He(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=pc(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{const{data:{session: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),console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await Cr(this.storage,this.storageKey,!0));try{return await ee(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await He(this.storage,`${this.storageKey}-code-verifier`),Q(i))return this._returnResult({data:null,error:i});throw i}}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(Q(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:s,error:n}=await this._useSession(async i=>{var a,o,c,u,d;const{data:h,error:g}=i;if(g)throw g;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await ee(this.fetch,"GET",f,{headers:this.headers,jwt:(d=(u=h.session)===null||u===void 0?void 0:u.access_token)!==null&&d!==void 0?d:void 0})});if(n)throw n;return ze()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),this._returnResult({data:{provider:e.provider,url:s==null?void 0:s.url},error:null})}catch(s){if(Q(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{const{error:n,data:{session:i}}=r;if(n)throw n;const{options:a,provider:o,token:c,access_token:u,nonce:d}=e,h=await ee(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i==null?void 0:i.access_token)!==null&&s!==void 0?s:void 0,body:{provider:o,id_token:c,access_token:u,nonce:d,link_identity:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:mt}),{data:g,error:f}=h;return f?this._returnResult({data:{user:null,session:null},error:f}):!g||!g.session||!g.user?this._returnResult({data:{user:null,session:null},error:new Ar}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:f}))}catch(n){if(await He(this.storage,`${this.storageKey}-code-verifier`),Q(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 ee(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(Q(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const s=Date.now();return await yc(async n=>(n>0&&await mc(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await ee(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:mt})),(n,i)=>{const a=200*Math.pow(2,n);return i&&gn(i)&&Date.now()+a-s<Fr})}catch(s){if(this._debug(r,"error",s),Q(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),ze()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await or(this.storage,this.storageKey);if(n&&this.userStorage){let a=await or(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:n.user},await Lr(this.userStorage,this.storageKey+"-user",a)),n.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:bn()}else if(n&&!n.user&&!n.user){const a=await or(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(n.user=a.user,await He(this.storage,this.storageKey+"-user"),await Lr(this.storage,this.storageKey,n)):n.user=bn()}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()<fn;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${fn}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:a}=await this._callRefreshToken(n.refresh_token);a&&(console.error(a),gn(a)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:o}=await this._getUser(n.access_token);!o&&(a!=null&&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),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new ot;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new an;const{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new ot;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const o={data:i.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(i){if(this._debug(n,"error",i),Q(i)){const a={data:null,error:i};return gn(i)||await this._removeSession(),(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){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(c){i.push(c)}});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,await He(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await Lr(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=Ci(n);await Lr(this.storage,this.storageKey,i)}else{const n=Ci(r);await Lr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await He(this.storage,this.storageKey),await He(this.storage,this.storageKey+"-code-verifier"),await He(this.storage,this.storageKey+"-user"),this.userStorage&&await He(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&ze()&&(window!=null&&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(),Fr);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/Fr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Fr}ms, refresh threshold is ${Cn} ticks`),n<=Cn&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Aa)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!ze()||!(window!=null&&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==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){const n=[`provider=${encodeURIComponent(r)}`];if(s!=null&&s.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s!=null&&s.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[i,a]=await Cr(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});n.push(o.toString())}if(s!=null&&s.queryParams){const i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s!=null&&s.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await ee(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(Q(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:c,error:u}=await ee(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((n=c==null?void 0:c.totp)===null||n===void 0)&&n.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(r){if(Q(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Vc(e.webauthn.credential_response):Gc(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:c}=await ee(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:c}))})}catch(r){if(Q(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const a=await ee(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});if(a.error)return a;const{data:o}=a;if(o.type!=="webauthn")return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:zc(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Kc(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(Q(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=r==null?void 0: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:f}=zs(e);let y=null;f.aal&&(y=f.aal);let b=y;const{data:{user:_},error:v}=await this.getUser(e);if(v)return this._returnResult({data:null,error:v});((s=(r=_==null?void 0:_.factors)===null||r===void 0?void 0:r.filter(x=>x.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(b="aal2");const j=f.amr||[];return{data:{currentLevel:y,nextLevel:b,currentAuthenticationMethods:j},error:null}}catch(f){if(Q(f))return this._returnResult({data:null,error:f});throw f}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:c}=zs(a.access_token);let u=null;c.aal&&(u=c.aal);let d=u;((i=(n=a.user.factors)===null||n===void 0?void 0:n.filter(f=>f.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(d="aal2");const g=c.amr||[];return{data:{currentLevel:u,nextLevel:d,currentAuthenticationMethods:g},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 ee(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 ot})})}catch(r){if(Q(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 ot});const a=await ee(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&&ze()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(Q(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 ot});const a=await ee(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&&ze()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(Q(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 ee(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 ot})})}catch(e){if(Q(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 ee(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 ot})})}catch(r){if(Q(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+sc>n)return s;const{data:i,error:a}=await ee(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:f,error:y}=await this.getSession();if(y||!f.session)return this._returnResult({data:null,error:y});s=f.session.access_token}const{header:n,payload:i,signature:a,raw:{header:o,payload:c}}=zs(s);r!=null&&r.allowExpired||Ec(i.exp);const u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!u){const{error:f}=await this.getUser(s);if(f)throw f;return{data:{claims:i,header:n,signature:a},error:null}}const d=jc(n.alg),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,a,hc(`${o}.${c}`)))throw new Nn("Invalid JWT signature");return{data:{claims:i,header:n,signature:a},error:null}}catch(s){if(Q(s))return this._returnResult({data:null,error:s});throw s}}}vs.nextInstanceID={};const su=vs,nu="2.100.0";let as="";typeof Deno<"u"?as="deno":typeof document<"u"?as="web":typeof navigator<"u"&&navigator.product==="ReactNative"?as="react-native":as="node";const iu={"X-Client-Info":`supabase-js-${as}/${nu}`},au={headers:iu},ou={schema:"public"},lu={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},cu={};function ws(t){"@babel/helpers - typeof";return ws=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},ws(t)}function uu(t,e){if(ws(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(ws(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function du(t){var e=uu(t,"string");return ws(e)=="symbol"?e:e+""}function hu(t,e,r){return(e=du(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function $i(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 Be(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?$i(Object(r),!0).forEach(function(s){hu(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):$i(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const fu=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),pu=()=>Headers,gu=(t,e,r)=>{const s=fu(r),n=pu();return async(i,a)=>{var o;const c=(o=await e())!==null&&o!==void 0?o:t;let u=new n(a==null?void 0:a.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),s(i,Be(Be({},a),{},{headers:u}))}};function bu(t){return t.endsWith("/")?t:t+"/"}function mu(t,e){var r,s;const{db:n,auth:i,realtime:a,global:o}=t,{db:c,auth:u,realtime:d,global:h}=e,g={db:Be(Be({},c),n),auth:Be(Be({},u),i),realtime:Be(Be({},d),a),storage:{},global:Be(Be(Be({},h),o),{},{headers:Be(Be({},(r=h==null?void 0:h.headers)!==null&&r!==void 0?r:{}),(s=o==null?void 0:o.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return t.accessToken?g.accessToken=t.accessToken:delete g.accessToken,g}function yu(t){const e=t==null?void 0: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(bu(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var vu=class extends su{constructor(t){super(t)}},wu=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=yu(t);if(!e)throw new Error("supabaseKey is required.");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:ou,realtime:cu,auth:Be(Be({},lu),{},{storageKey:a}),global:au},c=mu(r??{},o);if(this.storageKey=(s=c.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},c.accessToken)this.accessToken=c.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=c.auth)!==null&&u!==void 0?u:{},this.headers,c.global.fetch)}this.fetch=gu(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Be({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.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 Wo(new URL("rest/v1",i).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit}),this.storage=new Xl(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new Io(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:a,lock:o,debug:c,throwOnError:u},d,h){const g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new vu({url:this.authUrl.href,headers:Be(Be({},g),d),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:o,debug:c,throwOnError:u,fetch:h,hasCustomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new _l(this.realtimeUrl.href,Be(Be({},t),{},{params:Be(Be({},{apikey:this.supabaseKey}),t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const In=(t,e,r)=>new wu(t,e,r);function xu(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}xu()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");var Os=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},hr,Gt,Dr,ia,_u=(ia=class extends Os{constructor(){super();se(this,hr);se(this,Gt);se(this,Dr);z(this,Dr,e=>{if(typeof window<"u"&&window.addEventListener){const r=()=>e();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){w(this,Gt)||this.setEventListener(w(this,Dr))}onUnsubscribe(){var e;this.hasListeners()||((e=w(this,Gt))==null||e.call(this),z(this,Gt,void 0))}setEventListener(e){var r;z(this,Dr,e),(r=w(this,Gt))==null||r.call(this),z(this,Gt,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){w(this,hr)!==e&&(z(this,hr,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(r=>{r(e)})}isFocused(){var e;return typeof w(this,hr)=="boolean"?w(this,hr):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},hr=new WeakMap,Gt=new WeakMap,Dr=new WeakMap,ia),Zn=new _u,ku={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},kt,fr,aa,Su=(aa=class{constructor(){se(this,kt,ku);se(this,fr,!1)}setTimeoutProvider(t){process.env.NODE_ENV!=="production"&&w(this,fr)&&t!==w(this,kt)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:w(this,kt),provider:t}),z(this,kt,t),process.env.NODE_ENV!=="production"&&z(this,fr,!1)}setTimeout(t,e){return process.env.NODE_ENV!=="production"&&z(this,fr,!0),w(this,kt).setTimeout(t,e)}clearTimeout(t){w(this,kt).clearTimeout(t)}setInterval(t,e){return process.env.NODE_ENV!=="production"&&z(this,fr,!0),w(this,kt).setInterval(t,e)}clearInterval(t){w(this,kt).clearInterval(t)}},kt=new WeakMap,fr=new WeakMap,aa),dr=new Su;function Eu(t){setTimeout(t,0)}var ju=typeof window>"u"||"Deno"in globalThis;function st(){}function Tu(t,e){return typeof t=="function"?t(e):t}function Bn(t){return typeof t=="number"&&t>=0&&t!==1/0}function Pa(t,e){return Math.max(t+(e||0)-Date.now(),0)}function tr(t,e){return typeof t=="function"?t(e):t}function ft(t,e){return typeof t=="function"?t(e):t}function Di(t,e){const{type:r="all",exact:s,fetchStatus:n,predicate:i,queryKey:a,stale:o}=t;if(a){if(s){if(e.queryHash!==ei(a,e.options))return!1}else if(!_s(e.queryKey,a))return!1}if(r!=="all"){const c=e.isActive();if(r==="active"&&!c||r==="inactive"&&c)return!1}return!(typeof o=="boolean"&&e.isStale()!==o||n&&n!==e.state.fetchStatus||i&&!i(e))}function Ui(t,e){const{exact:r,status:s,predicate:n,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(r){if(xs(e.options.mutationKey)!==xs(i))return!1}else if(!_s(e.options.mutationKey,i))return!1}return!(s&&e.state.status!==s||n&&!n(e))}function ei(t,e){return((e==null?void 0:e.queryKeyHashFn)||xs)(t)}function xs(t){return JSON.stringify(t,(e,r)=>$n(r)?Object.keys(r).sort().reduce((s,n)=>(s[n]=r[n],s),{}):r)}function _s(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(r=>_s(t[r],e[r])):!1}var Ru=Object.prototype.hasOwnProperty;function Fn(t,e,r=0){if(t===e)return t;if(r>500)return e;const s=Mi(t)&&Mi(e);if(!s&&!($n(t)&&$n(e)))return e;const i=(s?t:Object.keys(t)).length,a=s?e:Object.keys(e),o=a.length,c=s?new Array(o):{};let u=0;for(let d=0;d<o;d++){const h=s?d:a[d],g=t[h],f=e[h];if(g===f){c[h]=g,(s?d<i:Ru.call(t,h))&&u++;continue}if(g===null||f===null||typeof g!="object"||typeof f!="object"){c[h]=f;continue}const y=Fn(g,f,r+1);c[h]=y,y===g&&u++}return i===o&&u===i?t:c}function Ln(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(const r in t)if(t[r]!==e[r])return!1;return!0}function Mi(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function $n(t){if(!Wi(t))return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(!Wi(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function Wi(t){return Object.prototype.toString.call(t)==="[object Object]"}function Au(t){return new Promise(e=>{dr.setTimeout(e,t)})}function Dn(t,e,r){if(typeof r.structuralSharing=="function")return r.structuralSharing(t,e);if(r.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return Fn(t,e)}catch(s){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${r.queryHash}]: ${s}`),s}return Fn(t,e)}return e}function Cu(t,e,r=0){const s=[...t,e];return r&&s.length>r?s.slice(1):s}function Ou(t,e,r=0){const s=[e,...t];return r&&s.length>r?s.slice(0,-1):s}var Zs=Symbol();function Na(t,e){return process.env.NODE_ENV!=="production"&&t.queryFn===Zs&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${t.queryHash}'`),!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===Zs?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function Ia(t,e){return typeof t=="function"?t(...e):!!t}function Pu(t,e,r){let s=!1,n;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(n??(n=e()),s||(s=!0,n.aborted?r():n.addEventListener("abort",r,{once:!0})),n)}),t}var ks=(()=>{let t=()=>ju;return{isServer(){return t()},setIsServer(e){t=e}}})();function Un(){let t,e;const r=new Promise((n,i)=>{t=n,e=i});r.status="pending",r.catch(()=>{});function s(n){Object.assign(r,n),delete r.resolve,delete r.reject}return r.resolve=n=>{s({status:"fulfilled",value:n}),t(n)},r.reject=n=>{s({status:"rejected",reason:n}),e(n)},r}var Nu=Eu;function Iu(){let t=[],e=0,r=o=>{o()},s=o=>{o()},n=Nu;const i=o=>{e?t.push(o):n(()=>{r(o)})},a=()=>{const o=t;t=[],o.length&&n(()=>{s(()=>{o.forEach(c=>{r(c)})})})};return{batch:o=>{let c;e++;try{c=o()}finally{e--,e||a()}return c},batchCalls:o=>(...c)=>{i(()=>{o(...c)})},schedule:i,setNotifyFunction:o=>{r=o},setBatchNotifyFunction:o=>{s=o},setScheduler:o=>{n=o}}}var Ke=Iu(),Ur,Jt,Mr,oa,Bu=(oa=class extends Os{constructor(){super();se(this,Ur,!0);se(this,Jt);se(this,Mr);z(this,Mr,e=>{if(typeof window<"u"&&window.addEventListener){const r=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",s)}}})}onSubscribe(){w(this,Jt)||this.setEventListener(w(this,Mr))}onUnsubscribe(){var e;this.hasListeners()||((e=w(this,Jt))==null||e.call(this),z(this,Jt,void 0))}setEventListener(e){var r;z(this,Mr,e),(r=w(this,Jt))==null||r.call(this),z(this,Jt,e(this.setOnline.bind(this)))}setOnline(e){w(this,Ur)!==e&&(z(this,Ur,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return w(this,Ur)}},Ur=new WeakMap,Jt=new WeakMap,Mr=new WeakMap,oa),en=new Bu;function Fu(t){return Math.min(1e3*2**t,3e4)}function Ba(t){return(t??"online")==="online"?en.isOnline():!0}var Mn=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function Fa(t){let e=!1,r=0,s;const n=Un(),i=()=>n.status!=="pending",a=b=>{var _;if(!i()){const v=new Mn(b);g(v),(_=t.onCancel)==null||_.call(t,v)}},o=()=>{e=!0},c=()=>{e=!1},u=()=>Zn.isFocused()&&(t.networkMode==="always"||en.isOnline())&&t.canRun(),d=()=>Ba(t.networkMode)&&t.canRun(),h=b=>{i()||(s==null||s(),n.resolve(b))},g=b=>{i()||(s==null||s(),n.reject(b))},f=()=>new Promise(b=>{var _;s=v=>{(i()||u())&&b(v)},(_=t.onPause)==null||_.call(t)}).then(()=>{var b;s=void 0,i()||(b=t.onContinue)==null||b.call(t)}),y=()=>{if(i())return;let b;const _=r===0?t.initialPromise:void 0;try{b=_??t.fn()}catch(v){b=Promise.reject(v)}Promise.resolve(b).then(h).catch(v=>{var k;if(i())return;const S=t.retry??(ks.isServer()?0:3),j=t.retryDelay??Fu,x=typeof j=="function"?j(r,v):j,A=S===!0||typeof S=="number"&&r<S||typeof S=="function"&&S(r,v);if(e||!A){g(v);return}r++,(k=t.onFail)==null||k.call(t,r,v),Au(x).then(()=>u()?void 0:f()).then(()=>{e?g(v):y()})})};return{promise:n,status:()=>n.status,cancel:a,continue:()=>(s==null||s(),n),cancelRetry:o,continueRetry:c,canStart:d,start:()=>(d()?y():f().then(y),n)}}var pr,la,La=(la=class{constructor(){se(this,pr)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Bn(this.gcTime)&&z(this,pr,dr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(ks.isServer()?1/0:5*60*1e3))}clearGcTimeout(){w(this,pr)&&(dr.clearTimeout(w(this,pr)),z(this,pr,void 0))}},pr=new WeakMap,la),gr,Wr,ht,br,We,Es,mr,lt,$a,Ct,ca,Lu=(ca=class extends La{constructor(e){super();se(this,lt);se(this,gr);se(this,Wr);se(this,ht);se(this,br);se(this,We);se(this,Es);se(this,mr);z(this,mr,!1),z(this,Es,e.defaultOptions),this.setOptions(e.options),this.observers=[],z(this,br,e.client),z(this,ht,w(this,br).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,z(this,gr,Hi(this.options)),this.state=e.state??w(this,gr),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=w(this,We))==null?void 0:e.promise}setOptions(e){if(this.options={...w(this,Es),...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const r=Hi(this.options);r.data!==void 0&&(this.setState(qi(r.data,r.dataUpdatedAt)),z(this,gr,r))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&w(this,ht).remove(this)}setData(e,r){const s=Dn(this.state.data,e,this.options);return fe(this,lt,Ct).call(this,{data:s,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),s}setState(e,r){fe(this,lt,Ct).call(this,{type:"setState",state:e,setStateOptions:r})}cancel(e){var s,n;const r=(s=w(this,We))==null?void 0:s.promise;return(n=w(this,We))==null||n.cancel(e),r?r.then(st).catch(st):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return w(this,gr)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>ft(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Zs||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>tr(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!Pa(this.state.dataUpdatedAt,e)}onFocus(){var r;const e=this.observers.find(s=>s.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(r=w(this,We))==null||r.continue()}onOnline(){var r;const e=this.observers.find(s=>s.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(r=w(this,We))==null||r.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),w(this,ht).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(r=>r!==e),this.observers.length||(w(this,We)&&(w(this,mr)||fe(this,lt,$a).call(this)?w(this,We).cancel({revert:!0}):w(this,We).cancelRetry()),this.scheduleGc()),w(this,ht).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||fe(this,lt,Ct).call(this,{type:"invalidate"})}async fetch(e,r){var c,u,d,h,g,f,y,b,_,v,S,j;if(this.state.fetchStatus!=="idle"&&((c=w(this,We))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(w(this,We))return w(this,We).continueRetry(),w(this,We).promise}if(e&&this.setOptions(e),!this.options.queryFn){const x=this.observers.find(A=>A.options.queryFn);x&&this.setOptions(x.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const s=new AbortController,n=x=>{Object.defineProperty(x,"signal",{enumerable:!0,get:()=>(z(this,mr,!0),s.signal)})},i=()=>{const x=Na(this.options,r),k=(()=>{const F={client:w(this,br),queryKey:this.queryKey,meta:this.meta};return n(F),F})();return z(this,mr,!1),this.options.persister?this.options.persister(x,k,this):x(k)},o=(()=>{const x={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:w(this,br),state:this.state,fetchFn:i};return n(x),x})();(u=this.options.behavior)==null||u.onFetch(o,this),z(this,Wr,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((d=o.fetchOptions)==null?void 0:d.meta))&&fe(this,lt,Ct).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta}),z(this,We,Fa({initialPromise:r==null?void 0:r.initialPromise,fn:o.fetchFn,onCancel:x=>{x instanceof Mn&&x.revert&&this.setState({...w(this,Wr),fetchStatus:"idle"}),s.abort()},onFail:(x,A)=>{fe(this,lt,Ct).call(this,{type:"failed",failureCount:x,error:A})},onPause:()=>{fe(this,lt,Ct).call(this,{type:"pause"})},onContinue:()=>{fe(this,lt,Ct).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{const x=await w(this,We).start();if(x===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(x),(f=(g=w(this,ht).config).onSuccess)==null||f.call(g,x,this),(b=(y=w(this,ht).config).onSettled)==null||b.call(y,x,this.state.error,this),x}catch(x){if(x instanceof Mn){if(x.silent)return w(this,We).promise;if(x.revert){if(this.state.data===void 0)throw x;return this.state.data}}throw fe(this,lt,Ct).call(this,{type:"error",error:x}),(v=(_=w(this,ht).config).onError)==null||v.call(_,x,this),(j=(S=w(this,ht).config).onSettled)==null||j.call(S,this.state.data,x,this),x}finally{this.scheduleGc()}}},gr=new WeakMap,Wr=new WeakMap,ht=new WeakMap,br=new WeakMap,We=new WeakMap,Es=new WeakMap,mr=new WeakMap,lt=new WeakSet,$a=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ct=function(e){const r=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...Da(s.data,this.options),fetchMeta:e.meta??null};case"success":const n={...s,...qi(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return z(this,Wr,e.manual?n:void 0),n;case"error":const i=e.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=r(this.state),Ke.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),w(this,ht).notify({query:this,type:"updated",action:e})})},ca);function Da(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ba(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function qi(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Hi(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,r=e!==void 0,s=r?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:r?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var rt,pe,js,Ze,yr,qr,Nt,Qt,Ts,Hr,zr,vr,wr,Yt,Kr,xe,os,Wn,qn,Hn,zn,Kn,Vn,Gn,Ua,ua,$u=(ua=class extends Os{constructor(e,r){super();se(this,xe);se(this,rt);se(this,pe);se(this,js);se(this,Ze);se(this,yr);se(this,qr);se(this,Nt);se(this,Qt);se(this,Ts);se(this,Hr);se(this,zr);se(this,vr);se(this,wr);se(this,Yt);se(this,Kr,new Set);this.options=r,z(this,rt,e),z(this,Qt,null),z(this,Nt,Un()),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(w(this,pe).addObserver(this),zi(w(this,pe),this.options)?fe(this,xe,os).call(this):this.updateResult(),fe(this,xe,zn).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Jn(w(this,pe),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Jn(w(this,pe),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,fe(this,xe,Kn).call(this),fe(this,xe,Vn).call(this),w(this,pe).removeObserver(this)}setOptions(e){const r=this.options,s=w(this,pe);if(this.options=w(this,rt).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ft(this.options.enabled,w(this,pe))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");fe(this,xe,Gn).call(this),w(this,pe).setOptions(this.options),r._defaulted&&!Ln(this.options,r)&&w(this,rt).getQueryCache().notify({type:"observerOptionsUpdated",query:w(this,pe),observer:this});const n=this.hasListeners();n&&Ki(w(this,pe),s,this.options,r)&&fe(this,xe,os).call(this),this.updateResult(),n&&(w(this,pe)!==s||ft(this.options.enabled,w(this,pe))!==ft(r.enabled,w(this,pe))||tr(this.options.staleTime,w(this,pe))!==tr(r.staleTime,w(this,pe)))&&fe(this,xe,Wn).call(this);const i=fe(this,xe,qn).call(this);n&&(w(this,pe)!==s||ft(this.options.enabled,w(this,pe))!==ft(r.enabled,w(this,pe))||i!==w(this,Yt))&&fe(this,xe,Hn).call(this,i)}getOptimisticResult(e){const r=w(this,rt).getQueryCache().build(w(this,rt),e),s=this.createResult(r,e);return Uu(this,s)&&(z(this,Ze,s),z(this,qr,this.options),z(this,yr,w(this,pe).state)),s}getCurrentResult(){return w(this,Ze)}trackResult(e,r){return new Proxy(e,{get:(s,n)=>(this.trackProp(n),r==null||r(n),n==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&w(this,Nt).status==="pending"&&w(this,Nt).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,n))})}trackProp(e){w(this,Kr).add(e)}getCurrentQuery(){return w(this,pe)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const r=w(this,rt).defaultQueryOptions(e),s=w(this,rt).getQueryCache().build(w(this,rt),r);return s.fetch().then(()=>this.createResult(s,r))}fetch(e){return fe(this,xe,os).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),w(this,Ze)))}createResult(e,r){var O;const s=w(this,pe),n=this.options,i=w(this,Ze),a=w(this,yr),o=w(this,qr),u=e!==s?e.state:w(this,js),{state:d}=e;let h={...d},g=!1,f;if(r._optimisticResults){const T=this.hasListeners(),R=!T&&zi(e,r),N=T&&Ki(e,s,r,n);(R||N)&&(h={...h,...Da(d.data,e.options)}),r._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:y,errorUpdatedAt:b,status:_}=h;f=h.data;let v=!1;if(r.placeholderData!==void 0&&f===void 0&&_==="pending"){let T;i!=null&&i.isPlaceholderData&&r.placeholderData===(o==null?void 0:o.placeholderData)?(T=i.data,v=!0):T=typeof r.placeholderData=="function"?r.placeholderData((O=w(this,zr))==null?void 0:O.state.data,w(this,zr)):r.placeholderData,T!==void 0&&(_="success",f=Dn(i==null?void 0:i.data,T,r),g=!0)}if(r.select&&f!==void 0&&!v)if(i&&f===(a==null?void 0:a.data)&&r.select===w(this,Ts))f=w(this,Hr);else try{z(this,Ts,r.select),f=r.select(f),f=Dn(i==null?void 0:i.data,f,r),z(this,Hr,f),z(this,Qt,null)}catch(T){z(this,Qt,T)}w(this,Qt)&&(y=w(this,Qt),f=w(this,Hr),b=Date.now(),_="error");const S=h.fetchStatus==="fetching",j=_==="pending",x=_==="error",A=j&&S,k=f!==void 0,E={status:_,fetchStatus:h.fetchStatus,isPending:j,isSuccess:_==="success",isError:x,isInitialLoading:A,isLoading:A,data:f,dataUpdatedAt:h.dataUpdatedAt,error:y,errorUpdatedAt:b,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:S,isRefetching:S&&!j,isLoadingError:x&&!k,isPaused:h.fetchStatus==="paused",isPlaceholderData:g,isRefetchError:x&&k,isStale:ti(e,r),refetch:this.refetch,promise:w(this,Nt),isEnabled:ft(r.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const T=E.data!==void 0,R=E.status==="error"&&!T,N=K=>{R?K.reject(E.error):T&&K.resolve(E.data)},C=()=>{const K=z(this,Nt,E.promise=Un());N(K)},L=w(this,Nt);switch(L.status){case"pending":e.queryHash===s.queryHash&&N(L);break;case"fulfilled":(R||E.data!==L.value)&&C();break;case"rejected":(!R||E.error!==L.reason)&&C();break}}return E}updateResult(){const e=w(this,Ze),r=this.createResult(w(this,pe),this.options);if(z(this,yr,w(this,pe).state),z(this,qr,this.options),w(this,yr).data!==void 0&&z(this,zr,w(this,pe)),Ln(r,e))return;z(this,Ze,r);const s=()=>{if(!e)return!0;const{notifyOnChangeProps:n}=this.options,i=typeof n=="function"?n():n;if(i==="all"||!i&&!w(this,Kr).size)return!0;const a=new Set(i??w(this,Kr));return this.options.throwOnError&&a.add("error"),Object.keys(w(this,Ze)).some(o=>{const c=o;return w(this,Ze)[c]!==e[c]&&a.has(c)})};fe(this,xe,Ua).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&fe(this,xe,zn).call(this)}},rt=new WeakMap,pe=new WeakMap,js=new WeakMap,Ze=new WeakMap,yr=new WeakMap,qr=new WeakMap,Nt=new WeakMap,Qt=new WeakMap,Ts=new WeakMap,Hr=new WeakMap,zr=new WeakMap,vr=new WeakMap,wr=new WeakMap,Yt=new WeakMap,Kr=new WeakMap,xe=new WeakSet,os=function(e){fe(this,xe,Gn).call(this);let r=w(this,pe).fetch(this.options,e);return e!=null&&e.throwOnError||(r=r.catch(st)),r},Wn=function(){fe(this,xe,Kn).call(this);const e=tr(this.options.staleTime,w(this,pe));if(ks.isServer()||w(this,Ze).isStale||!Bn(e))return;const s=Pa(w(this,Ze).dataUpdatedAt,e)+1;z(this,vr,dr.setTimeout(()=>{w(this,Ze).isStale||this.updateResult()},s))},qn=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(w(this,pe)):this.options.refetchInterval)??!1},Hn=function(e){fe(this,xe,Vn).call(this),z(this,Yt,e),!(ks.isServer()||ft(this.options.enabled,w(this,pe))===!1||!Bn(w(this,Yt))||w(this,Yt)===0)&&z(this,wr,dr.setInterval(()=>{(this.options.refetchIntervalInBackground||Zn.isFocused())&&fe(this,xe,os).call(this)},w(this,Yt)))},zn=function(){fe(this,xe,Wn).call(this),fe(this,xe,Hn).call(this,fe(this,xe,qn).call(this))},Kn=function(){w(this,vr)&&(dr.clearTimeout(w(this,vr)),z(this,vr,void 0))},Vn=function(){w(this,wr)&&(dr.clearInterval(w(this,wr)),z(this,wr,void 0))},Gn=function(){const e=w(this,rt).getQueryCache().build(w(this,rt),this.options);if(e===w(this,pe))return;const r=w(this,pe);z(this,pe,e),z(this,js,e.state),this.hasListeners()&&(r==null||r.removeObserver(this),e.addObserver(this))},Ua=function(e){Ke.batch(()=>{e.listeners&&this.listeners.forEach(r=>{r(w(this,Ze))}),w(this,rt).getQueryCache().notify({query:w(this,pe),type:"observerResultsUpdated"})})},ua);function Du(t,e){return ft(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function zi(t,e){return Du(t,e)||t.state.data!==void 0&&Jn(t,e,e.refetchOnMount)}function Jn(t,e,r){if(ft(e.enabled,t)!==!1&&tr(e.staleTime,t)!=="static"){const s=typeof r=="function"?r(t):r;return s==="always"||s!==!1&&ti(t,e)}return!1}function Ki(t,e,r,s){return(t!==e||ft(s.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&ti(t,r)}function ti(t,e){return ft(e.enabled,t)!==!1&&t.isStaleByTime(tr(e.staleTime,t))}function Uu(t,e){return!Ln(t.getCurrentResult(),e)}function Vi(t){return{onFetch:(e,r)=>{var d,h,g,f,y;const s=e.options,n=(g=(h=(d=e.fetchOptions)==null?void 0:d.meta)==null?void 0:h.fetchMore)==null?void 0:g.direction,i=((f=e.state.data)==null?void 0:f.pages)||[],a=((y=e.state.data)==null?void 0:y.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const u=async()=>{let b=!1;const _=j=>{Pu(j,()=>e.signal,()=>b=!0)},v=Na(e.options,e.fetchOptions),S=async(j,x,A)=>{if(b)return Promise.reject();if(x==null&&j.pages.length)return Promise.resolve(j);const F=(()=>{const R={client:e.client,queryKey:e.queryKey,pageParam:x,direction:A?"backward":"forward",meta:e.options.meta};return _(R),R})(),E=await v(F),{maxPages:O}=e.options,T=A?Ou:Cu;return{pages:T(j.pages,E,O),pageParams:T(j.pageParams,x,O)}};if(n&&i.length){const j=n==="backward",x=j?Mu:Gi,A={pages:i,pageParams:a},k=x(s,A);o=await S(A,k,j)}else{const j=t??i.length;do{const x=c===0?a[0]??s.initialPageParam:Gi(s,o);if(c>0&&x==null)break;o=await S(o,x),c++}while(c<j)}return o};e.options.persister?e.fetchFn=()=>{var b,_;return(_=(b=e.options).persister)==null?void 0:_.call(b,u,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r)}:e.fetchFn=u}}}function Gi(t,{pages:e,pageParams:r}){const s=e.length-1;return e.length>0?t.getNextPageParam(e[s],e,r[s],r):void 0}function Mu(t,{pages:e,pageParams:r}){var s;return e.length>0?(s=t.getPreviousPageParam)==null?void 0:s.call(t,e[0],e,r[0],r):void 0}var Rs,St,Qe,xr,Et,zt,da,Wu=(da=class extends La{constructor(e){super();se(this,Et);se(this,Rs);se(this,St);se(this,Qe);se(this,xr);z(this,Rs,e.client),this.mutationId=e.mutationId,z(this,Qe,e.mutationCache),z(this,St,[]),this.state=e.state||qu(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){w(this,St).includes(e)||(w(this,St).push(e),this.clearGcTimeout(),w(this,Qe).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){z(this,St,w(this,St).filter(r=>r!==e)),this.scheduleGc(),w(this,Qe).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){w(this,St).length||(this.state.status==="pending"?this.scheduleGc():w(this,Qe).remove(this))}continue(){var e;return((e=w(this,xr))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var a,o,c,u,d,h,g,f,y,b,_,v,S,j,x,A,k,F;const r=()=>{fe(this,Et,zt).call(this,{type:"continue"})},s={client:w(this,Rs),meta:this.options.meta,mutationKey:this.options.mutationKey};z(this,xr,Fa({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(E,O)=>{fe(this,Et,zt).call(this,{type:"failed",failureCount:E,error:O})},onPause:()=>{fe(this,Et,zt).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>w(this,Qe).canRun(this)}));const n=this.state.status==="pending",i=!w(this,xr).canStart();try{if(n)r();else{fe(this,Et,zt).call(this,{type:"pending",variables:e,isPaused:i}),w(this,Qe).config.onMutate&&await w(this,Qe).config.onMutate(e,this,s);const O=await((o=(a=this.options).onMutate)==null?void 0:o.call(a,e,s));O!==this.state.context&&fe(this,Et,zt).call(this,{type:"pending",context:O,variables:e,isPaused:i})}const E=await w(this,xr).start();return await((u=(c=w(this,Qe).config).onSuccess)==null?void 0:u.call(c,E,e,this.state.context,this,s)),await((h=(d=this.options).onSuccess)==null?void 0:h.call(d,E,e,this.state.context,s)),await((f=(g=w(this,Qe).config).onSettled)==null?void 0:f.call(g,E,null,this.state.variables,this.state.context,this,s)),await((b=(y=this.options).onSettled)==null?void 0:b.call(y,E,null,e,this.state.context,s)),fe(this,Et,zt).call(this,{type:"success",data:E}),E}catch(E){try{await((v=(_=w(this,Qe).config).onError)==null?void 0:v.call(_,E,e,this.state.context,this,s))}catch(O){Promise.reject(O)}try{await((j=(S=this.options).onError)==null?void 0:j.call(S,E,e,this.state.context,s))}catch(O){Promise.reject(O)}try{await((A=(x=w(this,Qe).config).onSettled)==null?void 0:A.call(x,void 0,E,this.state.variables,this.state.context,this,s))}catch(O){Promise.reject(O)}try{await((F=(k=this.options).onSettled)==null?void 0:F.call(k,void 0,E,e,this.state.context,s))}catch(O){Promise.reject(O)}throw fe(this,Et,zt).call(this,{type:"error",error:E}),E}finally{w(this,Qe).runNext(this)}}},Rs=new WeakMap,St=new WeakMap,Qe=new WeakMap,xr=new WeakMap,Et=new WeakSet,zt=function(e){const r=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=r(this.state),Ke.batch(()=>{w(this,St).forEach(s=>{s.onMutationUpdate(e)}),w(this,Qe).notify({mutation:this,type:"updated",action:e})})},da);function qu(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var It,wt,As,ha,Hu=(ha=class extends Os{constructor(e={}){super();se(this,It);se(this,wt);se(this,As);this.config=e,z(this,It,new Set),z(this,wt,new Map),z(this,As,0)}build(e,r,s){const n=new Wu({client:e,mutationCache:this,mutationId:++$s(this,As)._,options:e.defaultMutationOptions(r),state:s});return this.add(n),n}add(e){w(this,It).add(e);const r=Ks(e);if(typeof r=="string"){const s=w(this,wt).get(r);s?s.push(e):w(this,wt).set(r,[e])}this.notify({type:"added",mutation:e})}remove(e){if(w(this,It).delete(e)){const r=Ks(e);if(typeof r=="string"){const s=w(this,wt).get(r);if(s)if(s.length>1){const n=s.indexOf(e);n!==-1&&s.splice(n,1)}else s[0]===e&&w(this,wt).delete(r)}}this.notify({type:"removed",mutation:e})}canRun(e){const r=Ks(e);if(typeof r=="string"){const s=w(this,wt).get(r),n=s==null?void 0:s.find(i=>i.state.status==="pending");return!n||n===e}else return!0}runNext(e){var s;const r=Ks(e);if(typeof r=="string"){const n=(s=w(this,wt).get(r))==null?void 0:s.find(i=>i!==e&&i.state.isPaused);return(n==null?void 0:n.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Ke.batch(()=>{w(this,It).forEach(e=>{this.notify({type:"removed",mutation:e})}),w(this,It).clear(),w(this,wt).clear()})}getAll(){return Array.from(w(this,It))}find(e){const r={exact:!0,...e};return this.getAll().find(s=>Ui(r,s))}findAll(e={}){return this.getAll().filter(r=>Ui(e,r))}notify(e){Ke.batch(()=>{this.listeners.forEach(r=>{r(e)})})}resumePausedMutations(){const e=this.getAll().filter(r=>r.state.isPaused);return Ke.batch(()=>Promise.all(e.map(r=>r.continue().catch(st))))}},It=new WeakMap,wt=new WeakMap,As=new WeakMap,ha);function Ks(t){var e;return(e=t.options.scope)==null?void 0:e.id}var jt,fa,zu=(fa=class extends Os{constructor(e={}){super();se(this,jt);this.config=e,z(this,jt,new Map)}build(e,r,s){const n=r.queryKey,i=r.queryHash??ei(n,r);let a=this.get(i);return a||(a=new Lu({client:e,queryKey:n,queryHash:i,options:e.defaultQueryOptions(r),state:s,defaultOptions:e.getQueryDefaults(n)}),this.add(a)),a}add(e){w(this,jt).has(e.queryHash)||(w(this,jt).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const r=w(this,jt).get(e.queryHash);r&&(e.destroy(),r===e&&w(this,jt).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Ke.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return w(this,jt).get(e)}getAll(){return[...w(this,jt).values()]}find(e){const r={exact:!0,...e};return this.getAll().find(s=>Di(r,s))}findAll(e={}){const r=this.getAll();return Object.keys(e).length>0?r.filter(s=>Di(e,s)):r}notify(e){Ke.batch(()=>{this.listeners.forEach(r=>{r(e)})})}onFocus(){Ke.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Ke.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},jt=new WeakMap,fa),Ie,Xt,Zt,Vr,Gr,er,Jr,Qr,pa,Ku=(pa=class{constructor(t={}){se(this,Ie);se(this,Xt);se(this,Zt);se(this,Vr);se(this,Gr);se(this,er);se(this,Jr);se(this,Qr);z(this,Ie,t.queryCache||new zu),z(this,Xt,t.mutationCache||new Hu),z(this,Zt,t.defaultOptions||{}),z(this,Vr,new Map),z(this,Gr,new Map),z(this,er,0)}mount(){$s(this,er)._++,w(this,er)===1&&(z(this,Jr,Zn.subscribe(async t=>{t&&(await this.resumePausedMutations(),w(this,Ie).onFocus())})),z(this,Qr,en.subscribe(async t=>{t&&(await this.resumePausedMutations(),w(this,Ie).onOnline())})))}unmount(){var t,e;$s(this,er)._--,w(this,er)===0&&((t=w(this,Jr))==null||t.call(this),z(this,Jr,void 0),(e=w(this,Qr))==null||e.call(this),z(this,Qr,void 0))}isFetching(t){return w(this,Ie).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return w(this,Xt).findAll({...t,status:"pending"}).length}getQueryData(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=w(this,Ie).get(e.queryHash))==null?void 0:r.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),r=w(this,Ie).build(this,e),s=r.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(tr(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return w(this,Ie).findAll(t).map(({queryKey:e,state:r})=>{const s=r.data;return[e,s]})}setQueryData(t,e,r){const s=this.defaultQueryOptions({queryKey:t}),n=w(this,Ie).get(s.queryHash),i=n==null?void 0:n.state.data,a=Tu(e,i);if(a!==void 0)return w(this,Ie).build(this,s).setData(a,{...r,manual:!0})}setQueriesData(t,e,r){return Ke.batch(()=>w(this,Ie).findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,r)]))}getQueryState(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=w(this,Ie).get(e.queryHash))==null?void 0:r.state}removeQueries(t){const e=w(this,Ie);Ke.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){const r=w(this,Ie);return Ke.batch(()=>(r.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const r={revert:!0,...e},s=Ke.batch(()=>w(this,Ie).findAll(t).map(n=>n.cancel(r)));return Promise.all(s).then(st).catch(st)}invalidateQueries(t,e={}){return Ke.batch(()=>(w(this,Ie).findAll(t).forEach(r=>{r.invalidate()}),(t==null?void 0:t.refetchType)==="none"?Promise.resolve():this.refetchQueries({...t,type:(t==null?void 0:t.refetchType)??(t==null?void 0:t.type)??"active"},e)))}refetchQueries(t,e={}){const r={...e,cancelRefetch:e.cancelRefetch??!0},s=Ke.batch(()=>w(this,Ie).findAll(t).filter(n=>!n.isDisabled()&&!n.isStatic()).map(n=>{let i=n.fetch(void 0,r);return r.throwOnError||(i=i.catch(st)),n.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(s).then(st)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=w(this,Ie).build(this,e);return r.isStaleByTime(tr(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(st).catch(st)}fetchInfiniteQuery(t){return t.behavior=Vi(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(st).catch(st)}ensureInfiniteQueryData(t){return t.behavior=Vi(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return en.isOnline()?w(this,Xt).resumePausedMutations():Promise.resolve()}getQueryCache(){return w(this,Ie)}getMutationCache(){return w(this,Xt)}getDefaultOptions(){return w(this,Zt)}setDefaultOptions(t){z(this,Zt,t)}setQueryDefaults(t,e){w(this,Vr).set(xs(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...w(this,Vr).values()],r={};return e.forEach(s=>{_s(t,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(t,e){w(this,Gr).set(xs(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...w(this,Gr).values()],r={};return e.forEach(s=>{_s(t,s.mutationKey)&&Object.assign(r,s.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;const e={...w(this,Zt).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=ei(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===Zs&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...w(this,Zt).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){w(this,Ie).clear(),w(this,Xt).clear()}},Ie=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,Vr=new WeakMap,Gr=new WeakMap,er=new WeakMap,Jr=new WeakMap,Qr=new WeakMap,pa),Ma=pt.createContext(void 0),Wa=t=>{const e=pt.useContext(Ma);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},Vu=({client:t,children:e})=>(pt.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),l.jsx(Ma.Provider,{value:t,children:e})),qa=pt.createContext(!1),Gu=()=>pt.useContext(qa);qa.Provider;function Ju(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var Qu=pt.createContext(Ju()),Yu=()=>pt.useContext(Qu),Xu=(t,e,r)=>{const s=r!=null&&r.state.error&&typeof t.throwOnError=="function"?Ia(t.throwOnError,[r.state.error,r]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},Zu=t=>{pt.useEffect(()=>{t.clearReset()},[t])},ed=({result:t,errorResetBoundary:e,throwOnError:r,query:s,suspense:n})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(n&&t.data===void 0||Ia(r,[t.error,s])),td=t=>{if(t.suspense){const r=n=>n==="static"?n:Math.max(n??1e3,1e3),s=t.staleTime;t.staleTime=typeof s=="function"?(...n)=>r(s(...n)):r(s),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},rd=(t,e)=>t.isLoading&&t.isFetching&&!e,sd=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,Ji=(t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()});function nd(t,e,r){var g,f,y,b;if(process.env.NODE_ENV!=="production"&&(typeof t!="object"||Array.isArray(t)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const s=Gu(),n=Yu(),i=Wa(),a=i.defaultQueryOptions(t);(f=(g=i.getDefaultOptions().queries)==null?void 0:g._experimental_beforeQuery)==null||f.call(g,a);const o=i.getQueryCache().get(a.queryHash);process.env.NODE_ENV!=="production"&&(a.queryFn||console.error(`[${a.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),a._optimisticResults=s?"isRestoring":"optimistic",td(a),Xu(a,n,o),Zu(n);const c=!i.getQueryCache().get(a.queryHash),[u]=pt.useState(()=>new e(i,a)),d=u.getOptimisticResult(a),h=!s&&t.subscribed!==!1;if(pt.useSyncExternalStore(pt.useCallback(_=>{const v=h?u.subscribe(Ke.batchCalls(_)):st;return u.updateResult(),v},[u,h]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),pt.useEffect(()=>{u.setOptions(a)},[a,u]),sd(a,d))throw Ji(a,u,n);if(ed({result:d,errorResetBoundary:n,throwOnError:a.throwOnError,query:o,suspense:a.suspense}))throw d.error;if((b=(y=i.getDefaultOptions().queries)==null?void 0:y._experimental_afterQuery)==null||b.call(y,a,d),a.experimental_prefetchInRender&&!ks.isServer()&&rd(d,s)){const _=c?Ji(a,u,n):o==null?void 0:o.promise;_==null||_.catch(st).finally(()=>{u.updateResult()})}return a.notifyOnChangeProps?d:u.trackResult(d)}function Ps(t,e){return nd(t,$u)}const id=5e3,ad=()=>`bob_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;function Ha({ga4Config:t,hostContext:e,callbacks:r,enabled:s=!0,bobSupabaseUrl:n,bobSupabaseKey:i}){const a=p.useRef(ad()),o=p.useRef(!1),c=p.useRef(null),u=p.useRef(!1),d=p.useCallback((E,O)=>{if(!(!(t!=null&&t.measurementId)||typeof window>"u")&&window.gtag){const T={...O,send_to:t.measurementId};t.debug&&console.log("[BobAnalytics] GA4 event:",E,T),window.gtag("event",E,T)}},[t]),h=p.useCallback((E,O={})=>{var R,N,C,L,K,H,Y,Z;if(!s)return;const T={event_name:E,timestamp:new Date().toISOString(),session_id:a.current,user_email:(R=e==null?void 0:e.user)==null?void 0:R.email,user_id:(N=e==null?void 0:e.user)==null?void 0:N.id,vehicle_id:(K=(L=(C=e==null?void 0:e.vehicle)==null?void 0:C.selectedVehicle)==null?void 0:L.vehicle_id)==null?void 0:K.toString(),rego:(Y=(H=e==null?void 0:e.vehicle)==null?void 0:H.selectedVehicle)==null?void 0:Y.rego,parameters:O};d(E,{session_id:T.session_id,user_email:T.user_email,vehicle_id:T.vehicle_id,...O}),(Z=r==null?void 0:r.onAnalyticsEvent)==null||Z.call(r,T),t!=null&&t.debug&&console.log("[BobAnalytics] Event tracked:",T)},[s,e,r,d,t==null?void 0:t.debug]),g=p.useCallback(()=>{var E,O,T;o.current||(o.current=!0,h("bob_session_start",{widget_version:Bt,has_vehicle:!!((E=e==null?void 0:e.vehicle)!=null&&E.selectedVehicle),has_user:!!((O=e==null?void 0:e.user)!=null&&O.id)||!!((T=e==null?void 0:e.user)!=null&&T.email)}))},[h,e]),f=p.useCallback((E,O)=>{h("bob_message_sent",{message_length:E,has_vehicle:O})},[h]),y=p.useCallback(E=>{h("bob_vehicle_identified",{vehicle_make:E.make||"unknown",vehicle_model:E.model||"unknown",vehicle_year:E.year||"unknown",rego:E.rego})},[h]),b=p.useCallback((E,O)=>{h("bob_parts_viewed",{part_count:E,vehicle_id:O})},[h]),_=p.useCallback(E=>{h("bob_product_clicked",{sku:E.sku,product_name:E.product_name,price:E.price,brand:E.brand})},[h]),v=p.useCallback(E=>{h("bob_product_viewed",{sku:E.sku,product_name:E.product_name,price:E.price,brand:E.brand})},[h]),S=p.useCallback(E=>{h("bob_add_to_cart",{sku:E.sku,product_name:E.product_name,price:E.price,brand:E.brand,quantity:E.quantity??1})},[h]),j=p.useCallback((E,O)=>{h("bob_checkout_started",{cart_value:E,item_count:O})},[h]),x=p.useCallback(E=>{const O=Math.ceil(E/5/150*60);h("bob_speech_played",{text_length:E,duration_estimate:O})},[h]),A=p.useCallback(E=>{h("bob_speech_failed",{text_length:E})},[h]),k=p.useCallback((E,O)=>{h("bob_error",{error_type:E,error_message:O})},[h]),F=p.useCallback(E=>{if(!s||!n||!i)return;const O=(E==null?void 0:E.led_to_cart)||(E==null?void 0:E.had_product_match),T=()=>{var N,C,L,K,H,Y;u.current=!1;const R={session_id:a.current,user_id:((N=e==null?void 0:e.user)==null?void 0:N.id)||null,channel:"web",vehicle_id:(E==null?void 0:E.vehicle_id)||((K=(L=(C=e==null?void 0:e.vehicle)==null?void 0:C.selectedVehicle)==null?void 0:L.vehicle_id)==null?void 0:K.toString())||null,rego:(E==null?void 0:E.rego)||((Y=(H=e==null?void 0:e.vehicle)==null?void 0:H.selectedVehicle)==null?void 0:Y.rego)||null,had_product_match:(E==null?void 0:E.had_product_match)||!1,led_to_cart:(E==null?void 0:E.led_to_cart)||!1};fetch(`${n}/functions/v1/bob-conversation-track`,{method:"POST",headers:{"Content-Type":"application/json",apikey:i},body:JSON.stringify(R)}).catch(Z=>{console.warn("[BobAnalytics] Conversation track failed:",Z)})};if(O){c.current&&(clearTimeout(c.current),c.current=null),T();return}u.current||(u.current=!0,c.current=setTimeout(T,id))},[s,n,i,e]);return p.useEffect(()=>{g()},[g]),p.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[]),{trackEvent:h,sessionId:a.current,trackSessionStart:g,trackMessageSent:f,trackVehicleIdentified:y,trackPartsViewed:b,trackProductClicked:_,trackProductViewed:v,trackAddToCart:S,trackCheckoutStarted:j,trackSpeechPlayed:x,trackSpeechFailed:A,trackError:k,trackConversationActivity:F}}const on=p.createContext(null);function ri({children:t,bobConfig:e,hostApiConfig:r,hostContext:s={},callbacks:n={},queryClient:i,ga4Config:a,analyticsEnabled:o=!0,bottomOffset:c=0,zIndexBase:u=50}){const d=p.useMemo(()=>new Ku({defaultOptions:{queries:{retry:1,staleTime:3e5}}}),[]),h=i||d,g=!!i;p.useEffect(()=>{console.log(`[BobWidget] v${Bt} initialized`),console.log(`[BobWidget] QueryClient: ${g?"external (shared)":"internal"}`),console.log(`[BobWidget] Analytics: ${o?"enabled":"disabled"}`),a!=null&&a.measurementId&&console.log(`[BobWidget] GA4: ${a.measurementId}`)},[g,o,a==null?void 0:a.measurementId]);const f=p.useMemo(()=>In(e.supabaseUrl,e.supabaseKey),[e.supabaseUrl,e.supabaseKey]),[y,b]=p.useState(s);p.useEffect(()=>{b(s)},[s]);const _=p.useCallback(S=>{b(j=>({...j,...S}))},[]),v=p.useMemo(()=>({bobSupabase:f,bobConfig:e,hostApiConfig:r,hostContext:y,callbacks:n,updateHostContext:_,ga4Config:a,analyticsEnabled:o,bottomOffset:c,zIndexBase:u}),[f,e,r,y,n,_,a,o,c,u]);return l.jsx(Vu,{client:h,children:l.jsx(on.Provider,{value:v,children:t})})}function Lt(){const t=p.useContext(on);if(!t)throw new Error("useBobContext must be used within a BobProvider");return t}function od(){const{bobSupabase:t}=Lt();return t}function _r(){const t=p.useContext(on);return(t==null?void 0:t.bobSupabase)||null}function ld(){const{hostContext:t}=Lt();return t}function cd(){const{hostApiConfig:t}=Lt();return t}function ud(){const{callbacks:t}=Lt();return t}function dd(){const{ga4Config:t,analyticsEnabled:e}=Lt();return{ga4Config:t,enabled:e}}function si(){const t=p.useContext(on);return t?{bottomOffset:t.bottomOffset,zIndexBase:t.zIndexBase}:{bottomOffset:0,zIndexBase:50}}let Vs=null;const Qi=typeof window<"u"?window.AudioContext||window.webkitAudioContext:null,za=()=>(!Vs&&Qi&&(Vs=new Qi,console.log("[BobWidget] AudioContext created, initial state:",Vs.state)),Vs),Ka=async()=>{const t=za();if(!t)return!1;if(t.state==="running")return!0;try{return await t.resume(),console.log("[BobWidget] AudioContext resumed →",t.state),t.state==="running"}catch(r){return console.warn("[BobWidget] AudioContext resume failed:",r),!1}},hd=async(t,e,r)=>{const s=za();s.state!=="running"&&await s.resume();const n=await s.decodeAudioData(t),i=s.createBufferSource();i.buffer=n,i.connect(s.destination);let a=!1;return i.onended=()=>{a||(a=!0,r==null||r())},i.start(0),e==null||e(),{source:i,stop:()=>{try{i.stop()}catch{}}}};let Yi=!1;const Va=t=>{if(!t||Yi)return()=>{};const e=async()=>{await Ka()&&(Yi=!0,t.removeEventListener("touchstart",e,!0),t.removeEventListener("pointerdown",e,!0),t.removeEventListener("click",e,!0))};return t.addEventListener("touchstart",e,{capture:!0,passive:!0}),t.addEventListener("pointerdown",e,{capture:!0}),t.addEventListener("click",e,{capture:!0}),()=>{t.removeEventListener("touchstart",e,!0),t.removeEventListener("pointerdown",e,!0),t.removeEventListener("click",e,!0)}},fd=15e3,pd={greeting_returning:/ah hey|you again|what you after this time/i,greeting_welcome:/g'?day|welcome.*carfix|bob.*here/i,ask_rego:/need your rego|rego.*get cracking|what('?s| is) your rego/i,vehicle_not_found:/couldn'?t find that|double.?check.*plate/i,no_parts_found:/nothing came up|no results|sorry.*search/i,checkout_ready:/ready to checkout|checkout.*ready|choice.*checkout/i,rego_searching:/let('?s| us) see what car|sweet.*searching|searching for/i},ss=new Map,gd=t=>t.replace(/\bya\b/gi,"you"),Ga=({onStart:t,onEnd:e,onFailed:r}={})=>{const{bobConfig:s,bobSupabase:n}=Lt(),[i,a]=p.useState(!1),o=p.useRef(null),c=p.useRef(null),u=p.useRef(!1),d=p.useRef([]),h=p.useRef(!1),g=p.useRef(!1),f=p.useRef(null),y=p.useRef(null),b=p.useRef(t),_=p.useRef(e),v=p.useRef(r);p.useEffect(()=>{b.current=t,_.current=e,v.current=r},[t,e,r]);const S=p.useCallback(()=>{c.current&&(clearTimeout(c.current),c.current=null)},[]),j=p.useCallback(()=>{var N;u.current||(u.current=!0,console.log("[BobWidget TTS] Fallback: triggering onStart without audio"),(N=b.current)==null||N.call(b))},[]),x=p.useCallback(async N=>{if(ss.has(N))return ss.get(N)||null;try{const{data:C,error:L}=await n.from("bob_audio_clips").select("audio_url").eq("clip_key",N).eq("is_active",!0).single();return L||!C?(ss.set(N,null),null):(ss.set(N,C),C)}catch(C){return console.warn(`[BobWidget TTS] Clip lookup failed for ${N}:`,C),ss.set(N,null),null}},[n]),A=p.useCallback(async N=>{for(const[C,L]of Object.entries(pd))if(L.test(N)){console.log(`[BobWidget TTS] Pattern matched: ${C}`);const K=await x(C);if(K!=null&&K.audio_url)return K.audio_url}return null},[x]),k=p.useCallback(async()=>{var K,H;if(h.current||d.current.length===0)return;h.current=!0;const N=d.current.shift();if(!N){h.current=!1;return}const{text:C,isGreeting:L}=N;L&&(g.current=!0),u.current=!1,S(),o.current&&(o.current.stop(),o.current=null),c.current=setTimeout(()=>{var Y,Z;console.warn("[BobWidget TTS] Timeout - triggering fallback callbacks"),j(),a(!1),g.current=!1,(Y=_.current)==null||Y.call(_),(Z=v.current)==null||Z.call(v),o.current=null,h.current=!1,k()},fd);try{let Y=null;const Z=await A(C);if(Z){console.log("[BobWidget TTS] Using pre-recorded audio (fast path)");const V=await fetch(Z);V.ok&&(Y=await V.arrayBuffer())}if(!Y){console.log("[BobWidget TTS] No pre-recorded clip, using ElevenLabs TTS");const V=gd(C),ge=await fetch(`${s.supabaseUrl}/functions/v1/bob-tts-elevenlabs`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.supabaseKey}`},body:JSON.stringify({text:V})});if(!ge.ok){const te=await ge.json().catch(()=>({}));throw console.error("[BobWidget TTS] Request failed:",te),new Error("TTS request failed")}Y=await ge.arrayBuffer()}await Ka();const W=await hd(Y,()=>{var V;S(),f.current=null,u.current||(u.current=!0,a(!0),console.log("[BobWidget TTS] Audio playing via AudioContext, triggering onStart"),(V=b.current)==null||V.call(b))},()=>{var V;S(),a(!1),g.current=!1,console.log("[BobWidget TTS] Audio ended, triggering onEnd"),(V=_.current)==null||V.call(_),o.current=null,h.current=!1,k()});o.current=W}catch(Y){S(),L&&(f.current=C,console.log("[BobWidget TTS] Greeting stored for retry on user interaction")),console.error("[BobWidget TTS] Speech synthesis error:",Y),j(),a(!1),g.current=!1,(K=_.current)==null||K.call(_),(H=v.current)==null||H.call(v),h.current=!1,k()}},[s.supabaseUrl,s.supabaseKey,S,j,A]),F=p.useCallback((N,C=!1)=>{if(N.trim()){if(C){if(y.current===N){console.log(`[BobWidget TTS] Ignoring duplicate greeting: "${N.substring(0,30)}..."`);return}y.current=N,f.current=null}if(g.current&&!C){console.log("[BobWidget TTS] Greeting playing - queueing message"),d.current.push({text:N,isGreeting:C});return}C?d.current.unshift({text:N,isGreeting:C}):d.current.push({text:N,isGreeting:C}),k()}},[k]),E=p.useCallback(()=>{if(f.current&&!o.current&&!h.current){console.log("[BobWidget TTS] Retrying pending greeting on user interaction");const N=f.current;f.current=null,F(N,!0)}},[F]),O=p.useCallback((N=!1)=>{var C;S(),d.current=[],o.current&&(o.current.stop(),o.current=null),a(!1),g.current=!1,h.current=!1,N||(C=_.current)==null||C.call(_)},[S]),T=p.useCallback(()=>{o.current&&o.current.stop()},[]),R=p.useCallback(()=>{},[]);return p.useEffect(()=>()=>{S(),d.current=[],o.current&&(o.current.stop(),o.current=null)},[S]),{speak:F,stop:O,pause:T,resume:R,isSpeaking:i,isSupported:!0,retryPendingGreeting:E}},Xi="bob_last_visit",bd=30;function Ja(t=bd){const[e,r]=p.useState(!1),[s,n]=p.useState(null);return p.useEffect(()=>{try{const i=localStorage.getItem(Xi),a=Date.now();if(i){const o=parseInt(i,10),c=(a-o)/(1e3*60*60*24);c<=t?(r(!0),n(new Date(o)),console.log(`[BobWidget] Returning user detected - last visit ${Math.round(c)} days ago`)):console.log(`[BobWidget] Previous visit was ${Math.round(c)} days ago - treating as new user`)}else console.log("[BobWidget] First time visitor detected");localStorage.setItem(Xi,String(a))}catch(i){console.warn("[BobWidget] Could not access localStorage for returning user detection:",i)}},[t]),{isReturningUser:e,lastVisitDate:s,daysSinceLastVisit:s?Math.round((Date.now()-s.getTime())/(1e3*60*60*24)):null}}const Qn=t=>{if(!t)return t;let e=t;return e=e.replace(/\b(retrieve_parts|lookup_vehicle|search_general_products|retrieve_service_packages|add_to_cart|get_cart|create_checkout|get_customer_context|get_product_details|search_products|check_vehicle_fitment|search_web)\s*\([^)]*\)/gi,""),e=e.replace(/\(\s*(vehicleid|vehicle_id|part_type|query|plate|user_email|sku)\s*=\s*[^)]+\)/gi,""),e=e.replace(/\b(retrieve_parts|lookup_vehicle|search_general_products|retrieve_service_packages|add_to_cart|get_cart|create_checkout|get_customer_context|get_product_details|search_products|check_vehicle_fitment|search_web)\s*\(/gi,""),e=e.replace(/\b(vehicleid|vehicle_id|part_type)\s*=\s*(['"]?[\w\s]+['"]?)\s*,?\s*/gi,""),e=e.replace(/```[\s\S]*?```/g,""),e=e.replace(/\(\s*\)/g,""),e=e.replace(/\s{2,}/g," "),e=e.trim(),e},md=t=>{let e=Qn(t);return e=e.replace(/[\[\]{}]/g,""),e=e.replace(/https?:\/\/[^\s]+/g,""),e=e.replace(/\bSKU\s*:?\s*\w+/gi,""),e},yd=["what version","which version","software version","bob version","your version","current version","running version","version number","what ver","which ver"],Zi=["recommend","suggest","need","part","filter","brake","rotor","oil","price","$","stock","available","pads","disc","spark plug","battery","clutch","alternator","starter","muffler","exhaust","service pack","add-on","tyre shine","windscreen wash"],Qa=({setAnimationState:t,manualMode:e=!1,talkingState:r="talking",thinkingState:s="researching",completeState:n="idle",idleState:i="idle",listenState:a="listening",onStreamStart:o,onStreamComplete:c,onShowingProduct:u,onResearchStart:d,onReadyToSpeak:h,onHighlightPart:g,onHighlightProduct:f,onNoPartsFound:y,onAutoFetchComplete:b,onVariantSelectionRequired:_,shelfCategoriesRef:v,initialVehicle:S})=>{var Ns,Is,Bs,Fs;const{bobConfig:j,hostApiConfig:x,hostContext:A,callbacks:k,ga4Config:F,analyticsEnabled:E}=Lt(),O=Ha({ga4Config:F,hostContext:A,callbacks:k,enabled:E}),{isReturningUser:T}=Ja(),[R,N]=p.useState([]),[C,L]=p.useState(""),[K,H]=p.useState(!1),[Y,Z]=p.useState(!1),[W,V]=p.useState(null),ge=p.useRef(null),te=p.useRef(!1),ie=p.useRef(!1),ve=p.useRef(""),$=p.useRef(!1),ae=p.useRef(null);p.useRef(null);const J="carfix_bob_session",B=4*60*60*1e3,Se=p.useRef(!1),ke=(U,re)=>{try{const ue={messages:U??R,vehicleCandidates:je.current,conversationState:Fe.current,identifiedVehicle:re!==void 0?re:W,savedAt:Date.now()};sessionStorage.setItem(J,JSON.stringify(ue))}catch(ue){console.warn("[BobWidget] Failed to save session:",ue)}},we=p.useRef({source:"none",isPlaying:!1,hasCannedAudio:!1,cannedUrl:null,currentAudio:null,searchingQueue:[]}),je=p.useRef([]),Fe=p.useRef("AWAITING_REGO");p.useEffect(()=>{if(!Se.current){Se.current=!0;try{const U=sessionStorage.getItem(J);if(U){const re=JSON.parse(U);if(Date.now()-(re.savedAt||0)<B&&Array.isArray(re.messages)&&re.messages.length>0){console.log("[BobWidget] Restoring session:",re.messages.length,"messages, state:",re.conversationState),N(re.messages),ie.current=!0,Array.isArray(re.vehicleCandidates)&&(je.current=re.vehicleCandidates),re.conversationState&&(Fe.current=re.conversationState),re.identifiedVehicle&&(V(re.identifiedVehicle),console.log("[BobWidget] Restored identifiedVehicle:",re.identifiedVehicle.make,re.identifiedVehicle.model));return}else console.log("[BobWidget] Session expired, clearing"),sessionStorage.removeItem(J)}}catch(U){console.warn("[BobWidget] Failed to restore session:",U),sessionStorage.removeItem(J)}S&&(console.log("[BobWidget] Applying initialVehicle:",S.make,S.model),je.current=[S],Fe.current="VEHICLE_CONFIRMED",V(S))}},[]),p.useEffect(()=>{R.length>0&&ke(R)},[R]);const[$e,Ye]=p.useState(!1),qe=()=>{const U=we.current;if(U.currentAudio){try{U.currentAudio.pause(),U.currentAudio.currentTime=0}catch(re){console.warn("[BobWidget] Error stopping audio:",re)}U.currentAudio=null}U.isPlaying=!1,U.source="none",U.searchingQueue=[],Ye(!1),oe()},et=(U,re,ue)=>{const me=we.current;if(me.isPlaying){if(re==="canned"||re==="searching"&&me.source==="tts")qe();else if(me.source==="canned"){console.log("[BobWidget Audio] Skipping lower priority audio while canned is playing");return}}const Ve=new Audio(U);me.currentAudio=Ve,me.source=re,me.isPlaying=!0,Ve.onplay=()=>{console.log(`[BobWidget Audio] ${re} STARTED:`,U.split("/").pop()),Ye(!0),e||ce(r)},Ve.onended=()=>{console.log(`[BobWidget Audio] ${re} ENDED`),me.currentAudio=null,me.isPlaying=!1,me.source="none",Ye(!1),ue==null||ue()},Ve.onerror=()=>{console.warn(`[BobWidget Audio] ${re} FAILED:`,U),me.currentAudio=null,me.isPlaying=!1,me.source="none",Ye(!1),ue==null||ue()},Ve.play().catch($t=>{console.warn(`[BobWidget Audio] ${re} autoplay blocked:`,$t),me.currentAudio=null,me.isPlaying=!1,me.source="none",ue==null||ue()})},it=()=>{const U=we.current;if(U.hasCannedAudio||U.source==="canned"){console.log("[BobWidget Audio] Skipping searching audio - canned audio takes priority"),U.searchingQueue=[];return}if(U.searchingQueue.length===0){!e&&U.source==="searching"&&ce(s);return}const re=U.searchingQueue.shift();et(re,"searching",()=>{it()})},De=()=>{ae.current&&(clearTimeout(ae.current),ae.current=null)},{speak:I,stop:oe,isSpeaking:Ae,retryPendingGreeting:M}=Ga({onStart:()=>{De(),$.current=!0,console.log("[BobWidget STATE] Speech STARTED - transitioning to TALK state"),O.trackSpeechPlayed(ve.current.length),h==null||h(),e||(console.log("[BobWidget STATE] Setting state to:",r),ce(r))},onEnd:()=>{De(),console.log("[BobWidget STATE] Speech ENDED - transitioning out of TALK state");const U=Zi.some(re=>ve.current.toLowerCase().includes(re.toLowerCase()));e||(U&&u?(console.log("[BobWidget STATE] Has products - calling onShowingProduct"),u()):c?(console.log("[BobWidget STATE] Calling onStreamComplete"),c()):(console.log("[BobWidget STATE] Setting state to:",n),ce(n),setTimeout(()=>{console.log("[BobWidget STATE] Post-complete transition to:",a),ce(a)},2e3)))},onFailed:()=>{console.warn("[BobWidget] Speech synthesis failed - fallback triggered"),O.trackSpeechFailed(ve.current.length)}});p.useEffect(()=>{var U;(U=k.onStopSpeechReady)==null||U.call(k,qe)},[]),p.useEffect(()=>{var U;(U=ge.current)==null||U.scrollIntoView({behavior:"smooth"})},[R]),p.useEffect(()=>{var re,ue;const U=(re=A.vehicle)==null?void 0:re.selectedVehicle;U&&!W&&(console.log("[BobWidget] Setting vehicle from host context:",U),V(U),(ue=k.onVehicleIdentified)==null||ue.call(k,U),O.trackVehicleIdentified({make:U.make,model:U.model,year:U.year,rego:U.rego}))},[(Ns=A.vehicle)==null?void 0:Ns.selectedVehicle]),p.useEffect(()=>{var U;if(R.length===0&&!ie.current){ie.current=!0;const re=(U=A.vehicle)==null?void 0:U.selectedVehicle;let ue;T?(ue="Ah hey... you again! What you after this time?",console.log("[BobWidget] Using returning user greeting")):re?ue=`G'day! Saw you've got the ${`${re.year} ${re.make} ${re.model}`} - choice wagon! What can I help you find for it today?`:ue="G'day! Bob from CARFIX here. How can I help ya today?",N([{role:"assistant",content:ue}]),Y||setTimeout(()=>{console.log("[BobWidget] Speaking initial greeting (priority)"),I(ue,!0)},500)}},[(Is=A.vehicle)==null?void 0:Is.selectedVehicle,R.length,Y,I]),p.useEffect(()=>{const U=()=>{console.log("[BobWidget] User interaction detected - retrying pending greeting"),M(),document.removeEventListener("click",U),document.removeEventListener("touchstart",U)};return document.addEventListener("click",U,{once:!0}),document.addEventListener("touchstart",U,{once:!0}),()=>{document.removeEventListener("click",U),document.removeEventListener("touchstart",U)}},[M]),p.useEffect(()=>{var sr,Dt;const U=(sr=A.vehicle)==null?void 0:sr.selectedVehicle;if(!U||te.current)return;const re=U.vehicle_id??U.id,ue=Number.parseInt(String(re),10);if(!Number.isFinite(ue)){console.warn("[BobWidget] Vehicle has invalid vehicle_id, cannot auto-fetch:",U);return}te.current=!0;const me={...U,vehicle_id:String(ue)},Ve=(Dt=A.user)==null?void 0:Dt.email;(async()=>{var Ut,Mt;const kr=`${j.supabaseUrl}/functions/v1/bob-chat`;try{const gt=await fetch(kr,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${j.supabaseKey}`},body:JSON.stringify({messages:[],vehicleContext:me,customerEmail:Ve,autoFetchParts:!0,hostConfig:x,hostContext:A})});if(!gt.ok||!gt.body){console.error("[BobWidget] Auto-fetch failed:",gt.status);return}const Sr=gt.body.getReader(),nr=new TextDecoder;let bt="";for(;;){const{done:Er,value:jr}=await Sr.read();if(Er)break;bt+=nr.decode(jr,{stream:!0});let Wt;for(;(Wt=bt.indexOf(`
74
+ `))!==-1;){let ut=bt.slice(0,Wt);if(bt=bt.slice(Wt+1),ut.endsWith("\r")&&(ut=ut.slice(0,-1)),ut.startsWith(":")||ut.trim()===""||!ut.startsWith("data: "))continue;const m=ut.slice(6).trim();if(m==="[DONE]")break;try{const P=JSON.parse(m);P.type==="service_packages_found"&&P.packages&&(console.log("[useBobChat autoFetch] Received service_packages_found:",P.packages.length,"packages"),(Ut=k.onServicePackagesFound)==null||Ut.call(k,P.packages),v!=null&&v.current&&P.packages.forEach(q=>{q.title&&v.current.add(q.title)})),P.type==="parts_found"&&P.parts&&(console.log("[useBobChat autoFetch] Received parts_found:",P.parts.length,"parts"),(Mt=k.onPartsFound)==null||Mt.call(k,P.parts),O.trackPartsViewed(Array.isArray(P.parts)?P.parts.length:0,String(ue)))}catch{}}}b==null||b()}catch(gt){console.error("[BobWidget] Auto-fetch error:",gt)}})()},[(Bs=A.vehicle)==null?void 0:Bs.selectedVehicle,(Fs=A.user)==null?void 0:Fs.email]);const ce=U=>{try{t(U)}catch{console.warn(`[BobWidget] State "${U}" not available`)}},Ce=async U=>{var Ve,$t,sr,Dt,kr,Ut,Mt,gt,Sr,nr,bt,Er,jr,Wt,ut,m,P,q;const re=`${j.supabaseUrl}/functions/v1/bob-chat`,ue=(Ve=A.user)==null?void 0:Ve.email;let me=!1;try{const X={messages:[...R,U],hostConfig:x,hostContext:A};v!=null&&v.current&&v.current.size>0&&(X.shelfContext=Array.from(v.current).join(", ")),W&&(X.vehicleContext=W),ue&&(X.customerEmail=ue),console.log("[useBobChat DEBUG] vehicleCandidatesRef.current:",JSON.stringify(($t=je.current)==null?void 0:$t.slice(0,2))),console.log("[useBobChat DEBUG] vehicleCandidatesRef.current.length:",(sr=je.current)==null?void 0:sr.length),console.log("[useBobChat DEBUG] conversationStateRef.current:",Fe.current),je.current&&je.current.length>0?(X.vehicleCandidates=je.current,console.log("[useBobChat] ✅ Including",je.current.length,"vehicle candidates in request")):console.log("[useBobChat] ⚠️ No vehicle candidates to include - ref is empty");const de=await fetch(re,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${j.supabaseKey}`},body:JSON.stringify(X)});if(!de.ok){if(de.status===429){(Dt=k.onError)==null||Dt.call(k,new Error("Rate limit exceeded"));return}if(de.status===402){(kr=k.onError)==null||kr.call(k,new Error("Payment required"));return}throw new Error("Failed to start stream")}if(!de.body)throw new Error("No response body");const _e=de.body.getReader(),he=new TextDecoder;let le="",Me=!1,Ee="";for(;!Me;){const{done:Oe,value:dt}=await _e.read();if(Oe)break;le+=he.decode(dt,{stream:!0});let At;for(;(At=le.indexOf(`
75
+ `))!==-1;){let at=le.slice(0,At);if(le=le.slice(At+1),at.endsWith("\r")&&(at=at.slice(0,-1)),at.startsWith(":")||at.trim()===""||!at.startsWith("data: "))continue;const Zr=at.slice(6).trim();if(Zr==="[DONE]"){Me=!0;break}try{const D=JSON.parse(Zr);if(D.type==="conversation_state"){console.log("[useBobChat] 🔄 conversation_state event received:",D.state),Fe.current=D.state,D.candidates&&Array.isArray(D.candidates)?(je.current=D.candidates,console.log("[useBobChat] ✅ Stored",D.candidates.length,"vehicle candidates from state event"),console.log("[useBobChat] First candidate:",JSON.stringify(D.candidates[0]))):console.log("[useBobChat] ⚠️ conversation_state had no candidates array"),ke();continue}if(D.type==="variant_selection_required"){const ye=Array.isArray(D.candidates)?D.candidates.length:0;console.log("[useBobChat] 🎴 variant_selection_required event received:",ye,"cards"),Array.isArray(D.candidates)?_==null||_(D.candidates,typeof D.make=="string"?D.make:"",typeof D.model=="string"?D.model:""):console.warn("[useBobChat] ⚠️ variant_selection_required had no candidates array");continue}if(D.type==="vehicle_identified"&&D.vehicle){V(D.vehicle),je.current=[],Fe.current="VEHICLE_CONFIRMED",ke(void 0,D.vehicle),(Ut=k.onVehicleIdentified)==null||Ut.call(k,D.vehicle),O.trackVehicleIdentified({make:D.vehicle.make,model:D.vehicle.model,year:D.vehicle.year,rego:D.vehicle.rego});continue}if(D.type==="vehicle_candidates_found"&&D.candidates){console.log("[useBobChat] 📦 vehicle_candidates_found event received:",D.candidates.length,"candidates"),je.current=D.candidates,console.log("[useBobChat] ✅ Candidates stored in ref. First:",JSON.stringify(D.candidates[0])),ke();continue}if(D.type==="service_packages_found"&&D.packages){(Mt=k.onServicePackagesFound)==null||Mt.call(k,D.packages),v!=null&&v.current&&(D.packages.forEach(ye=>{ye.title&&v.current.add(ye.title)}),console.log("[useBobChat] Eagerly added service package titles to shelfCategories:",Array.from(v.current)));continue}if(D.type==="parts_found"&&D.parts){console.log("[useBobChat] Received parts_found event:",D.parts.length,"parts"),(gt=k.onPartsFound)==null||gt.call(k,D.parts),v!=null&&v.current&&Array.isArray(D.parts)&&D.parts.forEach(ye=>{const Pe=ye.partslot_description||"Other Parts";Pe&&v.current.add(Pe)}),O.trackPartsViewed(Array.isArray(D.parts)?D.parts.length:0,(Sr=W==null?void 0:W.vehicle_id)==null?void 0:Sr.toString());continue}if(D.type==="bob_suggestions"&&D.products){console.log("[useBobChat] Received bob_suggestions:",D.products.length,"products",D.title),N(ye=>{var qt;const Pe=[...ye],Ne=Pe[Pe.length-1];return console.log("[useBobChat] Attaching to message:",Ne==null?void 0:Ne.role,(qt=Ne==null?void 0:Ne.content)==null?void 0:qt.slice(0,40)),(Ne==null?void 0:Ne.role)==="assistant"?Pe.map((ir,dn)=>dn===Pe.length-1?{...ir,suggestedProducts:D.products,suggestionsTitle:D.title}:ir):Pe}),console.log("[useBobChat] bob_suggestions processed for inline display only");continue}if(D.type==="no_parts_found"){(nr=k.onPartsFound)==null||nr.call(k,[]),(bt=k.onServicePackagesFound)==null||bt.call(k,[]),y==null||y();continue}if(D.type==="highlight_category"&&D.category){console.log("[useBobChat] highlight_category event:",D.category),me=!0,g==null||g(D.category);continue}if(D.type==="navigate_url"&&D.url){console.log("[useBobChat] navigate_url event:",D.url),oe(),(Er=k.onNavigateToProductPage)==null||Er.call(k,{sku:D.sku,url:D.url});continue}if(D.type==="quick_replies"&&Array.isArray(D.replies)){console.log("[useBobChat] quick_replies event:",D.replies.length,"buttons"),N(ye=>{var qt;const Pe=[...ye],Ne=Pe.length-1;return((qt=Pe[Ne])==null?void 0:qt.role)==="assistant"?Pe.map((ir,dn)=>dn===Ne?{...ir,quickReplies:D.replies}:ir):Pe});continue}if(D.type==="audio_hint"&&D.audio_url){console.log("[useBobChat] Audio hint received:",D.clip_key,D.audio_url);const ye=we.current;ye.hasCannedAudio=!0,ye.cannedUrl=D.audio_url,qe();continue}if(D.type==="bob_searching"&&D.audio_url){console.log("[useBobChat] Bob searching:",D.search_type,D.clip_key),D.transcript&&N(Pe=>{const Ne=Pe[Pe.length-1];return(Ne==null?void 0:Ne.role)!=="assistant"||(Ne==null?void 0:Ne.content)!==D.transcript?[...Pe,{role:"assistant",content:D.transcript}]:Pe});const ye=we.current;ye.searchingQueue.push(D.audio_url),!ye.isPlaying&&!ye.hasCannedAudio&&!Y&&it();continue}if(D.type==="cart_updated"&&D.items){if((jr=k.onCartUpdated)==null||jr.call(k,D.items),k.onAddToCart)for(const ye of D.items)k.onAddToCart({product_id:ye.product_id||ye.productName||"",product_name:ye.product_name||ye.productName||"",quantity:ye.quantity||1,unit_price:ye.unit_price||0,vehicle_id:ye.vehicle_id,sku:ye.sku,brand:ye.brand});continue}const Ls=(m=(ut=(Wt=D.choices)==null?void 0:Wt[0])==null?void 0:ut.delta)==null?void 0:m.content;if(Ls){Ee+=Ls;let ye=Ee.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");ye=Qn(ye),N(Pe=>{const Ne=Pe[Pe.length-1];return(Ne==null?void 0:Ne.role)==="assistant"?Pe.map((qt,ir)=>ir===Pe.length-1?{...qt,content:ye}:qt):[...Pe,{role:"assistant",content:ye}]}),(P=k.onBobMessage)==null||P.call(k,ye)}}catch{le=at+`
76
+ `+le;break}}}let Re=Ee.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");Re=Qn(Re),ve.current=Re;const Ge=Zi.some(Oe=>Ee.toLowerCase().includes(Oe.toLowerCase()));if(console.log("[useBobChat] v3.2.10 scroll debug: highlightCategoryReceived=",me,"shelfCategories=",v!=null&&v.current?Array.from(v.current):"none"),!me&&(v!=null&&v.current)&&v.current.size>0){const Oe=Re.toLowerCase();let dt=null,At=0;for(const at of v.current){const Zr=at.toLowerCase().split(/\s+/).filter(Boolean),D=Zr.filter(Ls=>Oe.includes(Ls)).length;D===Zr.length&&D>At&&(At=D,dt=at)}dt&&(console.log("[useBobChat] v3.2.10 shelf category match:",dt,`(${At} words)`),g==null||g(dt))}const Rt=Ee.match(/(?:go with|recommend|suggest|grab|try)\s+(?:the\s+)?(\w+)\s+(?:at|for)\s+\$(\d+(?:\.\d{2})?)/i);if(Rt){const[,Oe,dt]=Rt;f==null||f({brand:Oe,price:parseFloat(dt)})}const Je=we.current;if(!Y&&ve.current.trim()){if($.current=!1,De(),Je.hasCannedAudio&&Je.cannedUrl)console.log("[BobWidget] Playing canned audio (priority):",Je.cannedUrl),qe(),et(Je.cannedUrl,"canned",()=>{Je.hasCannedAudio=!1,Je.cannedUrl=null,De(),e||(Ge&&u?u():c?c():(ce(n),setTimeout(()=>ce(a),3e3)))}),$.current=!0,h==null||h();else if(Je.isPlaying)console.log("[BobWidget] Skipping TTS - audio already playing:",Je.source);else{const Oe=md(ve.current);console.log("[BobWidget] Playing TTS (no canned audio)"),I(Oe)}ae.current=setTimeout(()=>{$.current||(console.warn("[BobWidget] Speech fallback after 5s"),h==null||h(),e||(Ge&&u?u():c?c():(ce(n),setTimeout(()=>ce(a),3e3))))},5e3)}else h==null||h(),e||(Ge&&u?u():c?c():(ce(n),setTimeout(()=>ce(a),3e3)))}catch(X){console.error("[BobWidget] Chat error:",X);const de=X instanceof Error?X:new Error("Unknown error");(q=k.onError)==null||q.call(k,de),O.trackError(de.name||"ChatError",de.message||"Unknown chat error"),e||ce(i)}},Xe=async()=>{if(!C.trim()||K)return;M(),oe();const U={role:"user",content:C};N(me=>[...me,U]),L(""),O.trackMessageSent(C.length,!!W);const re=C.toLowerCase();if(yd.some(me=>re.includes(me))){const me=`G'day mate! I'm running Bob v${Bt} - she's running sweet as! Anything else I can help ya with?`;N(Ve=>[...Ve,{role:"assistant",content:me}]),Y||I(me);return}H(!0),console.log("[BobWidget STATE] User sent message - switching to RESEARCH state:",s),d==null||d(),e||ce(s),await Ce(U),H(!1)};return{messages:R,input:C,setInput:L,isLoading:K,handleSend:Xe,handleKeyPress:U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),Xe())},handleInputFocus:()=>{M()},handleInputBlur:()=>{},chatEndRef:ge,clearMessages:()=>{sessionStorage.removeItem(J),je.current=[],Fe.current="AWAITING_REGO",N([{role:"assistant",content:"G'day! Bob from CARFIX here. How can I help ya today?"}])},isMuted:Y,toggleMute:()=>{Z(U=>!U),Y||oe()},isSpeaking:Ae||$e,identifiedVehicle:W,clearVehicle:()=>{V(null)},sendDirectMessage:U=>{if(!U.trim())return;console.log("[BobWidget] sendDirectMessage:",U),oe(),H(!1),L("");const re={role:"user",content:U};N(ue=>[...ue,re]),d==null||d(),e||ce(s),H(!0),Ce(re).finally(()=>H(!1))},stopAllAudio:qe}},vd={states:[],configs:[],uploadedImages:[],looks:[],activeLookId:null},Ya=t=>{const e=Wa(),r=_r();return p.useEffect(()=>{if(!r)return;const s=r.channel("animation-states-changes").on("postgres_changes",{event:"*",schema:"public",table:"animation_states"},()=>{e.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe(),n=r.channel("bob-animations-changes").on("postgres_changes",{event:"*",schema:"public",table:"bob_animations"},()=>{e.invalidateQueries({queryKey:["bob-animation-data"]})}).subscribe();return()=>{r.removeChannel(s),r.removeChannel(n)}},[e,r]),Ps({queryKey:["bob-animation-data",t],queryFn:async()=>{var j;if(!r)return console.log("[BobAnimation] No supabase client, returning empty data"),vd;const{data:s,error:n}=await r.from("bob_looks").select("*").order("display_order");if(n)throw n;const i=(s||[]).find(x=>x.is_active),a=t||(i==null?void 0:i.id)||s&&((j=s[0])==null?void 0:j.id)||null;if(!a)return console.warn("[BobAnimation] No looks configured in database"),{states:[],configs:[],uploadedImages:[],looks:s||[],activeLookId:null};console.log(`[BobAnimation] Loading animations for look: ${(i==null?void 0:i.name)||a}`);const{data:o,error:c}=await r.from("animation_states").select("*").eq("is_active",!0).eq("look_id",a).order("display_order");if(c)throw c;const{data:u,error:d}=await r.from("bob_animations").select("*").eq("is_active",!0).eq("look_id",a).order("animation_state").order("sequence_order");if(d)throw d;const h=(o||[]).map(x=>x.state_key);console.log(`[BobAnimation] Loaded ${h.length} states: ${h.join(", ")}`);const f=["idle","talking","listening"].filter(x=>{const A=[x,x.replace("ing",""),x+"ing"];return!h.some(k=>A.includes(k))});f.length>0&&console.warn(`[BobAnimation] ⚠️ Missing critical states: ${f.join(", ")}`);const y=new Set(h),b=(u||[]).filter(x=>y.has(x.animation_state));console.log(`[BobAnimation] Loaded ${b.length} animation frames`);const{data:_,error:v}=await r.storage.from("bob-images").list();if(v)throw v;const S=(_||[]).map(x=>{const{data:A}=r.storage.from("bob-images").getPublicUrl(x.name);return A.publicUrl});return b.forEach(x=>{const A=new Image;A.src=x.image_url}),{states:o||[],configs:b,uploadedImages:S,looks:s||[],activeLookId:a}},staleTime:30*1e3,gcTime:5*60*1e3})},Xa=(t={})=>{const{isSpeaking:e=!1}=t,[r,s]=p.useState(""),[n,i]=p.useState(0),[a,o]=p.useState(400),[c,u]=p.useState(!1),d=p.useRef(null),h=p.useRef(0),g=p.useRef(e),f=p.useRef(0),y=p.useRef(0),b=p.useRef(!1),_=p.useRef(0),{data:v,isLoading:S}=Ya(),j=p.useRef({}),{imageUrlsMap:x,alternateImages:A,offsetsMap:k,scalesMap:F,availableStates:E}=p.useMemo(()=>{if(!v)return{imageUrlsMap:{},alternateImages:{},offsetsMap:{},scalesMap:{},availableStates:[]};const C={},L={},K={},H={},Y=v.states.map(Z=>Z.state_key);return Y.forEach(Z=>{const W=v.configs.filter(ie=>ie.animation_state===Z),V=W.map(ie=>ie.image_url),ge=W.map(ie=>ie.vertical_offset||0),te=W.map(ie=>ie.scale||100);if(V.length>0){const ie=v.states.find(ve=>ve.state_key===Z);C[Z]={url:V[0],animation_speed:(ie==null?void 0:ie.animation_speed)||400,pause_duration:(ie==null?void 0:ie.pause_duration)||0,loop_count:(ie==null?void 0:ie.loop_count)||0},L[Z]=V,K[Z]=ge,H[Z]=te}}),{imageUrlsMap:C,alternateImages:L,offsetsMap:K,scalesMap:H,availableStates:Y}},[v]);p.useEffect(()=>{j.current=x},[x]),p.useEffect(()=>{const C=g.current;if(g.current=e,C&&!e){const L=r.toLowerCase();(L.includes("talk")||L==="talking")&&(console.log("[useBobAnimation] Speech ended while in talk state - forcing loop completion"),y.current=999)}},[e,r]);const O=p.useCallback(C=>{s(L=>L===C?L:(f.current=0,y.current=0,b.current=!1,i(0),C))},[]);p.useEffect(()=>{E.length>0&&!r&&s(E[0])},[E,r]),p.useEffect(()=>{const C=A[r];if(d.current!==null&&(cancelAnimationFrame(d.current),d.current=null),f.current=0,y.current=0,b.current=!1,h.current=0,i(0),!C||C.length<=1)return;const L=j.current[r],K=(L==null?void 0:L.animation_speed)||a||400,H=(L==null?void 0:L.loop_count)||0,Y=(L==null?void 0:L.pause_duration)||0,Z=r.toLowerCase().includes("talk"),W=V=>{if(h.current===0&&(h.current=V),b.current){V-_.current>=Y&&(b.current=!1,y.current=0,h.current=V),d.current=requestAnimationFrame(W);return}if(V-h.current>=K){h.current=V;const te=(f.current+1)%C.length;te===0?(y.current++,Z&&g.current?(f.current=te,i(te)):H>0&&y.current>=H?Y>0&&(b.current=!0,_.current=V):(f.current=te,i(te))):(f.current=te,i(te))}d.current=requestAnimationFrame(W)};return d.current=requestAnimationFrame(W),()=>{d.current!==null&&(cancelAnimationFrame(d.current),d.current=null)}},[r,A,a]);const T=p.useCallback(()=>{const C=A[r];if(!C||C.length===0){const L=E.find(K=>{var H;return((H=A[K])==null?void 0:H.length)>0});return L?(console.warn(`[useBobAnimation] No images for "${r}", using fallback: ${L}`),A[L][0]):(console.error("[useBobAnimation] No valid images found for any state!"),"")}return C[n]||C[0]},[A,r,E,n]),R=p.useCallback(()=>{const C=k[r];if(!C||C.length===0){const L=E.find(K=>{var H;return((H=k[K])==null?void 0:H.length)>0});return L?k[L][0]:0}return C[n]||C[0]},[k,r,E,n]),N=p.useCallback(()=>{const C=F[r];if(!C||C.length===0){const L=E.find(K=>{var H;return((H=F[K])==null?void 0:H.length)>0});return L?F[L][0]:100}return C[n]||C[0]},[F,r,E,n]);return{animationState:r,setAnimationState:O,getCurrentImage:T,getCurrentOffset:R,getCurrentScale:N,imageUrls:x,availableStates:E,setTalkSpeed:o,manualMode:c,setManualMode:u,isLoading:S}},Za=()=>{const t=_r(),{data:e=[],isLoading:r}=Ps({queryKey:["bob-backdrops"],queryFn:async()=>{if(!t)return console.log("[useBobBackdrop] No supabase client, returning empty"),[];const{data:n,error:i}=await t.from("bob_backdrops").select("*").order("display_order",{ascending:!0});if(i)throw i;return n},staleTime:5*60*1e3,gcTime:10*60*1e3}),s=e.find(n=>n.is_active);return{backdrops:e,activeBackdrop:s,isLoading:r}},eo=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=12,className:i="",verticalOffset:a=0,scale:o=100})=>{const c=a+n,u=55*(o/100);return l.jsx("div",{className:`flex flex-col items-center justify-center gap-6 w-full ${i}`,children:l.jsxs("div",{className:"relative w-full max-w-[600px] mx-auto aspect-[16/10] overflow-hidden",children:[r&&l.jsx("img",{src:r,alt:"Backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-bottom"}),l.jsx("img",{src:t,alt:`Bob ${e}`,className:"absolute z-10 h-auto object-contain left-1/2 -translate-x-1/2",style:{bottom:`${c}%`,width:`${u}%`,maxWidth:`${220*(o/100)}px`,transformOrigin:"center bottom"}}),s&&l.jsx("img",{src:s,alt:"Counter",className:"absolute z-20 bottom-0 left-0 w-full object-cover object-bottom",style:{height:`${n}%`}})]})})},G={primary:"#0052CC",primaryHover:"#0047B3",secondary:"#38BDF8",foreground:"#0F172A",accent:"#FF8C00",success:"#22C55E",destructive:"#EF4444",performanceRed:"#DC2626",mutedForeground:"#64748B",background:"#FAFAFA",card:"#FFFFFF",border:"#E2E8F0",slateEconomy:"#475569"},tn={Economy:{icon:"DollarSign",emoji:"💰",textColor:"#475569",background:"#F1F5F9",border:"#CBD5E1",description:"Smart savings"},Standard:{icon:"Star",emoji:"⭐",textColor:"#0052CC",background:"rgba(0,82,204,0.1)",border:"rgba(0,82,204,0.3)",description:"Best value",isRecommended:!0},Premium:{icon:"Award",emoji:"🏆",textColor:"#D97706",background:"#FEF3C7",border:"#FCD34D",description:"Superior quality"},Performance:{icon:"Zap",emoji:"⚡",textColor:"#DC2626",background:"#FEE2E2",border:"#FCA5A5",description:"Maximum power"}},yn={"Oil Change":"Neglecting oil changes leads to engine wear, overheating, and catastrophic failure costing thousands. Quality oil and filters keep your engine running smoothly. Each CARFIX Oil Change Service Pack includes premium oil and filter matched to your engine specifications.","Front Brake Service":"Your front brakes handle 70% of stopping power. Worn pads dangerously increase stopping distance. Quality brake components ensure confident, safe stops. Each CARFIX Front Brake Service Pack includes pads and rotors to restore your braking performance.","Rear Brake Service":"Rear brakes provide stability and balance during emergency stops. Worn components cause instability and longer stopping distances. Each CARFIX Rear Brake Service Pack includes quality pads/shoes and rotors/drums for complete rear brake renewal.","Timing Belt Service":"A snapped timing belt destroys engines instantly, causing $8,000+ in damage. Preventive replacement is essential for peace of mind. Each CARFIX Timing Belt Service Pack includes the belt, tensioner, and related components.",Wipers:"Worn wipers reduce visibility in rain, compromising safety. Quality blades provide streak-free, clear vision. Each CARFIX Wipers Service Pack includes the gear you need to change all of your vehicle's wiper blades to restore your driving vision.","Coolant Service":"Old coolant causes overheating, warped cylinder heads, and engine seizure. Fresh coolant protects your entire cooling system. Each CARFIX Coolant Service Pack includes quality coolant matched to your vehicle's requirements.","Air Filter Service":"Clogged air filters reduce engine performance by 10% and increase fuel consumption. Clean filters improve power and economy. Each CARFIX Air Filter Service Pack includes a precision-fit filter for optimal airflow.","Spark Plug Service":"Worn spark plugs cause misfires, poor fuel economy, and catalytic converter damage. Fresh plugs restore smooth, efficient running. Each CARFIX Spark Plug Service Pack includes quality plugs matched to your engine.","Battery Service":"A failing battery leaves you stranded without warning. Reliable power is essential for starting and electronics. Each CARFIX Battery Service Pack includes a quality battery sized for your vehicle's demands.","Cabin Filter":"Cabin filters clean the air you and your passengers breathe. Replace regularly to remove pollen, dust, and odours. Each CARFIX Cabin Filter Service Pack includes a quality filter for fresh, clean cabin air.","Fuel Filter Service":"Clogged fuel filters restrict flow, causing poor performance and potential engine damage. Clean fuel is critical for efficiency. Each CARFIX Fuel Filter Service Pack includes a quality filter for optimal fuel delivery.","Transmission Service":"Old transmission fluid causes rough shifting, slipping, and premature wear. Fresh fluid extends transmission life. Each CARFIX Transmission Service Pack includes quality fluid matched to your transmission type."},wd="Keep your vehicle running safely and efficiently with quality parts matched to your specific make and model. Each CARFIX Service Pack includes everything you need for this essential maintenance.",Ss={storageBase:"https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public",productImage:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/product_images/${t}.jpg`,brandLogo:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${t.replace(/\s+/g,"")}.jpg`,carfixImage:t=>`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/carfix_images/${t}_1.jpg`},to={fitsVehicle:{background:"rgba(34,197,94,0.1)",text:"#22C55E",border:"rgba(34,197,94,0.2)",icon:"Check",label:"Fits Your Vehicle"},viscosity:{background:"#EFF6FF",text:"#1D4ED8",border:"#BFDBFE",icon:"Gauge"},volume:{background:"#ECFEFF",text:"#0E7490",border:"#A5F3FC",icon:"Droplets"},quantity:{background:"#F1F5F9",text:"#475569",border:"#CBD5E1"},partNumber:{background:"transparent",text:"#64748B",border:"transparent"},carfixValue:{background:"rgba(0,82,204,0.1)",text:"#0052CC",border:"rgba(0,82,204,0.2)",icon:"Sparkles",label:"CARFIX Value"},rotorPair:{background:"#EFF6FF",text:"#1D4ED8",border:"#BFDBFE",label:"Pair"}},vt={packageTitle:{fontSize:"20px",fontWeight:700},partslotName:{fontSize:"14px",fontWeight:600},productName:{fontSize:"14px",fontWeight:500},description:{fontSize:"14px",fontWeight:400},priceMain:{fontSize:"20px",fontWeight:700},priceSecondary:{fontSize:"12px",fontWeight:400},tierLabel:{fontSize:"14px",fontWeight:500},badgeText:{fontSize:"12px",fontWeight:500}};function ro(t){var s;const e=((s=t.name)==null?void 0:s.toLowerCase())||"",r=(t.partslotDescription||t.partslot_description||"").toLowerCase();return e.includes("rotor")||r.includes("disc rotor")||r.includes("brake rotor")||t.per_car_qty===2}function so(t,e){return e?{displayPrice:t*2,unitPriceLabel:`$${t.toFixed(2)} each`}:{displayPrice:t}}function nt(t){return`$${t.toFixed(2)}`}function no(t){if(yn[t])return yn[t];const e=t.toLowerCase();for(const[r,s]of Object.entries(yn))if(e.includes(r.toLowerCase())||r.toLowerCase().includes(e))return s;return wd}const ls=({type:t,value:e,className:r=""})=>{const s=to[t],n=e||("label"in s?s.label:""),i=()=>{if(!("icon"in s))return null;const a={width:12,height:12};switch(s.icon){case"Check":return l.jsx("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",children:l.jsx("polyline",{points:"20 6 9 17 4 12"})});case"Sparkles":return l.jsxs("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[l.jsx("path",{d:"M12 3l1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5L12 3z"}),l.jsx("path",{d:"M5 19l1 3 1-3 3-1-3-1-1-3-1 3-3 1 3 1z"})]});case"Gauge":return l.jsxs("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[l.jsx("circle",{cx:"12",cy:"12",r:"10"}),l.jsx("path",{d:"M12 6v6l4 2"})]});case"Droplets":return l.jsx("svg",{style:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:l.jsx("path",{d:"M12 2.69l5.66 5.66a8 8 0 11-11.31 0z"})});default:return null}};return l.jsxs("span",{className:r,style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",fontSize:"12px",fontWeight:500,background:s.background,color:s.text,border:`1px solid ${s.border}`,whiteSpace:"nowrap"},children:[i(),n]})},ni=({products:t,title:e,onProductClick:r,onAddToCart:s})=>!t||t.length===0?null:l.jsxs("div",{style:{marginTop:"16px",width:"100%"},children:[e&&l.jsxs("div",{style:{marginBottom:"12px",fontSize:vt.partslotName.fontSize,fontWeight:vt.partslotName.fontWeight,color:G.foreground,display:"flex",alignItems:"center",gap:"8px"},children:[l.jsx("span",{style:{fontSize:"18px"},children:"🚗"}),e]}),l.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:t.slice(0,6).map((n,i)=>l.jsx(xd,{product:n,onProductClick:r,onAddToCart:s,isRecommended:i===0},n.id||n.sku||i))}),t.length>6&&l.jsxs("div",{style:{marginTop:"12px",fontSize:"13px",color:G.mutedForeground,textAlign:"center"},children:["+ ",t.length-6," more options available"]})]}),xd=({product:t,onProductClick:e,onAddToCart:r,isRecommended:s=!1})=>{const[n,i]=p.useState(!1),[a,o]=p.useState(!1),c=t.image_url||t.image||(t.sku?Ss.productImage(t.sku):null),u=t.brand?Ss.brandLogo(t.brand):null,d=t.brand||"Quality Part",h=t.name||"Product",g=t.price??0,f=t.partNumber||t.part_number,y=ro({name:t.name,partslotDescription:t.partslotDescription,per_car_qty:t.quantity}),{displayPrice:b,unitPriceLabel:_}=so(g,y);return l.jsxs("div",{style:{background:G.card,borderRadius:"12px",border:`2px solid ${G.border}`,overflow:"hidden",cursor:e?"pointer":"default",transition:"all 0.2s ease"},onClick:()=>e==null?void 0:e(t),onMouseEnter:v=>{v.currentTarget.style.borderColor=`${G.primary}80`,v.currentTarget.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)"},onMouseLeave:v=>{v.currentTarget.style.borderColor=G.border,v.currentTarget.style.boxShadow="none"},children:[t.partslotDescription&&l.jsxs("div",{style:{background:"rgba(0,0,0,0.03)",borderBottom:`1px solid ${G.border}`,padding:"10px 16px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[l.jsx("span",{style:{fontSize:vt.partslotName.fontSize,fontWeight:vt.partslotName.fontWeight,color:G.foreground},children:t.partslotDescription}),s&&l.jsx(ls,{type:"carfixValue"})]}),l.jsxs("div",{style:{padding:"16px",display:"flex",gap:"16px"},children:[l.jsx("div",{style:{width:"96px",minWidth:"96px",height:"96px",borderRadius:"8px",background:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",border:`1px solid ${G.border}`},children:c&&!n?l.jsx("img",{src:c,alt:h,style:{width:"100%",height:"100%",objectFit:"contain",padding:"4px"},onError:()=>i(!0)}):l.jsx("span",{style:{fontSize:"32px",opacity:.5},children:"🔧"})}),l.jsxs("div",{style:{flex:1,minWidth:0},children:[l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:[u&&!a&&l.jsx("img",{src:u,alt:d,style:{height:"16px",width:"auto",objectFit:"contain"},onError:()=>o(!0)}),l.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:G.foreground,textTransform:"uppercase"},children:d})]}),l.jsx("div",{style:{fontSize:vt.productName.fontSize,fontWeight:vt.productName.fontWeight,color:G.foreground,overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",lineHeight:"1.4",marginBottom:"8px"},children:h}),l.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px",marginBottom:"12px"},children:[l.jsx(ls,{type:"fitsVehicle"}),y&&l.jsx(ls,{type:"rotorPair"}),t.quantity&&t.quantity>1&&!y&&l.jsx(ls,{type:"quantity",value:`Qty: ${t.quantity}`}),f&&l.jsxs("span",{style:{fontSize:"12px",color:G.mutedForeground},children:["#",f]})]})]}),l.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",justifyContent:"space-between",minWidth:"100px"},children:[l.jsxs("div",{style:{textAlign:"right"},children:[l.jsx("div",{style:{fontSize:vt.priceMain.fontSize,fontWeight:vt.priceMain.fontWeight,color:G.foreground},children:nt(b)}),_&&l.jsx("div",{style:{fontSize:vt.priceSecondary.fontSize,color:G.mutedForeground},children:_}),l.jsx("div",{style:{fontSize:vt.priceSecondary.fontSize,color:G.mutedForeground},children:"inc GST"})]}),r&&l.jsx("button",{onClick:v=>{v.stopPropagation(),r(t)},style:{background:G.primary,color:"#FFFFFF",border:"none",borderRadius:"8px",padding:"8px 16px",fontSize:"13px",fontWeight:600,cursor:"pointer",transition:"all 0.2s ease",whiteSpace:"nowrap"},onMouseEnter:v=>{v.currentTarget.style.background=G.primaryHover},onMouseLeave:v=>{v.currentTarget.style.background=G.primary},onMouseDown:v=>{v.currentTarget.style.transform="scale(0.98)"},onMouseUp:v=>{v.currentTarget.style.transform="scale(1)"},children:"Add to Cart"})]})]})]})},io=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:o,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,className:g="",onAddToCart:f,onProductClick:y})=>l.jsx("div",{className:g,style:{width:"100%",maxWidth:"72rem",margin:"0 auto",padding:"0 16px 32px 16px"},children:l.jsxs("div",{style:{backgroundColor:"rgba(20, 30, 50, 0.85)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"16px",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.3)",overflow:"hidden"},children:[l.jsx("div",{style:{padding:"16px",borderBottom:"1px solid rgba(255,255,255,0.1)",backgroundColor:"rgba(0,0,0,0.2)"},children:l.jsxs("div",{style:{display:"flex",gap:"8px"},children:[l.jsx("input",{value:e,onChange:b=>r(b.target.value),onKeyPress:i,onFocus:a,onBlur:o,placeholder:"Ask Bob about car parts...",disabled:s,style:{flex:1,padding:"12px 16px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",color:"white",fontSize:"16px",outline:"none"}}),d&&l.jsx("button",{onClick:d,style:{flexShrink:0,padding:"12px",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"12px",backgroundColor:"rgba(255,255,255,0.1)",cursor:"pointer",minHeight:"unset",minWidth:"unset"},title:u?"Unmute Bob's voice":"Mute Bob's voice",children:u?"🔇":"🔊"}),l.jsx("button",{onClick:n,disabled:s||!e.trim(),style:{flexShrink:0,padding:"12px 20px",background:s||!e.trim()?"rgba(0, 102, 204, 0.3)":"linear-gradient(135deg, rgba(0, 102, 204, 0.95), rgba(0, 73, 153, 1))",color:"white",borderRadius:"12px",border:"1px solid rgba(255,255,255,0.2)",cursor:s||!e.trim()?"not-allowed":"pointer",opacity:s||!e.trim()?.5:1,minHeight:"unset",minWidth:"unset",fontWeight:600},children:"Send"})]})}),l.jsxs("div",{style:{overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"12px",height:"400px",background:"rgba(0,0,0,0.1)"},children:[[...t].reverse().map((b,_)=>{var v;return l.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:b.role==="user"?"flex-end":"flex-start"},children:l.jsxs("div",{style:{maxWidth:(v=b.suggestedProducts)!=null&&v.length?"100%":"80%",borderRadius:"16px",padding:"12px 16px",fontSize:"14px",backgroundColor:b.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9), rgba(0, 73, 153, 1))":"rgba(255,255,255,0.1)",background:b.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9), rgba(0, 73, 153, 1))":"rgba(255,255,255,0.08)",color:"white",border:"1px solid rgba(255,255,255,0.15)",boxShadow:"0 2px 8px rgba(0,0,0,0.2)"},children:[b.content,b.role==="assistant"&&b.suggestedProducts&&b.suggestedProducts.length>0&&l.jsx(ni,{products:b.suggestedProducts,title:b.suggestionsTitle,onAddToCart:f,onProductClick:y})]})},_)}),l.jsx("div",{ref:c})]})]})}),_d=768,kd=1024;function ln(){const[t,e]=p.useState("mobile");return p.useEffect(()=>{const r=()=>{const s=window.innerWidth;s>=kd?e("desktop"):s>=_d?e("tablet"):e("mobile")};return r(),window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),t}function ii(){const t=ln();return Sd(t)}function Sd(t){switch(t){case"mobile":return{bobOffset:1,productWidth:1,uiScale:1,partialLeftPosition:-30,hiddenPosition:-100};case"tablet":return{bobOffset:.7,productWidth:.85,uiScale:1.1,partialLeftPosition:-25,hiddenPosition:-80};case"desktop":return{bobOffset:.5,productWidth:.7,uiScale:1.2,partialLeftPosition:-5,hiddenPosition:-60};default:return{bobOffset:1,productWidth:1,uiScale:1,partialLeftPosition:-20,hiddenPosition:-100}}}const cn=({currentImage:t,animationState:e,counterOverlayUrl:r,counterHeightPercent:s=15,scale:n=100,position:i="center",verticalOffset:a=0,hasArrived:o=!0})=>{const c=ii(),d=95*n/100,h=550*n/100,g=()=>{switch(i){case"center":return"50%";case"partial-left":return`${c.partialLeftPosition}%`;case"hidden":return`${c.hiddenPosition}%`;default:return"50%"}},f=()=>i==="center"?"translateX(-50%)":"translateX(0)",y=s+a,b=()=>i==="hidden"?"all 0.35s cubic-bezier(0.4, 0, 0.2, 1)":"all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1)";return l.jsxs("div",{className:"absolute inset-0 pointer-events-none",style:{overflow:"visible"},children:[l.jsx("div",{className:"absolute z-[60]",style:{bottom:`${y}%`,left:g(),maxHeight:`${100-s-2}%`,transform:f(),width:`${d}%`,maxWidth:`${h}px`,transition:b()+", opacity 0.6s ease-out",willChange:"transform, left, opacity",opacity:o?1:0},children:l.jsx("img",{src:t,alt:`Bob ${e}`,className:"w-full h-auto object-contain",style:{display:"block",maxHeight:"100%",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1})}),r&&l.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-[70]",style:{height:`${s}%`,pointerEvents:"none"},children:l.jsx("img",{src:r,alt:"Shop counter",className:"w-full h-full",style:{objectFit:"fill",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1})})]})},Ed={background:"rgba(20, 30, 50, 0.92)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"28px",boxShadow:"0 10px 40px rgba(0, 0, 0, 0.35), inset 0 0 0 1px rgba(255,255,255,0.1)"},jd={background:"linear-gradient(135deg, rgba(40, 60, 100, 0.95) 0%, rgba(20, 40, 80, 0.98) 100%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(0, 0, 0, 0.35), 0 0 0 1px rgba(255,255,255,0.15), inset 0 1px 0 rgba(255,255,255,0.2)"},ao={background:"rgba(255, 255, 255, 0.08)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"28px",boxShadow:"0 10px 40px rgba(0, 0, 0, 0.3)"},fs={primary:{color:"rgba(255, 255, 255, 1)",textShadow:"0 1px 3px rgba(0,0,0,0.5)"}},Td={background:"rgba(255, 255, 255, 0.12)",borderRadius:"20px",border:"1px solid rgba(255, 255, 255, 0.15)"},ea={background:"rgba(255, 255, 255, 0.15)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"12px"},Rd={width:"4px",height:"4px",borderRadius:"50%",background:"rgba(255, 255, 255, 0.6)",boxShadow:"0 0 8px rgba(255, 255, 255, 0.4)"},oo=({product:t,isSpotlighted:e=!1,onProductClick:r,onAddToCart:s})=>{const[n,i]=p.useState(!1),[a,o]=p.useState(0),c=()=>{r==null||r(t)},u=y=>{y.stopPropagation(),s==null||s(t)},d=()=>{a===0&&t.brandImageUrl?o(1):o(2)},h=a===0?t.image_url:a===1?t.brandImageUrl:void 0,g=e?jd:Ed,f=t.webDescription||t.name;return l.jsxs("div",{onClick:c,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),className:"relative w-full cursor-pointer glass-card",style:{...g,padding:"16px",paddingBottom:"60px",position:"relative",transform:n?"scale(1.04) translateY(-4px)":"scale(1) translateY(0)",boxShadow:n?"0 16px 56px rgba(0, 0, 0, 0.4), 0 0 24px rgba(255,255,255,0.08)":g.boxShadow,transition:"transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.3s ease-out"},children:[e&&l.jsxs("div",{className:"absolute -top-2.5 -right-2.5 z-10 flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.95) 0%, rgba(0, 73, 153, 1) 100%)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.3)",borderRadius:"20px",boxShadow:"0 8px 24px rgba(0, 102, 204, 0.5)",color:"white"},children:[l.jsx("svg",{className:"w-3.5 h-3.5",fill:"currentColor",viewBox:"0 0 20 20",children:l.jsx("path",{d:"M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"})}),"Bob's Pick"]}),l.jsxs("div",{className:"flex items-start gap-4",children:[l.jsx("div",{className:"flex-shrink-0 flex items-center justify-center overflow-hidden",style:{...Td,width:"92px",height:"92px",backgroundColor:"#ffffff"},children:h&&a<2?l.jsx("img",{src:h,alt:t.name,className:"w-full h-full object-contain p-2",loading:"lazy",onError:d}):l.jsx("div",{className:"flex flex-col items-center justify-center",style:{color:"rgba(255,255,255,0.4)"},children:l.jsx("svg",{className:"w-8 h-8",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"font-bold leading-tight",style:{fontSize:"15px",letterSpacing:"-0.01em",...fs.primary},children:f}),t.partNumber&&l.jsx("p",{className:"mt-0.5 text-xs",style:{color:"rgba(255,255,255,0.5)"},children:t.partNumber}),l.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 flex-wrap",children:[t.brand&&l.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5",style:{...ea,color:"rgba(255, 255, 255, 0.9)"},children:[l.jsx("svg",{className:"w-2.5 h-2.5",fill:"currentColor",viewBox:"0 0 20 20",children:l.jsx("path",{fillRule:"evenodd",d:"M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),t.brand]}),t.perCarQty&&t.perCarQty>1&&l.jsxs("span",{className:"inline-flex items-center text-xs font-semibold px-2 py-0.5",style:{...ea,color:"rgba(255, 200, 50, 0.95)"},children:["Qty: ",t.perCarQty]})]}),(t.viscosity||t.volume)&&l.jsx("p",{className:"mt-1 text-xs font-medium",style:{color:"rgba(255, 255, 255, 0.7)"},children:[t.viscosity,t.volume].filter(Boolean).join(" / ")}),l.jsx("p",{className:"font-extrabold mt-2",style:{fontSize:"22px",letterSpacing:"-0.02em",color:"#FFD700",textShadow:"0 2px 6px rgba(0, 0, 0, 0.5), 0 0 12px rgba(255, 215, 0, 0.3)"},children:t.price>0?`$${t.price.toFixed(2)}`:"POA"})]})]}),l.jsx("button",{onClick:u,className:"absolute flex items-center justify-center cursor-pointer",style:{bottom:"12px",right:"12px",background:"linear-gradient(135deg, #22C55E 0%, #16A34A 100%)",border:"1px solid rgba(255, 255, 255, 0.35)",borderRadius:"22px",boxShadow:"0 10px 40px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)",width:"44px",height:"44px",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease-out"},onMouseEnter:y=>{y.currentTarget.style.transform="scale(1.08) translateY(-2px)",y.currentTarget.style.boxShadow="0 14px 48px rgba(34, 197, 94, 0.5), inset 0 1px 0 rgba(255,255,255,0.4)"},onMouseLeave:y=>{y.currentTarget.style.transform="scale(1) translateY(0)",y.currentTarget.style.boxShadow="0 10px 40px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},children:l.jsx("svg",{className:"w-5 h-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M12 4v16m8-8H4"})})}),t.partslotDescription&&l.jsx("div",{className:"mt-3 pt-3",style:{borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:l.jsx("span",{className:"text-xs font-medium",style:{color:"rgba(255, 255, 255, 0.6)"},children:t.partslotDescription})})]})},lo=["SHOE","DRUM"],co=["PAD","ROTOR"];function uo(t){var s,n;const e=((s=t.id)==null?void 0:s.toLowerCase())||"",r=((n=t.title)==null?void 0:n.toLowerCase())||"";return e.includes("rear-brake")||r.includes("rear brake")}function ho(t,e){const r=e==="disc"?lo:co;return t.filter(s=>{const n=s.partslotName.toUpperCase();return!r.some(i=>n.includes(i))})}function fo(t){return t.reduce((e,r)=>e+r.displayPrice,0)}function po(t){const e=t.flatMap(n=>n.products),r=e.some(n=>{const i=n.partslotName.toUpperCase();return n.displayPrice>0&&co.some(a=>i.includes(a))}),s=e.some(n=>{const i=n.partslotName.toUpperCase();return n.displayPrice>0&&lo.some(a=>i.includes(a))});return{hasDisc:r,hasDrum:s}}const vn=(t,e)=>{if(!t||!e)return!1;const r=t.toLowerCase();return e.toLowerCase().replace(/s\b/g,"").split(/\s+/).filter(Boolean).every(n=>r.includes(n))},Ad=(t,e)=>{var n;const r=((n=t.brand)==null?void 0:n.toLowerCase())===e.brand.toLowerCase(),s=Math.abs(t.price-e.price)<1;return r&&s},Cd=({product:t,isSpotlighted:e,spotlightedRef:r,onProductClick:s,onAddToCart:n})=>l.jsx("div",{ref:e?r:void 0,children:l.jsx(oo,{product:t,isSpotlighted:e,onProductClick:s,onAddToCart:n})}),un=({products:t,servicePackages:e,highlightedPartType:r,highlightedProduct:s,scrollToCategory:n,onScrollToCategoryComplete:i,onProductClick:a,onPackageSelect:o,isResearching:c,visible:u=!0,counterHeightPercent:d=22,hasVehicle:h=!1,onAddToCart:g,vehicleMakeModel:f,pendingVariants:y,pendingVariantMake:b,pendingVariantModel:_,onVariantSelect:v})=>{const S=f||"Bob's Shelf",j=ln();ii();const x=p.useRef(null),A=p.useRef({}),k=p.useRef(null),[F,E]=p.useState(null),[O,T]=p.useState({}),[R,N]=p.useState({}),C=p.useMemo(()=>{const $={};return t.forEach(J=>{const B=J.partslotDescription||"Other Parts";$[B]||($[B]=[]),$[B].push(J)}),Object.keys($).sort((J,B)=>J.localeCompare(B)).map(J=>({name:J,products:$[J]}))},[t]);p.useEffect(()=>{if(!r)return;const $=setTimeout(()=>{const ae=Object.entries(A.current);for(const[J,B]of ae)if(B&&vn(J,r)){B.scrollIntoView({behavior:"smooth",block:"start"});break}},300);return()=>clearTimeout($)},[r]),p.useEffect(()=>{if(!n)return;const $=setTimeout(()=>{const ae=Object.entries(A.current);for(const[J,B]of ae)if(B&&vn(J,n)){B.scrollIntoView({behavior:"smooth",block:"start"});break}i==null||i()},300);return()=>clearTimeout($)},[n]);const[L,K]=p.useState(0),H=$=>{const ae=$.currentTarget,J=ae.scrollHeight-ae.clientHeight;if(J>0){const B=ae.scrollTop/J;K(Math.max(0,Math.min(1,B)))}},Y=((y==null?void 0:y.length)??0)>0,Z=t.length>0||e.length>0||Y,W=c&&!Z,V=Z&&!W,ge=u||Z,te=j==="mobile"?92:j==="tablet"?65:70,ie=j==="desktop"?"900px":j==="tablet"?"500px":"100%",ve=j==="mobile"?"calc(8px + env(safe-area-inset-top, 4px))":"6px";return l.jsxs(l.Fragment,{children:[Z&&u&&l.jsx("div",{style:{position:"fixed",right:"2px",top:`calc(${L*65+18}%)`,...Rd,opacity:.8,transition:"top 0.1s ease-out",zIndex:100,pointerEvents:"none"}}),l.jsxs("div",{ref:x,onScroll:H,className:`absolute overflow-y-auto overflow-x-hidden flex flex-col gap-3 md:gap-4 transition-all duration-400 ease-out product-scroll ${ge?"opacity-100 translate-x-0":"opacity-0 translate-x-12 pointer-events-none"}`,style:{width:`${te}%`,maxWidth:ie,right:"0",left:"auto",top:ve,bottom:j==="mobile"?"calc(100px + env(safe-area-inset-bottom, 0px))":"52px",paddingTop:"4px",paddingRight:"16px",paddingLeft:"16px",paddingBottom:"8px",zIndex:55,pointerEvents:"auto",touchAction:"pan-y",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none"},children:[l.jsx("div",{className:"sticky top-0 z-10 -mx-1 px-3 py-2.5",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.85) 0%, rgba(0, 73, 153, 0.9) 100%)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",borderRadius:"24px",boxShadow:"0 10px 40px rgba(0, 102, 204, 0.4)",border:"1px solid rgba(255, 255, 255, 0.25)"},children:l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[c&&Z?l.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:l.jsx("div",{className:"w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin"})}):l.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:l.jsx("svg",{className:"w-3.5 h-3.5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),l.jsx("span",{style:{...fs.primary,fontWeight:700,fontSize:"14px",letterSpacing:"0.025em"},children:c&&Z?"Updating...":S})]}),l.jsxs("span",{style:{color:"rgba(255,255,255,0.8)",fontSize:"12px",fontWeight:500},children:[t.length+e.length," ",t.length+e.length===1?"item":"items"]})]})}),W&&l.jsx("div",{className:"p-5",children:l.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[l.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(0, 102, 204, 0.3)"},children:l.jsx("div",{className:"w-6 h-6 border-2 border-t-transparent rounded-full animate-spin",style:{borderColor:"rgba(255,255,255,0.8)",borderTopColor:"transparent"}})}),l.jsxs("div",{children:[l.jsx("p",{style:{...fs.primary,fontWeight:600,fontSize:"14px"},children:"Searching shelves..."}),l.jsx("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:"Finding the best parts for you"})]})]})}),Y&&y&&v&&l.jsxs("div",{className:"flex flex-col gap-3",children:[l.jsx("div",{className:"sticky top-0 z-10 px-4 py-3",style:{background:"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)",backdropFilter:"blur(20px) saturate(180%)",WebkitBackdropFilter:"blur(20px) saturate(180%)",borderRadius:"20px",boxShadow:"0 8px 32px rgba(0, 102, 204, 0.35)",border:"1px solid rgba(255, 255, 255, 0.2)"},children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center",style:{background:"rgba(255,255,255,0.2)"},children:l.jsx("svg",{className:"w-4 h-4 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),l.jsxs("div",{children:[l.jsxs("span",{className:"text-white font-semibold text-sm",children:["Which ",b," ",_,"?"]}),l.jsx("span",{className:"text-white/70 text-xs block",children:"Tap your variant to continue"})]})]})}),l.jsx("div",{className:"flex flex-col gap-2 px-1",children:(()=>{const $=(y||[]).map(J=>[J.engineCode,J.kw?`${J.kw}kW`:null,J.ccDisplay||(J.cc?`${J.cc}cc`:null),J.fuelType].filter(Boolean).join(" · ")||J.displayTitle),ae=$.reduce((J,B)=>(J[B]=(J[B]||0)+1,J),{});return(y||[]).map((J,B)=>{const Se=$[B],we=ae[Se]>1&&J.displaySubtitle?J.displaySubtitle:Se;return l.jsx("button",{type:"button",onClick:()=>v(J),className:"w-full text-left transition-all duration-200 cursor-pointer rounded-2xl overflow-hidden focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 active:scale-[0.98]",style:{background:"linear-gradient(135deg, rgba(255, 255, 255, 0.92) 0%, rgba(255, 255, 255, 0.85) 100%)",backdropFilter:"blur(12px) saturate(150%)",WebkitBackdropFilter:"blur(12px) saturate(150%)",boxShadow:"0 4px 24px rgba(0, 0, 0, 0.12)",border:"1px solid rgba(255, 255, 255, 0.4)",minHeight:"72px"},children:l.jsxs("div",{className:"flex items-center gap-3 p-4",children:[l.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center shrink-0 font-bold text-lg text-white",style:{background:"linear-gradient(135deg, #0066CC 0%, #0052A3 100%)",boxShadow:"0 2px 8px rgba(0, 102, 204, 0.4)"},children:J.optionNumber}),l.jsx("div",{className:"flex-1 min-w-0",children:l.jsx("p",{className:"font-semibold text-gray-900 text-base leading-tight",children:we})}),l.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{background:"rgba(0, 102, 204, 0.1)"},children:l.jsx("svg",{className:"w-4 h-4 text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M9 5l7 7-7 7"})})})]})},J.vehicle_id)})})()})]}),!W&&!Z&&l.jsx("div",{className:"p-5",children:l.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[l.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center",style:{background:"rgba(255, 149, 0, 0.3)"},children:l.jsx("svg",{className:"w-5 h-5",style:{color:"#FF9500"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),l.jsxs("div",{children:[l.jsx("p",{style:{...fs.primary,fontWeight:600,fontSize:"14px"},children:"No products to display"}),l.jsxs("p",{style:{color:"rgba(255,255,255,0.6)",fontSize:"12px",marginTop:"2px"},children:["Products: ",t.length," | Packages: ",e.length]})]})]})}),V&&e.length>0&&l.jsx("div",{className:"space-y-4",children:e.map($=>{var it,De;const ae=uo($),J=($.preparedTiers||[]).filter(I=>!I.isHidden),{hasDisc:B,hasDrum:Se}=ae?po(J):{hasDisc:!1,hasDrum:!1},ke=ae&&B&&!Se?"disc":ae&&Se&&!B?"drum":R[$.id]||"disc";let we=J;ae&&(we=J.map(I=>{const oe=ho(I.products,ke);return{...I,products:oe,totalPrice:fo(oe),productCount:oe.length}}));const je=((it=we.find(I=>I.isRecommended))==null?void 0:it.tierName)||((De=we[0])==null?void 0:De.tierName)||"",Fe=O[$.id]||je,$e=we.find(I=>I.tierName===Fe),qe=no($.title).split(".")[0]+".",et=F===$.id;return l.jsxs("div",{ref:I=>{A.current[$.title]=I},className:"overflow-hidden transition-all duration-300",style:{background:G.card,borderRadius:"16px",border:`1px solid ${G.border}`,boxShadow:"0 4px 20px rgba(0,0,0,0.08)"},children:[l.jsx("div",{className:"px-4 py-3",style:{background:`linear-gradient(135deg, ${G.primary} 0%, ${G.primaryHover} 100%)`},children:l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 flex items-center justify-center flex-shrink-0",children:l.jsx("svg",{className:"h-5 w-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("h3",{className:"text-white font-bold text-base leading-tight truncate",children:$.title}),$.estimated_time&&l.jsx("div",{className:"flex items-center gap-3 mt-0.5",children:l.jsxs("span",{className:"text-white/70 text-xs flex items-center gap-1",children:[l.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),$.estimated_time]})})]})]})}),l.jsxs("div",{className:"px-4 py-3 border-b",style:{borderColor:G.border},children:[l.jsx("p",{className:"text-sm leading-relaxed",style:{color:G.mutedForeground},children:qe}),ae&&B&&Se&&l.jsxs("div",{className:"mt-2 mb-1",children:[l.jsx("p",{className:"text-[11px] mb-1.5",style:{color:G.mutedForeground},children:"Select your vehicle's rear brake type"}),l.jsxs("div",{className:"flex rounded-xl overflow-hidden border",style:{borderColor:G.border},children:[l.jsx("button",{onClick:()=>N(I=>({...I,[$.id]:"disc"})),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:ke==="disc"?G.primary:"transparent",color:ke==="disc"?"#FFFFFF":G.mutedForeground},children:"Disc Brakes (Pads + Rotors)"}),l.jsx("button",{onClick:()=>N(I=>({...I,[$.id]:"drum"})),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:ke==="drum"?G.primary:"transparent",color:ke==="drum"?"#FFFFFF":G.mutedForeground},children:"Drum Brakes (Shoes + Drums)"})]})]})]}),we.length>0&&l.jsxs("div",{className:"p-3",children:[l.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide mb-2 px-1",style:{color:G.mutedForeground},children:"Choose Your Value Level"}),l.jsx("div",{className:"grid gap-2",style:{gridTemplateColumns:`repeat(${Math.min(we.length,4)}, 1fr)`},children:we.map(I=>{const oe=tn[I.tierName],Ae=I.tierName===Fe;return l.jsxs("div",{onClick:()=>T(M=>({...M,[$.id]:I.tierName})),className:"relative rounded-xl text-center transition-all cursor-pointer",style:{padding:we.length>=4?"6px 4px":"8px",background:I.isRecommended?`${G.primary}10`:Ae?`${G.primary}05`:G.background,border:`2px solid ${I.isRecommended?G.primary:Ae?G.primary+"80":G.border}`},children:[I.isRecommended&&l.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wide whitespace-nowrap",style:{background:G.primary,color:"white"},children:"Carfix Value"}),l.jsxs("p",{className:"text-sm font-bold mt-1",style:{color:(oe==null?void 0:oe.textColor)||G.foreground},children:[oe==null?void 0:oe.emoji," ",I.displayName]}),l.jsx("div",{className:"flex flex-col items-center gap-1 mt-2",style:{minHeight:we.length>=4?"40px":"48px"},children:I.brands.slice(0,1).map((M,ce)=>{const Ce=`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${M.fullName.replace(/\s+/g,"")}.jpg`;return l.jsx("div",{className:"w-full bg-white rounded-lg flex items-center justify-center overflow-hidden",style:{height:we.length>=4?"36px":"44px",maxWidth:we.length>=4?"64px":"80px",boxShadow:"0 2px 8px rgba(0,0,0,0.1)",border:"1px solid #F1F5F9"},children:l.jsx("img",{src:M.imageUrl,alt:M.fullName,className:"w-auto object-contain",style:{height:we.length>=4?"26px":"32px"},onError:Xe=>{const be=Xe.target;be.src!==Ce?be.src=Ce:(be.style.display="none",be.parentElement.innerHTML=`<span class="text-[10px] font-semibold text-gray-600 truncate px-1">${M.fullName}</span>`)}})},ce)})}),l.jsxs("p",{className:"text-[10px] mt-2",style:{color:G.mutedForeground},children:[I.productCount," ",I.productCount===1?"part":"parts"]}),I.savingsAmount&&I.savingsAmount>0?l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"text-[11px] line-through",style:{color:G.mutedForeground},children:nt(I.originalTotalPrice)}),l.jsx("p",{className:"text-base font-bold",style:{color:G.success},children:nt(I.totalPrice)}),l.jsxs("p",{className:"text-[9px] font-semibold px-1.5 py-0.5 rounded-full mt-0.5",style:{background:`${G.success}15`,color:G.success},children:["SAVE ",nt(I.savingsAmount)," — ",I.bundleDiscountPercentage,"% Bundle Deal"]})]}):l.jsx("p",{className:"text-base font-bold mt-1",style:{color:G.foreground},children:nt(I.totalPrice)}),l.jsx("p",{className:"text-[10px]",style:{color:G.mutedForeground},children:"inc GST"}),l.jsx("button",{onClick:M=>{M.stopPropagation();const ce=I.bundleDiscountPercentage||0,Ce=1-ce/100,Xe=I.products.map(be=>({id:be.sku,name:be.name,brand:be.brand,price:ce>0?Math.round(be.displayPrice*Ce*100)/100:be.displayPrice,sku:be.sku,partNumber:be.partNumber||void 0,image_url:be.productImageUrl,partslotDescription:be.partslotName,quantity:1,_bundleMeta:{is_bundle_item:!0,bundle_discount_percentage:ce,service_package_name:$.title,service_package_id:$.id,quality_tier:I.tierName}}));g==null||g(Xe)},className:"w-full mt-2 py-1.5 rounded-lg text-[10px] font-semibold transition-all",style:{background:I.isRecommended?G.success:"#F1F5F9",color:I.isRecommended?"white":G.success,border:I.isRecommended?"none":"1px solid #E2E8F0",textAlign:"center"},children:"Add"})]},I.tierName)})})]}),l.jsxs("div",{onClick:()=>E(et?null:$.id),className:"flex items-center justify-center gap-1.5 py-2 cursor-pointer hover:bg-gray-50 transition-colors border-t",style:{borderColor:G.border},children:[l.jsx("span",{className:"text-xs",style:{color:G.mutedForeground},children:et?"Hide details":"Show details"}),l.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${et?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",style:{color:G.mutedForeground},children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),et&&$e&&l.jsx("div",{className:"px-4 pb-4 border-t animate-in slide-in-from-top-2 duration-200",style:{borderColor:G.border},children:l.jsxs("div",{className:"pt-3",children:[l.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide mb-3",style:{color:G.mutedForeground},children:[$e.displayName," Tier Products"]}),l.jsx("div",{className:"space-y-2",children:$e.products.map(I=>l.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg",style:{background:G.background,border:`1px solid ${G.border}`},children:[l.jsx("div",{className:"flex-shrink-0 bg-white rounded-lg overflow-hidden flex items-center justify-center",style:{width:"56px",height:"56px",minWidth:"56px",maxWidth:"56px"},children:I.productImageUrl?l.jsx("img",{src:I.productImageUrl,alt:I.name,className:"object-contain",style:{width:"100%",height:"100%",maxWidth:"56px",maxHeight:"56px",padding:"4px"}}):l.jsx("svg",{className:"w-6 h-6 text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"text-xs font-medium truncate",style:{color:G.foreground},children:I.name}),l.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[l.jsx("span",{className:"text-[10px]",style:{color:G.mutedForeground},children:I.brand}),I.isRotor&&l.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 font-medium",children:"Pair"})]}),l.jsx("p",{className:"text-[10px] mt-0.5",style:{color:G.mutedForeground},children:I.partslotName})]}),l.jsxs("div",{className:"text-right flex-shrink-0",children:[l.jsx("p",{className:"text-sm font-bold",style:{color:G.primary},children:nt(I.displayPrice)}),I.isRotor&&l.jsxs("p",{className:"text-[9px]",style:{color:G.mutedForeground},children:["$",I.price.toFixed(2)," ea"]})]})]},I.sku))})]})})]},$.id)})}),V&&C.map(({name:$,products:ae})=>{const J=r&&vn($,r);return l.jsxs("section",{ref:B=>{A.current[$]=B},className:"transition-all duration-300",style:{background:"transparent",borderRadius:"24px"},children:[l.jsxs("div",{"data-testid":"partslot-header","data-partslot-name":$,className:"px-3 py-2.5 flex items-center justify-between",style:{background:J?"rgba(0, 102, 204, 0.95)":"rgba(0, 51, 102, 0.9)",borderRadius:"16px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",marginBottom:"8px"},children:[l.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[l.jsx("div",{className:"w-5 h-5 rounded-md flex items-center justify-center flex-shrink-0",style:{background:J?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 1) 100%)":"rgba(255,255,255,0.2)"},children:l.jsx("svg",{className:"h-3 w-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),l.jsx("span",{className:"text-xs font-bold truncate uppercase tracking-wide",style:{color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)"},children:$})]}),l.jsx("span",{className:"text-[10px] font-bold px-2.5 py-1 rounded-full flex-shrink-0",style:{background:"rgba(255, 149, 0, 0.9)",color:"white",boxShadow:"0 2px 8px rgba(255, 149, 0, 0.4)"},children:ae.length})]}),l.jsx("div",{className:"flex flex-col gap-3",children:ae.map((B,Se)=>{const ke=!!(s&&Ad(B,s));return l.jsx("div",{"data-testid":"partslot-product",children:l.jsx(Cd,{product:B,isSpotlighted:ke,spotlightedRef:k,onProductClick:a,onAddToCart:g,viewportSize:j})},`${B.id}-${Se}`)})})]},$)}),l.jsx("div",{className:"h-4"})]})]})},ai=({onTranscript:t,onSpeechEnd:e,language:r="en-NZ",mode:s="toggle"}={})=>{const[n,i]=p.useState(!1),[a,o]=p.useState(""),[c,u]=p.useState(""),[d,h]=p.useState(null),[g,f]=p.useState(!1),y=p.useRef(null),b=p.useRef(""),_=p.useRef(t),v=p.useRef(e),S=p.useRef(null),j=15e3;p.useEffect(()=>{_.current=t,v.current=e},[t,e]),p.useEffect(()=>{if(typeof window<"u"&&window.location.protocol!=="https:"&&window.location.hostname!=="localhost"&&window.location.hostname!=="127.0.0.1"){console.warn("[BobWidget] Speech recognition requires HTTPS. PTT will not work on HTTP."),h("Voice input requires a secure connection (HTTPS)"),f(!1);return}const F=window.SpeechRecognition||window.webkitSpeechRecognition;if(F){f(!0);const E=new F;E.continuous=s==="ptt",E.interimResults=!0,E.lang=r,E.maxAlternatives=1,E.onstart=()=>{i(!0),h(null)},E.onresult=O=>{let T="",R="";for(let N=O.resultIndex;N<O.results.length;N++){const C=O.results[N][0].transcript;O.results[N].isFinal?R+=C:T+=C}R&&(b.current=R,o(R),_.current&&_.current(R)),u(T)},E.onerror=O=>{switch(i(!1),O.error){case"no-speech":h("No speech detected. Please try again.");break;case"audio-capture":h("No microphone found. Please check your device.");break;case"not-allowed":h("Microphone permission denied. Please allow access.");break;default:h("Speech recognition error. Please try again.")}},E.onend=()=>{S.current&&(clearTimeout(S.current),S.current=null),i(!1),u(""),b.current&&v.current&&v.current(b.current),b.current=""},y.current=E}return()=>{y.current&&y.current.stop()}},[r,s]);const x=()=>{if(y.current&&!n){o(""),u(""),h(null),S.current=setTimeout(()=>{console.warn("[SpeechRecognition] Safety timeout - forcing stop after 15s"),y.current&&y.current.abort(),i(!1),u("")},j);try{y.current.start()}catch(F){console.warn("[SpeechRecognition] start() failed (already running):",F),S.current&&(clearTimeout(S.current),S.current=null)}}},A=()=>{S.current&&(clearTimeout(S.current),S.current=null),y.current&&n&&y.current.stop()};return{isListening:n,transcript:a,interimTranscript:c,error:d,isSupported:g,startListening:x,stopListening:A,toggleListening:()=>{n?A():x()}}},go=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:o,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,onAddToCart:g,onProductClick:f,onQuickReply:y,onInterrupt:b,counterHeightPercent:_=22})=>{var ve;const[v,S]=p.useState(!1),j=p.useRef(null),x=p.useRef(!1),{bottomOffset:A,zIndexBase:k}=si(),{isListening:F,interimTranscript:E,error:O,isSupported:T,startListening:R,stopListening:N}=ai({onTranscript:$=>r($),language:"en-NZ",mode:"ptt"});p.useEffect(()=>{E&&r(E)},[E,r]);const C=h?"speaking":s?"processing":F?"listening":"idle",L=p.useCallback($=>{if($.preventDefault(),C==="speaking"){b==null||b();return}s||x.current||(x.current=!0,navigator.vibrate&&navigator.vibrate(30),R())},[C,s,R,b]),K=p.useCallback(()=>{x.current&&(x.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),N(),setTimeout(()=>{n()},150))},[N,n]),H=[...t].reverse().find($=>$.role==="assistant"),Y=((ve=H==null?void 0:H.suggestedProducts)==null?void 0:ve.length)||0,Z=H!=null&&H.content?H.content.length>50?H.content.slice(0,50)+"...":H.content:"Ask Bob about car parts...",W=Y>0?` (${Y} products)`:"",V={idle:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.9) 0%, rgba(22, 163, 74, 0.95) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 8px 32px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},active:{background:"linear-gradient(135deg, rgba(255, 149, 0, 0.95) 0%, rgba(230, 134, 0, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(255, 149, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.3)"},disabled:{background:"rgba(156, 163, 175, 0.5)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"32px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)"}},te={idle:V.idle,listening:V.active,processing:V.disabled,speaking:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.95) 0%, rgba(22, 163, 74, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"32px",boxShadow:"0 12px 48px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"}}[C],ie={idle:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-breathe 2s ease-in-out infinite"},listening:null,processing:{border:"2px solid rgba(156, 163, 175, 0.6)",animation:"ring-processing 1.5s ease-in-out infinite"},speaking:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-speaking 1.8s ease-in-out infinite"}};return l.jsxs("div",{ref:j,style:{position:"fixed",bottom:A,left:0,right:0,...ao,background:"rgba(15, 23, 42, 0.92)",borderRadius:"28px 28px 0 0",borderBottom:"none",transition:"all 0.3s ease-out",boxShadow:"0 -10px 40px rgba(0, 0, 0, 0.3)",height:v?"55vh":"90px",zIndex:k+80,paddingBottom:"env(safe-area-inset-bottom, 8px)"},children:[l.jsx("button",{onClick:()=>S(!v),style:{position:"absolute",top:"-20px",left:"50%",transform:"translateX(-50%)",background:"rgba(255, 255, 255, 0.15)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"9999px",padding:"6px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)",zIndex:k+90,cursor:"pointer",minHeight:"unset",minWidth:"unset"},"aria-label":v?"Collapse chat":"Expand chat",children:v?l.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}):l.jsx("svg",{style:{height:"16px",width:"16px",color:"rgba(255,255,255,0.8)"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 15l7-7 7 7"})})}),!v&&l.jsx("div",{onClick:()=>S(!0),style:{padding:"8px 12px 2px 12px",cursor:"pointer"},children:l.jsxs("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Z,W&&l.jsx("span",{style:{color:"rgba(255,200,0,0.9)",fontWeight:600},children:W})]})}),v&&l.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px"},className:"glass-scroll",children:[[...t].reverse().map(($,ae)=>{var J;return l.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:$.role==="user"?"flex-end":"flex-start"},children:l.jsxs("div",{style:{maxWidth:(J=$.suggestedProducts)!=null&&J.length?"100%":"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:$.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)":"rgba(255, 255, 255, 0.12)",backdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",color:"rgba(255, 255, 255, 0.95)",textShadow:"0 1px 2px rgba(0,0,0,0.2)"},children:[$.content,$.role==="assistant"&&$.suggestedProducts&&$.suggestedProducts.length>0&&l.jsx(ni,{products:$.suggestedProducts,title:$.suggestionsTitle,onAddToCart:g,onProductClick:f}),$.role==="assistant"&&$.quickReplies&&$.quickReplies.length>0&&l.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"8px"},children:$.quickReplies.map((B,Se)=>l.jsx("button",{onClick:ke=>{ke.stopPropagation(),b==null||b(),y==null||y(B.url)},style:{padding:"6px 14px",borderRadius:"20px",border:"1px solid rgba(0,102,204,0.6)",background:"rgba(0,102,204,0.15)",color:"white",fontSize:"13px",fontWeight:600,cursor:"pointer",backdropFilter:"blur(8px)",WebkitBackdropFilter:"blur(8px)",minHeight:"unset",minWidth:"unset"},children:B.label},Se))})]})},ae)}),l.jsx("div",{ref:c})]}),T&&l.jsxs("div",{style:{display:"flex",justifyContent:"center",padding:"12px 16px 8px 16px",position:"relative"},children:[C==="listening"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite",opacity:0,pointerEvents:"none"}}),l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite 0.5s",opacity:0,pointerEvents:"none"}})]}),C!=="listening"&&ie[C]&&l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:ie[C].border,transform:"translate(-50%, -50%)",animation:ie[C].animation,pointerEvents:"none"}}),l.jsx("button",{onTouchStart:L,onTouchEnd:K,onTouchCancel:K,onMouseDown:L,onMouseUp:K,onMouseLeave:K,onClick:F?K:void 0,disabled:C==="processing","aria-label":"Hold to talk to Bob",className:"glass-button bob-ptt-btn",style:{width:"200px",height:"64px",minHeight:"unset",minWidth:"unset",display:"flex",alignItems:"center",justifyContent:"center",userSelect:"none",touchAction:"none",cursor:C==="processing"?"not-allowed":"pointer",opacity:C==="processing"?.6:1,transform:C==="listening"?"scale(1.04)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease, background 0.3s ease",backdropFilter:te.backdropFilter,WebkitBackdropFilter:te.WebkitBackdropFilter,"--bob-ptt-bg":te.background,"--bob-ptt-shadow":te.boxShadow,"--bob-ptt-border":te.border,"--bob-ptt-radius":"32px"},title:"Hold to talk",children:l.jsx("span",{style:{fontSize:"22px",fontWeight:800,letterSpacing:"0.15em",...fs.primary,textTransform:"uppercase",fontFamily:"system-ui, -apple-system, sans-serif"},children:C==="listening"?"LISTENING":C==="processing"?"THINKING":C==="speaking"?"TAP TO STOP":"TALK"})})]}),l.jsxs("div",{style:{padding:"4px 12px 8px 12px",borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:[O&&l.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:O}),l.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[d&&l.jsx("button",{onClick:d,style:{flexShrink:0,height:"40px",width:"40px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"12px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:h?"#0066CC":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:u?"Unmute":"Mute",children:u?l.jsxs("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):l.jsx("svg",{style:{height:"18px",width:"18px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),l.jsxs("div",{style:{flex:1,position:"relative",height:"40px"},children:[l.jsx("input",{type:"text",value:e,onChange:$=>r($.target.value),onKeyPress:i,onFocus:a,onBlur:o,placeholder:"Message Bob...",disabled:C!=="idle",className:"high-contrast-input bob-chat-input",style:{width:"100%",height:"40px",fontSize:"16px",padding:"0 14px",background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",color:"#0F172A",outline:"none",opacity:C!=="idle"?0:1,transition:"opacity 0.15s ease"}}),C!=="idle"&&l.jsxs("div",{className:"bob-state-overlay",style:{position:"absolute",inset:0,background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",display:"flex",alignItems:"center",padding:"0 14px",gap:"8px"},children:[C==="listening"&&l.jsxs(l.Fragment,{children:[l.jsx("span",{style:{width:"10px",height:"10px",borderRadius:"50%",backgroundColor:"#FF8C00",animation:"dot-pulse 1s ease-in-out infinite",flexShrink:0}}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Listening..."})]}),C==="processing"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{width:"18px",height:"18px",flexShrink:0,border:"2px solid rgba(15, 23, 42, 0.15)",borderTop:"2px solid #0F172A",borderRadius:"50%",animation:"processing-spin 0.8s linear infinite"}}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is researching your input."})]}),C==="speaking"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{display:"flex",alignItems:"center",gap:"2px",height:"20px",flexShrink:0},children:[0,.15,.3,.45,.6].map(($,ae)=>l.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${$}s infinite`}},ae))}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is talking..."}),u&&l.jsxs("svg",{style:{height:"16px",width:"16px",color:"#ef4444",marginLeft:"auto",flexShrink:0},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]})]})]})]})]})]})]})},bo=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,messages:i,input:a,setInput:o,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:g,chatEndRef:f,isMuted:y,onToggleMute:b,isSpeaking:_,products:v,servicePackages:S,highlightedPartType:j,highlightedProduct:x,scrollToCategory:A,onScrollToCategoryComplete:k,onProductClick:F,onPackageSelect:E,isResearching:O,onAddToCart:T,onQuickReply:R,onInterrupt:N,vehicle:C,onChangeVehicle:L,pendingVariants:K,pendingVariantMake:H,pendingVariantModel:Y,onVariantSelect:Z,bobOffset:W=0,bobScale:V=100,embedded:ge=!1})=>{console.log("[MobileBobLayout] Rendering with:",{currentImage:(t==null?void 0:t.substring(0,50))||"EMPTY",backdropUrl:(r==null?void 0:r.substring(0,50))||"NONE",counterOverlayUrl:(s==null?void 0:s.substring(0,50))||"NONE"});const te=ln(),[ie,ve]=p.useState("center"),[$,ae]=p.useState("hidden"),J=v.length>0||S.length>0,B=((K==null?void 0:K.length)??0)>0,Se=J||B,je=(()=>{switch(te){case"desktop":return 70;case"tablet":return 80;case"mobile":return 140;default:return 140}})()*V/100;p.useEffect(()=>{if(O&&$!=="loading"&&$!=="visible")ae("loading"),ie==="center"&&ve("partial-left");else if(Se&&$!=="visible")if(ie==="center"){ve("partial-left"),ae("transitioning");const $e=setTimeout(()=>{ae("visible")},400);return()=>clearTimeout($e)}else ae("visible");else!Se&&!O&&$!=="hidden"&&(ae("hidden"),ve("center"))},[Se,O,$,ie]);const Fe=$!=="hidden";return l.jsxs("div",{className:ge?"absolute inset-0 overflow-hidden":"fixed inset-0 overflow-hidden",style:{height:ge?"100%":"100dvh",touchAction:"manipulation"},children:[r&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"absolute inset-0 z-0",style:{backgroundImage:`url(${r})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:"blur(var(--bob-blur-intensity, 0px)) brightness(0.95)",transform:"scale(1.02)"}}),l.jsx("div",{className:"absolute inset-0 z-[1]",style:{background:"rgba(0, 0, 0, var(--bob-overlay-opacity, 0.1))"}})]}),l.jsx(cn,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:je,position:ie,verticalOffset:W}),l.jsx(un,{products:v,servicePackages:S,highlightedPartType:j,highlightedProduct:x,scrollToCategory:A,onScrollToCategoryComplete:k,onProductClick:F,onPackageSelect:E,isResearching:O,visible:Fe,counterHeightPercent:n,hasVehicle:!!C,onAddToCart:T,pendingVariants:K,pendingVariantMake:H,pendingVariantModel:Y,onVariantSelect:Z}),l.jsx(go,{messages:i,input:a,setInput:o,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:g,chatEndRef:f,isMuted:y,onToggleMute:b,isSpeaking:_,onAddToCart:T,onProductClick:F,onQuickReply:R,onInterrupt:N,counterHeightPercent:n})]})},mo=({messages:t,input:e,setInput:r,isLoading:s,onSend:n,onKeyPress:i,onInputFocus:a,onInputBlur:o,chatEndRef:c,isMuted:u=!1,onToggleMute:d,isSpeaking:h=!1,onQuickReply:g,onInterrupt:f,counterHeightPercent:y=22})=>{const[b,_]=p.useState(!1),v=p.useRef(null),S=p.useRef(!1),{bottomOffset:j,zIndexBase:x}=si(),{isListening:A,interimTranscript:k,error:F,isSupported:E,startListening:O,stopListening:T}=ai({onTranscript:V=>r(V),language:"en-NZ",mode:"ptt"});p.useEffect(()=>{k&&r(k)},[k,r]);const R=h?"speaking":s?"processing":A?"listening":"idle",N=p.useCallback(V=>{if(V.preventDefault(),R==="speaking"){f==null||f();return}s||S.current||(S.current=!0,navigator.vibrate&&navigator.vibrate(30),O())},[R,s,O,f]),C=p.useCallback(()=>{S.current&&(S.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),T(),setTimeout(()=>{n()},150))},[T,n]),L=[...t].reverse().find(V=>V.role==="assistant"),K=L!=null&&L.content?L.content.length>50?L.content.slice(0,50)+"...":L.content:"Ask Bob about car parts...",H={idle:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.9) 0%, rgba(22, 163, 74, 0.95) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 8px 32px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"},active:{background:"linear-gradient(135deg, rgba(255, 149, 0, 0.95) 0%, rgba(230, 134, 0, 1) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 12px 48px rgba(255, 149, 0, 0.5), inset 0 1px 0 rgba(255,255,255,0.3)"},disabled:{background:"rgba(156, 163, 175, 0.5)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"50%",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.2)"}},Z={idle:H.idle,listening:H.active,processing:H.disabled,speaking:{background:"linear-gradient(135deg, rgba(34, 197, 94, 0.9) 0%, rgba(22, 163, 74, 0.95) 100%)",backdropFilter:"blur(16px) saturate(180%)",WebkitBackdropFilter:"blur(16px) saturate(180%)",border:"1px solid rgba(255, 255, 255, 0.4)",borderRadius:"50%",boxShadow:"0 12px 48px rgba(34, 197, 94, 0.4), inset 0 1px 0 rgba(255,255,255,0.3)"}}[R],W={idle:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-breathe 2s ease-in-out infinite"},listening:null,processing:{border:"2px solid rgba(156, 163, 175, 0.6)",animation:"ring-processing 1.5s ease-in-out infinite"},speaking:{border:"2px solid rgba(34, 197, 94, 0.5)",animation:"ring-speaking 1.8s ease-in-out infinite"}};return l.jsxs("div",{ref:v,style:{position:"absolute",bottom:0,left:0,right:0,top:"auto",contain:"layout",transform:"translateZ(0)",WebkitTransform:"translateZ(0)",backfaceVisibility:"hidden",WebkitBackfaceVisibility:"hidden",isolation:"isolate",...ao,background:"rgba(15, 23, 42, 0.92)",borderRadius:"28px 28px 0 0",borderBottom:"none",transition:"height 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 -10px 40px rgba(0, 0, 0, 0.3)",height:b?"55%":"110px",overflow:"visible",zIndex:x+30,paddingBottom:"calc(8px + env(safe-area-inset-bottom, 0px))",pointerEvents:"none"},children:[l.jsx("button",{onClick:()=>_(!b),style:{position:"absolute",top:"-24px",left:"50%",transform:"translateX(-50%)",background:"rgba(0, 102, 204, 0.9)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"2px solid rgba(255, 255, 255, 0.35)",borderRadius:"9999px",padding:"8px",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.3)",zIndex:x+40,cursor:"pointer",minHeight:"32px",minWidth:"32px",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto"},"aria-label":b?"Collapse chat":"Expand chat",children:b?l.jsx("svg",{style:{height:"16px",width:"16px",color:"white"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M19 9l-7 7-7-7"})}):l.jsx("svg",{style:{height:"16px",width:"16px",color:"white"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M5 15l7-7 7 7"})})}),!b&&l.jsx("div",{onClick:()=>_(!0),style:{padding:"6px 12px 4px 12px",height:"26px",overflow:"hidden",cursor:"pointer",pointerEvents:"auto"},children:l.jsx("p",{style:{fontSize:"12px",color:"white",textShadow:"0 1px 3px rgba(0,0,0,0.6)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:K})}),b&&l.jsxs("div",{style:{height:"calc(100% - 100px)",overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"8px",pointerEvents:"auto"},className:"glass-scroll",children:[[...t].reverse().map((V,ge)=>l.jsx("div",{style:{display:"flex",justifyContent:V.role==="user"?"flex-end":"flex-start"},children:l.jsxs("div",{style:{maxWidth:"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:V.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9) 0%, rgba(0, 73, 153, 0.95) 100%)":"rgba(255, 255, 255, 0.12)",backdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.2)",color:"rgba(255, 255, 255, 0.95)",textShadow:"0 1px 2px rgba(0,0,0,0.2)"},children:[V.content,V.role==="assistant"&&V.quickReplies&&V.quickReplies.length>0&&l.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"8px"},children:V.quickReplies.map((te,ie)=>l.jsx("button",{onClick:ve=>{ve.stopPropagation(),f==null||f(),g==null||g(te.url)},style:{padding:"6px 14px",borderRadius:"20px",border:"1px solid rgba(0,102,204,0.6)",background:"rgba(0,102,204,0.15)",color:"white",fontSize:"13px",fontWeight:600,cursor:"pointer",backdropFilter:"blur(8px)",WebkitBackdropFilter:"blur(8px)",minHeight:"unset",minWidth:"unset"},children:te.label},ie))})]})},ge)),l.jsx("div",{ref:c})]}),l.jsxs("div",{style:{padding:b?"8px 12px 4px 12px":"4px 12px 4px 12px",borderTop:b?"1px solid rgba(255, 255, 255, 0.15)":"none",pointerEvents:"auto"},children:[F&&l.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:F}),l.jsxs("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[d&&b&&l.jsx("button",{onClick:d,style:{flexShrink:0,height:"36px",width:"36px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"10px",background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(8px)",color:h?"#22c55e":"rgba(255,255,255,0.7)",cursor:"pointer",border:"1px solid rgba(255, 255, 255, 0.2)",minHeight:"unset",minWidth:"unset"},title:u?"Unmute":"Mute",children:u?l.jsxs("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):l.jsx("svg",{style:{height:"16px",width:"16px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"})})}),l.jsxs("div",{style:{flex:1,position:"relative",height:"40px"},children:[l.jsx("input",{type:"text",value:e,onChange:V=>r(V.target.value),onKeyPress:i,onFocus:a,onBlur:o,placeholder:"Message Bob...",disabled:R!=="idle",className:"high-contrast-input bob-chat-input",style:{width:"100%",height:"40px",fontSize:"16px",padding:"0 14px",background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",color:"#0F172A",outline:"none",opacity:R!=="idle"?0:1,transition:"opacity 0.15s ease"}}),R!=="idle"&&l.jsxs("div",{className:"bob-state-overlay",style:{position:"absolute",inset:0,background:"#FFFFFF",border:"2px solid rgba(15, 23, 42, 0.15)",borderRadius:"20px",display:"flex",alignItems:"center",padding:"0 14px",gap:"8px"},children:[R==="listening"&&l.jsxs(l.Fragment,{children:[l.jsx("span",{style:{width:"10px",height:"10px",borderRadius:"50%",backgroundColor:"#FF8C00",animation:"dot-pulse 1s ease-in-out infinite",flexShrink:0}}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Listening..."})]}),R==="processing"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{width:"18px",height:"18px",flexShrink:0,border:"2px solid rgba(15, 23, 42, 0.15)",borderTop:"2px solid #0F172A",borderRadius:"50%",animation:"processing-spin 0.8s linear infinite"}}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is researching your input."})]}),R==="speaking"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{display:"flex",alignItems:"center",gap:"2px",height:"20px",flexShrink:0},children:[0,.15,.3,.45,.6].map((V,ge)=>l.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${V}s infinite`}},ge))}),l.jsx("span",{style:{fontSize:"14px",color:"#0F172A",fontWeight:500},children:"Bob is talking..."}),u&&l.jsxs("svg",{style:{height:"16px",width:"16px",color:"#ef4444",marginLeft:"auto",flexShrink:0},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]})]})]})]}),E&&l.jsxs("div",{style:{position:"relative",marginLeft:"4px"},children:[R==="listening"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite",opacity:0,pointerEvents:"none"}}),l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:"2px solid #FF9500",transform:"translate(-50%, -50%)",animation:"ptt-wave 1.5s ease-out infinite 0.5s",opacity:0,pointerEvents:"none"}})]}),R!=="listening"&&W[R]&&l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:W[R].border,transform:"translate(-50%, -50%)",animation:W[R].animation,pointerEvents:"none"}}),l.jsxs("button",{onTouchStart:N,onTouchEnd:C,onTouchCancel:C,onMouseDown:N,onMouseUp:C,onMouseLeave:C,disabled:R==="processing","aria-label":"Hold to talk to Bob",className:"glass-button bob-ptt-btn",style:{position:"relative",flexShrink:0,height:"72px",width:"72px",minHeight:"unset",minWidth:"unset",display:"flex",alignItems:"center",justifyContent:"center",userSelect:"none",touchAction:"none",color:"white",cursor:R==="processing"?"not-allowed":"pointer",opacity:R==="processing"?.6:1,transform:R==="listening"?"scale(1.08)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease, background 0.3s ease",zIndex:x+45,backdropFilter:Z.backdropFilter,WebkitBackdropFilter:Z.WebkitBackdropFilter,"--bob-ptt-bg":Z.background,"--bob-ptt-shadow":Z.boxShadow,"--bob-ptt-border":Z.border,"--bob-ptt-radius":"50%"},title:"Hold to talk",children:[l.jsx("svg",{style:{height:"28px",width:"28px",filter:"drop-shadow(0 1px 2px rgba(0, 0, 0, 0.2))"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"})}),R==="listening"&&l.jsx("div",{style:{position:"absolute",top:"8px",right:"8px",width:"12px",height:"12px",borderRadius:"50%",backgroundColor:"#fef3c7",animation:"ptt-dot 0.6s ease-in-out infinite alternate"}})]})]})]})]})]})},Od=({product:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{const n=t.productUrl||t.product_url,i=t.partNumber||t.part_number,a=!!n||!!s;return l.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-white/95 backdrop-blur-md overflow-hidden",children:[l.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-gray-200 bg-white/80 backdrop-blur-sm",children:l.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-blue-600 font-medium text-sm hover:text-blue-700 active:scale-95 transition-all",children:[l.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back to Products"]})}),l.jsxs("div",{className:"flex-1 overflow-y-auto",children:[l.jsx("div",{className:"aspect-square bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center",children:t.image_url?l.jsx("img",{src:t.image_url,alt:t.name,className:"w-full h-full object-contain p-4"}):l.jsxs("div",{className:"flex flex-col items-center justify-center text-gray-400",children:[l.jsx("svg",{className:"h-16 w-16 mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})}),l.jsx("span",{className:"text-sm font-medium uppercase tracking-wide",children:"No Image Available"})]})}),l.jsxs("div",{className:"p-4 space-y-4",children:[l.jsxs("div",{children:[l.jsx("h1",{className:"text-xl font-bold text-gray-900 mb-1",children:t.name}),t.brand&&l.jsx("p",{className:"text-sm text-gray-600 font-medium",children:t.brand})]}),l.jsxs("div",{className:"bg-blue-50 rounded-xl p-4",children:[l.jsx("p",{className:"text-sm text-gray-600 mb-1",children:"Price"}),l.jsx("p",{className:"text-2xl font-bold text-blue-600",children:t.price>0?`$${t.price.toFixed(2)}`:"Price on Request"}),t.price>0&&l.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Inc. GST"})]}),l.jsxs("div",{className:"space-y-3",children:[t.partslotDescription&&l.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[l.jsx("span",{className:"text-sm text-gray-500",children:"Category"}),l.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.partslotDescription})]}),t.sku&&l.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[l.jsx("span",{className:"text-sm text-gray-500",children:"SKU"}),l.jsx("span",{className:"text-sm font-medium text-gray-900",children:t.sku})]}),i&&l.jsxs("div",{className:"flex justify-between py-2 border-b border-gray-100",children:[l.jsx("span",{className:"text-sm text-gray-500",children:"Part Number"}),l.jsx("span",{className:"text-sm font-medium text-gray-900",children:i})]})]}),a&&l.jsx("a",{href:n||"#",onClick:o=>{s&&(o.preventDefault(),s(t))},target:n&&!s?"_blank":void 0,rel:n&&!s?"noopener noreferrer":void 0,className:"block text-center text-blue-600 text-sm font-medium hover:underline py-2",children:"View Full Details on CARFIX →"})]})]}),l.jsx("div",{className:"p-4 border-t border-gray-200 bg-white/95 backdrop-blur-sm",children:l.jsx("button",{onClick:()=>r==null?void 0:r(t),className:"w-full bg-blue-600 text-white text-base font-semibold py-3 rounded-xl hover:bg-blue-700 active:bg-blue-800 transition-colors shadow-lg",children:"Add to Cart"})})]})},yo=({package:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{var j;const[n,i]=p.useState(!1),a=p.useMemo(()=>uo(t),[t.id,t.title]),{hasDisc:o,hasDrum:c}=p.useMemo(()=>{if(!a||!t.preparedTiers)return{hasDisc:!1,hasDrum:!1};const x=t.preparedTiers.filter(A=>!A.isHidden);return po(x)},[a,t.preparedTiers]),[u,d]=p.useState("disc"),h=p.useMemo(()=>!a||o&&!c?"disc":c&&!o?"drum":u,[a,o,c,u]),g=a&&o&&c,f=p.useMemo(()=>{if(!t.preparedTiers||t.preparedTiers.length===0)return[];const x=t.preparedTiers.filter(A=>!A.isHidden);return a?x.map(A=>{const k=ho(A.products,h);return{...A,products:k,totalPrice:fo(k),productCount:k.length}}):x},[t.preparedTiers,a,h]),y=f.length>0,b=x=>{const A=x.bundleDiscountPercentage||0,k=1-A/100,F=x.products.map(E=>({...E,displayPrice:A>0?Math.round(E.displayPrice*k*100)/100:E.displayPrice,_bundleMeta:{is_bundle_item:!0,bundle_discount_percentage:A,service_package_name:t.title,service_package_id:t.id,quality_tier:x.tierName}}));r==null||r(F)},_=x=>x===2?"grid-cols-2":x===3?"grid-cols-3":"grid-cols-2",v=no(t.title),S=((j=f[0])==null?void 0:j.productCount)||0;return l.jsxs("div",{className:"absolute inset-0 z-35 flex flex-col bg-[#FAFAFA] overflow-hidden",children:[l.jsx("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[#E2E8F0] bg-white shadow-sm",children:l.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-[#0052CC] font-medium text-sm hover:text-[#0047B3] active:scale-95 transition-all",children:[l.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),"Back"]})}),l.jsxs("div",{className:"flex-1 overflow-y-auto",children:[l.jsxs("div",{className:"px-4 pt-4 pb-4",style:{background:"linear-gradient(135deg, rgba(0,82,204,0.05) 0%, rgba(56,189,248,0.05) 100%)"},children:[l.jsxs("div",{className:"flex items-start gap-3",children:[l.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center flex-shrink-0 bg-white shadow-md",children:t.icon_url?l.jsx("img",{src:t.icon_url,alt:"",className:"w-8 h-8 object-contain"}):l.jsx("svg",{className:"w-7 h-7 text-[#0052CC]",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("h1",{className:"text-xl font-bold text-[#0F172A]",children:t.title}),l.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-[#64748B]",children:[t.estimated_time&&l.jsxs("span",{className:"flex items-center gap-1",children:[l.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),t.estimated_time]}),t.difficulty_level&&l.jsxs("span",{className:"flex items-center gap-1",children:[l.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11.42 15.17L17.25 21A2.652 2.652 0 0021 17.25l-5.877-5.877M11.42 15.17l2.496-3.03c.317-.384.74-.626 1.208-.766M11.42 15.17l-4.655 5.653a2.548 2.548 0 11-3.586-3.586l6.837-5.63m5.108-.233c.55-.164 1.163-.188 1.743-.14a4.5 4.5 0 004.486-6.336l-3.276 3.277a3.004 3.004 0 01-2.25-2.25l3.276-3.276a4.5 4.5 0 00-6.336 4.486c.091 1.076-.071 2.264-.904 2.95l-.102.085"})}),t.difficulty_level]})]})]})]}),l.jsx("p",{className:"text-sm text-[#64748B] mt-3 leading-relaxed",children:v}),g&&l.jsxs("div",{className:"mt-3",children:[l.jsx("p",{className:"text-[11px] text-[#94A3B8] mb-1.5",children:"Select your vehicle's rear brake type"}),l.jsxs("div",{className:"flex rounded-xl overflow-hidden border border-[#E2E8F0] bg-white",children:[l.jsx("button",{onClick:()=>d("disc"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:u==="disc"?G.primary:"transparent",color:u==="disc"?"#FFFFFF":"#64748B"},children:"Disc Brakes (Pads + Rotors)"}),l.jsx("button",{onClick:()=>d("drum"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:u==="drum"?G.primary:"transparent",color:u==="drum"?"#FFFFFF":"#64748B"},children:"Drum Brakes (Shoes + Drums)"})]})]})]}),l.jsxs("div",{className:"px-4 py-3 flex items-center justify-center gap-2 border-b border-[#E2E8F0] bg-white",children:[l.jsx("span",{className:"font-semibold text-[#0F172A] text-sm",children:"Choose Your Value Level"}),l.jsx("span",{className:"text-[#64748B] text-xs cursor-help",title:"Select the quality tier that suits your needs",children:"ⓘ"})]}),l.jsx("div",{className:"p-4",children:y?l.jsx("div",{className:`grid ${_(f.length)} gap-3`,children:f.map(x=>{const A=tn[x.tierName];return l.jsxs("div",{className:"relative rounded-2xl overflow-hidden bg-white shadow-md flex flex-col",style:{border:x.isRecommended?"2px solid #0052CC":"1px solid #E2E8F0"},children:[x.isRecommended&&l.jsx("div",{className:"absolute top-0 left-0 right-0 px-2 py-1 text-[9px] font-bold text-white text-center",style:{background:G.primary},children:"★ CARFIX VALUE"}),l.jsxs("div",{className:`p-3 flex-1 flex flex-col ${x.isRecommended?"pt-7":""}`,children:[l.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[l.jsx("span",{className:"text-lg",children:A==null?void 0:A.emoji}),l.jsxs("div",{children:[l.jsx("span",{className:"font-bold text-sm block",style:{color:(A==null?void 0:A.textColor)||G.foreground},children:x.displayName}),l.jsx("span",{className:"text-[10px] text-[#64748B] hidden md:block",children:x.description||(A==null?void 0:A.description)})]})]}),l.jsx("div",{className:"flex items-center gap-1.5 mb-3 min-h-[42px] flex-wrap",children:x.brands.slice(0,3).map(k=>l.jsx("div",{className:"h-10 px-2 bg-white rounded-xl flex items-center justify-center shadow-md border border-[#F1F5F9]",children:l.jsx("img",{src:k.imageUrl,alt:k.fullName,className:"h-6 w-auto object-contain",onError:F=>{const E=F.target,O=`${Ss.storageBase}/brand_images/${k.fullName.replace(/\s+/g,"")}.jpg`;if(E.src!==O)E.src=O;else{const T=E.parentElement;T&&(T.innerHTML=`<span class="text-[10px] font-medium text-slate-700 px-1 truncate max-w-[60px]">${k.name}</span>`)}}})},k.name))}),l.jsxs("p",{className:"text-xs text-[#64748B] hidden md:block mb-2",children:[x.productCount," part",x.productCount!==1?"s":""," included"]}),l.jsx("div",{className:"mt-auto",children:x.savingsAmount&&x.savingsAmount>0?l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"text-xs line-through text-[#94A3B8]",children:nt(x.originalTotalPrice)}),l.jsx("p",{className:"text-xl font-bold",style:{color:"#22C55E"},children:nt(x.totalPrice)}),l.jsxs("p",{className:"text-[10px] font-semibold text-[#22C55E] bg-[#22C55E]/10 inline-block px-1.5 py-0.5 rounded-full mt-0.5",children:["SAVE ",nt(x.savingsAmount)," — ",x.bundleDiscountPercentage,"% Bundle Deal"]})]}):l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"text-xl font-bold",style:{color:x.isRecommended?"#0052CC":"#0F172A"},children:nt(x.totalPrice)}),l.jsx("p",{className:"text-[10px] text-[#64748B] hidden md:block",children:"inc GST"})]})}),l.jsx("button",{onClick:()=>b(x),className:`mt-3 w-full px-3 py-2.5 rounded-xl text-xs font-semibold transition-all hover:scale-[1.02] active:scale-95 flex items-center justify-center ${x.isRecommended?"bg-[#22C55E] text-white shadow-md hover:bg-[#16A34A]":"bg-slate-100 text-[#22C55E] border border-slate-200 hover:bg-slate-200"}`,children:"Add to Cart"})]})]},x.tierName)})}):l.jsxs("div",{className:"rounded-2xl p-6 bg-white border border-[#E2E8F0] shadow-md text-center",children:[l.jsx("svg",{className:"w-12 h-12 mx-auto text-[#94A3B8] mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),l.jsx("p",{className:"text-sm font-medium text-[#64748B]",children:"Package details not available for this vehicle"}),l.jsx("p",{className:"text-xs text-[#94A3B8] mt-1",children:"Please try refreshing or contact support"})]})}),y&&l.jsxs("div",{className:"px-4 pb-4",children:[l.jsxs("button",{onClick:()=>i(!n),className:"w-full flex items-center justify-between p-3 rounded-xl bg-white border border-[#E2E8F0] hover:bg-slate-50 transition-all shadow-sm",children:[l.jsxs("span",{className:"text-sm font-medium text-[#0F172A]",children:[n?"▼":"▶"," View Product Details"]}),l.jsxs("span",{className:"text-xs text-[#64748B]",children:[S," product",S!==1?"s":""]})]}),n&&l.jsx("div",{className:"mt-3 space-y-4 bg-white rounded-xl border border-[#E2E8F0] p-3",children:f.map(x=>{if(x.products.length===0)return null;const A=tn[x.tierName];return l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-2 pb-1 border-b border-[#E2E8F0]",children:[l.jsx("span",{className:"text-lg",children:A==null?void 0:A.emoji}),l.jsx("span",{className:"font-semibold text-sm",style:{color:A==null?void 0:A.textColor},children:x.displayName}),l.jsxs("span",{className:"text-xs text-[#64748B]",children:["(",x.products.length," parts)"]})]}),l.jsx("div",{className:"space-y-2",children:x.products.map((k,F)=>{var T;const E=(T=t.carfixValueProducts)==null?void 0:T.includes(k.sku),O=k.unitPrice??k.price;return l.jsxs("div",{className:"flex items-center gap-3 p-2.5 rounded-xl transition-all hover:bg-slate-50 cursor-pointer border border-[#E2E8F0]",onClick:()=>s==null?void 0:s(k.sku),children:[l.jsx("div",{className:"flex-shrink-0 rounded-lg bg-white overflow-hidden border border-[#E2E8F0]",style:{width:"56px",height:"56px",minWidth:"56px",maxWidth:"56px"},children:l.jsx("img",{src:k.productImageUrl||Ss.productImage(k.sku),alt:k.name,className:"object-contain",style:{width:"100%",height:"100%",maxWidth:"56px",maxHeight:"56px",padding:"6px"},onError:R=>{R.target.src="/placeholder.svg"}})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[l.jsx("span",{className:"text-xs font-semibold text-[#0F172A]",children:k.brandFullName||k.brand}),E&&l.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"rgba(0, 82, 204, 0.1)",color:"#0052CC"},children:"CFX VALUE"}),k.isMultiQty&&k.perCarQty>1&&l.jsxs("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#F0FDF4",color:"#15803D"},children:["×",k.perCarQty]}),k.isRotor&&l.jsx("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#EFF6FF",color:"#1D4ED8"},children:"Pair"})]}),l.jsx("p",{className:"text-xs text-[#64748B] line-clamp-1",children:k.name})]}),l.jsxs("div",{className:"text-right flex-shrink-0",children:[l.jsx("p",{className:"text-sm font-bold text-[#0F172A]",children:nt(k.displayPrice)}),k.isMultiQty&&k.perCarQty>1&&l.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[k.perCarQty,"× ",nt(O)," each"]}),k.isRotor&&!k.isMultiQty&&l.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[nt(O)," each"]})]})]},`${k.sku}-${F}`)})})]},x.tierName)})})]}),t.bundle_discount_percentage&&t.bundle_discount_percentage>0&&l.jsx("div",{className:"px-4 pb-4",children:l.jsx("div",{className:"rounded-xl p-3 text-center",style:{background:"rgba(34,197,94,0.1)",border:"1px solid rgba(34,197,94,0.2)"},children:l.jsxs("span",{className:"text-sm font-semibold text-[#22C55E]",children:["Bundle saves you ",t.bundle_discount_percentage,"%"]})})})]})]})},vo=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,messages:i,input:a,setInput:o,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:g,chatEndRef:f,isMuted:y,onToggleMute:b,isSpeaking:_,products:v,servicePackages:S,highlightedPartType:j,highlightedProduct:x,scrollToCategory:A,onScrollToCategoryComplete:k,onProductClick:F,onPackageSelect:E,isResearching:O,onAddToCart:T,onNavigateToProductPage:R,onQuickReply:N,onInterrupt:C,vehicle:L,onChangeVehicle:K,pendingVariants:H,pendingVariantMake:Y,pendingVariantModel:Z,onVariantSelect:W,bobOffset:V=0,bobScale:ge=100})=>{const[te,ie]=p.useState("center"),[ve,$]=p.useState("hidden"),[ae,J]=p.useState("products"),[B,Se]=p.useState(null),[ke,we]=p.useState(null),je=v.length>0||S.length>0,Fe=((H==null?void 0:H.length)??0)>0,$e=je||Fe,et=(ae==="productDetail"?70:te==="center"&&!$e?140:98)*ge/100;p.useEffect(()=>{if(O&&ve!=="loading"&&ve!=="visible")$("loading"),te==="center"&&ie("partial-left");else if($e&&ve!=="visible")if(te==="center"){ie("partial-left"),$("transitioning");const M=setTimeout(()=>{$("visible")},400);return()=>clearTimeout(M)}else $("visible");else!$e&&!O&&ve!=="hidden"&&($("hidden"),ie("center"))},[$e,O,ve,te]);const it=M=>{if(R){R(M),F==null||F(M);return}Se(M),J("productDetail"),F==null||F(M)},De=()=>{Se(null),we(null),J("products")},I=M=>{console.log("[ContainedMobileBobLayout] Package selected:",M.title),we(M),J("packageDetail"),E==null||E(M)},oe=ve!=="hidden"&&ae==="products",Ae=ve!=="hidden";return l.jsxs("div",{className:"absolute inset-0",style:{overflow:"clip",isolation:"isolate",WebkitUserSelect:"none",userSelect:"none",WebkitTouchCallout:"none"},onContextMenu:M=>M.preventDefault(),children:[r&&l.jsx("div",{className:"absolute inset-0 z-0 transition-all duration-500 ease-out",style:{backgroundImage:`url(${r})`,backgroundSize:"cover",backgroundPosition:"center bottom",filter:Ae?"blur(var(--bob-blur-intensity, 0px)) brightness(0.95)":"none",transform:Ae?"scale(1.02)":"scale(1)",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"}}),l.jsx(cn,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:et,position:te,verticalOffset:V}),l.jsx(un,{products:v,servicePackages:S,highlightedPartType:j,highlightedProduct:x,scrollToCategory:A,onScrollToCategoryComplete:k,onProductClick:it,onPackageSelect:I,isResearching:O,visible:oe,counterHeightPercent:n,hasVehicle:!!L,onAddToCart:T,vehicleMakeModel:L?`${L.make||""} ${L.model||""}`.trim():void 0,pendingVariants:H,pendingVariantMake:Y,pendingVariantModel:Z,onVariantSelect:W}),ae==="productDetail"&&B&&l.jsx(Od,{product:B,onBack:De,onAddToCart:T,onNavigateToProductPage:R}),ae==="packageDetail"&&ke&&l.jsx(yo,{package:ke,onBack:De,onAddToCart:M=>{M.forEach(ce=>{var Ce;T==null||T({id:ce.sku||((Ce=ce.partslotId)==null?void 0:Ce.toString())||"unknown",name:ce.name||ce.partslotName||"Unknown Part",brand:ce.brand,price:ce.displayPrice,sku:ce.sku,partNumber:ce.partNumber,image_url:ce.productImageUrl,partslotDescription:ce.partslotName})})},onNavigateToProductPage:M=>{const ce=v.find(Ce=>Ce.sku===M);ce&&R&&R(ce)}}),ae==="products"&&l.jsx(mo,{messages:i,input:a,setInput:o,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:g,chatEndRef:f,isMuted:y,onToggleMute:b,isSpeaking:_,onQuickReply:N,onInterrupt:C,counterHeightPercent:n})]})},oi=({variant:t="inline",initialState:e="idle",showChat:r=!0,className:s="",backdropUrl:n,counterOverlayUrl:i,counterHeightPercent:a,defaultBobImage:o,verticalOffset:c=0,scale:u=100,sessionToken:d,embedded:h=!1,initialVehicle:g})=>{var it,De;const{callbacks:f}=Lt(),[y,b]=p.useState(!1),{animationState:_,setAnimationState:v,getCurrentImage:S,getCurrentOffset:j,getCurrentScale:x,availableStates:A}=Xa({isSpeaking:y}),{activeBackdrop:k}=Za(),[F,E]=p.useState([]),[O,T]=p.useState([]),[R,N]=p.useState(null),[C,L]=p.useState(null),[K,H]=p.useState(!1),[Y,Z]=p.useState(null),W=p.useRef(new Set);p.useEffect(()=>{const I=new Set(F.map(oe=>oe.partslotDescription||"Other Parts").filter(Boolean));W.current=I},[F]),p.useEffect(()=>{if(O.length>0){const I=new Set(W.current);O.forEach(oe=>{oe.title&&I.add(oe.title)}),W.current=I}},[O]);const[V,ge]=p.useState([]),[te,ie]=p.useState(""),[ve,$]=p.useState(""),ae=p.useRef(null),J=p.useRef(null);p.useEffect(()=>{ae.current=I=>{if(H(!1),!I||I.length===0){console.log("[Bob] Clearing products (empty array received)"),E([]);return}const oe=I[0];console.log("[Bob] First part raw keys:",Object.keys(oe));const Ae=I.map((M,ce)=>{const Ce=M.Brand||M.brand||"";return{id:M.SKU||M.sku||`part-${ce}`,name:M["Part Product Type"]||M.partslot_description||M.name||"Unknown Part",brand:Ce,price:M["Metro Retail Price"]||M.price||0,sku:M.SKU||M.sku,partNumber:M["Part Number"]||M.part_number||null,partslotDescription:M["Part Product Type"]||M.partslot_description||M.partslotDescription||M.part_type||M.category||"General Parts",image_url:M.image_url||(M.SKU||M.sku?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/product_images/${M.SKU||M.sku}.jpg`:void 0),webDescription:M["Web Part Description"]||M.web_description||null,brandDescription:M["Brand Description"]||M.brand_description||null,perCarQty:M["Per Car Qty"]||M.per_car_qty||1,volume:M.volume||null,viscosity:M.viscosity||null,brandImageUrl:Ce?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${Ce.replace(/\s+/g,"")}.jpg`:void 0}});E(M=>{var rr;const ce=new Set(M.map(Ue=>Ue.sku).filter(Boolean)),Ce=new Set(M.map(Ue=>Ue.partslotDescription||"Other Parts")),Xe=new Set,be=Ae.filter(Ue=>!Ue.sku||Xe.has(Ue.sku)||ce.has(Ue.sku)?!1:(Xe.add(Ue.sku),!0));if(console.log("[Bob] Products mapped:",Ae.length,"-> new unique:",be.length,"-> existing:",M.length),be.length>0&&M.length>0){const Ue=(rr=be.find(Xr=>!Ce.has(Xr.partslotDescription||"Other Parts")))==null?void 0:rr.partslotDescription;Ue&&setTimeout(()=>Z(Ue),100)}return[...M,...be]})},J.current=I=>{if(!I||I.length===0){console.log("[Bob] Clearing service packages (empty array received)"),T([]);return}console.log("[Bob] Service packages received via stable ref:",I.length),T(I)}},[]);const B=Qa({setAnimationState:v,manualMode:!1,onReadyToSpeak:()=>{console.log("[BobWidget] Ready to speak")},onStreamComplete:()=>{v(A.find(I=>I.includes("idle"))||"idle")},onResearchStart:()=>{H(!0)},onVariantSelectionRequired:(I,oe,Ae)=>{H(!1),ge(I),ie(oe),$(Ae)},onHighlightPart:I=>{N(I),setTimeout(()=>N(null),8e3)},onHighlightProduct:I=>{L(I),setTimeout(()=>L(null),8e3)},onAutoFetchComplete:()=>{H(!1)},shelfCategoriesRef:W,initialVehicle:g});p.useEffect(()=>{B.identifiedVehicle&&(ge([]),ie(""),$(""))},[(it=B.identifiedVehicle)==null?void 0:it.vehicle_id,(De=B.identifiedVehicle)==null?void 0:De.id]);const Se=I=>{B.sendDirectMessage(`Option ${I.optionNumber}`)};p.useEffect(()=>{b(B.isSpeaking)},[B.isSpeaking]),p.useEffect(()=>{const I=f.onPartsFound,oe=f.onServicePackagesFound;return f.onPartsFound=Ae=>{var M;(M=ae.current)==null||M.call(ae,Ae),I==null||I(Ae)},f.onServicePackagesFound=Ae=>{var M;(M=J.current)==null||M.call(J,Ae),oe==null||oe(Ae)},()=>{f.onPartsFound=I,f.onServicePackagesFound=oe}},[f]);const ke=n||(k==null?void 0:k.image_url),we=i||(k==null?void 0:k.counter_overlay_url)||void 0,je=a||(k==null?void 0:k.counter_height_percent)||12,Fe=S()||o||"",$e=j(),Ye=x(),qe=p.useCallback(I=>{var M,ce,Ce,Xe;const oe=Array.isArray(I)?I:[I],Ae=((ce=(M=B.identifiedVehicle)==null?void 0:M.vehicle_id)==null?void 0:ce.toString())||((Xe=(Ce=B.identifiedVehicle)==null?void 0:Ce.id)==null?void 0:Xe.toString());oe.forEach(be=>{var Ue;const rr={product_id:be.id||be.sku||"",product_name:be.name,quantity:be.quantity||1,unit_price:be.price,sku:be.sku,brand:be.brand,image_url:be.image_url,vehicle_id:Ae,...be._bundleMeta||{}};(Ue=f.onAddToCart)==null||Ue.call(f,rr)})},[B.identifiedVehicle,f]);if(t==="mobile"||t==="fullscreen")return l.jsx(bo,{currentImage:Fe,animationState:_,backdropUrl:ke,counterOverlayUrl:we,counterHeightPercent:je,bobOffset:$e,bobScale:Ye,embedded:h,messages:B.messages,input:B.input,setInput:B.setInput,isLoading:B.isLoading,onSend:B.handleSend,onKeyPress:B.handleKeyPress,onInputFocus:B.handleInputFocus,onInputBlur:B.handleInputBlur,chatEndRef:B.chatEndRef,isMuted:B.isMuted,onToggleMute:B.toggleMute,isSpeaking:B.isSpeaking,products:F,servicePackages:O,highlightedPartType:R,highlightedProduct:C,scrollToCategory:Y,onScrollToCategoryComplete:()=>Z(null),onAddToCart:qe,onNavigateToProductPage:I=>{var oe;return(oe=f.onNavigateToProductPage)==null?void 0:oe.call(f,I)},onQuickReply:I=>{var oe;return(oe=f.onNavigateToProductPage)==null?void 0:oe.call(f,{url:I})},onPackageSelect:I=>console.log("[BobWidget] Package selected:",I),isResearching:K,vehicle:B.identifiedVehicle,pendingVariants:V,pendingVariantMake:te,pendingVariantModel:ve,onVariantSelect:Se,onInterrupt:B.stopAllAudio});if(t==="inline"&&r)return l.jsx("div",{className:`relative w-full h-full ${s}`,children:l.jsx(vo,{currentImage:Fe,animationState:_,backdropUrl:ke,counterOverlayUrl:we,counterHeightPercent:je,bobOffset:$e,bobScale:Ye,messages:B.messages,input:B.input,setInput:B.setInput,isLoading:B.isLoading,onSend:B.handleSend,onKeyPress:B.handleKeyPress,onInputFocus:B.handleInputFocus,onInputBlur:B.handleInputBlur,chatEndRef:B.chatEndRef,isMuted:B.isMuted,onToggleMute:B.toggleMute,isSpeaking:B.isSpeaking,products:F,servicePackages:O,highlightedPartType:R,highlightedProduct:C,scrollToCategory:Y,onScrollToCategoryComplete:()=>Z(null),onAddToCart:qe,onNavigateToProductPage:I=>{var oe;return(oe=f.onNavigateToProductPage)==null?void 0:oe.call(f,I)},onQuickReply:I=>{var oe;return(oe=f.onNavigateToProductPage)==null?void 0:oe.call(f,{url:I})},onPackageSelect:I=>console.log("[BobWidget] Package selected:",I),isResearching:K,vehicle:B.identifiedVehicle,pendingVariants:V,pendingVariantMake:te,pendingVariantModel:ve,onVariantSelect:Se,onInterrupt:B.stopAllAudio})});const et={inline:"",floating:"fixed bottom-4 right-4 w-96 z-50 shadow-2xl rounded-lg overflow-hidden"};return l.jsxs("div",{className:`${et[t]||""} ${s}`,children:[Fe&&l.jsx(eo,{currentImage:Fe,animationState:_,backdropUrl:ke,counterOverlayUrl:we,counterHeightPercent:je,verticalOffset:$e,scale:Ye}),r&&l.jsx(io,{messages:B.messages,input:B.input,setInput:B.setInput,isLoading:B.isLoading,onSend:B.handleSend,onKeyPress:B.handleKeyPress,onInputFocus:B.handleInputFocus,onInputBlur:B.handleInputBlur,chatEndRef:B.chatEndRef,isMuted:B.isMuted,onToggleMute:B.toggleMute,isSpeaking:B.isSpeaking})]})},wo=(t=!0)=>{const[e,r]=p.useState("prompt"),s=p.useRef(!1);return p.useEffect(()=>{if(!t)return;navigator.permissions?navigator.permissions.query({name:"microphone"}).then(i=>{r(i.state),i.state!=="granted"&&(i.state==="prompt"&&!s.current&&(s.current=!0,navigator.mediaDevices.getUserMedia({audio:!0}).then(a=>{a.getTracks().forEach(o=>o.stop()),r("granted")}).catch(()=>r("denied"))),i.addEventListener("change",()=>{r(i.state)}))}).catch(()=>{n()}):n();function n(){var i;if(!s.current){if(!((i=navigator.mediaDevices)!=null&&i.getUserMedia)){r("unsupported");return}s.current=!0,navigator.mediaDevices.getUserMedia({audio:!0}).then(a=>{a.getTracks().forEach(o=>o.stop()),r("granted")}).catch(()=>r("denied"))}}},[t]),{micPermission:e}},Pd=({bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,variant:n="mobile",initialState:i,showChat:a,className:o,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:h,verticalOffset:g,scale:f,ga4Config:y,analyticsEnabled:b=!0,bottomOffset:_=0,zIndexBase:v=50,embedded:S=!1})=>{const{micPermission:j}=wo(!0),x=p.useRef(null);return p.useEffect(()=>Va(x.current),[]),p.useEffect(()=>{console.log("[BobWidget] Initialized",{version:Bt,variant:n,bottomOffset:_,zIndexBase:v,bobConfigUrl:t.supabaseUrl,hostApiBaseUrl:e.baseUrl,analyticsEnabled:b,micPermission:j})},[n,_,v,t.supabaseUrl,e.baseUrl,b,j]),l.jsx("div",{ref:x,className:"bob-widget-root",style:{width:"100%",height:"100%"},children:l.jsx(ri,{bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,ga4Config:y,analyticsEnabled:b,bottomOffset:_,zIndexBase:v,children:l.jsx(oi,{variant:n,initialState:i,showChat:a,className:o,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:h,verticalOffset:g,scale:f,embedded:S})})})};function Nd(t){return t<640?"mobile":t<1024?"tablet":"desktop"}function Id(){const t=[];if(typeof window>"u")return t;const e=document.querySelector(".bob-widget-root");if(!e)return t.push("bob-widget-root not found in DOM"),t;const r=window.getComputedStyle(e),s=e.parentElement;return s&&window.getComputedStyle(s).overflow==="hidden"&&t.push("Parent has overflow:hidden - may clip Bob"),r.transform!=="none"&&r.transform!=="matrix(1, 0, 0, 1, 0, 0)"&&t.push(`Unexpected transform on root: ${r.transform}`),r.isolation!=="isolate"&&t.push("Isolation not properly set"),t}const xo=({partnerConfig:t,sessionToken:e})=>{const[r,s]=p.useState(null),[n,i]=p.useState([]),[a,o]=p.useState(!1);if(p.useEffect(()=>{const u=()=>{var g;const d=window.innerWidth,h=window.innerHeight;s({viewport:{width:d,height:h,deviceType:Nd(d)},origin:window.location.origin,originAllowed:((g=t==null?void 0:t.allowed_origins)==null?void 0:g.some(f=>f===window.location.origin||f.includes("*")))??!1,userAgent:navigator.userAgent.slice(0,50)+"...",timestamp:new Date().toISOString()}),i(Id())};return u(),window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[t]),!r)return null;const c=({ok:u,label:d})=>l.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"4px",fontSize:"11px",fontWeight:500,background:u?"rgba(34, 197, 94, 0.2)":"rgba(239, 68, 68, 0.2)",color:u?"#22c55e":"#ef4444"},children:[u?"✓":"✗"," ",d]});return l.jsxs("div",{style:{position:"fixed",top:"8px",right:"8px",zIndex:99999,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace',fontSize:"11px",lineHeight:1.4},children:[l.jsx("button",{onClick:()=>o(!a),style:{position:"absolute",top:0,right:0,width:"24px",height:"24px",background:"rgba(0, 0, 0, 0.8)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"4px",color:"#fff",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1},children:a?"🔍":"✕"}),!a&&l.jsxs("div",{style:{background:"rgba(0, 0, 0, 0.9)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"8px",padding:"12px",color:"#fff",maxWidth:"320px",backdropFilter:"blur(8px)"},children:[l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"12px",paddingBottom:"8px",borderBottom:"1px solid rgba(255,255,255,0.1)"},children:[l.jsx("span",{style:{fontSize:"14px"},children:"🔧"}),l.jsxs("span",{style:{fontWeight:600},children:["Bob Debug v",Bt]})]}),l.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px",marginBottom:"12px"},children:[l.jsx(c,{ok:!!t,label:`Partner: ${(t==null?void 0:t.partner_code)||"none"}`}),l.jsx(c,{ok:!!e,label:e?"Session":"No Session"}),l.jsx(c,{ok:r.originAllowed,label:"Origin"})]}),l.jsxs("div",{style:{display:"grid",gap:"6px"},children:[l.jsx(Nr,{label:"Viewport",value:`${r.viewport.width}×${r.viewport.height} (${r.viewport.deviceType})`}),l.jsx(Nr,{label:"Origin",value:r.origin}),l.jsx(Nr,{label:"Bottom Offset",value:`${(t==null?void 0:t.default_bottom_offset)??0}px`}),l.jsx(Nr,{label:"Z-Index Base",value:`${(t==null?void 0:t.default_z_index_base)??50}`}),l.jsx(Nr,{label:"Blur",value:`${(t==null?void 0:t.backdrop_blur_intensity)??8}px`}),l.jsx(Nr,{label:"Overlay",value:`${(((t==null?void 0:t.backdrop_overlay_opacity)??.15)*100).toFixed(0)}%`})]}),(t==null?void 0:t.feature_flags)&&l.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[l.jsx("div",{style:{color:"rgba(255,255,255,0.5)",marginBottom:"4px"},children:"Features:"}),l.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px"},children:Object.entries(t.feature_flags).map(([u,d])=>l.jsx(c,{ok:!!d,label:u.replace(/([A-Z])/g," $1").trim()},u))})]}),n.length>0&&l.jsxs("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)"},children:[l.jsx("div",{style:{color:"#ef4444",marginBottom:"4px"},children:"⚠️ CSS Conflicts:"}),n.map((u,d)=>l.jsxs("div",{style:{color:"#fca5a5",fontSize:"10px"},children:["• ",u]},d))]}),l.jsx("div",{style:{marginTop:"12px",paddingTop:"8px",borderTop:"1px solid rgba(255,255,255,0.1)",color:"rgba(255,255,255,0.4)",fontSize:"10px"},children:r.timestamp})]})]})},Nr=({label:t,value:e})=>l.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:"8px"},children:[l.jsxs("span",{style:{color:"rgba(255,255,255,0.5)"},children:[t,":"]}),l.jsx("span",{style:{color:"#fff",textAlign:"right",wordBreak:"break-all"},children:e})]}),ta="https://gjoguxzstsihhxvdgpto.supabase.co",ra="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imdqb2d1eHpzdHNpaGh4dmRncHRvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjM5MzgyODEsImV4cCI6MjA3OTUxNDI4MX0.detu4TKB7RjC6l6CrVaPYoi0Hhz2asDt6zxNx1cdzq8";function Bd(t,e){return t.some(r=>{if(r.includes("*")){const s=r.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${s}$`).test(e)}return r===e})}function _o(t){const[e,r]=p.useState(null),[s,n]=p.useState(!0),[i,a]=p.useState(null),[o,c]=p.useState(!1),[u,d]=p.useState(null),h=p.useCallback(async()=>{if(!t){n(!1),a(new Error("Partner code is required"));return}n(!0),a(null);try{const g=In(ta,ra);console.log(`[BobWidget] Loading partner config for: ${t}`);const{data:f,error:y}=await g.from("bob_partners").select("*").eq("partner_code",t).eq("is_active",!0).maybeSingle();if(y)throw new Error(`Failed to load partner config: ${y.message}`);if(!f)throw new Error(`Partner "${t}" not found or inactive`);const b=f,_=typeof window<"u"?window.location.origin:"",v=Bd(b.allowed_origins||[],_);!v&&_&&(console.warn(`[BobWidget] Origin "${_}" not in allowed origins for ${t}`),console.warn("[BobWidget] Allowed origins:",b.allowed_origins));const S=In(b.bob_supabase_url||ta,b.bob_supabase_key||ra,{auth:{storageKey:`bobwidget_${b.partner_code.toLowerCase()}`,persistSession:!1,autoRefreshToken:!1}});console.log("[BobWidget] Partner config loaded:",{partner:b.partner_code,displayName:b.display_name,bottomOffset:b.default_bottom_offset,blurIntensity:b.backdrop_blur_intensity,features:b.feature_flags,originAllowed:v}),r(b),c(v),d(S)}catch(g){const f=g instanceof Error?g:new Error("Unknown error loading partner config");console.error("[BobWidget] Partner config error:",f),a(f)}finally{n(!1)}},[t]);return p.useEffect(()=>{h()},[h]),{config:e,isLoading:s,error:i,isOriginAllowed:o,supabaseClient:u,reload:h}}function ko(t,e,r){return t!=null&&t.feature_flags?t.feature_flags[e]??r:r}const Fd=()=>l.jsxs("div",{className:"bob-widget-root",style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",background:"linear-gradient(180deg, #0a1628 0%, #0f2137 100%)"},children:[l.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[l.jsx("div",{style:{width:"48px",height:"48px",border:"4px solid rgba(0, 102, 204, 0.3)",borderTopColor:"#0066cc",borderRadius:"50%",animation:"spin 1s linear infinite"}}),l.jsx("span",{style:{color:"rgba(255,255,255,0.7)",fontSize:"14px"},children:"Loading Bob..."})]}),l.jsx("style",{children:`
76
77
  @keyframes spin {
77
78
  to { transform: rotate(360deg); }
78
79
  }
79
- `})]}),id=({error:t,partner:e})=>o.jsx("div",{className:"bob-widget-root",style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",background:"linear-gradient(180deg, #1a0a0a 0%, #2a1515 100%)",padding:"24px"},children:o.jsxs("div",{style:{maxWidth:"400px",textAlign:"center",color:"white"},children:[o.jsx("div",{style:{fontSize:"48px",marginBottom:"16px"},children:"⚠️"}),o.jsx("h3",{style:{fontSize:"20px",fontWeight:600,marginBottom:"8px"},children:"Bob Widget Error"}),o.jsx("p",{style:{fontSize:"14px",color:"rgba(255,255,255,0.7)",marginBottom:"16px"},children:t.message}),o.jsxs("code",{style:{display:"block",fontSize:"12px",background:"rgba(255,0,0,0.1)",padding:"12px",borderRadius:"8px",color:"#ff6b6b"},children:["Partner: ",e,o.jsx("br",{}),"Origin: ",typeof window<"u"?window.location.origin:"unknown"]})]})}),ad=p.forwardRef(({partner:t,sessionToken:e,bottomOffset:r,zIndexBase:s,backdropBlurIntensity:n,backdropOverlayOpacity:i,onAddToCart:a,onNavigate:l,onCheckout:c,onError:u,debug:d=!1,className:h="",initialVehicle:g},f)=>{const m=p.useRef(null);p.useImperativeHandle(f,()=>({stopSpeech:()=>{var E;return(E=m.current)==null?void 0:E.call(m)},interrupt:()=>{var E;return(E=m.current)==null?void 0:E.call(m)}}));const{config:b,isLoading:_,error:y,supabaseClient:k}=oo(t);p.useEffect(()=>{console.log("[BobStandalone] Initialized",{version:It,partner:t,sessionToken:e?"present":"none",debug:d})},[t,e,d]);const j=p.useMemo(()=>({onAddToCart:a?E=>a(E):void 0,onCheckoutRequested:c,onError:u,onNavigateToProductPage:l?E=>{const P=E;P!=null&&P.url?l(P.url):P!=null&&P.sku&&l(`/product/${P.sku}`)}:void 0,onStopSpeechReady:E=>{m.current=E}}),[a,l,c,u]),x=p.useMemo(()=>({}),[]);if(_)return o.jsx(nd,{});if(y||!b||!k){const E=y||new Error("Failed to initialize Bob");return u==null||u(E),o.jsx(id,{error:E,partner:t})}const T=r??b.default_bottom_offset,S=s??b.default_z_index_base,F=d||lo(b,"showDebugOverlay",!1);return o.jsx("div",{className:`bob-widget-root ${h}`,style:{width:"100%",height:"100%","--bob-blur-intensity":`${n??b.backdrop_blur_intensity}px`,"--bob-overlay-opacity":i??b.backdrop_overlay_opacity,"--bob-z-base":S},children:o.jsxs(Gn,{bobConfig:{supabaseUrl:b.bob_supabase_url,supabaseKey:b.bob_supabase_key},hostApiConfig:{baseUrl:b.api_base_url,apiKey:"",partnerCode:b.partner_code},hostContext:x,callbacks:j,bottomOffset:T,zIndexBase:S,children:[o.jsx(Zn,{variant:"inline",sessionToken:e,initialVehicle:g}),F&&o.jsx(ao,{partnerConfig:b,sessionToken:e})]})})}),od=({children:t,isSpeaking:e=!1,hasProducts:r=!1,onVisibilityChange:s,onPositionChange:n,currentPosition:i="center"})=>{const[a,l]=p.useState(!1),[c,u]=p.useState(0),d=p.useRef(null),h=p.useRef(0),g=p.useRef(0),f=p.useRef(!1),m=.25;p.useEffect(()=>{e&&i==="hidden"&&(n==null||n("partial-left"),s==null||s(!0))},[e,i,n,s]);const b=p.useCallback(x=>{h.current=x.touches[0].clientX,g.current=x.touches[0].clientY,f.current=!1,l(!0)},[]),_=p.useCallback(x=>{if(!a)return;const T=x.touches[0].clientX,S=x.touches[0].clientY,F=T-h.current,E=S-g.current;!f.current&&Math.abs(F)>10&&(f.current=Math.abs(F)>Math.abs(E)),f.current&&(x.preventDefault(),u(F))},[a]),y=p.useCallback(()=>{var E;if(!a)return;l(!1);const x=((E=d.current)==null?void 0:E.offsetWidth)||300,T=Math.abs(c)/x,S=c<0,F=c>0;S?i==="center"&&T>m?(n==null||n("partial-left"),s==null||s(!0)):i==="partial-left"&&T>m&&(n==null||n("hidden"),s==null||s(!1)):F&&(i==="hidden"&&T>m?(n==null||n("partial-left"),s==null||s(!0)):i==="partial-left"&&T>m&&!r&&(n==null||n("center"),s==null||s(!0))),u(0)},[a,c,i,r,n,s]),k=p.useCallback(()=>{n==null||n("partial-left"),s==null||s(!0)},[n,s]),j=()=>a&&c!==0?`translateX(${Math.max(-100,Math.min(100,c))}px)`:"translateX(0)";return o.jsxs(o.Fragment,{children:[o.jsxs("div",{ref:d,style:{position:"fixed",inset:0,width:"100vw",height:"100dvh",transform:j(),transition:a?"none":"transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)",willChange:"transform"},onTouchStart:b,onTouchMove:_,onTouchEnd:y,children:[t,i==="center"&&!a&&o.jsx("div",{className:"absolute left-2 top-1/2 -translate-y-1/2 pointer-events-none",style:{animation:"swipeHint 3s ease-in-out 2s 1",opacity:0},children:o.jsx("svg",{className:"w-6 h-6 text-white/50",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})})]}),i==="hidden"&&o.jsx("button",{onClick:k,className:"fixed left-0 top-1/2 -translate-y-1/2 z-50 flex items-center justify-center",style:{writingMode:"vertical-rl",textOrientation:"mixed",background:"linear-gradient(180deg, #0066CC 0%, #004999 100%)",padding:"16px 8px",borderTopRightRadius:"12px",borderBottomRightRadius:"12px",boxShadow:"4px 0 12px rgba(0, 102, 204, 0.3)",animation:"slideInFromLeft 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)",border:"none",cursor:"pointer"},children:o.jsx("span",{className:"text-white font-bold text-lg tracking-wider",children:"BOB"})}),o.jsx("style",{children:`
80
+ `})]}),Ld=({error:t,partner:e})=>l.jsx("div",{className:"bob-widget-root",style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",background:"linear-gradient(180deg, #1a0a0a 0%, #2a1515 100%)",padding:"24px"},children:l.jsxs("div",{style:{maxWidth:"400px",textAlign:"center",color:"white"},children:[l.jsx("div",{style:{fontSize:"48px",marginBottom:"16px"},children:"⚠️"}),l.jsx("h3",{style:{fontSize:"20px",fontWeight:600,marginBottom:"8px"},children:"Bob Widget Error"}),l.jsx("p",{style:{fontSize:"14px",color:"rgba(255,255,255,0.7)",marginBottom:"16px"},children:t.message}),l.jsxs("code",{style:{display:"block",fontSize:"12px",background:"rgba(255,0,0,0.1)",padding:"12px",borderRadius:"8px",color:"#ff6b6b"},children:["Partner: ",e,l.jsx("br",{}),"Origin: ",typeof window<"u"?window.location.origin:"unknown"]})]})}),$d=p.forwardRef(({partner:t,sessionToken:e,bottomOffset:r,zIndexBase:s,backdropBlurIntensity:n,backdropOverlayOpacity:i,onAddToCart:a,onNavigate:o,onCheckout:c,onError:u,debug:d=!1,className:h="",initialVehicle:g},f)=>{const y=p.useRef(null),b=p.useRef(null);p.useImperativeHandle(f,()=>({stopSpeech:()=>{var O;return(O=y.current)==null?void 0:O.call(y)},interrupt:()=>{var O;return(O=y.current)==null?void 0:O.call(y)}}));const{config:_,isLoading:v,error:S,supabaseClient:j}=_o(t);p.useEffect(()=>{console.log("[BobStandalone] Initialized",{version:Bt,partner:t,sessionToken:e?"present":"none",debug:d})},[t,e,d]),p.useEffect(()=>{if(!(v||!_||!j))return Va(b.current)},[v,_==null?void 0:_.id,j]);const x=p.useMemo(()=>({onAddToCart:a?O=>a(O):void 0,onCheckoutRequested:c,onError:u,onNavigateToProductPage:o?O=>{const T=O;T!=null&&T.url?o(T.url):T!=null&&T.sku&&o(`/product/${T.sku}`)}:void 0,onStopSpeechReady:O=>{y.current=O}}),[a,o,c,u]),A=p.useMemo(()=>({}),[]);if(v)return l.jsx(Fd,{});if(S||!_||!j){const O=S||new Error("Failed to initialize Bob");return u==null||u(O),l.jsx(Ld,{error:O,partner:t})}const k=r??_.default_bottom_offset,F=s??_.default_z_index_base,E=d||ko(_,"showDebugOverlay",!1);return l.jsx("div",{ref:b,className:`bob-widget-root ${h}`,style:{width:"100%",height:"100%","--bob-blur-intensity":`${n??_.backdrop_blur_intensity}px`,"--bob-overlay-opacity":i??_.backdrop_overlay_opacity,"--bob-z-base":F},children:l.jsxs(ri,{bobConfig:{supabaseUrl:_.bob_supabase_url,supabaseKey:_.bob_supabase_key},hostApiConfig:{baseUrl:_.api_base_url,apiKey:"",partnerCode:_.partner_code},hostContext:A,callbacks:x,bottomOffset:k,zIndexBase:F,children:[l.jsx(oi,{variant:"inline",sessionToken:e,initialVehicle:g}),E&&l.jsx(xo,{partnerConfig:_,sessionToken:e})]})})}),Dd=({children:t,isSpeaking:e=!1,hasProducts:r=!1,onVisibilityChange:s,onPositionChange:n,currentPosition:i="center"})=>{const[a,o]=p.useState(!1),[c,u]=p.useState(0),d=p.useRef(null),h=p.useRef(0),g=p.useRef(0),f=p.useRef(!1),y=.25;p.useEffect(()=>{e&&i==="hidden"&&(n==null||n("partial-left"),s==null||s(!0))},[e,i,n,s]);const b=p.useCallback(x=>{h.current=x.touches[0].clientX,g.current=x.touches[0].clientY,f.current=!1,o(!0)},[]),_=p.useCallback(x=>{if(!a)return;const A=x.touches[0].clientX,k=x.touches[0].clientY,F=A-h.current,E=k-g.current;!f.current&&Math.abs(F)>10&&(f.current=Math.abs(F)>Math.abs(E)),f.current&&(x.preventDefault(),u(F))},[a]),v=p.useCallback(()=>{var E;if(!a)return;o(!1);const x=((E=d.current)==null?void 0:E.offsetWidth)||300,A=Math.abs(c)/x,k=c<0,F=c>0;k?i==="center"&&A>y?(n==null||n("partial-left"),s==null||s(!0)):i==="partial-left"&&A>y&&(n==null||n("hidden"),s==null||s(!1)):F&&(i==="hidden"&&A>y?(n==null||n("partial-left"),s==null||s(!0)):i==="partial-left"&&A>y&&!r&&(n==null||n("center"),s==null||s(!0))),u(0)},[a,c,i,r,n,s]),S=p.useCallback(()=>{n==null||n("partial-left"),s==null||s(!0)},[n,s]),j=()=>a&&c!==0?`translateX(${Math.max(-100,Math.min(100,c))}px)`:"translateX(0)";return l.jsxs(l.Fragment,{children:[l.jsxs("div",{ref:d,style:{position:"fixed",inset:0,width:"100vw",height:"100dvh",transform:j(),transition:a?"none":"transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)",willChange:"transform"},onTouchStart:b,onTouchMove:_,onTouchEnd:v,children:[t,i==="center"&&!a&&l.jsx("div",{className:"absolute left-2 top-1/2 -translate-y-1/2 pointer-events-none",style:{animation:"swipeHint 3s ease-in-out 2s 1",opacity:0},children:l.jsx("svg",{className:"w-6 h-6 text-white/50",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})})]}),i==="hidden"&&l.jsx("button",{onClick:S,className:"fixed left-0 top-1/2 -translate-y-1/2 z-50 flex items-center justify-center",style:{writingMode:"vertical-rl",textOrientation:"mixed",background:"linear-gradient(180deg, #0066CC 0%, #004999 100%)",padding:"16px 8px",borderTopRightRadius:"12px",borderBottomRightRadius:"12px",boxShadow:"4px 0 12px rgba(0, 102, 204, 0.3)",animation:"slideInFromLeft 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)",border:"none",cursor:"pointer"},children:l.jsx("span",{className:"text-white font-bold text-lg tracking-wider",children:"BOB"})}),l.jsx("style",{children:`
80
81
  @keyframes slideInFromLeft {
81
82
  from {
82
83
  transform: translateX(-100%) translateY(-50%);
@@ -98,4 +99,4 @@ ${y}`}class $e extends Error{constructor({message:e,code:r,cause:s,name:n}){var
98
99
  transform: translateX(-10px) translateY(-50%);
99
100
  }
100
101
  }
101
- `})]})},Wt={primary:"216 100% 40%",secondary:"199 95% 74%",success:"33 100% 50%",background:"223 46% 13%",backgroundMode:"dark",sparkDealColor:"33 100% 50%",primaryHex:"#0066CC",secondaryHex:"#7DD3FC",successHex:"#FF9500",backgroundHex:"#111827",sparkDealHex:"#FF9500"};function rs(t){const e=t.match(/(\d+\.?\d*)\s+(\d+\.?\d*)%?\s+(\d+\.?\d*)%?/);if(!e)return"#000000";const r=parseFloat(e[1]),s=parseFloat(e[2])/100,n=parseFloat(e[3])/100,i=(1-Math.abs(2*n-1))*s,a=i*(1-Math.abs(r/60%2-1)),l=n-i/2;let c=0,u=0,d=0;r<60?(c=i,u=a):r<120?(c=a,u=i):r<180?(u=i,d=a):r<240?(u=a,d=i):r<300?(c=a,d=i):(c=i,d=a);const h=g=>Math.round((g+l)*255).toString(16).padStart(2,"0");return`#${h(c)}${h(u)}${h(d)}`}function co(){const t=xr();return Ts({queryKey:["bob-theme-settings"],queryFn:async()=>{var d,h,g,f,m,b,_,y,k,j,x;if(!t)return console.log("[useThemeSettings] No supabase client, using defaults"),Wt;const{data:e,error:r}=await t.from("bob_theme_settings").select("setting_key, color_value, hex_preview").in("setting_key",["matrix_primary","matrix_secondary","matrix_success","matrix_background","matrix_background_mode","matrix_spark_deal_color"]);if(r)return console.error("[useThemeSettings] Error fetching:",r),Wt;if(!e||e.length===0)return Wt;const s=new Map(e.map(T=>[T.setting_key,T])),n=((d=s.get("matrix_primary"))==null?void 0:d.color_value)||Wt.primary,i=((h=s.get("matrix_secondary"))==null?void 0:h.color_value)||Wt.secondary,a=((g=s.get("matrix_success"))==null?void 0:g.color_value)||Wt.success,l=((f=s.get("matrix_background"))==null?void 0:f.color_value)||Wt.background,c=((m=s.get("matrix_spark_deal_color"))==null?void 0:m.color_value)||Wt.sparkDealColor,u=((b=s.get("matrix_background_mode"))==null?void 0:b.color_value)||"dark";return{primary:n,secondary:i,success:a,background:l,backgroundMode:u,sparkDealColor:c,primaryHex:((_=s.get("matrix_primary"))==null?void 0:_.hex_preview)||rs(n),secondaryHex:((y=s.get("matrix_secondary"))==null?void 0:y.hex_preview)||rs(i),successHex:((k=s.get("matrix_success"))==null?void 0:k.hex_preview)||rs(a),backgroundHex:((j=s.get("matrix_background"))==null?void 0:j.hex_preview)||rs(l),sparkDealHex:((x=s.get("matrix_spark_deal_color"))==null?void 0:x.hex_preview)||rs(c)}},staleTime:60*1e3,gcTime:5*60*1e3})}const fn={enabled:!0,inRain:!0,rainFrequency:.15,primingEnabled:!0,bannerEnabled:!0,delayMs:2e3,scrollSpeed:5e3,maxPerSession:3,minResearchTime:1500,bobCommentary:!1};function ld(){const t=xr();return Ts({queryKey:["spark-deals-settings"],queryFn:async()=>{if(!t)return fn;const{data:e,error:r}=await t.from("bob_settings").select("setting_key, setting_value").like("setting_key","spark_deals_%");if(r)return console.error("[useSparkDealsSettings] Error:",r),fn;if(!e||e.length===0)return fn;const s=new Map(e.map(n=>[n.setting_key,n.setting_value]));return{enabled:s.get("spark_deals_enabled")==="true",inRain:s.get("spark_deals_in_rain")==="true",rainFrequency:parseFloat(s.get("spark_deals_rain_frequency")||"0.15"),primingEnabled:s.get("spark_deals_priming_enabled")==="true",bannerEnabled:s.get("spark_deals_banner_enabled")==="true",delayMs:parseInt(s.get("spark_deals_delay_ms")||"2000",10),scrollSpeed:parseInt(s.get("spark_deals_scroll_speed")||"5000",10),maxPerSession:parseInt(s.get("spark_deals_max_per_session")||"3",10),minResearchTime:parseInt(s.get("spark_deals_min_research_time")||"1500",10),bobCommentary:s.get("spark_deals_bob_commentary")==="true"}},staleTime:60*1e3,gcTime:5*60*1e3})}function uo(t=!0){const e=xr();return Ts({queryKey:["spark-deals"],queryFn:async()=>{if(!e)return console.log("[useSparkDeals] No supabase client"),[];try{return console.error("[useSparkDeals] Missing VITE_SUPABASE_URL"),[]}catch(r){return console.error("[useSparkDeals] Error:",r),[]}},enabled:t,staleTime:5*60*1e3,gcTime:10*60*1e3})}function cd(t){const e=[];return t.forEach(r=>{e.push(`$${r.price.toFixed(0)}`),r.brand&&e.push(r.brand.toUpperCase());const s=r.product_name.split(" ")[0];s&&s.length>2&&e.push(s.toUpperCase())}),e}const ho=({deals:t,currentDealIndex:e,onDealChange:r,onDealClick:s,scrollSpeed:n,theme:i})=>{const[a,l]=p.useState(!1),[c,u]=p.useState(100),d=t[e],h=i.sparkDealHex||"#FF9500",g=i.backgroundMode!=="light";p.useEffect(()=>{if(!d)return;l(!0),u(100);const b=setTimeout(()=>{u(0)},50),_=setTimeout(()=>{u(-100)},n-500),y=setTimeout(()=>{const k=(e+1)%t.length;r(k),l(!1)},n);return()=>{clearTimeout(b),clearTimeout(_),clearTimeout(y)}},[e,d,n,t.length,r]);const f=p.useCallback(()=>{d&&s(d)},[d,s]);if(!d)return null;const m=d.original_price?Math.round((1-d.price/d.original_price)*100):null;return o.jsxs("div",{className:"absolute bottom-20 left-0 right-0 z-20 overflow-hidden pointer-events-none",style:{height:"72px"},children:[o.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-auto",style:{transform:`translateX(${c}%)`,transition:"transform 0.5s ease-out"},children:o.jsxs("button",{onClick:f,className:"group flex items-center gap-4 px-6 py-3 rounded-xl shadow-2xl transition-all hover:scale-105 active:scale-95",style:{background:g?"linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(17, 24, 39, 0.9) 100%)":"linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(248, 250, 252, 0.98) 100%)",border:`2px solid ${h}`,boxShadow:`0 8px 32px -4px ${h}40, 0 4px 16px -2px rgba(0,0,0,0.2)`},children:[o.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center shrink-0",style:{background:`${h}20`},children:o.jsx("svg",{className:"w-5 h-5",fill:h,viewBox:"0 0 24 24",children:o.jsx("path",{d:"M11.645 20.91l-.007-.003-.022-.012a15.247 15.247 0 01-.383-.218 25.18 25.18 0 01-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0112 5.052 5.5 5.5 0 0116.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 01-4.244 3.17 15.247 15.247 0 01-.383.219l-.022.012-.007.004-.003.001a.752.752 0 01-.704 0l-.003-.001z"})})}),o.jsxs("div",{className:"flex flex-col items-start min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs font-bold uppercase tracking-wider",style:{color:h},children:"⚡ Spark Deal"}),m&&m>0&&o.jsxs("span",{className:"text-xs font-bold px-2 py-0.5 rounded-full",style:{background:h,color:g?"#000":"#fff"},children:[m,"% OFF"]})]}),o.jsxs("p",{className:"text-sm font-semibold truncate max-w-[200px]",style:{color:g?"#fff":"#111827"},children:[d.brand," ",d.product_name]})]}),o.jsxs("div",{className:"flex flex-col items-end shrink-0",children:[d.original_price&&d.original_price>d.price&&o.jsxs("span",{className:"text-xs line-through",style:{color:g?"#9ca3af":"#6b7280"},children:["$",d.original_price.toFixed(2)]}),o.jsxs("span",{className:"text-xl font-bold",style:{color:h},children:["$",d.price.toFixed(2)]})]}),o.jsx("svg",{className:"w-5 h-5 opacity-60 group-hover:opacity-100 group-hover:translate-x-1 transition-all",fill:"none",stroke:h,strokeWidth:2,viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8.25 4.5l7.5 7.5-7.5 7.5"})})]})}),t.length>1&&o.jsx("div",{className:"absolute bottom-1 left-0 right-0 flex justify-center gap-1.5",children:t.map((b,_)=>o.jsx("div",{className:"w-1.5 h-1.5 rounded-full transition-all",style:{background:_===e?h:`${h}40`,transform:_===e?"scale(1.3)":"scale(1)"}},_))})]})},Vi=["*",":","=",">","<","+","-","|","•","○","●","◆","◇","0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","K","M","N","P","R","S","T","X","Z","#","@","$","%","&","~","^","/","\\","[","]","{","}"],Gi=["BR","KE","OI","FI","LT","SP","RK","EN","GN","PT","CL","UT","AX","WH","EL","TI","RE","PA","DS","RO","TR","BT","HP","CV","XL"],ud=({phase:t,message:e,onComplete:r,onSparkDealClick:s,subliminalBrands:n=[]})=>{const i=p.useRef(null),a=p.useRef(),l=p.useRef([]),c=p.useRef(0),[u,d]=p.useState(0),[h,g]=p.useState(!1),[f,m]=p.useState(0),{data:b}=co(),{data:_}=ld(),{data:y}=uo(t!=="hidden"&&(_==null?void 0:_.enabled)),k=b||{primaryHex:"#0066CC",secondaryHex:"#004999",successHex:"#FF9500",backgroundHex:"#111827",sparkDealHex:"#FF9500",backgroundMode:"dark"},j=_||{enabled:!0,inRain:!0,rainFrequency:.15,primingEnabled:!0,bannerEnabled:!0,delayMs:2e3,scrollSpeed:5e3,maxPerSession:3,minResearchTime:1500},x=y&&j.inRain?[...cd(y),...n]:n,T=.08,S=p.useCallback(()=>x.length>0&&Math.random()<T?{char:x[Math.floor(Math.random()*x.length)],isSubliminal:!0}:Math.random()<.15?{char:Gi[Math.floor(Math.random()*Gi.length)],isSubliminal:!1}:{char:Vi[Math.floor(Math.random()*Vi.length)],isSubliminal:!1},[x]),F=p.useCallback((R,O)=>R.isSubliminal?k.sparkDealHex:t==="success"?k.successHex:Math.sin(O*2+R.x*.01)*.5+.5>.5?k.primaryHex:k.secondaryHex,[t,k]),E=p.useCallback((R,O)=>{const A=[],$=Math.floor(R/25);for(let V=0;V<$;V++){const{char:z,isSubliminal:ie}=S();A.push({x:V*25+12,y:Math.random()*O,speed:1.5+Math.random()*3.5,char:z,isSubliminal:ie,opacity:.2+Math.random()*.6,size:ie?13:9+Math.random()*3,glowIntensity:ie?.6:0,changeCounter:Math.floor(Math.random()*30)})}l.current=A},[S]);p.useEffect(()=>{if(t==="hidden"){a.current&&cancelAnimationFrame(a.current);return}const R=i.current;if(!R)return;const O=R.getContext("2d");if(!O)return;const A=()=>{R.width=R.offsetWidth*window.devicePixelRatio,R.height=R.offsetHeight*window.devicePixelRatio,O.scale(window.devicePixelRatio,window.devicePixelRatio),E(R.offsetWidth,R.offsetHeight)};A(),c.current=Date.now();const $=()=>{const V=R.offsetWidth,z=R.offsetHeight,Y=(Date.now()-c.current)/1e3;if(O.clearRect(0,0,V,z),l.current.forEach(U=>{const K=F(U,Y);if(O.font=`bold ${U.size}px monospace`,O.fillStyle=K,O.globalAlpha=U.opacity,U.isSubliminal&&U.glowIntensity>0?(O.shadowColor=k.sparkDealHex,O.shadowBlur=8*U.glowIntensity):O.shadowBlur=0,O.fillText(U.char,U.x,U.y),U.y+=U.speed,U.changeCounter++,U.changeCounter>20+Math.random()*40){const{char:he,isSubliminal:Z}=S();U.char=he,U.isSubliminal=Z,U.size=Z?13:9+Math.random()*3,U.glowIntensity=Z?.6:0,U.changeCounter=0}if(U.y>z+20){const{char:he,isSubliminal:Z}=S();U.y=-20,U.char=he,U.isSubliminal=Z,U.speed=1.5+Math.random()*3.5,U.opacity=.2+Math.random()*.6,U.size=Z?13:9+Math.random()*3,U.glowIntensity=Z?.6:0,U.changeCounter=0}}),O.globalAlpha=1,O.shadowBlur=0,t==="success"){const U=Math.max(0,1-Y*2);U>0&&(O.fillStyle=`rgba(255, 149, 0, ${U*.3})`,O.fillRect(0,0,V,z)),Y>.5&&r&&r()}a.current=requestAnimationFrame($)};return $(),window.addEventListener("resize",A),()=>{a.current&&cancelAnimationFrame(a.current),window.removeEventListener("resize",A)}},[t,k,S,F,E,r]),p.useEffect(()=>{if(t==="hidden"||!y||y.length===0||!j.bannerEnabled){g(!1);return}if(f>=j.maxPerSession)return;const R=setTimeout(()=>{g(!0)},j.delayMs);return()=>clearTimeout(R)},[t,y,j,f]);const P=p.useCallback(R=>{d(R),m(O=>O+1)},[]),C=p.useCallback(R=>{console.log("[MatrixLoader] Spark deal clicked:",R.product_name),s==null||s(R)},[s]);return t==="hidden"?null:o.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center overflow-hidden pointer-events-none",style:{background:"transparent"},children:[o.jsx("canvas",{ref:i,className:"absolute inset-0 w-full h-full",style:{opacity:.85}}),h&&y&&y.length>0&&o.jsx(ho,{deals:y.slice(0,j.maxPerSession),currentDealIndex:u,onDealChange:P,onDealClick:C,scrollSpeed:j.scrollSpeed,theme:k})]})},dd=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,products:i,servicePackages:a,highlightedPartType:l,highlightedProduct:c,onProductClick:u,onPackageSelect:d,isResearching:h,vehicle:g,onChangeVehicle:f,bobOffset:m=0,bobScale:b=100,bobHasArrived:_=!0,externalBobPosition:y,onBobPositionChange:k,pendingVariants:j,pendingVariantMake:x,pendingVariantModel:T,onVariantSelect:S})=>{const F=Xs(),E=Yn(),[P,C]=p.useState("center"),[R,O]=p.useState("hidden"),A=y??P,$=p.useCallback(re=>{C(re),k==null||k(re)},[k]),V=i.length>0||a.length>0,z=((j==null?void 0:j.length)??0)>0,ie=V||z,K=(()=>{switch(F){case"desktop":return 80*E.uiScale;case"tablet":return 90*E.uiScale;case"mobile":return 140;default:return 140}})()*b/100;p.useEffect(()=>{if(h&&R!=="loading"&&R!=="visible"){if(z){A==="center"&&$("partial-left");return}O("loading"),A==="center"&&$("partial-left")}else if(ie&&R!=="visible")if(A==="center"){$("partial-left"),O("transitioning");const re=setTimeout(()=>{O("visible")},400);return()=>clearTimeout(re)}else O("visible");else!ie&&!h&&R!=="hidden"&&(z||(O("hidden"),$("center")))},[ie,z,h,R,A,$]);const he=R!=="hidden"||z,Z=he&&ie;return o.jsxs("div",{className:"absolute inset-0 overflow-hidden",style:{width:"100%",height:"100%",touchAction:"manipulation",isolation:"isolate"},children:[r&&o.jsxs(o.Fragment,{children:[o.jsx("img",{src:r,alt:"Shop backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-center transition-all duration-500",style:{pointerEvents:"none",filter:Z?"blur(var(--bob-blur-intensity, 0px))":"none",transform:Z?"scale(1.02)":"scale(1)",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1}),o.jsx("div",{className:"absolute inset-0 z-[1] transition-opacity duration-500 pointer-events-none",style:{background:"rgba(0, 0, 0, var(--bob-overlay-opacity, 0.1))",opacity:Z?1:0}})]}),o.jsx(Zs,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:K,position:A,verticalOffset:m,hasArrived:_}),o.jsx(en,{products:i,servicePackages:a,highlightedPartType:l,highlightedProduct:c,onProductClick:u,onPackageSelect:d,isResearching:h,visible:he,counterHeightPercent:n,hasVehicle:!!g,pendingVariants:j,pendingVariantMake:x,pendingVariantModel:T,onVariantSelect:S})]})},hd=6e4,fd=({states:t,setAnimationState:e,manualMode:r})=>{const[s,n]=p.useState("page_load"),[i,a]=p.useState(!1),l=p.useRef(null),c=p.useCallback(C=>{const R=t.find(O=>O.chat_trigger===C&&O.is_active);return console.log(`[StateTransitions] Looking for trigger: "${C}" -> found:`,(R==null?void 0:R.state_key)||"none"),R},[t]),u=p.useCallback(()=>t.find(C=>C.chat_trigger==="processing_input"||C.state_key==="research"||C.state_key==="researching"||C.title.toLowerCase().includes("research")||C.title.toLowerCase().includes("thinking")),[t]),d=p.useCallback(()=>t.find(C=>C.chat_trigger==="streaming_response"||C.state_key==="talk"||C.state_key==="talking"||C.title.toLowerCase().includes("talk")),[t]),h=p.useCallback(()=>t.find(C=>C.chat_trigger==="awaiting_input"||C.state_key==="talk_pause"||C.state_key==="listening"||C.title.toLowerCase().includes("listen")||C.title.toLowerCase().includes("pause")),[t]),g=p.useCallback(()=>{const C=t.find(R=>R.chat_trigger==="response_complete"||R.state_key==="complete"||R.title.toLowerCase().includes("complete"));return C||t.find(R=>R.state_key==="idle"||R.title.toLowerCase().includes("idle"))},[t]),f=p.useCallback(()=>t.find(C=>C.chat_trigger==="idle"||C.state_key==="idle"||C.title.toLowerCase().includes("idle")),[t]),m=p.useCallback(C=>{const R=t.find(O=>O.state_key===C);return{speed:(R==null?void 0:R.animation_speed)||400,pauseDuration:(R==null?void 0:R.pause_duration)||0,loopCount:(R==null?void 0:R.loop_count)||0}},[t]),b=p.useCallback(()=>{l.current&&(clearTimeout(l.current),l.current=null)},[]),_=p.useCallback(()=>{b(),!r&&(l.current=setTimeout(()=>{const C=f();C&&(n("idle"),e(C.state_key))},hd))},[r,f,e,b]),y=p.useCallback(C=>{if(r)return;const R=c(C);R&&e(R.state_key)},[r,c,e]),k=p.useCallback(()=>{if(r)return;const C=h();C&&(n("awaiting_input"),e(C.state_key),_())},[r,h,e,_]),j=p.useCallback(()=>{i||r||(a(!0),n("page_load"),y("page_load"),setTimeout(()=>{k()},3e3))},[i,r,y,k]),x=p.useCallback(()=>{if(r)return;b(),n("processing_input");const C=u();console.log("[StateTransitions] User input - switching to RESEARCH:",C==null?void 0:C.state_key),C?e(C.state_key):y("processing_input")},[r,b,u,e,y]),T=p.useCallback(()=>{if(r)return;b(),n("streaming_response");const C=d();console.log("[StateTransitions] Speech started - switching to TALK:",C==null?void 0:C.state_key),C&&e(C.state_key)},[r,b,d,e]),S=p.useCallback(()=>{if(r)return;const C=g();console.log("[StateTransitions] Speech ended - switching to COMPLETE:",C==null?void 0:C.state_key),C&&e(C.state_key),setTimeout(()=>{r||k()},2e3)},[r,g,e,k]),F=p.useCallback(()=>{b(),n("streaming_response"),console.log("[StateTransitions] Stream started (API response)")},[b]),E=p.useCallback(()=>{n("response_complete"),console.log("[StateTransitions] Stream complete (API finished)");const C=g();C&&e(C.state_key),setTimeout(()=>{k()},2e3)},[g,e,k]),P=p.useCallback(()=>{if(r)return;n("showing_product"),console.log("[StateTransitions] Showing products");const C=t.find(R=>R.chat_trigger==="showing_product"||R.state_key==="showing_product");C&&e(C.state_key),setTimeout(()=>{k()},3e3)},[r,t,e,k]);return p.useEffect(()=>()=>b(),[b]),{chatStage:s,initialize:j,onUserInput:x,onSpeechStart:T,onSpeechEnd:S,onStreamStart:F,onStreamComplete:E,onShowingProduct:P,getStateSettings:m}},pd=()=>{const t=xr();return{checkHealth:async()=>{if(!t)return{healthy:!1,reason:"No Supabase client available - ensure BobProvider is configured",stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};try{const{data:r,error:s}=await t.from("bob_looks").select("id, name, is_active").eq("is_active",!0).limit(1);if(s)return{healthy:!1,reason:`Database error fetching looks: ${s.message}`,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const n=r==null?void 0:r[0];if(!n)return{healthy:!1,reason:"No active look configured in bob_looks table",stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const{data:i,error:a}=await t.from("animation_states").select("state_key").eq("is_active",!0).eq("look_id",n.id);if(a)return{healthy:!1,reason:`Database error fetching states: ${a.message}`,activeLookId:n.id,activeLookName:n.name,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const l=(i==null?void 0:i.map(m=>m.state_key))||[],u=["idle","talking","listening"].filter(m=>{const b=[m,m.replace("ing",""),m+"ing"];return!l.some(_=>b.includes(_))}),{data:d,error:h}=await t.from("bob_animations").select("id").eq("is_active",!0).eq("look_id",n.id),g=h?0:(d==null?void 0:d.length)||0,f=l.length>=4&&g>0&&u.length===0;return{healthy:f,reason:f?void 0:`Missing critical states: ${u.join(", ")}`,activeLookId:n.id,activeLookName:n.name,stateCount:l.length,states:l,missingCritical:u,frameCount:g}}catch(r){return{healthy:!1,reason:`Unexpected error: ${r instanceof Error?r.message:"Unknown"}`,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0}}}}};console.log(`[BobWidget] Package loaded - v${It}`);exports.BADGE_CONFIG=Ma;exports.BOB_VERSION=It;exports.Bob=Zn;exports.BobCharacter=Ua;exports.BobDebugOverlay=ao;exports.BobProvider=Gn;exports.BobStandalone=ad;exports.BobSuggestions=Qn;exports.BobWidget=ed;exports.CARFIX_COLORS=G;exports.ChatInterface=Ha;exports.ContainedChatDrawer=ro;exports.ContainedMobileBobLayout=no;exports.IMAGE_URLS=vs;exports.MatrixProductLoader=ud;exports.MobileBobCharacter=Zs;exports.MobileBobLayout=to;exports.MobileBobLayoutCore=dd;exports.MobileChatDrawer=eo;exports.MobileProductColumn=en;exports.ProductBadge=is;exports.ProductTile=Va;exports.QUALITY_TIER_CONFIG=Ks;exports.ServicePackageDetailView=so;exports.SparkDealBanner=ho;exports.SwipeableBob=od;exports.TYPOGRAPHY=vt;exports.formatNZD=nt;exports.getBobVersion=po;exports.getDisplayPrice=qa;exports.getFeatureFlag=lo;exports.isRotorProduct=Wa;exports.useBobAnalytics=Ia;exports.useBobAnalyticsConfig=Nu;exports.useBobAnimation=Da;exports.useBobAnimationData=$a;exports.useBobBackdrop=La;exports.useBobCallbacks=Iu;exports.useBobChat=Fa;exports.useBobContext=Bt;exports.useBobHealthCheck=pd;exports.useBobLayoutConfig=Jn;exports.useBobStateTransitions=fd;exports.useBobSupabase=Au;exports.useBobSupabaseSafe=xr;exports.useHostApiConfig=Pu;exports.useHostContext=Ou;exports.useMicPermission=io;exports.usePartnerConfig=oo;exports.useReturningUser=Ba;exports.useSparkDeals=uo;exports.useSpeechRecognition=Xn;exports.useSpeechSynthesis=Na;exports.useThemeSettings=co;
102
+ `})]})},Ht={primary:"216 100% 40%",secondary:"199 95% 74%",success:"33 100% 50%",background:"223 46% 13%",backgroundMode:"dark",sparkDealColor:"33 100% 50%",primaryHex:"#0066CC",secondaryHex:"#7DD3FC",successHex:"#FF9500",backgroundHex:"#111827",sparkDealHex:"#FF9500"};function ns(t){const e=t.match(/(\d+\.?\d*)\s+(\d+\.?\d*)%?\s+(\d+\.?\d*)%?/);if(!e)return"#000000";const r=parseFloat(e[1]),s=parseFloat(e[2])/100,n=parseFloat(e[3])/100,i=(1-Math.abs(2*n-1))*s,a=i*(1-Math.abs(r/60%2-1)),o=n-i/2;let c=0,u=0,d=0;r<60?(c=i,u=a):r<120?(c=a,u=i):r<180?(u=i,d=a):r<240?(u=a,d=i):r<300?(c=a,d=i):(c=i,d=a);const h=g=>Math.round((g+o)*255).toString(16).padStart(2,"0");return`#${h(c)}${h(u)}${h(d)}`}function So(){const t=_r();return Ps({queryKey:["bob-theme-settings"],queryFn:async()=>{var d,h,g,f,y,b,_,v,S,j,x;if(!t)return console.log("[useThemeSettings] No supabase client, using defaults"),Ht;const{data:e,error:r}=await t.from("bob_theme_settings").select("setting_key, color_value, hex_preview").in("setting_key",["matrix_primary","matrix_secondary","matrix_success","matrix_background","matrix_background_mode","matrix_spark_deal_color"]);if(r)return console.error("[useThemeSettings] Error fetching:",r),Ht;if(!e||e.length===0)return Ht;const s=new Map(e.map(A=>[A.setting_key,A])),n=((d=s.get("matrix_primary"))==null?void 0:d.color_value)||Ht.primary,i=((h=s.get("matrix_secondary"))==null?void 0:h.color_value)||Ht.secondary,a=((g=s.get("matrix_success"))==null?void 0:g.color_value)||Ht.success,o=((f=s.get("matrix_background"))==null?void 0:f.color_value)||Ht.background,c=((y=s.get("matrix_spark_deal_color"))==null?void 0:y.color_value)||Ht.sparkDealColor,u=((b=s.get("matrix_background_mode"))==null?void 0:b.color_value)||"dark";return{primary:n,secondary:i,success:a,background:o,backgroundMode:u,sparkDealColor:c,primaryHex:((_=s.get("matrix_primary"))==null?void 0:_.hex_preview)||ns(n),secondaryHex:((v=s.get("matrix_secondary"))==null?void 0:v.hex_preview)||ns(i),successHex:((S=s.get("matrix_success"))==null?void 0:S.hex_preview)||ns(a),backgroundHex:((j=s.get("matrix_background"))==null?void 0:j.hex_preview)||ns(o),sparkDealHex:((x=s.get("matrix_spark_deal_color"))==null?void 0:x.hex_preview)||ns(c)}},staleTime:60*1e3,gcTime:5*60*1e3})}const wn={enabled:!0,inRain:!0,rainFrequency:.15,primingEnabled:!0,bannerEnabled:!0,delayMs:2e3,scrollSpeed:5e3,maxPerSession:3,minResearchTime:1500,bobCommentary:!1};function Ud(){const t=_r();return Ps({queryKey:["spark-deals-settings"],queryFn:async()=>{if(!t)return wn;const{data:e,error:r}=await t.from("bob_settings").select("setting_key, setting_value").like("setting_key","spark_deals_%");if(r)return console.error("[useSparkDealsSettings] Error:",r),wn;if(!e||e.length===0)return wn;const s=new Map(e.map(n=>[n.setting_key,n.setting_value]));return{enabled:s.get("spark_deals_enabled")==="true",inRain:s.get("spark_deals_in_rain")==="true",rainFrequency:parseFloat(s.get("spark_deals_rain_frequency")||"0.15"),primingEnabled:s.get("spark_deals_priming_enabled")==="true",bannerEnabled:s.get("spark_deals_banner_enabled")==="true",delayMs:parseInt(s.get("spark_deals_delay_ms")||"2000",10),scrollSpeed:parseInt(s.get("spark_deals_scroll_speed")||"5000",10),maxPerSession:parseInt(s.get("spark_deals_max_per_session")||"3",10),minResearchTime:parseInt(s.get("spark_deals_min_research_time")||"1500",10),bobCommentary:s.get("spark_deals_bob_commentary")==="true"}},staleTime:60*1e3,gcTime:5*60*1e3})}function Eo(t=!0){const e=_r();return Ps({queryKey:["spark-deals"],queryFn:async()=>{if(!e)return console.log("[useSparkDeals] No supabase client"),[];try{return console.error("[useSparkDeals] Missing VITE_SUPABASE_URL"),[]}catch(r){return console.error("[useSparkDeals] Error:",r),[]}},enabled:t,staleTime:5*60*1e3,gcTime:10*60*1e3})}function Md(t){const e=[];return t.forEach(r=>{e.push(`$${r.price.toFixed(0)}`),r.brand&&e.push(r.brand.toUpperCase());const s=r.product_name.split(" ")[0];s&&s.length>2&&e.push(s.toUpperCase())}),e}const jo=({deals:t,currentDealIndex:e,onDealChange:r,onDealClick:s,scrollSpeed:n,theme:i})=>{const[a,o]=p.useState(!1),[c,u]=p.useState(100),d=t[e],h=i.sparkDealHex||"#FF9500",g=i.backgroundMode!=="light";p.useEffect(()=>{if(!d)return;o(!0),u(100);const b=setTimeout(()=>{u(0)},50),_=setTimeout(()=>{u(-100)},n-500),v=setTimeout(()=>{const S=(e+1)%t.length;r(S),o(!1)},n);return()=>{clearTimeout(b),clearTimeout(_),clearTimeout(v)}},[e,d,n,t.length,r]);const f=p.useCallback(()=>{d&&s(d)},[d,s]);if(!d)return null;const y=d.original_price?Math.round((1-d.price/d.original_price)*100):null;return l.jsxs("div",{className:"absolute bottom-20 left-0 right-0 z-20 overflow-hidden pointer-events-none",style:{height:"72px"},children:[l.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-auto",style:{transform:`translateX(${c}%)`,transition:"transform 0.5s ease-out"},children:l.jsxs("button",{onClick:f,className:"group flex items-center gap-4 px-6 py-3 rounded-xl shadow-2xl transition-all hover:scale-105 active:scale-95",style:{background:g?"linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(17, 24, 39, 0.9) 100%)":"linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(248, 250, 252, 0.98) 100%)",border:`2px solid ${h}`,boxShadow:`0 8px 32px -4px ${h}40, 0 4px 16px -2px rgba(0,0,0,0.2)`},children:[l.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center shrink-0",style:{background:`${h}20`},children:l.jsx("svg",{className:"w-5 h-5",fill:h,viewBox:"0 0 24 24",children:l.jsx("path",{d:"M11.645 20.91l-.007-.003-.022-.012a15.247 15.247 0 01-.383-.218 25.18 25.18 0 01-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0112 5.052 5.5 5.5 0 0116.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 01-4.244 3.17 15.247 15.247 0 01-.383.219l-.022.012-.007.004-.003.001a.752.752 0 01-.704 0l-.003-.001z"})})}),l.jsxs("div",{className:"flex flex-col items-start min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-xs font-bold uppercase tracking-wider",style:{color:h},children:"⚡ Spark Deal"}),y&&y>0&&l.jsxs("span",{className:"text-xs font-bold px-2 py-0.5 rounded-full",style:{background:h,color:g?"#000":"#fff"},children:[y,"% OFF"]})]}),l.jsxs("p",{className:"text-sm font-semibold truncate max-w-[200px]",style:{color:g?"#fff":"#111827"},children:[d.brand," ",d.product_name]})]}),l.jsxs("div",{className:"flex flex-col items-end shrink-0",children:[d.original_price&&d.original_price>d.price&&l.jsxs("span",{className:"text-xs line-through",style:{color:g?"#9ca3af":"#6b7280"},children:["$",d.original_price.toFixed(2)]}),l.jsxs("span",{className:"text-xl font-bold",style:{color:h},children:["$",d.price.toFixed(2)]})]}),l.jsx("svg",{className:"w-5 h-5 opacity-60 group-hover:opacity-100 group-hover:translate-x-1 transition-all",fill:"none",stroke:h,strokeWidth:2,viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8.25 4.5l7.5 7.5-7.5 7.5"})})]})}),t.length>1&&l.jsx("div",{className:"absolute bottom-1 left-0 right-0 flex justify-center gap-1.5",children:t.map((b,_)=>l.jsx("div",{className:"w-1.5 h-1.5 rounded-full transition-all",style:{background:_===e?h:`${h}40`,transform:_===e?"scale(1.3)":"scale(1)"}},_))})]})},sa=["*",":","=",">","<","+","-","|","•","○","●","◆","◇","0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","K","M","N","P","R","S","T","X","Z","#","@","$","%","&","~","^","/","\\","[","]","{","}"],na=["BR","KE","OI","FI","LT","SP","RK","EN","GN","PT","CL","UT","AX","WH","EL","TI","RE","PA","DS","RO","TR","BT","HP","CV","XL"],Wd=({phase:t,message:e,onComplete:r,onSparkDealClick:s,subliminalBrands:n=[]})=>{const i=p.useRef(null),a=p.useRef(),o=p.useRef([]),c=p.useRef(0),[u,d]=p.useState(0),[h,g]=p.useState(!1),[f,y]=p.useState(0),{data:b}=So(),{data:_}=Ud(),{data:v}=Eo(t!=="hidden"&&(_==null?void 0:_.enabled)),S=b||{primaryHex:"#0066CC",secondaryHex:"#004999",successHex:"#FF9500",backgroundHex:"#111827",sparkDealHex:"#FF9500",backgroundMode:"dark"},j=_||{enabled:!0,inRain:!0,rainFrequency:.15,primingEnabled:!0,bannerEnabled:!0,delayMs:2e3,scrollSpeed:5e3,maxPerSession:3,minResearchTime:1500},x=v&&j.inRain?[...Md(v),...n]:n,A=.08,k=p.useCallback(()=>x.length>0&&Math.random()<A?{char:x[Math.floor(Math.random()*x.length)],isSubliminal:!0}:Math.random()<.15?{char:na[Math.floor(Math.random()*na.length)],isSubliminal:!1}:{char:sa[Math.floor(Math.random()*sa.length)],isSubliminal:!1},[x]),F=p.useCallback((R,N)=>R.isSubliminal?S.sparkDealHex:t==="success"?S.successHex:Math.sin(N*2+R.x*.01)*.5+.5>.5?S.primaryHex:S.secondaryHex,[t,S]),E=p.useCallback((R,N)=>{const C=[],L=Math.floor(R/25);for(let K=0;K<L;K++){const{char:H,isSubliminal:Y}=k();C.push({x:K*25+12,y:Math.random()*N,speed:1.5+Math.random()*3.5,char:H,isSubliminal:Y,opacity:.2+Math.random()*.6,size:Y?13:9+Math.random()*3,glowIntensity:Y?.6:0,changeCounter:Math.floor(Math.random()*30)})}o.current=C},[k]);p.useEffect(()=>{if(t==="hidden"){a.current&&cancelAnimationFrame(a.current);return}const R=i.current;if(!R)return;const N=R.getContext("2d");if(!N)return;const C=()=>{R.width=R.offsetWidth*window.devicePixelRatio,R.height=R.offsetHeight*window.devicePixelRatio,N.scale(window.devicePixelRatio,window.devicePixelRatio),E(R.offsetWidth,R.offsetHeight)};C(),c.current=Date.now();const L=()=>{const K=R.offsetWidth,H=R.offsetHeight,Z=(Date.now()-c.current)/1e3;if(N.clearRect(0,0,K,H),o.current.forEach(W=>{const V=F(W,Z);if(N.font=`bold ${W.size}px monospace`,N.fillStyle=V,N.globalAlpha=W.opacity,W.isSubliminal&&W.glowIntensity>0?(N.shadowColor=S.sparkDealHex,N.shadowBlur=8*W.glowIntensity):N.shadowBlur=0,N.fillText(W.char,W.x,W.y),W.y+=W.speed,W.changeCounter++,W.changeCounter>20+Math.random()*40){const{char:ge,isSubliminal:te}=k();W.char=ge,W.isSubliminal=te,W.size=te?13:9+Math.random()*3,W.glowIntensity=te?.6:0,W.changeCounter=0}if(W.y>H+20){const{char:ge,isSubliminal:te}=k();W.y=-20,W.char=ge,W.isSubliminal=te,W.speed=1.5+Math.random()*3.5,W.opacity=.2+Math.random()*.6,W.size=te?13:9+Math.random()*3,W.glowIntensity=te?.6:0,W.changeCounter=0}}),N.globalAlpha=1,N.shadowBlur=0,t==="success"){const W=Math.max(0,1-Z*2);W>0&&(N.fillStyle=`rgba(255, 149, 0, ${W*.3})`,N.fillRect(0,0,K,H)),Z>.5&&r&&r()}a.current=requestAnimationFrame(L)};return L(),window.addEventListener("resize",C),()=>{a.current&&cancelAnimationFrame(a.current),window.removeEventListener("resize",C)}},[t,S,k,F,E,r]),p.useEffect(()=>{if(t==="hidden"||!v||v.length===0||!j.bannerEnabled){g(!1);return}if(f>=j.maxPerSession)return;const R=setTimeout(()=>{g(!0)},j.delayMs);return()=>clearTimeout(R)},[t,v,j,f]);const O=p.useCallback(R=>{d(R),y(N=>N+1)},[]),T=p.useCallback(R=>{console.log("[MatrixLoader] Spark deal clicked:",R.product_name),s==null||s(R)},[s]);return t==="hidden"?null:l.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center overflow-hidden pointer-events-none",style:{background:"transparent"},children:[l.jsx("canvas",{ref:i,className:"absolute inset-0 w-full h-full",style:{opacity:.85}}),h&&v&&v.length>0&&l.jsx(jo,{deals:v.slice(0,j.maxPerSession),currentDealIndex:u,onDealChange:O,onDealClick:T,scrollSpeed:j.scrollSpeed,theme:S})]})},qd=({currentImage:t,animationState:e,backdropUrl:r,counterOverlayUrl:s,counterHeightPercent:n=22,products:i,servicePackages:a,highlightedPartType:o,highlightedProduct:c,onProductClick:u,onPackageSelect:d,isResearching:h,vehicle:g,onChangeVehicle:f,bobOffset:y=0,bobScale:b=100,bobHasArrived:_=!0,externalBobPosition:v,onBobPositionChange:S,pendingVariants:j,pendingVariantMake:x,pendingVariantModel:A,onVariantSelect:k})=>{const F=ln(),E=ii(),[O,T]=p.useState("center"),[R,N]=p.useState("hidden"),C=v??O,L=p.useCallback(ie=>{T(ie),S==null||S(ie)},[S]),K=i.length>0||a.length>0,H=((j==null?void 0:j.length)??0)>0,Y=K||H,V=(()=>{switch(F){case"desktop":return 80*E.uiScale;case"tablet":return 90*E.uiScale;case"mobile":return 140;default:return 140}})()*b/100;p.useEffect(()=>{if(h&&R!=="loading"&&R!=="visible"){if(H){C==="center"&&L("partial-left");return}N("loading"),C==="center"&&L("partial-left")}else if(Y&&R!=="visible")if(C==="center"){L("partial-left"),N("transitioning");const ie=setTimeout(()=>{N("visible")},400);return()=>clearTimeout(ie)}else N("visible");else!Y&&!h&&R!=="hidden"&&(H||(N("hidden"),L("center")))},[Y,H,h,R,C,L]);const ge=R!=="hidden"||H,te=ge&&Y;return l.jsxs("div",{className:"absolute inset-0 overflow-hidden",style:{width:"100%",height:"100%",touchAction:"manipulation",isolation:"isolate",WebkitUserSelect:"none",userSelect:"none",WebkitTouchCallout:"none"},children:[r&&l.jsxs(l.Fragment,{children:[l.jsx("img",{src:r,alt:"Shop backdrop",className:"absolute inset-0 z-0 w-full h-full object-cover object-center transition-all duration-500",style:{pointerEvents:"none",filter:te?"blur(var(--bob-blur-intensity, 0px))":"none",transform:te?"scale(1.02)":"scale(1)",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"},draggable:!1}),l.jsx("div",{className:"absolute inset-0 z-[1] transition-opacity duration-500 pointer-events-none",style:{background:"rgba(0, 0, 0, var(--bob-overlay-opacity, 0.1))",opacity:te?1:0}})]}),l.jsx(cn,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:V,position:C,verticalOffset:y,hasArrived:_}),l.jsx(un,{products:i,servicePackages:a,highlightedPartType:o,highlightedProduct:c,onProductClick:u,onPackageSelect:d,isResearching:h,visible:ge,counterHeightPercent:n,hasVehicle:!!g,pendingVariants:j,pendingVariantMake:x,pendingVariantModel:A,onVariantSelect:k})]})},Hd=6e4,zd=({states:t,setAnimationState:e,manualMode:r})=>{const[s,n]=p.useState("page_load"),[i,a]=p.useState(!1),o=p.useRef(null),c=p.useCallback(T=>{const R=t.find(N=>N.chat_trigger===T&&N.is_active);return console.log(`[StateTransitions] Looking for trigger: "${T}" -> found:`,(R==null?void 0:R.state_key)||"none"),R},[t]),u=p.useCallback(()=>t.find(T=>T.chat_trigger==="processing_input"||T.state_key==="research"||T.state_key==="researching"||T.title.toLowerCase().includes("research")||T.title.toLowerCase().includes("thinking")),[t]),d=p.useCallback(()=>t.find(T=>T.chat_trigger==="streaming_response"||T.state_key==="talk"||T.state_key==="talking"||T.title.toLowerCase().includes("talk")),[t]),h=p.useCallback(()=>t.find(T=>T.chat_trigger==="awaiting_input"||T.state_key==="talk_pause"||T.state_key==="listening"||T.title.toLowerCase().includes("listen")||T.title.toLowerCase().includes("pause")),[t]),g=p.useCallback(()=>{const T=t.find(R=>R.chat_trigger==="response_complete"||R.state_key==="complete"||R.title.toLowerCase().includes("complete"));return T||t.find(R=>R.state_key==="idle"||R.title.toLowerCase().includes("idle"))},[t]),f=p.useCallback(()=>t.find(T=>T.chat_trigger==="idle"||T.state_key==="idle"||T.title.toLowerCase().includes("idle")),[t]),y=p.useCallback(T=>{const R=t.find(N=>N.state_key===T);return{speed:(R==null?void 0:R.animation_speed)||400,pauseDuration:(R==null?void 0:R.pause_duration)||0,loopCount:(R==null?void 0:R.loop_count)||0}},[t]),b=p.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),_=p.useCallback(()=>{b(),!r&&(o.current=setTimeout(()=>{const T=f();T&&(n("idle"),e(T.state_key))},Hd))},[r,f,e,b]),v=p.useCallback(T=>{if(r)return;const R=c(T);R&&e(R.state_key)},[r,c,e]),S=p.useCallback(()=>{if(r)return;const T=h();T&&(n("awaiting_input"),e(T.state_key),_())},[r,h,e,_]),j=p.useCallback(()=>{i||r||(a(!0),n("page_load"),v("page_load"),setTimeout(()=>{S()},3e3))},[i,r,v,S]),x=p.useCallback(()=>{if(r)return;b(),n("processing_input");const T=u();console.log("[StateTransitions] User input - switching to RESEARCH:",T==null?void 0:T.state_key),T?e(T.state_key):v("processing_input")},[r,b,u,e,v]),A=p.useCallback(()=>{if(r)return;b(),n("streaming_response");const T=d();console.log("[StateTransitions] Speech started - switching to TALK:",T==null?void 0:T.state_key),T&&e(T.state_key)},[r,b,d,e]),k=p.useCallback(()=>{if(r)return;const T=g();console.log("[StateTransitions] Speech ended - switching to COMPLETE:",T==null?void 0:T.state_key),T&&e(T.state_key),setTimeout(()=>{r||S()},2e3)},[r,g,e,S]),F=p.useCallback(()=>{b(),n("streaming_response"),console.log("[StateTransitions] Stream started (API response)")},[b]),E=p.useCallback(()=>{n("response_complete"),console.log("[StateTransitions] Stream complete (API finished)");const T=g();T&&e(T.state_key),setTimeout(()=>{S()},2e3)},[g,e,S]),O=p.useCallback(()=>{if(r)return;n("showing_product"),console.log("[StateTransitions] Showing products");const T=t.find(R=>R.chat_trigger==="showing_product"||R.state_key==="showing_product");T&&e(T.state_key),setTimeout(()=>{S()},3e3)},[r,t,e,S]);return p.useEffect(()=>()=>b(),[b]),{chatStage:s,initialize:j,onUserInput:x,onSpeechStart:A,onSpeechEnd:k,onStreamStart:F,onStreamComplete:E,onShowingProduct:O,getStateSettings:y}},Kd=()=>{const t=_r();return{checkHealth:async()=>{if(!t)return{healthy:!1,reason:"No Supabase client available - ensure BobProvider is configured",stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};try{const{data:r,error:s}=await t.from("bob_looks").select("id, name, is_active").eq("is_active",!0).limit(1);if(s)return{healthy:!1,reason:`Database error fetching looks: ${s.message}`,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const n=r==null?void 0:r[0];if(!n)return{healthy:!1,reason:"No active look configured in bob_looks table",stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const{data:i,error:a}=await t.from("animation_states").select("state_key").eq("is_active",!0).eq("look_id",n.id);if(a)return{healthy:!1,reason:`Database error fetching states: ${a.message}`,activeLookId:n.id,activeLookName:n.name,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0};const o=(i==null?void 0:i.map(y=>y.state_key))||[],u=["idle","talking","listening"].filter(y=>{const b=[y,y.replace("ing",""),y+"ing"];return!o.some(_=>b.includes(_))}),{data:d,error:h}=await t.from("bob_animations").select("id").eq("is_active",!0).eq("look_id",n.id),g=h?0:(d==null?void 0:d.length)||0,f=o.length>=4&&g>0&&u.length===0;return{healthy:f,reason:f?void 0:`Missing critical states: ${u.join(", ")}`,activeLookId:n.id,activeLookName:n.name,stateCount:o.length,states:o,missingCritical:u,frameCount:g}}catch(r){return{healthy:!1,reason:`Unexpected error: ${r instanceof Error?r.message:"Unknown"}`,stateCount:0,states:[],missingCritical:["idle","talking","listening"],frameCount:0}}}}};console.log(`[BobWidget] Package loaded - v${Bt}`);exports.BADGE_CONFIG=to;exports.BOB_VERSION=Bt;exports.Bob=oi;exports.BobCharacter=eo;exports.BobDebugOverlay=xo;exports.BobProvider=ri;exports.BobStandalone=$d;exports.BobSuggestions=ni;exports.BobWidget=Pd;exports.CARFIX_COLORS=G;exports.ChatInterface=io;exports.ContainedChatDrawer=mo;exports.ContainedMobileBobLayout=vo;exports.IMAGE_URLS=Ss;exports.MatrixProductLoader=Wd;exports.MobileBobCharacter=cn;exports.MobileBobLayout=bo;exports.MobileBobLayoutCore=qd;exports.MobileChatDrawer=go;exports.MobileProductColumn=un;exports.ProductBadge=ls;exports.ProductTile=oo;exports.QUALITY_TIER_CONFIG=tn;exports.ServicePackageDetailView=yo;exports.SparkDealBanner=jo;exports.SwipeableBob=Dd;exports.TYPOGRAPHY=vt;exports.formatNZD=nt;exports.getBobVersion=Ro;exports.getDisplayPrice=so;exports.getFeatureFlag=ko;exports.isRotorProduct=ro;exports.useBobAnalytics=Ha;exports.useBobAnalyticsConfig=dd;exports.useBobAnimation=Xa;exports.useBobAnimationData=Ya;exports.useBobBackdrop=Za;exports.useBobCallbacks=ud;exports.useBobChat=Qa;exports.useBobContext=Lt;exports.useBobHealthCheck=Kd;exports.useBobLayoutConfig=si;exports.useBobStateTransitions=zd;exports.useBobSupabase=od;exports.useBobSupabaseSafe=_r;exports.useHostApiConfig=cd;exports.useHostContext=ld;exports.useMicPermission=wo;exports.usePartnerConfig=_o;exports.useReturningUser=Ja;exports.useSparkDeals=Eo;exports.useSpeechRecognition=ai;exports.useSpeechSynthesis=Ga;exports.useThemeSettings=So;