@gymmymac/bob-widget 3.2.3 → 3.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/BOB-DOCUMENTATION.md +17 -134
- package/CHANGELOG.md +7 -0
- package/README.md +11 -8
- package/dist/__tests__/bobV2DirectorModes.test.d.ts +10 -0
- package/dist/__tests__/quickReplyAndStopSpeech.test.d.ts +11 -0
- package/dist/components/BobStandalone.d.ts +18 -1
- package/dist/components/mobile/ContainedChatDrawer.d.ts +4 -0
- package/dist/components/mobile/ContainedMobileBobLayout.d.ts +4 -0
- package/dist/components/mobile/MobileBobLayout.d.ts +4 -0
- package/dist/components/mobile/MobileChatDrawer.d.ts +4 -0
- package/dist/hooks/useBobAnalytics.d.ts +12 -1
- package/dist/hooks/useBobChat.d.ts +2 -0
- package/dist/hooks/useMicPermission.d.ts +12 -0
- package/dist/hooks/useSpeechSynthesis.d.ts +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +32 -32
- package/dist/index.mjs +4080 -3791
- package/dist/types/context.d.ts +5 -0
- package/dist/types/message.d.ts +8 -0
- package/package.json +1 -1
- package/install/carfix/00-README-PREINSTALL.md +0 -111
- package/install/carfix/05-runtime-verification-checklist.md +0 -54
- package/install/carfix/CARFIX-INSTALLATION-BRIEF.md +0 -367
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Jn=t=>{throw TypeError(t)};var Ys=(t,e,r)=>e.has(t)||Jn("Cannot "+r);var k=(t,e,r)=>(Ys(t,e,"read from private field"),r?r.call(t):e.get(t)),te=(t,e,r)=>e.has(t)?Jn("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),H=(t,e,r,s)=>(Ys(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),fe=(t,e,r)=>(Ys(t,e,"access private method"),r);var js=(t,e,r,s)=>({set _(n){H(t,e,n,r)},get _(){return k(t,e,s)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("react");function Za(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 at=Za(g),At="3.2.4",eo=()=>At;var cn={exports:{}},Jr={};/**
|
|
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
|
|
9
|
+
*/var Qn;function to(){if(Qn)return Jr;Qn=1;var t=g,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={},f=null,p=null;u!==void 0&&(f=""+u),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(p=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:f,ref:p,props:h,_owner:n.current}}return Jr.Fragment=r,Jr.jsx=a,Jr.jsxs=a,Jr}var Qr={};/**
|
|
10
10
|
* @license React
|
|
11
11
|
* react-jsx-runtime.development.js
|
|
12
12
|
*
|
|
@@ -14,32 +14,32 @@
|
|
|
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
|
|
18
|
-
`+_e+
|
|
19
|
-
`),
|
|
20
|
-
`),
|
|
21
|
-
`+
|
|
17
|
+
*/var Yn;function ro(){return Yn||(Yn=1,process.env.NODE_ENV!=="production"&&function(){var t=g,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"),f=Symbol.for("react.lazy"),p=Symbol.for("react.offscreen"),y=Symbol.iterator,b="@@iterator";function m(w){if(w===null||typeof w!="object")return null;var N=y&&w[y]||w[b];return typeof N=="function"?N:null}var v=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function x(w){{for(var N=arguments.length,q=new Array(N>1?N-1:0),ne=1;ne<N;ne++)q[ne-1]=arguments[ne];S("error",w,q)}}function S(w,N,q){{var ne=v.ReactDebugCurrentFrame,be=ne.getStackAddendum();be!==""&&(N+="%s",q=q.concat([be]));var de=q.map(function(ae){return String(ae)});de.unshift("Warning: "+N),Function.prototype.apply.call(console[w],console,de)}}var _=!1,C=!1,I=!1,O=!1,E=!1,B;B=Symbol.for("react.module.reference");function j(w){return!!(typeof w=="string"||typeof w=="function"||w===s||w===i||E||w===n||w===u||w===d||O||w===p||_||C||I||typeof w=="object"&&w!==null&&(w.$$typeof===f||w.$$typeof===h||w.$$typeof===a||w.$$typeof===l||w.$$typeof===c||w.$$typeof===B||w.getModuleId!==void 0))}function R(w,N,q){var ne=w.displayName;if(ne)return ne;var be=N.displayName||N.name||"";return be!==""?q+"("+be+")":q}function A(w){return w.displayName||"Context"}function T(w){if(w==null)return null;if(typeof w.tag=="number"&&x("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof w=="function")return w.displayName||w.name||null;if(typeof w=="string")return w;switch(w){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 w=="object")switch(w.$$typeof){case l:var N=w;return A(N)+".Consumer";case a:var q=w;return A(q._context)+".Provider";case c:return R(w,w.render,"ForwardRef");case h:var ne=w.displayName||null;return ne!==null?ne:T(w.type)||"Memo";case f:{var be=w,de=be._payload,ae=be._init;try{return T(ae(de))}catch{return null}}}return null}var F=Object.assign,M=0,K,ee,Z,z,V,le,G;function L(){}L.__reactDisabledLog=!0;function D(){{if(M===0){K=console.log,ee=console.info,Z=console.warn,z=console.error,V=console.group,le=console.groupCollapsed,G=console.groupEnd;var w={configurable:!0,enumerable:!0,value:L,writable:!0};Object.defineProperties(console,{info:w,log:w,warn:w,error:w,group:w,groupCollapsed:w,groupEnd:w})}M++}}function U(){{if(M--,M===0){var w={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:F({},w,{value:K}),info:F({},w,{value:ee}),warn:F({},w,{value:Z}),error:F({},w,{value:z}),group:F({},w,{value:V}),groupCollapsed:F({},w,{value:le}),groupEnd:F({},w,{value:G})})}M<0&&x("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var Q=v.ReactCurrentDispatcher,_e;function Se(w,N,q){{if(_e===void 0)try{throw Error()}catch(be){var ne=be.stack.trim().match(/\n( *(at )?)/);_e=ne&&ne[1]||""}return`
|
|
18
|
+
`+_e+w}}var Re=!1,Ne;{var Me=typeof WeakMap=="function"?WeakMap:Map;Ne=new Me}function Pe(w,N){if(!w||Re)return"";{var q=Ne.get(w);if(q!==void 0)return q}var ne;Re=!0;var be=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var de;de=Q.current,Q.current=null,D();try{if(N){var ae=function(){throw Error()};if(Object.defineProperty(ae.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ae,[])}catch(he){ne=he}Reflect.construct(w,[],ae)}else{try{ae.call()}catch(he){ne=he}w.call(ae.prototype)}}else{try{throw Error()}catch(he){ne=he}w()}}catch(he){if(he&&ne&&typeof he.stack=="string"){for(var oe=he.stack.split(`
|
|
19
|
+
`),Be=ne.stack.split(`
|
|
20
|
+
`),we=oe.length-1,Ce=Be.length-1;we>=1&&Ce>=0&&oe[we]!==Be[Ce];)Ce--;for(;we>=1&&Ce>=0;we--,Ce--)if(oe[we]!==Be[Ce]){if(we!==1||Ce!==1)do if(we--,Ce--,Ce<0||oe[we]!==Be[Ce]){var $=`
|
|
21
|
+
`+oe[we].replace(" at new "," at ");return w.displayName&&$.includes("<anonymous>")&&($=$.replace("<anonymous>",w.displayName)),typeof w=="function"&&Ne.set(w,$),$}while(we>=1&&Ce>=0);break}}}finally{Re=!1,Q.current=de,U(),Error.prepareStackTrace=be}var kt=w?w.displayName||w.name:"",Ee=kt?Se(kt):"";return typeof w=="function"&&Ne.set(w,Ee),Ee}function qe(w,N,q){return Pe(w,!1)}function ft(w){var N=w.prototype;return!!(N&&N.isReactComponent)}function P(w,N,q){if(w==null)return"";if(typeof w=="function")return Pe(w,ft(w));if(typeof w=="string")return Se(w);switch(w){case u:return Se("Suspense");case d:return Se("SuspenseList")}if(typeof w=="object")switch(w.$$typeof){case c:return qe(w.render);case h:return P(w.type,N,q);case f:{var ne=w,be=ne._payload,de=ne._init;try{return P(de(be),N,q)}catch{}}}return""}var X=Object.prototype.hasOwnProperty,ce={},me=v.ReactDebugCurrentFrame;function ze(w){if(w){var N=w._owner,q=P(w.type,w._source,N?N.type:null);me.setExtraStackFrame(q)}else me.setExtraStackFrame(null)}function ie(w,N,q,ne,be){{var de=Function.call.bind(X);for(var ae in w)if(de(w,ae)){var oe=void 0;try{if(typeof w[ae]!="function"){var Be=Error((ne||"React class")+": "+q+" type `"+ae+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof w[ae]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw Be.name="Invariant Violation",Be}oe=w[ae](N,ae,ne,q,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(we){oe=we}oe&&!(oe instanceof Error)&&(ze(be),x("%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).",ne||"React class",q,ae,typeof oe),ze(null)),oe instanceof Error&&!(oe.message in ce)&&(ce[oe.message]=!0,ze(be),x("Failed %s type: %s",q,oe.message),ze(null))}}}var Te=Array.isArray;function ue(w){return Te(w)}function Gt(w){{var N=typeof Symbol=="function"&&Symbol.toStringTag,q=N&&w[Symbol.toStringTag]||w.constructor.name||"Object";return q}}function Gn(w){try{return Js(w),!1}catch{return!0}}function Js(w){return""+w}function Hr(w){if(Gn(w))return x("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",Gt(w)),Js(w)}var Kr=v.ReactCurrentOwner,Ss={key:!0,ref:!0,__self:!0,__source:!0},Vr,W;function ge(w){if(X.call(w,"ref")){var N=Object.getOwnPropertyDescriptor(w,"ref").get;if(N&&N.isReactWarning)return!1}return w.ref!==void 0}function ye(w){if(X.call(w,"key")){var N=Object.getOwnPropertyDescriptor(w,"key").get;if(N&&N.isReactWarning)return!1}return w.key!==void 0}function ve(w,N){typeof w.ref=="string"&&Kr.current}function Ve(w,N){{var q=function(){Vr||(Vr=!0,x("%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)",N))};q.isReactWarning=!0,Object.defineProperty(w,"key",{get:q,configurable:!0})}}function Jt(w,N){{var q=function(){W||(W=!0,x("%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)",N))};q.isReactWarning=!0,Object.defineProperty(w,"ref",{get:q,configurable:!0})}}var Qt=function(w,N,q,ne,be,de,ae){var oe={$$typeof:e,type:w,key:N,ref:q,props:ae,_owner:de};return oe._store={},Object.defineProperty(oe._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(oe,"_self",{configurable:!1,enumerable:!1,writable:!1,value:ne}),Object.defineProperty(oe,"_source",{configurable:!1,enumerable:!1,writable:!1,value:be}),Object.freeze&&(Object.freeze(oe.props),Object.freeze(oe)),oe};function Yt(w,N,q,ne,be){{var de,ae={},oe=null,Be=null;q!==void 0&&(Hr(q),oe=""+q),ye(N)&&(Hr(N.key),oe=""+N.key),ge(N)&&(Be=N.ref,ve(N,be));for(de in N)X.call(N,de)&&!Ss.hasOwnProperty(de)&&(ae[de]=N[de]);if(w&&w.defaultProps){var we=w.defaultProps;for(de in we)ae[de]===void 0&&(ae[de]=we[de])}if(oe||Be){var Ce=typeof w=="function"?w.displayName||w.name||"Unknown":w;oe&&Ve(ae,Ce),Be&&Jt(ae,Ce)}return Qt(w,oe,Be,be,ne,Kr.current,ae)}}var It=v.ReactCurrentOwner,Nt=v.ReactDebugCurrentFrame;function st(w){if(w){var N=w._owner,q=P(w.type,w._source,N?N.type:null);Nt.setExtraStackFrame(q)}else Nt.setExtraStackFrame(null)}var Ye;Ye=!1;function Bt(w){return typeof w=="object"&&w!==null&&w.$$typeof===e}function Xt(){{if(It.current){var w=T(It.current.type);if(w)return`
|
|
22
22
|
|
|
23
|
-
Check the render method of \``+
|
|
23
|
+
Check the render method of \``+w+"`."}return""}}function pt(w){return""}var Zt={};function wr(w){{var N=Xt();if(!N){var q=typeof w=="string"?w:w.displayName||w.name;q&&(N=`
|
|
24
24
|
|
|
25
|
-
Check the top-level render call using <`+
|
|
25
|
+
Check the top-level render call using <`+q+">.")}return N}}function wt(w,N){{if(!w._store||w._store.validated||w.key!=null)return;w._store.validated=!0;var q=wr(N);if(Zt[q])return;Zt[q]=!0;var ne="";w&&w._owner&&w._owner!==It.current&&(ne=" It was passed a child from "+T(w._owner.type)+"."),st(w),x('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',q,ne),st(null)}}function Xe(w,N){{if(typeof w!="object")return;if(ue(w))for(var q=0;q<w.length;q++){var ne=w[q];Bt(ne)&&wt(ne,N)}else if(Bt(w))w._store&&(w._store.validated=!0);else if(w){var be=m(w);if(typeof be=="function"&&be!==w.entries)for(var de=be.call(w),ae;!(ae=de.next()).done;)Bt(ae.value)&&wt(ae.value,N)}}}function er(w){{var N=w.type;if(N==null||typeof N=="string")return;var q;if(typeof N=="function")q=N.propTypes;else if(typeof N=="object"&&(N.$$typeof===c||N.$$typeof===h))q=N.propTypes;else return;if(q){var ne=T(N);ie(q,w.props,"prop",ne,w)}else if(N.PropTypes!==void 0&&!Ye){Ye=!0;var be=T(N);x("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",be||"Unknown")}typeof N.getDefaultProps=="function"&&!N.getDefaultProps.isReactClassApproved&&x("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function He(w){{for(var N=Object.keys(w.props),q=0;q<N.length;q++){var ne=N[q];if(ne!=="children"&&ne!=="key"){st(w),x("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",ne),st(null);break}}w.ref!==null&&(st(w),x("Invalid attribute `ref` supplied to `React.Fragment`."),st(null))}}var Ze={};function et(w,N,q,ne,be,de){{var ae=j(w);if(!ae){var oe="";(w===void 0||typeof w=="object"&&w!==null&&Object.keys(w).length===0)&&(oe+=" 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 Be=pt();Be?oe+=Be:oe+=Xt();var we;w===null?we="null":ue(w)?we="array":w!==void 0&&w.$$typeof===e?(we="<"+(T(w.type)||"Unknown")+" />",oe=" Did you accidentally export a JSX literal instead of a component?"):we=typeof w,x("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",we,oe)}var Ce=Yt(w,N,q,be,de);if(Ce==null)return Ce;if(ae){var $=N.children;if($!==void 0)if(ne)if(ue($)){for(var kt=0;kt<$.length;kt++)Xe($[kt],w);Object.freeze&&Object.freeze($)}else x("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 Xe($,w)}if(X.call(N,"key")){var Ee=T(w),he=Object.keys(N).filter(function(St){return St!=="key"}),ke=he.length>0?"{key: someKey, "+he.join(": ..., ")+": ...}":"{key: someKey}";if(!Ze[Ee+ke]){var gt=he.length>0?"{"+he.join(": ..., ")+": ...}":"{}";x(`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} />`,
|
|
30
|
+
<%s key={someKey} {...props} />`,ke,Ee,gt,Ee),Ze[Ee+ke]=!0}}return w===s?He(Ce):er(Ce),Ce}}function xt(w,N,q){return et(w,N,q,!0)}function Gr(w,N,q){return et(w,N,q,!1)}var _t=Gr,Es=xt;Qr.Fragment=s,Qr.jsx=_t,Qr.jsxs=Es}()),Qr}process.env.NODE_ENV==="production"?cn.exports=to():cn.exports=ro();var o=cn.exports;function Ms(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 so(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 no=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class Ln extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}}class io extends Ln{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class Xn extends Ln{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Zn extends Ln{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var un;(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"})(un||(un={}));class ao{constructor(e,{headers:r={},customFetch:s,region:n=un.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=no(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return so(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 f={},{region:p}=s;p||(p=this.region);const y=new URL(`${this.url}/${r}`);p&&p!=="any"&&(f["x-region"]=p,y.searchParams.set("forceFunctionRegion",p));let b;u&&(l&&!Object.prototype.hasOwnProperty.call(l,"Content-Type")||!l)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",b=u):typeof u=="string"?(f["Content-Type"]="text/plain",b=u):typeof FormData<"u"&&u instanceof FormData?b=u:(f["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 m=d;h&&(a=new AbortController,i=setTimeout(()=>a.abort(),h),d?(m=a.signal,d.addEventListener("abort",()=>a.abort())):m=a.signal);const v=yield this.fetch(y.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),l),body:b,signal:m}).catch(C=>{throw new io(C)}),x=v.headers.get("x-relay-error");if(x&&x==="true")throw new Xn(v);if(!v.ok)throw new Zn(v);let S=((n=v.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),_;return S==="application/json"?_=yield v.json():S==="application/octet-stream"||S==="application/pdf"?_=yield v.blob():S==="text/event-stream"?_=v:S==="multipart/form-data"?_=yield v.formData():_=yield v.text(),{data:_,error:null,response:v}}catch(l){return{data:null,error:l,response:l instanceof Zn||l instanceof Xn?l.context:void 0}}finally{i&&clearTimeout(i)}})}}var oo=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},lo=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,f;if(r.method!=="HEAD"){var p;const v=await i.text();v===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((p=r.headers.get("Accept"))===null||p===void 0)&&p.includes("application/vnd.pgrst.plan+text"))?l=v:l=JSON.parse(v))}const b=(h=r.headers.get("Prefer"))===null||h===void 0?void 0:h.match(/count=(exact|planned|estimated)/),m=(f=i.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");b&&m&&m.length>1&&(c=parseInt(m[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 y;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||(y=a.details)===null||y===void 0)&&y.includes("0 rows"))&&(a=null,u=200,d="OK"),a&&r.shouldThrowOnError)throw new oo(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,f,p,y;const v=(h=d==null?void 0:d.message)!==null&&h!==void 0?h:"",x=(f=d==null?void 0:d.code)!==null&&f!==void 0?f:"";l=`${(p=i==null?void 0:i.name)!==null&&p!==void 0?p:"FetchError"}: ${i==null?void 0:i.message}`,l+=`
|
|
31
31
|
|
|
32
|
-
Caused by: ${(
|
|
33
|
-
${d.stack}`)}else{var m;l=(m=i==null?void 0:i.stack)!==null&&m!==void 0?m:""}const b=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)",b>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${b} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((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)",b>this.urlLengthLimit&&(c+=`. Your request URL is ${b} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{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}},oo=class extends ao{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 Xn=new RegExp("[,()]");var Er=class extends oo{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"&&Xn.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"&&Xn.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).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}},lo=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 Er({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 Er({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 Er({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 Er({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 Er({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function ns(t){"@babel/helpers - typeof";return ns=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},ns(t)}function co(t,e){if(ns(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(ns(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function uo(t){var e=co(t,"string");return ns(e)=="symbol"?e:e+""}function ho(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 Zn(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 Es(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Zn(Object(r),!0).forEach(function(s){ho(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Zn(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var fo=class Gi{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),f=u==null?void 0:u.signal;if(f){if(f.aborted)return clearTimeout(h),l(c,u);const p=()=>{clearTimeout(h),d.abort()};return f.addEventListener("abort",p,{once:!0}),l(c,Es(Es({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(h),f.removeEventListener("abort",p)})}return l(c,Es(Es({},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 lo(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Gi(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=p=>p!==null&&typeof p=="object"&&(!Array.isArray(p)||p.some(d)),h=s&&Object.values(r).some(d);h?(l="POST",u=r):s||n?(l=s?"HEAD":"GET",Object.entries(r).filter(([p,v])=>v!==void 0).map(([p,v])=>[p,Array.isArray(v)?`{${v.join(",")}}`:`${v}`]).forEach(([p,v])=>{c.searchParams.append(p,v)})):(l="POST",u=r);const f=new Headers(this.headers);return h?f.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&f.set("Prefer",`count=${i}`),new Er({method:l,url:c,headers:f,schema:this.schemaName,body:u,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};class po{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}`,x&&(l+=` (${x})`),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 m=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)",m>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${m} 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)",m>this.urlLengthLimit&&(c+=`. Your request URL is ${m} 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}},co=class extends lo{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 ei=new RegExp("[,()]");var Tr=class extends co{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"&&ei.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"&&ei.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).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}},uo=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 Tr({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 Tr({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 Tr({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 Tr({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 Tr({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function as(t){"@babel/helpers - typeof";return as=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},as(t)}function ho(t,e){if(as(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(as(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function fo(t){var e=ho(t,"string");return as(e)=="symbol"?e:e+""}function po(t,e,r){return(e=fo(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function ti(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 Ts(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?ti(Object(r),!0).forEach(function(s){po(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):ti(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var go=class Qi{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),f=u==null?void 0:u.signal;if(f){if(f.aborted)return clearTimeout(h),l(c,u);const p=()=>{clearTimeout(h),d.abort()};return f.addEventListener("abort",p,{once:!0}),l(c,Ts(Ts({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(h),f.removeEventListener("abort",p)})}return l(c,Ts(Ts({},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 uo(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Qi(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=p=>p!==null&&typeof p=="object"&&(!Array.isArray(p)||p.some(d)),h=s&&Object.values(r).some(d);h?(l="POST",u=r):s||n?(l=s?"HEAD":"GET",Object.entries(r).filter(([p,y])=>y!==void 0).map(([p,y])=>[p,Array.isArray(y)?`{${y.join(",")}}`:`${y}`]).forEach(([p,y])=>{c.searchParams.append(p,y)})):(l="POST",u=r);const f=new Headers(this.headers);return h?f.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&f.set("Prefer",`count=${i}`),new Tr({method:l,url:c,headers:f,schema:this.schemaName,body:u,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};class bo{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 go="2.95.3",bo=`realtime-js/${go}`,mo="1.0.0",Ji="2.0.0",ei=Ji,ln=1e4,yo=1e3,vo=100;var Ft;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(Ft||(Ft={}));var Ne;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(Ne||(Ne={}));var dt;(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"})(dt||(dt={}));var cn;(function(t){t.websocket="websocket"})(cn||(cn={}));var Zt;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(Zt||(Zt={}));class wo{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 f=this.USER_BROADCAST_PUSH_META_LENGTH+c.length+l.length+a.length+u.length+h.length,p=new ArrayBuffer(this.HEADER_LENGTH+f);let v=new DataView(p),m=0;v.setUint8(m++,this.KINDS.userBroadcastPush),v.setUint8(m++,c.length),v.setUint8(m++,l.length),v.setUint8(m++,a.length),v.setUint8(m++,u.length),v.setUint8(m++,h.length),v.setUint8(m++,r),Array.from(c,y=>v.setUint8(m++,y.charCodeAt(0))),Array.from(l,y=>v.setUint8(m++,y.charCodeAt(0))),Array.from(a,y=>v.setUint8(m++,y.charCodeAt(0))),Array.from(u,y=>v.setUint8(m++,y.charCodeAt(0))),Array.from(h,y=>v.setUint8(m++,y.charCodeAt(0)));var b=new Uint8Array(p.byteLength+s.byteLength);return b.set(new Uint8Array(p),0),b.set(new Uint8Array(s),p.byteLength),b.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 f=e.slice(c,e.byteLength),p=l===this.JSON_ENCODING?JSON.parse(s.decode(f)):f,v={type:this.BROADCAST_EVENT,event:d,payload:p};return a>0&&(v.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:v}}_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 Qi{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 xe;(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"})(xe||(xe={}));const ti=(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]=xo(a,t,e,n),i),{}):{}},xo=(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)?Yi(i,a):un(a)},Yi=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return Eo(e,r)}switch(t){case xe.bool:return _o(e);case xe.float4:case xe.float8:case xe.int2:case xe.int4:case xe.int8:case xe.numeric:case xe.oid:return ko(e);case xe.json:case xe.jsonb:return So(e);case xe.timestamp:return jo(e);case xe.abstime:case xe.date:case xe.daterange:case xe.int4range:case xe.int8range:case xe.money:case xe.reltime:case xe.text:case xe.time:case xe.timestamptz:case xe.timetz:case xe.tsrange:case xe.tstzrange:return un(e);default:return un(e)}},un=t=>t,_o=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},ko=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},So=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Eo=(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=>Yi(e,l))}return t},jo=t=>typeof t=="string"?t.replace(" ","T"):t,Xi=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 Js{constructor(e,r,s={},n=ln){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 ri;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(ri||(ri={}));class ts{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=ts.syncState(this.state,n,i,a),this.pendingDiffs.forEach(c=>{this.state=ts.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=ts.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 f=d.map(b=>b.presence_ref),p=h.map(b=>b.presence_ref),v=d.filter(b=>p.indexOf(b.presence_ref)<0),m=h.filter(b=>f.indexOf(b.presence_ref)<0);v.length>0&&(l[u]=v),m.length>0&&(c[u]=m)}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(p=>p.presence_ref),f=d.filter(p=>h.indexOf(p.presence_ref)<0);e[l].unshift(...f)}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 si;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(si||(si={}));var rs;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(rs||(rs={}));var xt;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(xt||(xt={}));class Rr{constructor(e,r={config:{}},s){var n,i;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.state=Ne.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 Js(this,dt.join,this.params,this.timeout),this.rejoinTimer=new Qi(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Ne.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=Ne.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=Ne.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Ne.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=Ne.errored,this.rejoinTimer.scheduleTimeout())}),this._on(dt.reply,{},(a,l)=>{this._trigger(this._replyEventName(l),a)}),this.presence=new ts(this),this.broadcastEndpointURL=Xi(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==Ne.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(p=>p.filter))!==null&&n!==void 0?n:[],d=!!this.bindings[rs.PRESENCE]&&this.bindings[rs.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,h={},f={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(p=>e==null?void 0:e(xt.CHANNEL_ERROR,p)),this._onClose(()=>e==null?void 0:e(xt.CLOSED)),this.updateJoinPayload(Object.assign({config:f},h)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:p})=>{var v;if(this.socket._isManualToken()||this.socket.setAuth(),p===void 0){e==null||e(xt.SUBSCRIBED);return}else{const m=this.bindings.postgres_changes,b=(v=m==null?void 0:m.length)!==null&&v!==void 0?v:0,y=[];for(let _=0;_<b;_++){const k=m[_],{filter:{event:w,schema:E,table:A,filter:F}}=k,N=p&&p[_];if(N&&N.event===w&&Rr.isFilterValueEqual(N.schema,E)&&Rr.isFilterValueEqual(N.table,A)&&Rr.isFilterValueEqual(N.filter,F))y.push(Object.assign(Object.assign({},k),{id:N.id}));else{this.unsubscribe(),this.state=Ne.errored,e==null||e(xt.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=y,e&&e(xt.SUBSCRIBED);return}}).receive("error",p=>{this.state=Ne.errored,e==null||e(xt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(p).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(xt.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===Ne.joined&&e===rs.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=Ne.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(dt.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(n=>{s=new Js(this,dt.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=Ne.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 Js(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>vo){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}=dt;if(s&&[l,c,u,d].indexOf(a)>=0&&s!==this._joinRef())return;let f=this._onMessage(a,r,s);if(r&&!f)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(p=>{var v,m,b;return((v=p.filter)===null||v===void 0?void 0:v.event)==="*"||((b=(m=p.filter)===null||m===void 0?void 0:m.event)===null||b===void 0?void 0:b.toLocaleLowerCase())===a}).map(p=>p.callback(f,s)):(i=this.bindings[a])===null||i===void 0||i.filter(p=>{var v,m,b,y,_,k;if(["broadcast","presence","postgres_changes"].includes(a))if("id"in p){const w=p.id,E=(v=p.filter)===null||v===void 0?void 0:v.event;return w&&((m=r.ids)===null||m===void 0?void 0:m.includes(w))&&(E==="*"||(E==null?void 0:E.toLocaleLowerCase())===((b=r.data)===null||b===void 0?void 0:b.type.toLocaleLowerCase()))}else{const w=(_=(y=p==null?void 0:p.filter)===null||y===void 0?void 0:y.event)===null||_===void 0?void 0:_.toLocaleLowerCase();return w==="*"||w===((k=r==null?void 0:r.event)===null||k===void 0?void 0:k.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===a}).map(p=>{if(typeof f=="object"&&"ids"in f){const v=f.data,{schema:m,table:b,commit_timestamp:y,type:_,errors:k}=v;f=Object.assign(Object.assign({},{schema:m,table:b,commit_timestamp:y,eventType:_,new:{},old:{},errors:k}),this._getPayloadRecords(v))}p.callback(f,s)})}_isClosed(){return this.state===Ne.closed}_isJoined(){return this.state===Ne.joined}_isJoining(){return this.state===Ne.joining}_isLeaving(){return this.state===Ne.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&&Rr.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(dt.close,{},e)}_onError(e){this._on(dt.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Ne.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=ti(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=ti(e.columns,e.old_record)),r}}const Qs=()=>{},js={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},To=[1e3,2e3,5e3,1e4],Ro=1e4,Co=`
|
|
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 mo="2.98.0",yo=`realtime-js/${mo}`,vo="1.0.0",Yi="2.0.0",ri=Yi,dn=1e4,wo=1e3,xo=100;var $t;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})($t||($t={}));var Fe;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(Fe||(Fe={}));var ht;(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"})(ht||(ht={}));var hn;(function(t){t.websocket="websocket"})(hn||(hn={}));var nr;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(nr||(nr={}));class _o{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 f=this.USER_BROADCAST_PUSH_META_LENGTH+c.length+l.length+a.length+u.length+h.length,p=new ArrayBuffer(this.HEADER_LENGTH+f);let y=new DataView(p),b=0;y.setUint8(b++,this.KINDS.userBroadcastPush),y.setUint8(b++,c.length),y.setUint8(b++,l.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(l,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 m=new Uint8Array(p.byteLength+s.byteLength);return m.set(new Uint8Array(p),0),m.set(new Uint8Array(s),p.byteLength),m.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 f=e.slice(c,e.byteLength),p=l===this.JSON_ENCODING?JSON.parse(s.decode(f)):f,y={type:this.BROADCAST_EVENT,event:d,payload:p};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)))}}class Xi{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 je;(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"})(je||(je={}));const si=(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]=ko(a,t,e,n),i),{}):{}},ko=(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)?Zi(i,a):fn(a)},Zi=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return To(e,r)}switch(t){case je.bool:return So(e);case je.float4:case je.float8:case je.int2:case je.int4:case je.int8:case je.numeric:case je.oid:return Eo(e);case je.json:case je.jsonb:return jo(e);case je.timestamp:return Ro(e);case je.abstime:case je.date:case je.daterange:case je.int4range:case je.int8range:case je.money:case je.reltime:case je.text:case je.time:case je.timestamptz:case je.timetz:case je.tsrange:case je.tstzrange:return fn(e);default:return fn(e)}},fn=t=>t,So=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},Eo=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},jo=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},To=(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=>Zi(e,l))}return t},Ro=t=>typeof t=="string"?t.replace(" ","T"):t,ea=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 Xs{constructor(e,r,s={},n=dn){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 ni;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(ni||(ni={}));class ss{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=ss.syncState(this.state,n,i,a),this.pendingDiffs.forEach(c=>{this.state=ss.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=ss.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 f=d.map(m=>m.presence_ref),p=h.map(m=>m.presence_ref),y=d.filter(m=>p.indexOf(m.presence_ref)<0),b=h.filter(m=>f.indexOf(m.presence_ref)<0);y.length>0&&(l[u]=y),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(p=>p.presence_ref),f=d.filter(p=>h.indexOf(p.presence_ref)<0);e[l].unshift(...f)}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 ii;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(ii||(ii={}));var ns;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(ns||(ns={}));var Tt;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Tt||(Tt={}));class Ar{constructor(e,r={config:{}},s){var n,i;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.state=Fe.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 Xs(this,ht.join,this.params,this.timeout),this.rejoinTimer=new Xi(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Fe.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=Fe.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=Fe.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Fe.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=Fe.errored,this.rejoinTimer.scheduleTimeout())}),this._on(ht.reply,{},(a,l)=>{this._trigger(this._replyEventName(l),a)}),this.presence=new ss(this),this.broadcastEndpointURL=ea(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==Fe.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(p=>p.filter))!==null&&n!==void 0?n:[],d=!!this.bindings[ns.PRESENCE]&&this.bindings[ns.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,h={},f={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(p=>e==null?void 0:e(Tt.CHANNEL_ERROR,p)),this._onClose(()=>e==null?void 0:e(Tt.CLOSED)),this.updateJoinPayload(Object.assign({config:f},h)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:p})=>{var y;if(this.socket._isManualToken()||this.socket.setAuth(),p===void 0){e==null||e(Tt.SUBSCRIBED);return}else{const b=this.bindings.postgres_changes,m=(y=b==null?void 0:b.length)!==null&&y!==void 0?y:0,v=[];for(let x=0;x<m;x++){const S=b[x],{filter:{event:_,schema:C,table:I,filter:O}}=S,E=p&&p[x];if(E&&E.event===_&&Ar.isFilterValueEqual(E.schema,C)&&Ar.isFilterValueEqual(E.table,I)&&Ar.isFilterValueEqual(E.filter,O))v.push(Object.assign(Object.assign({},S),{id:E.id}));else{this.unsubscribe(),this.state=Fe.errored,e==null||e(Tt.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=v,e&&e(Tt.SUBSCRIBED);return}}).receive("error",p=>{this.state=Fe.errored,e==null||e(Tt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(p).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(Tt.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===Fe.joined&&e===ns.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=Fe.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(ht.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(n=>{s=new Xs(this,ht.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=Fe.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 Xs(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>xo){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}=ht;if(s&&[l,c,u,d].indexOf(a)>=0&&s!==this._joinRef())return;let f=this._onMessage(a,r,s);if(r&&!f)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(p=>{var y,b,m;return((y=p.filter)===null||y===void 0?void 0:y.event)==="*"||((m=(b=p.filter)===null||b===void 0?void 0:b.event)===null||m===void 0?void 0:m.toLocaleLowerCase())===a}).map(p=>p.callback(f,s)):(i=this.bindings[a])===null||i===void 0||i.filter(p=>{var y,b,m,v,x,S;if(["broadcast","presence","postgres_changes"].includes(a))if("id"in p){const _=p.id,C=(y=p.filter)===null||y===void 0?void 0:y.event;return _&&((b=r.ids)===null||b===void 0?void 0:b.includes(_))&&(C==="*"||(C==null?void 0:C.toLocaleLowerCase())===((m=r.data)===null||m===void 0?void 0:m.type.toLocaleLowerCase()))}else{const _=(x=(v=p==null?void 0:p.filter)===null||v===void 0?void 0:v.event)===null||x===void 0?void 0:x.toLocaleLowerCase();return _==="*"||_===((S=r==null?void 0:r.event)===null||S===void 0?void 0:S.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===a}).map(p=>{if(typeof f=="object"&&"ids"in f){const y=f.data,{schema:b,table:m,commit_timestamp:v,type:x,errors:S}=y;f=Object.assign(Object.assign({},{schema:b,table:m,commit_timestamp:v,eventType:x,new:{},old:{},errors:S}),this._getPayloadRecords(y))}p.callback(f,s)})}_isClosed(){return this.state===Fe.closed}_isJoined(){return this.state===Fe.joined}_isJoining(){return this.state===Fe.joining}_isLeaving(){return this.state===Fe.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&&Ar.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(ht.close,{},e)}_onError(e){this._on(ht.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Fe.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=si(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=si(e.columns,e.old_record)),r}}const Zs=()=>{},Rs={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Co=[1e3,2e3,5e3,1e4],Ao=1e4,Oo=`
|
|
38
38
|
addEventListener("message", (e) => {
|
|
39
39
|
if (e.data.event === "start") {
|
|
40
40
|
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
41
41
|
}
|
|
42
|
-
});`;class
|
|
42
|
+
});`;class Po{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=dn,this.transport=null,this.heartbeatIntervalMs=Rs.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Zs,this.ref=0,this.reconnectTimer=null,this.vsn=ri,this.logger=Zs,this.conn=null,this.sendBuffer=[],this.serializer=new _o,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}/${hn.websocket}`,this.httpEndpoint=ea(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=bo.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const r=e.message;throw r.includes("Node.js")?new Error(`${r}
|
|
43
43
|
|
|
44
44
|
To use Realtime in Node.js, you need to provide a WebSocket implementation:
|
|
45
45
|
|
|
@@ -52,31 +52,31 @@ Option 2: Install and provide the "ws" package:
|
|
|
52
52
|
const client = new RealtimeClient(url, {
|
|
53
53
|
...options,
|
|
54
54
|
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 r==="ok"&&this._remove(e),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 Ft.connecting:return Zt.Connecting;case Ft.open:return Zt.Open;case Ft.closing:return Zt.Closing;default:return Zt.Closed}}isConnected(){return this.connectionState()===Zt.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 Rr(`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(yo,"heartbeat timeout"),setTimeout(()=>{var r;this.isConnected()||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout()},js.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===Ft.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===Ft.open||this.conn.readyState===Ft.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.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(dt.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([Co],{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:bo};r&&n.updateJoinPayload(i),n.joinedOnce&&n._isJoined()&&n._push(dt.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 Qi(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},js.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var r,s,n,i,a,l,c,u,d,h,f,p;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:ln,this.heartbeatIntervalMs=(n=e==null?void 0:e.heartbeatIntervalMs)!==null&&n!==void 0?n:js.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:Qs,this.vsn=(c=e==null?void 0:e.vsn)!==null&&c!==void 0?c:ei,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:v=>To[v-1]||Ro,this.vsn){case mo:this.encode=(d=e==null?void 0:e.encode)!==null&&d!==void 0?d:(v,m)=>m(JSON.stringify(v)),this.decode=(h=e==null?void 0:e.decode)!==null&&h!==void 0?h:(v,m)=>m(JSON.parse(v));break;case Ji:this.encode=(f=e==null?void 0:e.encode)!==null&&f!==void 0?f:this.serializer.encode.bind(this.serializer),this.decode=(p=e==null?void 0:e.decode)!==null&&p!==void 0?p: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 is=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 Oo(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 Po(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 Io(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:a}){const l=Oo(t.baseUrl,s,n),c=await Po(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"),f=h&&d?JSON.parse(d):d;if(!u.ok){const p=h?f:void 0,v=p==null?void 0:p.error;throw new is((v==null?void 0:v.message)??`Request failed with status ${u.status}`,{status:u.status,icebergType:v==null?void 0:v.type,icebergCode:v==null?void 0:v.code,details:p})}return{status:u.status,headers:u.headers,data:f}}}}function Ts(t){return t.join("")}var No=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:Ts(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/${Ts(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ts(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Ts(t.namespace)}`}),!0}catch(e){if(e instanceof is&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof is&&r.status===409)return;throw r}}};function yr(t){return t.join("")}var Bo=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/${yr(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/${yr(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/${yr(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/${yr(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/${yr(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/${yr(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof is&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof is&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},Fo=class{constructor(t){var s;let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Io({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=(s=t.accessDelegation)==null?void 0:s.join(","),this.namespaceOps=new No(this.client,e),this.tableOps=new Bo(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)}},Us=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 Ms(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var Rs=class extends Us{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}}},Zi=class extends Us{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};const Lo=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),$o=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)},dn=t=>{if(Array.isArray(t))return t.map(r=>dn(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]=dn(s)}),e},Do=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function as(t){"@babel/helpers - typeof";return as=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},as(t)}function Uo(t,e){if(as(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(as(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Mo(t){var e=Uo(t,"string");return as(e)=="symbol"?e:e+""}function Wo(t,e,r){return(e=Mo(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function ni(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?ni(Object(r),!0).forEach(function(s){Wo(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):ni(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const ii=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)},qo=async(t,e,r,s)=>{if(t&&typeof t=="object"&&"status"in t&&"ok"in t&&typeof t.status=="number"&&!(r!=null&&r.noResolveJson)){const n=t,i=n.status||500;if(typeof n.json=="function")n.json().then(a=>{const l=(a==null?void 0:a.statusCode)||(a==null?void 0:a.code)||i+"";e(new Rs(ii(a),i,l,s))}).catch(()=>{if(s==="vectors"){const a=i+"";e(new Rs(n.statusText||`HTTP ${i} error`,i,a,s))}else{const a=i+"";e(new Rs(n.statusText||`HTTP ${i} error`,i,a,s))}});else{const a=i+"";e(new Rs(n.statusText||`HTTP ${i} error`,i,a,s))}}else e(new Zi(ii(t),t,s))},zo=(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):($o(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 Jr(t,e,r,s,n,i,a){return new Promise((l,c)=>{t(r,zo(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=>qo(u,c,s,a))})}function ea(t="storage"){return{get:async(e,r,s,n)=>Jr(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,i)=>Jr(e,"POST",r,n,i,s,t),put:async(e,r,s,n,i)=>Jr(e,"PUT",r,n,i,s,t),head:async(e,r,s,n)=>Jr(e,"HEAD",r,ne(ne({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,i)=>Jr(e,"DELETE",r,n,i,s,t)}}const Ho=ea("storage"),{get:os,post:ot,put:hn,head:Ko,remove:Bn}=Ho,Ze=ea("vectors");var Wr=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=Lo(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(Ms(r))return{data:null,error:r};throw r}}},Vo=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(Ms(e))return{data:null,error:e};throw e}}};let ta;ta=Symbol.toStringTag;var Go=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[ta]="BlobDownloadBuilder",this.promise=null}asStream(){return new Vo(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(Ms(e))return{data:null,error:e};throw e}}};const Jo={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ai={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Qo=class extends Wr{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({},ai),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"?hn:ot)(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:ai.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 hn(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 ot(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 Us("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 ot(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 ot(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),i=await ot(s.fetch,`${s.url}/object/sign/${n}`,ne({expiresIn:e},r!=null&&r.transform?{transform:r.transform}:{}),{headers:s.headers});const a=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{signedUrl:encodeURI(`${s.url}${i.signedURL}${a}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{const n=await ot(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=()=>os(this.fetch,`${this.url}/${s}/${a}${i}`,{headers:this.headers,noResolveJson:!0},r);return new Go(l,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>dn(await os(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await Ko(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(s){if(e.shouldThrowOnError)throw s;if(Ms(s)&&s instanceof Zi){const n=s.originalError;if([400,404].includes(n==null?void 0:n.status))return{data:!1,error:s}}throw s}}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 Bn(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({},Jo),e),{},{prefix:t||""});return await ot(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 ot(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 Yo="2.95.3",vs={"X-Client-Info":`storage-js/${Yo}`};var Xo=class extends Wr{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({},vs),e);super(i,a,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await os(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await os(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await ot(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 hn(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 ot(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Bn(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():""}},Zo=class extends Wr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ne(ne({},vs),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await ot(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 os(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Bn(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!Do(t))throw new Us("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 Fo({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}}}}})}},el=class extends Wr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ne(ne({},vs),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await Ze.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await Ze.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await Ze.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await Ze.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},tl=class extends Wr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ne(ne({},vs),{},{"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 Ze.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await Ze.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 Ze.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await Ze.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 Ze.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},rl=class extends Wr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=ne(ne({},vs),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ze.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Ze.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await Ze.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ze.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},sl=class extends rl{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new nl(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)}},nl=class extends el{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 il(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},il=class extends tl{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}))}},al=class extends Xo{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new Qo(this.url,this.headers,t,this.fetch)}get vectors(){return new sl(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Zo(this.url+"/iceberg",this.headers,this.fetch)}};const ra="2.95.3",jr=30*1e3,fn=3,Ys=fn*jr,ol="http://localhost:9999",ll="supabase.auth.token",cl={"X-Client-Info":`gotrue-js/${ra}`},pn="X-Supabase-Api-Version",sa={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},ul=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,dl=10*60*1e3;class ls extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}}function G(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class hl extends ls{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}}function fl(t){return G(t)&&t.name==="AuthApiError"}class er extends ls{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class Et extends ls{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}}class Xe extends Et{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Xs(t){return G(t)&&t.name==="AuthSessionMissingError"}class vr extends Et{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Cs extends Et{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class As extends Et{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 pl(t){return G(t)&&t.name==="AuthImplicitGrantRedirectError"}class oi extends Et{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 gl extends Et{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class gn extends Et{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function Zs(t){return G(t)&&t.name==="AuthRetryableFetchError"}class li extends Et{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}}class bn extends Et{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Is="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),ci=`
|
|
56
|
-
\r=`.split(""),bl=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<ci.length;e+=1)t[ci[e].charCodeAt(0)]=-2;for(let e=0;e<Is.length;e+=1)t[Is[e].charCodeAt(0)]=e;return t})();function ui(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(Is[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(Is[s]),e.queuedBits-=6}}function na(t,e,r){const s=bl[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 di(t){const e=[],r=a=>{e.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=a=>{vl(a,s,r)};for(let a=0;a<t.length;a+=1)na(t.charCodeAt(a),n,i);return e.join("")}function ml(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 yl(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}ml(s,e)}}function vl(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 Cr(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)na(t.charCodeAt(n),r,s);return new Uint8Array(e)}function wl(t){const e=[];return yl(t,r=>e.push(r)),new Uint8Array(e)}function tr(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>ui(n,r,s)),ui(null,r,s),e.join("")}function xl(t){return Math.round(Date.now()/1e3)+t}function _l(){return Symbol("auth-callback")}const De=()=>typeof window<"u"&&typeof document<"u",Qt={tested:!1,writable:!1},ia=()=>{if(!De())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Qt.tested)return Qt.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Qt.tested=!0,Qt.writable=!0}catch{Qt.tested=!0,Qt.writable=!1}return Qt.writable};function kl(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 aa=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Sl=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Tr=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},Yt=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},$e=async(t,e)=>{await t.removeItem(e)};class Ws{constructor(){this.promise=new Ws.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}Ws.promiseConstructor=Promise;function Os(t){const e=t.split(".");if(e.length!==3)throw new bn("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!ul.test(e[s]))throw new bn("JWT not in base64url format");return{header:JSON.parse(di(e[0])),payload:JSON.parse(di(e[1])),signature:Cr(e[2]),raw:{header:e[0],payload:e[1]}}}async function El(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function jl(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 Tl(t){return("0"+t.toString(16)).substr(-2)}function Rl(){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,Tl).join("")}async function Cl(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 Al(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 Cl(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function wr(t,e,r=!1){const s=Rl();let n=s;r&&(n+="/PASSWORD_RECOVERY"),await Tr(t,`${e}-code-verifier`,n);const i=await Al(s);return[i,s===i?"plain":"s256"]}const Ol=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Pl(t){const e=t.headers.get(pn);if(!e||!e.match(Ol))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Il(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 Nl(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 Bl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function xr(t){if(!Bl.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function en(){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 Fl(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 hi(t){return JSON.parse(JSON.stringify(t))}const Xt=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Ll=[502,503,504];async function fi(t){var e;if(!Sl(t))throw new gn(Xt(t),0);if(Ll.includes(t.status))throw new gn(Xt(t),t.status);let r;try{r=await t.json()}catch(i){throw new er(Xt(i),i)}let s;const n=Pl(t);if(n&&n.getTime()>=sa["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 li(Xt(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new Xe}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 li(Xt(r),t.status,r.weak_password.reasons);throw new hl(Xt(r),t.status||500,s)}const $l=(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 se(t,e,r,s){var n;const i=Object.assign({},s==null?void 0:s.headers);i[pn]||(i[pn]=sa["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 Dl(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 Dl(t,e,r,s,n,i){const a=$l(e,s,n,i);let l;try{l=await t(r,Object.assign({},a))}catch(c){throw console.error(c),new gn(Xt(c),0)}if(l.ok||await fi(l),s!=null&&s.noResolveJson)return l;try{return await l.json()}catch(c){await fi(c)}}function at(t){var e;let r=null;Wl(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=xl(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=at(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 Lt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Ul(t){return{data:t,error:null}}function Ml(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=t,a=Ds(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 gi(t){return t}function Wl(t){return t.access_token&&t.refresh_token&&t.expires_in}const tn=["global","local","others"];class ql{constructor({url:e="",headers:r={},fetch:s}){this.url=e,this.headers=r,this.fetch=aa(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)}}async signOut(e,r=tn[0]){if(tn.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${tn.join(", ")}`);try{return await se(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(G(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await se(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Lt})}catch(s){if(G(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:r}=e,s=Ds(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 se(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Ml,redirectTo:r==null?void 0:r.redirectTo})}catch(r){if(G(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await se(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Lt})}catch(r){if(G(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 se(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:gi});if(d.error)throw d.error;const h=await d.json(),f=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,p=(c=(l=d.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(v=>{const m=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(v.split(";")[1].split("=")[1]);u[`${b}Page`]=m}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(G(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){xr(e);try{return await se(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Lt})}catch(r){if(G(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){xr(e);try{return await se(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Lt})}catch(s){if(G(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){xr(e);try{return await se(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Lt})}catch(s){if(G(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){xr(e.userId);try{const{data:r,error:s}=await se(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(G(r))return{data:null,error:r};throw r}}async _deleteFactor(e){xr(e.userId),xr(e.id);try{return{data:await se(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(G(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 se(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:gi});if(d.error)throw d.error;const h=await d.json(),f=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,p=(c=(l=d.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(v=>{const m=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(v.split(";")[1].split("=")[1]);u[`${b}Page`]=m}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(G(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await se(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(G(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await se(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(G(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await se(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(G(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await se(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(G(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await se(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(G(r))return{data:null,error:r};throw r}}}function bi(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}const _r={debug:!!(globalThis&&ia()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class oa extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class zl extends oa{}async function Hl(t,e,r){_r.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),_r.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async n=>{if(n){_r.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,n.name);try{return await r()}finally{_r.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,n.name)}}else{if(e===0)throw _r.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new zl(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(_r.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}}))}function Kl(){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 la(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Vl(t){return parseInt(t,16)}function Gl(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function Jl(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:f}=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(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);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 p=
|
|
58
|
-
`:"",
|
|
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 $t.connecting:return nr.Connecting;case $t.open:return nr.Open;case $t.closing:return nr.Closing;default:return nr.Closed}}isConnected(){return this.connectionState()===nr.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 Ar(`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(wo,"heartbeat timeout"),setTimeout(()=>{var r;this.isConnected()||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout()},Rs.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===$t.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===$t.open||this.conn.readyState===$t.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(ht.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([Oo],{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:yo};r&&n.updateJoinPayload(i),n.joinedOnce&&n._isJoined()&&n._push(ht.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 Xi(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Rs.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var r,s,n,i,a,l,c,u,d,h,f,p;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:dn,this.heartbeatIntervalMs=(n=e==null?void 0:e.heartbeatIntervalMs)!==null&&n!==void 0?n:Rs.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:Zs,this.vsn=(c=e==null?void 0:e.vsn)!==null&&c!==void 0?c:ri,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:y=>Co[y-1]||Ao,this.vsn){case vo:this.encode=(d=e==null?void 0:e.encode)!==null&&d!==void 0?d:(y,b)=>b(JSON.stringify(y)),this.decode=(h=e==null?void 0:e.decode)!==null&&h!==void 0?h:(y,b)=>b(JSON.parse(y));break;case Yi:this.encode=(f=e==null?void 0:e.encode)!==null&&f!==void 0?f:this.serializer.encode.bind(this.serializer),this.decode=(p=e==null?void 0:e.decode)!==null&&p!==void 0?p: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 os=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 Io(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 No(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 Bo(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:a}){const l=Io(t.baseUrl,s,n),c=await No(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"),f=h&&d?JSON.parse(d):d;if(!u.ok){const p=h?f:void 0,y=p==null?void 0:p.error;throw new os((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:p})}return{status:u.status,headers:u.headers,data:f}}}}function Cs(t){return t.join("")}var Fo=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:Cs(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/${Cs(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Cs(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Cs(t.namespace)}`}),!0}catch(e){if(e instanceof os&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof os&&r.status===409)return;throw r}}};function xr(t){return t.join("")}var Lo=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/${xr(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/${xr(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/${xr(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/${xr(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/${xr(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/${xr(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof os&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof os&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},$o=class{constructor(t){var s;let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Bo({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=(s=t.accessDelegation)==null?void 0:s.join(","),this.namespaceOps=new Fo(this.client,e),this.tableOps=new Lo(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)}},Ws=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 qs(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var As=class extends Ws{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}}},ta=class extends Ws{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};const Do=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Uo=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)},pn=t=>{if(Array.isArray(t))return t.map(r=>pn(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]=pn(s)}),e},Mo=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function ls(t){"@babel/helpers - typeof";return ls=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},ls(t)}function Wo(t,e){if(ls(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(ls(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function qo(t){var e=Wo(t,"string");return ls(e)=="symbol"?e:e+""}function zo(t,e,r){return(e=qo(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 re(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){zo(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 oi=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)},Ho=async(t,e,r,s)=>{if(t&&typeof t=="object"&&"status"in t&&"ok"in t&&typeof t.status=="number"&&!(r!=null&&r.noResolveJson)){const n=t,i=n.status||500;if(typeof n.json=="function")n.json().then(a=>{const l=(a==null?void 0:a.statusCode)||(a==null?void 0:a.code)||i+"";e(new As(oi(a),i,l,s))}).catch(()=>{if(s==="vectors"){const a=i+"";e(new As(n.statusText||`HTTP ${i} error`,i,a,s))}else{const a=i+"";e(new As(n.statusText||`HTTP ${i} error`,i,a,s))}});else{const a=i+"";e(new As(n.statusText||`HTTP ${i} error`,i,a,s))}}else e(new ta(oi(t),t,s))},Ko=(t,e,r,s)=>{const n={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"||t==="HEAD"||!s?re(re({},n),r):(Uo(s)?(n.headers=re({"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),re(re({},n),r))};async function Yr(t,e,r,s,n,i,a){return new Promise((l,c)=>{t(r,Ko(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=>Ho(u,c,s,a))})}function ra(t="storage"){return{get:async(e,r,s,n)=>Yr(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,i)=>Yr(e,"POST",r,n,i,s,t),put:async(e,r,s,n,i)=>Yr(e,"PUT",r,n,i,s,t),head:async(e,r,s,n)=>Yr(e,"HEAD",r,re(re({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,i)=>Yr(e,"DELETE",r,n,i,s,t)}}const Vo=ra("storage"),{get:cs,post:lt,put:gn,head:Go,remove:$n}=Vo,rt=ra("vectors");var zr=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=Do(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=re(re({},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(qs(r))return{data:null,error:r};throw r}}},Jo=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(qs(e))return{data:null,error:e};throw e}}};let sa;sa=Symbol.toStringTag;var Qo=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[sa]="BlobDownloadBuilder",this.promise=null}asStream(){return new Jo(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(qs(e))return{data:null,error:e};throw e}}};const Yo={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},li={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Xo=class extends zr{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=re(re({},li),s);let l=re(re({},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=re(re({},l),s.headers));const u=n._removeEmptyFolders(e),d=n._getFinalPath(u),h=await(t=="PUT"?gn:lt)(n.fetch,`${n.url}/object/${d}`,i,re({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=re({upsert:li.upsert},s),d=re(re({},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 gn(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=re({},r.headers);e!=null&&e.upsert&&(n["x-upsert"]="true");const i=await lt(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 Ws("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 lt(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 lt(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),i=await lt(s.fetch,`${s.url}/object/sign/${n}`,re({expiresIn:e},r!=null&&r.transform?{transform:r.transform}:{}),{headers:s.headers});const a=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{signedUrl:encodeURI(`${s.url}${i.signedURL}${a}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{const n=await lt(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=>re(re({},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=()=>cs(this.fetch,`${this.url}/${s}/${a}${i}`,{headers:this.headers,noResolveJson:!0},r);return new Qo(l,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>pn(await cs(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await Go(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(s){if(e.shouldThrowOnError)throw s;if(qs(s)&&s instanceof ta){const n=s.originalError;if([400,404].includes(n==null?void 0:n.status))return{data:!1,error:s}}throw s}}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 $n(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=re(re(re({},Yo),e),{},{prefix:t||""});return await lt(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=re({},t);return await lt(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 Zo="2.98.0",xs={"X-Client-Info":`storage-js/${Zo}`};var el=class extends zr{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=re(re({},xs),e);super(i,a,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await cs(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await cs(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await lt(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 gn(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 lt(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await $n(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():""}},tl=class extends zr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=re(re({},xs),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await lt(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 cs(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await $n(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!Mo(t))throw new Ws("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 $o({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}}}}})}},rl=class extends zr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=re(re({},xs),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await rt.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await rt.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await rt.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await rt.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},sl=class extends zr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=re(re({},xs),{},{"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 rt.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await rt.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 rt.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await rt.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 rt.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},nl=class extends zr{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=re(re({},xs),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await rt.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await rt.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await rt.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await rt.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},il=class extends nl{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new al(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)}},al=class extends rl{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,re(re({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,re(re({},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 ol(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},ol=class extends sl{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,re(re({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,re(re({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,re(re({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,re(re({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,re(re({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},ll=class extends el{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new Xo(this.url,this.headers,t,this.fetch)}get vectors(){return new il(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new tl(this.url+"/iceberg",this.headers,this.fetch)}};const na="2.98.0",Rr=30*1e3,bn=3,en=bn*Rr,cl="http://localhost:9999",ul="supabase.auth.token",dl={"X-Client-Info":`gotrue-js/${na}`},mn="X-Supabase-Api-Version",ia={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},hl=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,fl=10*60*1e3;class us extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}}function Y(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class pl extends us{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}}function gl(t){return Y(t)&&t.name==="AuthApiError"}class ir extends us{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class Ot extends us{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}}class tt extends Ot{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function tn(t){return Y(t)&&t.name==="AuthSessionMissingError"}class _r extends Ot{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Os extends Ot{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Ps extends Ot{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 bl(t){return Y(t)&&t.name==="AuthImplicitGrantRedirectError"}class ci extends Ot{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 ml extends Ot{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 yn extends Ot{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function rn(t){return Y(t)&&t.name==="AuthRetryableFetchError"}class ui extends Ot{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}}class vn extends Ot{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Bs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),di=`
|
|
56
|
+
\r=`.split(""),yl=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<di.length;e+=1)t[di[e].charCodeAt(0)]=-2;for(let e=0;e<Bs.length;e+=1)t[Bs[e].charCodeAt(0)]=e;return t})();function hi(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(Bs[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(Bs[s]),e.queuedBits-=6}}function aa(t,e,r){const s=yl[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 fi(t){const e=[],r=a=>{e.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=a=>{xl(a,s,r)};for(let a=0;a<t.length;a+=1)aa(t.charCodeAt(a),n,i);return e.join("")}function vl(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 wl(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}vl(s,e)}}function xl(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 Or(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)aa(t.charCodeAt(n),r,s);return new Uint8Array(e)}function _l(t){const e=[];return wl(t,r=>e.push(r)),new Uint8Array(e)}function ar(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>hi(n,r,s)),hi(null,r,s),e.join("")}function kl(t){return Math.round(Date.now()/1e3)+t}function Sl(){return Symbol("auth-callback")}const De=()=>typeof window<"u"&&typeof document<"u",tr={tested:!1,writable:!1},oa=()=>{if(!De())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(tr.tested)return tr.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),tr.tested=!0,tr.writable=!0}catch{tr.tested=!0,tr.writable=!1}return tr.writable};function El(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 la=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),jl=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Cr=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},rr=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},$e=async(t,e)=>{await t.removeItem(e)};class zs{constructor(){this.promise=new zs.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}zs.promiseConstructor=Promise;function Is(t){const e=t.split(".");if(e.length!==3)throw new vn("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!hl.test(e[s]))throw new vn("JWT not in base64url format");return{header:JSON.parse(fi(e[0])),payload:JSON.parse(fi(e[1])),signature:Or(e[2]),raw:{header:e[0],payload:e[1]}}}async function Tl(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Rl(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 Cl(t){return("0"+t.toString(16)).substr(-2)}function Al(){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,Cl).join("")}async function Ol(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 Pl(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 Ol(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function kr(t,e,r=!1){const s=Al();let n=s;r&&(n+="/PASSWORD_RECOVERY"),await Cr(t,`${e}-code-verifier`,n);const i=await Pl(s);return[i,s===i?"plain":"s256"]}const Il=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Nl(t){const e=t.headers.get(mn);if(!e||!e.match(Il))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Bl(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 Fl(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 Ll=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Sr(t){if(!Ll.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function sn(){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 $l(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 pi(t){return JSON.parse(JSON.stringify(t))}const sr=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Dl=[502,503,504];async function gi(t){var e;if(!jl(t))throw new yn(sr(t),0);if(Dl.includes(t.status))throw new yn(sr(t),t.status);let r;try{r=await t.json()}catch(i){throw new ir(sr(i),i)}let s;const n=Nl(t);if(n&&n.getTime()>=ia["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 ui(sr(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new tt}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 ui(sr(r),t.status,r.weak_password.reasons);throw new pl(sr(r),t.status||500,s)}const Ul=(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 se(t,e,r,s){var n;const i=Object.assign({},s==null?void 0:s.headers);i[mn]||(i[mn]=ia["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 Ml(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 Ml(t,e,r,s,n,i){const a=Ul(e,s,n,i);let l;try{l=await t(r,Object.assign({},a))}catch(c){throw console.error(c),new yn(sr(c),0)}if(l.ok||await gi(l),s!=null&&s.noResolveJson)return l;try{return await l.json()}catch(c){await gi(c)}}function ot(t){var e;let r=null;zl(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=kl(t.expires_in)));const s=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:s},error:null}}function bi(t){const e=ot(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,s)=>r&&typeof s=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Dt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Wl(t){return{data:t,error:null}}function ql(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=t,a=Ms(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 mi(t){return t}function zl(t){return t.access_token&&t.refresh_token&&t.expires_in}const nn=["global","local","others"];class Hl{constructor({url:e="",headers:r={},fetch:s}){this.url=e,this.headers=r,this.fetch=la(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)}}async signOut(e,r=nn[0]){if(nn.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${nn.join(", ")}`);try{return await se(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(Y(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await se(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Dt})}catch(s){if(Y(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:r}=e,s=Ms(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 se(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:ql,redirectTo:r==null?void 0:r.redirectTo})}catch(r){if(Y(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await se(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Dt})}catch(r){if(Y(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 se(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:mi});if(d.error)throw d.error;const h=await d.json(),f=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,p=(c=(l=d.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(y=>{const b=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(y.split(";")[1].split("=")[1]);u[`${m}Page`]=b}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(Y(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Sr(e);try{return await se(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Dt})}catch(r){if(Y(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Sr(e);try{return await se(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Dt})}catch(s){if(Y(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){Sr(e);try{return await se(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Dt})}catch(s){if(Y(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){Sr(e.userId);try{const{data:r,error:s}=await se(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(Y(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Sr(e.userId),Sr(e.id);try{return{data:await se(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(Y(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 se(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:mi});if(d.error)throw d.error;const h=await d.json(),f=(a=d.headers.get("x-total-count"))!==null&&a!==void 0?a:0,p=(c=(l=d.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(y=>{const b=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(y.split(";")[1].split("=")[1]);u[`${m}Page`]=b}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(Y(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await se(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Y(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await se(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Y(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await se(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(Y(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await se(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(Y(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await se(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Y(r))return{data:null,error:r};throw r}}}function yi(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}const Et={debug:!!(globalThis&&oa()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class ca extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Kl extends ca{}async function Vl(t,e,r){Et.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const s=new globalThis.AbortController;e>0&&setTimeout(()=>{s.abort(),Et.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 n=>{if(n){Et.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,n.name);try{return await r()}finally{Et.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,n.name)}}else{if(e===0)throw Et.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Kl(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(Et.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}})}catch(n){if((n==null?void 0:n.name)==="AbortError"&&e>0)return Et.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:!0},async i=>{if(i){Et.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,i.name);try{return await r()}finally{Et.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,i.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw n}}function Gl(){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 ua(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Jl(t){return parseInt(t,16)}function Ql(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function Yl(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:f}=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(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);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 p=ua(t.address),y=d?`${d}://${s}`:s,b=t.statement?`${t.statement}
|
|
58
|
+
`:"",m=`${y} wants you to sign in with your Ethereum account:
|
|
59
59
|
${p}
|
|
60
60
|
|
|
61
|
-
${
|
|
61
|
+
${b}`;let v=`URI: ${h}
|
|
62
62
|
Version: ${f}
|
|
63
63
|
Chain ID: ${r}${a?`
|
|
64
64
|
Nonce: ${a}`:""}
|
|
65
|
-
Issued At: ${i.toISOString()}`;if(n&&(
|
|
66
|
-
Expiration Time: ${n.toISOString()}`),l&&(
|
|
67
|
-
Not Before: ${l.toISOString()}`),c&&(
|
|
68
|
-
Request ID: ${c}`),u){let
|
|
69
|
-
Resources:`;for(const
|
|
70
|
-
- ${
|
|
71
|
-
${y}`}class Ie 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 Ns extends Ie{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function Ql({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 Ie({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 Ie({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 Ie({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 Ie({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 Ie({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new Ie({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 Ie({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new Ie({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(ca(a)){if(i.rp.id!==a)return new Ie({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Ie({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 Ie({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 Ie({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 Ie({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Yl({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 Ie({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new Ie({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(ca(s)){if(r.rpId!==s)return new Ie({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Ie({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new Ie({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 Ie({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class Xl{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 Zl=new Xl;function ec(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=Ds(t,["challenge","user","excludeCredentials"]),i=Cr(e).buffer,a=Object.assign(Object.assign({},r),{id:Cr(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:Cr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return l}function tc(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=Ds(t,["challenge","allowCredentials"]),n=Cr(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:Cr(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return i}function rc(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:tr(new Uint8Array(t.response.attestationObject)),clientDataJSON:tr(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function sc(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:tr(new Uint8Array(n.authenticatorData)),clientDataJSON:tr(new Uint8Array(n.clientDataJSON)),signature:tr(new Uint8Array(n.signature)),userHandle:n.userHandle?tr(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function ca(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function mi(){var t,e;return!!(De()&&"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 nc(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ns("Browser returned unexpected credential type",e)}:{data:null,error:new Ns("Empty credential response",e)}}catch(e){return{data:null,error:Ql({error:e,options:t})}}}async function ic(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ns("Browser returned unexpected credential type",e)}:{data:null,error:new Ns("Empty credential response",e)}}catch(e){return{data:null,error:Yl({error:e,options:t})}}}const ac={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},oc={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Bs(...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]=Bs(l,a):s[i]=Bs(a)}else s[i]=a}return s}function lc(t,e){return Bs(ac,t,e||{})}function cc(t,e){return Bs(oc,t,e||{})}class uc{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??Zl.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 p=(await this.client.getUser()).data.user,v=((a=p==null?void 0:p.user_metadata)===null||a===void 0?void 0:a.name)||(p==null?void 0:p.email)||(p==null?void 0:p.id)||"User";d.name=`${d.id}:${v}`}}d.displayName||(d.displayName=d.name)}switch(l.webauthn.type){case"create":{const d=lc(l.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:h,error:f}=await nc({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:f}}case"request":{const d=cc(l.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:h,error:f}=await ic(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:f}}}}catch(l){return G(l)?{data:null,error:l}:{data:null,error:new er("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 ls("rpId is required for WebAuthn authentication")};try{if(!mi())return{data:null,error:new er("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 G(a)?{data:null,error:a}:{data:null,error:new er("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 ls("rpId is required for WebAuthn registration")};try{if(!mi())return{data:null,error:new er("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(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.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 G(a)?{data:null,error:a}:{data:null,error:new er("Unexpected error in register",a)}}}}Kl();const dc={url:ol,storageKey:ll,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:cl,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function yi(t,e,r){return await r()}const kr={};class cs{get jwks(){var e,r;return(r=(e=kr[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){kr[this.storageKey]=Object.assign(Object.assign({},kr[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=kr[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){kr[this.storageKey]=Object.assign(Object.assign({},kr[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({},dc),e);if(this.storageKey=i.storageKey,this.instanceID=(r=cs.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,cs.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&De()){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 ql({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=aa(i.fetch),this.lock=i.lock||yi,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&&De()&&(!((s=globalThis==null?void 0:globalThis.navigator)===null||s===void 0)&&s.locks)?this.lock=Hl:this.lock=yi,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 uc(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:ia()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=bi(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=bi(this.memoryStorage)),De()&&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)}})}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} (${ra}) ${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(De()&&(r=kl(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),De()&&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),pl(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 G(r)?this._returnResult({error:r}):this._returnResult({error:new er("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const i=await se(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:at}),{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(G(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:f}=e;let p=null,v=null;this.flowType==="pkce"&&([p,v]=await wr(this.storage,this.storageKey)),i=await se(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f==null?void 0:f.emailRedirectTo,body:{email:d,password:h,data:(r=f==null?void 0:f.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:p,code_challenge_method:v},xform:at})}else if("phone"in e){const{phone:d,password:h,options:f}=e;i=await se(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:h,data:(s=f==null?void 0:f.data)!==null&&s!==void 0?s:{},channel:(n=f==null?void 0:f.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken}},xform:at})}else throw new Cs("You must provide either an email or phone number and a password");const{data:a,error:l}=i;if(l||!a)return await $e(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 $e(this.storage,`${this.storageKey}-code-verifier`),G(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 se(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:pi})}else if("phone"in e){const{phone:i,password:a,options:l}=e;r=await se(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:pi})}else throw new Cs("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 vr;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(G(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,f;let p,v;if("message"in e)p=e.message,v=e.signature;else{const{chain:m,wallet:b,statement:y,options:_}=e;let k;if(De())if(typeof b=="object")k=b;else{const U=window;if("ethereum"in U&&typeof U.ethereum=="object"&&"request"in U.ethereum&&typeof U.ethereum.request=="function")k=U.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 b!="object"||!(_!=null&&_.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");k=b}const w=new URL((r=_==null?void 0:_.url)!==null&&r!==void 0?r:window.location.href),E=await k.request({method:"eth_requestAccounts"}).then(U=>U).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!E||E.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const A=la(E[0]);let F=(s=_==null?void 0:_.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!F){const U=await k.request({method:"eth_chainId"});F=Vl(U)}const N={domain:w.host,address:A,statement:y,uri:w.href,version:"1",chainId:F,nonce:(n=_==null?void 0:_.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(a=(i=_==null?void 0:_.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(l=_==null?void 0:_.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=_==null?void 0:_.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=_==null?void 0:_.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(d=_==null?void 0:_.signInWithEthereum)===null||d===void 0?void 0:d.resources};p=Jl(N),v=await k.request({method:"personal_sign",params:[Gl(p),A]})}try{const{data:m,error:b}=await se(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:v},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:at});if(b)throw b;if(!m||!m.session||!m.user){const y=new vr;return this._returnResult({data:{user:null,session:null},error:y})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:b})}catch(m){if(G(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async signInWithSolana(e){var r,s,n,i,a,l,c,u,d,h,f,p;let v,m;if("message"in e)v=e.message,m=e.signature;else{const{chain:b,wallet:y,statement:_,options:k}=e;let w;if(De())if(typeof y=="object")w=y;else{const A=window;if("solana"in A&&typeof A.solana=="object"&&("signIn"in A.solana&&typeof A.solana.signIn=="function"||"signMessage"in A.solana&&typeof A.solana.signMessage=="function"))w=A.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"||!(k!=null&&k.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=y}const E=new URL((r=k==null?void 0:k.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in w&&w.signIn){const A=await w.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},k==null?void 0:k.signInWithSolana),{version:"1",domain:E.host,uri:E.href}),_?{statement:_}:null));let F;if(Array.isArray(A)&&A[0]&&typeof A[0]=="object")F=A[0];else if(A&&typeof A=="object"&&"signedMessage"in A&&"signature"in A)F=A;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)v=typeof F.signedMessage=="string"?F.signedMessage:new TextDecoder().decode(F.signedMessage),m=F.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in w)||typeof w.signMessage!="function"||!("publicKey"in w)||typeof w!="object"||!w.publicKey||!("toBase58"in w.publicKey)||typeof w.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");v=[`${E.host} wants you to sign in with your Solana account:`,w.publicKey.toBase58(),..._?["",_,""]:[""],"Version: 1",`URI: ${E.href}`,`Issued At: ${(n=(s=k==null?void 0:k.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=k==null?void 0:k.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${k.signInWithSolana.notBefore}`]:[],...!((a=k==null?void 0:k.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${k.signInWithSolana.expirationTime}`]:[],...!((l=k==null?void 0:k.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${k.signInWithSolana.chainId}`]:[],...!((c=k==null?void 0:k.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${k.signInWithSolana.nonce}`]:[],...!((u=k==null?void 0:k.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${k.signInWithSolana.requestId}`]:[],...!((h=(d=k==null?void 0:k.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||h===void 0)&&h.length?["Resources",...k.signInWithSolana.resources.map(F=>`- ${F}`)]:[]].join(`
|
|
72
|
-
`);const A=await w.signMessage(new TextEncoder().encode(v),"utf8");if(!A||!(A instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=A}}try{const{data:b,error:y}=await se(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:v,signature:tr(m)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:at});if(y)throw y;if(!b||!b.session||!b.user){const _=new vr;return this._returnResult({data:{user:null,session:null},error:_})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:y})}catch(b){if(G(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async _exchangeCodeForSession(e){const r=await Yt(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new gl;const{data:i,error:a}=await se(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:at});if(await $e(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!i||!i.session||!i.user){const l=new vr;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 $e(this.storage,`${this.storageKey}-code-verifier`),G(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 se(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:at}),{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 vr;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(G(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 wr(this.storage,this.storageKey));const{error:h}=await se(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 se(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 Cs("You must provide either an email or phone number.")}catch(l){if(await $e(this.storage,`${this.storageKey}-code-verifier`),G(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 se(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:at});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(G(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 wr(this.storage,this.storageKey));const u=await se(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:Ul});return!((i=u.data)===null||i===void 0)&&i.url&&De()&&!(!((a=e.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await $e(this.storage,`${this.storageKey}-code-verifier`),G(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 Xe;const{error:n}=await se(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(G(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 se(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 se(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 Cs("You must provide either an email or phone number and a type")}catch(r){if(G(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 Yt(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()<Ys:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await Yt(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=en()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=Fl(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 se(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Lt}):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 Xe}:await se(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:Lt})})}catch(r){if(G(r))return Xs(r)&&(await this._removeSession(),await $e(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async s=>{const{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new Xe;const a=n.session;let l=null,c=null;this.flowType==="pkce"&&e.email!=null&&([l,c]=await wr(this.storage,this.storageKey));const{data:u,error:d}=await se(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:Lt});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 $e(this.storage,`${this.storageKey}-code-verifier`),G(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 Xe;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:a}=Os(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(G(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 Xe;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(G(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!De())throw new As("No browser detected.");if(e.error||e.error_description||e.error_code)throw new As(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 oi("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new As("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 oi("No code detected.");const{data:_,error:k}=await this._exchangeCodeForSession(e.code);if(k)throw k;const w=new URL(window.location.href);return w.searchParams.delete("code"),window.history.replaceState(window.history.state,"",w.toString()),{data:{session:_.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 As("No session defined in URL");const d=Math.round(Date.now()/1e3),h=parseInt(l);let f=d+h;c&&(f=parseInt(c));const p=f-d;p*1e3<=jr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);const v=f-h;d-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,f,d):d-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",v,f,d);const{data:m,error:b}=await this._getUser(i);if(b)throw b;const y={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:h,expires_at:f,refresh_token:a,token_type:u,user:m.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(G(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 Yt(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&&!Xs(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&&!(fl(l)&&(l.status===404||l.status===401||l.status===403)||Xs(l)))return this._returnResult({error:l})}return e!=="others"&&(await this._removeSession(),await $e(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 wr(this.storage,this.storageKey,!0));try{return await se(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 $e(this.storage,`${this.storageKey}-code-verifier`),G(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(G(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:f}=i;if(f)throw f;const p=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 se(this.fetch,"GET",p,{headers:this.headers,jwt:(d=(u=h.session)===null||u===void 0?void 0:u.access_token)!==null&&d!==void 0?d:void 0})});if(n)throw n;return De()&&!(!((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(G(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 se(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:at}),{data:f,error:p}=h;return p?this._returnResult({data:{user:null,session:null},error:p}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new vr}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:p}))}catch(n){if(await $e(this.storage,`${this.storageKey}-code-verifier`),G(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 se(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(G(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 jl(async n=>(n>0&&await El(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await se(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:at})),(n,i)=>{const a=200*Math.pow(2,n);return i&&Zs(i)&&Date.now()+a-s<jr})}catch(s){if(this._debug(r,"error",s),G(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),De()&&!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 Yt(this.storage,this.storageKey);if(n&&this.userStorage){let a=await Yt(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:n.user},await Tr(this.userStorage,this.storageKey+"-user",a)),n.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:en()}else if(n&&!n.user&&!n.user){const a=await Yt(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(n.user=a.user,await $e(this.storage,this.storageKey+"-user"),await Tr(this.storage,this.storageKey,n)):n.user=en()}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()<Ys;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${Ys}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:a}=await this._callRefreshToken(n.refresh_token);a&&(console.error(a),Zs(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 Xe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Ws;const{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new Xe;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),G(i)){const a={data:null,error:i};return Zs(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 $e(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await Tr(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=hi(n);await Tr(this.storage,this.storageKey,i)}else{const n=hi(r);await Tr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await $e(this.storage,this.storageKey),await $e(this.storage,this.storageKey+"-code-verifier"),await $e(this.storage,this.storageKey+"-user"),this.userStorage&&await $e(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&De()&&(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(),jr);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)/jr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${jr}ms, refresh threshold is ${fn} ticks`),n<=fn&&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 oa)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!De()||!(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 wr(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 se(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(G(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 se(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(G(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"?rc(e.webauthn.credential_response):sc(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:c}=await se(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(G(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 se(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:ec(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:tc(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(G(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:p}=Os(e);let v=null;p.aal&&(v=p.aal);let m=v;const{data:{user:b},error:y}=await this.getUser(e);if(y)return this._returnResult({data:null,error:y});((s=(r=b==null?void 0:b.factors)===null||r===void 0?void 0:r.filter(w=>w.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(m="aal2");const k=p.amr||[];return{data:{currentLevel:v,nextLevel:m,currentAuthenticationMethods:k},error:null}}catch(p){if(G(p))return this._returnResult({data:null,error:p});throw p}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}=Os(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(p=>p.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(d="aal2");const f=c.amr||[];return{data:{currentLevel:u,nextLevel:d,currentAuthenticationMethods:f},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 se(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 Xe})})}catch(r){if(G(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 Xe});const a=await se(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&&De()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(G(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 Xe});const a=await se(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&&De()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(G(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 se(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 Xe})})}catch(e){if(G(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 se(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 Xe})})}catch(r){if(G(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+dl>n)return s;const{data:i,error:a}=await se(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:p,error:v}=await this.getSession();if(v||!p.session)return this._returnResult({data:null,error:v});s=p.session.access_token}const{header:n,payload:i,signature:a,raw:{header:l,payload:c}}=Os(s);r!=null&&r.allowExpired||Il(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:p}=await this.getUser(s);if(p)throw p;return{data:{claims:i,header:n,signature:a},error:null}}const d=Nl(n.alg),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,a,wl(`${l}.${c}`)))throw new bn("Invalid JWT signature");return{data:{claims:i,header:n,signature:a},error:null}}catch(s){if(G(s))return this._returnResult({data:null,error:s});throw s}}}cs.nextInstanceID={};const hc=cs,fc="2.95.3";let Xr="";typeof Deno<"u"?Xr="deno":typeof document<"u"?Xr="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Xr="react-native":Xr="node";const pc={"X-Client-Info":`supabase-js-${Xr}/${fc}`},gc={headers:pc},bc={schema:"public"},mc={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},yc={};function us(t){"@babel/helpers - typeof";return us=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},us(t)}function vc(t,e){if(us(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(us(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function wc(t){var e=vc(t,"string");return us(e)=="symbol"?e:e+""}function xc(t,e,r){return(e=wc(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function vi(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 Ce(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?vi(Object(r),!0).forEach(function(s){xc(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):vi(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const _c=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),kc=()=>Headers,Sc=(t,e,r)=>{const s=_c(r),n=kc();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,Ce(Ce({},a),{},{headers:u}))}};function Ec(t){return t.endsWith("/")?t:t+"/"}function jc(t,e){var r,s;const{db:n,auth:i,realtime:a,global:l}=t,{db:c,auth:u,realtime:d,global:h}=e,f={db:Ce(Ce({},c),n),auth:Ce(Ce({},u),i),realtime:Ce(Ce({},d),a),storage:{},global:Ce(Ce(Ce({},h),l),{},{headers:Ce(Ce({},(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?f.accessToken=t.accessToken:delete f.accessToken,f}function Tc(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(Ec(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Rc=class extends hc{constructor(t){super(t)}},Cc=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=Tc(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:bc,realtime:yc,auth:Ce(Ce({},mc),{},{storageKey:a}),global:gc},c=jc(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=Sc(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Ce({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 fo(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 al(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new no(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 f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Rc({url:this.authUrl.href,headers:Ce(Ce({},f),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(p=>p.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Ao(this.realtimeUrl.href,Ce(Ce({},t),{},{params:Ce(Ce({},{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 mn=(t,e,r)=>new Cc(t,e,r);function Ac(){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}Ac()&&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 ws=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(){}},Oc={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},pt,sr,$i,Pc=($i=class{constructor(){re(this,pt,Oc);re(this,sr,!1)}setTimeoutProvider(t){process.env.NODE_ENV!=="production"&&S(this,sr)&&t!==S(this,pt)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:S(this,pt),provider:t}),q(this,pt,t),process.env.NODE_ENV!=="production"&&q(this,sr,!1)}setTimeout(t,e){return process.env.NODE_ENV!=="production"&&q(this,sr,!0),S(this,pt).setTimeout(t,e)}clearTimeout(t){S(this,pt).clearTimeout(t)}setInterval(t,e){return process.env.NODE_ENV!=="production"&&q(this,sr,!0),S(this,pt).setInterval(t,e)}clearInterval(t){S(this,pt).clearInterval(t)}},pt=new WeakMap,sr=new WeakMap,$i),rr=new Pc;function Ic(t){setTimeout(t,0)}var fr=typeof window>"u"||"Deno"in globalThis;function Ve(){}function Nc(t,e){return typeof t=="function"?t(e):t}function yn(t){return typeof t=="number"&&t>=0&&t!==1/0}function ua(t,e){return Math.max(t+(e||0)-Date.now(),0)}function Ht(t,e){return typeof t=="function"?t(e):t}function rt(t,e){return typeof t=="function"?t(e):t}function wi(t,e){const{type:r="all",exact:s,fetchStatus:n,predicate:i,queryKey:a,stale:l}=t;if(a){if(s){if(e.queryHash!==Fn(a,e.options))return!1}else if(!hs(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 xi(t,e){const{exact:r,status:s,predicate:n,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(r){if(ds(e.options.mutationKey)!==ds(i))return!1}else if(!hs(e.options.mutationKey,i))return!1}return!(s&&e.state.status!==s||n&&!n(e))}function Fn(t,e){return((e==null?void 0:e.queryKeyHashFn)||ds)(t)}function ds(t){return JSON.stringify(t,(e,r)=>xn(r)?Object.keys(r).sort().reduce((s,n)=>(s[n]=r[n],s),{}):r)}function hs(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(r=>hs(t[r],e[r])):!1}var Bc=Object.prototype.hasOwnProperty;function vn(t,e,r=0){if(t===e)return t;if(r>500)return e;const s=_i(t)&&_i(e);if(!s&&!(xn(t)&&xn(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],f=t[h],p=e[h];if(f===p){c[h]=f,(s?d<i:Bc.call(t,h))&&u++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){c[h]=p;continue}const v=vn(f,p,r+1);c[h]=v,v===f&&u++}return i===l&&u===i?t:c}function wn(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 _i(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function xn(t){if(!ki(t))return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(!ki(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function ki(t){return Object.prototype.toString.call(t)==="[object Object]"}function Fc(t){return new Promise(e=>{rr.setTimeout(e,t)})}function _n(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 vn(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 vn(t,e)}return e}function Lc(t,e,r=0){const s=[...t,e];return r&&s.length>r?s.slice(1):s}function $c(t,e,r=0){const s=[e,...t];return r&&s.length>r?s.slice(0,-1):s}var Fs=Symbol();function da(t,e){return process.env.NODE_ENV!=="production"&&t.queryFn===Fs&&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===Fs?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function ha(t,e){return typeof t=="function"?t(...e):!!t}function Dc(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 nr,$t,Ar,Di,Uc=(Di=class extends ws{constructor(){super();re(this,nr);re(this,$t);re(this,Ar);q(this,Ar,e=>{if(!fr&&window.addEventListener){const r=()=>e();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){S(this,$t)||this.setEventListener(S(this,Ar))}onUnsubscribe(){var e;this.hasListeners()||((e=S(this,$t))==null||e.call(this),q(this,$t,void 0))}setEventListener(e){var r;q(this,Ar,e),(r=S(this,$t))==null||r.call(this),q(this,$t,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){S(this,nr)!==e&&(q(this,nr,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(r=>{r(e)})}isFocused(){var e;return typeof S(this,nr)=="boolean"?S(this,nr):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},nr=new WeakMap,$t=new WeakMap,Ar=new WeakMap,Di),Ln=new Uc;function kn(){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 Mc=Ic;function Wc(){let t=[],e=0,r=l=>{l()},s=l=>{l()},n=Mc;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 Ue=Wc(),Or,Dt,Pr,Ui,qc=(Ui=class extends ws{constructor(){super();re(this,Or,!0);re(this,Dt);re(this,Pr);q(this,Pr,e=>{if(!fr&&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(){S(this,Dt)||this.setEventListener(S(this,Pr))}onUnsubscribe(){var e;this.hasListeners()||((e=S(this,Dt))==null||e.call(this),q(this,Dt,void 0))}setEventListener(e){var r;q(this,Pr,e),(r=S(this,Dt))==null||r.call(this),q(this,Dt,e(this.setOnline.bind(this)))}setOnline(e){S(this,Or)!==e&&(q(this,Or,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return S(this,Or)}},Or=new WeakMap,Dt=new WeakMap,Pr=new WeakMap,Ui),Ls=new qc;function zc(t){return Math.min(1e3*2**t,3e4)}function fa(t){return(t??"online")==="online"?Ls.isOnline():!0}var Sn=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function pa(t){let e=!1,r=0,s;const n=kn(),i=()=>n.status!=="pending",a=m=>{var b;if(!i()){const y=new Sn(m);f(y),(b=t.onCancel)==null||b.call(t,y)}},l=()=>{e=!0},c=()=>{e=!1},u=()=>Ln.isFocused()&&(t.networkMode==="always"||Ls.isOnline())&&t.canRun(),d=()=>fa(t.networkMode)&&t.canRun(),h=m=>{i()||(s==null||s(),n.resolve(m))},f=m=>{i()||(s==null||s(),n.reject(m))},p=()=>new Promise(m=>{var b;s=y=>{(i()||u())&&m(y)},(b=t.onPause)==null||b.call(t)}).then(()=>{var m;s=void 0,i()||(m=t.onContinue)==null||m.call(t)}),v=()=>{if(i())return;let m;const b=r===0?t.initialPromise:void 0;try{m=b??t.fn()}catch(y){m=Promise.reject(y)}Promise.resolve(m).then(h).catch(y=>{var A;if(i())return;const _=t.retry??(fr?0:3),k=t.retryDelay??zc,w=typeof k=="function"?k(r,y):k,E=_===!0||typeof _=="number"&&r<_||typeof _=="function"&&_(r,y);if(e||!E){f(y);return}r++,(A=t.onFail)==null||A.call(t,r,y),Fc(w).then(()=>u()?void 0:p()).then(()=>{e?f(y):v()})})};return{promise:n,status:()=>n.status,cancel:a,continue:()=>(s==null||s(),n),cancelRetry:l,continueRetry:c,canStart:d,start:()=>(d()?v():p().then(v),n)}}var ir,Mi,ga=(Mi=class{constructor(){re(this,ir)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),yn(this.gcTime)&&q(this,ir,rr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(fr?1/0:5*60*1e3))}clearGcTimeout(){S(this,ir)&&(rr.clearTimeout(S(this,ir)),q(this,ir,void 0))}},ir=new WeakMap,Mi),ar,Ir,tt,or,Le,ps,lr,ct,wt,Wi,Hc=(Wi=class extends ga{constructor(e){super();re(this,ct);re(this,ar);re(this,Ir);re(this,tt);re(this,or);re(this,Le);re(this,ps);re(this,lr);q(this,lr,!1),q(this,ps,e.defaultOptions),this.setOptions(e.options),this.observers=[],q(this,or,e.client),q(this,tt,S(this,or).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,q(this,ar,Ei(this.options)),this.state=e.state??S(this,ar),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=S(this,Le))==null?void 0:e.promise}setOptions(e){if(this.options={...S(this,ps),...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const r=Ei(this.options);r.data!==void 0&&(this.setState(Si(r.data,r.dataUpdatedAt)),q(this,ar,r))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&S(this,tt).remove(this)}setData(e,r){const s=_n(this.state.data,e,this.options);return ue(this,ct,wt).call(this,{data:s,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),s}setState(e,r){ue(this,ct,wt).call(this,{type:"setState",state:e,setStateOptions:r})}cancel(e){var s,n;const r=(s=S(this,Le))==null?void 0:s.promise;return(n=S(this,Le))==null||n.cancel(e),r?r.then(Ve).catch(Ve):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(S(this,ar))}isActive(){return this.observers.some(e=>rt(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Fs||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ht(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:!ua(this.state.dataUpdatedAt,e)}onFocus(){var r;const e=this.observers.find(s=>s.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(r=S(this,Le))==null||r.continue()}onOnline(){var r;const e=this.observers.find(s=>s.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(r=S(this,Le))==null||r.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),S(this,tt).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(r=>r!==e),this.observers.length||(S(this,Le)&&(S(this,lr)?S(this,Le).cancel({revert:!0}):S(this,Le).cancelRetry()),this.scheduleGc()),S(this,tt).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||ue(this,ct,wt).call(this,{type:"invalidate"})}async fetch(e,r){var c,u,d,h,f,p,v,m,b,y,_,k;if(this.state.fetchStatus!=="idle"&&((c=S(this,Le))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(S(this,Le))return S(this,Le).continueRetry(),S(this,Le).promise}if(e&&this.setOptions(e),!this.options.queryFn){const w=this.observers.find(E=>E.options.queryFn);w&&this.setOptions(w.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=w=>{Object.defineProperty(w,"signal",{enumerable:!0,get:()=>(q(this,lr,!0),s.signal)})},i=()=>{const w=da(this.options,r),A=(()=>{const F={client:S(this,or),queryKey:this.queryKey,meta:this.meta};return n(F),F})();return q(this,lr,!1),this.options.persister?this.options.persister(w,A,this):w(A)},l=(()=>{const w={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:S(this,or),state:this.state,fetchFn:i};return n(w),w})();(u=this.options.behavior)==null||u.onFetch(l,this),q(this,Ir,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((d=l.fetchOptions)==null?void 0:d.meta))&&ue(this,ct,wt).call(this,{type:"fetch",meta:(h=l.fetchOptions)==null?void 0:h.meta}),q(this,Le,pa({initialPromise:r==null?void 0:r.initialPromise,fn:l.fetchFn,onCancel:w=>{w instanceof Sn&&w.revert&&this.setState({...S(this,Ir),fetchStatus:"idle"}),s.abort()},onFail:(w,E)=>{ue(this,ct,wt).call(this,{type:"failed",failureCount:w,error:E})},onPause:()=>{ue(this,ct,wt).call(this,{type:"pause"})},onContinue:()=>{ue(this,ct,wt).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode,canRun:()=>!0}));try{const w=await S(this,Le).start();if(w===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(w),(p=(f=S(this,tt).config).onSuccess)==null||p.call(f,w,this),(m=(v=S(this,tt).config).onSettled)==null||m.call(v,w,this.state.error,this),w}catch(w){if(w instanceof Sn){if(w.silent)return S(this,Le).promise;if(w.revert){if(this.state.data===void 0)throw w;return this.state.data}}throw ue(this,ct,wt).call(this,{type:"error",error:w}),(y=(b=S(this,tt).config).onError)==null||y.call(b,w,this),(k=(_=S(this,tt).config).onSettled)==null||k.call(_,this.state.data,w,this),w}finally{this.scheduleGc()}}},ar=new WeakMap,Ir=new WeakMap,tt=new WeakMap,or=new WeakMap,Le=new WeakMap,ps=new WeakMap,lr=new WeakMap,ct=new WeakSet,wt=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,...ba(s.data,this.options),fetchMeta:e.meta??null};case"success":const n={...s,...Si(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return q(this,Ir,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),Ue.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),S(this,tt).notify({query:this,type:"updated",action:e})})},Wi);function ba(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:fa(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function Si(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Ei(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 Ke,de,gs,ze,cr,Nr,_t,Ut,bs,Br,Fr,ur,dr,Mt,Lr,ge,Zr,En,jn,Tn,Rn,Cn,An,On,ma,qi,Kc=(qi=class extends ws{constructor(e,r){super();re(this,ge);re(this,Ke);re(this,de);re(this,gs);re(this,ze);re(this,cr);re(this,Nr);re(this,_t);re(this,Ut);re(this,bs);re(this,Br);re(this,Fr);re(this,ur);re(this,dr);re(this,Mt);re(this,Lr,new Set);this.options=r,q(this,Ke,e),q(this,Ut,null),q(this,_t,kn()),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(S(this,de).addObserver(this),ji(S(this,de),this.options)?ue(this,ge,Zr).call(this):this.updateResult(),ue(this,ge,Rn).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Pn(S(this,de),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Pn(S(this,de),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,ue(this,ge,Cn).call(this),ue(this,ge,An).call(this),S(this,de).removeObserver(this)}setOptions(e){const r=this.options,s=S(this,de);if(this.options=S(this,Ke).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof rt(this.options.enabled,S(this,de))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");ue(this,ge,On).call(this),S(this,de).setOptions(this.options),r._defaulted&&!wn(this.options,r)&&S(this,Ke).getQueryCache().notify({type:"observerOptionsUpdated",query:S(this,de),observer:this});const n=this.hasListeners();n&&Ti(S(this,de),s,this.options,r)&&ue(this,ge,Zr).call(this),this.updateResult(),n&&(S(this,de)!==s||rt(this.options.enabled,S(this,de))!==rt(r.enabled,S(this,de))||Ht(this.options.staleTime,S(this,de))!==Ht(r.staleTime,S(this,de)))&&ue(this,ge,En).call(this);const i=ue(this,ge,jn).call(this);n&&(S(this,de)!==s||rt(this.options.enabled,S(this,de))!==rt(r.enabled,S(this,de))||i!==S(this,Mt))&&ue(this,ge,Tn).call(this,i)}getOptimisticResult(e){const r=S(this,Ke).getQueryCache().build(S(this,Ke),e),s=this.createResult(r,e);return Gc(this,s)&&(q(this,ze,s),q(this,Nr,this.options),q(this,cr,S(this,de).state)),s}getCurrentResult(){return S(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&&S(this,_t).status==="pending"&&S(this,_t).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,n))})}trackProp(e){S(this,Lr).add(e)}getCurrentQuery(){return S(this,de)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const r=S(this,Ke).defaultQueryOptions(e),s=S(this,Ke).getQueryCache().build(S(this,Ke),r);return s.fetch().then(()=>this.createResult(s,r))}fetch(e){return ue(this,ge,Zr).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),S(this,ze)))}createResult(e,r){var U;const s=S(this,de),n=this.options,i=S(this,ze),a=S(this,cr),l=S(this,Nr),u=e!==s?e.state:S(this,gs),{state:d}=e;let h={...d},f=!1,p;if(r._optimisticResults){const j=this.hasListeners(),R=!j&&ji(e,r),T=j&&Ti(e,s,r,n);(R||T)&&(h={...h,...ba(d.data,e.options)}),r._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:v,errorUpdatedAt:m,status:b}=h;p=h.data;let y=!1;if(r.placeholderData!==void 0&&p===void 0&&b==="pending"){let j;i!=null&&i.isPlaceholderData&&r.placeholderData===(l==null?void 0:l.placeholderData)?(j=i.data,y=!0):j=typeof r.placeholderData=="function"?r.placeholderData((U=S(this,Fr))==null?void 0:U.state.data,S(this,Fr)):r.placeholderData,j!==void 0&&(b="success",p=_n(i==null?void 0:i.data,j,r),f=!0)}if(r.select&&p!==void 0&&!y)if(i&&p===(a==null?void 0:a.data)&&r.select===S(this,bs))p=S(this,Br);else try{q(this,bs,r.select),p=r.select(p),p=_n(i==null?void 0:i.data,p,r),q(this,Br,p),q(this,Ut,null)}catch(j){q(this,Ut,j)}S(this,Ut)&&(v=S(this,Ut),p=S(this,Br),m=Date.now(),b="error");const _=h.fetchStatus==="fetching",k=b==="pending",w=b==="error",E=k&&_,A=p!==void 0,N={status:b,fetchStatus:h.fetchStatus,isPending:k,isSuccess:b==="success",isError:w,isInitialLoading:E,isLoading:E,data:p,dataUpdatedAt:h.dataUpdatedAt,error:v,errorUpdatedAt:m,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:_,isRefetching:_&&!k,isLoadingError:w&&!A,isPaused:h.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:w&&A,isStale:$n(e,r),refetch:this.refetch,promise:S(this,_t),isEnabled:rt(r.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const j=N.data!==void 0,R=N.status==="error"&&!j,T=K=>{R?K.reject(N.error):j&&K.resolve(N.data)},C=()=>{const K=q(this,_t,N.promise=kn());T(K)},B=S(this,_t);switch(B.status){case"pending":e.queryHash===s.queryHash&&T(B);break;case"fulfilled":(R||N.data!==B.value)&&C();break;case"rejected":(!R||N.error!==B.reason)&&C();break}}return N}updateResult(){const e=S(this,ze),r=this.createResult(S(this,de),this.options);if(q(this,cr,S(this,de).state),q(this,Nr,this.options),S(this,cr).data!==void 0&&q(this,Fr,S(this,de)),wn(r,e))return;q(this,ze,r);const s=()=>{if(!e)return!0;const{notifyOnChangeProps:n}=this.options,i=typeof n=="function"?n():n;if(i==="all"||!i&&!S(this,Lr).size)return!0;const a=new Set(i??S(this,Lr));return this.options.throwOnError&&a.add("error"),Object.keys(S(this,ze)).some(l=>{const c=l;return S(this,ze)[c]!==e[c]&&a.has(c)})};ue(this,ge,ma).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&ue(this,ge,Rn).call(this)}},Ke=new WeakMap,de=new WeakMap,gs=new WeakMap,ze=new WeakMap,cr=new WeakMap,Nr=new WeakMap,_t=new WeakMap,Ut=new WeakMap,bs=new WeakMap,Br=new WeakMap,Fr=new WeakMap,ur=new WeakMap,dr=new WeakMap,Mt=new WeakMap,Lr=new WeakMap,ge=new WeakSet,Zr=function(e){ue(this,ge,On).call(this);let r=S(this,de).fetch(this.options,e);return e!=null&&e.throwOnError||(r=r.catch(Ve)),r},En=function(){ue(this,ge,Cn).call(this);const e=Ht(this.options.staleTime,S(this,de));if(fr||S(this,ze).isStale||!yn(e))return;const s=ua(S(this,ze).dataUpdatedAt,e)+1;q(this,ur,rr.setTimeout(()=>{S(this,ze).isStale||this.updateResult()},s))},jn=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(S(this,de)):this.options.refetchInterval)??!1},Tn=function(e){ue(this,ge,An).call(this),q(this,Mt,e),!(fr||rt(this.options.enabled,S(this,de))===!1||!yn(S(this,Mt))||S(this,Mt)===0)&&q(this,dr,rr.setInterval(()=>{(this.options.refetchIntervalInBackground||Ln.isFocused())&&ue(this,ge,Zr).call(this)},S(this,Mt)))},Rn=function(){ue(this,ge,En).call(this),ue(this,ge,Tn).call(this,ue(this,ge,jn).call(this))},Cn=function(){S(this,ur)&&(rr.clearTimeout(S(this,ur)),q(this,ur,void 0))},An=function(){S(this,dr)&&(rr.clearInterval(S(this,dr)),q(this,dr,void 0))},On=function(){const e=S(this,Ke).getQueryCache().build(S(this,Ke),this.options);if(e===S(this,de))return;const r=S(this,de);q(this,de,e),q(this,gs,e.state),this.hasListeners()&&(r==null||r.removeObserver(this),e.addObserver(this))},ma=function(e){Ue.batch(()=>{e.listeners&&this.listeners.forEach(r=>{r(S(this,ze))}),S(this,Ke).getQueryCache().notify({query:S(this,de),type:"observerResultsUpdated"})})},qi);function Vc(t,e){return rt(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function ji(t,e){return Vc(t,e)||t.state.data!==void 0&&Pn(t,e,e.refetchOnMount)}function Pn(t,e,r){if(rt(e.enabled,t)!==!1&&Ht(e.staleTime,t)!=="static"){const s=typeof r=="function"?r(t):r;return s==="always"||s!==!1&&$n(t,e)}return!1}function Ti(t,e,r,s){return(t!==e||rt(s.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&$n(t,r)}function $n(t,e){return rt(e.enabled,t)!==!1&&t.isStaleByTime(Ht(e.staleTime,t))}function Gc(t,e){return!wn(t.getCurrentResult(),e)}function Ri(t){return{onFetch:(e,r)=>{var d,h,f,p,v;const s=e.options,n=(f=(h=(d=e.fetchOptions)==null?void 0:d.meta)==null?void 0:h.fetchMore)==null?void 0:f.direction,i=((p=e.state.data)==null?void 0:p.pages)||[],a=((v=e.state.data)==null?void 0:v.pageParams)||[];let l={pages:[],pageParams:[]},c=0;const u=async()=>{let m=!1;const b=k=>{Dc(k,()=>e.signal,()=>m=!0)},y=da(e.options,e.fetchOptions),_=async(k,w,E)=>{if(m)return Promise.reject();if(w==null&&k.pages.length)return Promise.resolve(k);const F=(()=>{const R={client:e.client,queryKey:e.queryKey,pageParam:w,direction:E?"backward":"forward",meta:e.options.meta};return b(R),R})(),N=await y(F),{maxPages:U}=e.options,j=E?$c:Lc;return{pages:j(k.pages,N,U),pageParams:j(k.pageParams,w,U)}};if(n&&i.length){const k=n==="backward",w=k?Jc:Ci,E={pages:i,pageParams:a},A=w(s,E);l=await _(E,A,k)}else{const k=t??i.length;do{const w=c===0?a[0]??s.initialPageParam:Ci(s,l);if(c>0&&w==null)break;l=await _(l,w),c++}while(c<k)}return l};e.options.persister?e.fetchFn=()=>{var m,b;return(b=(m=e.options).persister)==null?void 0:b.call(m,u,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r)}:e.fetchFn=u}}}function Ci(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 Jc(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 ms,gt,We,hr,bt,Bt,zi,Qc=(zi=class extends ga{constructor(e){super();re(this,bt);re(this,ms);re(this,gt);re(this,We);re(this,hr);q(this,ms,e.client),this.mutationId=e.mutationId,q(this,We,e.mutationCache),q(this,gt,[]),this.state=e.state||Yc(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){S(this,gt).includes(e)||(S(this,gt).push(e),this.clearGcTimeout(),S(this,We).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){q(this,gt,S(this,gt).filter(r=>r!==e)),this.scheduleGc(),S(this,We).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){S(this,gt).length||(this.state.status==="pending"?this.scheduleGc():S(this,We).remove(this))}continue(){var e;return((e=S(this,hr))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var a,l,c,u,d,h,f,p,v,m,b,y,_,k,w,E,A,F;const r=()=>{ue(this,bt,Bt).call(this,{type:"continue"})},s={client:S(this,ms),meta:this.options.meta,mutationKey:this.options.mutationKey};q(this,hr,pa({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(N,U)=>{ue(this,bt,Bt).call(this,{type:"failed",failureCount:N,error:U})},onPause:()=>{ue(this,bt,Bt).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>S(this,We).canRun(this)}));const n=this.state.status==="pending",i=!S(this,hr).canStart();try{if(n)r();else{ue(this,bt,Bt).call(this,{type:"pending",variables:e,isPaused:i}),S(this,We).config.onMutate&&await S(this,We).config.onMutate(e,this,s);const U=await((l=(a=this.options).onMutate)==null?void 0:l.call(a,e,s));U!==this.state.context&&ue(this,bt,Bt).call(this,{type:"pending",context:U,variables:e,isPaused:i})}const N=await S(this,hr).start();return await((u=(c=S(this,We).config).onSuccess)==null?void 0:u.call(c,N,e,this.state.context,this,s)),await((h=(d=this.options).onSuccess)==null?void 0:h.call(d,N,e,this.state.context,s)),await((p=(f=S(this,We).config).onSettled)==null?void 0:p.call(f,N,null,this.state.variables,this.state.context,this,s)),await((m=(v=this.options).onSettled)==null?void 0:m.call(v,N,null,e,this.state.context,s)),ue(this,bt,Bt).call(this,{type:"success",data:N}),N}catch(N){try{await((y=(b=S(this,We).config).onError)==null?void 0:y.call(b,N,e,this.state.context,this,s))}catch(U){Promise.reject(U)}try{await((k=(_=this.options).onError)==null?void 0:k.call(_,N,e,this.state.context,s))}catch(U){Promise.reject(U)}try{await((E=(w=S(this,We).config).onSettled)==null?void 0:E.call(w,void 0,N,this.state.variables,this.state.context,this,s))}catch(U){Promise.reject(U)}try{await((F=(A=this.options).onSettled)==null?void 0:F.call(A,void 0,N,e,this.state.context,s))}catch(U){Promise.reject(U)}throw ue(this,bt,Bt).call(this,{type:"error",error:N}),N}finally{S(this,We).runNext(this)}}},ms=new WeakMap,gt=new WeakMap,We=new WeakMap,hr=new WeakMap,bt=new WeakSet,Bt=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),Ue.batch(()=>{S(this,gt).forEach(s=>{s.onMutationUpdate(e)}),S(this,We).notify({mutation:this,type:"updated",action:e})})},zi);function Yc(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var kt,ut,ys,Hi,Xc=(Hi=class extends ws{constructor(e={}){super();re(this,kt);re(this,ut);re(this,ys);this.config=e,q(this,kt,new Set),q(this,ut,new Map),q(this,ys,0)}build(e,r,s){const n=new Qc({client:e,mutationCache:this,mutationId:++Ss(this,ys)._,options:e.defaultMutationOptions(r),state:s});return this.add(n),n}add(e){S(this,kt).add(e);const r=Ps(e);if(typeof r=="string"){const s=S(this,ut).get(r);s?s.push(e):S(this,ut).set(r,[e])}this.notify({type:"added",mutation:e})}remove(e){if(S(this,kt).delete(e)){const r=Ps(e);if(typeof r=="string"){const s=S(this,ut).get(r);if(s)if(s.length>1){const n=s.indexOf(e);n!==-1&&s.splice(n,1)}else s[0]===e&&S(this,ut).delete(r)}}this.notify({type:"removed",mutation:e})}canRun(e){const r=Ps(e);if(typeof r=="string"){const s=S(this,ut).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=Ps(e);if(typeof r=="string"){const n=(s=S(this,ut).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(){Ue.batch(()=>{S(this,kt).forEach(e=>{this.notify({type:"removed",mutation:e})}),S(this,kt).clear(),S(this,ut).clear()})}getAll(){return Array.from(S(this,kt))}find(e){const r={exact:!0,...e};return this.getAll().find(s=>xi(r,s))}findAll(e={}){return this.getAll().filter(r=>xi(e,r))}notify(e){Ue.batch(()=>{this.listeners.forEach(r=>{r(e)})})}resumePausedMutations(){const e=this.getAll().filter(r=>r.state.isPaused);return Ue.batch(()=>Promise.all(e.map(r=>r.continue().catch(Ve))))}},kt=new WeakMap,ut=new WeakMap,ys=new WeakMap,Hi);function Ps(t){var e;return(e=t.options.scope)==null?void 0:e.id}var mt,Ki,Zc=(Ki=class extends ws{constructor(e={}){super();re(this,mt);this.config=e,q(this,mt,new Map)}build(e,r,s){const n=r.queryKey,i=r.queryHash??Fn(n,r);let a=this.get(i);return a||(a=new Hc({client:e,queryKey:n,queryHash:i,options:e.defaultQueryOptions(r),state:s,defaultOptions:e.getQueryDefaults(n)}),this.add(a)),a}add(e){S(this,mt).has(e.queryHash)||(S(this,mt).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const r=S(this,mt).get(e.queryHash);r&&(e.destroy(),r===e&&S(this,mt).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Ue.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return S(this,mt).get(e)}getAll(){return[...S(this,mt).values()]}find(e){const r={exact:!0,...e};return this.getAll().find(s=>wi(r,s))}findAll(e={}){const r=this.getAll();return Object.keys(e).length>0?r.filter(s=>wi(e,s)):r}notify(e){Ue.batch(()=>{this.listeners.forEach(r=>{r(e)})})}onFocus(){Ue.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Ue.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},mt=new WeakMap,Ki),Re,Wt,qt,$r,Dr,zt,Ur,Mr,Vi,eu=(Vi=class{constructor(t={}){re(this,Re);re(this,Wt);re(this,qt);re(this,$r);re(this,Dr);re(this,zt);re(this,Ur);re(this,Mr);q(this,Re,t.queryCache||new Zc),q(this,Wt,t.mutationCache||new Xc),q(this,qt,t.defaultOptions||{}),q(this,$r,new Map),q(this,Dr,new Map),q(this,zt,0)}mount(){Ss(this,zt)._++,S(this,zt)===1&&(q(this,Ur,Ln.subscribe(async t=>{t&&(await this.resumePausedMutations(),S(this,Re).onFocus())})),q(this,Mr,Ls.subscribe(async t=>{t&&(await this.resumePausedMutations(),S(this,Re).onOnline())})))}unmount(){var t,e;Ss(this,zt)._--,S(this,zt)===0&&((t=S(this,Ur))==null||t.call(this),q(this,Ur,void 0),(e=S(this,Mr))==null||e.call(this),q(this,Mr,void 0))}isFetching(t){return S(this,Re).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return S(this,Wt).findAll({...t,status:"pending"}).length}getQueryData(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=S(this,Re).get(e.queryHash))==null?void 0:r.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),r=S(this,Re).build(this,e),s=r.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(Ht(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return S(this,Re).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=S(this,Re).get(s.queryHash),i=n==null?void 0:n.state.data,a=Nc(e,i);if(a!==void 0)return S(this,Re).build(this,s).setData(a,{...r,manual:!0})}setQueriesData(t,e,r){return Ue.batch(()=>S(this,Re).findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,r)]))}getQueryState(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=S(this,Re).get(e.queryHash))==null?void 0:r.state}removeQueries(t){const e=S(this,Re);Ue.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){const r=S(this,Re);return Ue.batch(()=>(r.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const r={revert:!0,...e},s=Ue.batch(()=>S(this,Re).findAll(t).map(n=>n.cancel(r)));return Promise.all(s).then(Ve).catch(Ve)}invalidateQueries(t,e={}){return Ue.batch(()=>(S(this,Re).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=Ue.batch(()=>S(this,Re).findAll(t).filter(n=>!n.isDisabled()&&!n.isStatic()).map(n=>{let i=n.fetch(void 0,r);return r.throwOnError||(i=i.catch(Ve)),n.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(s).then(Ve)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=S(this,Re).build(this,e);return r.isStaleByTime(Ht(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(Ve).catch(Ve)}fetchInfiniteQuery(t){return t.behavior=Ri(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(Ve).catch(Ve)}ensureInfiniteQueryData(t){return t.behavior=Ri(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return Ls.isOnline()?S(this,Wt).resumePausedMutations():Promise.resolve()}getQueryCache(){return S(this,Re)}getMutationCache(){return S(this,Wt)}getDefaultOptions(){return S(this,qt)}setDefaultOptions(t){q(this,qt,t)}setQueryDefaults(t,e){S(this,$r).set(ds(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...S(this,$r).values()],r={};return e.forEach(s=>{hs(t,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(t,e){S(this,Dr).set(ds(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...S(this,Dr).values()],r={};return e.forEach(s=>{hs(t,s.mutationKey)&&Object.assign(r,s.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;const e={...S(this,qt).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=Fn(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===Fs&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...S(this,qt).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){S(this,Re).clear(),S(this,Wt).clear()}},Re=new WeakMap,Wt=new WeakMap,qt=new WeakMap,$r=new WeakMap,Dr=new WeakMap,zt=new WeakMap,Ur=new WeakMap,Mr=new WeakMap,Vi),ya=st.createContext(void 0),va=t=>{const e=st.useContext(ya);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},tu=({client:t,children:e})=>(st.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),o.jsx(ya.Provider,{value:t,children:e})),wa=st.createContext(!1),ru=()=>st.useContext(wa);wa.Provider;function su(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var nu=st.createContext(su()),iu=()=>st.useContext(nu),au=(t,e,r)=>{const s=r!=null&&r.state.error&&typeof t.throwOnError=="function"?ha(t.throwOnError,[r.state.error,r]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},ou=t=>{st.useEffect(()=>{t.clearReset()},[t])},lu=({result:t,errorResetBoundary:e,throwOnError:r,query:s,suspense:n})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(n&&t.data===void 0||ha(r,[t.error,s])),cu=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))}},uu=(t,e)=>t.isLoading&&t.isFetching&&!e,du=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,Ai=(t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()});function hu(t,e,r){var f,p,v,m;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=ru(),n=iu(),i=va(),a=i.defaultQueryOptions(t);(p=(f=i.getDefaultOptions().queries)==null?void 0:f._experimental_beforeQuery)==null||p.call(f,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",cu(a),au(a,n,l),ou(n);const c=!i.getQueryCache().get(a.queryHash),[u]=st.useState(()=>new e(i,a)),d=u.getOptimisticResult(a),h=!s&&t.subscribed!==!1;if(st.useSyncExternalStore(st.useCallback(b=>{const y=h?u.subscribe(Ue.batchCalls(b)):Ve;return u.updateResult(),y},[u,h]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),st.useEffect(()=>{u.setOptions(a)},[a,u]),du(a,d))throw Ai(a,u,n);if(lu({result:d,errorResetBoundary:n,throwOnError:a.throwOnError,query:l,suspense:a.suspense}))throw d.error;if((m=(v=i.getDefaultOptions().queries)==null?void 0:v._experimental_afterQuery)==null||m.call(v,a,d),a.experimental_prefetchInRender&&!fr&&uu(d,s)){const b=c?Ai(a,u,n):l==null?void 0:l.promise;b==null||b.catch(Ve).finally(()=>{u.updateResult()})}return a.notifyOnChangeProps?d:u.trackResult(d)}function xs(t,e){return hu(t,Kc)}const fu=()=>`bob_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;function xa({ga4Config:t,hostContext:e,callbacks:r,enabled:s=!0}){const n=g.useRef(fu()),i=g.useRef(!1),a=g.useCallback((k,w)=>{if(!(!(t!=null&&t.measurementId)||typeof window>"u")&&window.gtag){const E={...w,send_to:t.measurementId};t.debug&&console.log("[BobAnalytics] GA4 event:",k,E),window.gtag("event",k,E)}},[t]),l=g.useCallback((k,w={})=>{var A,F,N,U,j,R,T,C;if(!s)return;const E={event_name:k,timestamp:new Date().toISOString(),session_id:n.current,user_email:(A=e==null?void 0:e.user)==null?void 0:A.email,user_id:(F=e==null?void 0:e.user)==null?void 0:F.id,vehicle_id:(j=(U=(N=e==null?void 0:e.vehicle)==null?void 0:N.selectedVehicle)==null?void 0:U.vehicle_id)==null?void 0:j.toString(),rego:(T=(R=e==null?void 0:e.vehicle)==null?void 0:R.selectedVehicle)==null?void 0:T.rego,parameters:w};a(k,{session_id:E.session_id,user_email:E.user_email,vehicle_id:E.vehicle_id,...w}),(C=r==null?void 0:r.onAnalyticsEvent)==null||C.call(r,E),t!=null&&t.debug&&console.log("[BobAnalytics] Event tracked:",E)},[s,e,r,a,t==null?void 0:t.debug]),c=g.useCallback(()=>{var k,w,E;i.current||(i.current=!0,l("bob_session_start",{widget_version:St,has_vehicle:!!((k=e==null?void 0:e.vehicle)!=null&&k.selectedVehicle),has_user:!!((w=e==null?void 0:e.user)!=null&&w.id)||!!((E=e==null?void 0:e.user)!=null&&E.email)}))},[l,e]),u=g.useCallback((k,w)=>{l("bob_message_sent",{message_length:k,has_vehicle:w})},[l]),d=g.useCallback(k=>{l("bob_vehicle_identified",{vehicle_make:k.make||"unknown",vehicle_model:k.model||"unknown",vehicle_year:k.year||"unknown",rego:k.rego})},[l]),h=g.useCallback((k,w)=>{l("bob_parts_viewed",{part_count:k,vehicle_id:w})},[l]),f=g.useCallback(k=>{l("bob_product_clicked",{sku:k.sku,product_name:k.product_name,price:k.price,brand:k.brand})},[l]),p=g.useCallback(k=>{l("bob_product_viewed",{sku:k.sku,product_name:k.product_name,price:k.price,brand:k.brand})},[l]),v=g.useCallback(k=>{l("bob_add_to_cart",{sku:k.sku,product_name:k.product_name,price:k.price,brand:k.brand,quantity:k.quantity??1})},[l]),m=g.useCallback((k,w)=>{l("bob_checkout_started",{cart_value:k,item_count:w})},[l]),b=g.useCallback(k=>{const w=Math.ceil(k/5/150*60);l("bob_speech_played",{text_length:k,duration_estimate:w})},[l]),y=g.useCallback(k=>{l("bob_speech_failed",{text_length:k})},[l]),_=g.useCallback((k,w)=>{l("bob_error",{error_type:k,error_message:w})},[l]);return g.useEffect(()=>{c()},[c]),{trackEvent:l,sessionId:n.current,trackSessionStart:c,trackMessageSent:u,trackVehicleIdentified:d,trackPartsViewed:h,trackProductClicked:f,trackProductViewed:p,trackAddToCart:v,trackCheckoutStarted:m,trackSpeechPlayed:b,trackSpeechFailed:y,trackError:_}}const qs=g.createContext(null);function Dn({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=g.useMemo(()=>new eu({defaultOptions:{queries:{retry:1,staleTime:3e5}}}),[]),h=i||d,f=!!i;g.useEffect(()=>{console.log(`[BobWidget] v${St} initialized`),console.log(`[BobWidget] QueryClient: ${f?"external (shared)":"internal"}`),console.log(`[BobWidget] Analytics: ${l?"enabled":"disabled"}`),a!=null&&a.measurementId&&console.log(`[BobWidget] GA4: ${a.measurementId}`)},[f,l,a==null?void 0:a.measurementId]);const p=g.useMemo(()=>mn(e.supabaseUrl,e.supabaseKey),[e.supabaseUrl,e.supabaseKey]),[v,m]=g.useState(s);g.useEffect(()=>{m(s)},[s]);const b=g.useCallback(_=>{m(k=>({...k,..._}))},[]),y=g.useMemo(()=>({bobSupabase:p,bobConfig:e,hostApiConfig:r,hostContext:v,callbacks:n,updateHostContext:b,ga4Config:a,analyticsEnabled:l,bottomOffset:c,zIndexBase:u}),[p,e,r,v,n,b,a,l,c,u]);return o.jsx(tu,{client:h,children:o.jsx(qs.Provider,{value:y,children:t})})}function jt(){const t=g.useContext(qs);if(!t)throw new Error("useBobContext must be used within a BobProvider");return t}function pu(){const{bobSupabase:t}=jt();return t}function pr(){const t=g.useContext(qs);return(t==null?void 0:t.bobSupabase)||null}function gu(){const{hostContext:t}=jt();return t}function bu(){const{hostApiConfig:t}=jt();return t}function mu(){const{callbacks:t}=jt();return t}function yu(){const{ga4Config:t,analyticsEnabled:e}=jt();return{ga4Config:t,enabled:e}}function Un(){const t=g.useContext(qs);return t?{bottomOffset:t.bottomOffset,zIndexBase:t.zIndexBase}:{bottomOffset:0,zIndexBase:50}}const vu=15e3,wu={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},Qr=new Map,xu=t=>t.replace(/\bya\b/gi,"you"),_a=({onStart:t,onEnd:e,onFailed:r}={})=>{const{bobConfig:s,bobSupabase:n}=jt(),[i,a]=g.useState(!1),l=g.useRef(null),c=g.useRef(null),u=g.useRef(!1),d=g.useRef([]),h=g.useRef(!1),f=g.useRef(!1),p=g.useRef(null),v=g.useRef(null),m=g.useRef(t),b=g.useRef(e),y=g.useRef(r);g.useEffect(()=>{m.current=t,b.current=e,y.current=r},[t,e,r]);const _=g.useCallback(()=>{c.current&&(clearTimeout(c.current),c.current=null)},[]),k=g.useCallback(()=>{var T;u.current||(u.current=!0,console.log("[BobWidget TTS] Fallback: triggering onStart without audio"),(T=m.current)==null||T.call(m))},[]),w=g.useCallback(async T=>{if(Qr.has(T)){const C=Qr.get(T);return console.log(`[BobWidget TTS] Cache hit for clip: ${T}`,C?"found":"null"),C||null}try{console.log(`[BobWidget TTS] Fetching clip from DB: ${T}`);const{data:C,error:B}=await n.from("bob_audio_clips").select("audio_url").eq("clip_key",T).eq("is_active",!0).single();return B||!C?(console.log(`[BobWidget TTS] No clip found for: ${T}`),Qr.set(T,null),null):(console.log(`[BobWidget TTS] Clip found: ${T} -> ${C.audio_url}`),Qr.set(T,C),C)}catch(C){return console.warn(`[BobWidget TTS] Clip lookup failed for ${T}:`,C),Qr.set(T,null),null}},[n]),E=g.useCallback(async T=>{for(const[C,B]of Object.entries(wu))if(B.test(T)){console.log(`[BobWidget TTS] Pattern matched: ${C}`);const K=await w(C);if(K!=null&&K.audio_url)return K.audio_url}return null},[w]),A=g.useCallback(async()=>{var K,Y,te;if(h.current||d.current.length===0)return;h.current=!0;const T=d.current.shift();if(!T){h.current=!1;return}const{text:C,isGreeting:B}=T;B&&(f.current=!0),u.current=!1,_(),l.current&&(l.current.pause(),l.current=null),c.current=setTimeout(()=>{var $,M;console.warn("[BobWidget TTS] Timeout - triggering fallback callbacks"),k(),a(!1),f.current=!1,($=b.current)==null||$.call(b),(M=y.current)==null||M.call(y),l.current=null,h.current=!1,A()},vu);try{let $=null;if($=await E(C),$)console.log("[BobWidget TTS] Using pre-recorded audio (fast path)");else{console.log("[BobWidget TTS] No pre-recorded clip, using ElevenLabs TTS");const J=xu(C),oe=await fetch(`${s.supabaseUrl}/functions/v1/bob-tts-elevenlabs`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.supabaseKey}`},body:JSON.stringify({text:J})});if(!oe.ok){const P=await oe.json().catch(()=>({}));throw console.error("[BobWidget TTS] Request failed:",P),new Error("TTS request failed")}const X=await oe.blob();$=URL.createObjectURL(X)}const M=new Audio($);l.current=M,M.onplay=()=>{var J;_(),p.current=null,u.current||(u.current=!0,a(!0),console.log("[BobWidget TTS] Audio playing, triggering onStart (animation: TALKING)"),(J=m.current)==null||J.call(m))},M.onended=()=>{var J;_(),a(!1),f.current=!1,console.log("[BobWidget TTS] Audio ended, triggering onEnd (animation: COMPLETE/IDLE)"),(J=b.current)==null||J.call(b),l.current=null,h.current=!1,A()},M.onerror=J=>{var oe,X;_(),console.warn("[BobWidget TTS] Audio playback error:",J),k(),a(!1),f.current=!1,(oe=b.current)==null||oe.call(b),(X=y.current)==null||X.call(y),l.current=null,h.current=!1,A()};try{await M.play()}catch(J){console.warn("[BobWidget TTS] Audio play() failed (autoplay policy):",J),_(),B&&(p.current=C,console.log("[BobWidget TTS] Greeting stored for retry on user interaction")),k(),a(!1),f.current=!1,(K=b.current)==null||K.call(b),h.current=!1,A()}}catch($){_(),console.error("[BobWidget TTS] Speech synthesis error:",$),k(),a(!1),f.current=!1,(Y=b.current)==null||Y.call(b),(te=y.current)==null||te.call(y),h.current=!1,A()}},[s.supabaseUrl,s.supabaseKey,_,k,E]),F=g.useCallback((T,C=!1)=>{if(T.trim()){if(C){if(v.current===T){console.log(`[BobWidget TTS] Ignoring duplicate greeting: "${T.substring(0,30)}..."`);return}v.current=T,p.current=null}if(f.current&&!C){console.log("[BobWidget TTS] Greeting playing - queueing message"),d.current.push({text:T,isGreeting:C});return}C?d.current.unshift({text:T,isGreeting:C}):d.current.push({text:T,isGreeting:C}),A()}},[A]),N=g.useCallback(()=>{if(p.current&&!l.current&&!h.current){console.log("[BobWidget TTS] Retrying pending greeting on user interaction");const T=p.current;p.current=null,F(T,!0)}},[F]),U=g.useCallback(()=>{_(),d.current=[],l.current&&(l.current.pause(),l.current=null),a(!1),f.current=!1,h.current=!1},[_]),j=g.useCallback(()=>{var T;(T=l.current)==null||T.pause()},[]),R=g.useCallback(()=>{var T;(T=l.current)==null||T.play()},[]);return g.useEffect(()=>()=>{_(),d.current=[],l.current&&(l.current.pause(),l.current=null)},[_]),{speak:F,stop:U,pause:j,resume:R,isSpeaking:i,isSupported:!0,retryPendingGreeting:N}},Oi="bob_last_visit",_u=30;function ka(t=_u){const[e,r]=g.useState(!1),[s,n]=g.useState(null);return g.useEffect(()=>{try{const i=localStorage.getItem(Oi),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(Oi,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 In=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},ku=t=>{let e=In(t);return e=e.replace(/[\[\]{}]/g,""),e=e.replace(/https?:\/\/[^\s]+/g,""),e=e.replace(/\bSKU\s*:?\s*\w+/gi,""),e},Su=["what version","which version","software version","bob version","your version","current version","running version","version number","what ver","which ver"],rn=["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"],Eu=["WIPER BLADE FRONT","WIPER BLADE REAR","WIPER BLADE SET","BRAKE PAD KIT","BRAKE PAD KIT FRONT","BRAKE PAD KIT REAR","BRAKE ROTOR","BRAKE ROTOR FRONT","BRAKE ROTOR REAR","BRAKE DISC","AIR FILTER","OIL FILTER","CABIN FILTER","FUEL FILTER","SPARK PLUG SET","SPARK PLUG","BALL JOINT","TIE ROD END","CONTROL ARM","WHEEL BEARING","CV JOINT","DRIVE SHAFT","TIMING BELT KIT","SERPENTINE BELT","DRIVE BELT","SHOCK ABSORBER","STRUT","COIL SPRING","CLUTCH KIT","CLUTCH PLATE","ALTERNATOR","STARTER MOTOR","WATER PUMP","THERMOSTAT","RADIATOR","RADIATOR HOSE","EXHAUST","MUFFLER","CATALYTIC CONVERTER","brake pads","brake rotors","brake discs","brakes","air filter","oil filter","cabin filter","fuel filter","spark plugs","spark plug","wiper","wipers","battery","batteries","clutch","clutch kit","alternator","starter motor","muffler","exhaust","cv joint","axle","timing belt","serpentine belt","shock absorber","struts","suspension"],Sa=({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:f,onHighlightProduct:p,onNoPartsFound:v,onAutoFetchComplete:m,onVariantSelectionRequired:b})=>{var qr,zr,Hr,_s;const{bobConfig:y,hostApiConfig:_,hostContext:k,callbacks:w,ga4Config:E,analyticsEnabled:A}=jt(),F=xa({ga4Config:E,hostContext:k,callbacks:w,enabled:A}),{isReturningUser:N}=ka(),[U,j]=g.useState([]),[R,T]=g.useState(""),[C,B]=g.useState(!1),[K,Y]=g.useState(!1),[te,$]=g.useState(null),M=g.useRef(null),J=g.useRef(!1),oe=g.useRef(!1),X=g.useRef(""),P=g.useRef(!1),D=g.useRef(null);g.useRef(null);const V=g.useRef({source:"none",isPlaying:!1,hasCannedAudio:!1,cannedUrl:null,currentAudio:null,searchingQueue:[]}),Q=g.useRef([]),_e=g.useRef("AWAITING_REGO"),Te=()=>{const z=V.current;if(z.currentAudio){try{z.currentAudio.pause(),z.currentAudio.currentTime=0}catch(fe){console.warn("[BobWidget] Error stopping audio:",fe)}z.currentAudio=null}z.isPlaying=!1,z.source="none",z.searchingQueue=[],Qe()},Ae=(z,fe,ye)=>{const pe=V.current;if(pe.isPlaying){if(fe==="canned"||fe==="searching"&&pe.source==="tts")Te();else if(pe.source==="canned"){console.log("[BobWidget Audio] Skipping lower priority audio while canned is playing");return}}const He=new Audio(z);pe.currentAudio=He,pe.source=fe,pe.isPlaying=!0,He.onplay=()=>{console.log(`[BobWidget Audio] ${fe} STARTED:`,z.split("/").pop()),e||ee(r)},He.onended=()=>{console.log(`[BobWidget Audio] ${fe} ENDED`),pe.currentAudio=null,pe.isPlaying=!1,pe.source="none",ye==null||ye()},He.onerror=()=>{console.warn(`[BobWidget Audio] ${fe} FAILED:`,z),pe.currentAudio=null,pe.isPlaying=!1,pe.source="none",ye==null||ye()},He.play().catch(Kt=>{console.warn(`[BobWidget Audio] ${fe} autoplay blocked:`,Kt),pe.currentAudio=null,pe.isPlaying=!1,pe.source="none",ye==null||ye()})},Be=()=>{const z=V.current;if(z.hasCannedAudio||z.source==="canned"){console.log("[BobWidget Audio] Skipping searching audio - canned audio takes priority"),z.searchingQueue=[];return}if(z.searchingQueue.length===0){!e&&z.source==="searching"&&ee(s);return}const fe=z.searchingQueue.shift();Ae(fe,"searching",()=>{Be()})},Je=()=>{D.current&&(clearTimeout(D.current),D.current=null)},{speak:qe,stop:Qe,isSpeaking:nt,retryPendingGreeting:O}=_a({onStart:()=>{Je(),P.current=!0,console.log("[BobWidget STATE] Speech STARTED - transitioning to TALK state"),F.trackSpeechPlayed(X.current.length),h==null||h(),e||(console.log("[BobWidget STATE] Setting state to:",r),ee(r))},onEnd:()=>{Je(),console.log("[BobWidget STATE] Speech ENDED - transitioning out of TALK state");const z=rn.some(fe=>X.current.toLowerCase().includes(fe.toLowerCase()));e||(z&&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),ee(n),setTimeout(()=>{console.log("[BobWidget STATE] Post-complete transition to:",a),ee(a)},2e3)))},onFailed:()=>{console.warn("[BobWidget] Speech synthesis failed - fallback triggered"),F.trackSpeechFailed(X.current.length)}});g.useEffect(()=>{var z;(z=M.current)==null||z.scrollIntoView({behavior:"smooth"})},[U]),g.useEffect(()=>{var fe,ye;const z=(fe=k.vehicle)==null?void 0:fe.selectedVehicle;z&&!te&&(console.log("[BobWidget] Setting vehicle from host context:",z),$(z),(ye=w.onVehicleIdentified)==null||ye.call(w,z),F.trackVehicleIdentified({make:z.make,model:z.model,year:z.year,rego:z.rego}))},[(qr=k.vehicle)==null?void 0:qr.selectedVehicle]),g.useEffect(()=>{var z;if(U.length===0&&!oe.current){oe.current=!0;const fe=(z=k.vehicle)==null?void 0:z.selectedVehicle;let ye;N?(ye="Ah hey... you again! What you after this time?",console.log("[BobWidget] Using returning user greeting")):fe?ye=`G'day! Saw you've got the ${`${fe.year} ${fe.make} ${fe.model}`} - choice wagon! What can I help you find for it today?`:ye="G'day! Bob from CARFIX here. How can I help ya today?",j([{role:"assistant",content:ye}]),K||setTimeout(()=>{console.log("[BobWidget] Speaking initial greeting (priority)"),qe(ye,!0)},500)}},[(zr=k.vehicle)==null?void 0:zr.selectedVehicle,U.length,K,qe]),g.useEffect(()=>{const z=()=>{console.log("[BobWidget] User interaction detected - retrying pending greeting"),O(),document.removeEventListener("click",z),document.removeEventListener("touchstart",z)};return document.addEventListener("click",z,{once:!0}),document.addEventListener("touchstart",z,{once:!0}),()=>{document.removeEventListener("click",z),document.removeEventListener("touchstart",z)}},[O]),g.useEffect(()=>{var Vt,Gt;const z=(Vt=k.vehicle)==null?void 0:Vt.selectedVehicle;if(!z||J.current)return;const fe=z.vehicle_id??z.id,ye=Number.parseInt(String(fe),10);if(!Number.isFinite(ye)){console.warn("[BobWidget] Vehicle has invalid vehicle_id, cannot auto-fetch:",z);return}J.current=!0;const pe={...z,vehicle_id:String(ye)},He=(Gt=k.user)==null?void 0:Gt.email;(async()=>{var yt,Tt;const gr=`${y.supabaseUrl}/functions/v1/bob-chat`;try{const Me=await fetch(gr,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y.supabaseKey}`},body:JSON.stringify({messages:[],vehicleContext:pe,customerEmail:He,autoFetchParts:!0,hostConfig:_,hostContext:k})});if(!Me.ok||!Me.body){console.error("[BobWidget] Auto-fetch failed:",Me.status);return}const Rt=Me.body.getReader(),Ct=new TextDecoder;let it="";for(;;){const{done:br,value:Jt}=await Rt.read();if(br)break;it+=Ct.decode(Jt,{stream:!0});let At;for(;(At=it.indexOf(`
|
|
73
|
-
`))!==-1;){let
|
|
74
|
-
`))!==-1;){let
|
|
75
|
-
`+vt;break}}}let Kr=Pt.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");Kr=In(Kr),X.current=Kr;const x=rn.some(le=>Pt.toLowerCase().includes(le.toLowerCase())),I=Pt.toLowerCase();for(const le of Eu)if(I.includes(le.toLowerCase())){const he=le.replace(/s\s*$/i,"").toUpperCase();f==null||f(he);break}const W=Pt.match(/(?:go with|recommend|suggest|grab|try)\s+(?:the\s+)?(\w+)\s+(?:at|for)\s+\$(\d+(?:\.\d{2})?)/i);if(W){const[,le,he]=W;p==null||p({brand:le,price:parseFloat(he)})}const Z=V.current;if(!K&&X.current.trim()){if(P.current=!1,Je(),Z.hasCannedAudio&&Z.cannedUrl)console.log("[BobWidget] Playing canned audio (priority):",Z.cannedUrl),Te(),Ae(Z.cannedUrl,"canned",()=>{Z.hasCannedAudio=!1,Z.cannedUrl=null,Je(),e||(x&&u?u():c?c():(ee(n),setTimeout(()=>ee(a),3e3)))}),P.current=!0,h==null||h();else if(Z.isPlaying)console.log("[BobWidget] Skipping TTS - audio already playing:",Z.source);else{const le=ku(X.current);console.log("[BobWidget] Playing TTS (no canned audio)"),qe(le)}D.current=setTimeout(()=>{P.current||(console.warn("[BobWidget] Speech fallback after 5s"),h==null||h(),e||(x&&u?u():c?c():(ee(n),setTimeout(()=>ee(a),3e3))))},5e3)}else h==null||h(),e||(x&&u?u():c?c():(ee(n),setTimeout(()=>ee(a),3e3)))}catch(Se){console.error("[BobWidget] Chat error:",Se);const et=Se instanceof Error?Se:new Error("Unknown error");(Ot=w.onError)==null||Ot.call(w,et),F.trackError(et.name||"ChatError",et.message||"Unknown chat error"),e||ee(i)}},we=async()=>{if(!R.trim()||C)return;O(),Qe();const z={role:"user",content:R};j(pe=>[...pe,z]),T(""),F.trackMessageSent(R.length,!!te);const fe=R.toLowerCase();if(Su.some(pe=>fe.includes(pe))){const pe=`G'day mate! I'm running Bob v${St} - she's running sweet as! Anything else I can help ya with?`;j(He=>[...He,{role:"assistant",content:pe}]),K||qe(pe);return}B(!0),console.log("[BobWidget STATE] User sent message - switching to RESEARCH state:",s),d==null||d(),e||ee(s),await Oe(z),B(!1)};return{messages:U,input:R,setInput:T,isLoading:C,handleSend:we,handleKeyPress:z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),we())},handleInputFocus:()=>{O()},handleInputBlur:()=>{},chatEndRef:M,clearMessages:()=>{j([{role:"assistant",content:"G'day! Bob from CARFIX here. How can I help ya today?"}])},isMuted:K,toggleMute:()=>{Y(z=>!z),K||Qe()},isSpeaking:nt,identifiedVehicle:te,clearVehicle:()=>{$(null)}}},ju={states:[],configs:[],uploadedImages:[],looks:[],activeLookId:null},Ea=t=>{const e=va(),r=pr();return g.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]),xs({queryKey:["bob-animation-data",t],queryFn:async()=>{var k;if(!r)return console.log("[BobAnimation] No supabase client, returning empty data"),ju;const{data:s,error:n}=await r.from("bob_looks").select("*").order("display_order");if(n)throw n;const i=(s||[]).find(w=>w.is_active),a=t||(i==null?void 0:i.id)||s&&((k=s[0])==null?void 0:k.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(w=>w.state_key);console.log(`[BobAnimation] Loaded ${h.length} states: ${h.join(", ")}`);const p=["idle","talking","listening"].filter(w=>{const E=[w,w.replace("ing",""),w+"ing"];return!h.some(A=>E.includes(A))});p.length>0&&console.warn(`[BobAnimation] ⚠️ Missing critical states: ${p.join(", ")}`);const v=new Set(h),m=(u||[]).filter(w=>v.has(w.animation_state));console.log(`[BobAnimation] Loaded ${m.length} animation frames`);const{data:b,error:y}=await r.storage.from("bob-images").list();if(y)throw y;const _=(b||[]).map(w=>{const{data:E}=r.storage.from("bob-images").getPublicUrl(w.name);return E.publicUrl});return m.forEach(w=>{const E=new Image;E.src=w.image_url}),{states:l||[],configs:m,uploadedImages:_,looks:s||[],activeLookId:a}},staleTime:30*1e3,gcTime:5*60*1e3})},ja=(t={})=>{const{isSpeaking:e=!1}=t,[r,s]=g.useState(""),[n,i]=g.useState(0),[a,l]=g.useState(400),[c,u]=g.useState(!1),d=g.useRef(null),h=g.useRef(0),f=g.useRef(e),p=g.useRef(0),v=g.useRef(0),m=g.useRef(!1),b=g.useRef(0),{data:y,isLoading:_}=Ea(),k=g.useRef({}),{imageUrlsMap:w,alternateImages:E,offsetsMap:A,scalesMap:F,availableStates:N}=g.useMemo(()=>{if(!y)return{imageUrlsMap:{},alternateImages:{},offsetsMap:{},scalesMap:{},availableStates:[]};const C={},B={},K={},Y={},te=y.states.map($=>$.state_key);return te.forEach($=>{const M=y.configs.filter(P=>P.animation_state===$),J=M.map(P=>P.image_url),oe=M.map(P=>P.vertical_offset||0),X=M.map(P=>P.scale||100);if(J.length>0){const P=y.states.find(D=>D.state_key===$);C[$]={url:J[0],animation_speed:(P==null?void 0:P.animation_speed)||400,pause_duration:(P==null?void 0:P.pause_duration)||0,loop_count:(P==null?void 0:P.loop_count)||0},B[$]=J,K[$]=oe,Y[$]=X}}),{imageUrlsMap:C,alternateImages:B,offsetsMap:K,scalesMap:Y,availableStates:te}},[y]);g.useEffect(()=>{k.current=w},[w]),g.useEffect(()=>{const C=f.current;if(f.current=e,C&&!e){const B=r.toLowerCase();(B.includes("talk")||B==="talking")&&(console.log("[useBobAnimation] Speech ended while in talk state - forcing loop completion"),v.current=999)}},[e,r]);const U=g.useCallback(C=>{s(B=>B===C?B:(p.current=0,v.current=0,m.current=!1,i(0),C))},[]);g.useEffect(()=>{N.length>0&&!r&&s(N[0])},[N,r]),g.useEffect(()=>{const C=E[r];if(d.current!==null&&(cancelAnimationFrame(d.current),d.current=null),p.current=0,v.current=0,m.current=!1,h.current=0,i(0),!C||C.length<=1)return;const B=k.current[r],K=(B==null?void 0:B.animation_speed)||a||400,Y=(B==null?void 0:B.loop_count)||0,te=(B==null?void 0:B.pause_duration)||0,$=r.toLowerCase().includes("talk"),M=J=>{if(h.current===0&&(h.current=J),m.current){J-b.current>=te&&(m.current=!1,v.current=0,h.current=J),d.current=requestAnimationFrame(M);return}if(J-h.current>=K){h.current=J;const X=(p.current+1)%C.length;X===0?(v.current++,$&&f.current?(p.current=X,i(X)):Y>0&&v.current>=Y?te>0&&(m.current=!0,b.current=J):(p.current=X,i(X))):(p.current=X,i(X))}d.current=requestAnimationFrame(M)};return d.current=requestAnimationFrame(M),()=>{d.current!==null&&(cancelAnimationFrame(d.current),d.current=null)}},[r,E,a]);const j=g.useCallback(()=>{const C=E[r];if(!C||C.length===0){const B=N.find(K=>{var Y;return((Y=E[K])==null?void 0:Y.length)>0});return B?(console.warn(`[useBobAnimation] No images for "${r}", using fallback: ${B}`),E[B][0]):(console.error("[useBobAnimation] No valid images found for any state!"),"")}return C[n]||C[0]},[E,r,N,n]),R=g.useCallback(()=>{const C=A[r];if(!C||C.length===0){const B=N.find(K=>{var Y;return((Y=A[K])==null?void 0:Y.length)>0});return B?A[B][0]:0}return C[n]||C[0]},[A,r,N,n]),T=g.useCallback(()=>{const C=F[r];if(!C||C.length===0){const B=N.find(K=>{var Y;return((Y=F[K])==null?void 0:Y.length)>0});return B?F[B][0]:100}return C[n]||C[0]},[F,r,N,n]);return{animationState:r,setAnimationState:U,getCurrentImage:j,getCurrentOffset:R,getCurrentScale:T,imageUrls:w,availableStates:N,setTalkSpeed:l,manualMode:c,setManualMode:u,isLoading:_}},Ta=()=>{const t=pr(),{data:e=[],isLoading:r}=xs({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}},Ra=({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}%`}})]})})},H={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"},$s={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"}},sn={"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."},Tu="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.",fs={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`},Ca={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"}},lt={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 Aa(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 Oa(t,e){return e?{displayPrice:t*2,unitPriceLabel:`$${t.toFixed(2)} each`}:{displayPrice:t}}function Ge(t){return`$${t.toFixed(2)}`}function Pa(t){if(sn[t])return sn[t];const e=t.toLowerCase();for(const[r,s]of Object.entries(sn))if(e.includes(r.toLowerCase())||r.toLowerCase().includes(e))return s;return Tu}const es=({type:t,value:e,className:r=""})=>{const s=Ca[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]})},Mn=({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:lt.partslotName.fontSize,fontWeight:lt.partslotName.fontWeight,color:H.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(Ru,{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:H.mutedForeground,textAlign:"center"},children:["+ ",t.length-6," more options available"]})]}),Ru=({product:t,onProductClick:e,onAddToCart:r,isRecommended:s=!1})=>{const[n,i]=g.useState(!1),[a,l]=g.useState(!1),c=t.image_url||t.image||(t.sku?fs.productImage(t.sku):null),u=t.brand?fs.brandLogo(t.brand):null,d=t.brand||"Quality Part",h=t.name||"Product",f=t.price??0,p=t.partNumber||t.part_number,v=Aa({name:t.name,partslotDescription:t.partslotDescription,per_car_qty:t.quantity}),{displayPrice:m,unitPriceLabel:b}=Oa(f,v);return o.jsxs("div",{style:{background:H.card,borderRadius:"12px",border:`2px solid ${H.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=`${H.primary}80`,y.currentTarget.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)"},onMouseLeave:y=>{y.currentTarget.style.borderColor=H.border,y.currentTarget.style.boxShadow="none"},children:[t.partslotDescription&&o.jsxs("div",{style:{background:"rgba(0,0,0,0.03)",borderBottom:`1px solid ${H.border}`,padding:"10px 16px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsx("span",{style:{fontSize:lt.partslotName.fontSize,fontWeight:lt.partslotName.fontWeight,color:H.foreground},children:t.partslotDescription}),s&&o.jsx(es,{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 ${H.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:H.foreground,textTransform:"uppercase"},children:d})]}),o.jsx("div",{style:{fontSize:lt.productName.fontSize,fontWeight:lt.productName.fontWeight,color:H.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(es,{type:"fitsVehicle"}),v&&o.jsx(es,{type:"rotorPair"}),t.quantity&&t.quantity>1&&!v&&o.jsx(es,{type:"quantity",value:`Qty: ${t.quantity}`}),p&&o.jsxs("span",{style:{fontSize:"12px",color:H.mutedForeground},children:["#",p]})]})]}),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:lt.priceMain.fontSize,fontWeight:lt.priceMain.fontWeight,color:H.foreground},children:Ge(m)}),b&&o.jsx("div",{style:{fontSize:lt.priceSecondary.fontSize,color:H.mutedForeground},children:b}),o.jsx("div",{style:{fontSize:lt.priceSecondary.fontSize,color:H.mutedForeground},children:"inc GST"})]}),r&&o.jsx("button",{onClick:y=>{y.stopPropagation(),r(t)},style:{background:H.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=H.primaryHover},onMouseLeave:y=>{y.currentTarget.style.background=H.primary},onMouseDown:y=>{y.currentTarget.style.transform="scale(0.98)"},onMouseUp:y=>{y.currentTarget.style.transform="scale(1)"},children:"Add to Cart"})]})]})]})},Ia=({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:f="",onAddToCart:p,onProductClick:v})=>o.jsx("div",{className:f,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:m=>r(m.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((m,b)=>{var y;return o.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:m.role==="user"?"flex-end":"flex-start"},children:o.jsxs("div",{style:{maxWidth:(y=m.suggestedProducts)!=null&&y.length?"100%":"80%",borderRadius:"16px",padding:"12px 16px",fontSize:"14px",backgroundColor:m.role==="user"?"linear-gradient(135deg, rgba(0, 102, 204, 0.9), rgba(0, 73, 153, 1))":"rgba(255,255,255,0.1)",background:m.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:[m.content,m.role==="assistant"&&m.suggestedProducts&&m.suggestedProducts.length>0&&o.jsx(Mn,{products:m.suggestedProducts,title:m.suggestionsTitle,onAddToCart:p,onProductClick:v})]})},b)}),o.jsx("div",{ref:c})]})]})}),Cu=768,Au=1024;function zs(){const[t,e]=g.useState("mobile");return g.useEffect(()=>{const r=()=>{const s=window.innerWidth;s>=Au?e("desktop"):s>=Cu?e("tablet"):e("mobile")};return r(),window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),t}function Wn(){const t=zs();return Ou(t)}function Ou(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 Hs=({currentImage:t,animationState:e,counterOverlayUrl:r,counterHeightPercent:s=15,scale:n=100,position:i="center",verticalOffset:a=0,hasArrived:l=!0})=>{const c=Wn(),d=95*n/100,h=550*n/100,f=()=>{switch(i){case"center":return"50%";case"partial-left":return`${c.partialLeftPosition}%`;case"hidden":return`${c.hiddenPosition}%`;default:return"50%"}},p=()=>i==="center"?"translateX(-50%)":"translateX(0)",v=s+a,m=()=>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:`${v}%`,left:f(),maxHeight:`${100-s-2}%`,transform:p(),width:`${d}%`,maxWidth:`${h}px`,transition:m()+", 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})})]})},Pu={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)"},Iu={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)"},Na={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)"},ss={primary:{color:"rgba(255, 255, 255, 1)",textShadow:"0 1px 3px rgba(0,0,0,0.5)"}},Nu={background:"rgba(255, 255, 255, 0.12)",borderRadius:"20px",border:"1px solid rgba(255, 255, 255, 0.15)"},Pi={background:"rgba(255, 255, 255, 0.15)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"12px"},Bu={width:"4px",height:"4px",borderRadius:"50%",background:"rgba(255, 255, 255, 0.6)",boxShadow:"0 0 8px rgba(255, 255, 255, 0.4)"},Ba=({product:t,isSpotlighted:e=!1,onProductClick:r,onAddToCart:s})=>{const[n,i]=g.useState(!1),[a,l]=g.useState(0),c=()=>{r==null||r(t)},u=v=>{v.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,f=e?Iu:Pu,p=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:{...f,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)":f.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:{...Nu,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",...ss.primary},children:p}),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:{...Pi,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:{...Pi,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:v=>{v.currentTarget.style.transform="scale(1.08) translateY(-2px)",v.currentTarget.style.boxShadow="0 14px 48px rgba(34, 197, 94, 0.5), inset 0 1px 0 rgba(255,255,255,0.4)"},onMouseLeave:v=>{v.currentTarget.style.transform="scale(1) translateY(0)",v.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})})]})},Fu=["SHOE","DRUM"],Lu=["PAD","ROTOR"];function Fa(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 La(t,e){const r=e==="disc"?Fu:Lu;return t.filter(s=>{const n=s.partslotName.toUpperCase();return!r.some(i=>n.includes(i))})}function $a(t){return t.reduce((e,r)=>e+r.displayPrice,0)}const Ii=(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))},$u=(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},Du=({product:t,isSpotlighted:e,spotlightedRef:r,onProductClick:s})=>o.jsx("div",{ref:e?r:void 0,children:o.jsx(Ba,{product:t,isSpotlighted:e,onProductClick:s})}),Ks=({products:t,servicePackages:e,highlightedPartType:r,highlightedProduct:s,onProductClick:n,onPackageSelect:i,isResearching:a,visible:l=!0,counterHeightPercent:c=22,hasVehicle:u=!1,onAddToCart:d,vehicleMakeModel:h,pendingVariants:f,pendingVariantMake:p,pendingVariantModel:v,onVariantSelect:m})=>{const b=h||"Bob's Shelf",y=zs();Wn();const _=g.useRef(null),k=g.useRef({}),w=g.useRef(null),[E,A]=g.useState(null),[F,N]=g.useState({}),[U,j]=g.useState({}),R=g.useMemo(()=>{const P={};return t.forEach(V=>{const Q=V.partslotDescription||"Other Parts";P[Q]||(P[Q]=[]),P[Q].push(V)}),Object.keys(P).sort((V,Q)=>V.localeCompare(Q)).map(V=>({name:V,products:P[V]}))},[t]);g.useEffect(()=>{if(!r)return;const P=setTimeout(()=>{const D=Object.entries(k.current);for(const[V,Q]of D)if(Q&&Ii(V,r)){Q.scrollIntoView({behavior:"smooth",block:"start"});break}},300);return()=>clearTimeout(P)},[r]);const[T,C]=g.useState(0),B=P=>{const D=P.currentTarget,V=D.scrollHeight-D.clientHeight;if(V>0){const Q=D.scrollTop/V;C(Math.max(0,Math.min(1,Q)))}},K=((f==null?void 0:f.length)??0)>0,Y=t.length>0||e.length>0||K,te=a&&!Y,$=Y&&!te,M=l||Y,J=y==="mobile"?92:y==="tablet"?65:70,oe=y==="desktop"?"900px":y==="tablet"?"500px":"100%",X=y==="mobile"?"calc(8px + env(safe-area-inset-top, 4px))":"6px";return o.jsxs(o.Fragment,{children:[Y&&l&&o.jsx("div",{style:{position:"fixed",right:"2px",top:`calc(${T*65+18}%)`,...Bu,opacity:.8,transition:"top 0.1s ease-out",zIndex:100,pointerEvents:"none"}}),o.jsxs("div",{ref:_,onScroll:B,className:`absolute overflow-y-auto overflow-x-hidden flex flex-col gap-3 md:gap-4 transition-all duration-400 ease-out product-scroll ${M?"opacity-100 translate-x-0":"opacity-0 translate-x-12 pointer-events-none"}`,style:{width:`${J}%`,maxWidth:oe,right:"0",left:"auto",top:X,bottom:y==="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:[a&&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:{...ss.primary,fontWeight:700,fontSize:"14px",letterSpacing:"0.025em"},children:a&&Y?"Updating...":b})]}),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"]})]})}),te&&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:{...ss.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"})]})]})}),K&&f&&m&&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 ",p," ",v,"?"]}),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 P=(f||[]).map(V=>[V.engineCode,V.kw?`${V.kw}kW`:null,V.ccDisplay||(V.cc?`${V.cc}cc`:null),V.fuelType].filter(Boolean).join(" · ")||V.displayTitle),D=P.reduce((V,Q)=>(V[Q]=(V[Q]||0)+1,V),{});return(f||[]).map((V,Q)=>{const _e=P[Q],Ae=D[_e]>1&&V.displaySubtitle?V.displaySubtitle:_e;return o.jsx("button",{type:"button",onClick:()=>m(V),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:V.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:Ae})}),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"})})})]})},V.vehicle_id)})})()})]}),!te&&!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:{...ss.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]})]})]})}),$&&e.length>0&&o.jsx("div",{className:"space-y-4",children:e.map(P=>{var Qe,nt;const D=Fa(P),V=U[P.id]||"disc";let Q=(P.preparedTiers||[]).filter(O=>!O.isHidden);D&&(Q=Q.map(O=>{const ee=La(O.products,V);return{...O,products:ee,totalPrice:$a(ee),productCount:ee.length}}));const _e=((Qe=Q.find(O=>O.isRecommended))==null?void 0:Qe.tierName)||((nt=Q[0])==null?void 0:nt.tierName)||"",Te=F[P.id]||_e,Ae=Q.find(O=>O.tierName===Te),Je=Pa(P.title).split(".")[0]+".",qe=E===P.id;return o.jsxs("div",{className:"overflow-hidden transition-all duration-300",style:{background:H.card,borderRadius:"16px",border:`1px solid ${H.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, ${H.primary} 0%, ${H.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:P.title}),P.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"})}),P.estimated_time]})})]})]})}),o.jsxs("div",{className:"px-4 py-3 border-b",style:{borderColor:H.border},children:[o.jsx("p",{className:"text-sm leading-relaxed",style:{color:H.mutedForeground},children:Je}),D&&o.jsxs("div",{className:"mt-2 mb-1",children:[o.jsx("p",{className:"text-[11px] mb-1.5",style:{color:H.mutedForeground},children:"Select your vehicle's rear brake type"}),o.jsxs("div",{className:"flex rounded-xl overflow-hidden border",style:{borderColor:H.border},children:[o.jsx("button",{onClick:()=>j(O=>({...O,[P.id]:"disc"})),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:V==="disc"?H.primary:"transparent",color:V==="disc"?"#FFFFFF":H.mutedForeground},children:"Disc Brakes (Pads + Rotors)"}),o.jsx("button",{onClick:()=>j(O=>({...O,[P.id]:"drum"})),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:V==="drum"?H.primary:"transparent",color:V==="drum"?"#FFFFFF":H.mutedForeground},children:"Drum Brakes (Shoes + Drums)"})]})]})]}),Q.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:H.mutedForeground},children:"Choose Your Value Level"}),o.jsx("div",{className:"grid gap-2",style:{gridTemplateColumns:`repeat(${Math.min(Q.length,4)}, 1fr)`},children:Q.map(O=>{const ee=$s[O.tierName],Oe=O.tierName===Te;return o.jsxs("div",{onClick:()=>N(we=>({...we,[P.id]:O.tierName})),className:"relative rounded-xl text-center transition-all cursor-pointer",style:{padding:Q.length>=4?"6px 4px":"8px",background:O.isRecommended?`${H.primary}10`:Oe?`${H.primary}05`:H.background,border:`2px solid ${O.isRecommended?H.primary:Oe?H.primary+"80":H.border}`},children:[O.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:H.primary,color:"white"},children:"Carfix Value"}),o.jsxs("p",{className:"text-sm font-bold mt-1",style:{color:(ee==null?void 0:ee.textColor)||H.foreground},children:[ee==null?void 0:ee.emoji," ",O.displayName]}),o.jsx("div",{className:"flex flex-col items-center gap-1 mt-2",style:{minHeight:Q.length>=4?"40px":"48px"},children:O.brands.slice(0,1).map((we,me)=>{const ie=`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${we.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:Q.length>=4?"36px":"44px",maxWidth:Q.length>=4?"64px":"80px",boxShadow:"0 2px 8px rgba(0,0,0,0.1)",border:"1px solid #F1F5F9"},children:o.jsx("img",{src:we.imageUrl,alt:we.fullName,className:"w-auto object-contain",style:{height:Q.length>=4?"26px":"32px"},onError:ht=>{const ke=ht.target;ke.src!==ie?ke.src=ie:(ke.style.display="none",ke.parentElement.innerHTML=`<span class="text-[10px] font-semibold text-gray-600 truncate px-1">${we.fullName}</span>`)}})},me)})}),o.jsxs("p",{className:"text-[10px] mt-2",style:{color:H.mutedForeground},children:[O.productCount," ",O.productCount===1?"part":"parts"]}),O.savingsAmount&&O.savingsAmount>0?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-[11px] line-through",style:{color:H.mutedForeground},children:Ge(O.originalTotalPrice)}),o.jsx("p",{className:"text-base font-bold",style:{color:H.success},children:Ge(O.totalPrice)}),o.jsxs("p",{className:"text-[9px] font-semibold px-1.5 py-0.5 rounded-full mt-0.5",style:{background:`${H.success}15`,color:H.success},children:["SAVE ",Ge(O.savingsAmount)," — ",O.bundleDiscountPercentage,"% Bundle Deal"]})]}):o.jsx("p",{className:"text-base font-bold mt-1",style:{color:H.foreground},children:Ge(O.totalPrice)}),o.jsx("p",{className:"text-[10px]",style:{color:H.mutedForeground},children:"inc GST"}),o.jsx("button",{onClick:we=>{we.stopPropagation();const me=O.bundleDiscountPercentage||0,ie=1-me/100,ht=O.products.map(ke=>({id:ke.sku,name:ke.name,brand:ke.brand,price:me>0?Math.round(ke.displayPrice*ie*100)/100:ke.displayPrice,sku:ke.sku,partNumber:ke.partNumber||void 0,image_url:ke.productImageUrl,partslotDescription:ke.partslotName,quantity:1}));d==null||d(ht)},className:"w-full mt-2 py-1.5 rounded-lg text-[10px] font-semibold transition-all",style:{background:O.isRecommended?H.success:"#F1F5F9",color:O.isRecommended?"white":H.success,border:O.isRecommended?"none":"1px solid #E2E8F0",textAlign:"center"},children:"Add"})]},O.tierName)})})]}),o.jsxs("div",{onClick:()=>A(qe?null:P.id),className:"flex items-center justify-center gap-1.5 py-2 cursor-pointer hover:bg-gray-50 transition-colors border-t",style:{borderColor:H.border},children:[o.jsx("span",{className:"text-xs",style:{color:H.mutedForeground},children:qe?"Hide details":"Show details"}),o.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${qe?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",style:{color:H.mutedForeground},children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),qe&&Ae&&o.jsx("div",{className:"px-4 pb-4 border-t animate-in slide-in-from-top-2 duration-200",style:{borderColor:H.border},children:o.jsxs("div",{className:"pt-3",children:[o.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide mb-3",style:{color:H.mutedForeground},children:[Ae.displayName," Tier Products"]}),o.jsx("div",{className:"space-y-2",children:Ae.products.map(O=>o.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg",style:{background:H.background,border:`1px solid ${H.border}`},children:[o.jsx("div",{className:"w-14 h-14 flex-shrink-0 bg-white rounded-lg overflow-hidden flex items-center justify-center",children:O.productImageUrl?o.jsx("img",{src:O.productImageUrl,alt:O.name,className:"w-full h-full object-contain p-1"}):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:H.foreground},children:O.name}),o.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[o.jsx("span",{className:"text-[10px]",style:{color:H.mutedForeground},children:O.brand}),O.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:H.mutedForeground},children:O.partslotName})]}),o.jsxs("div",{className:"text-right flex-shrink-0",children:[o.jsx("p",{className:"text-sm font-bold",style:{color:H.primary},children:Ge(O.displayPrice)}),O.isRotor&&o.jsxs("p",{className:"text-[9px]",style:{color:H.mutedForeground},children:["$",O.price.toFixed(2)," ea"]})]})]},O.sku))})]})})]},P.id)})}),$&&R.map(({name:P,products:D})=>{const V=r&&Ii(P,r);return o.jsxs("section",{ref:Q=>{k.current[P]=Q},className:"transition-all duration-300",style:{background:"transparent",borderRadius:"24px"},children:[o.jsxs("div",{"data-testid":"partslot-header","data-partslot-name":P,className:"px-3 py-2.5 flex items-center justify-between",style:{background:V?"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:V?"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:P})]}),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:D.length})]}),o.jsx("div",{className:"flex flex-col gap-3",children:D.map((Q,_e)=>{const Te=!!(s&&$u(Q,s));return o.jsx("div",{"data-testid":"partslot-product",children:o.jsx(Du,{product:Q,isSpotlighted:Te,spotlightedRef:w,onProductClick:n,viewportSize:y})},`${Q.id}-${_e}`)})})]},P)}),o.jsx("div",{className:"h-4"})]})]})},qn=({onTranscript:t,onSpeechEnd:e,language:r="en-NZ",mode:s="toggle"}={})=>{const[n,i]=g.useState(!1),[a,l]=g.useState(""),[c,u]=g.useState(""),[d,h]=g.useState(null),[f,p]=g.useState(!1),v=g.useRef(null),m=g.useRef(""),b=g.useRef(t),y=g.useRef(e),_=g.useRef(null),k=15e3;g.useEffect(()=>{b.current=t,y.current=e},[t,e]),g.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)"),p(!1);return}const F=window.SpeechRecognition||window.webkitSpeechRecognition;if(F){p(!0);const N=new F;N.continuous=s==="ptt",N.interimResults=!0,N.lang=r,N.maxAlternatives=1,N.onstart=()=>{i(!0),h(null)},N.onresult=U=>{let j="",R="";for(let T=U.resultIndex;T<U.results.length;T++){const C=U.results[T][0].transcript;U.results[T].isFinal?R+=C:j+=C}R&&(m.current=R,l(R),b.current&&b.current(R)),u(j)},N.onerror=U=>{switch(i(!1),U.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.")}},N.onend=()=>{_.current&&(clearTimeout(_.current),_.current=null),i(!1),u(""),m.current&&y.current&&y.current(m.current),m.current=""},v.current=N}return()=>{v.current&&v.current.stop()}},[r,s]);const w=()=>{v.current&&!n&&(l(""),u(""),h(null),_.current=setTimeout(()=>{console.warn("[SpeechRecognition] Safety timeout - forcing stop after 15s"),v.current&&v.current.abort(),i(!1),u("")},k),v.current.start())},E=()=>{_.current&&(clearTimeout(_.current),_.current=null),v.current&&n&&v.current.stop()};return{isListening:n,transcript:a,interimTranscript:c,error:d,isSupported:f,startListening:w,stopListening:E,toggleListening:()=>{n?E():w()}}},Da=({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:f,onProductClick:p,counterHeightPercent:v=22})=>{var X;const[m,b]=g.useState(!1),y=g.useRef(null),_=g.useRef(!1),{bottomOffset:k,zIndexBase:w}=Un(),{isListening:E,interimTranscript:A,error:F,isSupported:N,startListening:U,stopListening:j}=qn({onTranscript:P=>r(P),language:"en-NZ",mode:"ptt"});g.useEffect(()=>{A&&r(A)},[A,r]);const R=g.useCallback(P=>{P.preventDefault(),!(s||_.current)&&(_.current=!0,navigator.vibrate&&navigator.vibrate(30),U())},[s,U]),T=g.useCallback(()=>{_.current&&(_.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),j(),setTimeout(()=>{n()},150))},[j,n]),C=[...t].reverse().find(P=>P.role==="assistant"),B=((X=C==null?void 0:C.suggestedProducts)==null?void 0:X.length)||0,K=C!=null&&C.content?C.content.length>50?C.content.slice(0,50)+"...":C.content:"Ask Bob about car parts...",Y=B>0?` (${B} products)`:"",te={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)"}},$=h?"speaking":s?"processing":E?"listening":"idle",J={idle:te.idle,listening:te.active,processing:te.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)"}}[$],oe={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:"fixed",bottom:k,left:0,right:0,...Na,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:m?"55vh":"90px",zIndex:w+80,paddingBottom:"env(safe-area-inset-bottom, 8px)"},children:[o.jsx("button",{onClick:()=>b(!m),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:w+90,cursor:"pointer",minHeight:"unset",minWidth:"unset"},"aria-label":m?"Collapse chat":"Expand chat",children:m?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"})})}),!m&&o.jsx("div",{onClick:()=>b(!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:[K,Y&&o.jsx("span",{style:{color:"rgba(255,200,0,0.9)",fontWeight:600},children:Y})]})}),m&&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((P,D)=>{var V;return o.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:P.role==="user"?"flex-end":"flex-start"},children:o.jsxs("div",{style:{maxWidth:(V=P.suggestedProducts)!=null&&V.length?"100%":"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:P.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:[P.content,P.role==="assistant"&&P.suggestedProducts&&P.suggestedProducts.length>0&&o.jsx(Mn,{products:P.suggestedProducts,title:P.suggestionsTitle,onAddToCart:f,onProductClick:p})]})},D)}),o.jsx("div",{ref:c})]}),N&&o.jsxs("div",{style:{display:"flex",justifyContent:"center",padding:"12px 16px 8px 16px",position:"relative"},children:[$==="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"}})]}),$!=="listening"&&oe[$]&&o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:oe[$].border,transform:"translate(-50%, -50%)",animation:oe[$].animation,pointerEvents:"none"}}),o.jsx("button",{onTouchStart:R,onTouchEnd:T,onTouchCancel:T,onMouseDown:R,onMouseUp:T,onMouseLeave:T,onClick:E?T:void 0,disabled:$==="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:$==="processing"?"not-allowed":"pointer",opacity:$==="processing"?.6:1,transform:$==="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:J.backdropFilter,WebkitBackdropFilter:J.WebkitBackdropFilter,"--bob-ptt-bg":J.background,"--bob-ptt-shadow":J.boxShadow,"--bob-ptt-border":J.border,"--bob-ptt-radius":"32px"},title:"Hold to talk",children:o.jsx("span",{style:{fontSize:"22px",fontWeight:800,letterSpacing:"0.15em",...ss.primary,textTransform:"uppercase",fontFamily:"system-ui, -apple-system, sans-serif"},children:$==="listening"?"LISTENING":$==="processing"?"THINKING":$==="speaking"?"PLAYING":"TALK"})})]}),o.jsxs("div",{style:{padding:"4px 12px 8px 12px",borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:[F&&o.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:F}),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:P=>r(P.target.value),onKeyPress:i,onFocus:a,onBlur:l,placeholder:"Message Bob...",disabled:$!=="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:$!=="idle"?0:1,transition:"opacity 0.15s ease"}}),$!=="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:[$==="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..."})]}),$==="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."})]}),$==="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((P,D)=>o.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${P}s infinite`}},D))}),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"})]})]})]})]})]})]})]})},Ua=({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:f,chatEndRef:p,isMuted:v,onToggleMute:m,isSpeaking:b,products:y,servicePackages:_,highlightedPartType:k,highlightedProduct:w,onProductClick:E,onPackageSelect:A,isResearching:F,vehicle:N,onChangeVehicle:U,pendingVariants:j,pendingVariantMake:R,pendingVariantModel:T,onVariantSelect:C,bobOffset:B=0,bobScale:K=100,embedded:Y=!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=zs(),[$,M]=g.useState("center"),[J,oe]=g.useState("hidden"),X=y.length>0||_.length>0,P=((j==null?void 0:j.length)??0)>0,D=X||P,_e=(()=>{switch(te){case"desktop":return 70;case"tablet":return 80;case"mobile":return 140;default:return 140}})()*K/100;g.useEffect(()=>{if(F&&J!=="loading"&&J!=="visible")oe("loading"),$==="center"&&M("partial-left");else if(D&&J!=="visible")if($==="center"){M("partial-left"),oe("transitioning");const Ae=setTimeout(()=>{oe("visible")},400);return()=>clearTimeout(Ae)}else oe("visible");else!D&&!F&&J!=="hidden"&&(oe("hidden"),M("center"))},[D,F,J,$]);const Te=J!=="hidden";return o.jsxs("div",{className:Y?"absolute inset-0 overflow-hidden":"fixed inset-0 overflow-hidden",style:{height:Y?"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(Hs,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:_e,position:$,verticalOffset:B}),o.jsx(Ks,{products:y,servicePackages:_,highlightedPartType:k,highlightedProduct:w,onProductClick:E,onPackageSelect:A,isResearching:F,visible:Te,counterHeightPercent:n,hasVehicle:!!N,pendingVariants:j,pendingVariantMake:R,pendingVariantModel:T,onVariantSelect:C}),o.jsx(Da,{messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:f,chatEndRef:p,isMuted:v,onToggleMute:m,isSpeaking:b,onAddToCart:E,onProductClick:E,counterHeightPercent:n})]})},Ma=({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,counterHeightPercent:f=22})=>{const[p,v]=g.useState(!1),m=g.useRef(null),b=g.useRef(!1),{bottomOffset:y,zIndexBase:_}=Un(),{isListening:k,interimTranscript:w,error:E,isSupported:A,startListening:F,stopListening:N}=qn({onTranscript:$=>r($),language:"en-NZ",mode:"ptt"});g.useEffect(()=>{w&&r(w)},[w,r]);const U=g.useCallback($=>{$.preventDefault(),!(s||b.current)&&(b.current=!0,navigator.vibrate&&navigator.vibrate(30),F())},[s,F]),j=g.useCallback(()=>{b.current&&(b.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),N(),setTimeout(()=>{n()},150))},[N,n]),R=[...t].reverse().find($=>$.role==="assistant"),T=R!=null&&R.content?R.content.length>50?R.content.slice(0,50)+"...":R.content:"Ask Bob about car parts...",C={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)"}},B=h?"speaking":s?"processing":k?"listening":"idle",Y={idle:C.idle,listening:C.active,processing:C.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)"}}[B],te={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:m,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",...Na,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:p?"55%":"110px",overflow:"visible",zIndex:_+30,paddingBottom:"calc(8px + env(safe-area-inset-bottom, 0px))",pointerEvents:"none"},children:[o.jsx("button",{onClick:()=>v(!p),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:_+40,cursor:"pointer",minHeight:"32px",minWidth:"32px",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto"},"aria-label":p?"Collapse chat":"Expand chat",children:p?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"})})}),!p&&o.jsx("div",{onClick:()=>v(!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:T})}),p&&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(($,M)=>o.jsx("div",{style:{display:"flex",justifyContent:$.role==="user"?"flex-end":"flex-start"},children:o.jsx("div",{style:{maxWidth:"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})},M)),o.jsx("div",{ref:c})]}),o.jsxs("div",{style:{padding:p?"8px 12px 4px 12px":"4px 12px 4px 12px",borderTop:p?"1px solid rgba(255, 255, 255, 0.15)":"none",pointerEvents:"auto"},children:[E&&o.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:E}),o.jsxs("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[d&&p&&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:$=>r($.target.value),onKeyPress:i,onFocus:a,onBlur:l,placeholder:"Message Bob...",disabled:B!=="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:B!=="idle"?0:1,transition:"opacity 0.15s ease"}}),B!=="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:[B==="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..."})]}),B==="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."})]}),B==="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(($,M)=>o.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${$}s infinite`}},M))}),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"})]})]})]})]}),A&&o.jsxs("div",{style:{position:"relative",marginLeft:"4px"},children:[B==="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"}})]}),B!=="listening"&&te[B]&&o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:te[B].border,transform:"translate(-50%, -50%)",animation:te[B].animation,pointerEvents:"none"}}),o.jsxs("button",{onTouchStart:U,onTouchEnd:j,onTouchCancel:j,onMouseDown:U,onMouseUp:j,onMouseLeave:j,disabled:B==="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:B==="processing"?"not-allowed":"pointer",opacity:B==="processing"?.6:1,transform:B==="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:_+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"})}),B==="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"}})]})]})]})]})]})},Uu=({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"})})]})},Wa=({package:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{var m;const[n,i]=g.useState(!1),[a,l]=g.useState("disc"),c=g.useMemo(()=>Fa(t),[t.id,t.title]),u=g.useMemo(()=>{if(!t.preparedTiers||t.preparedTiers.length===0)return[];const b=t.preparedTiers.filter(y=>!y.isHidden);return c?b.map(y=>{const _=La(y.products,a);return{...y,products:_,totalPrice:$a(_),productCount:_.length}}):b},[t.preparedTiers,c,a]),d=u.length>0,h=b=>{const y=b.bundleDiscountPercentage||0;if(y>0){const _=1-y/100,k=b.products.map(w=>({...w,displayPrice:Math.round(w.displayPrice*_*100)/100}));r==null||r(k)}else r==null||r(b.products)},f=b=>b===2?"grid-cols-2":b===3?"grid-cols-3":"grid-cols-2",p=Pa(t.title),v=((m=u[0])==null?void 0:m.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:p}),c&&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:()=>l("disc"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:a==="disc"?H.primary:"transparent",color:a==="disc"?"#FFFFFF":"#64748B"},children:"Disc Brakes (Pads + Rotors)"}),o.jsx("button",{onClick:()=>l("drum"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:a==="drum"?H.primary:"transparent",color:a==="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:d?o.jsx("div",{className:`grid ${f(u.length)} gap-3`,children:u.map(b=>{const y=$s[b.tierName];return o.jsxs("div",{className:"relative rounded-2xl overflow-hidden bg-white shadow-md flex flex-col",style:{border:b.isRecommended?"2px solid #0052CC":"1px solid #E2E8F0"},children:[b.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:H.primary},children:"★ CARFIX VALUE"}),o.jsxs("div",{className:`p-3 flex-1 flex flex-col ${b.isRecommended?"pt-7":""}`,children:[o.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[o.jsx("span",{className:"text-lg",children:y==null?void 0:y.emoji}),o.jsxs("div",{children:[o.jsx("span",{className:"font-bold text-sm block",style:{color:(y==null?void 0:y.textColor)||H.foreground},children:b.displayName}),o.jsx("span",{className:"text-[10px] text-[#64748B] hidden md:block",children:b.description||(y==null?void 0:y.description)})]})]}),o.jsx("div",{className:"flex items-center gap-1.5 mb-3 min-h-[42px] flex-wrap",children:b.brands.slice(0,3).map(_=>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:_.imageUrl,alt:_.fullName,className:"h-6 w-auto object-contain",onError:k=>{const w=k.target,E=`${fs.storageBase}/brand_images/${_.fullName.replace(/\s+/g,"")}.jpg`;if(w.src!==E)w.src=E;else{const A=w.parentElement;A&&(A.innerHTML=`<span class="text-[10px] font-medium text-slate-700 px-1 truncate max-w-[60px]">${_.name}</span>`)}}})},_.name))}),o.jsxs("p",{className:"text-xs text-[#64748B] hidden md:block mb-2",children:[b.productCount," part",b.productCount!==1?"s":""," included"]}),o.jsx("div",{className:"mt-auto",children:b.savingsAmount&&b.savingsAmount>0?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-xs line-through text-[#94A3B8]",children:Ge(b.originalTotalPrice)}),o.jsx("p",{className:"text-xl font-bold",style:{color:"#22C55E"},children:Ge(b.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 ",Ge(b.savingsAmount)," — ",b.bundleDiscountPercentage,"% Bundle Deal"]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-xl font-bold",style:{color:b.isRecommended?"#0052CC":"#0F172A"},children:Ge(b.totalPrice)}),o.jsx("p",{className:"text-[10px] text-[#64748B] hidden md:block",children:"inc GST"})]})}),o.jsx("button",{onClick:()=>h(b),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 ${b.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"})]})]},b.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"})]})}),d&&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:[v," product",v!==1?"s":""]})]}),n&&o.jsx("div",{className:"mt-3 space-y-4 bg-white rounded-xl border border-[#E2E8F0] p-3",children:u.map(b=>{if(b.products.length===0)return null;const y=$s[b.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:y==null?void 0:y.emoji}),o.jsx("span",{className:"font-semibold text-sm",style:{color:y==null?void 0:y.textColor},children:b.displayName}),o.jsxs("span",{className:"text-xs text-[#64748B]",children:["(",b.products.length," parts)"]})]}),o.jsx("div",{className:"space-y-2",children:b.products.map((_,k)=>{var A;const w=(A=t.carfixValueProducts)==null?void 0:A.includes(_.sku),E=_.unitPrice??_.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(_.sku),children:[o.jsx("div",{className:"w-14 h-14 flex-shrink-0 rounded-lg bg-white overflow-hidden border border-[#E2E8F0]",children:o.jsx("img",{src:_.productImageUrl||fs.productImage(_.sku),alt:_.name,className:"w-full h-full object-contain p-1.5",onError:F=>{F.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:_.brandFullName||_.brand}),w&&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"}),_.isMultiQty&&_.perCarQty>1&&o.jsxs("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#F0FDF4",color:"#15803D"},children:["×",_.perCarQty]}),_.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:_.name})]}),o.jsxs("div",{className:"text-right flex-shrink-0",children:[o.jsx("p",{className:"text-sm font-bold text-[#0F172A]",children:Ge(_.displayPrice)}),_.isMultiQty&&_.perCarQty>1&&o.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[_.perCarQty,"× ",Ge(E)," each"]}),_.isRotor&&!_.isMultiQty&&o.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[Ge(E)," each"]})]})]},`${_.sku}-${k}`)})})]},b.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,"%"]})})})]})]})},qa=({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:f,chatEndRef:p,isMuted:v,onToggleMute:m,isSpeaking:b,products:y,servicePackages:_,highlightedPartType:k,highlightedProduct:w,onProductClick:E,onPackageSelect:A,isResearching:F,onAddToCart:N,onNavigateToProductPage:U,vehicle:j,onChangeVehicle:R,pendingVariants:T,pendingVariantMake:C,pendingVariantModel:B,onVariantSelect:K,bobOffset:Y=0,bobScale:te=100})=>{const[$,M]=g.useState("center"),[J,oe]=g.useState("hidden"),[X,P]=g.useState("products"),[D,V]=g.useState(null),[Q,_e]=g.useState(null),Te=y.length>0||_.length>0,Ae=((T==null?void 0:T.length)??0)>0,Be=Te||Ae,Qe=(X==="productDetail"?70:$==="center"&&!Be?140:98)*te/100;g.useEffect(()=>{if(F&&J!=="loading"&&J!=="visible")oe("loading"),$==="center"&&M("partial-left");else if(Be&&J!=="visible")if($==="center"){M("partial-left"),oe("transitioning");const me=setTimeout(()=>{oe("visible")},400);return()=>clearTimeout(me)}else oe("visible");else!Be&&!F&&J!=="hidden"&&(oe("hidden"),M("center"))},[Be,F,J,$]);const nt=me=>{if(U){U(me),E==null||E(me);return}V(me),P("productDetail"),E==null||E(me)},O=()=>{V(null),_e(null),P("products")},ee=me=>{console.log("[ContainedMobileBobLayout] Package selected:",me.title),_e(me),P("packageDetail"),A==null||A(me)},Oe=J!=="hidden"&&X==="products",we=J!=="hidden";return o.jsxs("div",{className:"absolute inset-0",style:{overflow:"clip",isolation:"isolate"},onContextMenu:me=>me.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:we?"blur(var(--bob-blur-intensity, 0px)) brightness(0.95)":"none",transform:we?"scale(1.02)":"scale(1)",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"}}),o.jsx(Hs,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:Qe,position:$,verticalOffset:Y}),o.jsx(Ks,{products:y,servicePackages:_,highlightedPartType:k,highlightedProduct:w,onProductClick:nt,onPackageSelect:ee,isResearching:F,visible:Oe,counterHeightPercent:n,hasVehicle:!!j,vehicleMakeModel:j?`${j.make||""} ${j.model||""}`.trim():void 0,pendingVariants:T,pendingVariantMake:C,pendingVariantModel:B,onVariantSelect:K}),X==="productDetail"&&D&&o.jsx(Uu,{product:D,onBack:O,onAddToCart:N,onNavigateToProductPage:U}),X==="packageDetail"&&Q&&o.jsx(Wa,{package:Q,onBack:O,onNavigateToProductPage:me=>{const ie=y.find(ht=>ht.sku===me);ie&&U&&U(ie)}}),X==="products"&&o.jsx(Ma,{messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:f,chatEndRef:p,isMuted:v,onToggleMute:m,isSpeaking:b,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})=>{var Qe,nt;const{callbacks:f}=jt(),[p,v]=g.useState(!1),{animationState:m,setAnimationState:b,getCurrentImage:y,getCurrentOffset:_,getCurrentScale:k,availableStates:w}=ja({isSpeaking:p}),{activeBackdrop:E}=Ta(),[A,F]=g.useState([]),[N,U]=g.useState([]),[j,R]=g.useState(null),[T,C]=g.useState(null),[B,K]=g.useState(!1),[Y,te]=g.useState([]),[$,M]=g.useState(""),[J,oe]=g.useState(""),X=g.useRef(null),P=g.useRef(null);g.useEffect(()=>{X.current=O=>{if(K(!1),!O||O.length===0){console.log("[Bob] Clearing products (empty array received)"),F([]);return}const ee=O[0];console.log("[Bob] First part raw keys:",Object.keys(ee));const Oe=O.map((ie,ht)=>{const ke=ie.Brand||ie.brand||"";return{id:ie.SKU||ie.sku||`part-${ht}`,name:ie["Part Product Type"]||ie.partslot_description||ie.name||"Unknown Part",brand:ke,price:ie["Metro Retail Price"]||ie.price||0,sku:ie.SKU||ie.sku,partNumber:ie["Part Number"]||ie.part_number||null,partslotDescription:ie["Part Product Type"]||ie.partslot_description||ie.partslotDescription||ie.part_type||ie.category||"General Parts",image_url:ie.image_url||(ie.SKU||ie.sku?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/product_images/${ie.SKU||ie.sku}.jpg`:void 0),webDescription:ie["Web Part Description"]||ie.web_description||null,brandDescription:ie["Brand Description"]||ie.brand_description||null,perCarQty:ie["Per Car Qty"]||ie.per_car_qty||1,volume:ie.volume||null,viscosity:ie.viscosity||null,brandImageUrl:ke?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${ke.replace(/\s+/g,"")}.jpg`:void 0}}),we=new Set,me=Oe.filter(ie=>!ie.sku||we.has(ie.sku)?!1:(we.add(ie.sku),!0));console.log("[Bob] Products mapped:",Oe.length,"-> deduped:",me.length),F(me)},P.current=O=>{if(!O||O.length===0){console.log("[Bob] Clearing service packages (empty array received)"),U([]);return}console.log("[Bob] Service packages received via stable ref:",O.length),U(O)}},[]);const D=Sa({setAnimationState:b,manualMode:!1,onReadyToSpeak:()=>{console.log("[BobWidget] Ready to speak")},onStreamComplete:()=>{b(w.find(O=>O.includes("idle"))||"idle")},onResearchStart:()=>{K(!0),te([]),M(""),oe("")},onVariantSelectionRequired:(O,ee,Oe)=>{K(!1),te(O),M(ee),oe(Oe)},onHighlightPart:O=>{R(O),setTimeout(()=>R(null),8e3)},onHighlightProduct:O=>{C(O),setTimeout(()=>C(null),8e3)},onAutoFetchComplete:()=>{K(!1)}});g.useEffect(()=>{D.identifiedVehicle&&(te([]),M(""),oe(""))},[(Qe=D.identifiedVehicle)==null?void 0:Qe.vehicle_id,(nt=D.identifiedVehicle)==null?void 0:nt.id]);const V=O=>{te([]),D.setInput(`Option ${O.optionNumber}`),setTimeout(()=>{D.handleSend()},80)};g.useEffect(()=>{v(D.isSpeaking)},[D.isSpeaking]),g.useEffect(()=>{const O=f.onPartsFound,ee=f.onServicePackagesFound;return f.onPartsFound=Oe=>{var we;(we=X.current)==null||we.call(X,Oe),O==null||O(Oe)},f.onServicePackagesFound=Oe=>{var we;(we=P.current)==null||we.call(P,Oe),ee==null||ee(Oe)},()=>{f.onPartsFound=O,f.onServicePackagesFound=ee}},[f]);const Q=n||(E==null?void 0:E.image_url),_e=i||(E==null?void 0:E.counter_overlay_url)||void 0,Te=a||(E==null?void 0:E.counter_height_percent)||12,Ae=y()||l||"",Be=_(),Je=k();if(t==="mobile"||t==="fullscreen")return o.jsx(Ua,{currentImage:Ae,animationState:m,backdropUrl:Q,counterOverlayUrl:_e,counterHeightPercent:Te,bobOffset:Be,bobScale:Je,embedded:h,messages:D.messages,input:D.input,setInput:D.setInput,isLoading:D.isLoading,onSend:D.handleSend,onKeyPress:D.handleKeyPress,onInputFocus:D.handleInputFocus,onInputBlur:D.handleInputBlur,chatEndRef:D.chatEndRef,isMuted:D.isMuted,onToggleMute:D.toggleMute,isSpeaking:D.isSpeaking,products:A,servicePackages:N,highlightedPartType:j,highlightedProduct:T,onAddToCart:O=>{var ee;return(ee=f.onAddToCart)==null?void 0:ee.call(f,{product_id:O.id,product_name:O.name,quantity:1,unit_price:O.price,sku:O.sku,brand:O.brand})},onNavigateToProductPage:O=>{var ee;return(ee=f.onNavigateToProductPage)==null?void 0:ee.call(f,O)},onPackageSelect:O=>console.log("[BobWidget] Package selected:",O),isResearching:B,vehicle:D.identifiedVehicle,pendingVariants:Y,pendingVariantMake:$,pendingVariantModel:J,onVariantSelect:V});if(t==="inline"&&r)return o.jsx("div",{className:`relative w-full h-full ${s}`,children:o.jsx(qa,{currentImage:Ae,animationState:m,backdropUrl:Q,counterOverlayUrl:_e,counterHeightPercent:Te,bobOffset:Be,bobScale:Je,messages:D.messages,input:D.input,setInput:D.setInput,isLoading:D.isLoading,onSend:D.handleSend,onKeyPress:D.handleKeyPress,onInputFocus:D.handleInputFocus,onInputBlur:D.handleInputBlur,chatEndRef:D.chatEndRef,isMuted:D.isMuted,onToggleMute:D.toggleMute,isSpeaking:D.isSpeaking,products:A,servicePackages:N,highlightedPartType:j,highlightedProduct:T,onAddToCart:O=>{var ee;return(ee=f.onAddToCart)==null?void 0:ee.call(f,{product_id:O.id,product_name:O.name,quantity:1,unit_price:O.price,sku:O.sku,brand:O.brand})},onNavigateToProductPage:O=>{var ee;return(ee=f.onNavigateToProductPage)==null?void 0:ee.call(f,O)},onPackageSelect:O=>console.log("[BobWidget] Package selected:",O),isResearching:B,vehicle:D.identifiedVehicle,pendingVariants:Y,pendingVariantMake:$,pendingVariantModel:J,onVariantSelect:V})});const qe={inline:"",floating:"fixed bottom-4 right-4 w-96 z-50 shadow-2xl rounded-lg overflow-hidden"};return o.jsxs("div",{className:`${qe[t]||""} ${s}`,children:[Ae&&o.jsx(Ra,{currentImage:Ae,animationState:m,backdropUrl:Q,counterOverlayUrl:_e,counterHeightPercent:Te,verticalOffset:Be,scale:Je}),r&&o.jsx(Ia,{messages:D.messages,input:D.input,setInput:D.setInput,isLoading:D.isLoading,onSend:D.handleSend,onKeyPress:D.handleKeyPress,onInputFocus:D.handleInputFocus,onInputBlur:D.handleInputBlur,chatEndRef:D.chatEndRef,isMuted:D.isMuted,onToggleMute:D.toggleMute,isSpeaking:D.isSpeaking})]})},Mu=({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:f,scale:p,ga4Config:v,analyticsEnabled:m=!0,bottomOffset:b=0,zIndexBase:y=50,embedded:_=!1})=>(g.useEffect(()=>{console.log("[BobWidget] Initialized",{version:St,variant:n,bottomOffset:b,zIndexBase:y,bobConfigUrl:t.supabaseUrl,hostApiBaseUrl:e.baseUrl,analyticsEnabled:m})},[n,b,y,t.supabaseUrl,e.baseUrl,m]),o.jsx("div",{className:"bob-widget-root",style:{width:"100%",height:"100%"},children:o.jsx(Dn,{bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,ga4Config:v,analyticsEnabled:m,bottomOffset:b,zIndexBase:y,children:o.jsx(zn,{variant:n,initialState:i,showChat:a,className:l,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:h,verticalOffset:f,scale:p,embedded:_})})}));function Wu(t){return t<640?"mobile":t<1024?"tablet":"desktop"}function qu(){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 za=({partnerConfig:t,sessionToken:e})=>{const[r,s]=g.useState(null),[n,i]=g.useState([]),[a,l]=g.useState(!1);if(g.useEffect(()=>{const u=()=>{var f;const d=window.innerWidth,h=window.innerHeight;s({viewport:{width:d,height:h,deviceType:Wu(d)},origin:window.location.origin,originAllowed:((f=t==null?void 0:t.allowed_origins)==null?void 0:f.some(p=>p===window.location.origin||p.includes("*")))??!1,userAgent:navigator.userAgent.slice(0,50)+"...",timestamp:new Date().toISOString()}),i(qu())};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",St]})]}),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(Sr,{label:"Viewport",value:`${r.viewport.width}×${r.viewport.height} (${r.viewport.deviceType})`}),o.jsx(Sr,{label:"Origin",value:r.origin}),o.jsx(Sr,{label:"Bottom Offset",value:`${(t==null?void 0:t.default_bottom_offset)??0}px`}),o.jsx(Sr,{label:"Z-Index Base",value:`${(t==null?void 0:t.default_z_index_base)??50}`}),o.jsx(Sr,{label:"Blur",value:`${(t==null?void 0:t.backdrop_blur_intensity)??8}px`}),o.jsx(Sr,{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})]})]})},Sr=({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})]}),Ni="https://gjoguxzstsihhxvdgpto.supabase.co",Bi="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imdqb2d1eHpzdHNpaGh4dmRncHRvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjM5MzgyODEsImV4cCI6MjA3OTUxNDI4MX0.detu4TKB7RjC6l6CrVaPYoi0Hhz2asDt6zxNx1cdzq8";function zu(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 Ha(t){const[e,r]=g.useState(null),[s,n]=g.useState(!0),[i,a]=g.useState(null),[l,c]=g.useState(!1),[u,d]=g.useState(null),h=g.useCallback(async()=>{if(!t){n(!1),a(new Error("Partner code is required"));return}n(!0),a(null);try{const f=mn(Ni,Bi);console.log(`[BobWidget] Loading partner config for: ${t}`);const{data:p,error:v}=await f.from("bob_partners").select("*").eq("partner_code",t).eq("is_active",!0).maybeSingle();if(v)throw new Error(`Failed to load partner config: ${v.message}`);if(!p)throw new Error(`Partner "${t}" not found or inactive`);const m=p,b=typeof window<"u"?window.location.origin:"",y=zu(m.allowed_origins||[],b);!y&&b&&(console.warn(`[BobWidget] Origin "${b}" not in allowed origins for ${t}`),console.warn("[BobWidget] Allowed origins:",m.allowed_origins));const _=mn(m.bob_supabase_url||Ni,m.bob_supabase_key||Bi,{auth:{storageKey:`bobwidget_${m.partner_code.toLowerCase()}`,persistSession:!1,autoRefreshToken:!1}});console.log("[BobWidget] Partner config loaded:",{partner:m.partner_code,displayName:m.display_name,bottomOffset:m.default_bottom_offset,blurIntensity:m.backdrop_blur_intensity,features:m.feature_flags,originAllowed:y}),r(m),c(y),d(_)}catch(f){const p=f instanceof Error?f:new Error("Unknown error loading partner config");console.error("[BobWidget] Partner config error:",p),a(p)}finally{n(!1)}},[t]);return g.useEffect(()=>{h()},[h]),{config:e,isLoading:s,error:i,isOriginAllowed:l,supabaseClient:u,reload:h}}function Ka(t,e,r){return t!=null&&t.feature_flags?t.feature_flags[e]??r:r}const Hu=()=>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:`
|
|
65
|
+
Issued At: ${i.toISOString()}`;if(n&&(v+=`
|
|
66
|
+
Expiration Time: ${n.toISOString()}`),l&&(v+=`
|
|
67
|
+
Not Before: ${l.toISOString()}`),c&&(v+=`
|
|
68
|
+
Request ID: ${c}`),u){let x=`
|
|
69
|
+
Resources:`;for(const S of u){if(!S||typeof S!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${S}`);x+=`
|
|
70
|
+
- ${S}`}v+=x}return`${m}
|
|
71
|
+
${v}`}class Ie 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 Fs extends Ie{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function Xl({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 Ie({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 Ie({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 Ie({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 Ie({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 Ie({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new Ie({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 Ie({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new Ie({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(da(a)){if(i.rp.id!==a)return new Ie({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Ie({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 Ie({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 Ie({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 Ie({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Zl({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 Ie({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new Ie({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(da(s)){if(r.rpId!==s)return new Ie({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Ie({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new Ie({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 Ie({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class ec{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 tc=new ec;function rc(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=Ms(t,["challenge","user","excludeCredentials"]),i=Or(e).buffer,a=Object.assign(Object.assign({},r),{id:Or(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:Or(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return l}function sc(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=Ms(t,["challenge","allowCredentials"]),n=Or(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:Or(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return i}function nc(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:ar(new Uint8Array(t.response.attestationObject)),clientDataJSON:ar(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function ic(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:ar(new Uint8Array(n.authenticatorData)),clientDataJSON:ar(new Uint8Array(n.clientDataJSON)),signature:ar(new Uint8Array(n.signature)),userHandle:n.userHandle?ar(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function da(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function vi(){var t,e;return!!(De()&&"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 ac(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Fs("Browser returned unexpected credential type",e)}:{data:null,error:new Fs("Empty credential response",e)}}catch(e){return{data:null,error:Xl({error:e,options:t})}}}async function oc(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Fs("Browser returned unexpected credential type",e)}:{data:null,error:new Fs("Empty credential response",e)}}catch(e){return{data:null,error:Zl({error:e,options:t})}}}const lc={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},cc={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Ls(...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]=Ls(l,a):s[i]=Ls(a)}else s[i]=a}return s}function uc(t,e){return Ls(lc,t,e||{})}function dc(t,e){return Ls(cc,t,e||{})}class hc{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??tc.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 p=(await this.client.getUser()).data.user,y=((a=p==null?void 0:p.user_metadata)===null||a===void 0?void 0:a.name)||(p==null?void 0:p.email)||(p==null?void 0:p.id)||"User";d.name=`${d.id}:${y}`}}d.displayName||(d.displayName=d.name)}switch(l.webauthn.type){case"create":{const d=uc(l.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:h,error:f}=await ac({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:f}}case"request":{const d=dc(l.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:h,error:f}=await oc(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:f}}}}catch(l){return Y(l)?{data:null,error:l}:{data:null,error:new ir("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 us("rpId is required for WebAuthn authentication")};try{if(!vi())return{data:null,error:new ir("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 Y(a)?{data:null,error:a}:{data:null,error:new ir("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 us("rpId is required for WebAuthn registration")};try{if(!vi())return{data:null,error:new ir("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(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.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 Y(a)?{data:null,error:a}:{data:null,error:new ir("Unexpected error in register",a)}}}}Gl();const fc={url:cl,storageKey:ul,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:dl,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function wi(t,e,r){return await r()}const Er={};class ds{get jwks(){var e,r;return(r=(e=Er[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Er[this.storageKey]=Object.assign(Object.assign({},Er[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Er[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Er[this.storageKey]=Object.assign(Object.assign({},Er[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({},fc),e);if(this.storageKey=i.storageKey,this.instanceID=(r=ds.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,ds.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&De()){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 Hl({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=la(i.fetch),this.lock=i.lock||wi,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&&De()&&(!((s=globalThis==null?void 0:globalThis.navigator)===null||s===void 0)&&s.locks)?this.lock=Vl:this.lock=wi,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 hc(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:oa()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=yi(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=yi(this.memoryStorage)),De()&&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} (${na}) ${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(De()&&(r=El(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),De()&&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),bl(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 Y(r)?this._returnResult({error:r}):this._returnResult({error:new ir("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const i=await se(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:ot}),{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(Y(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:f}=e;let p=null,y=null;this.flowType==="pkce"&&([p,y]=await kr(this.storage,this.storageKey)),i=await se(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f==null?void 0:f.emailRedirectTo,body:{email:d,password:h,data:(r=f==null?void 0:f.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:p,code_challenge_method:y},xform:ot})}else if("phone"in e){const{phone:d,password:h,options:f}=e;i=await se(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:h,data:(s=f==null?void 0:f.data)!==null&&s!==void 0?s:{},channel:(n=f==null?void 0:f.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken}},xform:ot})}else throw new Os("You must provide either an email or phone number and a password");const{data:a,error:l}=i;if(l||!a)return await $e(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 $e(this.storage,`${this.storageKey}-code-verifier`),Y(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 se(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:bi})}else if("phone"in e){const{phone:i,password:a,options:l}=e;r=await se(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:bi})}else throw new Os("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 _r;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(Y(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,f;let p,y;if("message"in e)p=e.message,y=e.signature;else{const{chain:b,wallet:m,statement:v,options:x}=e;let S;if(De())if(typeof m=="object")S=m;else{const B=window;if("ethereum"in B&&typeof B.ethereum=="object"&&"request"in B.ethereum&&typeof B.ethereum.request=="function")S=B.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 m!="object"||!(x!=null&&x.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");S=m}const _=new URL((r=x==null?void 0:x.url)!==null&&r!==void 0?r:window.location.href),C=await S.request({method:"eth_requestAccounts"}).then(B=>B).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!C||C.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const I=ua(C[0]);let O=(s=x==null?void 0:x.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!O){const B=await S.request({method:"eth_chainId"});O=Jl(B)}const E={domain:_.host,address:I,statement:v,uri:_.href,version:"1",chainId:O,nonce:(n=x==null?void 0:x.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(a=(i=x==null?void 0:x.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(l=x==null?void 0:x.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=x==null?void 0:x.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=x==null?void 0:x.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(d=x==null?void 0:x.signInWithEthereum)===null||d===void 0?void 0:d.resources};p=Yl(E),y=await S.request({method:"personal_sign",params:[Ql(p),I]})}try{const{data:b,error:m}=await se(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:y},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:ot});if(m)throw m;if(!b||!b.session||!b.user){const v=new _r;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:m})}catch(b){if(Y(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,f,p;let y,b;if("message"in e)y=e.message,b=e.signature;else{const{chain:m,wallet:v,statement:x,options:S}=e;let _;if(De())if(typeof v=="object")_=v;else{const I=window;if("solana"in I&&typeof I.solana=="object"&&("signIn"in I.solana&&typeof I.solana.signIn=="function"||"signMessage"in I.solana&&typeof I.solana.signMessage=="function"))_=I.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"||!(S!=null&&S.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=v}const C=new URL((r=S==null?void 0:S.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in _&&_.signIn){const I=await _.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},S==null?void 0:S.signInWithSolana),{version:"1",domain:C.host,uri:C.href}),x?{statement:x}:null));let O;if(Array.isArray(I)&&I[0]&&typeof I[0]=="object")O=I[0];else if(I&&typeof I=="object"&&"signedMessage"in I&&"signature"in I)O=I;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in O&&"signature"in O&&(typeof O.signedMessage=="string"||O.signedMessage instanceof Uint8Array)&&O.signature instanceof Uint8Array)y=typeof O.signedMessage=="string"?O.signedMessage:new TextDecoder().decode(O.signedMessage),b=O.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in _)||typeof _.signMessage!="function"||!("publicKey"in _)||typeof _!="object"||!_.publicKey||!("toBase58"in _.publicKey)||typeof _.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");y=[`${C.host} wants you to sign in with your Solana account:`,_.publicKey.toBase58(),...x?["",x,""]:[""],"Version: 1",`URI: ${C.href}`,`Issued At: ${(n=(s=S==null?void 0:S.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=S==null?void 0:S.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${S.signInWithSolana.notBefore}`]:[],...!((a=S==null?void 0:S.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${S.signInWithSolana.expirationTime}`]:[],...!((l=S==null?void 0:S.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${S.signInWithSolana.chainId}`]:[],...!((c=S==null?void 0:S.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${S.signInWithSolana.nonce}`]:[],...!((u=S==null?void 0:S.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${S.signInWithSolana.requestId}`]:[],...!((h=(d=S==null?void 0:S.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||h===void 0)&&h.length?["Resources",...S.signInWithSolana.resources.map(O=>`- ${O}`)]:[]].join(`
|
|
72
|
+
`);const I=await _.signMessage(new TextEncoder().encode(y),"utf8");if(!I||!(I instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");b=I}}try{const{data:m,error:v}=await se(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:y,signature:ar(b)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:ot});if(v)throw v;if(!m||!m.session||!m.user){const x=new _r;return this._returnResult({data:{user:null,session:null},error:x})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:v})}catch(m){if(Y(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async _exchangeCodeForSession(e){const r=await rr(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new ml;const{data:i,error:a}=await se(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:ot});if(await $e(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!i||!i.session||!i.user){const l=new _r;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 $e(this.storage,`${this.storageKey}-code-verifier`),Y(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 se(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:ot}),{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 _r;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(Y(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 kr(this.storage,this.storageKey));const{error:h}=await se(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 se(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 Os("You must provide either an email or phone number.")}catch(l){if(await $e(this.storage,`${this.storageKey}-code-verifier`),Y(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 se(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:ot});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(Y(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 kr(this.storage,this.storageKey));const u=await se(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:Wl});return!((i=u.data)===null||i===void 0)&&i.url&&De()&&!(!((a=e.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await $e(this.storage,`${this.storageKey}-code-verifier`),Y(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 tt;const{error:n}=await se(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(Y(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 se(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 se(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 Os("You must provide either an email or phone number and a type")}catch(r){if(Y(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 rr(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()<en:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await rr(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=sn()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=$l(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 se(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Dt}):await this._useSession(async r=>{var s,n,i;const{data:a,error:l}=r;if(l)throw l;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new tt}:await se(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:Dt})})}catch(r){if(Y(r))return tn(r)&&(await this._removeSession(),await $e(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async s=>{const{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new tt;const a=n.session;let l=null,c=null;this.flowType==="pkce"&&e.email!=null&&([l,c]=await kr(this.storage,this.storageKey));const{data:u,error:d}=await se(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:Dt});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 $e(this.storage,`${this.storageKey}-code-verifier`),Y(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 tt;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:a}=Is(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(Y(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 tt;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(Y(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!De())throw new Ps("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ps(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 ci("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ps("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 ci("No code detected.");const{data:x,error:S}=await this._exchangeCodeForSession(e.code);if(S)throw S;const _=new URL(window.location.href);return _.searchParams.delete("code"),window.history.replaceState(window.history.state,"",_.toString()),{data:{session:x.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 Ps("No session defined in URL");const d=Math.round(Date.now()/1e3),h=parseInt(l);let f=d+h;c&&(f=parseInt(c));const p=f-d;p*1e3<=Rr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);const y=f-h;d-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,f,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,f,d);const{data:b,error:m}=await this._getUser(i);if(m)throw m;const v={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:h,expires_at:f,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(Y(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 rr(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&&!tn(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&&!(gl(l)&&(l.status===404||l.status===401||l.status===403)||tn(l)))return this._returnResult({error:l})}return e!=="others"&&(await this._removeSession(),await $e(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=Sl(),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 kr(this.storage,this.storageKey,!0));try{return await se(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 $e(this.storage,`${this.storageKey}-code-verifier`),Y(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(Y(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:f}=i;if(f)throw f;const p=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 se(this.fetch,"GET",p,{headers:this.headers,jwt:(d=(u=h.session)===null||u===void 0?void 0:u.access_token)!==null&&d!==void 0?d:void 0})});if(n)throw n;return De()&&!(!((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(Y(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 se(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:ot}),{data:f,error:p}=h;return p?this._returnResult({data:{user:null,session:null},error:p}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new _r}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:p}))}catch(n){if(await $e(this.storage,`${this.storageKey}-code-verifier`),Y(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 se(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(Y(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 Rl(async n=>(n>0&&await Tl(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await se(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ot})),(n,i)=>{const a=200*Math.pow(2,n);return i&&rn(i)&&Date.now()+a-s<Rr})}catch(s){if(this._debug(r,"error",s),Y(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),De()&&!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 rr(this.storage,this.storageKey);if(n&&this.userStorage){let a=await rr(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:n.user},await Cr(this.userStorage,this.storageKey+"-user",a)),n.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:sn()}else if(n&&!n.user&&!n.user){const a=await rr(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(n.user=a.user,await $e(this.storage,this.storageKey+"-user"),await Cr(this.storage,this.storageKey,n)):n.user=sn()}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()<en;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${en}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:a}=await this._callRefreshToken(n.refresh_token);a&&(console.error(a),rn(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 tt;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new zs;const{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new tt;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),Y(i)){const a={data:null,error:i};return rn(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 $e(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await Cr(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=pi(n);await Cr(this.storage,this.storageKey,i)}else{const n=pi(r);await Cr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await $e(this.storage,this.storageKey),await $e(this.storage,this.storageKey+"-code-verifier"),await $e(this.storage,this.storageKey+"-user"),this.userStorage&&await $e(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&De()&&(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(),Rr);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)/Rr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Rr}ms, refresh threshold is ${bn} ticks`),n<=bn&&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 ca)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!De()||!(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 kr(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 se(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(Y(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 se(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(Y(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"?nc(e.webauthn.credential_response):ic(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:c}=await se(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(Y(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 se(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:rc(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:sc(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(Y(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:p}=Is(e);let y=null;p.aal&&(y=p.aal);let b=y;const{data:{user:m},error:v}=await this.getUser(e);if(v)return this._returnResult({data:null,error:v});((s=(r=m==null?void 0:m.factors)===null||r===void 0?void 0:r.filter(_=>_.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(b="aal2");const S=p.amr||[];return{data:{currentLevel:y,nextLevel:b,currentAuthenticationMethods:S},error:null}}catch(p){if(Y(p))return this._returnResult({data:null,error:p});throw p}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}=Is(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(p=>p.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(d="aal2");const f=c.amr||[];return{data:{currentLevel:u,nextLevel:d,currentAuthenticationMethods:f},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 se(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 tt})})}catch(r){if(Y(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 tt});const a=await se(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&&De()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(Y(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 tt});const a=await se(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&&De()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(Y(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 se(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 tt})})}catch(e){if(Y(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 se(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 tt})})}catch(r){if(Y(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+fl>n)return s;const{data:i,error:a}=await se(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:p,error:y}=await this.getSession();if(y||!p.session)return this._returnResult({data:null,error:y});s=p.session.access_token}const{header:n,payload:i,signature:a,raw:{header:l,payload:c}}=Is(s);r!=null&&r.allowExpired||Bl(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:p}=await this.getUser(s);if(p)throw p;return{data:{claims:i,header:n,signature:a},error:null}}const d=Fl(n.alg),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,a,_l(`${l}.${c}`)))throw new vn("Invalid JWT signature");return{data:{claims:i,header:n,signature:a},error:null}}catch(s){if(Y(s))return this._returnResult({data:null,error:s});throw s}}}ds.nextInstanceID={};const pc=ds,gc="2.98.0";let es="";typeof Deno<"u"?es="deno":typeof document<"u"?es="web":typeof navigator<"u"&&navigator.product==="ReactNative"?es="react-native":es="node";const bc={"X-Client-Info":`supabase-js-${es}/${gc}`},mc={headers:bc},yc={schema:"public"},vc={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},wc={};function hs(t){"@babel/helpers - typeof";return hs=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},hs(t)}function xc(t,e){if(hs(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(hs(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function _c(t){var e=xc(t,"string");return hs(e)=="symbol"?e:e+""}function kc(t,e,r){return(e=_c(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function xi(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 Oe(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?xi(Object(r),!0).forEach(function(s){kc(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):xi(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const Sc=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ec=()=>Headers,jc=(t,e,r)=>{const s=Sc(r),n=Ec();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,Oe(Oe({},a),{},{headers:u}))}};function Tc(t){return t.endsWith("/")?t:t+"/"}function Rc(t,e){var r,s;const{db:n,auth:i,realtime:a,global:l}=t,{db:c,auth:u,realtime:d,global:h}=e,f={db:Oe(Oe({},c),n),auth:Oe(Oe({},u),i),realtime:Oe(Oe({},d),a),storage:{},global:Oe(Oe(Oe({},h),l),{},{headers:Oe(Oe({},(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?f.accessToken=t.accessToken:delete f.accessToken,f}function Cc(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(Tc(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Ac=class extends pc{constructor(t){super(t)}},Oc=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=Cc(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:yc,realtime:wc,auth:Oe(Oe({},vc),{},{storageKey:a}),global:mc},c=Rc(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=jc(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Oe({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 go(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 ll(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new ao(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 f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Ac({url:this.authUrl.href,headers:Oe(Oe({},f),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(p=>p.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Po(this.realtimeUrl.href,Oe(Oe({},t),{},{params:Oe(Oe({},{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 wn=(t,e,r)=>new Oc(t,e,r);function Pc(){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}Pc()&&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 _s=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(){}},Ic={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},bt,lr,Ui,Nc=(Ui=class{constructor(){te(this,bt,Ic);te(this,lr,!1)}setTimeoutProvider(t){process.env.NODE_ENV!=="production"&&k(this,lr)&&t!==k(this,bt)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:k(this,bt),provider:t}),H(this,bt,t),process.env.NODE_ENV!=="production"&&H(this,lr,!1)}setTimeout(t,e){return process.env.NODE_ENV!=="production"&&H(this,lr,!0),k(this,bt).setTimeout(t,e)}clearTimeout(t){k(this,bt).clearTimeout(t)}setInterval(t,e){return process.env.NODE_ENV!=="production"&&H(this,lr,!0),k(this,bt).setInterval(t,e)}clearInterval(t){k(this,bt).clearInterval(t)}},bt=new WeakMap,lr=new WeakMap,Ui),or=new Nc;function Bc(t){setTimeout(t,0)}var yr=typeof window>"u"||"Deno"in globalThis;function Je(){}function Fc(t,e){return typeof t=="function"?t(e):t}function xn(t){return typeof t=="number"&&t>=0&&t!==1/0}function ha(t,e){return Math.max(t+(e||0)-Date.now(),0)}function Vt(t,e){return typeof t=="function"?t(e):t}function it(t,e){return typeof t=="function"?t(e):t}function _i(t,e){const{type:r="all",exact:s,fetchStatus:n,predicate:i,queryKey:a,stale:l}=t;if(a){if(s){if(e.queryHash!==Dn(a,e.options))return!1}else if(!ps(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 ki(t,e){const{exact:r,status:s,predicate:n,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(r){if(fs(e.options.mutationKey)!==fs(i))return!1}else if(!ps(e.options.mutationKey,i))return!1}return!(s&&e.state.status!==s||n&&!n(e))}function Dn(t,e){return((e==null?void 0:e.queryKeyHashFn)||fs)(t)}function fs(t){return JSON.stringify(t,(e,r)=>Sn(r)?Object.keys(r).sort().reduce((s,n)=>(s[n]=r[n],s),{}):r)}function ps(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(r=>ps(t[r],e[r])):!1}var Lc=Object.prototype.hasOwnProperty;function _n(t,e,r=0){if(t===e)return t;if(r>500)return e;const s=Si(t)&&Si(e);if(!s&&!(Sn(t)&&Sn(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],f=t[h],p=e[h];if(f===p){c[h]=f,(s?d<i:Lc.call(t,h))&&u++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){c[h]=p;continue}const y=_n(f,p,r+1);c[h]=y,y===f&&u++}return i===l&&u===i?t:c}function kn(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 Si(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function Sn(t){if(!Ei(t))return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(!Ei(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function Ei(t){return Object.prototype.toString.call(t)==="[object Object]"}function $c(t){return new Promise(e=>{or.setTimeout(e,t)})}function En(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 _n(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 _n(t,e)}return e}function Dc(t,e,r=0){const s=[...t,e];return r&&s.length>r?s.slice(1):s}function Uc(t,e,r=0){const s=[e,...t];return r&&s.length>r?s.slice(0,-1):s}var $s=Symbol();function fa(t,e){return process.env.NODE_ENV!=="production"&&t.queryFn===$s&&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===$s?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function pa(t,e){return typeof t=="function"?t(...e):!!t}function Mc(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 cr,Ut,Pr,Mi,Wc=(Mi=class extends _s{constructor(){super();te(this,cr);te(this,Ut);te(this,Pr);H(this,Pr,e=>{if(!yr&&window.addEventListener){const r=()=>e();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){k(this,Ut)||this.setEventListener(k(this,Pr))}onUnsubscribe(){var e;this.hasListeners()||((e=k(this,Ut))==null||e.call(this),H(this,Ut,void 0))}setEventListener(e){var r;H(this,Pr,e),(r=k(this,Ut))==null||r.call(this),H(this,Ut,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){k(this,cr)!==e&&(H(this,cr,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(r=>{r(e)})}isFocused(){var e;return typeof k(this,cr)=="boolean"?k(this,cr):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},cr=new WeakMap,Ut=new WeakMap,Pr=new WeakMap,Mi),Un=new Wc;function jn(){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 qc=Bc;function zc(){let t=[],e=0,r=l=>{l()},s=l=>{l()},n=qc;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 Ue=zc(),Ir,Mt,Nr,Wi,Hc=(Wi=class extends _s{constructor(){super();te(this,Ir,!0);te(this,Mt);te(this,Nr);H(this,Nr,e=>{if(!yr&&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(){k(this,Mt)||this.setEventListener(k(this,Nr))}onUnsubscribe(){var e;this.hasListeners()||((e=k(this,Mt))==null||e.call(this),H(this,Mt,void 0))}setEventListener(e){var r;H(this,Nr,e),(r=k(this,Mt))==null||r.call(this),H(this,Mt,e(this.setOnline.bind(this)))}setOnline(e){k(this,Ir)!==e&&(H(this,Ir,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return k(this,Ir)}},Ir=new WeakMap,Mt=new WeakMap,Nr=new WeakMap,Wi),Ds=new Hc;function Kc(t){return Math.min(1e3*2**t,3e4)}function ga(t){return(t??"online")==="online"?Ds.isOnline():!0}var Tn=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function ba(t){let e=!1,r=0,s;const n=jn(),i=()=>n.status!=="pending",a=b=>{var m;if(!i()){const v=new Tn(b);f(v),(m=t.onCancel)==null||m.call(t,v)}},l=()=>{e=!0},c=()=>{e=!1},u=()=>Un.isFocused()&&(t.networkMode==="always"||Ds.isOnline())&&t.canRun(),d=()=>ga(t.networkMode)&&t.canRun(),h=b=>{i()||(s==null||s(),n.resolve(b))},f=b=>{i()||(s==null||s(),n.reject(b))},p=()=>new Promise(b=>{var m;s=v=>{(i()||u())&&b(v)},(m=t.onPause)==null||m.call(t)}).then(()=>{var b;s=void 0,i()||(b=t.onContinue)==null||b.call(t)}),y=()=>{if(i())return;let b;const m=r===0?t.initialPromise:void 0;try{b=m??t.fn()}catch(v){b=Promise.reject(v)}Promise.resolve(b).then(h).catch(v=>{var I;if(i())return;const x=t.retry??(yr?0:3),S=t.retryDelay??Kc,_=typeof S=="function"?S(r,v):S,C=x===!0||typeof x=="number"&&r<x||typeof x=="function"&&x(r,v);if(e||!C){f(v);return}r++,(I=t.onFail)==null||I.call(t,r,v),$c(_).then(()=>u()?void 0:p()).then(()=>{e?f(v):y()})})};return{promise:n,status:()=>n.status,cancel:a,continue:()=>(s==null||s(),n),cancelRetry:l,continueRetry:c,canStart:d,start:()=>(d()?y():p().then(y),n)}}var ur,qi,ma=(qi=class{constructor(){te(this,ur)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),xn(this.gcTime)&&H(this,ur,or.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(yr?1/0:5*60*1e3))}clearGcTimeout(){k(this,ur)&&(or.clearTimeout(k(this,ur)),H(this,ur,void 0))}},ur=new WeakMap,qi),dr,Br,nt,hr,Le,bs,fr,ut,jt,zi,Vc=(zi=class extends ma{constructor(e){super();te(this,ut);te(this,dr);te(this,Br);te(this,nt);te(this,hr);te(this,Le);te(this,bs);te(this,fr);H(this,fr,!1),H(this,bs,e.defaultOptions),this.setOptions(e.options),this.observers=[],H(this,hr,e.client),H(this,nt,k(this,hr).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,H(this,dr,Ti(this.options)),this.state=e.state??k(this,dr),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=k(this,Le))==null?void 0:e.promise}setOptions(e){if(this.options={...k(this,bs),...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const r=Ti(this.options);r.data!==void 0&&(this.setState(ji(r.data,r.dataUpdatedAt)),H(this,dr,r))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&k(this,nt).remove(this)}setData(e,r){const s=En(this.state.data,e,this.options);return fe(this,ut,jt).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,ut,jt).call(this,{type:"setState",state:e,setStateOptions:r})}cancel(e){var s,n;const r=(s=k(this,Le))==null?void 0:s.promise;return(n=k(this,Le))==null||n.cancel(e),r?r.then(Je).catch(Je):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(k(this,dr))}isActive(){return this.observers.some(e=>it(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===$s||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Vt(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:!ha(this.state.dataUpdatedAt,e)}onFocus(){var r;const e=this.observers.find(s=>s.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(r=k(this,Le))==null||r.continue()}onOnline(){var r;const e=this.observers.find(s=>s.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(r=k(this,Le))==null||r.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),k(this,nt).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(r=>r!==e),this.observers.length||(k(this,Le)&&(k(this,fr)?k(this,Le).cancel({revert:!0}):k(this,Le).cancelRetry()),this.scheduleGc()),k(this,nt).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||fe(this,ut,jt).call(this,{type:"invalidate"})}async fetch(e,r){var c,u,d,h,f,p,y,b,m,v,x,S;if(this.state.fetchStatus!=="idle"&&((c=k(this,Le))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(k(this,Le))return k(this,Le).continueRetry(),k(this,Le).promise}if(e&&this.setOptions(e),!this.options.queryFn){const _=this.observers.find(C=>C.options.queryFn);_&&this.setOptions(_.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=_=>{Object.defineProperty(_,"signal",{enumerable:!0,get:()=>(H(this,fr,!0),s.signal)})},i=()=>{const _=fa(this.options,r),I=(()=>{const O={client:k(this,hr),queryKey:this.queryKey,meta:this.meta};return n(O),O})();return H(this,fr,!1),this.options.persister?this.options.persister(_,I,this):_(I)},l=(()=>{const _={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:k(this,hr),state:this.state,fetchFn:i};return n(_),_})();(u=this.options.behavior)==null||u.onFetch(l,this),H(this,Br,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((d=l.fetchOptions)==null?void 0:d.meta))&&fe(this,ut,jt).call(this,{type:"fetch",meta:(h=l.fetchOptions)==null?void 0:h.meta}),H(this,Le,ba({initialPromise:r==null?void 0:r.initialPromise,fn:l.fetchFn,onCancel:_=>{_ instanceof Tn&&_.revert&&this.setState({...k(this,Br),fetchStatus:"idle"}),s.abort()},onFail:(_,C)=>{fe(this,ut,jt).call(this,{type:"failed",failureCount:_,error:C})},onPause:()=>{fe(this,ut,jt).call(this,{type:"pause"})},onContinue:()=>{fe(this,ut,jt).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode,canRun:()=>!0}));try{const _=await k(this,Le).start();if(_===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(_),(p=(f=k(this,nt).config).onSuccess)==null||p.call(f,_,this),(b=(y=k(this,nt).config).onSettled)==null||b.call(y,_,this.state.error,this),_}catch(_){if(_ instanceof Tn){if(_.silent)return k(this,Le).promise;if(_.revert){if(this.state.data===void 0)throw _;return this.state.data}}throw fe(this,ut,jt).call(this,{type:"error",error:_}),(v=(m=k(this,nt).config).onError)==null||v.call(m,_,this),(S=(x=k(this,nt).config).onSettled)==null||S.call(x,this.state.data,_,this),_}finally{this.scheduleGc()}}},dr=new WeakMap,Br=new WeakMap,nt=new WeakMap,hr=new WeakMap,Le=new WeakMap,bs=new WeakMap,fr=new WeakMap,ut=new WeakSet,jt=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,...ya(s.data,this.options),fetchMeta:e.meta??null};case"success":const n={...s,...ji(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return H(this,Br,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),Ue.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),k(this,nt).notify({query:this,type:"updated",action:e})})},zi);function ya(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ga(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function ji(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Ti(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 Ge,pe,ms,Ke,pr,Fr,Rt,Wt,ys,Lr,$r,gr,br,qt,Dr,xe,ts,Rn,Cn,An,On,Pn,In,Nn,va,Hi,Gc=(Hi=class extends _s{constructor(e,r){super();te(this,xe);te(this,Ge);te(this,pe);te(this,ms);te(this,Ke);te(this,pr);te(this,Fr);te(this,Rt);te(this,Wt);te(this,ys);te(this,Lr);te(this,$r);te(this,gr);te(this,br);te(this,qt);te(this,Dr,new Set);this.options=r,H(this,Ge,e),H(this,Wt,null),H(this,Rt,jn()),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(k(this,pe).addObserver(this),Ri(k(this,pe),this.options)?fe(this,xe,ts).call(this):this.updateResult(),fe(this,xe,On).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Bn(k(this,pe),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Bn(k(this,pe),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,fe(this,xe,Pn).call(this),fe(this,xe,In).call(this),k(this,pe).removeObserver(this)}setOptions(e){const r=this.options,s=k(this,pe);if(this.options=k(this,Ge).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof it(this.options.enabled,k(this,pe))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");fe(this,xe,Nn).call(this),k(this,pe).setOptions(this.options),r._defaulted&&!kn(this.options,r)&&k(this,Ge).getQueryCache().notify({type:"observerOptionsUpdated",query:k(this,pe),observer:this});const n=this.hasListeners();n&&Ci(k(this,pe),s,this.options,r)&&fe(this,xe,ts).call(this),this.updateResult(),n&&(k(this,pe)!==s||it(this.options.enabled,k(this,pe))!==it(r.enabled,k(this,pe))||Vt(this.options.staleTime,k(this,pe))!==Vt(r.staleTime,k(this,pe)))&&fe(this,xe,Rn).call(this);const i=fe(this,xe,Cn).call(this);n&&(k(this,pe)!==s||it(this.options.enabled,k(this,pe))!==it(r.enabled,k(this,pe))||i!==k(this,qt))&&fe(this,xe,An).call(this,i)}getOptimisticResult(e){const r=k(this,Ge).getQueryCache().build(k(this,Ge),e),s=this.createResult(r,e);return Qc(this,s)&&(H(this,Ke,s),H(this,Fr,this.options),H(this,pr,k(this,pe).state)),s}getCurrentResult(){return k(this,Ke)}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&&k(this,Rt).status==="pending"&&k(this,Rt).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,n))})}trackProp(e){k(this,Dr).add(e)}getCurrentQuery(){return k(this,pe)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const r=k(this,Ge).defaultQueryOptions(e),s=k(this,Ge).getQueryCache().build(k(this,Ge),r);return s.fetch().then(()=>this.createResult(s,r))}fetch(e){return fe(this,xe,ts).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),k(this,Ke)))}createResult(e,r){var B;const s=k(this,pe),n=this.options,i=k(this,Ke),a=k(this,pr),l=k(this,Fr),u=e!==s?e.state:k(this,ms),{state:d}=e;let h={...d},f=!1,p;if(r._optimisticResults){const j=this.hasListeners(),R=!j&&Ri(e,r),A=j&&Ci(e,s,r,n);(R||A)&&(h={...h,...ya(d.data,e.options)}),r._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:y,errorUpdatedAt:b,status:m}=h;p=h.data;let v=!1;if(r.placeholderData!==void 0&&p===void 0&&m==="pending"){let j;i!=null&&i.isPlaceholderData&&r.placeholderData===(l==null?void 0:l.placeholderData)?(j=i.data,v=!0):j=typeof r.placeholderData=="function"?r.placeholderData((B=k(this,$r))==null?void 0:B.state.data,k(this,$r)):r.placeholderData,j!==void 0&&(m="success",p=En(i==null?void 0:i.data,j,r),f=!0)}if(r.select&&p!==void 0&&!v)if(i&&p===(a==null?void 0:a.data)&&r.select===k(this,ys))p=k(this,Lr);else try{H(this,ys,r.select),p=r.select(p),p=En(i==null?void 0:i.data,p,r),H(this,Lr,p),H(this,Wt,null)}catch(j){H(this,Wt,j)}k(this,Wt)&&(y=k(this,Wt),p=k(this,Lr),b=Date.now(),m="error");const x=h.fetchStatus==="fetching",S=m==="pending",_=m==="error",C=S&&x,I=p!==void 0,E={status:m,fetchStatus:h.fetchStatus,isPending:S,isSuccess:m==="success",isError:_,isInitialLoading:C,isLoading:C,data:p,dataUpdatedAt:h.dataUpdatedAt,error:y,errorUpdatedAt:b,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:x,isRefetching:x&&!S,isLoadingError:_&&!I,isPaused:h.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:_&&I,isStale:Mn(e,r),refetch:this.refetch,promise:k(this,Rt),isEnabled:it(r.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const j=E.data!==void 0,R=E.status==="error"&&!j,A=M=>{R?M.reject(E.error):j&&M.resolve(E.data)},T=()=>{const M=H(this,Rt,E.promise=jn());A(M)},F=k(this,Rt);switch(F.status){case"pending":e.queryHash===s.queryHash&&A(F);break;case"fulfilled":(R||E.data!==F.value)&&T();break;case"rejected":(!R||E.error!==F.reason)&&T();break}}return E}updateResult(){const e=k(this,Ke),r=this.createResult(k(this,pe),this.options);if(H(this,pr,k(this,pe).state),H(this,Fr,this.options),k(this,pr).data!==void 0&&H(this,$r,k(this,pe)),kn(r,e))return;H(this,Ke,r);const s=()=>{if(!e)return!0;const{notifyOnChangeProps:n}=this.options,i=typeof n=="function"?n():n;if(i==="all"||!i&&!k(this,Dr).size)return!0;const a=new Set(i??k(this,Dr));return this.options.throwOnError&&a.add("error"),Object.keys(k(this,Ke)).some(l=>{const c=l;return k(this,Ke)[c]!==e[c]&&a.has(c)})};fe(this,xe,va).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&fe(this,xe,On).call(this)}},Ge=new WeakMap,pe=new WeakMap,ms=new WeakMap,Ke=new WeakMap,pr=new WeakMap,Fr=new WeakMap,Rt=new WeakMap,Wt=new WeakMap,ys=new WeakMap,Lr=new WeakMap,$r=new WeakMap,gr=new WeakMap,br=new WeakMap,qt=new WeakMap,Dr=new WeakMap,xe=new WeakSet,ts=function(e){fe(this,xe,Nn).call(this);let r=k(this,pe).fetch(this.options,e);return e!=null&&e.throwOnError||(r=r.catch(Je)),r},Rn=function(){fe(this,xe,Pn).call(this);const e=Vt(this.options.staleTime,k(this,pe));if(yr||k(this,Ke).isStale||!xn(e))return;const s=ha(k(this,Ke).dataUpdatedAt,e)+1;H(this,gr,or.setTimeout(()=>{k(this,Ke).isStale||this.updateResult()},s))},Cn=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(k(this,pe)):this.options.refetchInterval)??!1},An=function(e){fe(this,xe,In).call(this),H(this,qt,e),!(yr||it(this.options.enabled,k(this,pe))===!1||!xn(k(this,qt))||k(this,qt)===0)&&H(this,br,or.setInterval(()=>{(this.options.refetchIntervalInBackground||Un.isFocused())&&fe(this,xe,ts).call(this)},k(this,qt)))},On=function(){fe(this,xe,Rn).call(this),fe(this,xe,An).call(this,fe(this,xe,Cn).call(this))},Pn=function(){k(this,gr)&&(or.clearTimeout(k(this,gr)),H(this,gr,void 0))},In=function(){k(this,br)&&(or.clearInterval(k(this,br)),H(this,br,void 0))},Nn=function(){const e=k(this,Ge).getQueryCache().build(k(this,Ge),this.options);if(e===k(this,pe))return;const r=k(this,pe);H(this,pe,e),H(this,ms,e.state),this.hasListeners()&&(r==null||r.removeObserver(this),e.addObserver(this))},va=function(e){Ue.batch(()=>{e.listeners&&this.listeners.forEach(r=>{r(k(this,Ke))}),k(this,Ge).getQueryCache().notify({query:k(this,pe),type:"observerResultsUpdated"})})},Hi);function Jc(t,e){return it(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function Ri(t,e){return Jc(t,e)||t.state.data!==void 0&&Bn(t,e,e.refetchOnMount)}function Bn(t,e,r){if(it(e.enabled,t)!==!1&&Vt(e.staleTime,t)!=="static"){const s=typeof r=="function"?r(t):r;return s==="always"||s!==!1&&Mn(t,e)}return!1}function Ci(t,e,r,s){return(t!==e||it(s.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&Mn(t,r)}function Mn(t,e){return it(e.enabled,t)!==!1&&t.isStaleByTime(Vt(e.staleTime,t))}function Qc(t,e){return!kn(t.getCurrentResult(),e)}function Ai(t){return{onFetch:(e,r)=>{var d,h,f,p,y;const s=e.options,n=(f=(h=(d=e.fetchOptions)==null?void 0:d.meta)==null?void 0:h.fetchMore)==null?void 0:f.direction,i=((p=e.state.data)==null?void 0:p.pages)||[],a=((y=e.state.data)==null?void 0:y.pageParams)||[];let l={pages:[],pageParams:[]},c=0;const u=async()=>{let b=!1;const m=S=>{Mc(S,()=>e.signal,()=>b=!0)},v=fa(e.options,e.fetchOptions),x=async(S,_,C)=>{if(b)return Promise.reject();if(_==null&&S.pages.length)return Promise.resolve(S);const O=(()=>{const R={client:e.client,queryKey:e.queryKey,pageParam:_,direction:C?"backward":"forward",meta:e.options.meta};return m(R),R})(),E=await v(O),{maxPages:B}=e.options,j=C?Uc:Dc;return{pages:j(S.pages,E,B),pageParams:j(S.pageParams,_,B)}};if(n&&i.length){const S=n==="backward",_=S?Yc:Oi,C={pages:i,pageParams:a},I=_(s,C);l=await x(C,I,S)}else{const S=t??i.length;do{const _=c===0?a[0]??s.initialPageParam:Oi(s,l);if(c>0&&_==null)break;l=await x(l,_),c++}while(c<S)}return l};e.options.persister?e.fetchFn=()=>{var b,m;return(m=(b=e.options).persister)==null?void 0:m.call(b,u,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r)}:e.fetchFn=u}}}function Oi(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 Yc(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 vs,mt,We,mr,yt,Lt,Ki,Xc=(Ki=class extends ma{constructor(e){super();te(this,yt);te(this,vs);te(this,mt);te(this,We);te(this,mr);H(this,vs,e.client),this.mutationId=e.mutationId,H(this,We,e.mutationCache),H(this,mt,[]),this.state=e.state||Zc(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){k(this,mt).includes(e)||(k(this,mt).push(e),this.clearGcTimeout(),k(this,We).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){H(this,mt,k(this,mt).filter(r=>r!==e)),this.scheduleGc(),k(this,We).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){k(this,mt).length||(this.state.status==="pending"?this.scheduleGc():k(this,We).remove(this))}continue(){var e;return((e=k(this,mr))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var a,l,c,u,d,h,f,p,y,b,m,v,x,S,_,C,I,O;const r=()=>{fe(this,yt,Lt).call(this,{type:"continue"})},s={client:k(this,vs),meta:this.options.meta,mutationKey:this.options.mutationKey};H(this,mr,ba({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(E,B)=>{fe(this,yt,Lt).call(this,{type:"failed",failureCount:E,error:B})},onPause:()=>{fe(this,yt,Lt).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>k(this,We).canRun(this)}));const n=this.state.status==="pending",i=!k(this,mr).canStart();try{if(n)r();else{fe(this,yt,Lt).call(this,{type:"pending",variables:e,isPaused:i}),k(this,We).config.onMutate&&await k(this,We).config.onMutate(e,this,s);const B=await((l=(a=this.options).onMutate)==null?void 0:l.call(a,e,s));B!==this.state.context&&fe(this,yt,Lt).call(this,{type:"pending",context:B,variables:e,isPaused:i})}const E=await k(this,mr).start();return await((u=(c=k(this,We).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((p=(f=k(this,We).config).onSettled)==null?void 0:p.call(f,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,yt,Lt).call(this,{type:"success",data:E}),E}catch(E){try{await((v=(m=k(this,We).config).onError)==null?void 0:v.call(m,E,e,this.state.context,this,s))}catch(B){Promise.reject(B)}try{await((S=(x=this.options).onError)==null?void 0:S.call(x,E,e,this.state.context,s))}catch(B){Promise.reject(B)}try{await((C=(_=k(this,We).config).onSettled)==null?void 0:C.call(_,void 0,E,this.state.variables,this.state.context,this,s))}catch(B){Promise.reject(B)}try{await((O=(I=this.options).onSettled)==null?void 0:O.call(I,void 0,E,e,this.state.context,s))}catch(B){Promise.reject(B)}throw fe(this,yt,Lt).call(this,{type:"error",error:E}),E}finally{k(this,We).runNext(this)}}},vs=new WeakMap,mt=new WeakMap,We=new WeakMap,mr=new WeakMap,yt=new WeakSet,Lt=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),Ue.batch(()=>{k(this,mt).forEach(s=>{s.onMutationUpdate(e)}),k(this,We).notify({mutation:this,type:"updated",action:e})})},Ki);function Zc(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ct,dt,ws,Vi,eu=(Vi=class extends _s{constructor(e={}){super();te(this,Ct);te(this,dt);te(this,ws);this.config=e,H(this,Ct,new Set),H(this,dt,new Map),H(this,ws,0)}build(e,r,s){const n=new Xc({client:e,mutationCache:this,mutationId:++js(this,ws)._,options:e.defaultMutationOptions(r),state:s});return this.add(n),n}add(e){k(this,Ct).add(e);const r=Ns(e);if(typeof r=="string"){const s=k(this,dt).get(r);s?s.push(e):k(this,dt).set(r,[e])}this.notify({type:"added",mutation:e})}remove(e){if(k(this,Ct).delete(e)){const r=Ns(e);if(typeof r=="string"){const s=k(this,dt).get(r);if(s)if(s.length>1){const n=s.indexOf(e);n!==-1&&s.splice(n,1)}else s[0]===e&&k(this,dt).delete(r)}}this.notify({type:"removed",mutation:e})}canRun(e){const r=Ns(e);if(typeof r=="string"){const s=k(this,dt).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=Ns(e);if(typeof r=="string"){const n=(s=k(this,dt).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(){Ue.batch(()=>{k(this,Ct).forEach(e=>{this.notify({type:"removed",mutation:e})}),k(this,Ct).clear(),k(this,dt).clear()})}getAll(){return Array.from(k(this,Ct))}find(e){const r={exact:!0,...e};return this.getAll().find(s=>ki(r,s))}findAll(e={}){return this.getAll().filter(r=>ki(e,r))}notify(e){Ue.batch(()=>{this.listeners.forEach(r=>{r(e)})})}resumePausedMutations(){const e=this.getAll().filter(r=>r.state.isPaused);return Ue.batch(()=>Promise.all(e.map(r=>r.continue().catch(Je))))}},Ct=new WeakMap,dt=new WeakMap,ws=new WeakMap,Vi);function Ns(t){var e;return(e=t.options.scope)==null?void 0:e.id}var vt,Gi,tu=(Gi=class extends _s{constructor(e={}){super();te(this,vt);this.config=e,H(this,vt,new Map)}build(e,r,s){const n=r.queryKey,i=r.queryHash??Dn(n,r);let a=this.get(i);return a||(a=new Vc({client:e,queryKey:n,queryHash:i,options:e.defaultQueryOptions(r),state:s,defaultOptions:e.getQueryDefaults(n)}),this.add(a)),a}add(e){k(this,vt).has(e.queryHash)||(k(this,vt).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const r=k(this,vt).get(e.queryHash);r&&(e.destroy(),r===e&&k(this,vt).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Ue.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return k(this,vt).get(e)}getAll(){return[...k(this,vt).values()]}find(e){const r={exact:!0,...e};return this.getAll().find(s=>_i(r,s))}findAll(e={}){const r=this.getAll();return Object.keys(e).length>0?r.filter(s=>_i(e,s)):r}notify(e){Ue.batch(()=>{this.listeners.forEach(r=>{r(e)})})}onFocus(){Ue.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Ue.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},vt=new WeakMap,Gi),Ae,zt,Ht,Ur,Mr,Kt,Wr,qr,Ji,ru=(Ji=class{constructor(t={}){te(this,Ae);te(this,zt);te(this,Ht);te(this,Ur);te(this,Mr);te(this,Kt);te(this,Wr);te(this,qr);H(this,Ae,t.queryCache||new tu),H(this,zt,t.mutationCache||new eu),H(this,Ht,t.defaultOptions||{}),H(this,Ur,new Map),H(this,Mr,new Map),H(this,Kt,0)}mount(){js(this,Kt)._++,k(this,Kt)===1&&(H(this,Wr,Un.subscribe(async t=>{t&&(await this.resumePausedMutations(),k(this,Ae).onFocus())})),H(this,qr,Ds.subscribe(async t=>{t&&(await this.resumePausedMutations(),k(this,Ae).onOnline())})))}unmount(){var t,e;js(this,Kt)._--,k(this,Kt)===0&&((t=k(this,Wr))==null||t.call(this),H(this,Wr,void 0),(e=k(this,qr))==null||e.call(this),H(this,qr,void 0))}isFetching(t){return k(this,Ae).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return k(this,zt).findAll({...t,status:"pending"}).length}getQueryData(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=k(this,Ae).get(e.queryHash))==null?void 0:r.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),r=k(this,Ae).build(this,e),s=r.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(Vt(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return k(this,Ae).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=k(this,Ae).get(s.queryHash),i=n==null?void 0:n.state.data,a=Fc(e,i);if(a!==void 0)return k(this,Ae).build(this,s).setData(a,{...r,manual:!0})}setQueriesData(t,e,r){return Ue.batch(()=>k(this,Ae).findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,r)]))}getQueryState(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=k(this,Ae).get(e.queryHash))==null?void 0:r.state}removeQueries(t){const e=k(this,Ae);Ue.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){const r=k(this,Ae);return Ue.batch(()=>(r.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const r={revert:!0,...e},s=Ue.batch(()=>k(this,Ae).findAll(t).map(n=>n.cancel(r)));return Promise.all(s).then(Je).catch(Je)}invalidateQueries(t,e={}){return Ue.batch(()=>(k(this,Ae).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=Ue.batch(()=>k(this,Ae).findAll(t).filter(n=>!n.isDisabled()&&!n.isStatic()).map(n=>{let i=n.fetch(void 0,r);return r.throwOnError||(i=i.catch(Je)),n.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(s).then(Je)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=k(this,Ae).build(this,e);return r.isStaleByTime(Vt(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(Je).catch(Je)}fetchInfiniteQuery(t){return t.behavior=Ai(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(Je).catch(Je)}ensureInfiniteQueryData(t){return t.behavior=Ai(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return Ds.isOnline()?k(this,zt).resumePausedMutations():Promise.resolve()}getQueryCache(){return k(this,Ae)}getMutationCache(){return k(this,zt)}getDefaultOptions(){return k(this,Ht)}setDefaultOptions(t){H(this,Ht,t)}setQueryDefaults(t,e){k(this,Ur).set(fs(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...k(this,Ur).values()],r={};return e.forEach(s=>{ps(t,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(t,e){k(this,Mr).set(fs(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...k(this,Mr).values()],r={};return e.forEach(s=>{ps(t,s.mutationKey)&&Object.assign(r,s.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;const e={...k(this,Ht).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=Dn(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===$s&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...k(this,Ht).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){k(this,Ae).clear(),k(this,zt).clear()}},Ae=new WeakMap,zt=new WeakMap,Ht=new WeakMap,Ur=new WeakMap,Mr=new WeakMap,Kt=new WeakMap,Wr=new WeakMap,qr=new WeakMap,Ji),wa=at.createContext(void 0),xa=t=>{const e=at.useContext(wa);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},su=({client:t,children:e})=>(at.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),o.jsx(wa.Provider,{value:t,children:e})),_a=at.createContext(!1),nu=()=>at.useContext(_a);_a.Provider;function iu(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var au=at.createContext(iu()),ou=()=>at.useContext(au),lu=(t,e,r)=>{const s=r!=null&&r.state.error&&typeof t.throwOnError=="function"?pa(t.throwOnError,[r.state.error,r]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},cu=t=>{at.useEffect(()=>{t.clearReset()},[t])},uu=({result:t,errorResetBoundary:e,throwOnError:r,query:s,suspense:n})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(n&&t.data===void 0||pa(r,[t.error,s])),du=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))}},hu=(t,e)=>t.isLoading&&t.isFetching&&!e,fu=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,Pi=(t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()});function pu(t,e,r){var f,p,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=nu(),n=ou(),i=xa(),a=i.defaultQueryOptions(t);(p=(f=i.getDefaultOptions().queries)==null?void 0:f._experimental_beforeQuery)==null||p.call(f,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",du(a),lu(a,n,l),cu(n);const c=!i.getQueryCache().get(a.queryHash),[u]=at.useState(()=>new e(i,a)),d=u.getOptimisticResult(a),h=!s&&t.subscribed!==!1;if(at.useSyncExternalStore(at.useCallback(m=>{const v=h?u.subscribe(Ue.batchCalls(m)):Je;return u.updateResult(),v},[u,h]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),at.useEffect(()=>{u.setOptions(a)},[a,u]),fu(a,d))throw Pi(a,u,n);if(uu({result:d,errorResetBoundary:n,throwOnError:a.throwOnError,query:l,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&&!yr&&hu(d,s)){const m=c?Pi(a,u,n):l==null?void 0:l.promise;m==null||m.catch(Je).finally(()=>{u.updateResult()})}return a.notifyOnChangeProps?d:u.trackResult(d)}function ks(t,e){return pu(t,Gc)}const gu=5e3,bu=()=>`bob_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;function ka({ga4Config:t,hostContext:e,callbacks:r,enabled:s=!0,bobSupabaseUrl:n,bobSupabaseKey:i}){const a=g.useRef(bu()),l=g.useRef(!1),c=g.useRef(null),u=g.useRef(!1),d=g.useCallback((E,B)=>{if(!(!(t!=null&&t.measurementId)||typeof window>"u")&&window.gtag){const j={...B,send_to:t.measurementId};t.debug&&console.log("[BobAnalytics] GA4 event:",E,j),window.gtag("event",E,j)}},[t]),h=g.useCallback((E,B={})=>{var R,A,T,F,M,K,ee,Z;if(!s)return;const j={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:(A=e==null?void 0:e.user)==null?void 0:A.id,vehicle_id:(M=(F=(T=e==null?void 0:e.vehicle)==null?void 0:T.selectedVehicle)==null?void 0:F.vehicle_id)==null?void 0:M.toString(),rego:(ee=(K=e==null?void 0:e.vehicle)==null?void 0:K.selectedVehicle)==null?void 0:ee.rego,parameters:B};d(E,{session_id:j.session_id,user_email:j.user_email,vehicle_id:j.vehicle_id,...B}),(Z=r==null?void 0:r.onAnalyticsEvent)==null||Z.call(r,j),t!=null&&t.debug&&console.log("[BobAnalytics] Event tracked:",j)},[s,e,r,d,t==null?void 0:t.debug]),f=g.useCallback(()=>{var E,B,j;l.current||(l.current=!0,h("bob_session_start",{widget_version:At,has_vehicle:!!((E=e==null?void 0:e.vehicle)!=null&&E.selectedVehicle),has_user:!!((B=e==null?void 0:e.user)!=null&&B.id)||!!((j=e==null?void 0:e.user)!=null&&j.email)}))},[h,e]),p=g.useCallback((E,B)=>{h("bob_message_sent",{message_length:E,has_vehicle:B})},[h]),y=g.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=g.useCallback((E,B)=>{h("bob_parts_viewed",{part_count:E,vehicle_id:B})},[h]),m=g.useCallback(E=>{h("bob_product_clicked",{sku:E.sku,product_name:E.product_name,price:E.price,brand:E.brand})},[h]),v=g.useCallback(E=>{h("bob_product_viewed",{sku:E.sku,product_name:E.product_name,price:E.price,brand:E.brand})},[h]),x=g.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]),S=g.useCallback((E,B)=>{h("bob_checkout_started",{cart_value:E,item_count:B})},[h]),_=g.useCallback(E=>{const B=Math.ceil(E/5/150*60);h("bob_speech_played",{text_length:E,duration_estimate:B})},[h]),C=g.useCallback(E=>{h("bob_speech_failed",{text_length:E})},[h]),I=g.useCallback((E,B)=>{h("bob_error",{error_type:E,error_message:B})},[h]),O=g.useCallback(E=>{if(!s||!n||!i)return;const B=(E==null?void 0:E.led_to_cart)||(E==null?void 0:E.had_product_match),j=()=>{var A,T,F,M,K,ee;u.current=!1;const R={session_id:a.current,user_id:((A=e==null?void 0:e.user)==null?void 0:A.id)||null,channel:"web",vehicle_id:(E==null?void 0:E.vehicle_id)||((M=(F=(T=e==null?void 0:e.vehicle)==null?void 0:T.selectedVehicle)==null?void 0:F.vehicle_id)==null?void 0:M.toString())||null,rego:(E==null?void 0:E.rego)||((ee=(K=e==null?void 0:e.vehicle)==null?void 0:K.selectedVehicle)==null?void 0:ee.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(B){c.current&&(clearTimeout(c.current),c.current=null),j();return}u.current||(u.current=!0,c.current=setTimeout(j,gu))},[s,n,i,e]);return g.useEffect(()=>{f()},[f]),g.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[]),{trackEvent:h,sessionId:a.current,trackSessionStart:f,trackMessageSent:p,trackVehicleIdentified:y,trackPartsViewed:b,trackProductClicked:m,trackProductViewed:v,trackAddToCart:x,trackCheckoutStarted:S,trackSpeechPlayed:_,trackSpeechFailed:C,trackError:I,trackConversationActivity:O}}const Hs=g.createContext(null);function Wn({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=g.useMemo(()=>new ru({defaultOptions:{queries:{retry:1,staleTime:3e5}}}),[]),h=i||d,f=!!i;g.useEffect(()=>{console.log(`[BobWidget] v${At} initialized`),console.log(`[BobWidget] QueryClient: ${f?"external (shared)":"internal"}`),console.log(`[BobWidget] Analytics: ${l?"enabled":"disabled"}`),a!=null&&a.measurementId&&console.log(`[BobWidget] GA4: ${a.measurementId}`)},[f,l,a==null?void 0:a.measurementId]);const p=g.useMemo(()=>wn(e.supabaseUrl,e.supabaseKey),[e.supabaseUrl,e.supabaseKey]),[y,b]=g.useState(s);g.useEffect(()=>{b(s)},[s]);const m=g.useCallback(x=>{b(S=>({...S,...x}))},[]),v=g.useMemo(()=>({bobSupabase:p,bobConfig:e,hostApiConfig:r,hostContext:y,callbacks:n,updateHostContext:m,ga4Config:a,analyticsEnabled:l,bottomOffset:c,zIndexBase:u}),[p,e,r,y,n,m,a,l,c,u]);return o.jsx(su,{client:h,children:o.jsx(Hs.Provider,{value:v,children:t})})}function Pt(){const t=g.useContext(Hs);if(!t)throw new Error("useBobContext must be used within a BobProvider");return t}function mu(){const{bobSupabase:t}=Pt();return t}function vr(){const t=g.useContext(Hs);return(t==null?void 0:t.bobSupabase)||null}function yu(){const{hostContext:t}=Pt();return t}function vu(){const{hostApiConfig:t}=Pt();return t}function wu(){const{callbacks:t}=Pt();return t}function xu(){const{ga4Config:t,analyticsEnabled:e}=Pt();return{ga4Config:t,enabled:e}}function qn(){const t=g.useContext(Hs);return t?{bottomOffset:t.bottomOffset,zIndexBase:t.zIndexBase}:{bottomOffset:0,zIndexBase:50}}const _u=15e3,ku={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},Xr=new Map,Su=t=>t.replace(/\bya\b/gi,"you"),Sa=({onStart:t,onEnd:e,onFailed:r}={})=>{const{bobConfig:s,bobSupabase:n}=Pt(),[i,a]=g.useState(!1),l=g.useRef(null),c=g.useRef(null),u=g.useRef(!1),d=g.useRef([]),h=g.useRef(!1),f=g.useRef(!1),p=g.useRef(null),y=g.useRef(null),b=g.useRef(t),m=g.useRef(e),v=g.useRef(r);g.useEffect(()=>{b.current=t,m.current=e,v.current=r},[t,e,r]);const x=g.useCallback(()=>{c.current&&(clearTimeout(c.current),c.current=null)},[]),S=g.useCallback(()=>{var A;u.current||(u.current=!0,console.log("[BobWidget TTS] Fallback: triggering onStart without audio"),(A=b.current)==null||A.call(b))},[]),_=g.useCallback(async A=>{if(Xr.has(A)){const T=Xr.get(A);return console.log(`[BobWidget TTS] Cache hit for clip: ${A}`,T?"found":"null"),T||null}try{console.log(`[BobWidget TTS] Fetching clip from DB: ${A}`);const{data:T,error:F}=await n.from("bob_audio_clips").select("audio_url").eq("clip_key",A).eq("is_active",!0).single();return F||!T?(console.log(`[BobWidget TTS] No clip found for: ${A}`),Xr.set(A,null),null):(console.log(`[BobWidget TTS] Clip found: ${A} -> ${T.audio_url}`),Xr.set(A,T),T)}catch(T){return console.warn(`[BobWidget TTS] Clip lookup failed for ${A}:`,T),Xr.set(A,null),null}},[n]),C=g.useCallback(async A=>{for(const[T,F]of Object.entries(ku))if(F.test(A)){console.log(`[BobWidget TTS] Pattern matched: ${T}`);const M=await _(T);if(M!=null&&M.audio_url)return M.audio_url}return null},[_]),I=g.useCallback(async()=>{var M,K,ee;if(h.current||d.current.length===0)return;h.current=!0;const A=d.current.shift();if(!A){h.current=!1;return}const{text:T,isGreeting:F}=A;F&&(f.current=!0),u.current=!1,x(),l.current&&(l.current.pause(),l.current=null),c.current=setTimeout(()=>{var Z,z;console.warn("[BobWidget TTS] Timeout - triggering fallback callbacks"),S(),a(!1),f.current=!1,(Z=m.current)==null||Z.call(m),(z=v.current)==null||z.call(v),l.current=null,h.current=!1,I()},_u);try{let Z=null;if(Z=await C(T),Z)console.log("[BobWidget TTS] Using pre-recorded audio (fast path)");else{console.log("[BobWidget TTS] No pre-recorded clip, using ElevenLabs TTS");const V=Su(T),le=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(!le.ok){const L=await le.json().catch(()=>({}));throw console.error("[BobWidget TTS] Request failed:",L),new Error("TTS request failed")}const G=await le.blob();Z=URL.createObjectURL(G)}const z=new Audio(Z);l.current=z,z.onplay=()=>{var V;x(),p.current=null,u.current||(u.current=!0,a(!0),console.log("[BobWidget TTS] Audio playing, triggering onStart (animation: TALKING)"),(V=b.current)==null||V.call(b))},z.onended=()=>{var V;x(),a(!1),f.current=!1,console.log("[BobWidget TTS] Audio ended, triggering onEnd (animation: COMPLETE/IDLE)"),(V=m.current)==null||V.call(m),l.current=null,h.current=!1,I()},z.onerror=V=>{var le,G;x(),console.warn("[BobWidget TTS] Audio playback error:",V),S(),a(!1),f.current=!1,(le=m.current)==null||le.call(m),(G=v.current)==null||G.call(v),l.current=null,h.current=!1,I()};try{await z.play()}catch(V){console.warn("[BobWidget TTS] Audio play() failed (autoplay policy):",V),x(),F&&(p.current=T,console.log("[BobWidget TTS] Greeting stored for retry on user interaction")),S(),a(!1),f.current=!1,(M=m.current)==null||M.call(m),h.current=!1,I()}}catch(Z){x(),console.error("[BobWidget TTS] Speech synthesis error:",Z),S(),a(!1),f.current=!1,(K=m.current)==null||K.call(m),(ee=v.current)==null||ee.call(v),h.current=!1,I()}},[s.supabaseUrl,s.supabaseKey,x,S,C]),O=g.useCallback((A,T=!1)=>{if(A.trim()){if(T){if(y.current===A){console.log(`[BobWidget TTS] Ignoring duplicate greeting: "${A.substring(0,30)}..."`);return}y.current=A,p.current=null}if(f.current&&!T){console.log("[BobWidget TTS] Greeting playing - queueing message"),d.current.push({text:A,isGreeting:T});return}T?d.current.unshift({text:A,isGreeting:T}):d.current.push({text:A,isGreeting:T}),I()}},[I]),E=g.useCallback(()=>{if(p.current&&!l.current&&!h.current){console.log("[BobWidget TTS] Retrying pending greeting on user interaction");const A=p.current;p.current=null,O(A,!0)}},[O]),B=g.useCallback((A=!1)=>{var T;x(),d.current=[],l.current&&(l.current.onended=null,l.current.onerror=null,l.current.pause(),l.current=null),a(!1),f.current=!1,h.current=!1,A||(T=m.current)==null||T.call(m)},[x]),j=g.useCallback(()=>{var A;(A=l.current)==null||A.pause()},[]),R=g.useCallback(()=>{var A;(A=l.current)==null||A.play()},[]);return g.useEffect(()=>()=>{x(),d.current=[],l.current&&(l.current.pause(),l.current=null)},[x]),{speak:O,stop:B,pause:j,resume:R,isSpeaking:i,isSupported:!0,retryPendingGreeting:E}},Ii="bob_last_visit",Eu=30;function Ea(t=Eu){const[e,r]=g.useState(!1),[s,n]=g.useState(null);return g.useEffect(()=>{try{const i=localStorage.getItem(Ii),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(Ii,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 Fn=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},ju=t=>{let e=Fn(t);return e=e.replace(/[\[\]{}]/g,""),e=e.replace(/https?:\/\/[^\s]+/g,""),e=e.replace(/\bSKU\s*:?\s*\w+/gi,""),e},Tu=["what version","which version","software version","bob version","your version","current version","running version","version number","what ver","which ver"],an=["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"],Ru=["WIPER BLADE FRONT","WIPER BLADE REAR","WIPER BLADE SET","BRAKE PAD KIT","BRAKE PAD KIT FRONT","BRAKE PAD KIT REAR","BRAKE ROTOR","BRAKE ROTOR FRONT","BRAKE ROTOR REAR","BRAKE DISC","AIR FILTER","OIL FILTER","CABIN FILTER","FUEL FILTER","SPARK PLUG SET","SPARK PLUG","BALL JOINT","TIE ROD END","CONTROL ARM","WHEEL BEARING","CV JOINT","DRIVE SHAFT","TIMING BELT KIT","SERPENTINE BELT","DRIVE BELT","SHOCK ABSORBER","STRUT","COIL SPRING","CLUTCH KIT","CLUTCH PLATE","ALTERNATOR","STARTER MOTOR","WATER PUMP","THERMOSTAT","RADIATOR","RADIATOR HOSE","EXHAUST","MUFFLER","CATALYTIC CONVERTER","brake pads","brake rotors","brake discs","brakes","air filter","oil filter","cabin filter","fuel filter","spark plugs","spark plug","wiper","wipers","battery","batteries","clutch","clutch kit","alternator","starter motor","muffler","exhaust","cv joint","axle","timing belt","serpentine belt","shock absorber","struts","suspension"],ja=({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:f,onHighlightProduct:p,onNoPartsFound:y,onAutoFetchComplete:b,onVariantSelectionRequired:m})=>{var Hr,Kr,Ss,Vr;const{bobConfig:v,hostApiConfig:x,hostContext:S,callbacks:_,ga4Config:C,analyticsEnabled:I}=Pt(),O=ka({ga4Config:C,hostContext:S,callbacks:_,enabled:I}),{isReturningUser:E}=Ea(),[B,j]=g.useState([]),[R,A]=g.useState(""),[T,F]=g.useState(!1),[M,K]=g.useState(!1),[ee,Z]=g.useState(null),z=g.useRef(null),V=g.useRef(!1),le=g.useRef(!1),G=g.useRef(""),L=g.useRef(!1),D=g.useRef(null);g.useRef(null);const U=g.useRef({source:"none",isPlaying:!1,hasCannedAudio:!1,cannedUrl:null,currentAudio:null,searchingQueue:[]}),Q=g.useRef([]),_e=g.useRef("AWAITING_REGO"),Se=()=>{const W=U.current;if(W.currentAudio){try{W.currentAudio.pause(),W.currentAudio.currentTime=0}catch(ge){console.warn("[BobWidget] Error stopping audio:",ge)}W.currentAudio=null}W.isPlaying=!1,W.source="none",W.searchingQueue=[],qe()},Re=(W,ge,ye)=>{const ve=U.current;if(ve.isPlaying){if(ge==="canned"||ge==="searching"&&ve.source==="tts")Se();else if(ve.source==="canned"){console.log("[BobWidget Audio] Skipping lower priority audio while canned is playing");return}}const Ve=new Audio(W);ve.currentAudio=Ve,ve.source=ge,ve.isPlaying=!0,Ve.onplay=()=>{console.log(`[BobWidget Audio] ${ge} STARTED:`,W.split("/").pop()),e||X(r)},Ve.onended=()=>{console.log(`[BobWidget Audio] ${ge} ENDED`),ve.currentAudio=null,ve.isPlaying=!1,ve.source="none",ye==null||ye()},Ve.onerror=()=>{console.warn(`[BobWidget Audio] ${ge} FAILED:`,W),ve.currentAudio=null,ve.isPlaying=!1,ve.source="none",ye==null||ye()},Ve.play().catch(Jt=>{console.warn(`[BobWidget Audio] ${ge} autoplay blocked:`,Jt),ve.currentAudio=null,ve.isPlaying=!1,ve.source="none",ye==null||ye()})},Ne=()=>{const W=U.current;if(W.hasCannedAudio||W.source==="canned"){console.log("[BobWidget Audio] Skipping searching audio - canned audio takes priority"),W.searchingQueue=[];return}if(W.searchingQueue.length===0){!e&&W.source==="searching"&&X(s);return}const ge=W.searchingQueue.shift();Re(ge,"searching",()=>{Ne()})},Me=()=>{D.current&&(clearTimeout(D.current),D.current=null)},{speak:Pe,stop:qe,isSpeaking:ft,retryPendingGreeting:P}=Sa({onStart:()=>{Me(),L.current=!0,console.log("[BobWidget STATE] Speech STARTED - transitioning to TALK state"),O.trackSpeechPlayed(G.current.length),h==null||h(),e||(console.log("[BobWidget STATE] Setting state to:",r),X(r))},onEnd:()=>{Me(),console.log("[BobWidget STATE] Speech ENDED - transitioning out of TALK state");const W=an.some(ge=>G.current.toLowerCase().includes(ge.toLowerCase()));e||(W&&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),X(n),setTimeout(()=>{console.log("[BobWidget STATE] Post-complete transition to:",a),X(a)},2e3)))},onFailed:()=>{console.warn("[BobWidget] Speech synthesis failed - fallback triggered"),O.trackSpeechFailed(G.current.length)}});g.useEffect(()=>{var W;(W=_.onStopSpeechReady)==null||W.call(_,qe)},[]),g.useEffect(()=>{var W;(W=z.current)==null||W.scrollIntoView({behavior:"smooth"})},[B]),g.useEffect(()=>{var ge,ye;const W=(ge=S.vehicle)==null?void 0:ge.selectedVehicle;W&&!ee&&(console.log("[BobWidget] Setting vehicle from host context:",W),Z(W),(ye=_.onVehicleIdentified)==null||ye.call(_,W),O.trackVehicleIdentified({make:W.make,model:W.model,year:W.year,rego:W.rego}))},[(Hr=S.vehicle)==null?void 0:Hr.selectedVehicle]),g.useEffect(()=>{var W;if(B.length===0&&!le.current){le.current=!0;const ge=(W=S.vehicle)==null?void 0:W.selectedVehicle;let ye;E?(ye="Ah hey... you again! What you after this time?",console.log("[BobWidget] Using returning user greeting")):ge?ye=`G'day! Saw you've got the ${`${ge.year} ${ge.make} ${ge.model}`} - choice wagon! What can I help you find for it today?`:ye="G'day! Bob from CARFIX here. How can I help ya today?",j([{role:"assistant",content:ye}]),M||setTimeout(()=>{console.log("[BobWidget] Speaking initial greeting (priority)"),Pe(ye,!0)},500)}},[(Kr=S.vehicle)==null?void 0:Kr.selectedVehicle,B.length,M,Pe]),g.useEffect(()=>{const W=()=>{console.log("[BobWidget] User interaction detected - retrying pending greeting"),P(),document.removeEventListener("click",W),document.removeEventListener("touchstart",W)};return document.addEventListener("click",W,{once:!0}),document.addEventListener("touchstart",W,{once:!0}),()=>{document.removeEventListener("click",W),document.removeEventListener("touchstart",W)}},[P]),g.useEffect(()=>{var Qt,Yt;const W=(Qt=S.vehicle)==null?void 0:Qt.selectedVehicle;if(!W||V.current)return;const ge=W.vehicle_id??W.id,ye=Number.parseInt(String(ge),10);if(!Number.isFinite(ye)){console.warn("[BobWidget] Vehicle has invalid vehicle_id, cannot auto-fetch:",W);return}V.current=!0;const ve={...W,vehicle_id:String(ye)},Ve=(Yt=S.user)==null?void 0:Yt.email;(async()=>{var Nt,st;const It=`${v.supabaseUrl}/functions/v1/bob-chat`;try{const Ye=await fetch(It,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v.supabaseKey}`},body:JSON.stringify({messages:[],vehicleContext:ve,customerEmail:Ve,autoFetchParts:!0,hostConfig:x,hostContext:S})});if(!Ye.ok||!Ye.body){console.error("[BobWidget] Auto-fetch failed:",Ye.status);return}const Bt=Ye.body.getReader(),Xt=new TextDecoder;let pt="";for(;;){const{done:Zt,value:wr}=await Bt.read();if(Zt)break;pt+=Xt.decode(wr,{stream:!0});let wt;for(;(wt=pt.indexOf(`
|
|
73
|
+
`))!==-1;){let Xe=pt.slice(0,wt);if(pt=pt.slice(wt+1),Xe.endsWith("\r")&&(Xe=Xe.slice(0,-1)),Xe.startsWith(":")||Xe.trim()===""||!Xe.startsWith("data: "))continue;const er=Xe.slice(6).trim();if(er==="[DONE]")break;try{const He=JSON.parse(er);He.type==="service_packages_found"&&He.packages&&(console.log("[useBobChat autoFetch] Received service_packages_found:",He.packages.length,"packages"),(Nt=_.onServicePackagesFound)==null||Nt.call(_,He.packages)),He.type==="parts_found"&&He.parts&&(console.log("[useBobChat autoFetch] Received parts_found:",He.parts.length,"parts"),(st=_.onPartsFound)==null||st.call(_,He.parts),O.trackPartsViewed(Array.isArray(He.parts)?He.parts.length:0,String(ye)))}catch{}}}b==null||b()}catch(Ye){console.error("[BobWidget] Auto-fetch error:",Ye)}})()},[(Ss=S.vehicle)==null?void 0:Ss.selectedVehicle,(Vr=S.user)==null?void 0:Vr.email]);const X=W=>{try{t(W)}catch{console.warn(`[BobWidget] State "${W}" not available`)}},ce=async W=>{var ve,Ve,Jt,Qt,Yt,It,Nt,st,Ye,Bt,Xt,pt,Zt,wr,wt,Xe,er,He;const ge=`${v.supabaseUrl}/functions/v1/bob-chat`,ye=(ve=S.user)==null?void 0:ve.email;if(ee&&!M){const Ze=W.content.toLowerCase();if(an.some(xt=>Ze.includes(xt.toLowerCase()))){console.log("[useBobChat] 🎵 Playing optimistic searching audio");const xt=U.current;if(!xt.hasCannedAudio&&xt.source!=="canned"){const Gr=`${v.supabaseUrl}/storage/v1/object/public/bob-audio/parts_searching.mp3`;xt.searchingQueue.push(Gr),Ne()}}}try{const Ze={messages:[...B,W],hostConfig:x,hostContext:S};ee&&(Ze.vehicleContext=ee),ye&&(Ze.customerEmail=ye),console.log("[useBobChat DEBUG] vehicleCandidatesRef.current:",JSON.stringify((Ve=Q.current)==null?void 0:Ve.slice(0,2))),console.log("[useBobChat DEBUG] vehicleCandidatesRef.current.length:",(Jt=Q.current)==null?void 0:Jt.length),console.log("[useBobChat DEBUG] conversationStateRef.current:",_e.current),Q.current&&Q.current.length>0?(Ze.vehicleCandidates=Q.current,console.log("[useBobChat] ✅ Including",Q.current.length,"vehicle candidates in request")):console.log("[useBobChat] ⚠️ No vehicle candidates to include - ref is empty");const et=await fetch(ge,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v.supabaseKey}`},body:JSON.stringify(Ze)});if(!et.ok){if(et.status===429){(Qt=_.onError)==null||Qt.call(_,new Error("Rate limit exceeded"));return}if(et.status===402){(Yt=_.onError)==null||Yt.call(_,new Error("Payment required"));return}throw new Error("Failed to start stream")}if(!et.body)throw new Error("No response body");const xt=et.body.getReader(),Gr=new TextDecoder;let _t="",Es=!1,w="";for(;!Es;){const{done:ae,value:oe}=await xt.read();if(ae)break;_t+=Gr.decode(oe,{stream:!0});let Be;for(;(Be=_t.indexOf(`
|
|
74
|
+
`))!==-1;){let we=_t.slice(0,Be);if(_t=_t.slice(Be+1),we.endsWith("\r")&&(we=we.slice(0,-1)),we.startsWith(":")||we.trim()===""||!we.startsWith("data: "))continue;const Ce=we.slice(6).trim();if(Ce==="[DONE]"){Es=!0;break}try{const $=JSON.parse(Ce);if($.type==="conversation_state"){console.log("[useBobChat] 🔄 conversation_state event received:",$.state),_e.current=$.state,$.candidates&&Array.isArray($.candidates)?(Q.current=$.candidates,console.log("[useBobChat] ✅ Stored",$.candidates.length,"vehicle candidates from state event"),console.log("[useBobChat] First candidate:",JSON.stringify($.candidates[0]))):console.log("[useBobChat] ⚠️ conversation_state had no candidates array");continue}if($.type==="variant_selection_required"){const Ee=Array.isArray($.candidates)?$.candidates.length:0;console.log("[useBobChat] 🎴 variant_selection_required event received:",Ee,"cards"),Array.isArray($.candidates)?m==null||m($.candidates,typeof $.make=="string"?$.make:"",typeof $.model=="string"?$.model:""):console.warn("[useBobChat] ⚠️ variant_selection_required had no candidates array");continue}if($.type==="vehicle_identified"&&$.vehicle){Z($.vehicle),Q.current=[],_e.current="VEHICLE_CONFIRMED",(It=_.onVehicleIdentified)==null||It.call(_,$.vehicle),O.trackVehicleIdentified({make:$.vehicle.make,model:$.vehicle.model,year:$.vehicle.year,rego:$.vehicle.rego});continue}if($.type==="vehicle_candidates_found"&&$.candidates){console.log("[useBobChat] 📦 vehicle_candidates_found event received:",$.candidates.length,"candidates"),Q.current=$.candidates,console.log("[useBobChat] ✅ Candidates stored in ref. First:",JSON.stringify($.candidates[0]));continue}if($.type==="service_packages_found"&&$.packages){(Nt=_.onServicePackagesFound)==null||Nt.call(_,$.packages);continue}if($.type==="parts_found"&&$.parts){console.log("[useBobChat] Received parts_found event:",$.parts.length,"parts"),(st=_.onPartsFound)==null||st.call(_,$.parts),O.trackPartsViewed(Array.isArray($.parts)?$.parts.length:0,(Ye=ee==null?void 0:ee.vehicle_id)==null?void 0:Ye.toString());continue}if($.type==="bob_suggestions"&&$.products){console.log("[useBobChat] Received bob_suggestions:",$.products.length,"products",$.title),j(Ee=>{var gt;const he=[...Ee],ke=he[he.length-1];return console.log("[useBobChat] Attaching to message:",ke==null?void 0:ke.role,(gt=ke==null?void 0:ke.content)==null?void 0:gt.slice(0,40)),(ke==null?void 0:ke.role)==="assistant"?he.map((St,Qs)=>Qs===he.length-1?{...St,suggestedProducts:$.products,suggestionsTitle:$.title}:St):he}),console.log("[useBobChat] bob_suggestions processed for inline display only");continue}if($.type==="no_parts_found"){(Bt=_.onPartsFound)==null||Bt.call(_,[]),(Xt=_.onServicePackagesFound)==null||Xt.call(_,[]),y==null||y();continue}if($.type==="highlight_category"&&$.category){console.log("[useBobChat] highlight_category event:",$.category),f==null||f($.category);continue}if($.type==="navigate_url"&&$.url){console.log("[useBobChat] navigate_url event:",$.url),qe(),(pt=_.onNavigateToProductPage)==null||pt.call(_,{sku:$.sku,url:$.url});continue}if($.type==="quick_replies"&&Array.isArray($.replies)){console.log("[useBobChat] quick_replies event:",$.replies.length,"buttons"),j(Ee=>{var gt;const he=[...Ee],ke=he.length-1;return((gt=he[ke])==null?void 0:gt.role)==="assistant"?he.map((St,Qs)=>Qs===ke?{...St,quickReplies:$.replies}:St):he});continue}if($.type==="audio_hint"&&$.audio_url){console.log("[useBobChat] Audio hint received:",$.clip_key,$.audio_url);const Ee=U.current;Ee.hasCannedAudio=!0,Ee.cannedUrl=$.audio_url,Se();continue}if($.type==="bob_searching"&&$.audio_url){console.log("[useBobChat] Bob searching:",$.search_type,$.clip_key),$.transcript&&j(he=>{const ke=he[he.length-1];return(ke==null?void 0:ke.role)!=="assistant"||(ke==null?void 0:ke.content)!==$.transcript?[...he,{role:"assistant",content:$.transcript}]:he});const Ee=U.current;Ee.searchingQueue.push($.audio_url),!Ee.isPlaying&&!Ee.hasCannedAudio&&!M&&Ne();continue}if($.type==="cart_updated"&&$.items){(Zt=_.onCartUpdated)==null||Zt.call(_,$.items);continue}const kt=(Xe=(wt=(wr=$.choices)==null?void 0:wr[0])==null?void 0:wt.delta)==null?void 0:Xe.content;if(kt){w+=kt;let Ee=w.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");Ee=Fn(Ee),j(he=>{const ke=he[he.length-1];return(ke==null?void 0:ke.role)==="assistant"?he.map((gt,St)=>St===he.length-1?{...gt,content:Ee}:gt):[...he,{role:"assistant",content:Ee}]}),(er=_.onBobMessage)==null||er.call(_,Ee)}}catch{_t=we+`
|
|
75
|
+
`+_t;break}}}let N=w.replace(/\[VEHICLE_CONFIRMED:\{[\s\S]*?\}\]/g,"");N=Fn(N),G.current=N;const q=an.some(ae=>w.toLowerCase().includes(ae.toLowerCase())),ne=w.toLowerCase();for(const ae of Ru)if(ne.includes(ae.toLowerCase())){const oe=ae.replace(/s\s*$/i,"").toUpperCase();f==null||f(oe);break}const be=w.match(/(?:go with|recommend|suggest|grab|try)\s+(?:the\s+)?(\w+)\s+(?:at|for)\s+\$(\d+(?:\.\d{2})?)/i);if(be){const[,ae,oe]=be;p==null||p({brand:ae,price:parseFloat(oe)})}const de=U.current;if(!M&&G.current.trim()){if(L.current=!1,Me(),de.hasCannedAudio&&de.cannedUrl)console.log("[BobWidget] Playing canned audio (priority):",de.cannedUrl),Se(),Re(de.cannedUrl,"canned",()=>{de.hasCannedAudio=!1,de.cannedUrl=null,Me(),e||(q&&u?u():c?c():(X(n),setTimeout(()=>X(a),3e3)))}),L.current=!0,h==null||h();else if(de.isPlaying)console.log("[BobWidget] Skipping TTS - audio already playing:",de.source);else{const ae=ju(G.current);console.log("[BobWidget] Playing TTS (no canned audio)"),Pe(ae)}D.current=setTimeout(()=>{L.current||(console.warn("[BobWidget] Speech fallback after 5s"),h==null||h(),e||(q&&u?u():c?c():(X(n),setTimeout(()=>X(a),3e3))))},5e3)}else h==null||h(),e||(q&&u?u():c?c():(X(n),setTimeout(()=>X(a),3e3)))}catch(Ze){console.error("[BobWidget] Chat error:",Ze);const et=Ze instanceof Error?Ze:new Error("Unknown error");(He=_.onError)==null||He.call(_,et),O.trackError(et.name||"ChatError",et.message||"Unknown chat error"),e||X(i)}},me=async()=>{if(!R.trim()||T)return;P(),qe();const W={role:"user",content:R};j(ve=>[...ve,W]),A(""),O.trackMessageSent(R.length,!!ee);const ge=R.toLowerCase();if(Tu.some(ve=>ge.includes(ve))){const ve=`G'day mate! I'm running Bob v${At} - she's running sweet as! Anything else I can help ya with?`;j(Ve=>[...Ve,{role:"assistant",content:ve}]),M||Pe(ve);return}F(!0),console.log("[BobWidget STATE] User sent message - switching to RESEARCH state:",s),d==null||d(),e||X(s),await ce(W),F(!1)};return{messages:B,input:R,setInput:A,isLoading:T,handleSend:me,handleKeyPress:W=>{W.key==="Enter"&&!W.shiftKey&&(W.preventDefault(),me())},handleInputFocus:()=>{P()},handleInputBlur:()=>{},chatEndRef:z,clearMessages:()=>{j([{role:"assistant",content:"G'day! Bob from CARFIX here. How can I help ya today?"}])},isMuted:M,toggleMute:()=>{K(W=>!W),M||qe()},isSpeaking:ft,identifiedVehicle:ee,clearVehicle:()=>{Z(null)},sendDirectMessage:W=>{if(!W.trim())return;console.log("[BobWidget] sendDirectMessage:",W),qe(),F(!1),A("");const ge={role:"user",content:W};j(ye=>[...ye,ge]),d==null||d(),e||X(s),F(!0),ce(ge).finally(()=>F(!1))},stopAllAudio:Se}},Cu={states:[],configs:[],uploadedImages:[],looks:[],activeLookId:null},Ta=t=>{const e=xa(),r=vr();return g.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]),ks({queryKey:["bob-animation-data",t],queryFn:async()=>{var S;if(!r)return console.log("[BobAnimation] No supabase client, returning empty data"),Cu;const{data:s,error:n}=await r.from("bob_looks").select("*").order("display_order");if(n)throw n;const i=(s||[]).find(_=>_.is_active),a=t||(i==null?void 0:i.id)||s&&((S=s[0])==null?void 0:S.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(_=>_.state_key);console.log(`[BobAnimation] Loaded ${h.length} states: ${h.join(", ")}`);const p=["idle","talking","listening"].filter(_=>{const C=[_,_.replace("ing",""),_+"ing"];return!h.some(I=>C.includes(I))});p.length>0&&console.warn(`[BobAnimation] ⚠️ Missing critical states: ${p.join(", ")}`);const y=new Set(h),b=(u||[]).filter(_=>y.has(_.animation_state));console.log(`[BobAnimation] Loaded ${b.length} animation frames`);const{data:m,error:v}=await r.storage.from("bob-images").list();if(v)throw v;const x=(m||[]).map(_=>{const{data:C}=r.storage.from("bob-images").getPublicUrl(_.name);return C.publicUrl});return b.forEach(_=>{const C=new Image;C.src=_.image_url}),{states:l||[],configs:b,uploadedImages:x,looks:s||[],activeLookId:a}},staleTime:30*1e3,gcTime:5*60*1e3})},Ra=(t={})=>{const{isSpeaking:e=!1}=t,[r,s]=g.useState(""),[n,i]=g.useState(0),[a,l]=g.useState(400),[c,u]=g.useState(!1),d=g.useRef(null),h=g.useRef(0),f=g.useRef(e),p=g.useRef(0),y=g.useRef(0),b=g.useRef(!1),m=g.useRef(0),{data:v,isLoading:x}=Ta(),S=g.useRef({}),{imageUrlsMap:_,alternateImages:C,offsetsMap:I,scalesMap:O,availableStates:E}=g.useMemo(()=>{if(!v)return{imageUrlsMap:{},alternateImages:{},offsetsMap:{},scalesMap:{},availableStates:[]};const T={},F={},M={},K={},ee=v.states.map(Z=>Z.state_key);return ee.forEach(Z=>{const z=v.configs.filter(L=>L.animation_state===Z),V=z.map(L=>L.image_url),le=z.map(L=>L.vertical_offset||0),G=z.map(L=>L.scale||100);if(V.length>0){const L=v.states.find(D=>D.state_key===Z);T[Z]={url:V[0],animation_speed:(L==null?void 0:L.animation_speed)||400,pause_duration:(L==null?void 0:L.pause_duration)||0,loop_count:(L==null?void 0:L.loop_count)||0},F[Z]=V,M[Z]=le,K[Z]=G}}),{imageUrlsMap:T,alternateImages:F,offsetsMap:M,scalesMap:K,availableStates:ee}},[v]);g.useEffect(()=>{S.current=_},[_]),g.useEffect(()=>{const T=f.current;if(f.current=e,T&&!e){const F=r.toLowerCase();(F.includes("talk")||F==="talking")&&(console.log("[useBobAnimation] Speech ended while in talk state - forcing loop completion"),y.current=999)}},[e,r]);const B=g.useCallback(T=>{s(F=>F===T?F:(p.current=0,y.current=0,b.current=!1,i(0),T))},[]);g.useEffect(()=>{E.length>0&&!r&&s(E[0])},[E,r]),g.useEffect(()=>{const T=C[r];if(d.current!==null&&(cancelAnimationFrame(d.current),d.current=null),p.current=0,y.current=0,b.current=!1,h.current=0,i(0),!T||T.length<=1)return;const F=S.current[r],M=(F==null?void 0:F.animation_speed)||a||400,K=(F==null?void 0:F.loop_count)||0,ee=(F==null?void 0:F.pause_duration)||0,Z=r.toLowerCase().includes("talk"),z=V=>{if(h.current===0&&(h.current=V),b.current){V-m.current>=ee&&(b.current=!1,y.current=0,h.current=V),d.current=requestAnimationFrame(z);return}if(V-h.current>=M){h.current=V;const G=(p.current+1)%T.length;G===0?(y.current++,Z&&f.current?(p.current=G,i(G)):K>0&&y.current>=K?ee>0&&(b.current=!0,m.current=V):(p.current=G,i(G))):(p.current=G,i(G))}d.current=requestAnimationFrame(z)};return d.current=requestAnimationFrame(z),()=>{d.current!==null&&(cancelAnimationFrame(d.current),d.current=null)}},[r,C,a]);const j=g.useCallback(()=>{const T=C[r];if(!T||T.length===0){const F=E.find(M=>{var K;return((K=C[M])==null?void 0:K.length)>0});return F?(console.warn(`[useBobAnimation] No images for "${r}", using fallback: ${F}`),C[F][0]):(console.error("[useBobAnimation] No valid images found for any state!"),"")}return T[n]||T[0]},[C,r,E,n]),R=g.useCallback(()=>{const T=I[r];if(!T||T.length===0){const F=E.find(M=>{var K;return((K=I[M])==null?void 0:K.length)>0});return F?I[F][0]:0}return T[n]||T[0]},[I,r,E,n]),A=g.useCallback(()=>{const T=O[r];if(!T||T.length===0){const F=E.find(M=>{var K;return((K=O[M])==null?void 0:K.length)>0});return F?O[F][0]:100}return T[n]||T[0]},[O,r,E,n]);return{animationState:r,setAnimationState:B,getCurrentImage:j,getCurrentOffset:R,getCurrentScale:A,imageUrls:_,availableStates:E,setTalkSpeed:l,manualMode:c,setManualMode:u,isLoading:x}},Ca=()=>{const t=vr(),{data:e=[],isLoading:r}=ks({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}},Aa=({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}%`}})]})})},J={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"},Us={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"}},on={"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."},Au="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.",gs={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`},Oa={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"}},ct={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 Pa(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 Ia(t,e){return e?{displayPrice:t*2,unitPriceLabel:`$${t.toFixed(2)} each`}:{displayPrice:t}}function Qe(t){return`$${t.toFixed(2)}`}function Na(t){if(on[t])return on[t];const e=t.toLowerCase();for(const[r,s]of Object.entries(on))if(e.includes(r.toLowerCase())||r.toLowerCase().includes(e))return s;return Au}const rs=({type:t,value:e,className:r=""})=>{const s=Oa[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]})},zn=({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:ct.partslotName.fontSize,fontWeight:ct.partslotName.fontWeight,color:J.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(Ou,{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:J.mutedForeground,textAlign:"center"},children:["+ ",t.length-6," more options available"]})]}),Ou=({product:t,onProductClick:e,onAddToCart:r,isRecommended:s=!1})=>{const[n,i]=g.useState(!1),[a,l]=g.useState(!1),c=t.image_url||t.image||(t.sku?gs.productImage(t.sku):null),u=t.brand?gs.brandLogo(t.brand):null,d=t.brand||"Quality Part",h=t.name||"Product",f=t.price??0,p=t.partNumber||t.part_number,y=Pa({name:t.name,partslotDescription:t.partslotDescription,per_car_qty:t.quantity}),{displayPrice:b,unitPriceLabel:m}=Ia(f,y);return o.jsxs("div",{style:{background:J.card,borderRadius:"12px",border:`2px solid ${J.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=`${J.primary}80`,v.currentTarget.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)"},onMouseLeave:v=>{v.currentTarget.style.borderColor=J.border,v.currentTarget.style.boxShadow="none"},children:[t.partslotDescription&&o.jsxs("div",{style:{background:"rgba(0,0,0,0.03)",borderBottom:`1px solid ${J.border}`,padding:"10px 16px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsx("span",{style:{fontSize:ct.partslotName.fontSize,fontWeight:ct.partslotName.fontWeight,color:J.foreground},children:t.partslotDescription}),s&&o.jsx(rs,{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 ${J.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:J.foreground,textTransform:"uppercase"},children:d})]}),o.jsx("div",{style:{fontSize:ct.productName.fontSize,fontWeight:ct.productName.fontWeight,color:J.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(rs,{type:"fitsVehicle"}),y&&o.jsx(rs,{type:"rotorPair"}),t.quantity&&t.quantity>1&&!y&&o.jsx(rs,{type:"quantity",value:`Qty: ${t.quantity}`}),p&&o.jsxs("span",{style:{fontSize:"12px",color:J.mutedForeground},children:["#",p]})]})]}),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:ct.priceMain.fontSize,fontWeight:ct.priceMain.fontWeight,color:J.foreground},children:Qe(b)}),m&&o.jsx("div",{style:{fontSize:ct.priceSecondary.fontSize,color:J.mutedForeground},children:m}),o.jsx("div",{style:{fontSize:ct.priceSecondary.fontSize,color:J.mutedForeground},children:"inc GST"})]}),r&&o.jsx("button",{onClick:v=>{v.stopPropagation(),r(t)},style:{background:J.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=J.primaryHover},onMouseLeave:v=>{v.currentTarget.style.background=J.primary},onMouseDown:v=>{v.currentTarget.style.transform="scale(0.98)"},onMouseUp:v=>{v.currentTarget.style.transform="scale(1)"},children:"Add to Cart"})]})]})]})},Ba=({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:f="",onAddToCart:p,onProductClick:y})=>o.jsx("div",{className:f,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,m)=>{var v;return o.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:b.role==="user"?"flex-end":"flex-start"},children:o.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&&o.jsx(zn,{products:b.suggestedProducts,title:b.suggestionsTitle,onAddToCart:p,onProductClick:y})]})},m)}),o.jsx("div",{ref:c})]})]})}),Pu=768,Iu=1024;function Ks(){const[t,e]=g.useState("mobile");return g.useEffect(()=>{const r=()=>{const s=window.innerWidth;s>=Iu?e("desktop"):s>=Pu?e("tablet"):e("mobile")};return r(),window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),t}function Hn(){const t=Ks();return Nu(t)}function Nu(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 Vs=({currentImage:t,animationState:e,counterOverlayUrl:r,counterHeightPercent:s=15,scale:n=100,position:i="center",verticalOffset:a=0,hasArrived:l=!0})=>{const c=Hn(),d=95*n/100,h=550*n/100,f=()=>{switch(i){case"center":return"50%";case"partial-left":return`${c.partialLeftPosition}%`;case"hidden":return`${c.hiddenPosition}%`;default:return"50%"}},p=()=>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 o.jsxs("div",{className:"absolute inset-0 pointer-events-none",style:{overflow:"visible"},children:[o.jsx("div",{className:"absolute z-[60]",style:{bottom:`${y}%`,left:f(),maxHeight:`${100-s-2}%`,transform:p(),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})})]})},Bu={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)"},Fu={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)"},Fa={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)"},is={primary:{color:"rgba(255, 255, 255, 1)",textShadow:"0 1px 3px rgba(0,0,0,0.5)"}},Lu={background:"rgba(255, 255, 255, 0.12)",borderRadius:"20px",border:"1px solid rgba(255, 255, 255, 0.15)"},Ni={background:"rgba(255, 255, 255, 0.15)",border:"1px solid rgba(255, 255, 255, 0.25)",borderRadius:"12px"},$u={width:"4px",height:"4px",borderRadius:"50%",background:"rgba(255, 255, 255, 0.6)",boxShadow:"0 0 8px rgba(255, 255, 255, 0.4)"},La=({product:t,isSpotlighted:e=!1,onProductClick:r,onAddToCart:s})=>{const[n,i]=g.useState(!1),[a,l]=g.useState(0),c=()=>{r==null||r(t)},u=y=>{y.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,f=e?Fu:Bu,p=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:{...f,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)":f.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:{...Lu,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",...is.primary},children:p}),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:{...Ni,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:{...Ni,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: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: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})})]})},Du=["SHOE","DRUM"],Uu=["PAD","ROTOR"];function $a(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 Da(t,e){const r=e==="disc"?Du:Uu;return t.filter(s=>{const n=s.partslotName.toUpperCase();return!r.some(i=>n.includes(i))})}function Ua(t){return t.reduce((e,r)=>e+r.displayPrice,0)}const Bi=(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))},Mu=(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},Wu=({product:t,isSpotlighted:e,spotlightedRef:r,onProductClick:s})=>o.jsx("div",{ref:e?r:void 0,children:o.jsx(La,{product:t,isSpotlighted:e,onProductClick:s})}),Gs=({products:t,servicePackages:e,highlightedPartType:r,highlightedProduct:s,onProductClick:n,onPackageSelect:i,isResearching:a,visible:l=!0,counterHeightPercent:c=22,hasVehicle:u=!1,onAddToCart:d,vehicleMakeModel:h,pendingVariants:f,pendingVariantMake:p,pendingVariantModel:y,onVariantSelect:b})=>{const m=h||"Bob's Shelf",v=Ks();Hn();const x=g.useRef(null),S=g.useRef({}),_=g.useRef(null),[C,I]=g.useState(null),[O,E]=g.useState({}),[B,j]=g.useState({}),R=g.useMemo(()=>{const L={};return t.forEach(U=>{const Q=U.partslotDescription||"Other Parts";L[Q]||(L[Q]=[]),L[Q].push(U)}),Object.keys(L).sort((U,Q)=>U.localeCompare(Q)).map(U=>({name:U,products:L[U]}))},[t]);g.useEffect(()=>{if(!r)return;const L=setTimeout(()=>{const D=Object.entries(S.current);for(const[U,Q]of D)if(Q&&Bi(U,r)){Q.scrollIntoView({behavior:"smooth",block:"start"});break}},300);return()=>clearTimeout(L)},[r]);const[A,T]=g.useState(0),F=L=>{const D=L.currentTarget,U=D.scrollHeight-D.clientHeight;if(U>0){const Q=D.scrollTop/U;T(Math.max(0,Math.min(1,Q)))}},M=((f==null?void 0:f.length)??0)>0,K=t.length>0||e.length>0||M,ee=a&&!K,Z=K&&!ee,z=l||K,V=v==="mobile"?92:v==="tablet"?65:70,le=v==="desktop"?"900px":v==="tablet"?"500px":"100%",G=v==="mobile"?"calc(8px + env(safe-area-inset-top, 4px))":"6px";return o.jsxs(o.Fragment,{children:[K&&l&&o.jsx("div",{style:{position:"fixed",right:"2px",top:`calc(${A*65+18}%)`,...$u,opacity:.8,transition:"top 0.1s ease-out",zIndex:100,pointerEvents:"none"}}),o.jsxs("div",{ref:x,onScroll:F,className:`absolute overflow-y-auto overflow-x-hidden flex flex-col gap-3 md:gap-4 transition-all duration-400 ease-out product-scroll ${z?"opacity-100 translate-x-0":"opacity-0 translate-x-12 pointer-events-none"}`,style:{width:`${V}%`,maxWidth:le,right:"0",left:"auto",top:G,bottom:v==="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:[a&&K?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:{...is.primary,fontWeight:700,fontSize:"14px",letterSpacing:"0.025em"},children:a&&K?"Updating...":m})]}),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"]})]})}),ee&&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:{...is.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"})]})]})}),M&&f&&b&&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 ",p," ",y,"?"]}),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 L=(f||[]).map(U=>[U.engineCode,U.kw?`${U.kw}kW`:null,U.ccDisplay||(U.cc?`${U.cc}cc`:null),U.fuelType].filter(Boolean).join(" · ")||U.displayTitle),D=L.reduce((U,Q)=>(U[Q]=(U[Q]||0)+1,U),{});return(f||[]).map((U,Q)=>{const _e=L[Q],Re=D[_e]>1&&U.displaySubtitle?U.displaySubtitle:_e;return o.jsx("button",{type:"button",onClick:()=>b(U),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:U.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:Re})}),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"})})})]})},U.vehicle_id)})})()})]}),!ee&&!K&&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:{...is.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]})]})]})}),Z&&e.length>0&&o.jsx("div",{className:"space-y-4",children:e.map(L=>{var qe,ft;const D=$a(L),U=B[L.id]||"disc";let Q=(L.preparedTiers||[]).filter(P=>!P.isHidden);D&&(Q=Q.map(P=>{const X=Da(P.products,U);return{...P,products:X,totalPrice:Ua(X),productCount:X.length}}));const _e=((qe=Q.find(P=>P.isRecommended))==null?void 0:qe.tierName)||((ft=Q[0])==null?void 0:ft.tierName)||"",Se=O[L.id]||_e,Re=Q.find(P=>P.tierName===Se),Me=Na(L.title).split(".")[0]+".",Pe=C===L.id;return o.jsxs("div",{className:"overflow-hidden transition-all duration-300",style:{background:J.card,borderRadius:"16px",border:`1px solid ${J.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, ${J.primary} 0%, ${J.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:L.title}),L.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"})}),L.estimated_time]})})]})]})}),o.jsxs("div",{className:"px-4 py-3 border-b",style:{borderColor:J.border},children:[o.jsx("p",{className:"text-sm leading-relaxed",style:{color:J.mutedForeground},children:Me}),D&&o.jsxs("div",{className:"mt-2 mb-1",children:[o.jsx("p",{className:"text-[11px] mb-1.5",style:{color:J.mutedForeground},children:"Select your vehicle's rear brake type"}),o.jsxs("div",{className:"flex rounded-xl overflow-hidden border",style:{borderColor:J.border},children:[o.jsx("button",{onClick:()=>j(P=>({...P,[L.id]:"disc"})),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:U==="disc"?J.primary:"transparent",color:U==="disc"?"#FFFFFF":J.mutedForeground},children:"Disc Brakes (Pads + Rotors)"}),o.jsx("button",{onClick:()=>j(P=>({...P,[L.id]:"drum"})),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:U==="drum"?J.primary:"transparent",color:U==="drum"?"#FFFFFF":J.mutedForeground},children:"Drum Brakes (Shoes + Drums)"})]})]})]}),Q.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:J.mutedForeground},children:"Choose Your Value Level"}),o.jsx("div",{className:"grid gap-2",style:{gridTemplateColumns:`repeat(${Math.min(Q.length,4)}, 1fr)`},children:Q.map(P=>{const X=Us[P.tierName],ce=P.tierName===Se;return o.jsxs("div",{onClick:()=>E(me=>({...me,[L.id]:P.tierName})),className:"relative rounded-xl text-center transition-all cursor-pointer",style:{padding:Q.length>=4?"6px 4px":"8px",background:P.isRecommended?`${J.primary}10`:ce?`${J.primary}05`:J.background,border:`2px solid ${P.isRecommended?J.primary:ce?J.primary+"80":J.border}`},children:[P.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:J.primary,color:"white"},children:"Carfix Value"}),o.jsxs("p",{className:"text-sm font-bold mt-1",style:{color:(X==null?void 0:X.textColor)||J.foreground},children:[X==null?void 0:X.emoji," ",P.displayName]}),o.jsx("div",{className:"flex flex-col items-center gap-1 mt-2",style:{minHeight:Q.length>=4?"40px":"48px"},children:P.brands.slice(0,1).map((me,ze)=>{const ie=`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${me.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:Q.length>=4?"36px":"44px",maxWidth:Q.length>=4?"64px":"80px",boxShadow:"0 2px 8px rgba(0,0,0,0.1)",border:"1px solid #F1F5F9"},children:o.jsx("img",{src:me.imageUrl,alt:me.fullName,className:"w-auto object-contain",style:{height:Q.length>=4?"26px":"32px"},onError:Te=>{const ue=Te.target;ue.src!==ie?ue.src=ie:(ue.style.display="none",ue.parentElement.innerHTML=`<span class="text-[10px] font-semibold text-gray-600 truncate px-1">${me.fullName}</span>`)}})},ze)})}),o.jsxs("p",{className:"text-[10px] mt-2",style:{color:J.mutedForeground},children:[P.productCount," ",P.productCount===1?"part":"parts"]}),P.savingsAmount&&P.savingsAmount>0?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-[11px] line-through",style:{color:J.mutedForeground},children:Qe(P.originalTotalPrice)}),o.jsx("p",{className:"text-base font-bold",style:{color:J.success},children:Qe(P.totalPrice)}),o.jsxs("p",{className:"text-[9px] font-semibold px-1.5 py-0.5 rounded-full mt-0.5",style:{background:`${J.success}15`,color:J.success},children:["SAVE ",Qe(P.savingsAmount)," — ",P.bundleDiscountPercentage,"% Bundle Deal"]})]}):o.jsx("p",{className:"text-base font-bold mt-1",style:{color:J.foreground},children:Qe(P.totalPrice)}),o.jsx("p",{className:"text-[10px]",style:{color:J.mutedForeground},children:"inc GST"}),o.jsx("button",{onClick:me=>{me.stopPropagation();const ze=P.bundleDiscountPercentage||0,ie=1-ze/100,Te=P.products.map(ue=>({id:ue.sku,name:ue.name,brand:ue.brand,price:ze>0?Math.round(ue.displayPrice*ie*100)/100:ue.displayPrice,sku:ue.sku,partNumber:ue.partNumber||void 0,image_url:ue.productImageUrl,partslotDescription:ue.partslotName,quantity:1}));d==null||d(Te)},className:"w-full mt-2 py-1.5 rounded-lg text-[10px] font-semibold transition-all",style:{background:P.isRecommended?J.success:"#F1F5F9",color:P.isRecommended?"white":J.success,border:P.isRecommended?"none":"1px solid #E2E8F0",textAlign:"center"},children:"Add"})]},P.tierName)})})]}),o.jsxs("div",{onClick:()=>I(Pe?null:L.id),className:"flex items-center justify-center gap-1.5 py-2 cursor-pointer hover:bg-gray-50 transition-colors border-t",style:{borderColor:J.border},children:[o.jsx("span",{className:"text-xs",style:{color:J.mutedForeground},children:Pe?"Hide details":"Show details"}),o.jsx("svg",{className:`w-4 h-4 transition-transform duration-200 ${Pe?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",style:{color:J.mutedForeground},children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),Pe&&Re&&o.jsx("div",{className:"px-4 pb-4 border-t animate-in slide-in-from-top-2 duration-200",style:{borderColor:J.border},children:o.jsxs("div",{className:"pt-3",children:[o.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide mb-3",style:{color:J.mutedForeground},children:[Re.displayName," Tier Products"]}),o.jsx("div",{className:"space-y-2",children:Re.products.map(P=>o.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg",style:{background:J.background,border:`1px solid ${J.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:P.productImageUrl?o.jsx("img",{src:P.productImageUrl,alt:P.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:J.foreground},children:P.name}),o.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[o.jsx("span",{className:"text-[10px]",style:{color:J.mutedForeground},children:P.brand}),P.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:J.mutedForeground},children:P.partslotName})]}),o.jsxs("div",{className:"text-right flex-shrink-0",children:[o.jsx("p",{className:"text-sm font-bold",style:{color:J.primary},children:Qe(P.displayPrice)}),P.isRotor&&o.jsxs("p",{className:"text-[9px]",style:{color:J.mutedForeground},children:["$",P.price.toFixed(2)," ea"]})]})]},P.sku))})]})})]},L.id)})}),Z&&R.map(({name:L,products:D})=>{const U=r&&Bi(L,r);return o.jsxs("section",{ref:Q=>{S.current[L]=Q},className:"transition-all duration-300",style:{background:"transparent",borderRadius:"24px"},children:[o.jsxs("div",{"data-testid":"partslot-header","data-partslot-name":L,className:"px-3 py-2.5 flex items-center justify-between",style:{background:U?"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:U?"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:L})]}),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:D.length})]}),o.jsx("div",{className:"flex flex-col gap-3",children:D.map((Q,_e)=>{const Se=!!(s&&Mu(Q,s));return o.jsx("div",{"data-testid":"partslot-product",children:o.jsx(Wu,{product:Q,isSpotlighted:Se,spotlightedRef:_,onProductClick:n,viewportSize:v})},`${Q.id}-${_e}`)})})]},L)}),o.jsx("div",{className:"h-4"})]})]})},Kn=({onTranscript:t,onSpeechEnd:e,language:r="en-NZ",mode:s="toggle"}={})=>{const[n,i]=g.useState(!1),[a,l]=g.useState(""),[c,u]=g.useState(""),[d,h]=g.useState(null),[f,p]=g.useState(!1),y=g.useRef(null),b=g.useRef(""),m=g.useRef(t),v=g.useRef(e),x=g.useRef(null),S=15e3;g.useEffect(()=>{m.current=t,v.current=e},[t,e]),g.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)"),p(!1);return}const O=window.SpeechRecognition||window.webkitSpeechRecognition;if(O){p(!0);const E=new O;E.continuous=s==="ptt",E.interimResults=!0,E.lang=r,E.maxAlternatives=1,E.onstart=()=>{i(!0),h(null)},E.onresult=B=>{let j="",R="";for(let A=B.resultIndex;A<B.results.length;A++){const T=B.results[A][0].transcript;B.results[A].isFinal?R+=T:j+=T}R&&(b.current=R,l(R),m.current&&m.current(R)),u(j)},E.onerror=B=>{switch(i(!1),B.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=()=>{x.current&&(clearTimeout(x.current),x.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 _=()=>{if(y.current&&!n){l(""),u(""),h(null),x.current=setTimeout(()=>{console.warn("[SpeechRecognition] Safety timeout - forcing stop after 15s"),y.current&&y.current.abort(),i(!1),u("")},S);try{y.current.start()}catch(O){console.warn("[SpeechRecognition] start() failed (already running):",O),x.current&&(clearTimeout(x.current),x.current=null)}}},C=()=>{x.current&&(clearTimeout(x.current),x.current=null),y.current&&n&&y.current.stop()};return{isListening:n,transcript:a,interimTranscript:c,error:d,isSupported:f,startListening:_,stopListening:C,toggleListening:()=>{n?C():_()}}},Ma=({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:f,onProductClick:p,onQuickReply:y,onInterrupt:b,counterHeightPercent:m=22})=>{var D;const[v,x]=g.useState(!1),S=g.useRef(null),_=g.useRef(!1),{bottomOffset:C,zIndexBase:I}=qn(),{isListening:O,interimTranscript:E,error:B,isSupported:j,startListening:R,stopListening:A}=Kn({onTranscript:U=>r(U),language:"en-NZ",mode:"ptt"});g.useEffect(()=>{E&&r(E)},[E,r]);const T=h?"speaking":s?"processing":O?"listening":"idle",F=g.useCallback(U=>{if(U.preventDefault(),T==="speaking"){b==null||b();return}s||_.current||(_.current=!0,navigator.vibrate&&navigator.vibrate(30),R())},[T,s,R,b]),M=g.useCallback(()=>{_.current&&(_.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),A(),setTimeout(()=>{n()},150))},[A,n]),K=[...t].reverse().find(U=>U.role==="assistant"),ee=((D=K==null?void 0:K.suggestedProducts)==null?void 0:D.length)||0,Z=K!=null&&K.content?K.content.length>50?K.content.slice(0,50)+"...":K.content:"Ask Bob about car parts...",z=ee>0?` (${ee} 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)"}},G={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)"}}[T],L={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:S,style:{position:"fixed",bottom:C,left:0,right:0,...Fa,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:I+80,paddingBottom:"env(safe-area-inset-bottom, 8px)"},children:[o.jsx("button",{onClick:()=>x(!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:I+90,cursor:"pointer",minHeight:"unset",minWidth:"unset"},"aria-label":v?"Collapse chat":"Expand chat",children:v?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"})})}),!v&&o.jsx("div",{onClick:()=>x(!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:[Z,z&&o.jsx("span",{style:{color:"rgba(255,200,0,0.9)",fontWeight:600},children:z})]})}),v&&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((U,Q)=>{var _e;return o.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:U.role==="user"?"flex-end":"flex-start"},children:o.jsxs("div",{style:{maxWidth:(_e=U.suggestedProducts)!=null&&_e.length?"100%":"85%",borderRadius:"16px",padding:"10px 14px",fontSize:"14px",background:U.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:[U.content,U.role==="assistant"&&U.suggestedProducts&&U.suggestedProducts.length>0&&o.jsx(zn,{products:U.suggestedProducts,title:U.suggestionsTitle,onAddToCart:f,onProductClick:p}),U.role==="assistant"&&U.quickReplies&&U.quickReplies.length>0&&o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"8px"},children:U.quickReplies.map((Se,Re)=>o.jsx("button",{onClick:Ne=>{Ne.stopPropagation(),y==null||y(Se.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:Se.label},Re))})]})},Q)}),o.jsx("div",{ref:c})]}),j&&o.jsxs("div",{style:{display:"flex",justifyContent:"center",padding:"12px 16px 8px 16px",position:"relative"},children:[T==="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"}})]}),T!=="listening"&&L[T]&&o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"220px",height:"80px",borderRadius:"40px",border:L[T].border,transform:"translate(-50%, -50%)",animation:L[T].animation,pointerEvents:"none"}}),o.jsx("button",{onTouchStart:F,onTouchEnd:M,onTouchCancel:M,onMouseDown:F,onMouseUp:M,onMouseLeave:M,onClick:O?M:void 0,disabled:T==="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:T==="processing"?"not-allowed":"pointer",opacity:T==="processing"?.6:1,transform:T==="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:G.backdropFilter,WebkitBackdropFilter:G.WebkitBackdropFilter,"--bob-ptt-bg":G.background,"--bob-ptt-shadow":G.boxShadow,"--bob-ptt-border":G.border,"--bob-ptt-radius":"32px"},title:"Hold to talk",children:o.jsx("span",{style:{fontSize:"22px",fontWeight:800,letterSpacing:"0.15em",...is.primary,textTransform:"uppercase",fontFamily:"system-ui, -apple-system, sans-serif"},children:T==="listening"?"LISTENING":T==="processing"?"THINKING":T==="speaking"?"TAP TO STOP":"TALK"})})]}),o.jsxs("div",{style:{padding:"4px 12px 8px 12px",borderTop:"1px solid rgba(255, 255, 255, 0.15)"},children:[B&&o.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:B}),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:U=>r(U.target.value),onKeyPress:i,onFocus:a,onBlur:l,placeholder:"Message Bob...",disabled:T!=="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:T!=="idle"?0:1,transition:"opacity 0.15s ease"}}),T!=="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:[T==="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..."})]}),T==="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."})]}),T==="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((U,Q)=>o.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${U}s infinite`}},Q))}),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"})]})]})]})]})]})]})]})},Wa=({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:f,chatEndRef:p,isMuted:y,onToggleMute:b,isSpeaking:m,products:v,servicePackages:x,highlightedPartType:S,highlightedProduct:_,onProductClick:C,onPackageSelect:I,isResearching:O,onAddToCart:E,onQuickReply:B,onInterrupt:j,vehicle:R,onChangeVehicle:A,pendingVariants:T,pendingVariantMake:F,pendingVariantModel:M,onVariantSelect:K,bobOffset:ee=0,bobScale:Z=100,embedded:z=!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 V=Ks(),[le,G]=g.useState("center"),[L,D]=g.useState("hidden"),U=v.length>0||x.length>0,Q=((T==null?void 0:T.length)??0)>0,_e=U||Q,Ne=(()=>{switch(V){case"desktop":return 70;case"tablet":return 80;case"mobile":return 140;default:return 140}})()*Z/100;g.useEffect(()=>{if(O&&L!=="loading"&&L!=="visible")D("loading"),le==="center"&&G("partial-left");else if(_e&&L!=="visible")if(le==="center"){G("partial-left"),D("transitioning");const Pe=setTimeout(()=>{D("visible")},400);return()=>clearTimeout(Pe)}else D("visible");else!_e&&!O&&L!=="hidden"&&(D("hidden"),G("center"))},[_e,O,L,le]);const Me=L!=="hidden";return o.jsxs("div",{className:z?"absolute inset-0 overflow-hidden":"fixed inset-0 overflow-hidden",style:{height:z?"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(Vs,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:Ne,position:le,verticalOffset:ee}),o.jsx(Gs,{products:v,servicePackages:x,highlightedPartType:S,highlightedProduct:_,onProductClick:C,onPackageSelect:I,isResearching:O,visible:Me,counterHeightPercent:n,hasVehicle:!!R,onAddToCart:E,pendingVariants:T,pendingVariantMake:F,pendingVariantModel:M,onVariantSelect:K}),o.jsx(Ma,{messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:f,chatEndRef:p,isMuted:y,onToggleMute:b,isSpeaking:m,onAddToCart:E,onProductClick:C,onQuickReply:B,onInterrupt:j,counterHeightPercent:n})]})},qa=({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:f,onInterrupt:p,counterHeightPercent:y=22})=>{const[b,m]=g.useState(!1),v=g.useRef(null),x=g.useRef(!1),{bottomOffset:S,zIndexBase:_}=qn(),{isListening:C,interimTranscript:I,error:O,isSupported:E,startListening:B,stopListening:j}=Kn({onTranscript:V=>r(V),language:"en-NZ",mode:"ptt"});g.useEffect(()=>{I&&r(I)},[I,r]);const R=h?"speaking":s?"processing":C?"listening":"idle",A=g.useCallback(V=>{if(V.preventDefault(),R==="speaking"){p==null||p();return}s||x.current||(x.current=!0,navigator.vibrate&&navigator.vibrate(30),B())},[R,s,B,p]),T=g.useCallback(()=>{x.current&&(x.current=!1,navigator.vibrate&&navigator.vibrate([20,50,20]),j(),setTimeout(()=>{n()},150))},[j,n]),F=[...t].reverse().find(V=>V.role==="assistant"),M=F!=null&&F.content?F.content.length>50?F.content.slice(0,50)+"...":F.content:"Ask Bob about car parts...",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:"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:K.idle,listening:K.active,processing:K.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],z={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: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",...Fa,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:_+30,paddingBottom:"calc(8px + env(safe-area-inset-bottom, 0px))",pointerEvents:"none"},children:[o.jsx("button",{onClick:()=>m(!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:_+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:()=>m(!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:M})}),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((V,le)=>o.jsx("div",{style:{display:"flex",justifyContent:V.role==="user"?"flex-end":"flex-start"},children:o.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&&o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"8px"},children:V.quickReplies.map((G,L)=>o.jsx("button",{onClick:D=>{D.stopPropagation(),f==null||f(G.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:G.label},L))})]})},le)),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:[O&&o.jsx("div",{style:{marginBottom:"8px",fontSize:"12px",color:"#FF9500"},children:O}),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:V=>r(V.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((V,le)=>o.jsx("div",{style:{width:"3px",height:"4px",backgroundColor:"#22c55e",borderRadius:"2px",animation:`waveform-bar 0.8s ease-in-out ${V}s infinite`}},le))}),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"&&z[R]&&o.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",width:"84px",height:"84px",borderRadius:"50%",border:z[R].border,transform:"translate(-50%, -50%)",animation:z[R].animation,pointerEvents:"none"}}),o.jsxs("button",{onTouchStart:A,onTouchEnd:T,onTouchCancel:T,onMouseDown:A,onMouseUp:T,onMouseLeave:T,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:_+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:[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"}})]})]})]})]})]})},qu=({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"})})]})},za=({package:t,onBack:e,onAddToCart:r,onNavigateToProductPage:s})=>{var b;const[n,i]=g.useState(!1),[a,l]=g.useState("disc"),c=g.useMemo(()=>$a(t),[t.id,t.title]),u=g.useMemo(()=>{if(!t.preparedTiers||t.preparedTiers.length===0)return[];const m=t.preparedTiers.filter(v=>!v.isHidden);return c?m.map(v=>{const x=Da(v.products,a);return{...v,products:x,totalPrice:Ua(x),productCount:x.length}}):m},[t.preparedTiers,c,a]),d=u.length>0,h=m=>{const v=m.bundleDiscountPercentage||0;if(v>0){const x=1-v/100,S=m.products.map(_=>({..._,displayPrice:Math.round(_.displayPrice*x*100)/100}));r==null||r(S)}else r==null||r(m.products)},f=m=>m===2?"grid-cols-2":m===3?"grid-cols-3":"grid-cols-2",p=Na(t.title),y=((b=u[0])==null?void 0:b.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:p}),c&&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:()=>l("disc"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:a==="disc"?J.primary:"transparent",color:a==="disc"?"#FFFFFF":"#64748B"},children:"Disc Brakes (Pads + Rotors)"}),o.jsx("button",{onClick:()=>l("drum"),className:"flex-1 py-2 px-3 text-xs font-semibold transition-all",style:{background:a==="drum"?J.primary:"transparent",color:a==="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:d?o.jsx("div",{className:`grid ${f(u.length)} gap-3`,children:u.map(m=>{const v=Us[m.tierName];return o.jsxs("div",{className:"relative rounded-2xl overflow-hidden bg-white shadow-md flex flex-col",style:{border:m.isRecommended?"2px solid #0052CC":"1px solid #E2E8F0"},children:[m.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:J.primary},children:"★ CARFIX VALUE"}),o.jsxs("div",{className:`p-3 flex-1 flex flex-col ${m.isRecommended?"pt-7":""}`,children:[o.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[o.jsx("span",{className:"text-lg",children:v==null?void 0:v.emoji}),o.jsxs("div",{children:[o.jsx("span",{className:"font-bold text-sm block",style:{color:(v==null?void 0:v.textColor)||J.foreground},children:m.displayName}),o.jsx("span",{className:"text-[10px] text-[#64748B] hidden md:block",children:m.description||(v==null?void 0:v.description)})]})]}),o.jsx("div",{className:"flex items-center gap-1.5 mb-3 min-h-[42px] flex-wrap",children:m.brands.slice(0,3).map(x=>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:x.imageUrl,alt:x.fullName,className:"h-6 w-auto object-contain",onError:S=>{const _=S.target,C=`${gs.storageBase}/brand_images/${x.fullName.replace(/\s+/g,"")}.jpg`;if(_.src!==C)_.src=C;else{const I=_.parentElement;I&&(I.innerHTML=`<span class="text-[10px] font-medium text-slate-700 px-1 truncate max-w-[60px]">${x.name}</span>`)}}})},x.name))}),o.jsxs("p",{className:"text-xs text-[#64748B] hidden md:block mb-2",children:[m.productCount," part",m.productCount!==1?"s":""," included"]}),o.jsx("div",{className:"mt-auto",children:m.savingsAmount&&m.savingsAmount>0?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-xs line-through text-[#94A3B8]",children:Qe(m.originalTotalPrice)}),o.jsx("p",{className:"text-xl font-bold",style:{color:"#22C55E"},children:Qe(m.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 ",Qe(m.savingsAmount)," — ",m.bundleDiscountPercentage,"% Bundle Deal"]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-xl font-bold",style:{color:m.isRecommended?"#0052CC":"#0F172A"},children:Qe(m.totalPrice)}),o.jsx("p",{className:"text-[10px] text-[#64748B] hidden md:block",children:"inc GST"})]})}),o.jsx("button",{onClick:()=>h(m),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 ${m.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"})]})]},m.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"})]})}),d&&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:[y," product",y!==1?"s":""]})]}),n&&o.jsx("div",{className:"mt-3 space-y-4 bg-white rounded-xl border border-[#E2E8F0] p-3",children:u.map(m=>{if(m.products.length===0)return null;const v=Us[m.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:v==null?void 0:v.emoji}),o.jsx("span",{className:"font-semibold text-sm",style:{color:v==null?void 0:v.textColor},children:m.displayName}),o.jsxs("span",{className:"text-xs text-[#64748B]",children:["(",m.products.length," parts)"]})]}),o.jsx("div",{className:"space-y-2",children:m.products.map((x,S)=>{var I;const _=(I=t.carfixValueProducts)==null?void 0:I.includes(x.sku),C=x.unitPrice??x.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(x.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:x.productImageUrl||gs.productImage(x.sku),alt:x.name,className:"object-contain",style:{width:"100%",height:"100%",maxWidth:"56px",maxHeight:"56px",padding:"6px"},onError:O=>{O.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:x.brandFullName||x.brand}),_&&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"}),x.isMultiQty&&x.perCarQty>1&&o.jsxs("span",{className:"px-1.5 py-0.5 text-[8px] font-bold rounded-full",style:{background:"#F0FDF4",color:"#15803D"},children:["×",x.perCarQty]}),x.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:x.name})]}),o.jsxs("div",{className:"text-right flex-shrink-0",children:[o.jsx("p",{className:"text-sm font-bold text-[#0F172A]",children:Qe(x.displayPrice)}),x.isMultiQty&&x.perCarQty>1&&o.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[x.perCarQty,"× ",Qe(C)," each"]}),x.isRotor&&!x.isMultiQty&&o.jsxs("p",{className:"text-[10px] text-[#64748B]",children:[Qe(C)," each"]})]})]},`${x.sku}-${S}`)})})]},m.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,"%"]})})})]})]})},Ha=({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:f,chatEndRef:p,isMuted:y,onToggleMute:b,isSpeaking:m,products:v,servicePackages:x,highlightedPartType:S,highlightedProduct:_,onProductClick:C,onPackageSelect:I,isResearching:O,onAddToCart:E,onNavigateToProductPage:B,onQuickReply:j,onInterrupt:R,vehicle:A,onChangeVehicle:T,pendingVariants:F,pendingVariantMake:M,pendingVariantModel:K,onVariantSelect:ee,bobOffset:Z=0,bobScale:z=100})=>{const[V,le]=g.useState("center"),[G,L]=g.useState("hidden"),[D,U]=g.useState("products"),[Q,_e]=g.useState(null),[Se,Re]=g.useState(null),Ne=v.length>0||x.length>0,Me=((F==null?void 0:F.length)??0)>0,Pe=Ne||Me,P=(D==="productDetail"?70:V==="center"&&!Pe?140:98)*z/100;g.useEffect(()=>{if(O&&G!=="loading"&&G!=="visible")L("loading"),V==="center"&&le("partial-left");else if(Pe&&G!=="visible")if(V==="center"){le("partial-left"),L("transitioning");const Te=setTimeout(()=>{L("visible")},400);return()=>clearTimeout(Te)}else L("visible");else!Pe&&!O&&G!=="hidden"&&(L("hidden"),le("center"))},[Pe,O,G,V]);const X=Te=>{if(B){B(Te),C==null||C(Te);return}_e(Te),U("productDetail"),C==null||C(Te)},ce=()=>{_e(null),Re(null),U("products")},me=Te=>{console.log("[ContainedMobileBobLayout] Package selected:",Te.title),Re(Te),U("packageDetail"),I==null||I(Te)},ze=G!=="hidden"&&D==="products",ie=G!=="hidden";return o.jsxs("div",{className:"absolute inset-0",style:{overflow:"clip",isolation:"isolate"},onContextMenu:Te=>Te.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:ie?"blur(var(--bob-blur-intensity, 0px)) brightness(0.95)":"none",transform:ie?"scale(1.02)":"scale(1)",WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"}}),o.jsx(Vs,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:P,position:V,verticalOffset:Z}),o.jsx(Gs,{products:v,servicePackages:x,highlightedPartType:S,highlightedProduct:_,onProductClick:X,onPackageSelect:me,isResearching:O,visible:ze,counterHeightPercent:n,hasVehicle:!!A,onAddToCart:E,vehicleMakeModel:A?`${A.make||""} ${A.model||""}`.trim():void 0,pendingVariants:F,pendingVariantMake:M,pendingVariantModel:K,onVariantSelect:ee}),D==="productDetail"&&Q&&o.jsx(qu,{product:Q,onBack:ce,onAddToCart:E,onNavigateToProductPage:B}),D==="packageDetail"&&Se&&o.jsx(za,{package:Se,onBack:ce,onAddToCart:Te=>{Te.forEach(ue=>{var Gt;E==null||E({id:ue.sku||((Gt=ue.partslotId)==null?void 0:Gt.toString())||"unknown",name:ue.name||ue.partslotName||"Unknown Part",brand:ue.brand,price:ue.displayPrice,sku:ue.sku,partNumber:ue.partNumber,image_url:ue.productImageUrl,partslotDescription:ue.partslotName})})},onNavigateToProductPage:Te=>{const ue=v.find(Gt=>Gt.sku===Te);ue&&B&&B(ue)}}),D==="products"&&o.jsx(qa,{messages:i,input:a,setInput:l,isLoading:c,onSend:u,onKeyPress:d,onInputFocus:h,onInputBlur:f,chatEndRef:p,isMuted:y,onToggleMute:b,isSpeaking:m,onQuickReply:j,onInterrupt:R,counterHeightPercent:n})]})},Vn=({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})=>{var qe,ft;const{callbacks:f}=Pt(),[p,y]=g.useState(!1),{animationState:b,setAnimationState:m,getCurrentImage:v,getCurrentOffset:x,getCurrentScale:S,availableStates:_}=Ra({isSpeaking:p}),{activeBackdrop:C}=Ca(),[I,O]=g.useState([]),[E,B]=g.useState([]),[j,R]=g.useState(null),[A,T]=g.useState(null),[F,M]=g.useState(!1),[K,ee]=g.useState([]),[Z,z]=g.useState(""),[V,le]=g.useState(""),G=g.useRef(null),L=g.useRef(null);g.useEffect(()=>{G.current=P=>{if(M(!1),!P||P.length===0){console.log("[Bob] Clearing products (empty array received)"),O([]);return}const X=P[0];console.log("[Bob] First part raw keys:",Object.keys(X));const ce=P.map((ie,Te)=>{const ue=ie.Brand||ie.brand||"";return{id:ie.SKU||ie.sku||`part-${Te}`,name:ie["Part Product Type"]||ie.partslot_description||ie.name||"Unknown Part",brand:ue,price:ie["Metro Retail Price"]||ie.price||0,sku:ie.SKU||ie.sku,partNumber:ie["Part Number"]||ie.part_number||null,partslotDescription:ie["Part Product Type"]||ie.partslot_description||ie.partslotDescription||ie.part_type||ie.category||"General Parts",image_url:ie.image_url||(ie.SKU||ie.sku?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/product_images/${ie.SKU||ie.sku}.jpg`:void 0),webDescription:ie["Web Part Description"]||ie.web_description||null,brandDescription:ie["Brand Description"]||ie.brand_description||null,perCarQty:ie["Per Car Qty"]||ie.per_car_qty||1,volume:ie.volume||null,viscosity:ie.viscosity||null,brandImageUrl:ue?`https://flpzjbasdsfwoeruyxgp.supabase.co/storage/v1/object/public/brand_images/${ue.replace(/\s+/g,"")}.jpg`:void 0}}),me=new Set,ze=ce.filter(ie=>!ie.sku||me.has(ie.sku)?!1:(me.add(ie.sku),!0));console.log("[Bob] Products mapped:",ce.length,"-> deduped:",ze.length),O(ze)},L.current=P=>{if(!P||P.length===0){console.log("[Bob] Clearing service packages (empty array received)"),B([]);return}console.log("[Bob] Service packages received via stable ref:",P.length),B(P)}},[]);const D=ja({setAnimationState:m,manualMode:!1,onReadyToSpeak:()=>{console.log("[BobWidget] Ready to speak")},onStreamComplete:()=>{m(_.find(P=>P.includes("idle"))||"idle")},onResearchStart:()=>{M(!0)},onVariantSelectionRequired:(P,X,ce)=>{M(!1),ee(P),z(X),le(ce)},onHighlightPart:P=>{R(P),setTimeout(()=>R(null),8e3)},onHighlightProduct:P=>{T(P),setTimeout(()=>T(null),8e3)},onAutoFetchComplete:()=>{M(!1)}});g.useEffect(()=>{D.identifiedVehicle&&(ee([]),z(""),le(""))},[(qe=D.identifiedVehicle)==null?void 0:qe.vehicle_id,(ft=D.identifiedVehicle)==null?void 0:ft.id]);const U=P=>{D.sendDirectMessage(`Option ${P.optionNumber}`)};g.useEffect(()=>{y(D.isSpeaking)},[D.isSpeaking]),g.useEffect(()=>{const P=f.onPartsFound,X=f.onServicePackagesFound;return f.onPartsFound=ce=>{var me;(me=G.current)==null||me.call(G,ce),P==null||P(ce)},f.onServicePackagesFound=ce=>{var me;(me=L.current)==null||me.call(L,ce),X==null||X(ce)},()=>{f.onPartsFound=P,f.onServicePackagesFound=X}},[f]);const Q=n||(C==null?void 0:C.image_url),_e=i||(C==null?void 0:C.counter_overlay_url)||void 0,Se=a||(C==null?void 0:C.counter_height_percent)||12,Re=v()||l||"",Ne=x(),Me=S();if(t==="mobile"||t==="fullscreen")return o.jsx(Wa,{currentImage:Re,animationState:b,backdropUrl:Q,counterOverlayUrl:_e,counterHeightPercent:Se,bobOffset:Ne,bobScale:Me,embedded:h,messages:D.messages,input:D.input,setInput:D.setInput,isLoading:D.isLoading,onSend:D.handleSend,onKeyPress:D.handleKeyPress,onInputFocus:D.handleInputFocus,onInputBlur:D.handleInputBlur,chatEndRef:D.chatEndRef,isMuted:D.isMuted,onToggleMute:D.toggleMute,isSpeaking:D.isSpeaking,products:I,servicePackages:E,highlightedPartType:j,highlightedProduct:A,onAddToCart:P=>{(Array.isArray(P)?P:[P]).forEach(ce=>{var me;(me=f.onAddToCart)==null||me.call(f,{product_id:ce.id,product_name:ce.name,quantity:ce.quantity||1,unit_price:ce.price,sku:ce.sku,brand:ce.brand,image_url:ce.image_url})})},onNavigateToProductPage:P=>{var X;return(X=f.onNavigateToProductPage)==null?void 0:X.call(f,P)},onQuickReply:P=>{var X;return(X=f.onNavigateToProductPage)==null?void 0:X.call(f,{url:P})},onPackageSelect:P=>console.log("[BobWidget] Package selected:",P),isResearching:F,vehicle:D.identifiedVehicle,pendingVariants:K,pendingVariantMake:Z,pendingVariantModel:V,onVariantSelect:U,onInterrupt:D.stopAllAudio});if(t==="inline"&&r)return o.jsx("div",{className:`relative w-full h-full ${s}`,children:o.jsx(Ha,{currentImage:Re,animationState:b,backdropUrl:Q,counterOverlayUrl:_e,counterHeightPercent:Se,bobOffset:Ne,bobScale:Me,messages:D.messages,input:D.input,setInput:D.setInput,isLoading:D.isLoading,onSend:D.handleSend,onKeyPress:D.handleKeyPress,onInputFocus:D.handleInputFocus,onInputBlur:D.handleInputBlur,chatEndRef:D.chatEndRef,isMuted:D.isMuted,onToggleMute:D.toggleMute,isSpeaking:D.isSpeaking,products:I,servicePackages:E,highlightedPartType:j,highlightedProduct:A,onAddToCart:P=>{(Array.isArray(P)?P:[P]).forEach(ce=>{var me;(me=f.onAddToCart)==null||me.call(f,{product_id:ce.id,product_name:ce.name,quantity:ce.quantity||1,unit_price:ce.price,sku:ce.sku,brand:ce.brand,image_url:ce.image_url})})},onNavigateToProductPage:P=>{var X;return(X=f.onNavigateToProductPage)==null?void 0:X.call(f,P)},onQuickReply:P=>{var X;return(X=f.onNavigateToProductPage)==null?void 0:X.call(f,{url:P})},onPackageSelect:P=>console.log("[BobWidget] Package selected:",P),isResearching:F,vehicle:D.identifiedVehicle,pendingVariants:K,pendingVariantMake:Z,pendingVariantModel:V,onVariantSelect:U,onInterrupt:D.stopAllAudio})});const Pe={inline:"",floating:"fixed bottom-4 right-4 w-96 z-50 shadow-2xl rounded-lg overflow-hidden"};return o.jsxs("div",{className:`${Pe[t]||""} ${s}`,children:[Re&&o.jsx(Aa,{currentImage:Re,animationState:b,backdropUrl:Q,counterOverlayUrl:_e,counterHeightPercent:Se,verticalOffset:Ne,scale:Me}),r&&o.jsx(Ba,{messages:D.messages,input:D.input,setInput:D.setInput,isLoading:D.isLoading,onSend:D.handleSend,onKeyPress:D.handleKeyPress,onInputFocus:D.handleInputFocus,onInputBlur:D.handleInputBlur,chatEndRef:D.chatEndRef,isMuted:D.isMuted,onToggleMute:D.toggleMute,isSpeaking:D.isSpeaking})]})},Ka=(t=!0)=>{const[e,r]=g.useState("prompt"),s=g.useRef(!1);return g.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}},zu=({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:f,scale:p,ga4Config:y,analyticsEnabled:b=!0,bottomOffset:m=0,zIndexBase:v=50,embedded:x=!1})=>{const{micPermission:S}=Ka(!0);return g.useEffect(()=>{console.log("[BobWidget] Initialized",{version:At,variant:n,bottomOffset:m,zIndexBase:v,bobConfigUrl:t.supabaseUrl,hostApiBaseUrl:e.baseUrl,analyticsEnabled:b,micPermission:S})},[n,m,v,t.supabaseUrl,e.baseUrl,b,S]),o.jsx("div",{className:"bob-widget-root",style:{width:"100%",height:"100%"},children:o.jsx(Wn,{bobConfig:t,hostApiConfig:e,hostContext:r,callbacks:s,ga4Config:y,analyticsEnabled:b,bottomOffset:m,zIndexBase:v,children:o.jsx(Vn,{variant:n,initialState:i,showChat:a,className:l,backdropUrl:c,counterOverlayUrl:u,counterHeightPercent:d,defaultBobImage:h,verticalOffset:f,scale:p,embedded:x})})})};function Hu(t){return t<640?"mobile":t<1024?"tablet":"desktop"}function Ku(){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 Va=({partnerConfig:t,sessionToken:e})=>{const[r,s]=g.useState(null),[n,i]=g.useState([]),[a,l]=g.useState(!1);if(g.useEffect(()=>{const u=()=>{var f;const d=window.innerWidth,h=window.innerHeight;s({viewport:{width:d,height:h,deviceType:Hu(d)},origin:window.location.origin,originAllowed:((f=t==null?void 0:t.allowed_origins)==null?void 0:f.some(p=>p===window.location.origin||p.includes("*")))??!1,userAgent:navigator.userAgent.slice(0,50)+"...",timestamp:new Date().toISOString()}),i(Ku())};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",At]})]}),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(jr,{label:"Viewport",value:`${r.viewport.width}×${r.viewport.height} (${r.viewport.deviceType})`}),o.jsx(jr,{label:"Origin",value:r.origin}),o.jsx(jr,{label:"Bottom Offset",value:`${(t==null?void 0:t.default_bottom_offset)??0}px`}),o.jsx(jr,{label:"Z-Index Base",value:`${(t==null?void 0:t.default_z_index_base)??50}`}),o.jsx(jr,{label:"Blur",value:`${(t==null?void 0:t.backdrop_blur_intensity)??8}px`}),o.jsx(jr,{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})]})]})},jr=({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})]}),Fi="https://gjoguxzstsihhxvdgpto.supabase.co",Li="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imdqb2d1eHpzdHNpaGh4dmRncHRvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjM5MzgyODEsImV4cCI6MjA3OTUxNDI4MX0.detu4TKB7RjC6l6CrVaPYoi0Hhz2asDt6zxNx1cdzq8";function Vu(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 Ga(t){const[e,r]=g.useState(null),[s,n]=g.useState(!0),[i,a]=g.useState(null),[l,c]=g.useState(!1),[u,d]=g.useState(null),h=g.useCallback(async()=>{if(!t){n(!1),a(new Error("Partner code is required"));return}n(!0),a(null);try{const f=wn(Fi,Li);console.log(`[BobWidget] Loading partner config for: ${t}`);const{data:p,error:y}=await f.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(!p)throw new Error(`Partner "${t}" not found or inactive`);const b=p,m=typeof window<"u"?window.location.origin:"",v=Vu(b.allowed_origins||[],m);!v&&m&&(console.warn(`[BobWidget] Origin "${m}" not in allowed origins for ${t}`),console.warn("[BobWidget] Allowed origins:",b.allowed_origins));const x=wn(b.bob_supabase_url||Fi,b.bob_supabase_key||Li,{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(x)}catch(f){const p=f instanceof Error?f:new Error("Unknown error loading partner config");console.error("[BobWidget] Partner config error:",p),a(p)}finally{n(!1)}},[t]);return g.useEffect(()=>{h()},[h]),{config:e,isLoading:s,error:i,isOriginAllowed:l,supabaseClient:u,reload:h}}function Ja(t,e,r){return t!=null&&t.feature_flags?t.feature_flags[e]??r:r}const Gu=()=>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:`
|
|
76
76
|
@keyframes spin {
|
|
77
77
|
to { transform: rotate(360deg); }
|
|
78
78
|
}
|
|
79
|
-
`})]}),
|
|
79
|
+
`})]}),Ju=({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"]})]})}),Qu=g.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=""},f)=>{const p=g.useRef(null);g.useImperativeHandle(f,()=>({stopSpeech:()=>{var O;return(O=p.current)==null?void 0:O.call(p)},interrupt:()=>{var O;return(O=p.current)==null?void 0:O.call(p)}}));const{config:y,isLoading:b,error:m,supabaseClient:v}=Ga(t);g.useEffect(()=>{console.log("[BobStandalone] Initialized",{version:At,partner:t,sessionToken:e?"present":"none",debug:d})},[t,e,d]);const x=g.useMemo(()=>({onAddToCart:a?O=>a(O):void 0,onCheckoutRequested:c,onError:u,onNavigateToProductPage:l?O=>{const E=O;E!=null&&E.url?l(E.url):E!=null&&E.sku&&l(`/product/${E.sku}`)}:void 0,onStopSpeechReady:O=>{p.current=O}}),[a,l,c,u]),S=g.useMemo(()=>({}),[]);if(b)return o.jsx(Gu,{});if(m||!y||!v){const O=m||new Error("Failed to initialize Bob");return u==null||u(O),o.jsx(Ju,{error:O,partner:t})}const _=r??y.default_bottom_offset,C=s??y.default_z_index_base,I=d||Ja(y,"showDebugOverlay",!1);return o.jsx("div",{className:`bob-widget-root ${h}`,style:{width:"100%",height:"100%","--bob-blur-intensity":`${n??y.backdrop_blur_intensity}px`,"--bob-overlay-opacity":i??y.backdrop_overlay_opacity,"--bob-z-base":C},children:o.jsxs(Wn,{bobConfig:{supabaseUrl:y.bob_supabase_url,supabaseKey:y.bob_supabase_key},hostApiConfig:{baseUrl:y.api_base_url,apiKey:"",partnerCode:y.partner_code},hostContext:S,callbacks:x,bottomOffset:_,zIndexBase:C,children:[o.jsx(Vn,{variant:"inline",sessionToken:e}),I&&o.jsx(Va,{partnerConfig:y,sessionToken:e})]})})}),Yu=({children:t,isSpeaking:e=!1,hasProducts:r=!1,onVisibilityChange:s,onPositionChange:n,currentPosition:i="center"})=>{const[a,l]=g.useState(!1),[c,u]=g.useState(0),d=g.useRef(null),h=g.useRef(0),f=g.useRef(0),p=g.useRef(!1),y=.25;g.useEffect(()=>{e&&i==="hidden"&&(n==null||n("partial-left"),s==null||s(!0))},[e,i,n,s]);const b=g.useCallback(_=>{h.current=_.touches[0].clientX,f.current=_.touches[0].clientY,p.current=!1,l(!0)},[]),m=g.useCallback(_=>{if(!a)return;const C=_.touches[0].clientX,I=_.touches[0].clientY,O=C-h.current,E=I-f.current;!p.current&&Math.abs(O)>10&&(p.current=Math.abs(O)>Math.abs(E)),p.current&&(_.preventDefault(),u(O))},[a]),v=g.useCallback(()=>{var E;if(!a)return;l(!1);const _=((E=d.current)==null?void 0:E.offsetWidth)||300,C=Math.abs(c)/_,I=c<0,O=c>0;I?i==="center"&&C>y?(n==null||n("partial-left"),s==null||s(!0)):i==="partial-left"&&C>y&&(n==null||n("hidden"),s==null||s(!1)):O&&(i==="hidden"&&C>y?(n==null||n("partial-left"),s==null||s(!0)):i==="partial-left"&&C>y&&!r&&(n==null||n("center"),s==null||s(!0))),u(0)},[a,c,i,r,n,s]),x=g.useCallback(()=>{n==null||n("partial-left"),s==null||s(!0)},[n,s]),S=()=>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:S(),transition:a?"none":"transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)",willChange:"transform"},onTouchStart:b,onTouchMove:m,onTouchEnd:v,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:x,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
80
|
@keyframes slideInFromLeft {
|
|
81
81
|
from {
|
|
82
82
|
transform: translateX(-100%) translateY(-50%);
|
|
@@ -98,4 +98,4 @@ ${y}`}class Ie extends Error{constructor({message:e,code:r,cause:s,name:n}){var
|
|
|
98
98
|
transform: translateX(-10px) translateY(-50%);
|
|
99
99
|
}
|
|
100
100
|
}
|
|
101
|
-
`})]})},Nt={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 Yr(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=f=>Math.round((f+l)*255).toString(16).padStart(2,"0");return`#${h(c)}${h(u)}${h(d)}`}function Va(){const t=pr();return xs({queryKey:["bob-theme-settings"],queryFn:async()=>{var d,h,f,p,v,m,b,y,_,k,w;if(!t)return console.log("[useThemeSettings] No supabase client, using defaults"),Nt;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),Nt;if(!e||e.length===0)return Nt;const s=new Map(e.map(E=>[E.setting_key,E])),n=((d=s.get("matrix_primary"))==null?void 0:d.color_value)||Nt.primary,i=((h=s.get("matrix_secondary"))==null?void 0:h.color_value)||Nt.secondary,a=((f=s.get("matrix_success"))==null?void 0:f.color_value)||Nt.success,l=((p=s.get("matrix_background"))==null?void 0:p.color_value)||Nt.background,c=((v=s.get("matrix_spark_deal_color"))==null?void 0:v.color_value)||Nt.sparkDealColor,u=((m=s.get("matrix_background_mode"))==null?void 0:m.color_value)||"dark";return{primary:n,secondary:i,success:a,background:l,backgroundMode:u,sparkDealColor:c,primaryHex:((b=s.get("matrix_primary"))==null?void 0:b.hex_preview)||Yr(n),secondaryHex:((y=s.get("matrix_secondary"))==null?void 0:y.hex_preview)||Yr(i),successHex:((_=s.get("matrix_success"))==null?void 0:_.hex_preview)||Yr(a),backgroundHex:((k=s.get("matrix_background"))==null?void 0:k.hex_preview)||Yr(l),sparkDealHex:((w=s.get("matrix_spark_deal_color"))==null?void 0:w.hex_preview)||Yr(c)}},staleTime:60*1e3,gcTime:5*60*1e3})}const nn={enabled:!0,inRain:!0,rainFrequency:.15,primingEnabled:!0,bannerEnabled:!0,delayMs:2e3,scrollSpeed:5e3,maxPerSession:3,minResearchTime:1500,bobCommentary:!1};function Ju(){const t=pr();return xs({queryKey:["spark-deals-settings"],queryFn:async()=>{if(!t)return nn;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),nn;if(!e||e.length===0)return nn;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 Ga(t=!0){const e=pr();return xs({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 Qu(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 Ja=({deals:t,currentDealIndex:e,onDealChange:r,onDealClick:s,scrollSpeed:n,theme:i})=>{const[a,l]=g.useState(!1),[c,u]=g.useState(100),d=t[e],h=i.sparkDealHex||"#FF9500",f=i.backgroundMode!=="light";g.useEffect(()=>{if(!d)return;l(!0),u(100);const m=setTimeout(()=>{u(0)},50),b=setTimeout(()=>{u(-100)},n-500),y=setTimeout(()=>{const _=(e+1)%t.length;r(_),l(!1)},n);return()=>{clearTimeout(m),clearTimeout(b),clearTimeout(y)}},[e,d,n,t.length,r]);const p=g.useCallback(()=>{d&&s(d)},[d,s]);if(!d)return null;const v=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:p,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:f?"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"}),v&&v>0&&o.jsxs("span",{className:"text-xs font-bold px-2 py-0.5 rounded-full",style:{background:h,color:f?"#000":"#fff"},children:[v,"% OFF"]})]}),o.jsxs("p",{className:"text-sm font-semibold truncate max-w-[200px]",style:{color:f?"#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:f?"#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((m,b)=>o.jsx("div",{className:"w-1.5 h-1.5 rounded-full transition-all",style:{background:b===e?h:`${h}40`,transform:b===e?"scale(1.3)":"scale(1)"}},b))})]})},Fi=["*",":","=",">","<","+","-","|","•","○","●","◆","◇","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","#","@","$","%","&","~","^","/","\\","[","]","{","}"],Li=["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"],Yu=({phase:t,message:e,onComplete:r,onSparkDealClick:s,subliminalBrands:n=[]})=>{const i=g.useRef(null),a=g.useRef(),l=g.useRef([]),c=g.useRef(0),[u,d]=g.useState(0),[h,f]=g.useState(!1),[p,v]=g.useState(0),{data:m}=Va(),{data:b}=Ju(),{data:y}=Ga(t!=="hidden"&&(b==null?void 0:b.enabled)),_=m||{primaryHex:"#0066CC",secondaryHex:"#004999",successHex:"#FF9500",backgroundHex:"#111827",sparkDealHex:"#FF9500",backgroundMode:"dark"},k=b||{enabled:!0,inRain:!0,rainFrequency:.15,primingEnabled:!0,bannerEnabled:!0,delayMs:2e3,scrollSpeed:5e3,maxPerSession:3,minResearchTime:1500},w=y&&k.inRain?[...Qu(y),...n]:n,E=.08,A=g.useCallback(()=>w.length>0&&Math.random()<E?{char:w[Math.floor(Math.random()*w.length)],isSubliminal:!0}:Math.random()<.15?{char:Li[Math.floor(Math.random()*Li.length)],isSubliminal:!1}:{char:Fi[Math.floor(Math.random()*Fi.length)],isSubliminal:!1},[w]),F=g.useCallback((R,T)=>R.isSubliminal?_.sparkDealHex:t==="success"?_.successHex:Math.sin(T*2+R.x*.01)*.5+.5>.5?_.primaryHex:_.secondaryHex,[t,_]),N=g.useCallback((R,T)=>{const C=[],B=Math.floor(R/25);for(let K=0;K<B;K++){const{char:Y,isSubliminal:te}=A();C.push({x:K*25+12,y:Math.random()*T,speed:1.5+Math.random()*3.5,char:Y,isSubliminal:te,opacity:.2+Math.random()*.6,size:te?13:9+Math.random()*3,glowIntensity:te?.6:0,changeCounter:Math.floor(Math.random()*30)})}l.current=C},[A]);g.useEffect(()=>{if(t==="hidden"){a.current&&cancelAnimationFrame(a.current);return}const R=i.current;if(!R)return;const T=R.getContext("2d");if(!T)return;const C=()=>{R.width=R.offsetWidth*window.devicePixelRatio,R.height=R.offsetHeight*window.devicePixelRatio,T.scale(window.devicePixelRatio,window.devicePixelRatio),N(R.offsetWidth,R.offsetHeight)};C(),c.current=Date.now();const B=()=>{const K=R.offsetWidth,Y=R.offsetHeight,$=(Date.now()-c.current)/1e3;if(T.clearRect(0,0,K,Y),l.current.forEach(M=>{const J=F(M,$);if(T.font=`bold ${M.size}px monospace`,T.fillStyle=J,T.globalAlpha=M.opacity,M.isSubliminal&&M.glowIntensity>0?(T.shadowColor=_.sparkDealHex,T.shadowBlur=8*M.glowIntensity):T.shadowBlur=0,T.fillText(M.char,M.x,M.y),M.y+=M.speed,M.changeCounter++,M.changeCounter>20+Math.random()*40){const{char:oe,isSubliminal:X}=A();M.char=oe,M.isSubliminal=X,M.size=X?13:9+Math.random()*3,M.glowIntensity=X?.6:0,M.changeCounter=0}if(M.y>Y+20){const{char:oe,isSubliminal:X}=A();M.y=-20,M.char=oe,M.isSubliminal=X,M.speed=1.5+Math.random()*3.5,M.opacity=.2+Math.random()*.6,M.size=X?13:9+Math.random()*3,M.glowIntensity=X?.6:0,M.changeCounter=0}}),T.globalAlpha=1,T.shadowBlur=0,t==="success"){const M=Math.max(0,1-$*2);M>0&&(T.fillStyle=`rgba(255, 149, 0, ${M*.3})`,T.fillRect(0,0,K,Y)),$>.5&&r&&r()}a.current=requestAnimationFrame(B)};return B(),window.addEventListener("resize",C),()=>{a.current&&cancelAnimationFrame(a.current),window.removeEventListener("resize",C)}},[t,_,A,F,N,r]),g.useEffect(()=>{if(t==="hidden"||!y||y.length===0||!k.bannerEnabled){f(!1);return}if(p>=k.maxPerSession)return;const R=setTimeout(()=>{f(!0)},k.delayMs);return()=>clearTimeout(R)},[t,y,k,p]);const U=g.useCallback(R=>{d(R),v(T=>T+1)},[]),j=g.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(Ja,{deals:y.slice(0,k.maxPerSession),currentDealIndex:u,onDealChange:U,onDealClick:j,scrollSpeed:k.scrollSpeed,theme:_})]})},Xu=({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:f,onChangeVehicle:p,bobOffset:v=0,bobScale:m=100,bobHasArrived:b=!0,externalBobPosition:y,onBobPositionChange:_,pendingVariants:k,pendingVariantMake:w,pendingVariantModel:E,onVariantSelect:A})=>{const F=zs(),N=Wn(),[U,j]=g.useState("center"),[R,T]=g.useState("hidden"),C=y??U,B=g.useCallback(P=>{j(P),_==null||_(P)},[_]),K=i.length>0||a.length>0,Y=((k==null?void 0:k.length)??0)>0,te=K||Y,J=(()=>{switch(F){case"desktop":return 80*N.uiScale;case"tablet":return 90*N.uiScale;case"mobile":return 140;default:return 140}})()*m/100;g.useEffect(()=>{if(h&&R!=="loading"&&R!=="visible")T("loading"),C==="center"&&B("partial-left");else if(te&&R!=="visible")if(C==="center"){B("partial-left"),T("transitioning");const P=setTimeout(()=>{T("visible")},400);return()=>clearTimeout(P)}else T("visible");else!te&&!h&&R!=="hidden"&&(T("hidden"),B("center"))},[te,h,R,C,B]);const oe=R!=="hidden",X=oe&&te;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:X?"blur(var(--bob-blur-intensity, 0px))":"none",transform:X?"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:X?1:0}})]}),o.jsx(Hs,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:J,position:C,verticalOffset:v,hasArrived:b}),o.jsx(Ks,{products:i,servicePackages:a,highlightedPartType:l,highlightedProduct:c,onProductClick:u,onPackageSelect:d,isResearching:h,visible:oe,counterHeightPercent:n,hasVehicle:!!f,pendingVariants:k,pendingVariantMake:w,pendingVariantModel:E,onVariantSelect:A})]})},Zu=6e4,ed=({states:t,setAnimationState:e,manualMode:r})=>{const[s,n]=g.useState("page_load"),[i,a]=g.useState(!1),l=g.useRef(null),c=g.useCallback(j=>{const R=t.find(T=>T.chat_trigger===j&&T.is_active);return console.log(`[StateTransitions] Looking for trigger: "${j}" -> found:`,(R==null?void 0:R.state_key)||"none"),R},[t]),u=g.useCallback(()=>t.find(j=>j.chat_trigger==="processing_input"||j.state_key==="research"||j.state_key==="researching"||j.title.toLowerCase().includes("research")||j.title.toLowerCase().includes("thinking")),[t]),d=g.useCallback(()=>t.find(j=>j.chat_trigger==="streaming_response"||j.state_key==="talk"||j.state_key==="talking"||j.title.toLowerCase().includes("talk")),[t]),h=g.useCallback(()=>t.find(j=>j.chat_trigger==="awaiting_input"||j.state_key==="talk_pause"||j.state_key==="listening"||j.title.toLowerCase().includes("listen")||j.title.toLowerCase().includes("pause")),[t]),f=g.useCallback(()=>{const j=t.find(R=>R.chat_trigger==="response_complete"||R.state_key==="complete"||R.title.toLowerCase().includes("complete"));return j||t.find(R=>R.state_key==="idle"||R.title.toLowerCase().includes("idle"))},[t]),p=g.useCallback(()=>t.find(j=>j.chat_trigger==="idle"||j.state_key==="idle"||j.title.toLowerCase().includes("idle")),[t]),v=g.useCallback(j=>{const R=t.find(T=>T.state_key===j);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]),m=g.useCallback(()=>{l.current&&(clearTimeout(l.current),l.current=null)},[]),b=g.useCallback(()=>{m(),!r&&(l.current=setTimeout(()=>{const j=p();j&&(n("idle"),e(j.state_key))},Zu))},[r,p,e,m]),y=g.useCallback(j=>{if(r)return;const R=c(j);R&&e(R.state_key)},[r,c,e]),_=g.useCallback(()=>{if(r)return;const j=h();j&&(n("awaiting_input"),e(j.state_key),b())},[r,h,e,b]),k=g.useCallback(()=>{i||r||(a(!0),n("page_load"),y("page_load"),setTimeout(()=>{_()},3e3))},[i,r,y,_]),w=g.useCallback(()=>{if(r)return;m(),n("processing_input");const j=u();console.log("[StateTransitions] User input - switching to RESEARCH:",j==null?void 0:j.state_key),j?e(j.state_key):y("processing_input")},[r,m,u,e,y]),E=g.useCallback(()=>{if(r)return;m(),n("streaming_response");const j=d();console.log("[StateTransitions] Speech started - switching to TALK:",j==null?void 0:j.state_key),j&&e(j.state_key)},[r,m,d,e]),A=g.useCallback(()=>{if(r)return;const j=f();console.log("[StateTransitions] Speech ended - switching to COMPLETE:",j==null?void 0:j.state_key),j&&e(j.state_key),setTimeout(()=>{r||_()},2e3)},[r,f,e,_]),F=g.useCallback(()=>{m(),n("streaming_response"),console.log("[StateTransitions] Stream started (API response)")},[m]),N=g.useCallback(()=>{n("response_complete"),console.log("[StateTransitions] Stream complete (API finished)");const j=f();j&&e(j.state_key),setTimeout(()=>{_()},2e3)},[f,e,_]),U=g.useCallback(()=>{if(r)return;n("showing_product"),console.log("[StateTransitions] Showing products");const j=t.find(R=>R.chat_trigger==="showing_product"||R.state_key==="showing_product");j&&e(j.state_key),setTimeout(()=>{_()},3e3)},[r,t,e,_]);return g.useEffect(()=>()=>m(),[m]),{chatStage:s,initialize:k,onUserInput:w,onSpeechStart:E,onSpeechEnd:A,onStreamStart:F,onStreamComplete:N,onShowingProduct:U,getStateSettings:v}},td=()=>{const t=pr();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(v=>v.state_key))||[],u=["idle","talking","listening"].filter(v=>{const m=[v,v.replace("ing",""),v+"ing"];return!l.some(b=>m.includes(b))}),{data:d,error:h}=await t.from("bob_animations").select("id").eq("is_active",!0).eq("look_id",n.id),f=h?0:(d==null?void 0:d.length)||0,p=l.length>=4&&f>0&&u.length===0;return{healthy:p,reason:p?void 0:`Missing critical states: ${u.join(", ")}`,activeLookId:n.id,activeLookName:n.name,stateCount:l.length,states:l,missingCritical:u,frameCount:f}}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${St}`);exports.BADGE_CONFIG=Ca;exports.BOB_VERSION=St;exports.Bob=zn;exports.BobCharacter=Ra;exports.BobDebugOverlay=za;exports.BobProvider=Dn;exports.BobStandalone=Vu;exports.BobSuggestions=Mn;exports.BobWidget=Mu;exports.CARFIX_COLORS=H;exports.ChatInterface=Ia;exports.ContainedChatDrawer=Ma;exports.ContainedMobileBobLayout=qa;exports.IMAGE_URLS=fs;exports.MatrixProductLoader=Yu;exports.MobileBobCharacter=Hs;exports.MobileBobLayout=Ua;exports.MobileBobLayoutCore=Xu;exports.MobileChatDrawer=Da;exports.MobileProductColumn=Ks;exports.ProductBadge=es;exports.ProductTile=Ba;exports.QUALITY_TIER_CONFIG=$s;exports.ServicePackageDetailView=Wa;exports.SparkDealBanner=Ja;exports.SwipeableBob=Gu;exports.TYPOGRAPHY=lt;exports.formatNZD=Ge;exports.getBobVersion=Xa;exports.getDisplayPrice=Oa;exports.getFeatureFlag=Ka;exports.isRotorProduct=Aa;exports.useBobAnalytics=xa;exports.useBobAnalyticsConfig=yu;exports.useBobAnimation=ja;exports.useBobAnimationData=Ea;exports.useBobBackdrop=Ta;exports.useBobCallbacks=mu;exports.useBobChat=Sa;exports.useBobContext=jt;exports.useBobHealthCheck=td;exports.useBobLayoutConfig=Un;exports.useBobStateTransitions=ed;exports.useBobSupabase=pu;exports.useBobSupabaseSafe=pr;exports.useHostApiConfig=bu;exports.useHostContext=gu;exports.usePartnerConfig=Ha;exports.useReturningUser=ka;exports.useSparkDeals=Ga;exports.useSpeechRecognition=qn;exports.useSpeechSynthesis=_a;exports.useThemeSettings=Va;
|
|
101
|
+
`})]})},Ft={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 Zr(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=f=>Math.round((f+l)*255).toString(16).padStart(2,"0");return`#${h(c)}${h(u)}${h(d)}`}function Qa(){const t=vr();return ks({queryKey:["bob-theme-settings"],queryFn:async()=>{var d,h,f,p,y,b,m,v,x,S,_;if(!t)return console.log("[useThemeSettings] No supabase client, using defaults"),Ft;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),Ft;if(!e||e.length===0)return Ft;const s=new Map(e.map(C=>[C.setting_key,C])),n=((d=s.get("matrix_primary"))==null?void 0:d.color_value)||Ft.primary,i=((h=s.get("matrix_secondary"))==null?void 0:h.color_value)||Ft.secondary,a=((f=s.get("matrix_success"))==null?void 0:f.color_value)||Ft.success,l=((p=s.get("matrix_background"))==null?void 0:p.color_value)||Ft.background,c=((y=s.get("matrix_spark_deal_color"))==null?void 0:y.color_value)||Ft.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:((m=s.get("matrix_primary"))==null?void 0:m.hex_preview)||Zr(n),secondaryHex:((v=s.get("matrix_secondary"))==null?void 0:v.hex_preview)||Zr(i),successHex:((x=s.get("matrix_success"))==null?void 0:x.hex_preview)||Zr(a),backgroundHex:((S=s.get("matrix_background"))==null?void 0:S.hex_preview)||Zr(l),sparkDealHex:((_=s.get("matrix_spark_deal_color"))==null?void 0:_.hex_preview)||Zr(c)}},staleTime:60*1e3,gcTime:5*60*1e3})}const ln={enabled:!0,inRain:!0,rainFrequency:.15,primingEnabled:!0,bannerEnabled:!0,delayMs:2e3,scrollSpeed:5e3,maxPerSession:3,minResearchTime:1500,bobCommentary:!1};function Xu(){const t=vr();return ks({queryKey:["spark-deals-settings"],queryFn:async()=>{if(!t)return ln;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),ln;if(!e||e.length===0)return ln;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 Ya(t=!0){const e=vr();return ks({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 Zu(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 Xa=({deals:t,currentDealIndex:e,onDealChange:r,onDealClick:s,scrollSpeed:n,theme:i})=>{const[a,l]=g.useState(!1),[c,u]=g.useState(100),d=t[e],h=i.sparkDealHex||"#FF9500",f=i.backgroundMode!=="light";g.useEffect(()=>{if(!d)return;l(!0),u(100);const b=setTimeout(()=>{u(0)},50),m=setTimeout(()=>{u(-100)},n-500),v=setTimeout(()=>{const x=(e+1)%t.length;r(x),l(!1)},n);return()=>{clearTimeout(b),clearTimeout(m),clearTimeout(v)}},[e,d,n,t.length,r]);const p=g.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 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:p,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:f?"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"}),y&&y>0&&o.jsxs("span",{className:"text-xs font-bold px-2 py-0.5 rounded-full",style:{background:h,color:f?"#000":"#fff"},children:[y,"% OFF"]})]}),o.jsxs("p",{className:"text-sm font-semibold truncate max-w-[200px]",style:{color:f?"#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:f?"#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,m)=>o.jsx("div",{className:"w-1.5 h-1.5 rounded-full transition-all",style:{background:m===e?h:`${h}40`,transform:m===e?"scale(1.3)":"scale(1)"}},m))})]})},$i=["*",":","=",">","<","+","-","|","•","○","●","◆","◇","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","#","@","$","%","&","~","^","/","\\","[","]","{","}"],Di=["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"],ed=({phase:t,message:e,onComplete:r,onSparkDealClick:s,subliminalBrands:n=[]})=>{const i=g.useRef(null),a=g.useRef(),l=g.useRef([]),c=g.useRef(0),[u,d]=g.useState(0),[h,f]=g.useState(!1),[p,y]=g.useState(0),{data:b}=Qa(),{data:m}=Xu(),{data:v}=Ya(t!=="hidden"&&(m==null?void 0:m.enabled)),x=b||{primaryHex:"#0066CC",secondaryHex:"#004999",successHex:"#FF9500",backgroundHex:"#111827",sparkDealHex:"#FF9500",backgroundMode:"dark"},S=m||{enabled:!0,inRain:!0,rainFrequency:.15,primingEnabled:!0,bannerEnabled:!0,delayMs:2e3,scrollSpeed:5e3,maxPerSession:3,minResearchTime:1500},_=v&&S.inRain?[...Zu(v),...n]:n,C=.08,I=g.useCallback(()=>_.length>0&&Math.random()<C?{char:_[Math.floor(Math.random()*_.length)],isSubliminal:!0}:Math.random()<.15?{char:Di[Math.floor(Math.random()*Di.length)],isSubliminal:!1}:{char:$i[Math.floor(Math.random()*$i.length)],isSubliminal:!1},[_]),O=g.useCallback((R,A)=>R.isSubliminal?x.sparkDealHex:t==="success"?x.successHex:Math.sin(A*2+R.x*.01)*.5+.5>.5?x.primaryHex:x.secondaryHex,[t,x]),E=g.useCallback((R,A)=>{const T=[],F=Math.floor(R/25);for(let M=0;M<F;M++){const{char:K,isSubliminal:ee}=I();T.push({x:M*25+12,y:Math.random()*A,speed:1.5+Math.random()*3.5,char:K,isSubliminal:ee,opacity:.2+Math.random()*.6,size:ee?13:9+Math.random()*3,glowIntensity:ee?.6:0,changeCounter:Math.floor(Math.random()*30)})}l.current=T},[I]);g.useEffect(()=>{if(t==="hidden"){a.current&&cancelAnimationFrame(a.current);return}const R=i.current;if(!R)return;const A=R.getContext("2d");if(!A)return;const T=()=>{R.width=R.offsetWidth*window.devicePixelRatio,R.height=R.offsetHeight*window.devicePixelRatio,A.scale(window.devicePixelRatio,window.devicePixelRatio),E(R.offsetWidth,R.offsetHeight)};T(),c.current=Date.now();const F=()=>{const M=R.offsetWidth,K=R.offsetHeight,Z=(Date.now()-c.current)/1e3;if(A.clearRect(0,0,M,K),l.current.forEach(z=>{const V=O(z,Z);if(A.font=`bold ${z.size}px monospace`,A.fillStyle=V,A.globalAlpha=z.opacity,z.isSubliminal&&z.glowIntensity>0?(A.shadowColor=x.sparkDealHex,A.shadowBlur=8*z.glowIntensity):A.shadowBlur=0,A.fillText(z.char,z.x,z.y),z.y+=z.speed,z.changeCounter++,z.changeCounter>20+Math.random()*40){const{char:le,isSubliminal:G}=I();z.char=le,z.isSubliminal=G,z.size=G?13:9+Math.random()*3,z.glowIntensity=G?.6:0,z.changeCounter=0}if(z.y>K+20){const{char:le,isSubliminal:G}=I();z.y=-20,z.char=le,z.isSubliminal=G,z.speed=1.5+Math.random()*3.5,z.opacity=.2+Math.random()*.6,z.size=G?13:9+Math.random()*3,z.glowIntensity=G?.6:0,z.changeCounter=0}}),A.globalAlpha=1,A.shadowBlur=0,t==="success"){const z=Math.max(0,1-Z*2);z>0&&(A.fillStyle=`rgba(255, 149, 0, ${z*.3})`,A.fillRect(0,0,M,K)),Z>.5&&r&&r()}a.current=requestAnimationFrame(F)};return F(),window.addEventListener("resize",T),()=>{a.current&&cancelAnimationFrame(a.current),window.removeEventListener("resize",T)}},[t,x,I,O,E,r]),g.useEffect(()=>{if(t==="hidden"||!v||v.length===0||!S.bannerEnabled){f(!1);return}if(p>=S.maxPerSession)return;const R=setTimeout(()=>{f(!0)},S.delayMs);return()=>clearTimeout(R)},[t,v,S,p]);const B=g.useCallback(R=>{d(R),y(A=>A+1)},[]),j=g.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&&v&&v.length>0&&o.jsx(Xa,{deals:v.slice(0,S.maxPerSession),currentDealIndex:u,onDealChange:B,onDealClick:j,scrollSpeed:S.scrollSpeed,theme:x})]})},td=({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:f,onChangeVehicle:p,bobOffset:y=0,bobScale:b=100,bobHasArrived:m=!0,externalBobPosition:v,onBobPositionChange:x,pendingVariants:S,pendingVariantMake:_,pendingVariantModel:C,onVariantSelect:I})=>{const O=Ks(),E=Hn(),[B,j]=g.useState("center"),[R,A]=g.useState("hidden"),T=v??B,F=g.useCallback(L=>{j(L),x==null||x(L)},[x]),M=i.length>0||a.length>0,K=((S==null?void 0:S.length)??0)>0,ee=M||K,V=(()=>{switch(O){case"desktop":return 80*E.uiScale;case"tablet":return 90*E.uiScale;case"mobile":return 140;default:return 140}})()*b/100;g.useEffect(()=>{if(h&&R!=="loading"&&R!=="visible"){if(K){T==="center"&&F("partial-left");return}A("loading"),T==="center"&&F("partial-left")}else if(ee&&R!=="visible")if(T==="center"){F("partial-left"),A("transitioning");const L=setTimeout(()=>{A("visible")},400);return()=>clearTimeout(L)}else A("visible");else!ee&&!h&&R!=="hidden"&&(K||(A("hidden"),F("center")))},[ee,K,h,R,T,F]);const le=R!=="hidden"||K,G=le&ⅇ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:G?"blur(var(--bob-blur-intensity, 0px))":"none",transform:G?"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:G?1:0}})]}),o.jsx(Vs,{currentImage:t,animationState:e,counterOverlayUrl:s,counterHeightPercent:n,scale:V,position:T,verticalOffset:y,hasArrived:m}),o.jsx(Gs,{products:i,servicePackages:a,highlightedPartType:l,highlightedProduct:c,onProductClick:u,onPackageSelect:d,isResearching:h,visible:le,counterHeightPercent:n,hasVehicle:!!f,pendingVariants:S,pendingVariantMake:_,pendingVariantModel:C,onVariantSelect:I})]})},rd=6e4,sd=({states:t,setAnimationState:e,manualMode:r})=>{const[s,n]=g.useState("page_load"),[i,a]=g.useState(!1),l=g.useRef(null),c=g.useCallback(j=>{const R=t.find(A=>A.chat_trigger===j&&A.is_active);return console.log(`[StateTransitions] Looking for trigger: "${j}" -> found:`,(R==null?void 0:R.state_key)||"none"),R},[t]),u=g.useCallback(()=>t.find(j=>j.chat_trigger==="processing_input"||j.state_key==="research"||j.state_key==="researching"||j.title.toLowerCase().includes("research")||j.title.toLowerCase().includes("thinking")),[t]),d=g.useCallback(()=>t.find(j=>j.chat_trigger==="streaming_response"||j.state_key==="talk"||j.state_key==="talking"||j.title.toLowerCase().includes("talk")),[t]),h=g.useCallback(()=>t.find(j=>j.chat_trigger==="awaiting_input"||j.state_key==="talk_pause"||j.state_key==="listening"||j.title.toLowerCase().includes("listen")||j.title.toLowerCase().includes("pause")),[t]),f=g.useCallback(()=>{const j=t.find(R=>R.chat_trigger==="response_complete"||R.state_key==="complete"||R.title.toLowerCase().includes("complete"));return j||t.find(R=>R.state_key==="idle"||R.title.toLowerCase().includes("idle"))},[t]),p=g.useCallback(()=>t.find(j=>j.chat_trigger==="idle"||j.state_key==="idle"||j.title.toLowerCase().includes("idle")),[t]),y=g.useCallback(j=>{const R=t.find(A=>A.state_key===j);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=g.useCallback(()=>{l.current&&(clearTimeout(l.current),l.current=null)},[]),m=g.useCallback(()=>{b(),!r&&(l.current=setTimeout(()=>{const j=p();j&&(n("idle"),e(j.state_key))},rd))},[r,p,e,b]),v=g.useCallback(j=>{if(r)return;const R=c(j);R&&e(R.state_key)},[r,c,e]),x=g.useCallback(()=>{if(r)return;const j=h();j&&(n("awaiting_input"),e(j.state_key),m())},[r,h,e,m]),S=g.useCallback(()=>{i||r||(a(!0),n("page_load"),v("page_load"),setTimeout(()=>{x()},3e3))},[i,r,v,x]),_=g.useCallback(()=>{if(r)return;b(),n("processing_input");const j=u();console.log("[StateTransitions] User input - switching to RESEARCH:",j==null?void 0:j.state_key),j?e(j.state_key):v("processing_input")},[r,b,u,e,v]),C=g.useCallback(()=>{if(r)return;b(),n("streaming_response");const j=d();console.log("[StateTransitions] Speech started - switching to TALK:",j==null?void 0:j.state_key),j&&e(j.state_key)},[r,b,d,e]),I=g.useCallback(()=>{if(r)return;const j=f();console.log("[StateTransitions] Speech ended - switching to COMPLETE:",j==null?void 0:j.state_key),j&&e(j.state_key),setTimeout(()=>{r||x()},2e3)},[r,f,e,x]),O=g.useCallback(()=>{b(),n("streaming_response"),console.log("[StateTransitions] Stream started (API response)")},[b]),E=g.useCallback(()=>{n("response_complete"),console.log("[StateTransitions] Stream complete (API finished)");const j=f();j&&e(j.state_key),setTimeout(()=>{x()},2e3)},[f,e,x]),B=g.useCallback(()=>{if(r)return;n("showing_product"),console.log("[StateTransitions] Showing products");const j=t.find(R=>R.chat_trigger==="showing_product"||R.state_key==="showing_product");j&&e(j.state_key),setTimeout(()=>{x()},3e3)},[r,t,e,x]);return g.useEffect(()=>()=>b(),[b]),{chatStage:s,initialize:S,onUserInput:_,onSpeechStart:C,onSpeechEnd:I,onStreamStart:O,onStreamComplete:E,onShowingProduct:B,getStateSettings:y}},nd=()=>{const t=vr();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(y=>y.state_key))||[],u=["idle","talking","listening"].filter(y=>{const b=[y,y.replace("ing",""),y+"ing"];return!l.some(m=>b.includes(m))}),{data:d,error:h}=await t.from("bob_animations").select("id").eq("is_active",!0).eq("look_id",n.id),f=h?0:(d==null?void 0:d.length)||0,p=l.length>=4&&f>0&&u.length===0;return{healthy:p,reason:p?void 0:`Missing critical states: ${u.join(", ")}`,activeLookId:n.id,activeLookName:n.name,stateCount:l.length,states:l,missingCritical:u,frameCount:f}}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${At}`);exports.BADGE_CONFIG=Oa;exports.BOB_VERSION=At;exports.Bob=Vn;exports.BobCharacter=Aa;exports.BobDebugOverlay=Va;exports.BobProvider=Wn;exports.BobStandalone=Qu;exports.BobSuggestions=zn;exports.BobWidget=zu;exports.CARFIX_COLORS=J;exports.ChatInterface=Ba;exports.ContainedChatDrawer=qa;exports.ContainedMobileBobLayout=Ha;exports.IMAGE_URLS=gs;exports.MatrixProductLoader=ed;exports.MobileBobCharacter=Vs;exports.MobileBobLayout=Wa;exports.MobileBobLayoutCore=td;exports.MobileChatDrawer=Ma;exports.MobileProductColumn=Gs;exports.ProductBadge=rs;exports.ProductTile=La;exports.QUALITY_TIER_CONFIG=Us;exports.ServicePackageDetailView=za;exports.SparkDealBanner=Xa;exports.SwipeableBob=Yu;exports.TYPOGRAPHY=ct;exports.formatNZD=Qe;exports.getBobVersion=eo;exports.getDisplayPrice=Ia;exports.getFeatureFlag=Ja;exports.isRotorProduct=Pa;exports.useBobAnalytics=ka;exports.useBobAnalyticsConfig=xu;exports.useBobAnimation=Ra;exports.useBobAnimationData=Ta;exports.useBobBackdrop=Ca;exports.useBobCallbacks=wu;exports.useBobChat=ja;exports.useBobContext=Pt;exports.useBobHealthCheck=nd;exports.useBobLayoutConfig=qn;exports.useBobStateTransitions=sd;exports.useBobSupabase=mu;exports.useBobSupabaseSafe=vr;exports.useHostApiConfig=vu;exports.useHostContext=yu;exports.useMicPermission=Ka;exports.usePartnerConfig=Ga;exports.useReturningUser=Ea;exports.useSparkDeals=Ya;exports.useSpeechRecognition=Kn;exports.useSpeechSynthesis=Sa;exports.useThemeSettings=Qa;
|